source: tags/arb-6.0/AWTC/AWTC_next_neighbours.cxx

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