source: branches/ali/AWTC/AWTC_next_neighbours.cxx

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