source: tags/ms_r16q3/AWTC/AWTC_next_neighbours.cxx

Last change on this file was 14622, checked in by westram, 8 years ago
  • reintegrates 'ui' into 'trunk'
    • implements #656
    • adds instant update for
      • next neighbour search
      • branch analysis (mark functions)
      • arb-phylo (filter setup)
  • adds: log:branches/ui@14588:14621
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 18.3 KB
Line 
1// ================================================================ //
2//                                                                  //
3//   File      : AWTC_next_neighbours.cxx                           //
4//   Purpose   :                                                    //
5//                                                                  //
6//   Institute of Microbiology (Technical University Munich)        //
7//   http://www.arb-home.de/                                        //
8//                                                                  //
9// ================================================================ //
10
11#include "awtc_next_neighbours.hxx"
12
13#include <servercntrl.h>
14#include <PT_com.h>
15#include <client.h>
16#include <aw_window.hxx>
17#include <aw_root.hxx>
18#include <aw_awar.hxx>
19#include <arbdbt.h>
20#include <arb_strbuf.h>
21
22#include <climits>
23
24struct PT_FF_comImpl {
25    aisc_com  *link;
26    T_PT_MAIN  com;
27    T_PT_LOCS  locs;
28
29    PT_FF_comImpl()
30        : link(NULL)
31    {
32        ff_assert(!com.exists());
33        ff_assert(!locs.exists());
34    }
35};
36
37// -------------------
38//      FamilyList
39
40FamilyList::FamilyList()
41    : next(NULL),
42      name(NULL),
43      matches(0),
44      rel_matches(0.0)
45{}
46
47FamilyList::~FamilyList() {
48    free(name);
49    delete next;
50}
51
52FamilyList *FamilyList::insertSortedBy_matches(FamilyList *other) {
53    ff_assert(next == NULL); // only insert unlinked instace!
54
55    if (!other) {
56        return this;
57    }
58
59    if (matches >= other->matches) {
60        next = other;
61        return this;
62    }
63
64    // insert into other
65    FamilyList *rest = other->next;
66    other->next      = rest ? insertSortedBy_matches(rest) : this;
67
68    return other;
69}
70
71FamilyList *FamilyList::insertSortedBy_rel_matches(FamilyList *other) {
72    ff_assert(next == NULL); // only insert unlinked instace!
73
74    if (rel_matches >= other->rel_matches) {
75        next = other;
76        return this;
77    }
78
79    // insert into other
80    FamilyList *rest = other->next;
81    other->next      = rest ? insertSortedBy_rel_matches(rest) : this;
82
83    return other;
84
85}
86
87// ---------------------
88//      FamilyFinder
89
90FamilyFinder::FamilyFinder(bool rel_matches_, RelativeScoreScaling scaling_)
91    : rel_matches(rel_matches_),
92      scaling(scaling_), 
93      family_list(NULL),
94      hits_truncated(false),
95      real_hits(-1),
96      range(-1, -1)
97{
98}
99
100FamilyFinder::~FamilyFinder() {
101    delete_family_list();
102}
103
104void FamilyFinder::delete_family_list() {
105    delete family_list;
106    family_list = NULL;
107}
108
109// ------------------------
110//      PT_FamilyFinder
111
112PT_FamilyFinder::PT_FamilyFinder(GBDATA *gb_main_, int server_id_, int oligo_len_, int mismatches_, bool fast_flag_, bool rel_matches_, RelativeScoreScaling scaling_)
113    : FamilyFinder(rel_matches_, scaling_), 
114      gb_main(gb_main_),
115      server_id(server_id_),
116      oligo_len(oligo_len_),
117      mismatches(mismatches_),
118      fast_flag(fast_flag_)
119{
120    // 'mismatches'  = the number of allowed mismatches
121    // 'fast_flag'   = 0 -> do complete search, 1 -> search only oligos starting with 'A'
122    // 'rel_matches' = 0 -> score is number of oligo-hits, 1 -> score is relative to longer sequence (target or source) * 10
123
124    ci = new PT_FF_comImpl;
125}
126
127PT_FamilyFinder::~PT_FamilyFinder() {
128    delete_family_list();
129    close();
130    delete ci;
131}
132
133GB_ERROR PT_FamilyFinder::init_communication() {
134    const char *user = "PT_FamilyFinder";
135
136    ff_assert(!ci->locs.exists());
137   
138    // connect PT server
139    if (aisc_create(ci->link, PT_MAIN, ci->com,
140                    MAIN_LOCS, PT_LOCS, ci->locs,
141                    LOCS_USER, user,
142                    NULL)) {
143        return GB_export_error("Cannot initialize communication");
144    }
145    return 0;
146}
147
148
149GB_ERROR PT_FamilyFinder::open(const char *servername) {
150    GB_ERROR error = 0;
151   
152    ff_assert(!ci->com.exists() && !ci->link);
153
154    if (arb_look_and_start_server(AISC_MAGIC_NUMBER, servername)) {
155        error = "Cannot contact PT  server";
156    }
157    else {
158        const char *socketid = GBS_read_arb_tcp(servername);
159        if (!socketid) error = GB_await_error();
160        else {
161            ci->link = aisc_open(socketid, ci->com, AISC_MAGIC_NUMBER, &error);
162            if (!error) {
163                if (!ci->link) error                 = "Cannot contact PT server [1]";
164                else if (init_communication()) error = "Cannot contact PT server [2]";
165            }
166        }
167    }
168
169    ff_assert(error || (ci->com.exists() && ci->link));
170   
171    return error;
172}
173
174void PT_FamilyFinder::close() {
175    if (ci->link) aisc_close(ci->link, ci->com);
176    ci->link = 0;
177    ff_assert(!ci->com.exists());
178    ci->locs.clear();
179}
180
181GB_ERROR PT_FamilyFinder::retrieve_family(const char *sequence, FF_complement compl_mode, int max_results, double min_score) {
182    delete_family_list();
183
184    char     *compressed_sequence = GB_command_interpreter(gb_main, sequence, "|keep(acgtunACGTUN)", 0, 0);
185    GB_ERROR  error               = NULL;
186
187    if      (!compressed_sequence)    error = GB_await_error();
188    else if (!compressed_sequence[0]) error = "No data in sequence(-region)";
189    else {
190        bytestring bs;
191        bs.data = compressed_sequence;
192        bs.size = strlen(bs.data)+1;
193
194        /* Start find_family() at the PT_SERVER
195         *
196         * Here we have to make a loop, until the match count of the
197         * first member is big enough
198         */
199
200        ff_assert(!range.is_empty());
201
202        // create and init family finder object
203        T_PT_FAMILYFINDER ffinder;
204        if (aisc_create(ci->link, PT_LOCS, ci->locs,
205                        LOCS_FFINDER, PT_FAMILYFINDER, ffinder,
206                        FAMILYFINDER_PROBE_LEN,       long(oligo_len),          // oligo length (12 hardcoded till July 2008)
207                        FAMILYFINDER_MISMATCH_NUMBER, long(mismatches),         // number of mismatches (0 hardcoded till July 2008)
208                        FAMILYFINDER_FIND_TYPE,       long(fast_flag),          // 0: complete search, 1: quick search (only search oligos starting with 'A')
209                        FAMILYFINDER_SORT_TYPE,       long(uses_rel_matches()), // 0: matches, 1: relative matches (0 hardcoded till July 2008)
210                        FAMILYFINDER_REL_SCORING,     long(get_scaling()),      // scaling of relative scores
211                        FAMILYFINDER_SORT_MAX,        long(max_results),        // speed up family sorting (only sort retrieved results)
212                        FAMILYFINDER_MIN_SCORE,       double(min_score),        // limit hits by score
213                        FAMILYFINDER_COMPLEMENT,      long(compl_mode),         // any combination of: 1 = forward, 2 = reverse, 4 = reverse-complement, 8 = complement (1 hardcoded in PT-Server till July 2008)
214                        FAMILYFINDER_RANGE_STARTPOS,  long(range.start()),
215                        FAMILYFINDER_RANGE_ENDPOS,    long(range.is_limited() ? range.end() : -1),
216                        FAMILYFINDER_FIND_FAMILY,     &bs,                      // RPC (has to be last parameter!)
217                        NULL))
218        {
219            error = "Communication error with PT server ('retrieve_family')";
220        }
221        else {
222            char *ff_error = 0;
223
224            // Read family list
225            T_PT_FAMILYLIST f_list;
226            aisc_get(ci->link, PT_FAMILYFINDER, ffinder,
227                     FAMILYFINDER_FAMILY_LIST,      f_list.as_result_param(),
228                     FAMILYFINDER_FAMILY_LIST_SIZE, &real_hits,
229                     FAMILYFINDER_ERROR,            &ff_error,
230                     NULL);
231
232            if (ff_error[0]) {
233                error = GBS_global_string("PTSERVER: %s", ff_error);
234            }
235            else {
236                hits_truncated = false;
237                if (max_results<1) max_results = INT_MAX;
238
239                FamilyList *tail = NULL;
240                while (f_list.exists()) {
241                    if (max_results == 0) {
242                        hits_truncated = true;
243                        break;
244                    }
245                    max_results--;
246
247                    FamilyList *fl = new FamilyList;
248
249                    (tail ? tail->next : family_list) = fl;
250                    tail                              = fl;
251                    fl->next                          = NULL;
252
253                    aisc_get(ci->link, PT_FAMILYLIST, f_list,
254                             FAMILYLIST_NAME,        &fl->name,
255                             FAMILYLIST_MATCHES,     &fl->matches,
256                             FAMILYLIST_REL_MATCHES, &fl->rel_matches,
257                             FAMILYLIST_NEXT,        f_list.as_result_param(),
258                             NULL);
259                }
260            }
261            free(ff_error);
262        }
263
264        free(compressed_sequence);
265    }
266    return error;
267}
268
269GB_ERROR PT_FamilyFinder::searchFamily(const char *sequence, FF_complement compl_mode, int max_results, double min_score) {
270    // searches the PT-server for species related to 'sequence'.
271    //
272    // relation-score is calculated by fragmenting the sequence into oligos of length 'oligo_len' and
273    // then summarizing the number of hits.
274    //
275    // 'max_results' limits the length of the generated result list (low scores deleted first)
276    //               if < 1 -> don't limit
277    //
278    // 'min_score' limits the results by score (use 0 for unlimited results)
279    //
280    // When using restrict_2_region(), only pass the corresponding part via 'sequence' (not the full alignment)
281
282    GB_ERROR error = range.is_empty() ? "Specified range is empty" : NULL;
283    if (!error) {
284        error             = open(GBS_ptserver_tag(server_id));
285        if (!error) error = retrieve_family(sequence, compl_mode, max_results, min_score);
286        close();
287    }
288    return error;
289}
290
291const char *PT_FamilyFinder::results2string() {
292    GBS_strstruct *out = GBS_stropen(1000);
293    for (FamilyList *fl = family_list; fl; fl = fl->next) {
294        GBS_strnprintf(out, 100, "%s/%li/%3.5f,", fl->name, fl->matches, fl->rel_matches*100);
295    }
296    GBS_str_cut_tail(out, 1);
297    RETURN_LOCAL_ALLOC(GBS_strclose(out));
298}
299
300static void adjustOligolenAndMismatches(AW_root *aw_root, bool oligolen_changed) {
301    AW_awar *awar_oligolen   = aw_root->awar(AWAR_NN_OLIGO_LEN);
302    AW_awar *awar_mismatches = aw_root->awar(AWAR_NN_MISMATCHES);
303
304    int oligolen   = awar_oligolen->read_int();
305    int mismatches = awar_mismatches->read_int();
306
307    if (oligolen<=mismatches) { // =unwanted state
308        if (oligolen_changed) {
309            awar_mismatches->write_int(oligolen-1);
310        }
311        else {
312            awar_oligolen->write_int(mismatches+1);
313        }
314    }
315}
316
317void AWTC_create_common_next_neighbour_vars(AW_root *aw_root, const RootCallback& awar_changed_cb) {
318    static bool created = false;
319    if (!created) {
320        aw_root->awar_int(AWAR_NN_OLIGO_LEN,  12)->set_minmax(1, 200)->add_callback(makeRootCallback(adjustOligolenAndMismatches, true))->add_callback(awar_changed_cb);
321        aw_root->awar_int(AWAR_NN_MISMATCHES,  0)->set_minmax(0,  50)->add_callback(makeRootCallback(adjustOligolenAndMismatches, false))->add_callback(awar_changed_cb);
322        aw_root->awar_int(AWAR_NN_FAST_MODE,   0)->add_callback(awar_changed_cb);
323        aw_root->awar_int(AWAR_NN_REL_MATCHES, 1)->add_callback(awar_changed_cb);
324        aw_root->awar_int(AWAR_NN_REL_SCALING, RSS_BOTH_MIN)->add_callback(awar_changed_cb);
325
326        created = true;
327    }
328}
329
330void AWTC_create_common_next_neighbour_fields(AW_window *aws, int scaler_length) {
331    // used in several figs:
332    // - ad_spec_nn.fig
333    // - ad_spec_nnm.fig
334    // - faligner/family_settings.fig
335
336    aws->at("oligo_len");
337    aws->create_input_field_with_scaler(AWAR_NN_OLIGO_LEN, 3, scaler_length, AW_SCALER_EXP_LOWER);
338
339    aws->at("mismatches");
340    aws->create_input_field_with_scaler(AWAR_NN_MISMATCHES, 3, scaler_length, AW_SCALER_EXP_LOWER);
341
342    aws->at("mode");
343    aws->create_option_menu(AWAR_NN_FAST_MODE, true);
344    aws->insert_default_option("Complete", "", 0);
345    aws->insert_option("Quick", "", 1);
346    aws->update_option_menu();
347
348    aws->at("score");
349    aws->create_option_menu(AWAR_NN_REL_MATCHES, true);
350    aws->insert_option("absolute", "", 0);
351    aws->insert_default_option("relative", "", 1);
352    aws->update_option_menu();
353
354    aws->at("scaling");
355    aws->create_option_menu(AWAR_NN_REL_SCALING, true);
356    aws->insert_option        ("to source POC",  "", RSS_SOURCE);
357    aws->insert_option        ("to target POC",  "", RSS_TARGET);
358    aws->insert_default_option("to maximum POC", "", RSS_BOTH_MAX);
359    aws->insert_option        ("to minimum POC", "", RSS_BOTH_MIN);
360    aws->update_option_menu();
361}
362
363// --------------------------------------------------------------------------------
364
365#ifdef UNIT_TESTS
366
367#include <test_unit.h>
368
369class ff_tester {
370    GBDATA *gb_main;
371public:
372    bool    relativeMatches;
373    bool    fastMode;
374    bool    partial;
375    bool    shortOligo;
376    double  min_score;
377
378    RelativeScoreScaling scaling;
379
380    ff_tester(GBDATA *gb_main_)
381        : gb_main(gb_main_),
382          relativeMatches(false),
383          fastMode(false),
384          partial(false),
385          shortOligo(false),
386          min_score(0.0),
387          scaling(RSS_BOTH_MAX)
388    {}
389
390    const char *get_result(GB_ERROR& error) {
391        int             oligoLen = shortOligo ? (partial ? 3 : 6) : (partial ? 10 : 18);
392        PT_FamilyFinder ff(gb_main, TEST_SERVER_ID, oligoLen, 1, fastMode, relativeMatches, scaling);
393       
394        const char *sequence;
395        if (partial) {
396            ff.restrict_2_region(PosRange(39, 91)); // alignment range of bases 30-69 of sequence of 'LgtLytic'
397            sequence = "UCUAGCUUGCUAGACGGGUGGCGAG" "GGUAACCGUAGGGGA"; // bases 30-54 of sequence of 'LgtLytic' + 15 bases from 'DcdNodos' (outside region)
398        }
399        else {
400            // sequence of 'LgtLytic' in TEST_pt.arb:
401            sequence = "AGAGUUUGAUCAAGUCGAACGGCAGCACAGUCUAGCUUGCUAGACGGGUGGCGAGUGGCGAACGGACUUGGGGAAACUCAAGCUAAUACCGCAUAAUCAUGACUGGGGUGAAGUCGUAACAAGGUAGCCGUAGGGGAACCUGCGGCUGGAUCACCUCCUN";
402        }
403
404        error = ff.searchFamily(sequence, FF_FORWARD, 4, min_score);
405        return ff.results2string();
406    }
407};
408
409
410#define TEST_RELATIVES_COMMON(tester,expctd) \
411        GB_ERROR    error;                                      \
412        const char *result   = tester.get_result(error);        \
413        const char *expected = expctd;                          \
414        TEST_EXPECT_NO_ERROR(error);                            \
415   
416#define TEST_EXPECT_RELATIVES(tester,expctd) do {               \
417        TEST_RELATIVES_COMMON(tester,expctd);                   \
418        TEST_EXPECT_EQUAL(result, expected);                    \
419    } while(0)
420
421#define TEST_EXPECT_REL__BROK(tester,expctd) do {               \
422        TEST_RELATIVES_COMMON(tester,expctd);                   \
423        TEST_EXPECT_EQUAL__BROKEN(result, expected);            \
424    } while(0)
425   
426void TEST_SLOW_PT_FamilyFinder() {
427    GB_shell shell;
428    TEST_SETUP_GLOBAL_ENVIRONMENT("ptserver");
429
430    GBDATA *gb_main = GB_open("no.arb", "c");
431
432    // check some error cases
433    {
434        PT_FamilyFinder ffe(gb_main, TEST_SERVER_ID, 0, 1, 0, 0, RSS_BOTH_MAX);
435        TEST_EXPECT_CONTAINS(ffe.searchFamily("whatever", FF_FORWARD, 4, 0.0), "minimum oligo length is 1");
436    }
437   
438    ff_tester test(gb_main);
439
440    ff_tester ______RESET = test; TEST_EXPECT_RELATIVES(test, "LgtLytic/142/97.93103,HllHalod/62/43.05556,AclPleur/59/38.06452,PtVVVulg/51/34.00000");
441    test.partial          = true; TEST_EXPECT_RELATIVES(test, "LgtLytic/18/11.76471,VblVulni/5/3.24675,VbhChole/4/2.59740,DcdNodos/4/2.59740");
442    test.shortOligo       = true; TEST_EXPECT_RELATIVES(test, "PtVVVulg/38/23.03030,AclPleur/38/22.35294,VbhChole/38/23.60248,VblVulni/38/23.60248");
443    test.relativeMatches  = true; TEST_EXPECT_RELATIVES(test, "DsssDesu/38/38.77551,CltBotul/38/34.23423,PsAAAA00/38/32.75862,Bl0LLL00/38/25.67568");
444    test.min_score        = 32.6; TEST_EXPECT_RELATIVES(test, "DsssDesu/38/38.77551,CltBotul/38/34.23423,PsAAAA00/38/32.75862");
445    test                  = ______RESET;
446    test.shortOligo       = true; TEST_EXPECT_RELATIVES(test, "LgtLytic/154/98.08917,VbhChole/133/84.17722,VblVulni/133/84.17722,HllHalod/133/85.25641");
447    test.relativeMatches  = true; TEST_EXPECT_RELATIVES(test, "LgtLytic/154/98.08917,HllHalod/133/85.25641,VbhChole/133/84.17722,VblVulni/133/84.17722");
448    test.fastMode         = true; TEST_EXPECT_RELATIVES(test, "LgtLytic/42/26.75159,VblVulni/37/23.41772,HllHalod/36/23.07692,Stsssola/36/23.07692");
449    test.min_score        = 26.7; TEST_EXPECT_RELATIVES(test, "LgtLytic/42/26.75159");
450    test.min_score        = 26.8; TEST_EXPECT_RELATIVES(test, "");
451    test                  = ______RESET;
452    test.fastMode         = true; TEST_EXPECT_RELATIVES(test, "LgtLytic/40/27.58621,HllHalod/18/12.50000,AclPleur/17/10.96774,PtVVVulg/15/10.00000");
453    test.min_score        = 17.0; TEST_EXPECT_RELATIVES(test, "LgtLytic/40/27.58621,HllHalod/18/12.50000,AclPleur/17/10.96774");
454    test.min_score        = 17.5; TEST_EXPECT_RELATIVES(test, "LgtLytic/40/27.58621,HllHalod/18/12.50000");
455    test                  = ______RESET;
456
457    test.shortOligo      = true;
458    test.relativeMatches = true;
459    test.scaling         = RSS_BOTH_MAX; TEST_EXPECT_RELATIVES(test, "LgtLytic/154/98.08917,HllHalod/133/85.25641,VbhChole/133/84.17722,VblVulni/133/84.17722");
460    test.scaling         = RSS_BOTH_MIN; TEST_EXPECT_RELATIVES(test, "LgtLytic/154/98.71795,DsssDesu/84/88.42105,CltBotul/95/87.96296,PsAAAA00/97/85.84071");
461    test.scaling         = RSS_TARGET;   TEST_EXPECT_RELATIVES(test, "LgtLytic/154/98.08917,DsssDesu/84/88.42105,CltBotul/95/87.96296,PsAAAA00/97/85.84071");
462    test.scaling         = RSS_SOURCE;   TEST_EXPECT_RELATIVES(test, "LgtLytic/154/98.71795,VbhChole/133/85.25641,VblVulni/133/85.25641,HllHalod/133/85.25641");
463    test.partial         = true;
464    test.shortOligo      = false;
465    test.scaling         = RSS_BOTH_MAX; TEST_EXPECT_RELATIVES(test, "LgtLytic/18/11.76471,VblVulni/5/3.24675,VbhChole/4/2.59740,DcdNodos/4/2.59740");
466    test.scaling         = RSS_BOTH_MIN; TEST_EXPECT_RELATIVES(test, "LgtLytic/18/56.25000,VblVulni/5/15.62500,VbhChole/4/12.50000,DcdNodos/4/12.50000");
467    test.scaling         = RSS_TARGET;   TEST_EXPECT_RELATIVES(test, "LgtLytic/18/11.76471,VblVulni/5/3.24675,VbhChole/4/2.59740,DcdNodos/4/2.59740");
468    test.scaling         = RSS_SOURCE;   TEST_EXPECT_RELATIVES(test, "LgtLytic/18/56.25000,VblVulni/5/15.62500,VbhChole/4/12.50000,DcdNodos/4/12.50000");
469    test                 = ______RESET;
470
471    GB_close(gb_main);
472}
473
474#endif // UNIT_TESTS
475
Note: See TracBrowser for help on using the repository browser.