source: branches/port5/PROBE_DESIGN/probe_design.cxx

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