source: tags/arb-6.0/PROBE_DESIGN/probe_design.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: 78.4 KB
Line 
1// =============================================================== //
2//                                                                 //
3//   File      : probe_design.cxx                                  //
4//   Purpose   :                                                   //
5//                                                                 //
6//   Institute of Microbiology (Technical University Munich)       //
7//   http://www.arb-home.de/                                       //
8//                                                                 //
9// =============================================================== //
10
11#include "SaiProbeVisualization.hxx"
12#include "probe_match_parser.hxx"
13
14#include <PT_com.h>
15#include <PT_server.h> // needed for DOMAIN_MIN_LENGTH
16#include <client.h>
17#include <servercntrl.h>
18#include <probe_design.hxx>
19
20#include <GEN.hxx>
21#include <TreeCallbacks.hxx>
22
23#include <iupac.h>
24#include <awt_config_manager.hxx>
25#include <awt_sel_boxes.hxx>
26
27#include <aw_awars.hxx>
28#include <aw_preset.hxx>
29#include <aw_select.hxx>
30#include <aw_msg.hxx>
31#include <arb_progress.h>
32#include <aw_root.hxx>
33#include <aw_question.hxx>
34#include <adGene.h>
35#include <arb_strbuf.h>
36#include <arb_strarray.h>
37#include <arb_file.h>
38#include <aw_edit.hxx>
39
40// general awars
41
42#define AWAR_PROBE_CREATE_GENE_SERVER "tmp/probe_admin/gene_server" // whether to create a gene pt server
43
44// probe match awars
45
46// #define AWAR_PD_MATCH_ITEM     AWAR_SPECIES_NAME
47#define AWAR_PD_SELECTED_MATCH "tmp/probe_design/match"
48#define AWAR_PD_MATCH_RESOLVE  "tmp/probe_design/match_resolve" // for IUPAC resolution
49
50#define AWAR_PD_MATCH_SORTBY     "probe_match/sort_by" // weighted mismatches
51#define AWAR_PD_MATCH_COMPLEMENT "probe_match/complement" // check reverse complement too
52#define AWAR_PD_MATCH_MARKHITS   "probe_match/mark_hits" // mark hitten species in database
53#define AWAR_PD_MATCH_WRITE2TMP  "probe_match/write_2_tmp" // write result to field tmp
54#define AWAR_PD_MATCH_AUTOMATCH  "probe_match/auto_match" // auto match probes when target string changes
55
56#define AWAR_PD_MATCH_NHITS    "tmp/probe_match/nhits" // display the 'number of hits'
57
58// probe design awars
59
60#define AWAR_PD_DESIGN_CLIPRESULT "probe_design/CLIPRESULT" // 'length of output' (how many probes will get designed)
61#define AWAR_PD_DESIGN_MISHIT     "probe_design/MISHIT"     // 'non group hits'
62#define AWAR_PD_DESIGN_MAXBOND    "probe_design/MAXBOND"    // max hairpinbonds ?
63#define AWAR_PD_DESIGN_MINTARGETS "probe_design/MINTARGETS" // 'min. group hits (%)'
64
65#define AWAR_PD_DESIGN_MIN_LENGTH "probe_design/PROBELENGTH"      // min. length of probe
66#define AWAR_PD_DESIGN_MAX_LENGTH "probe_design/PROBEMAXLENGTH"   // max. length of probe (or empty)
67
68#define AWAR_PD_DESIGN_MIN_TEMP     "probe_design/MINTEMP"     // temperature (min)
69#define AWAR_PD_DESIGN_MAX_TEMP     "probe_design/MAXTEMP"     // temperature (max)
70#define AWAR_PD_DESIGN_MIN_GC       "probe_design/MINGC"       // GC content (min)
71#define AWAR_PD_DESIGN_MAX_GC       "probe_design/MAXGC"       // GC content (max)
72#define AWAR_PD_DESIGN_MIN_ECOLIPOS "probe_design/MINECOLI"    // ecolipos (min)
73#define AWAR_PD_DESIGN_MAX_ECOLIPOS "probe_design/MAXECOLI"    // ecolipos (max)
74
75#define AWAR_PD_DESIGN_GENE "probe_design/gene" // generate probes for genes ?
76
77// probe design/match (expert window)
78#define AWAR_PD_COMMON_EXP_BONDS "probe_design/bonds/pos"  // prefix for bonds
79#define AWAR_PD_COMMON_EXP_SPLIT "probe_design/SPLIT"
80
81#define AWAR_PD_DESIGN_EXP_DTEDGE "probe_design/DTEDGE"
82#define AWAR_PD_DESIGN_EXP_DT     "probe_design/DT"
83
84#define AWAR_PD_MATCH_NMATCHES   "probe_match/nmatches"
85#define AWAR_PD_MATCH_LIM_NMATCH "probe_match/lim_nmatch"
86#define AWAR_PD_MATCH_MAX_RES    "probe_match/maxres"
87
88// ----------------------------------------
89
90static saiProbeData *g_spd = 0;
91
92static struct {
93    aisc_com          *link;
94    T_PT_LOCS          locs;
95    T_PT_MAIN          com;
96    AW_window_simple  *win;
97    AW_selection_list *resultList; // @@@ replace by TypedSelectionList?
98} PD;
99
100struct ProbeMatchEventParam {
101    GBDATA            *gb_main;
102    AW_selection_list *selection_id;                // may be NULL
103    int               *counter;                     // may be NULL
104
105    ProbeMatchEventParam(GBDATA *gb_main_, int *counter_)         : gb_main(gb_main_), selection_id(NULL), counter(counter_) {}
106    ProbeMatchEventParam(GBDATA *gb_main_, AW_selection_list *id) : gb_main(gb_main_), selection_id(id),   counter(NULL)     {}
107};
108
109struct AutoMatchSettings {
110    AW_window            *aww;
111    ProbeMatchEventParam *event_param; // not owned!
112    bool                  disable;
113
114    AutoMatchSettings(AW_window *aww_, ProbeMatchEventParam *event_param_, bool disable_)
115        : aww(aww_) , event_param(event_param_) , disable(disable_)
116    {}
117    AutoMatchSettings()
118        : aww(NULL), event_param(NULL) , disable(true)
119    {}
120
121    bool initialized() const { return aww != NULL; }
122};
123
124static AutoMatchSettings auto_match_cb_settings;
125
126static void probe_match_event(AW_window *aww, ProbeMatchEventParam *event_param); // prototype
127
128static void auto_match_cb(AW_root *root) {
129    if (!auto_match_cb_settings.disable) {
130        char *ts = root->awar(AWAR_TARGET_STRING)->read_string();
131        if (strlen(ts) > 0) {
132            probe_match_event(auto_match_cb_settings.aww, auto_match_cb_settings.event_param);
133        }
134        free(ts);
135    }
136}
137
138static const char *auto_match_sensitive_awars[] = {
139    AWAR_TARGET_STRING,
140    AWAR_PT_SERVER,
141    AWAR_PD_MATCH_COMPLEMENT,
142    AWAR_MAX_MISMATCHES,
143    AWAR_PD_MATCH_SORTBY,
144    0
145};
146
147static void auto_match_changed(AW_root *root) {
148    static bool callback_active = false;
149    int         autoMatch       = root->awar(AWAR_PD_MATCH_AUTOMATCH)->read_int();
150
151    if (autoMatch) {
152        if (!callback_active) {
153            for (int i = 0; auto_match_sensitive_awars[i]; ++i) {
154                root->awar(auto_match_sensitive_awars[i])->add_callback(auto_match_cb);
155            }
156        }
157    }
158    else {
159        if (callback_active) {
160            for (int i = 0; auto_match_sensitive_awars[i]; ++i) {
161                root->awar(auto_match_sensitive_awars[i])->remove_callback(auto_match_cb);
162            }
163        }
164    }
165    callback_active = bool(autoMatch);
166}
167
168static void enable_auto_match_cb(AW_root *root, AW_window *aww, ProbeMatchEventParam *event_param) {
169    if (event_param == NULL && auto_match_cb_settings.initialized()) {
170        // "partially" enable (w/o ProbeMatchEventParam) is only done
171        // if not already "fully enabled"
172        return;
173    }
174
175    auto_match_cb_settings = AutoMatchSettings(aww, event_param, false);
176    auto_match_changed(root);
177}
178
179static void popup_match_window_cb(AW_window *aww, GBDATA *gb_main) { // @@@ shall be called by auto_match_cb (if never opened b4)
180    AW_root   *root         = aww->get_root();
181    AW_window *match_window = create_probe_match_window(root, gb_main);
182    match_window->activate();
183    root->awar(AWAR_TARGET_STRING)->touch(); // force re-match
184}
185
186// --------------------------------------------------------------------------------
187
188static void popup_probe_design_result_window(AW_window *aww, GBDATA *gb_main) {
189    if (!PD.win) {
190        AW_root *root = aww->get_root();
191
192        PD.win = new AW_window_simple;
193        PD.win->init(root, "PD_RESULT", "PD RESULT");
194        PD.win->load_xfig("pd_reslt.fig");
195
196        PD.win->button_length(6);
197        PD.win->auto_space(10, 10);
198
199        PD.win->at("help");
200        PD.win->callback(makeHelpCallback("probedesignresult.hlp"));
201        PD.win->create_button("HELP", "HELP", "H");
202
203        PD.win->at("result");
204        PD.resultList = PD.win->create_selection_list(AWAR_TARGET_STRING, 40, 5, false);
205        const StorableSelectionList *storable_result_list = new StorableSelectionList(TypedSelectionList("prb", PD.resultList, "designed probes", "designed")); // @@@ make member of PD ?
206
207        PD.resultList->clear();
208        PD.resultList->insert_default("No probes designed yet", "");
209
210        PD.win->at("buttons");
211       
212        PD.win->callback((AW_CB0)AW_POPDOWN);
213        PD.win->create_button("CLOSE", "CLOSE", "C");
214
215        PD.win->callback(makeWindowCallback(awt_clear_selection_list_cb, PD.resultList));
216        PD.win->create_button("CLEAR", "CLEAR", "R");
217       
218        PD.win->callback(makeCreateWindowCallback(create_load_box_for_selection_lists, storable_result_list));
219        PD.win->create_button("LOAD", "LOAD", "L");
220
221        PD.win->callback(makeCreateWindowCallback(create_save_box_for_selection_lists, storable_result_list));
222        PD.win->create_button("SAVE", "SAVE", "S");
223
224        PD.win->callback(makeWindowCallback(create_print_box_for_selection_lists, &storable_result_list->get_typedsellist()));
225        PD.win->create_button("PRINT", "PRINT", "P");
226
227        PD.win->callback(makeWindowCallback(popup_match_window_cb, gb_main));
228        PD.win->create_button("MATCH", "MATCH", "M");
229
230        PD.win->label("Auto match");
231        PD.win->create_toggle(AWAR_PD_MATCH_AUTOMATCH);
232
233        enable_auto_match_cb(root, PD.win, 0);
234    }
235    PD.win->activate();
236}
237
238static int init_local_com_struct()
239{
240    const char *user = GB_getenvUSER();
241
242    if (aisc_create(PD.link, PT_MAIN, PD.com,
243                    MAIN_LOCS, PT_LOCS, PD.locs,
244                    LOCS_USER, user,
245                    NULL)) {
246        return 1;
247    }
248    return 0;
249}
250
251static const char *PD_probe_pt_look_for_server(AW_root *root, GB_ERROR& error) { 
252    // return PT server info string (see GBS_read_arb_tcp for details)
253    // or NULL (in this case 'error' is set)
254
255    const char *result     = 0;
256    const char *server_tag = GBS_ptserver_tag(root->awar(AWAR_PT_SERVER)->read_int());
257
258    error = arb_look_and_start_server(AISC_MAGIC_NUMBER, server_tag);
259    if (!error) {
260        result             = GBS_read_arb_tcp(server_tag);
261        if (!result) error = GB_await_error();
262    }
263    pd_assert(contradicted(result, error));
264    return result;
265}
266
267static GB_ERROR species_requires(GBDATA *gb_species, const char *whats_required) {
268    return GBS_global_string("Species '%s' needs %s", GBT_read_name(gb_species), whats_required);
269}
270
271static GB_ERROR gene_requires(GBDATA *gb_gene, const char *whats_required) {
272    GBDATA *gb_species = GB_get_grandfather(gb_gene);
273    pd_assert(gb_species);
274    return GBS_global_string("Gene '%s' of organism '%s' needs %s", GBT_read_name(gb_gene), GBT_read_name(gb_species), whats_required);
275}
276
277static GB_ERROR pd_get_the_names(GBDATA *gb_main, bytestring &bs, bytestring &checksum) {
278    GBS_strstruct *names     = GBS_stropen(1024);
279    GBS_strstruct *checksums = GBS_stropen(1024);
280    GB_ERROR       error     = 0;
281
282    GB_begin_transaction(gb_main);
283
284    char *use = GBT_get_default_alignment(gb_main);
285
286    for (GBDATA *gb_species = GBT_first_marked_species(gb_main); gb_species; gb_species = GBT_next_marked_species(gb_species)) {
287        GBDATA *gb_name = GB_entry(gb_species, "name");
288        if (!gb_name) { error = species_requires(gb_species, "name"); break; }
289
290        GBDATA *gb_data = GBT_read_sequence(gb_species, use);
291        if (!gb_data) { error = species_requires(gb_species, GBS_global_string("data in '%s'", use)); break; }
292
293        GBS_intcat(checksums, GBS_checksum(GB_read_char_pntr(gb_data), 1, ".-"));
294        GBS_strcat(names, GB_read_char_pntr(gb_name));
295        GBS_chrcat(checksums, '#');
296        GBS_chrcat(names, '#');
297    }
298
299    GBS_str_cut_tail(names, 1); // remove trailing '#'
300    GBS_str_cut_tail(checksums, 1); // remove trailing '#'
301
302    free(use);
303
304    bs.data = GBS_strclose(names);
305    bs.size = strlen(bs.data)+1;
306
307    checksum.data = GBS_strclose(checksums);
308    checksum.size = strlen(checksum.data)+1;
309
310    GB_commit_transaction(gb_main);
311
312    return error;
313}
314
315static GB_ERROR pd_get_the_gene_names(GBDATA *gb_main, bytestring &bs, bytestring &checksum) {
316    GBS_strstruct *names     = GBS_stropen(1024);
317    GBS_strstruct *checksums = GBS_stropen(1024);
318    GB_ERROR       error     = 0;
319
320    GB_begin_transaction(gb_main);
321    const char *use = GENOM_ALIGNMENT; // gene pt server is always build on 'ali_genom'
322
323    for (GBDATA *gb_species = GEN_first_organism(gb_main); gb_species && !error; gb_species = GEN_next_organism(gb_species)) {
324        const char *species_name = 0;
325        {
326            GBDATA *gb_data = GBT_read_sequence(gb_species, use);
327            if (!gb_data) { error = species_requires(gb_species, GBS_global_string("data in '%s'", use)); break; }
328
329            GBDATA *gb_name = GB_search(gb_species, "name", GB_FIND);
330            if (!gb_name) { error = species_requires(gb_species, "name"); break; }
331            species_name = GB_read_char_pntr(gb_name);
332        }
333
334        for (GBDATA *gb_gene = GEN_first_marked_gene(gb_species); gb_gene && !error; gb_gene = GEN_next_marked_gene(gb_gene)) {
335            const char *gene_name = 0;
336            {
337                GBDATA *gb_gene_name = GB_entry(gb_gene, "name");
338                if (!gb_gene_name) { error = gene_requires(gb_gene, "name"); break; }
339                gene_name = GB_read_char_pntr(gb_gene_name);
340            }
341
342            {
343                char *gene_seq       = GBT_read_gene_sequence(gb_gene, false, 0);
344                if (!gene_seq) error = GB_await_error();
345                else {
346                    long        CheckSum = GBS_checksum(gene_seq, 1, ".-");
347                    const char *id       = GBS_global_string("%s/%s", species_name, gene_name);
348
349                    GBS_intcat(checksums, CheckSum);
350                    GBS_strcat(names, id);
351                    GBS_chrcat(checksums, '#');
352                    GBS_chrcat(names, '#');
353
354                    free(gene_seq);
355                }
356            }
357        }
358    }
359
360    GBS_str_cut_tail(names, 1); // remove trailing '#'
361    GBS_str_cut_tail(checksums, 1); // remove trailing '#'
362
363    if (error) {
364        GBS_strforget(names);
365        GBS_strforget(checksums);
366    }
367    else {
368        bs.size = GBS_memoffset(names)+1;
369        bs.data = GBS_strclose(names);
370
371        checksum.size = GBS_memoffset(checksums)+1;
372        checksum.data = GBS_strclose(checksums);
373    }
374    error = GB_end_transaction(gb_main, error);
375    return error;
376}
377
378static int probe_common_send_data(AW_root *root) {
379    // send data common to probe-design AND -match
380    if (aisc_put(PD.link, PT_LOCS, PD.locs,
381                 LOCS_SPLIT,   (double)root->awar(AWAR_PD_COMMON_EXP_SPLIT)->read_float(),
382                 NULL))
383        return 1;
384
385    for (int i=0; i<16; i++) {
386        char buffer[256];
387        sprintf(buffer, AWAR_PD_COMMON_EXP_BONDS "%i", i);
388        if (aisc_put(PD.link, PT_LOCS, PD.locs,
389                     PT_INDEX,  i,
390                     LOCS_BONDVAL, (double)root->awar(buffer)->read_float(),
391                     NULL))
392            return 1;
393    }
394    return 0;
395}
396static int probe_design_send_data(AW_root *root, const T_PT_PDC& pdc) {
397    if (aisc_put(PD.link, PT_PDC, pdc,
398                 PDC_DTEDGE,     (double)root->awar(AWAR_PD_DESIGN_EXP_DTEDGE)->read_float()*100.0,
399                 PDC_DT,         (double)root->awar(AWAR_PD_DESIGN_EXP_DT)->read_float()*100.0,
400                 PDC_CLIPRESULT, root->awar(AWAR_PD_DESIGN_CLIPRESULT)->read_int(),
401                 NULL))
402        return 1;
403
404    return probe_common_send_data(root);
405}
406static int probe_match_send_data(AW_root *root) {
407    if (aisc_put(PD.link, PT_LOCS, PD.locs,
408                 LOCS_MATCH_N_ACCEPT, root->awar(AWAR_PD_MATCH_NMATCHES)->read_int(), 
409                 LOCS_MATCH_N_LIMIT,  root->awar(AWAR_PD_MATCH_LIM_NMATCH)->read_int(),
410                 LOCS_MATCH_MAX_HITS, root->awar(AWAR_PD_MATCH_MAX_RES)->read_int(),
411                 NULL))
412        return 1;
413
414    return probe_common_send_data(root);
415}
416
417static int ecolipos2int(const char *awar_val) {
418    int i = atoi(awar_val);
419    return i>0 ? i : -1;
420}
421
422static char *readableUnknownNames(const ConstStrArray& unames) {
423    GBS_strstruct readable(100);
424
425    int ulast = unames.size()-1;
426    int umax  = ulast <= 10 ? ulast : 10;
427    for (int u = 0; u <= umax; ++u) {
428        if (u) readable.cat(u == ulast ? " and " : ", ");
429        readable.cat(unames[u]);
430    }
431
432    if (umax<ulast) readable.nprintf(30, " (and %i other)", ulast-umax);
433
434    return readable.release();
435}
436
437static void probe_design_event(AW_window *aww, GBDATA *gb_main) {
438    AW_root     *root  = aww->get_root();
439    T_PT_PDC     pdc;
440    T_PT_TPROBE  tprobe;
441    bytestring   bs;
442    bytestring   check;
443    GB_ERROR     error = 0;
444
445    arb_progress progress("Probe design");
446    progress.subtitle("Connecting PT-server");
447
448    {
449        const char *servername = PD_probe_pt_look_for_server(root, error);
450        if (servername) {
451            PD.link = aisc_open(servername, PD.com, AISC_MAGIC_NUMBER, &error);
452            if (!PD.link) error = "can't contact PT server";
453            PD.locs.clear();
454        }
455    }
456
457    if (!error && init_local_com_struct()) {
458        error = "Cannot contact to probe server: Connection Refused";
459    }
460
461    bool design_gene_probes = root->awar(AWAR_PD_DESIGN_GENE)->read_int();
462    if (design_gene_probes) {
463        GB_transaction ta(gb_main);
464        if (!GEN_is_genome_db(gb_main, -1)) design_gene_probes = false;
465    }
466
467    if (!error) {
468        if (design_gene_probes) { // design probes for genes
469            error = pd_get_the_gene_names(gb_main, bs, check);
470        }
471        else {
472            error = pd_get_the_names(gb_main, bs, check);
473        }
474    }
475
476    if (error) {
477        aw_message(error);
478        return;
479    }
480
481    progress.subtitle("probe design running");
482
483    if (aisc_create(PD.link, PT_LOCS, PD.locs,
484                    LOCS_PROBE_DESIGN_CONFIG, PT_PDC, pdc,
485                    PDC_MIN_PROBELEN, root->awar(AWAR_PD_DESIGN_MIN_LENGTH)->read_int(),
486                    PDC_MAX_PROBELEN, root->awar(AWAR_PD_DESIGN_MAX_LENGTH)->read_int(),
487                    PDC_MINTEMP,      (double)root->awar(AWAR_PD_DESIGN_MIN_TEMP)->read_float(),
488                    PDC_MAXTEMP,      (double)root->awar(AWAR_PD_DESIGN_MAX_TEMP)->read_float(),
489                    PDC_MINGC,        (double)root->awar(AWAR_PD_DESIGN_MIN_GC)->read_float()/100.0,
490                    PDC_MAXGC,        (double)root->awar(AWAR_PD_DESIGN_MAX_GC)->read_float()/100.0,
491                    PDC_MAXBOND,      (double)root->awar(AWAR_PD_DESIGN_MAXBOND)->read_int(),
492                    PDC_MIN_ECOLIPOS, (long)ecolipos2int(root->awar(AWAR_PD_DESIGN_MIN_ECOLIPOS)->read_char_pntr()),
493                    PDC_MAX_ECOLIPOS, (long)ecolipos2int(root->awar(AWAR_PD_DESIGN_MAX_ECOLIPOS)->read_char_pntr()),
494                    PDC_MISHIT,       root->awar(AWAR_PD_DESIGN_MISHIT)->read_int(),
495                    PDC_MINTARGETS,   (double)root->awar(AWAR_PD_DESIGN_MINTARGETS)->read_float()/100.0,
496                    NULL))
497    {
498        aw_message ("Connection to PT_SERVER lost (1)");
499        return;
500    }
501   
502    if (probe_design_send_data(root, pdc)) {
503        aw_message ("Connection to PT_SERVER lost (1)");
504        return;
505    }
506
507    aisc_put(PD.link, PT_PDC, pdc,
508             PDC_NAMES, &bs,
509             PDC_CHECKSUMS, &check,
510             NULL);
511
512
513    // Get the unknown names
514    bytestring unknown_names;
515    if (aisc_get(PD.link, PT_PDC, pdc,
516                 PDC_UNKNOWN_NAMES, &unknown_names,
517                 NULL)) {
518        aw_message ("Connection to PT_SERVER lost (1)");
519        return;
520    }
521
522    bool abort = false;
523
524    if (unknown_names.size>1) {
525        ConstStrArray unames_array;
526        GBT_split_string(unames_array, unknown_names.data, "#", true);
527
528        char *readable_unames = readableUnknownNames(unames_array);
529
530        if (design_gene_probes) { // updating sequences of missing genes is not possible with gene PT server
531            aw_message(GBS_global_string("Your PT server is not up to date or wrongly chosen!\n"
532                                         "It knows nothing about the following genes:\n"
533                                         "\n"
534                                         "  %s\n"
535                                         "\n"
536                                         "You have to rebuild the PT server.",
537                                         readable_unames));
538            abort = true;
539        }
540        else if (aw_question("ptserver_add_unknown",
541                             GBS_global_string("Your PT server is not up to date or wrongly chosen!\n"
542                                               "It knows nothing about the following species:\n"
543                                               "\n"
544                                               "  %s\n"
545                                               "\n"
546                                               "You may now temporarily add these sequences for probe design.\n",
547                                               readable_unames),
548                             "Add and continue,Abort"))
549        {
550            abort = true;
551        }
552        else {
553            GB_transaction ta(gb_main);
554
555            char *ali_name = GBT_get_default_alignment(gb_main);
556
557            for (size_t u = 0; !abort && u<unames_array.size(); ++u) {
558                const char *uname      = unames_array[u];
559                GBDATA     *gb_species = GBT_find_species(gb_main, uname);
560                if (!gb_species) {
561                    aw_message(GBS_global_string("Species '%s' not found", uname));
562                    abort = true;
563                }
564                else {
565                    GBDATA *data = GBT_read_sequence(gb_species, ali_name);
566                    if (!data) {
567                        aw_message(GB_export_errorf("Species '%s' has no sequence belonging to alignment '%s'", uname, ali_name));
568                        abort = true;
569                    }
570                    else {
571                        T_PT_SEQUENCE pts;
572
573                        bytestring bs_seq;
574                        bs_seq.data = (char*)GB_read_char_pntr(data);
575                        bs_seq.size = GB_read_string_count(data)+1;
576
577                        aisc_create(PD.link, PT_PDC, pdc,
578                                    PDC_SEQUENCE, PT_SEQUENCE, pts,
579                                    SEQUENCE_SEQUENCE, &bs_seq,
580                                    NULL);
581                    }
582                }
583            }
584            free(ali_name);
585        }
586        free(readable_unames);
587        free(unknown_names.data);
588    }
589
590    if (!abort) {
591        aisc_put(PD.link, PT_PDC, pdc,
592                 PDC_GO, 0,
593                 NULL);
594
595        progress.subtitle("Reading results from server");
596        {
597            char *locs_error = 0;
598            if (aisc_get(PD.link, PT_LOCS, PD.locs,
599                         LOCS_ERROR, &locs_error,
600                         NULL))
601            {
602                aw_message ("Connection to PT_SERVER lost (1)");
603                abort = true;
604            }
605            else if (*locs_error) {
606                aw_message(locs_error);
607                abort = true;
608            }
609            else {
610                free(locs_error);
611            }
612        }
613    }
614
615    if (!abort) {
616        aisc_get(PD.link, PT_PDC, pdc,
617                 PDC_TPROBE, tprobe.as_result_param(),
618                 NULL);
619
620        popup_probe_design_result_window(aww, gb_main);
621        PD.resultList->clear();
622
623        {
624            char *match_info = 0;
625            aisc_get(PD.link, PT_PDC, pdc,
626                     PDC_INFO_HEADER, &match_info,
627                     NULL);
628
629            char *s = strtok(match_info, "\n");
630            while (s) {
631                PD.resultList->insert(s, "");
632                s = strtok(0, "\n");
633            }
634            free(match_info);
635        }
636
637        while (tprobe.exists()) {
638            T_PT_TPROBE  tprobe_next;
639            char        *match_info = 0;
640
641            if (aisc_get(PD.link, PT_TPROBE, tprobe,
642                         TPROBE_NEXT, tprobe_next.as_result_param(),
643                         TPROBE_INFO, &match_info,
644                         NULL)) break;
645
646            tprobe.assign(tprobe_next);
647
648            char *probe, *space;
649            probe = strpbrk(match_info, "acgtuACGTU");
650            if (probe) space = strchr(probe, ' ');
651            if (probe && space) {
652                *space = 0; probe = strdup(probe); *space=' ';
653            }
654            else {
655                probe = strdup("");
656            }
657            PD.resultList->insert(match_info, probe);
658            free(probe);
659            free(match_info);
660        }
661        PD.resultList->insert_default("", "");
662        PD.resultList->update();
663    }
664
665    aisc_close(PD.link, PD.com); PD.link = 0;
666    return;
667}
668
669static bool allow_probe_match_event = true;
670
671static void probe_match_event(AW_window *aww, ProbeMatchEventParam *event_param) {
672    if (allow_probe_match_event) {
673        AW_selection_list *selection_id = event_param ? event_param->selection_id : NULL;
674        int               *counter      = event_param ? event_param->counter : NULL;
675        GBDATA            *gb_main      = event_param ? event_param->gb_main : NULL;
676        AW_root           *root         = aww->get_root();
677        int                show_status  = 0;
678        int                extras       = 1;        // mark species and write to temp fields
679        GB_ERROR           error        = 0;
680
681        if (!gb_main) { error = "Please open probe match window once to enable auto-match"; }
682
683        SmartPtr<arb_progress> progress;
684       
685        if (!error) {
686            const char *servername = PD_probe_pt_look_for_server(root, error);
687
688            if (!error) {
689                if (selection_id) {
690                    selection_id->clear();
691                    pd_assert(!counter);
692                    show_status = 1;
693                }
694                else if (counter) {
695                    extras = 0;
696                }
697
698                if (show_status) {
699                    progress = new arb_progress("Probe match");
700                    progress->subtitle("Connecting PT-server");
701                }
702
703                PD.link = aisc_open(servername, PD.com, AISC_MAGIC_NUMBER, &error);
704                if (!error && !PD.link) error = "Cannot contact PT-server";
705                PD.locs.clear();
706            }
707        }
708
709        if (!error && init_local_com_struct())     error = "Cannot contact PT-server (2)";
710        if (!error && probe_match_send_data(root)) error = "Connection to PT_SERVER lost (2)";
711
712        char *probe = root->awar(AWAR_TARGET_STRING)->read_string();
713
714        if (!error) {
715            if (show_status) progress->subtitle("Probe match running");
716
717            if (aisc_nput(PD.link, PT_LOCS, PD.locs,
718                          LOCS_MATCH_REVERSED,       root->awar(AWAR_PD_MATCH_COMPLEMENT)->read_int(),
719                          LOCS_MATCH_SORT_BY,        root->awar(AWAR_PD_MATCH_SORTBY)->read_int(),
720                          LOCS_MATCH_COMPLEMENT,     0,
721                          LOCS_MATCH_MAX_MISMATCHES, root->awar(AWAR_MAX_MISMATCHES)->read_int(),
722                          LOCS_SEARCHMATCH,          probe,
723                          NULL))
724            {
725                error = "Connection to PT_SERVER lost (2)";
726            }
727            else {
728                delete(g_spd);              // delete previous probe data
729                g_spd = new saiProbeData;
730                transferProbeData(g_spd);
731
732                if (selection_id) {
733                    g_spd->setProbeTarget(probe);
734                }
735            }
736        }
737
738        bytestring bs;
739        bs.data = 0;
740
741        long matches_truncated = 0;
742        if (!error) {
743            if (show_status) progress->subtitle("Reading results");
744
745            T_PT_MATCHLIST  match_list;
746            long            match_list_cnt    = 0;
747            char           *locs_error        = 0;
748
749            if (aisc_get(PD.link, PT_LOCS, PD.locs,
750                         LOCS_MATCH_LIST,        match_list.as_result_param(),
751                         LOCS_MATCH_LIST_CNT,    &match_list_cnt,
752                         LOCS_MATCH_STRING,      &bs,
753                         LOCS_MATCHES_TRUNCATED, &matches_truncated,
754                         LOCS_ERROR,             &locs_error,
755                         NULL))
756            {
757                error = "Connection to PT_SERVER lost (3)";
758            }
759            else {
760                if (locs_error) {
761                    if (*locs_error) error = GBS_static_string(locs_error);
762                    free(locs_error);
763                }
764                else {
765                    error = "Missing status from server (connection aborted?)";
766                }
767            }
768
769            root->awar(AWAR_PD_MATCH_NHITS)->write_string(GBS_global_string(matches_truncated ? "[more than %li]" : "%li", match_list_cnt));
770            if (matches_truncated) {
771                aw_message("Too many matches, displaying a random digest.\n"
772                           "Increase the limit in the expert window.");
773            }
774        }
775
776        long mcount                = 0;
777        long unknown_species_count = 0;
778        long unknown_gene_count    = 0;
779
780        if (!error) {
781            char        toksep[2]  = { 1, 0 };
782            char       *strtok_ptr = 0; // stores strtok position
783            const char *hinfo      = strtok_r(bs.data, toksep, &strtok_ptr);
784
785            bool              gene_flag = false;
786            ProbeMatchParser *parser    = 0;
787            char             *result    = (char*)malloc(1024);
788
789
790            if (hinfo) {
791                g_spd->setHeadline(hinfo);
792                parser = new ProbeMatchParser(probe, hinfo);
793                error  = parser->get_error();
794                if (!error) gene_flag = parser->is_gene_result();
795            }
796
797            if (selection_id) {
798                int width         = 0;
799                if (parser && !error) width = parser->get_probe_region_offset()+2+10; // 2 cause headline is shorter and 10 for match prefix region
800
801                const char *searched = GBS_global_string("%-*s%s", width, "Searched for ", probe);
802                selection_id->insert(searched, probe);
803                if (hinfo) selection_id->insert(hinfo, "");
804            }
805
806
807            // clear all marks and delete all 'tmp' entries
808
809            int mark        = extras && (int)root->awar(AWAR_PD_MATCH_MARKHITS)->read_int();
810            int write_2_tmp = extras && (int)root->awar(AWAR_PD_MATCH_WRITE2TMP)->read_int();
811
812            GB_push_transaction(gb_main);
813
814            GBDATA *gb_species_data = GBT_get_species_data(gb_main);
815            if (mark && !error) {
816                if (show_status) progress->subtitle(gene_flag ? "Unmarking all species and genes" : "Unmarking all species");
817                for (GBDATA *gb_species = GBT_first_marked_species_rel_species_data(gb_species_data);
818                     gb_species;
819                     gb_species = GBT_next_marked_species(gb_species))
820                {
821                    GB_write_flag(gb_species, 0);
822                }
823
824                if (gene_flag) {
825                    // unmark genes of ALL species
826                    for (GBDATA *gb_species = GBT_first_species_rel_species_data(gb_species_data);
827                         gb_species;
828                         gb_species = GBT_next_species(gb_species))
829                    {
830                        GBDATA *genData = GEN_find_gene_data(gb_species);
831                        if (genData) {
832                            for (GBDATA *gb_gene = GEN_first_marked_gene(gb_species);
833                                 gb_gene;
834                                 gb_gene = GEN_next_marked_gene(gb_gene))
835                            {
836                                GB_write_flag(gb_gene, 0);
837                            }
838                        }
839                    }
840                }
841            }
842            if (write_2_tmp && !error) {
843                if (show_status) progress->subtitle("Deleting old 'tmp' fields");
844                for (GBDATA *gb_species = GBT_first_species_rel_species_data(gb_species_data);
845                     gb_species;
846                     gb_species = GBT_next_species(gb_species))
847                {
848                    GBDATA *gb_tmp = GB_entry(gb_species, "tmp");
849                    if (gb_tmp) GB_delete(gb_tmp);
850                    if (gene_flag) {
851                        for (GBDATA *gb_gene = GEN_first_gene(gb_species);
852                             gb_gene;
853                             gb_gene = GEN_next_gene(gb_species))
854                        {
855                            gb_tmp = GB_entry(gb_gene, "tmp");
856                            if (gb_tmp) GB_delete(gb_tmp);
857                        }
858                    }
859                }
860            }
861
862            // read results from pt-server :
863
864            if (!error) {
865                if (show_status) progress->subtitle("Parsing results");
866
867                g_spd->probeSpecies.clear();
868                g_spd->probeSeq.clear();
869
870                if (gene_flag) {
871                    if (!GEN_is_genome_db(gb_main, -1)) {
872                        error = "Wrong PT-Server chosen (selected one is built for genes)";
873                    }
874                }
875            }
876
877            const char *match_name = 0;
878            while (hinfo && !error && (match_name = strtok_r(0, toksep, &strtok_ptr))) {
879                const char *match_info = strtok_r(0, toksep, &strtok_ptr);
880                if (!match_info) break;
881
882                pd_assert(parser);
883                ParsedProbeMatch  ppm(match_info, *parser);
884                char             *gene_str = 0;
885
886                if (gene_flag) {
887                    gene_str = ppm.get_column_content("genename", true);
888                }
889
890                if (!error) {
891                    char flags[]       = "xx";
892                    GBDATA *gb_species = GBT_find_species_rel_species_data(gb_species_data, match_name);
893
894                    if (gb_species) {
895                        GBDATA *gb_gene = 0;
896                        if (gene_flag && strncmp(gene_str, "intergene_", 10) != 0) { // real gene
897                            gb_gene = GEN_find_gene(gb_species, gene_str);
898                            if (!gb_gene) {
899                                aw_message(GBS_global_string("Gene '%s' not found in organism '%s'", gene_str, match_name));
900                            }
901                        }
902
903                        if (mark) {
904                            GB_write_flag(gb_species, 1);
905                            flags[0] = '*';
906                            if (gb_gene) {
907                                GB_write_flag(gb_gene, 1);
908                                flags[1] = '*';
909                            }
910                            else {
911                                flags[1] = '?'; // no gene
912                            }
913                        }
914                        else {
915                            flags[0] = " *"[GB_read_flag(gb_species)];
916                            flags[1] = " *?"[gb_gene ? GB_read_flag(gb_gene) : 2];
917                        }
918
919                        if (write_2_tmp) {
920                            // write or append to field 'tmp'
921                       
922                            GBDATA   *gb_tmp = 0;
923                            GB_ERROR  error2 = 0;
924                            bool      append = true;
925                            {
926                                GBDATA *gb_parent = gene_flag ? gb_gene : gb_species;
927                                gb_tmp            = GB_search(gb_parent, "tmp", GB_FIND);
928                                if (!gb_tmp) {
929                                    append              = false;
930                                    gb_tmp              = GB_search(gb_parent, "tmp", GB_STRING);
931                                    if (!gb_tmp) error2 = GB_await_error();
932                                }
933                            }
934
935                            if (!error2) {
936                                pd_assert(gb_tmp);
937                                if (append) {
938                                    char *prevContent = GB_read_string(gb_tmp);
939                                    if (!prevContent) {
940                                        error2 = GB_await_error();
941                                    }
942                                    else {
943                                        char *concatenatedContent = (char *)malloc(strlen(prevContent)+1+strlen(match_info)+1);
944                                        sprintf(concatenatedContent, "%s\n%s", prevContent, match_info);
945                                        error2 = GB_write_string(gb_tmp, concatenatedContent);
946                                        free(concatenatedContent);
947                                        free(prevContent);
948                                    }
949                                }
950                                else {
951                                    error2 = GB_write_string(gb_tmp, match_info);
952                                }
953                            }
954
955                            if (error2) aw_message(error2);
956                        }
957                    }
958                    else {
959                        flags[0] = flags[1] = '?'; // species does not exist
960                        unknown_species_count++;
961                    }
962
963
964                    if (gene_flag) {
965                        sprintf(result, "%s %s", flags, match_info+1); // both flags (skip 1 space from match info to keep alignment)
966                        char *gene_match_name = new char[strlen(match_name) + strlen(gene_str)+2];
967                        sprintf(gene_match_name, "%s/%s", match_name, gene_str);
968                        if (selection_id) selection_id->insert(result, gene_match_name);   // @@@ wert fuer awar eintragen
969                    }
970                    else {
971                        sprintf(result, "%c %s", flags[0], match_info); // only first flag ( = species related)
972                        if (selection_id) selection_id->insert(result, match_name);   // @@@ wert fuer awar eintragen
973
974                        if (selection_id) {  // storing probe data into linked lists
975                            g_spd->probeSeq.push_back(strdup(match_info));
976                            g_spd->probeSpecies.push_back(strdup(match_name));
977                        }
978                    }
979                    mcount++;
980                }
981
982                free(gene_str);
983            }
984
985            if (error) error = GBS_static_string(error); // make static copy (error may be freed by delete parser)
986            delete parser;
987            free(result);
988
989            GB_pop_transaction(gb_main);
990        }
991
992        if (error) {
993            root->awar(AWAR_PD_MATCH_NHITS)->write_string("[none]"); // clear hits
994            aw_message(error);
995        }
996        else {
997            if (unknown_species_count>0) {
998                aw_message(GBS_global_string("%li matches hit unknown species -- PT-server is out-of-date or build upon a different database", unknown_species_count));
999            }
1000            if (unknown_gene_count>0) {
1001                aw_message(GBS_global_string("%li matches hit unknown genes -- PT-server is out-of-date or build upon a different database", unknown_gene_count));
1002            }
1003
1004            if (selection_id) {     // if !selection_id then probe match window is not opened
1005                pd_assert(g_spd);
1006                root->awar(AWAR_SPV_DB_FIELD_NAME)->touch(); // force refresh of SAI/Probe window
1007            }
1008        }
1009
1010        if (counter) *counter = mcount;
1011
1012        aisc_close(PD.link, PD.com);
1013        PD.link = 0;
1014
1015        if (selection_id) {
1016            const char *last_line                 = 0;
1017            if (error) last_line                  = GBS_global_string("****** Error: %s *******", error);
1018            else if (matches_truncated) last_line = "****** List is truncated *******";
1019            else        last_line                 = "****** End of List *******";
1020
1021            selection_id->insert_default(last_line, "");
1022            selection_id->update();
1023        }
1024
1025        free(bs.data);
1026        free(probe);
1027
1028        LocallyModify<bool> flag(allow_probe_match_event, false);
1029        root->awar(AWAR_TREE_REFRESH)->touch();
1030    }
1031
1032    return;
1033}
1034
1035static void probe_match_all_event(AW_window *aww, AW_selection_list *iselection_id, GBDATA *gb_main) {
1036    auto_match_cb_settings.disable = true;
1037
1038    AW_root *root          = aww->get_root();
1039    char    *target_string = root->awar(AWAR_TARGET_STRING)->read_string();
1040
1041    AW_selection_list_iterator selentry(iselection_id);
1042
1043    arb_progress progress("Matching all resolved strings", iselection_id->size());
1044
1045    bool got_result = false;
1046    while (selentry) {
1047        const char *entry = selentry.get_value();
1048        root->awar(AWAR_TARGET_STRING)->write_string(entry); // probe match
1049        int counter = -1;
1050        ProbeMatchEventParam match_event(gb_main, &counter);
1051        probe_match_event(aww, &match_event);
1052        if (counter==-1) break;
1053
1054        {
1055            char *buffer = new char[strlen(entry)+10]; // write # of matched to list entries
1056            sprintf(buffer, "%5i %s", counter, entry);
1057            selentry.set_displayed(buffer);
1058            got_result   = true;
1059            delete [] buffer;
1060        }
1061
1062        ++selentry;
1063        progress.inc();
1064       
1065    }
1066
1067    if (got_result) {
1068        iselection_id->sort(true, true);
1069        iselection_id->update();
1070        root->awar(AWAR_TARGET_STRING)->write_string(target_string);
1071    }
1072
1073    auto_match_cb_settings.disable = false;
1074}
1075
1076static void resolved_probe_chosen(AW_root *root) {
1077    char *string = root->awar(AWAR_PD_MATCH_RESOLVE)->read_string();
1078    root->awar(AWAR_TARGET_STRING)->write_string(string);
1079}
1080
1081static void selected_match_changed_cb(AW_root *root) {
1082    // this gets called when ever the selected probe match changes
1083    char *temp;
1084    char *selected_match = root->awar(AWAR_PD_SELECTED_MATCH)->read_string();
1085
1086    if (strchr(selected_match, '/')) { // "organism/gene"
1087        temp = strtok(selected_match, "/");
1088        root->awar(AWAR_SPECIES_NAME)->write_string(temp);
1089        temp = strtok(NULL, " /\n");
1090        root->awar(AWAR_GENE_NAME)->write_string(temp);
1091    }
1092    else {
1093        root->awar(AWAR_SPECIES_NAME)->write_string(selected_match);
1094    }
1095
1096    {
1097        LocallyModify<bool> flag(allow_probe_match_event, false); // avoid recursion
1098        root->awar(AWAR_TARGET_STRING)->touch(); // forces editor to jump to probe match in gene
1099    }
1100
1101    free(selected_match);
1102}
1103
1104static void probelength_changed_cb(AW_root *root, bool min_changed) {
1105    AW_awar *awar_minl = root->awar(AWAR_PD_DESIGN_MIN_LENGTH);
1106    AW_awar *awar_maxl = root->awar(AWAR_PD_DESIGN_MAX_LENGTH);
1107
1108    int minl = awar_minl->read_int();
1109    int maxl = awar_maxl->read_int();
1110
1111    if (minl>maxl) {
1112        if (min_changed) awar_maxl->write_int(minl);
1113        else             awar_minl->write_int(maxl);
1114    }
1115}
1116
1117void create_probe_design_variables(AW_root *root, AW_default props, AW_default db)
1118{
1119    char buffer[256]; memset(buffer, 0, 256);
1120    int  i;
1121    PD.win = 0;        // design result window not created
1122    root->awar_string(AWAR_SPECIES_NAME,         "", props);
1123    root->awar_string(AWAR_PD_SELECTED_MATCH,    "", props)->add_callback(selected_match_changed_cb);
1124    root->awar_float (AWAR_PD_DESIGN_EXP_DTEDGE, .5, props);
1125    root->awar_float (AWAR_PD_DESIGN_EXP_DT,     .5, props);
1126
1127
1128    double default_bonds[16] = {
1129        0.0, 0.0, 0.5, 1.1,
1130        0.0, 0.0, 1.5, 0.0,
1131        0.5, 1.5, 0.4, 0.9,
1132        1.1, 0.0, 0.9, 0.0
1133    };
1134
1135    for (i=0; i<16; i++) {
1136        sprintf(buffer, AWAR_PD_COMMON_EXP_BONDS "%i", i);
1137        root->awar_float(buffer, default_bonds[i], props);
1138        root->awar(buffer)->set_minmax(0, 3.0);
1139    }
1140    root->awar_float(AWAR_PD_COMMON_EXP_SPLIT,  .5, props);
1141    root->awar_float(AWAR_PD_DESIGN_EXP_DTEDGE, .5, props);
1142    root->awar_float(AWAR_PD_DESIGN_EXP_DT,     .5, props);
1143
1144    root->awar_int  (AWAR_PD_DESIGN_CLIPRESULT, 50,   props)->set_minmax(0, 1000);
1145    root->awar_int  (AWAR_PD_DESIGN_MISHIT,     0,    props)->set_minmax(0, 100000);
1146    root->awar_int  (AWAR_PD_DESIGN_MAXBOND,    4,    props)->set_minmax(0, 20);
1147    root->awar_float(AWAR_PD_DESIGN_MINTARGETS, 50.0, props)->set_minmax(0, 100);
1148
1149    AW_awar *awar_min_len = root->awar_int(AWAR_PD_DESIGN_MIN_LENGTH, 18, props);
1150    awar_min_len->set_minmax(DOMAIN_MIN_LENGTH, 100)->add_callback(makeRootCallback(probelength_changed_cb, true));
1151    root->awar_int(AWAR_PD_DESIGN_MAX_LENGTH, awar_min_len->read_int(), props)->set_minmax(DOMAIN_MIN_LENGTH, 100)->add_callback(makeRootCallback(probelength_changed_cb, false));
1152
1153    root->awar_float(AWAR_PD_DESIGN_MIN_TEMP,     30.0,   props)->set_minmax(0, 1000);
1154    root->awar_float(AWAR_PD_DESIGN_MAX_TEMP,     100.0,  props)->set_minmax(0, 1000);
1155    root->awar_float(AWAR_PD_DESIGN_MIN_GC,       50.0,   props)->set_minmax(0, 100);
1156    root->awar_float(AWAR_PD_DESIGN_MAX_GC,       100.0,  props)->set_minmax(0, 100);
1157
1158    root->awar_string(AWAR_PD_DESIGN_MIN_ECOLIPOS, "", props);
1159    root->awar_string(AWAR_PD_DESIGN_MAX_ECOLIPOS, "", props);
1160
1161    root->awar_int(AWAR_PT_SERVER,      0, props);
1162    root->awar_int(AWAR_PD_DESIGN_GENE, 0, props);
1163
1164    root->awar_int   (AWAR_PD_MATCH_MARKHITS,   1,       props);
1165    root->awar_int   (AWAR_PD_MATCH_SORTBY,     0,       props);
1166    root->awar_int   (AWAR_PD_MATCH_WRITE2TMP,  0,       props);
1167    root->awar_int   (AWAR_PD_MATCH_COMPLEMENT, 0,       props);
1168
1169    root->awar_int   (AWAR_MAX_MISMATCHES,      0,       db)->set_min(0);
1170    root->awar_string(AWAR_TARGET_STRING,       0,       db);
1171
1172    root->awar_string(AWAR_PD_MATCH_NHITS,      "[none]",props);
1173    root->awar_int   (AWAR_PD_MATCH_NMATCHES,   1,       props);
1174    root->awar_int   (AWAR_PD_MATCH_LIM_NMATCH, 4,       props);
1175    root->awar_int   (AWAR_PD_MATCH_MAX_RES,    1000000, props);
1176
1177    root->awar_int   (AWAR_PD_MATCH_AUTOMATCH,  0,    props)->add_callback(auto_match_changed);
1178
1179    root->awar_string(AWAR_PD_MATCH_RESOLVE, "", props)->add_callback(resolved_probe_chosen);
1180    root->awar_string(AWAR_ITARGET_STRING, "", db);
1181
1182    root->awar_int   (AWAR_PROBE_ADMIN_PT_SERVER,    0,  db);
1183    root->awar_int   (AWAR_PROBE_CREATE_GENE_SERVER, 0,  db);
1184
1185    root->awar_string(AWAR_SPV_SAI_2_PROBE,    "",     db); // name of SAI selected in list
1186    root->awar_string(AWAR_SPV_DB_FIELD_NAME,  "name", db); // name of displayed species field
1187    root->awar_int   (AWAR_SPV_DB_FIELD_WIDTH, 10,     db); // width of displayed species field
1188    root->awar_string(AWAR_SPV_ACI_COMMAND,    "",     db); // User defined or pre-defined ACI command to display
1189    root->awar_string(AWAR_SPV_SELECTED_PROBE, "",     db); // For highlighting the selected PROBE
1190}
1191
1192static AW_window *create_probe_expert_window(AW_root *root, bool for_design) {
1193    AW_window_simple *aws = new AW_window_simple;
1194    if (for_design) {
1195        aws->init(root, "PD_exp", "Probe Design (Expert)");
1196        aws->load_xfig("pd_spec.fig");
1197    }
1198    else {
1199        aws->init(root, "PM_exp", "Probe Match (Expert)");
1200        aws->load_xfig("pm_spec.fig");
1201    }
1202   
1203    aws->label_length(30);
1204    aws->button_length(10);
1205
1206    aws->callback((AW_CB0)AW_POPDOWN);
1207    aws->at("close");
1208    aws->create_button("CLOSE", "CLOSE", "C");
1209
1210    aws->callback(makeHelpCallback(for_design ? "pd_spec_param.hlp" : "pm_spec_param.hlp")); // uses_hlp_res("pm_spec_param.hlp", "pd_spec_param.hlp"); see ../SOURCE_TOOLS/check_ressources.pl@uses_hlp_res
1211    aws->at("help");
1212    aws->create_button("HELP", "HELP", "C");
1213
1214    for (int i=0; i<16; i++) { // bond matrix
1215        char buffer[256];
1216        sprintf(buffer, "%i", i);
1217        aws->at(buffer);
1218        sprintf(buffer, AWAR_PD_COMMON_EXP_BONDS "%i", i);
1219        aws->create_input_field(buffer, 4);
1220    }
1221
1222    aws->sens_mask(AWM_EXP);
1223    aws->at("split"); aws->create_input_field(AWAR_PD_COMMON_EXP_SPLIT,  6);
1224
1225    if (for_design) {
1226        aws->at("dt_edge"); aws->create_input_field(AWAR_PD_DESIGN_EXP_DTEDGE, 6);
1227        aws->at("dt");      aws->create_input_field(AWAR_PD_DESIGN_EXP_DT,     6);
1228        aws->sens_mask(AWM_ALL);
1229    }
1230    else {
1231        aws->at("nmatches");   aws->create_input_field(AWAR_PD_MATCH_NMATCHES,   3);
1232        aws->at("lim_nmatch"); aws->create_input_field(AWAR_PD_MATCH_LIM_NMATCH, 3);
1233        aws->sens_mask(AWM_ALL);
1234        aws->at("max_res");    aws->create_input_field(AWAR_PD_MATCH_MAX_RES,    14);
1235    }
1236   
1237    return aws;
1238}
1239
1240static AWT_config_mapping_def probe_design_mapping_def[] = {
1241    { AWAR_PD_DESIGN_CLIPRESULT,   "clip" },
1242    { AWAR_PD_DESIGN_MISHIT,       "mishit" },
1243    { AWAR_PD_DESIGN_MAXBOND,      "maxbond" },
1244    { AWAR_PD_DESIGN_MINTARGETS,   "mintarget" },
1245    { AWAR_PD_DESIGN_MIN_LENGTH,   "probelen" },
1246    { AWAR_PD_DESIGN_MAX_LENGTH,   "probemaxlen" },
1247    { AWAR_PD_DESIGN_MIN_TEMP,     "mintemp" },
1248    { AWAR_PD_DESIGN_MAX_TEMP,     "maxtemp" },
1249    { AWAR_PD_DESIGN_MIN_GC,       "mingc" },
1250    { AWAR_PD_DESIGN_MAX_GC,       "maxgc" },
1251    { AWAR_PD_DESIGN_MIN_ECOLIPOS, "minecoli" },
1252    { AWAR_PD_DESIGN_MAX_ECOLIPOS, "maxecoli" },
1253    { AWAR_PD_DESIGN_GENE,         "gene" },
1254    { AWAR_PD_COMMON_EXP_SPLIT,    "split" }, 
1255    { AWAR_PD_DESIGN_EXP_DTEDGE,   "dtedge" },
1256    { AWAR_PD_DESIGN_EXP_DT,       "dt" },
1257    { 0, 0 }
1258};
1259
1260static void probe_design_init_config(AWT_config_definition& cdef) {
1261    cdef.add(probe_design_mapping_def);
1262    for (int i = 0; i<16; ++i) {
1263        cdef.add(GBS_global_string(AWAR_PD_COMMON_EXP_BONDS "%i", i), "bond", i);
1264    }
1265}
1266
1267static char *probe_design_store_config(AW_window *aww, AW_CL, AW_CL) {
1268    AWT_config_definition cdef(aww->get_root());
1269    probe_design_init_config(cdef);
1270    return cdef.read();
1271}
1272static void probe_design_restore_config(AW_window *aww, const char *stored_string, AW_CL, AW_CL) {
1273    AWT_config_definition cdef(aww->get_root());
1274    probe_design_init_config(cdef);
1275    cdef.write(stored_string);
1276}
1277
1278AW_window *create_probe_design_window(AW_root *root, GBDATA *gb_main) {
1279    bool is_genom_db;
1280    {
1281        GB_transaction ta(gb_main);
1282        is_genom_db = GEN_is_genome_db(gb_main, -1);
1283    }
1284
1285    AW_window_simple *aws = new AW_window_simple;
1286    aws->init(root, "PROBE_DESIGN", "PROBE DESIGN");
1287
1288    aws->load_xfig("pd_main.fig");
1289
1290    aws->callback((AW_CB0)AW_POPDOWN);
1291    aws->at("close");
1292    aws->create_button("CLOSE", "CLOSE", "C");
1293
1294    aws->at("help");
1295    aws->callback(makeHelpCallback("probedesign.hlp"));
1296    aws->create_button("HELP", "HELP", "H");
1297
1298    aws->callback(makeWindowCallback(probe_design_event, gb_main));
1299    aws->at("design");
1300    aws->highlight();
1301    aws->create_button("GO", "GO", "G");
1302
1303    aws->callback(makeWindowCallback(popup_probe_design_result_window, gb_main));
1304    aws->at("result");
1305    aws->create_button("RESULT", "RESULT", "S");
1306
1307    aws->callback(makeCreateWindowCallback(create_probe_expert_window, true));
1308    aws->at("expert");
1309    aws->create_button("EXPERT", "EXPERT", "S");
1310
1311    aws->at("pt_server");
1312    aws->label("PT-Server:");
1313    awt_create_selection_list_on_pt_servers(aws, AWAR_PT_SERVER, true);
1314
1315    aws->at("lenout");   aws->create_input_field(AWAR_PD_DESIGN_CLIPRESULT, 6);
1316    aws->at("mishit");   aws->create_input_field(AWAR_PD_DESIGN_MISHIT,     6);
1317    aws->sens_mask(AWM_EXP);
1318    aws->at("maxbonds"); aws->create_input_field(AWAR_PD_DESIGN_MAXBOND,    6);
1319    aws->sens_mask(AWM_ALL);
1320    aws->at("minhits");  aws->create_input_field(AWAR_PD_DESIGN_MINTARGETS, 6);
1321
1322    aws->at("minlen"); aws->create_input_field(AWAR_PD_DESIGN_MIN_LENGTH,   5);
1323    aws->at("maxlen"); aws->create_input_field(AWAR_PD_DESIGN_MAX_LENGTH,   5);
1324    aws->at("mint");   aws->create_input_field(AWAR_PD_DESIGN_MIN_TEMP,     5);
1325    aws->at("maxt");   aws->create_input_field(AWAR_PD_DESIGN_MAX_TEMP,     5);
1326    aws->at("mingc");  aws->create_input_field(AWAR_PD_DESIGN_MIN_GC,       5);
1327    aws->at("maxgc");  aws->create_input_field(AWAR_PD_DESIGN_MAX_GC,       5);
1328    aws->at("minpos"); aws->create_input_field(AWAR_PD_DESIGN_MIN_ECOLIPOS, 5);
1329    aws->at("maxpos"); aws->create_input_field(AWAR_PD_DESIGN_MAX_ECOLIPOS, 5);
1330
1331    if (is_genom_db) {
1332        aws->at("gene");
1333        aws->label("Gene probes?");
1334        aws->create_toggle(AWAR_PD_DESIGN_GENE);
1335    }
1336
1337    aws->at("save");
1338    AWT_insert_config_manager(aws, AW_ROOT_DEFAULT, "probe_design", probe_design_store_config, probe_design_restore_config, 0, 0);
1339
1340    return aws;
1341}
1342
1343// -------------------------------------------------------------------
1344
1345inline void my_strupr(char *s) {
1346    pd_assert(s);
1347    for (int i=0; s[i]; i++) {
1348        s[i] = toupper(s[i]);
1349    }
1350}
1351
1352static void resolve_IUPAC_target_string(AW_root *root, AW_selection_list *selection_id, GBDATA *gb_main) {
1353    selection_id->clear();
1354
1355    GB_alignment_type ali_type = GBT_get_alignment_type(gb_main, GBT_get_default_alignment(gb_main));
1356
1357    GB_ERROR err = 0;
1358    if (ali_type != GB_AT_RNA && ali_type!=GB_AT_DNA) {
1359        err = "Wrong alignment type";
1360        GB_clear_error();
1361    }
1362    else {
1363        int   index   = ali_type==GB_AT_RNA ? 1 : 0;
1364        char *istring = root->awar(AWAR_ITARGET_STRING)->read_string();
1365
1366        if (istring && istring[0]) { // contains sth?
1367            my_strupr(istring);
1368
1369            int bases_to_resolve = 0;
1370            char *istr = istring;
1371            int istring_length = strlen(istring);
1372
1373            for (;;) {
1374                char i = *istr++;
1375                if (!i) break;
1376                if (i=='?') continue; // ignore '?'
1377
1378                int idx = i-'A';
1379                if (idx<0 || idx>=26 || iupac::nuc_group[idx][index].members==0) {
1380                    err = GBS_global_string("Illegal character '%c' in IUPAC-String", i);
1381                    break;
1382                }
1383
1384                if (iupac::nuc_group[idx][index].count>1) {
1385                    bases_to_resolve++;
1386                }
1387            }
1388
1389            if (!err) {
1390                int *offsets_to_resolve = new int[bases_to_resolve];
1391                int resolutions = 1;
1392                {
1393                    istr = istring;
1394                    int offset = 0;
1395                    int offset_count = 0;
1396                    for (;;) {
1397                        char i = *istr++;
1398                        if (!i) break;
1399
1400                        if (i!='?') {
1401                            int idx = iupac::to_index(i);
1402                            pd_assert(iupac::nuc_group[idx][index].members);
1403
1404                            if (iupac::nuc_group[idx][index].count>1) {
1405                                offsets_to_resolve[offset_count++] = offset; // store string offsets of non-unique base-codes
1406                                resolutions *= iupac::nuc_group[idx][index].count; // calc # of resolutions
1407                            }
1408                        }
1409                        offset++;
1410                    }
1411                }
1412
1413                {
1414                    int *resolution_idx = new int[bases_to_resolve];
1415                    int *resolution_max_idx = new int[bases_to_resolve];
1416                    {
1417                        int i;
1418                        for (i=0; i<bases_to_resolve; i++) {
1419                            resolution_idx[i] = 0;
1420                            int idx = iupac::to_index(istring[offsets_to_resolve[i]]);
1421                            resolution_max_idx[i] = iupac::nuc_group[idx][index].count-1;
1422                        }
1423                    }
1424
1425                    char *buffer = new char[istring_length+1];
1426                    int not_last = resolutions-1;
1427
1428                    for (;;) {
1429                        // create string according to resolution_idx[]:
1430                        int i;
1431
1432                        memcpy(buffer, istring, istring_length+1);
1433                        for (i=0; i<bases_to_resolve; i++) {
1434                            int off = offsets_to_resolve[i];
1435                            int idx = iupac::to_index(istring[off]);
1436
1437                            pd_assert(iupac::nuc_group[idx][index].members);
1438                            buffer[off] = iupac::nuc_group[idx][index].members[resolution_idx[i]];
1439                        }
1440
1441                        selection_id->insert(buffer, buffer);
1442                        not_last--;
1443
1444                        // permute indices:
1445                        int nidx = bases_to_resolve-1;
1446                        int done = 0;
1447                        while (!done && nidx>=0) {
1448                            if (resolution_idx[nidx]<resolution_max_idx[nidx]) {
1449                                resolution_idx[nidx]++;
1450                                done = 1;
1451                                break;
1452                            }
1453                            nidx--;
1454                        }
1455                        if (!done) break; // we did all permutations!
1456
1457                        nidx++; // do not touch latest incremented index
1458                        while (nidx<bases_to_resolve) resolution_idx[nidx++] = 0; // zero all other indices
1459                    }
1460
1461                    delete [] buffer;
1462                    delete [] resolution_max_idx;
1463                    delete [] resolution_idx;
1464
1465                    pd_assert(!err);
1466                    selection_id->insert_default("", "");
1467                }
1468
1469                delete [] offsets_to_resolve;
1470            }
1471        }
1472        else { // empty input
1473            selection_id->insert_default("", "");
1474        }
1475    }
1476    if (err) selection_id->insert_default(err, "");
1477    selection_id->update();
1478}
1479
1480enum ModMode { TS_MOD_CLEAR, TS_MOD_REV_COMPL, TS_MOD_COMPL };
1481
1482static void modify_target_string(AW_window *aww, GBDATA *gb_main, ModMode mod_mode) {
1483    AW_root  *root          = aww->get_root();
1484    char     *target_string = root->awar(AWAR_TARGET_STRING)->read_string();
1485    GB_ERROR  error         = 0;
1486
1487    if (mod_mode == TS_MOD_CLEAR) target_string[0] = 0;
1488    else {
1489        GB_transaction    ta(gb_main);
1490        GB_alignment_type ali_type = GBT_get_alignment_type(gb_main, GBT_get_default_alignment(gb_main));
1491        if (ali_type == GB_AT_UNKNOWN) {
1492            error = GB_await_error();
1493        }
1494        else if (mod_mode == TS_MOD_REV_COMPL) {
1495            char T_or_U;
1496            error = GBT_determine_T_or_U(ali_type, &T_or_U, "reverse-complement");
1497            if (!error) GBT_reverseComplementNucSequence(target_string, strlen(target_string), T_or_U);
1498        }
1499        else if (mod_mode == TS_MOD_COMPL) {
1500            char T_or_U;
1501            error = GBT_determine_T_or_U(ali_type, &T_or_U, "complement");
1502            if (!error) freeset(target_string, GBT_complementNucSequence(target_string, strlen(target_string), T_or_U));
1503        }
1504    }
1505
1506    if (error) aw_message(error);
1507    else root->awar(AWAR_TARGET_STRING)->write_string(target_string);
1508    free(target_string);
1509}
1510
1511static AW_window *create_IUPAC_resolve_window(AW_root *root, GBDATA *gb_main) {
1512    AW_window_simple *aws = new AW_window_simple;
1513
1514    aws->init(root, "PROBE_MATCH_RESOLVE_IUPAC", "Resolve IUPAC for Probe Match");
1515    aws->load_xfig("pd_match_iupac.fig");
1516
1517    aws->callback((AW_CB0)AW_POPDOWN);
1518    aws->at("close");
1519    aws->create_button("CLOSE", "CLOSE", "C");
1520
1521    aws->callback(makeHelpCallback("pd_match_iupac.hlp"));
1522    aws->at("help");
1523    aws->create_button("HELP", "HELP", "C");
1524
1525    AW_selection_list *iselection_id;
1526    aws->at("iresult");
1527    iselection_id = aws->create_selection_list(AWAR_PD_MATCH_RESOLVE, 32, 15, true);
1528    iselection_id->insert_default("---empty---", "");
1529
1530    aws->at("istring");
1531    aws->create_input_field(AWAR_ITARGET_STRING, 32);
1532
1533    // add callback for automatic decomposition of AWAR_ITARGET_STRING:
1534    RootCallback upd_cb = makeRootCallback(resolve_IUPAC_target_string, iselection_id, gb_main);
1535    root->awar(AWAR_ITARGET_STRING)->add_callback(upd_cb);
1536    root->awar(AWAR_DEFAULT_ALIGNMENT)->add_callback(upd_cb);
1537
1538    aws->callback(makeWindowCallback(probe_match_all_event, iselection_id, gb_main));
1539    aws->at("match_all");
1540    aws->create_button("MATCH_ALL", "MATCH ALL", "A");
1541
1542    return aws;
1543}
1544
1545static void popupSaiProbeMatchWindow(AW_window *aw, GBDATA *gb_main) {
1546    static AW_window *aw_saiProbeMatch = 0;
1547
1548    if (!aw_saiProbeMatch) aw_saiProbeMatch = createSaiProbeMatchWindow(aw->get_root(), gb_main);
1549    if (g_spd) transferProbeData(g_spd); // transferring probe data to saiProbeMatch function
1550
1551    aw_saiProbeMatch->activate();
1552}
1553
1554AW_window *create_probe_match_window(AW_root *root, GBDATA *gb_main) {
1555    static AW_window_simple *aws = 0; // the one and only probe match window
1556    if (!aws) {
1557        aws = new AW_window_simple;
1558
1559        aws->init(root, "PROBE_MATCH", "PROBE MATCH");
1560
1561        aws->load_xfig("pd_match.fig");
1562
1563        aws->callback((AW_CB0)AW_POPDOWN);
1564        aws->at("close");
1565        aws->create_button("CLOSE", "CLOSE", "C");
1566
1567        aws->callback(makeHelpCallback("probematch.hlp"));
1568        aws->at("help");
1569        aws->create_button("HELP", "HELP", "H");
1570
1571        aws->at("string");
1572        aws->create_input_field(AWAR_TARGET_STRING, 32);
1573
1574        AW_selection_list *selection_id;
1575        aws->at("result");
1576        selection_id = aws->create_selection_list(AWAR_PD_SELECTED_MATCH, 110, 15, true);
1577        selection_id->insert_default("****** No results yet *******", "");  // if list is empty -> crashed if new species was selected in ARB_EDIT4
1578
1579        TypedSelectionList *typed_selection = new TypedSelectionList("match", selection_id, "probe match", "probe_match");
1580        aws->at("print");
1581        aws->callback(makeWindowCallback(create_print_box_for_selection_lists, typed_selection));
1582        aws->create_button("PRINT", "PRINT", "P");
1583
1584        aws->at("matchSai");
1585        aws->callback(makeWindowCallback(popupSaiProbeMatchWindow, gb_main));
1586        aws->create_button("MATCH_SAI", "Match SAI", "S");
1587
1588        aws->callback(makeCreateWindowCallback(create_probe_expert_window, false));
1589        aws->at("expert");
1590        aws->create_button("EXPERT", "EXPERT", "X");
1591
1592        aws->at("pt_server");
1593        awt_create_selection_list_on_pt_servers(aws, AWAR_PT_SERVER, true);
1594
1595        aws->at("complement");
1596        aws->create_toggle(AWAR_PD_MATCH_COMPLEMENT);
1597
1598        aws->at("mark");
1599        aws->create_toggle(AWAR_PD_MATCH_MARKHITS);
1600
1601        aws->at("weighted");
1602        aws->create_toggle(AWAR_PD_MATCH_SORTBY);
1603
1604        aws->at("mismatches");
1605        aws->create_input_field(AWAR_MAX_MISMATCHES);
1606
1607        aws->at("tmp");
1608        aws->create_toggle(AWAR_PD_MATCH_WRITE2TMP);
1609
1610        aws->at("nhits");
1611        aws->create_button(0, AWAR_PD_MATCH_NHITS);
1612
1613        aws->button_length(9);
1614
1615        ProbeMatchEventParam *event_param = new ProbeMatchEventParam(gb_main, selection_id);
1616        aws->callback(makeWindowCallback(probe_match_event, event_param));
1617        aws->at("match");
1618        aws->create_button("MATCH", "MATCH", "D");
1619
1620        aws->at("auto");
1621        aws->label("Auto");
1622        aws->create_toggle(AWAR_PD_MATCH_AUTOMATCH);
1623        enable_auto_match_cb(root, aws, event_param);
1624
1625        aws->callback(makeWindowCallback(modify_target_string, gb_main, TS_MOD_CLEAR));
1626        aws->at("clear");
1627        aws->create_button("CLEAR", "Clear", "0");
1628
1629        aws->callback(makeWindowCallback(modify_target_string, gb_main, TS_MOD_REV_COMPL));
1630        aws->at("revcompl");
1631        aws->create_button("REVCOMPL", "RevCompl", "R");
1632
1633        aws->callback(makeWindowCallback(modify_target_string, gb_main, TS_MOD_COMPL));
1634        aws->at("compl");
1635        aws->create_button("COMPL", "Compl", "C");
1636
1637        aws->callback(makeCreateWindowCallback(create_IUPAC_resolve_window, gb_main));
1638        aws->at("iupac");
1639        aws->create_button("IUPAC", "IUPAC", "I");
1640    }
1641    return aws;
1642}
1643
1644static void pd_start_pt_server(AW_window *aww) {
1645    const char *server_tag = GBS_ptserver_tag(aww->get_root()->awar(AWAR_PROBE_ADMIN_PT_SERVER)->read_int());
1646    arb_progress progress("Connecting PT-server");
1647    GB_ERROR error = arb_look_and_start_server(AISC_MAGIC_NUMBER, server_tag);
1648    if (error) aw_message(error);
1649}
1650
1651static void pd_kill_pt_server(AW_window *aww, bool kill_all)
1652{
1653    if (aw_ask_sure("kill_ptserver",
1654                    GBS_global_string("Are you sure to stop %s", kill_all ? "all servers" : "that server"))) {
1655        long min = 0;
1656        long max = 0;
1657
1658        if (kill_all) {
1659            const char * const *pt_servers = GBS_get_arb_tcp_entries("ARB_PT_SERVER*");
1660            while (pt_servers[max]) max++;
1661        }
1662        else {
1663            min = max = aww->get_root()->awar(AWAR_PROBE_ADMIN_PT_SERVER)->read_int(); // selected server
1664        }
1665
1666        arb_progress progress("Stopping PT-servers..", max-min+1);
1667        GB_ERROR     error = NULL;
1668
1669        for (int i = min; i <= max && !error;  i++) {
1670            char *choice = GBS_ptserver_id_to_choice(i, 0);
1671            if (!choice) {
1672                error = GB_await_error();
1673            }
1674            else {
1675                progress.subtitle(GBS_global_string("Trying to stop '%s'", choice));
1676
1677                const char *server_tag = GBS_ptserver_tag(i);
1678                GB_ERROR    kill_error = arb_look_and_kill_server(AISC_MAGIC_NUMBER, server_tag);
1679
1680                if (kill_error) aw_message(GBS_global_string("Could not stop '%s' (Reason: %s)", choice, kill_error));
1681                else aw_message(GBS_global_string("Stopped '%s'", choice));
1682
1683                free(choice);
1684            }
1685            progress.inc_and_check_user_abort(error);
1686        }
1687        progress.done();
1688        if (error) aw_message(error);
1689    }
1690}
1691
1692static void pd_query_pt_server(AW_window *aww) {
1693    const char *server_tag = GBS_ptserver_tag(aww->get_root()->awar(AWAR_PROBE_ADMIN_PT_SERVER)->read_int());
1694
1695    GBS_strstruct *strstruct = GBS_stropen(1024);
1696    GBS_strcat(strstruct,   "echo Contents of directory ARBHOME/lib/pts:;echo;"
1697               "(cd $ARBHOME/lib/pts; ls -l);"
1698               "echo; echo Disk space for PT_server files:; echo;"
1699               "df $ARBHOME/lib/pts;");
1700    GBS_strcat(strstruct, "echo;echo 'Running ARB programs:';");
1701
1702    {
1703        const char *server  = GBS_read_arb_tcp(server_tag);
1704        char       *arb_who = prefixSSH(server, "$ARBHOME/bin/arb_who", 0);
1705        GBS_strcat(strstruct, arb_who);
1706        free(arb_who);
1707    }
1708
1709    char *sys = GBS_strclose(strstruct);
1710    GB_xcmd(sys, true, false);
1711    free(sys);
1712}
1713
1714static void pd_export_pt_server(AW_window *aww, GBDATA *gb_main) {
1715    AW_root  *awr   = aww->get_root();
1716    GB_ERROR  error = 0;
1717
1718    bool create_gene_server = awr->awar(AWAR_PROBE_CREATE_GENE_SERVER)->read_int();
1719    {
1720        GB_transaction ta(gb_main);
1721        if (create_gene_server && !GEN_is_genome_db(gb_main, -1)) create_gene_server = false;
1722
1723        // check alignment first
1724        if (create_gene_server) {
1725            GBDATA *gb_ali     = GBT_get_alignment(gb_main, GENOM_ALIGNMENT);
1726            if (!gb_ali) error = GB_await_error();
1727        }
1728        else { // normal pt server
1729            char              *use     = GBT_get_default_alignment(gb_main);
1730            GB_alignment_type  alitype = GBT_get_alignment_type(gb_main, use);
1731            if (alitype == GB_AT_AA) error = "The PT-server does only support RNA/DNA sequence data";
1732            free(use);
1733        }
1734    }
1735
1736    long        server_num = awr->awar(AWAR_PROBE_ADMIN_PT_SERVER)->read_int();
1737    const char *server_tag  = GBS_ptserver_tag(server_num);
1738
1739    if (!error &&
1740        aw_question("update_ptserver",
1741                    "This function will send your loaded database to the pt_server,\n"
1742                    "which will need a long time (up to several hours) to analyse the data.\n"
1743                    "Until the new server has analyzed all data, no server functions are available.\n\n"
1744                    "Note 1: You must have the write permissions to do that ($ARBHOME/lib/pts/xxx))\n"
1745                    "Note 2: The server will do the job in background,\n"
1746                    "        quitting this program won't affect the server",
1747                    "Cancel,Do it"))
1748    {
1749        arb_progress progress("Updating PT-server");
1750        progress.subtitle("Stopping PT-server");
1751        arb_look_and_kill_server(AISC_MAGIC_NUMBER, server_tag);
1752
1753        const char *ipPort = GBS_read_arb_tcp(server_tag);
1754        const char *file   = GBS_scan_arb_tcp_param(ipPort, "-d");
1755
1756        GBS_add_ptserver_logentry(GBS_global_string("Started build of '%s'", file));
1757        {
1758            char *db_name = awr->awar(AWAR_DB_PATH)->read_string();
1759            GBS_add_ptserver_logentry(GBS_global_string("Exporting DB '%s'", db_name));
1760            free(db_name);
1761        }
1762
1763        progress.subtitle("Exporting the database");
1764        {
1765            const char *mode = GB_supports_mapfile() ? "mbf" : "bf"; // save PT-server database with Fastload file (if supported)
1766            if (create_gene_server) {
1767                char *temp_server_name = GBS_string_eval(file, "*.arb=*_temp.arb", 0);
1768                error = GB_save_as(gb_main, temp_server_name, mode);
1769
1770                if (!error) {
1771                    // convert database (genes -> species)
1772                    progress.subtitle("Preparing DB for gene PT server");
1773                    GBS_add_ptserver_logentry("Preparing DB for gene PT server");
1774                    char *command = GBS_global_string_copy("$ARBHOME/bin/arb_gene_probe %s %s", temp_server_name, file);
1775                    printf("Executing '%s'\n", command);
1776                    int result = system(command);
1777                    if (result != 0) {
1778                        error = GBS_global_string("Couldn't convert database for gene pt server (arb_gene_probe failed, see console for reason)");
1779                    }
1780                    free(command);
1781                }
1782                free(temp_server_name);
1783            }
1784            else { // normal pt_server
1785                error = GB_save_as(gb_main, file, mode);
1786            }
1787        }
1788
1789        if (!error) { // set pt-server database file to same permissions as pts directory
1790            char *dir = const_cast<char*>(strrchr(file, '/'));
1791            if (dir) {
1792                *dir = 0;
1793                long modi = GB_mode_of_file(file);
1794                *dir = '/';
1795                modi &= 0666;
1796                error = GB_set_mode_of_file(file, modi);
1797            }
1798        }
1799
1800        if (!error) {
1801            progress.subtitle("Start PT-server (builds in background)");
1802            error = arb_start_server(server_tag, 1);
1803        }
1804    }
1805    if (error) aw_message(error);
1806}
1807
1808static void pd_view_pt_log(AW_window *) {
1809    AW_edit(GBS_ptserver_logname());
1810}
1811
1812AW_window *create_probe_admin_window(AW_root *root, GBDATA *gb_main) {
1813    bool is_genom_db;
1814    {
1815        GB_transaction ta(gb_main);
1816        is_genom_db = GEN_is_genome_db(gb_main, -1);
1817    }
1818
1819    AW_window_simple *aws = new AW_window_simple;
1820    aws->init(root, "PT_SERVER_ADMIN", "PT_SERVER ADMIN");
1821
1822    aws->load_xfig("pd_admin.fig");
1823
1824
1825    aws->callback(makeHelpCallback("probeadmin.hlp"));
1826    aws->at("help");
1827    aws->create_button("HELP", "HELP", "H");
1828
1829    aws->callback((AW_CB0)AW_POPDOWN);
1830    aws->at("close");
1831    aws->create_button("CLOSE", "CLOSE", "C");
1832
1833    aws->button_length(18);
1834
1835    aws->at("pt_server");
1836    awt_create_selection_list_on_pt_servers(aws, AWAR_PROBE_ADMIN_PT_SERVER, false);
1837
1838    aws->at("start");
1839    aws->callback(pd_start_pt_server);
1840    aws->create_button("START_SERVER", "Start server");
1841
1842    aws->at("kill");
1843    aws->callback(makeWindowCallback(pd_kill_pt_server, false));
1844    aws->create_button("KILL_SERVER", "Stop server");
1845
1846    aws->at("query");
1847    aws->callback(pd_query_pt_server);
1848    aws->create_button("CHECK_SERVER", "Check server");
1849
1850    aws->at("kill_all");
1851    aws->callback(makeWindowCallback(pd_kill_pt_server, true));
1852    aws->create_button("KILL_ALL_SERVERS", "Stop all servers");
1853
1854    aws->at("edit");
1855    aws->callback(makeWindowCallback(awt_edit_arbtcpdat_cb, gb_main));
1856    aws->create_button("CREATE_TEMPLATE", "Configure");
1857
1858    aws->at("log");
1859    aws->callback(pd_view_pt_log);
1860    aws->create_button("EDIT_LOG", "View logfile");
1861
1862    aws->at("export");
1863    aws->callback(makeWindowCallback(pd_export_pt_server, gb_main));
1864    aws->create_button("UPDATE_SERVER", "Build server");
1865
1866    if (is_genom_db) {
1867        aws->at("gene_server");
1868        aws->label("Gene server?");
1869        aws->create_toggle(AWAR_PROBE_CREATE_GENE_SERVER);
1870    }
1871
1872    return aws;
1873}
1874
1875// --------------------------------------------------------------------------------
1876// Probe group result visualization
1877
1878#define AWAR_PG_SELECTED_RESULT "tmp/pg_result/selected"
1879
1880static struct pg_global_struct {
1881    char              *awar_pg_result_filename;     // awar containing result filename
1882    AW_window_simple  *pg_groups_window;            // window showing groups
1883    AW_selection_list *selList;                     // list containing groups
1884    AW_root           *aw_root;
1885    AWT_canvas        *ntw;                         // canvas of main window
1886
1887    char   *pg_filename;                            // database containing results (from one result file)
1888    GBDATA *pg_main;                                // root-handle of probe-group-database
1889} pg_global;
1890
1891
1892static void pg_result_selected(AW_window*, GBDATA *gb_main) {
1893    AW_root *aw_root = pg_global.aw_root;
1894    long position = aw_root->awar(AWAR_PG_SELECTED_RESULT)->read_int();
1895
1896    if (position) { // ignore headline
1897        long i = 1;
1898
1899        GB_transaction ta1(pg_global.pg_main);
1900        GB_transaction ta2(gb_main);
1901
1902        GBT_mark_all(gb_main, 0); // unmark all species
1903
1904        GBDATA *gb_species_data = GBT_get_species_data(gb_main);
1905        GBDATA *pg_group = GB_search(pg_global.pg_main, "probe_groups/group", GB_FIND);
1906        long count = 0;
1907        long marked = 0;
1908        for (; pg_group; pg_group=GB_nextChild(pg_group), ++i) {
1909            if (i==position) {
1910                GBDATA *pg_species = GB_search(pg_group, "species/name", GB_FIND);
1911                for (; pg_species; pg_species=GB_nextChild(pg_species), count++) {
1912                    const char *name           = GB_read_char_pntr(pg_species);
1913                    GBDATA     *gb_speciesname = GB_find_string(gb_species_data, "name", name, GB_IGNORE_CASE, SEARCH_GRANDCHILD);
1914                    if (gb_speciesname) {
1915                        GBDATA *gb_species = GB_get_father(gb_speciesname);
1916                        pd_assert(gb_species);
1917                        GB_write_flag(gb_species, 1); // mark species
1918                        if (!marked) { // select first species
1919                            aw_root->awar(AWAR_SPECIES_NAME)->write_string(name);
1920                        }
1921                        marked++;
1922                    }
1923                    else {
1924                        aw_message(GBS_global_string("No species '%s' in current DB", name));
1925                    }
1926                }
1927                break;
1928            }
1929        }
1930
1931        if (marked!=count) {
1932            aw_message(GBS_global_string("%li species were in group - %li species marked in database", count, marked));
1933        }
1934
1935        NT_group_not_marked_cb(NULL, pg_global.ntw);
1936    }
1937}
1938
1939static void create_probe_group_result_awars(AW_root *aw_root) {
1940    aw_root->awar_int(AWAR_PG_SELECTED_RESULT, 0);
1941}
1942
1943static void create_probe_group_result_sel_box(AW_root *aw_root, AW_window *aws, GBDATA *gb_main) {
1944    char *file_name = aw_root->awar(pg_global.awar_pg_result_filename)->read_string();
1945
1946    AW_selection_list *selList = pg_global.selList;
1947
1948    static bool awars_created;
1949    if (!awars_created) {
1950        create_probe_group_result_awars(aw_root);
1951        awars_created = 1;
1952    }
1953    aw_root->awar(AWAR_PG_SELECTED_RESULT)->write_int(0); // reset to element #0
1954
1955    if (selList==0) {
1956        aws->at("box");
1957        aws->callback(makeWindowCallback(pg_result_selected, gb_main));
1958        selList = pg_global.selList = aws->create_selection_list(AWAR_PG_SELECTED_RESULT, 2, 2, true);
1959    }
1960    else {
1961        selList->clear();
1962    }
1963
1964    GB_ERROR error = 0;
1965
1966    if (pg_global.pg_main) {
1967        GB_close(pg_global.pg_main);
1968        pg_global.pg_main = 0;
1969        freenull(pg_global.pg_filename);
1970    }
1971
1972    pg_global.aw_root = aw_root;
1973    pg_global.pg_filename = strdup(file_name);
1974    pg_global.pg_main = GB_open(file_name, "r");
1975
1976    if (pg_global.pg_main) {
1977        const char *reason = 0;
1978        int32_t i = 0;
1979        selList->insert("members | probes | fitness | quality | mintarget | mishit | probelen | birth", i++);
1980
1981        GB_transaction ta(pg_global.pg_main);
1982        GBDATA *pg_group = GB_search(pg_global.pg_main, "probe_groups/group", GB_FIND);
1983        if (pg_group) {
1984            for (; pg_group; pg_group=GB_nextChild(pg_group), ++i) {
1985
1986                double fitness=-1, quality=-1, min_targets=-1;
1987                int mishit=-1, probelength=-1, birth=-1;
1988                int member_count = 0;
1989                int probe_count = 0;
1990
1991                GBDATA *field;
1992
1993                field = GB_entry(pg_group, "fitness");        if (field) fitness     = GB_read_float(field);
1994                field = GB_entry(pg_group, "quality");        if (field) quality     = GB_read_float(field);
1995                field = GB_entry(pg_group, "min_targets");    if (field) min_targets = GB_read_float(field);
1996                field = GB_entry(pg_group, "mishit");         if (field) mishit      = GB_read_int(field);
1997                field = GB_entry(pg_group, "probelength");    if (field) probelength = GB_read_int(field);
1998                field = GB_entry(pg_group, "birth");          if (field) birth       = GB_read_int(field);
1999
2000                GBDATA *species = GB_search(pg_group, "species/name", GB_FIND);
2001                for (; species; species=GB_nextChild(species)) member_count++;
2002
2003                GBDATA *probe = GB_search(pg_group, "probes/data", GB_FIND);
2004                for (; probe; probe=GB_nextChild(probe)) probe_count++;
2005
2006                char entry[200];
2007
2008                sprintf(entry, "%7i | %6i | %7.5f | %7.1f | %9.2f | %6i | %8i | %5i",
2009                        member_count,
2010                        probe_count,
2011                        fitness,
2012                        quality,
2013                        min_targets,
2014                        mishit,
2015                        probelength,
2016                        birth);
2017
2018                selList->insert(entry, i);
2019            }
2020        }
2021        else {
2022            reason = "probe_group/group - no such entry";
2023        }
2024
2025        if (reason) {
2026            error = GB_export_errorf("Error in database format (reason: %s)", reason);
2027            selList->insert(error, (int32_t)0);
2028        }
2029
2030        selList->update();
2031    }
2032    else {
2033        error = GB_export_errorf("Can't open database '%s'", file_name);
2034        freenull(pg_global.pg_filename);
2035    }
2036
2037    free(file_name);
2038
2039    if (error) {
2040        aw_message(error);
2041    }
2042}
2043
2044static void create_probe_group_groups_window(AW_window *aww) {
2045    AW_root *aw_root = aww->get_root();
2046    GBDATA  *gb_main = pg_global.ntw->gb_main;
2047
2048    if (pg_global.pg_groups_window==0) { // window was not created yet
2049        AW_window_simple *aws = new AW_window_simple;
2050
2051        aws->init(aw_root, "PG_RESULT_SELECTION", "Probe group results");
2052        aws->load_xfig("pg_select.fig");
2053
2054        aws->at("close");
2055        aws->callback((AW_CB0)AW_POPDOWN);
2056        aws->create_button("CLOSE", "CLOSE", "C");
2057
2058        aws->at("help");
2059        aws->callback(makeHelpCallback(""));
2060        aws->create_button("HELP", "HELP");
2061
2062        create_probe_group_result_sel_box(aw_root, aws, gb_main);
2063
2064        pg_global.pg_groups_window = aws;
2065    }
2066    else { // window already created -> refresh selection box
2067        create_probe_group_result_sel_box(aw_root, pg_global.pg_groups_window, gb_main);
2068    }
2069
2070    pg_global.pg_groups_window->show();
2071}
2072
2073AW_window *create_probe_group_result_window(AW_root *awr, AWT_canvas *ntw) {
2074    freenull(pg_global.awar_pg_result_filename);
2075    pg_global.ntw = ntw;
2076
2077    return awt_create_load_box(awr, "Load", "arb_probe_group result", ".", "arb",
2078                               &pg_global.awar_pg_result_filename,
2079                               makeWindowCallback(create_probe_group_groups_window));
2080}
2081
Note: See TracBrowser for help on using the repository browser.