source: branches/tree/NTREE/ad_trees.cxx

Last change on this file was 18737, checked in by westram, 3 years ago
  • introduce LabelTranslator:
    • use for label translation when loading tree into database (TREE_load_to_db).
    • implement NOOP-translate: leaves labels as they are (=former behavior).
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 76.5 KB
Line 
1// =============================================================== //
2//                                                                 //
3//   File      : ad_trees.cxx                                      //
4//   Purpose   :                                                   //
5//                                                                 //
6//   Institute of Microbiology (Technical University Munich)       //
7//   http://www.arb-home.de/                                       //
8//                                                                 //
9// =============================================================== //
10
11#include "tree_position.h"
12#include "ad_trees.h"
13#include "NT_tree_cmp.h"
14
15#include <CT_ctree.hxx>
16
17#include <TreeAdmin.h>
18#include <TreeRead.h>
19#include <TreeWrite.h>
20#include <TreeCallbacks.hxx>
21
22#include <awt_sel_boxes.hxx>
23#include <awt_modules.hxx>
24#include <awt_TreeAwars.hxx>
25
26#include <aw_awars.hxx>
27#include <aw_edit.hxx>
28#include <aw_file.hxx>
29#include <aw_msg.hxx>
30#include <aw_root.hxx>
31#include <aw_select.hxx>
32
33#include <arb_strbuf.h>
34#include <arb_file.h>
35#include <arb_diff.h>
36#include <arb_defs.h>
37
38#include <cctype>
39#include <awt_config_manager.hxx>
40
41#define AWAR_TREE_SAV "ad_tree/"
42#define AWAR_TREE_TMP "tmp/ad_tree/"
43
44#define AWAR_TREE_SECURITY AWAR_TREE_TMP "tree_security"
45#define AWAR_TREE_REM      AWAR_TREE_TMP "tree_rem"
46#define AWAR_TREE_IMPORT   AWAR_TREE_TMP "import_tree"
47
48#define AWAR_GROUPXFER_SAV AWAR_TREE_SAV "groupxfer/"
49
50#define AWAR_GROUPXFER_SOURCE         AWAR_GROUPXFER_SAV "restrict"
51#define AWAR_GROUPXFER_OVERWRITE_MODE AWAR_GROUPXFER_SAV "overwrite"
52#define AWAR_GROUPXFER_INGROUP_ABS    AWAR_GROUPXFER_SAV "ingroup/abs"
53#define AWAR_GROUPXFER_INGROUP_REL    AWAR_GROUPXFER_SAV "ingroup/rel"
54#define AWAR_GROUPXFER_INGROUP_LIM    AWAR_GROUPXFER_SAV "ingroup/lim"
55#define AWAR_GROUPXFER_OUTGROUP_ABS   AWAR_GROUPXFER_SAV "outgroup/abs"
56#define AWAR_GROUPXFER_OUTGROUP_REL   AWAR_GROUPXFER_SAV "outgroup/rel"
57#define AWAR_GROUPXFER_OUTGROUP_LIM   AWAR_GROUPXFER_SAV "outgroup/lim"
58#define AWAR_GROUPXFER_UNKNOWN_ABS    AWAR_GROUPXFER_SAV "unknown"
59#define AWAR_GROUPXFER_KEELING        AWAR_GROUPXFER_SAV "keeling"
60#define AWAR_GROUPXFER_ACI            AWAR_GROUPXFER_SAV "aci"
61
62#define AWAR_TREE_EXPORT_FILEBASE AWAR_TREE_TMP "export_tree"
63#define AWAR_TREE_EXPORT_FILTER   AWAR_TREE_EXPORT_FILEBASE "/filter"
64#define AWAR_TREE_EXPORT_NAME     AWAR_TREE_EXPORT_FILEBASE "/file_name"
65
66#define AWAR_TREE_EXPORT_SAV AWAR_TREE_SAV "export_tree/"
67
68#define AWAR_TREE_EXPORT_FORMAT             AWAR_TREE_EXPORT_SAV "format"
69#define AWAR_TREE_EXPORT_NDS                AWAR_TREE_EXPORT_SAV "NDS"
70#define AWAR_TREE_EXPORT_INCLUDE_BOOTSTRAPS AWAR_TREE_EXPORT_SAV "bootstraps"
71#define AWAR_TREE_EXPORT_INCLUDE_BRANCHLENS AWAR_TREE_EXPORT_SAV "branchlens"
72#define AWAR_TREE_EXPORT_INCLUDE_GROUPNAMES AWAR_TREE_EXPORT_SAV "groupnames"
73#define AWAR_TREE_EXPORT_HIDE_FOLDED_GROUPS AWAR_TREE_EXPORT_SAV "hide_folded"
74#define AWAR_TREE_EXPORT_QUOTEMODE          AWAR_TREE_EXPORT_SAV "quote_mode"
75#define AWAR_TREE_EXPORT_REPLACE            AWAR_TREE_EXPORT_SAV "replace"
76
77
78#define AWAR_TREE_CONSENSE_TMP AWAR_TREE_TMP "consense/"
79#define AWAR_TREE_CONSENSE_SAV AWAR_TREE_SAV "consense/"
80
81#define AWAR_TREE_CONSENSE_TREE     AWAR_TREE_CONSENSE_SAV "tree"
82#define AWAR_TREE_CONSENSE_SELECTED AWAR_TREE_CONSENSE_TMP "selected"
83
84static void tree_vars_callback(AW_root *aw_root) {
85    // map tree awars to display database entries (security+comment)
86
87    if (GLOBAL.gb_main) {
88        GB_transaction ta(GLOBAL.gb_main);
89
90        char   *treename = aw_root->awar(AWAR_TREE_NAME)->read_string();
91        GBDATA *gb_tree  = GBT_find_tree(GLOBAL.gb_main, treename);
92
93        if (!gb_tree) {
94            aw_root->awar(AWAR_TREE_SECURITY)->unmap();
95            aw_root->awar(AWAR_TREE_REM)->unmap();
96        }
97        else {
98            GBDATA *tree_prot = GB_search(gb_tree, "security", GB_FIND);
99            if (!tree_prot) GBT_readOrCreate_int(gb_tree, "security", GB_read_security_write(gb_tree));
100            tree_prot         = GB_search(gb_tree, "security", GB_INT);
101
102            GBDATA *tree_rem = GB_search(gb_tree, "remark",   GB_STRING);
103            aw_root->awar(AWAR_TREE_SECURITY)->map(tree_prot);
104            aw_root->awar(AWAR_TREE_REM)     ->map(tree_rem);
105        }
106
107        // create default filename from tree-name:
108        {
109            char *suffix = aw_root->awar(AWAR_TREE_EXPORT_FILTER)->read_string();
110            char *fname  = GBS_string_eval(treename, GBS_global_string("*=*1.%s:tree_*=*1", suffix));
111
112            aw_root->awar(AWAR_TREE_EXPORT_NAME)->write_string(fname); // create default file name
113
114            free(fname);
115            free(suffix);
116        }
117
118        free(treename);
119    }
120}
121
122static void update_default_treename_cb(AW_root *aw_root) {
123    // update import tree name depending on file name
124    GB_transaction ta(GLOBAL.gb_main);
125
126    char *treename        = aw_root->awar(AWAR_TREE_IMPORT "/file_name")->read_string();
127    char *treename_nopath = strrchr(treename, '/');
128
129    if (treename_nopath) {
130        ++treename_nopath;
131    }
132    else {
133        treename_nopath = treename;
134    }
135
136    char *fname = GBS_string_eval(treename_nopath, "*.tree=tree_*1:*.ntree=tree_*1:*.xml=tree_*1:.=:-=_: =_");
137    aw_root->awar(AWAR_TREE_IMPORT "/tree_name")->write_string(fname);
138
139    free(fname);
140    free(treename);
141}
142
143static void ad_tree_set_security(AW_root *aw_root) {
144    if (GLOBAL.gb_main) {
145        GB_transaction ta(GLOBAL.gb_main);
146
147        char   *treename = aw_root->awar(AWAR_TREE_NAME)->read_string();
148        GBDATA *gb_tree  = GBT_find_tree(GLOBAL.gb_main, treename);
149
150        if (gb_tree) {
151            long prot = aw_root->awar(AWAR_TREE_SECURITY)->read_int();
152            long old  = GB_read_security_delete(gb_tree);
153
154            GB_ERROR error = NULp;
155            if (old != prot) {
156                error             = GB_write_security_delete(gb_tree, prot);
157                if (!error) error = GB_write_security_write(gb_tree, prot);
158            }
159            aw_message_if(error);
160        }
161        free(treename);
162    }
163}
164
165enum ExportTreeType {
166    AD_TREE_EXPORT_FORMAT_NEWICK,
167    AD_TREE_EXPORT_FORMAT_XML,
168    AD_TREE_EXPORT_FORMAT_NEWICK_PRETTY,
169};
170
171enum ExportNodeType {
172    AD_TREE_EXPORT_NODE_SPECIES_NAME,
173    AD_TREE_EXPORT_NODE_NDS
174};
175
176static void update_filter_cb(AW_root *root) {
177    const char *filter_type = NULp;
178
179    switch (ExportTreeType(root->awar(AWAR_TREE_EXPORT_FORMAT)->read_int())) {
180        case AD_TREE_EXPORT_FORMAT_XML: filter_type = "xml"; break;
181        case AD_TREE_EXPORT_FORMAT_NEWICK:
182        case AD_TREE_EXPORT_FORMAT_NEWICK_PRETTY:
183            switch (ExportNodeType(root->awar(AWAR_TREE_EXPORT_NDS)->read_int())) {
184                case AD_TREE_EXPORT_NODE_SPECIES_NAME:  filter_type = "tree"; break;
185                case AD_TREE_EXPORT_NODE_NDS:           filter_type = "ntree"; break;
186                default: nt_assert(0); break;
187            }
188            break;
189        default: nt_assert(0); break;
190    }
191
192    nt_assert(filter_type);
193    root->awar(AWAR_TREE_EXPORT_FILTER)->write_string(filter_type);
194}
195
196void create_trees_var(AW_root *aw_root, AW_default aw_def) {
197    AW_awar *awar_tree_name = aw_root->awar_string(AWAR_TREE_NAME, NULp, aw_def)->set_srt(SRT_AUTOCORRECT_TREENAME);
198
199    aw_root->awar_pointer(AWAR_GROUP, NULp, aw_def);
200
201    TreeAdmin::create_awars(aw_root, aw_def, true);
202
203    aw_root->awar_int   (AWAR_TREE_SECURITY, 0,    aw_def);
204    aw_root->awar_string(AWAR_TREE_REM,      NULp, aw_def);
205
206    AW_create_fileselection_awars(aw_root, AWAR_TREE_EXPORT_FILEBASE, "", ".tree", "treefile");
207    aw_root->awar_int(AWAR_TREE_EXPORT_FORMAT, AD_TREE_EXPORT_FORMAT_NEWICK, aw_def)-> add_callback(update_filter_cb);
208    aw_root->awar_int(AWAR_TREE_EXPORT_NDS,  AD_TREE_EXPORT_NODE_SPECIES_NAME, aw_def)-> add_callback(update_filter_cb);
209
210    aw_root->awar_int(AWAR_TREE_EXPORT_INCLUDE_BOOTSTRAPS,  0, aw_def);
211    aw_root->awar_int(AWAR_TREE_EXPORT_INCLUDE_BRANCHLENS,  1, aw_def);
212    aw_root->awar_int(AWAR_TREE_EXPORT_HIDE_FOLDED_GROUPS,  0, aw_def);
213    aw_root->awar_int(AWAR_TREE_EXPORT_INCLUDE_GROUPNAMES,  1, aw_def);
214    aw_root->awar_int(AWAR_TREE_EXPORT_QUOTEMODE, TREE_SINGLE_QUOTES, aw_def); // old default behavior
215    aw_root->awar_int(AWAR_TREE_EXPORT_REPLACE, 0, aw_def); // old default behavior
216
217    AW_create_fileselection_awars(aw_root, AWAR_TREE_IMPORT, "", ".tree", "treefile");
218
219    aw_root->awar_string(AWAR_TREE_IMPORT "/tree_name", "tree_",    aw_def)->set_srt(SRT_AUTOCORRECT_TREENAME);
220
221    aw_root->awar(AWAR_TREE_IMPORT "/file_name")->add_callback(update_default_treename_cb);
222    awar_tree_name->add_callback(tree_vars_callback);
223    awar_tree_name->map(AWAR_TREE);
224    aw_root->awar(AWAR_TREE_SECURITY)->add_callback(ad_tree_set_security);
225
226    aw_root->awar_int(AWAR_GROUPXFER_SOURCE,         XFER_ALL_GROUPS,        aw_def);
227    aw_root->awar_int(AWAR_GROUPXFER_OVERWRITE_MODE, REMOVE_EXISTING_GROUPS, aw_def);
228
229    aw_root->awar_float(AWAR_GROUPXFER_INGROUP_ABS,  1.0,    aw_def);
230    aw_root->awar_float(AWAR_GROUPXFER_OUTGROUP_ABS, 1.0,    aw_def);
231    aw_root->awar_float(AWAR_GROUPXFER_INGROUP_REL,  0.0,    aw_def);
232    aw_root->awar_float(AWAR_GROUPXFER_OUTGROUP_REL, 0.0,    aw_def);
233    aw_root->awar_float(AWAR_GROUPXFER_INGROUP_LIM,  0.0,    aw_def);
234    aw_root->awar_float(AWAR_GROUPXFER_OUTGROUP_LIM, 100.0,  aw_def);
235    aw_root->awar_float(AWAR_GROUPXFER_UNKNOWN_ABS,  0.0001, aw_def);
236    aw_root->awar_float(AWAR_GROUPXFER_KEELING,      0.01,   aw_def);
237
238    aw_root->awar_string(AWAR_GROUPXFER_ACI, "", aw_def);
239
240    aw_root->awar_string(AWAR_TREE_CONSENSE_TREE, "tree_consensus", aw_def)->set_srt(SRT_AUTOCORRECT_TREENAME);
241    AW_awar *ctree_awar = aw_root->awar_string(AWAR_TREE_CONSENSE_SELECTED, "", aw_def);
242    AWT_registerTreeAwarSimple(ctree_awar);
243
244    update_filter_cb(aw_root);
245    tree_vars_callback(aw_root);
246}
247
248static void tree_save_cb(AW_window *aww) {
249    AW_root  *aw_root   = aww->get_root();
250    char     *tree_name = aw_root->awar(AWAR_TREE_NAME)->read_string();
251
252    GB_ERROR error = NULp;
253
254    if (!tree_name || !strlen(tree_name)) {
255        error = "Please select a tree first";
256    }
257    else {
258        char *fname   = aw_root->awar(AWAR_TREE_EXPORT_NAME)->read_string();
259        char *db_name = aw_root->awar(AWAR_DB_NAME)->read_string();
260
261        bool           use_NDS    = ExportNodeType(aw_root->awar(AWAR_TREE_EXPORT_NDS)->read_int()) == AD_TREE_EXPORT_NODE_NDS;
262        ExportTreeType exportType = static_cast<ExportTreeType>(aw_root->awar(AWAR_TREE_EXPORT_FORMAT)->read_int());
263
264        SmartPtr<TreeLabeler> labeler;
265        if (use_NDS) labeler = new NDS_Labeler(NDS_OUTPUT_LEAFTEXT);
266        else         labeler = new Node_ID_Labeler;
267
268        switch (exportType) {
269            case AD_TREE_EXPORT_FORMAT_XML:
270                error = TREE_write_XML(GLOBAL.gb_main, db_name, tree_name, *labeler,
271                                       aw_root->awar(AWAR_TREE_EXPORT_HIDE_FOLDED_GROUPS)->read_int(),
272                                       fname);
273                break;
274
275            case AD_TREE_EXPORT_FORMAT_NEWICK:
276            case AD_TREE_EXPORT_FORMAT_NEWICK_PRETTY:
277                TREE_node_quoting quoteMode = TREE_node_quoting(aw_root->awar(AWAR_TREE_EXPORT_QUOTEMODE)->read_int());
278                if (aw_root->awar(AWAR_TREE_EXPORT_REPLACE)->read_int()) {
279                    quoteMode = TREE_node_quoting(quoteMode|TREE_FORCE_REPLACE);
280                }
281
282                error = TREE_write_Newick(GLOBAL.gb_main, tree_name, *labeler,
283                                          aw_root->awar(AWAR_TREE_EXPORT_INCLUDE_BRANCHLENS)->read_int(),
284                                          aw_root->awar(AWAR_TREE_EXPORT_INCLUDE_BOOTSTRAPS)->read_int(),
285                                          aw_root->awar(AWAR_TREE_EXPORT_INCLUDE_GROUPNAMES)->read_int(),
286                                          exportType == AD_TREE_EXPORT_FORMAT_NEWICK_PRETTY,
287                                          quoteMode,
288                                          fname);
289                break;
290        }
291
292        free(db_name);
293        free(fname);
294    }
295
296    aww->hide_or_notify(error);
297    free(tree_name);
298
299    AW_refresh_fileselection(aw_root, AWAR_TREE_EXPORT_FILEBASE);
300}
301
302static AWT_config_mapping_def tree_export_config_mapping[] = {
303    { AWAR_TREE_EXPORT_FORMAT,             "format" },
304    { AWAR_TREE_EXPORT_NDS,                "nodetype" },
305    { AWAR_TREE_EXPORT_INCLUDE_BRANCHLENS, "lengths" },
306    { AWAR_TREE_EXPORT_INCLUDE_BOOTSTRAPS, "bootstraps" },
307    { AWAR_TREE_EXPORT_INCLUDE_GROUPNAMES, "groupnames" },
308    { AWAR_TREE_EXPORT_HIDE_FOLDED_GROUPS, "hidefolded" },
309    { AWAR_TREE_EXPORT_QUOTEMODE,          "quotemode" },
310    { AWAR_TREE_EXPORT_REPLACE,            "replacechars" },
311
312    { NULp, NULp }
313};
314
315static AW_window *create_tree_export_window(AW_root *root) {
316    AW_window_simple *aws = new AW_window_simple;
317    aws->init(root, "SAVE_TREE", "TREE SAVE");
318    aws->load_xfig("tree_export.fig");
319
320    aws->at("close");
321    aws->callback(AW_POPDOWN);
322    aws->create_button("CLOSE", "CLOSE", "C");
323
324    aws->at("help");
325    aws->callback(makeHelpCallback("tr_export.hlp"));
326    aws->create_button("HELP", "HELP", "H");
327
328    AW_create_standard_fileselection(aws, AWAR_TREE_EXPORT_FILEBASE);
329
330    aws->auto_space(10, 10);
331
332    aws->at("user");
333    aws->create_option_menu(AWAR_TREE_EXPORT_FORMAT, true);
334    aws->insert_option("NEWICK TREE FORMAT",                   "N", AD_TREE_EXPORT_FORMAT_NEWICK);
335    aws->insert_option("NEWICK TREE FORMAT (pretty, but big)", "P", AD_TREE_EXPORT_FORMAT_NEWICK_PRETTY);
336    aws->insert_option("ARB_XML TREE FORMAT",                  "X", AD_TREE_EXPORT_FORMAT_XML);
337    aws->update_option_menu();
338
339    aws->at("user2");
340    aws->label("Nodetype");
341    aws->create_toggle_field(AWAR_TREE_EXPORT_NDS, 1);
342    aws->insert_default_toggle("Species ID ('name')", "S", 0);
343    aws->insert_toggle("NDS", "N", 1);
344    aws->update_toggle_field();
345
346    aws->at_newline(); aws->label("Save branch lengths"); aws->create_toggle(AWAR_TREE_EXPORT_INCLUDE_BRANCHLENS);
347    aws->at_newline(); aws->label("Save bootstrap values"); aws->create_toggle(AWAR_TREE_EXPORT_INCLUDE_BOOTSTRAPS);
348    aws->at_newline(); aws->label("Save group names"); aws->create_toggle(AWAR_TREE_EXPORT_INCLUDE_GROUPNAMES);
349    aws->at_newline(); aws->label("Hide folded groups (XML only)"); aws->create_toggle(AWAR_TREE_EXPORT_HIDE_FOLDED_GROUPS);
350
351    aws->at_newline();
352    aws->label("Name quoting (Newick only)");
353    aws->create_option_menu(AWAR_TREE_EXPORT_QUOTEMODE, true);
354    aws->insert_option("none",            "n", TREE_DISALLOW_QUOTES);
355    aws->insert_option("single",          "s", TREE_SINGLE_QUOTES);
356    aws->insert_option("double",          "d", TREE_DOUBLE_QUOTES);
357    aws->insert_option("single (forced)", "i", TREE_SINGLE_QUOTES|TREE_FORCE_QUOTES);
358    aws->insert_option("double (forced)", "o", TREE_DOUBLE_QUOTES|TREE_FORCE_QUOTES);
359    aws->update_option_menu();
360
361    aws->at_newline(); aws->label("Replace problem chars"); aws->create_toggle(AWAR_TREE_EXPORT_REPLACE);
362
363    aws->at_newline();
364    aws->button_length(10);
365
366    aws->callback(tree_save_cb);
367    aws->create_button("SAVE", "SAVE", "o");
368
369    AWT_insert_config_manager(aws, AW_ROOT_DEFAULT, "tree_export", tree_export_config_mapping);
370
371    aws->window_fit();
372    update_filter_cb(root);
373
374    return aws;
375}
376
377static char *readXmlTree(char *fname) {
378    // create a temp file
379    char tempFile[]  = "newickXXXXXX";
380    int createTempFile = mkstemp(tempFile);
381
382    if (createTempFile) {
383        GBS_strstruct buf(strlen(fname));
384
385        // extract path from fname in order to place a copy of dtd file required to validate xml file
386        {
387            char *tmpFname = ARB_strdup(fname);
388            for (char *tok = strtok(tmpFname, "/"); tok;) {
389                char *tmp = tok;
390                tok = strtok(NULp, "/");
391                if (tok) {
392                    buf.put('/');
393                    buf.cat(tmp);
394                }
395            }
396            free(tmpFname);
397        }
398
399        // linking arb_tree.dtd file to the Path from where xml file is loaded
400        char *command = GBS_global_string_copy("ln -s %s/lib/dtd/arb_tree.dtd %s/.", GB_getenvARBHOME(), buf.get_data());
401        GB_xcmd(command, XCMD_SYNC_WAIT_ON_ERROR);
402
403        // execute xml2newick to convert xml format tree to newick format tree
404        command = GBS_global_string_copy("xml2newick %s %s", fname, tempFile);
405        GB_xcmd(command, XCMD_SYNC_WAIT_ON_ERROR);
406
407        free(command);
408
409        // return newick format tree file
410        return ARB_strdup(tempFile);
411    }
412    else {
413        printf("Failed to create Temporary File to Parse xml file!\n");
414        return NULp;
415    }
416}
417
418static void tree_load_cb(AW_window *aww) {
419    GB_ERROR  error     = NULp;
420    AW_root  *aw_root   = aww->get_root();
421    char     *tree_name = aw_root->awar(AWAR_TREE_IMPORT "/tree_name")->read_string();
422
423    {
424        LabelTranslator relabeler; // @@@ use translation settings (create GUI+awars)
425
426        char *pcTreeFormat = aw_root->awar(AWAR_TREE_IMPORT "/filter")->read_string();
427        char *fname        = aw_root->awar(AWAR_TREE_IMPORT "/file_name")->read_string();
428        if (strcmp(pcTreeFormat, "xml") == 0) {
429            char *tempFname = readXmlTree(fname);
430
431            error = TREE_load_to_db(GLOBAL.gb_main, tempFname, tree_name, relabeler);
432
433            GB_unlink_or_warn(tempFname, NULp);
434            free(tempFname);
435        }
436        else {
437            error = TREE_load_to_db(GLOBAL.gb_main, fname, tree_name, relabeler);
438        }
439
440        free(fname);
441        free(pcTreeFormat);
442    }
443
444    aww->hide_or_notify(error);
445    if (!error) aw_root->awar(AWAR_TREE)->write_string(tree_name); // show new tree
446
447    free(tree_name);
448}
449
450static AW_window *create_tree_import_window(AW_root *root) {
451    AW_window_simple *aws = new AW_window_simple;
452    aws->init(root, "LOAD_TREE", "TREE LOAD");
453    aws->load_xfig("sel_box_tree.fig");
454
455    aws->at("close");
456    aws->callback(AW_POPDOWN);
457    aws->create_button("CLOSE", "CLOSE", "C");
458
459    aws->at("help");
460    aws->callback(makeHelpCallback("tr_import.hlp"));
461    aws->create_button("HELP", "HELP", "H");
462
463    aws->at("format");
464    aws->create_option_menu(AWAR_TREE_IMPORT "/filter", false);
465    aws->insert_default_option("Newick", "t", "tree");
466    aws->insert_option("XML", "x", "xml");
467    aws->update_option_menu();
468
469    aws->at("user");
470    aws->label("Tree name");
471    aws->create_input_field(AWAR_TREE_IMPORT "/tree_name", 15);
472
473    AW_create_standard_fileselection(aws, AWAR_TREE_IMPORT);
474
475    aws->at("save2");
476    aws->callback(tree_load_cb);
477    aws->create_button("LOAD", "LOAD", "o");
478
479    aws->window_fit();
480
481    return aws;
482}
483
484static void ad_move_tree_info(AW_window *aww, bool transferGroups) {
485    AW_root *awr = aww->get_root();
486
487    char     *log_file = NULp;
488    GB_ERROR  error    = NULp;
489
490    GroupTransferMode mode = COMPARE_TOPOLOGY;
491    GroupsToTransfer  what = XFER_ALL_GROUPS;
492
493    if (transferGroups) {
494        // log file is only written if transferring groups!
495        char *log_name       = GB_unique_filename("arb_node", "log");
496        log_file             = GB_create_tempfile(log_name);
497        if (!log_file) error = GB_await_error();
498        free(log_name);
499
500        what = GroupsToTransfer(awr->awar(AWAR_GROUPXFER_SOURCE)->read_int());
501        mode = GroupTransferMode(awr->awar(AWAR_GROUPXFER_OVERWRITE_MODE)->read_int());
502    }
503
504    if (!error) {
505        char *src_tree = TreeAdmin::source_tree_awar(awr)->read_string();
506        char *dst_tree = TreeAdmin::dest_tree_awar(awr)->read_string();
507        char *aci      = awr->awar(AWAR_GROUPXFER_ACI)->read_string();
508
509        NT_deselect_group(awr); // avoid crash (if group selected in target tree)
510
511        GroupMatchScorer userScorer;
512        if (transferGroups) {
513            userScorer.setLimits(RatioLimits(awr->awar(AWAR_GROUPXFER_INGROUP_LIM)->read_float()/100, 1.0),
514                                 RatioLimits(0.0, awr->awar(AWAR_GROUPXFER_OUTGROUP_LIM)->read_float()/100));
515
516            userScorer.setPerErrorPenalties(awr->awar(AWAR_GROUPXFER_INGROUP_ABS)->read_float(),
517                                            awr->awar(AWAR_GROUPXFER_OUTGROUP_ABS)->read_float(),
518                                            awr->awar(AWAR_GROUPXFER_UNKNOWN_ABS)->read_float());
519
520            userScorer.setRelativePenalties(awr->awar(AWAR_GROUPXFER_INGROUP_REL)->read_float(),
521                                            awr->awar(AWAR_GROUPXFER_OUTGROUP_REL)->read_float());
522        }
523
524        error = NTREE_move_tree_info(GLOBAL.gb_main, src_tree, dst_tree, log_file, mode, what, userScorer, aci);
525
526        if (mode == COMPARE_TOPOLOGY && !error) {
527            // if tree is not shown -> provide hint
528            TREE_canvas *canvas_showing_dest = NT_get_canvas_showing_tree(dst_tree, false);
529            if (!canvas_showing_dest) {
530                aw_message(GBS_global_string("Note: annotations added to tree '%s'\n"
531                                             "Press the right 'Display' button to view that tree", dst_tree));
532            }
533        }
534
535        if (log_file) {
536            AW_edit(log_file);
537            GB_remove_on_exit(log_file);
538        }
539
540        free(aci);
541        free(dst_tree);
542        free(src_tree);
543    }
544
545    aw_message_if(error);
546
547    free(log_file);
548}
549
550static void swap_source_dest_cb(AW_window *aww) {
551    AW_root *root = aww->get_root();
552
553    AW_awar *s = TreeAdmin::source_tree_awar(root);
554    AW_awar *d = TreeAdmin::dest_tree_awar(root);
555
556    char *old_src = s->read_string();
557    s->write_string(d->read_char_pntr());
558    d->write_string(old_src);
559    free(old_src);
560}
561
562static void copy_tree_awar_cb(UNFIXED, AW_awar *aw_source, AW_awar *aw_dest) {
563    const char *tree = aw_source->read_char_pntr();
564    if (tree && tree[0]) aw_dest->write_string(tree);
565}
566
567void NT_create_twoTreeSelection(AW_window *aws) {
568    AW_root *root = aws->get_root();
569
570    aws->auto_space(10, 3);
571
572    aws->at("tree1");
573    awt_create_TREE_selection_list(GLOBAL.gb_main, aws, TreeAdmin::source_tree_awar(root)->awar_name, true);
574    aws->at("tree2");
575    awt_create_TREE_selection_list(GLOBAL.gb_main, aws, TreeAdmin::dest_tree_awar(root)->awar_name, false);
576
577    AW_awar *awar_displayed_tree = root->awar(AWAR_TREE_NAME);
578
579    { // let source tree default to currently displayed tree:
580        static bool firstCall = true;
581        if (firstCall) {
582            TreeAdmin::source_tree_awar(root)->write_string(awar_displayed_tree->read_char_pntr());
583            firstCall = false;
584        }
585    }
586
587
588    aws->at("select1");
589    aws->callback(makeWindowCallback(copy_tree_awar_cb, awar_displayed_tree, TreeAdmin::source_tree_awar(root)));  aws->create_autosize_button("SELECT_DISPLAYED1", "Use shown");
590    aws->callback(makeWindowCallback(copy_tree_awar_cb, TreeAdmin::source_tree_awar(root), awar_displayed_tree));  aws->create_autosize_button("DISPLAY_SELECTED1", "Display");
591
592    aws->callback(swap_source_dest_cb);
593    aws->create_autosize_button("SWAP", "Swap");
594
595    aws->at("select2");
596    aws->callback(makeWindowCallback(copy_tree_awar_cb, awar_displayed_tree, TreeAdmin::dest_tree_awar(root)));  aws->create_autosize_button("SELECT_DISPLAYED2", "Use shown");
597    aws->callback(makeWindowCallback(copy_tree_awar_cb, TreeAdmin::dest_tree_awar(root), awar_displayed_tree));  aws->create_autosize_button("DISPLAY_SELECTED2", "Display");
598}
599
600static AW_window_simple *create_select_other_tree_window(AW_root *root, const char *winId, const char *winTitle, const char *helpFile, AW_awar *awar_displayed_tree) {
601    AW_window_simple *aws = new AW_window_simple;
602    aws->init(root, winId, winTitle);
603    aws->load_xfig("ad_one_tree.fig");
604
605    aws->at("close");
606    aws->auto_space(10, 3);
607
608    aws->callback(AW_POPDOWN);
609    aws->create_button("CLOSE", "Close", "C");
610
611    aws->at("help");
612    aws->callback(makeHelpCallback(helpFile));
613    aws->create_button("HELP", "Help", "H");
614
615    AW_awar *awar_other_tree = TreeAdmin::dest_tree_awar(root);
616
617    aws->at("tree");
618    awt_create_TREE_selection_list(GLOBAL.gb_main, aws, awar_other_tree->awar_name, true);
619
620    aws->at("select");
621    aws->callback(makeWindowCallback(copy_tree_awar_cb, awar_displayed_tree, awar_other_tree));     aws->create_autosize_button("SELECT_DISPLAYED", "Use");
622    aws->callback(makeWindowCallback(copy_tree_awar_cb, awar_other_tree,     awar_displayed_tree)); aws->create_autosize_button("DISPLAY_SELECTED", "Display");
623
624    aws->at("user");
625
626    return aws;
627}
628
629AW_window *NT_create_compareTopologies_window(AW_root *root) {
630    AW_window_simple *aws = new AW_window_simple;
631    aws->init(root, "CMP_TOPOLOGY", "Compare tree topologies");
632    aws->load_xfig("compare_topo.fig");
633
634    aws->at("close");
635    aws->callback(AW_POPDOWN);
636    aws->create_button("CLOSE", "Close", "C");
637
638    aws->at("help");
639    aws->callback(makeHelpCallback("compare_topo.hlp"));
640    aws->create_button("HELP", "Help", "H");
641
642    NT_create_twoTreeSelection(aws);
643
644    aws->at("user");
645    aws->callback(makeWindowCallback(ad_move_tree_info, false));
646    aws->create_autosize_button("CMP_TOPOLOGY", "Compare topologies");
647
648    return aws;
649}
650
651static AWT_config_mapping_def moveGroupInfo_mapping[] = {
652    { AWAR_GROUPXFER_INGROUP_ABS,    "ingroup_abs" },
653    { AWAR_GROUPXFER_INGROUP_REL,    "ingroup_rel" },
654    { AWAR_GROUPXFER_OUTGROUP_ABS,   "outgroup_abs" },
655    { AWAR_GROUPXFER_OUTGROUP_REL,   "outgroup_rel" },
656
657    { AWAR_GROUPXFER_UNKNOWN_ABS,    "unknown_abs" },
658    { AWAR_GROUPXFER_KEELING,        "keeling" },
659
660    { AWAR_GROUPXFER_INGROUP_LIM,    "ingroup_lim" },
661    { AWAR_GROUPXFER_OUTGROUP_LIM,   "outgroup_lim" },
662
663    { AWAR_GROUPXFER_SOURCE,         "sourceGroups" },
664    { AWAR_GROUPXFER_OVERWRITE_MODE, "overwriteGroups" },
665
666    { AWAR_GROUPXFER_ACI,            "aci" },
667
668    { NULp, NULp },
669};
670
671static AWT_predefined_config moveGroupInfo_predef[] = {
672    { "*only_perfect_groups", "Only copy perfectly matching groups with\n * 100% ingroup ratio and\n * 0% outgroup ratio", "ingroup_lim='100';outgroup_lim='0'" },
673
674    { "*maximize_ingroup_ratio", "Maximize ingroup ratio \n   over outgroup ratio.\n(Note: diff of factor 10 is maybe too strong)", "ingroup_abs='0';ingroup_rel='100';outgroup_abs='0';outgroup_rel='10'" },
675    { "*minimize_outgroup_ratio", "Minimize outgroup ratio \n     over ingroup ratio.\n(Note: diff of factor 10 is maybe too strong)", "ingroup_abs='0';ingroup_rel='10';outgroup_abs='0';outgroup_rel='100'" },
676
677    { "*report2name", "custom target group name:\n * add prefix \"XFRD_\" (allows to distinguish newly transferred from existing groups)\n * add suffix reporting penalty", "aci='\"XFRD_\";groupname;\" {penalty = \";penalty;\"}\"'" },
678
679    { NULp, NULp, NULp },
680};
681
682
683
684AW_window *NT_create_moveGroupInfo_window(AW_root *root) {
685    AW_window_simple *aws = new AW_window_simple;
686    aws->init(root, "COPY_NODE_INFO_OF_TREE", "Move groups");
687    aws->load_xfig("move_groups.fig");
688
689    aws->button_length(11);
690
691    aws->at("close");
692    aws->callback(AW_POPDOWN);
693    aws->create_button("CLOSE", "Close", "C");
694
695    aws->at("help");
696    aws->callback(makeHelpCallback("move_groups.hlp"));
697    aws->create_button("HELP", "Help", "H");
698
699    const int FLOAT_COLUMNS   = 10;
700    const int PERCENT_COLUMNS = 5;
701
702    aws->at("ipep"); aws->create_input_field(AWAR_GROUPXFER_INGROUP_ABS, FLOAT_COLUMNS);
703    aws->at("irp");  aws->create_input_field(AWAR_GROUPXFER_INGROUP_REL, FLOAT_COLUMNS);
704    aws->at("ilim"); aws->create_input_field(AWAR_GROUPXFER_INGROUP_LIM, PERCENT_COLUMNS);
705
706    aws->at("opep"); aws->create_input_field(AWAR_GROUPXFER_OUTGROUP_ABS, FLOAT_COLUMNS);
707    aws->at("orp");  aws->create_input_field(AWAR_GROUPXFER_OUTGROUP_REL, FLOAT_COLUMNS);
708    aws->at("olim"); aws->create_input_field(AWAR_GROUPXFER_OUTGROUP_LIM, PERCENT_COLUMNS);
709
710    aws->at("upep"); aws->create_input_field(AWAR_GROUPXFER_UNKNOWN_ABS, FLOAT_COLUMNS);
711    aws->at("keel"); aws->create_input_field(AWAR_GROUPXFER_KEELING,     FLOAT_COLUMNS);
712
713    aws->at("srcGrps");
714    aws->create_option_menu(AWAR_GROUPXFER_SOURCE, true);
715    aws->insert_option("all groups",         "a", XFER_ALL_GROUPS);
716    aws->insert_option("groups with marked", "m", XFER_GROUPS_WITH_MARKED);
717    aws->update_option_menu();
718
719    aws->at("tgtGrps");
720    aws->create_option_menu(AWAR_GROUPXFER_OVERWRITE_MODE, true);
721    aws->insert_option("remove existing groups",          "r", REMOVE_EXISTING_GROUPS);
722    aws->insert_option("keep \"newname [was: oldname]\"", "k", KEEP_OLD_NAMES);
723    aws->update_option_menu();
724
725    aws->at("aci");
726    aws->create_input_field(AWAR_GROUPXFER_ACI);
727
728    NT_create_twoTreeSelection(aws);
729
730    aws->at("go");
731    aws->callback(makeWindowCallback(ad_move_tree_info, true));
732    aws->create_button("GO", "GO", "G");
733
734    aws->at("cfg");
735    AWT_insert_config_manager(aws, AW_ROOT_DEFAULT, "moveGroupInfo", moveGroupInfo_mapping, NULp, moveGroupInfo_predef);
736
737    return aws;
738}
739
740static void reorder_trees_cb(AW_window *aww, awt_reorder_mode dest) {
741    // moves the tree in the list of trees
742
743    char     *tree_name = aww->get_root()->awar(AWAR_TREE_NAME)->read_string();
744    GB_ERROR  error     = NULp;
745
746    GB_transaction ta(GLOBAL.gb_main);
747    GBDATA *gb_treedata   = GBT_get_tree_data(GLOBAL.gb_main);
748    GBDATA *gb_moved_tree = GB_entry(gb_treedata, tree_name);
749
750    if (!gb_moved_tree) {
751        error = "No tree selected";
752    }
753    else {
754        GBT_ORDER_MODE  move_mode;
755        GBDATA         *gb_target_tree = NULp;
756
757        switch (dest) {
758            case ARM_UP:
759                move_mode      = GBT_INFRONTOF;
760                gb_target_tree = GBT_tree_infrontof(gb_moved_tree);
761                if (gb_target_tree) break;
762                FALLTHROUGH; // move top-tree up = move to bottom
763            case ARM_BOTTOM:
764                move_mode      = GBT_BEHIND;
765                gb_target_tree = GBT_find_bottom_tree(GLOBAL.gb_main);
766                break;
767
768            case ARM_DOWN:
769                move_mode      = GBT_BEHIND;
770                gb_target_tree = GBT_tree_behind(gb_moved_tree);
771                if (gb_target_tree) break;
772                FALLTHROUGH; // move bottom-tree down = move to top
773            case ARM_TOP:
774                move_mode      = GBT_INFRONTOF;
775                gb_target_tree = GBT_find_top_tree(GLOBAL.gb_main);
776                break;
777        }
778
779        if (gb_target_tree && gb_target_tree != gb_moved_tree) {
780            error = GBT_move_tree(gb_moved_tree, move_mode, gb_target_tree);
781        }
782    }
783
784    if (error) aw_message(error);
785    free(tree_name);
786}
787
788void popup_tree_admin_window(AW_window *awp) {
789    static AW_window_simple *aws = NULp;
790
791    if (!aws) {
792        AW_root *aw_root = awp->get_root();
793
794        aws = new AW_window_simple;
795        aws->init(aw_root, "TREE_ADMIN", "TREE ADMIN");
796        aws->load_xfig("ad_tree.fig");
797
798        aws->callback(AW_POPDOWN);
799        aws->at("close");
800        aws->create_button("CLOSE", "CLOSE", "C");
801
802        aws->callback(makeHelpCallback("treeadm.hlp"));
803        aws->at("help");
804        aws->create_button("HELP", "HELP", "H");
805
806        aws->button_length(40);
807
808        aws->at("sel");
809        aws->create_button(NULp, AWAR_TREE_NAME, NULp, "+");
810
811        aws->at("security");
812        aws->create_option_menu(AWAR_TREE_SECURITY, true);
813        aws->insert_option("0", "0", 0);
814        aws->insert_option("1", "1", 1);
815        aws->insert_option("2", "2", 2);
816        aws->insert_option("3", "3", 3);
817        aws->insert_option("4", "4", 4);
818        aws->insert_option("5", "5", 5);
819        aws->insert_default_option("6", "6", 6);
820        aws->update_option_menu();
821
822        aws->at("rem");
823        aws->create_text_field(AWAR_TREE_REM);
824
825
826        aws->button_length(20);
827
828        static TreeAdmin::Spec spec(GLOBAL.gb_main, AWAR_TREE_NAME);
829
830        aws->at("delete");
831        aws->help_text("treeadm.hlp");
832        aws->callback(makeWindowCallback(TreeAdmin::delete_tree_cb, &spec));
833        aws->create_button("DELETE", "Delete", "D");
834
835        aws->at("rename");
836        aws->help_text("treeadm.hlp");
837        aws->callback(makeCreateWindowCallback(TreeAdmin::create_rename_window, &spec));
838        aws->create_button("RENAME", "Rename", "R");
839
840        aws->at("copy");
841        aws->help_text("treeadm.hlp");
842        aws->callback(makeCreateWindowCallback(TreeAdmin::create_copy_window, &spec));
843        aws->create_button("COPY", "Copy", "C");
844
845        aws->at("export");
846        aws->help_text("tr_export.hlp");
847        aws->callback(create_tree_export_window);
848        aws->create_button("EXPORT", "Export", "E");
849
850        aws->at("import");
851        aws->help_text("tr_import.hlp");
852        aws->callback(create_tree_import_window);
853        aws->create_button("IMPORT", "Import", "I");
854
855        aws->button_length(0);
856
857        aws->at("list");
858        awt_create_TREE_selection_list(GLOBAL.gb_main, aws, AWAR_TREE_NAME, true);
859
860        aws->at("sort");
861        awt_create_order_buttons(aws, reorder_trees_cb);
862    }
863
864    aws->activate();
865}
866
867// -----------------------
868//      consense tree
869
870
871static void create_consense_tree_cb(AW_window *aww, AW_selection *selected_trees) {
872    AW_root  *aw_root = aww->get_root();
873    GB_ERROR  error   = NULp;
874
875    const char *cons_tree_name = aw_root->awar(AWAR_TREE_CONSENSE_TREE)->read_char_pntr();
876    if (!cons_tree_name || !cons_tree_name[0]) {
877        error = "No name specified for the consensus tree";
878    }
879    else {
880        StrArray tree_names;
881        selected_trees->get_values(tree_names);
882
883        if (tree_names.size()<2) {
884            error = "Not enough trees selected (at least 2 needed)";
885        }
886        else {
887            GBDATA *gb_main = GLOBAL.gb_main;
888            GB_transaction ta(gb_main);
889
890            {
891                arb_progress progress("Building consensus tree", 2L); // 2 steps: deconstruct, reconstruct
892                ConsensusTreeBuilder tree_builder;
893
894                progress.subtitle("loading input trees");
895                for (size_t t = 0; t<tree_names.size() && !error; ++t) {
896                    TreeRoot      *root = new SizeAwareRoot; // will be deleted when tree gets deleted
897                    SizeAwareTree *tree = DOWNCAST(SizeAwareTree*, GBT_read_tree(gb_main, tree_names[t], root));
898                    if (!tree) {
899                        error = GB_await_error();
900                    }
901                    else {
902                        tree_builder.add(tree, tree_names[t], 1.0);
903                    }
904                }
905
906                if (!error) {
907                    size_t    species_count;
908                    TreeNode *cons_tree = tree_builder.get(species_count, error); // triggers 2 implicit progress increments
909
910                    if (!error && progress.aborted()) {
911                        error = "user abort";
912                    }
913
914                    nt_assert(contradicted(cons_tree, error));
915                    if (cons_tree) {
916                        char *comment = tree_builder.get_tree_remark();
917                        error         = GBT_write_tree_with_remark(gb_main, cons_tree_name, cons_tree, comment);
918                        free(comment);
919                        UNCOVERED();
920                        destroy(cons_tree);
921                    }
922                }
923                if (error) progress.done();
924            }
925            error = ta.close(error);
926        }
927    }
928
929    if (!error) {
930        aw_root->awar(AWAR_TREE_NAME)->write_string(cons_tree_name); // show in main window
931    }
932
933    aw_message_if(error);
934}
935
936static void use_selected_as_target_cb(AW_window *aww) {
937    AW_root *aw_root = aww->get_root();
938    aw_root->awar(AWAR_TREE_CONSENSE_TREE)->write_string(aw_root->awar(AWAR_TREE_CONSENSE_SELECTED)->read_char_pntr());
939}
940
941AW_window *NT_create_consense_window(AW_root *aw_root) {
942    static AW_window_simple *aws = NULp;
943    if (!aws) {
944        aws = new AW_window_simple;
945        aws->init(aw_root, "CONSENSE_TREE", "Consensus Tree");
946        aws->load_xfig("ad_cons_tree.fig");
947
948        aws->auto_space(10, 10);
949
950        aws->callback(AW_POPDOWN);
951        aws->at("close");
952        aws->create_button("CLOSE", "CLOSE", "C");
953
954        aws->callback(makeHelpCallback("consense_tree.hlp"));
955        aws->at("help");
956        aws->create_button("HELP", "HELP", "H");
957
958        aws->at("list");
959        AW_DB_selection *all_trees      = awt_create_TREE_selection_list(GLOBAL.gb_main, aws, AWAR_TREE_CONSENSE_SELECTED, true);
960        AW_selection    *selected_trees = awt_create_subset_selection_list(aws, all_trees->get_sellist(), "selected", "add", "sort");
961
962        aws->at("name");
963        aws->create_input_field(AWAR_TREE_CONSENSE_TREE);
964
965        aws->callback(use_selected_as_target_cb);
966        aws->create_button("USE_AS_TARGET", "#moveLeft.xpm");
967
968        aws->at("build");
969        aws->callback(makeWindowCallback(create_consense_tree_cb, selected_trees));
970        aws->create_autosize_button("BUILD", "Build consensus tree", "B");
971    }
972    return aws;
973}
974
975class CombinedPosInfo {
976    // combines relative positions of a subtree in 2 trees (source- and target-tree).
977    // provides compare operations for SortByTopo
978
979    TreeRelativePosition source; // in source tree ("ordering tree")
980    TreeRelativePosition target; // in target tree ("modified tree")
981
982public:
983
984    CombinedPosInfo(const TreeRelativePosition& s, const TreeRelativePosition& t)
985        : source(s),
986          target(t)
987    {
988        nt_assert(target.is_known());
989    }
990    CombinedPosInfo(const CombinedPosInfo& c1, const CombinedPosInfo& c2)
991        : source(c1.source, c2.source),
992          target(c1.target, c2.target)
993    {}
994
995    int compare(const CombinedPosInfo &right) const {
996        // result similar to strcmp(this, right)
997        if (!source.is_known() || !right.source.is_known()) {
998            // one subtree is completely unknown in source-tree
999            // => keep target-tree order
1000            return target.compare(right.target);
1001        }
1002        return source.compare(right.source);
1003    }
1004};
1005
1006class SortByTopo : virtual Noncopyable {
1007    TreePositionLookup        source_pos; // in ordering topology
1008    const TreePositionLookup *target_pos; // in target topology (used where source_pos does not provide order)
1009
1010    CombinedPosInfo reorder_subtree_rec(TreeNode *node) { // similar to ../ARBDB/TreeNode.cxx@reorder_subtree
1011        static const char *smallest_leafname; // has to be set to the alphabetically smallest name (when function exits)
1012
1013        if (node->is_leaf()) {
1014            smallest_leafname = node->name;
1015            return CombinedPosInfo(source_pos.relative(node->name),
1016                                   target_pos->relative(node->name));
1017        }
1018
1019        CombinedPosInfo  leftInfo       = reorder_subtree_rec(node->get_leftson());
1020        const char      *smallest_left  = smallest_leafname;
1021        CombinedPosInfo  rightInfo      = reorder_subtree_rec(node->get_rightson());
1022        const char      *smallest_right = smallest_leafname;
1023
1024        bool left_leafname_bigger = strcmp(smallest_left, smallest_right)>0;
1025        smallest_leafname         = left_leafname_bigger ? smallest_right : smallest_left;
1026
1027        {
1028            int cmp = leftInfo.compare(rightInfo);
1029            if (cmp>0 || (cmp == 0 && left_leafname_bigger)) {
1030                node->swap_sons();
1031            }
1032        }
1033
1034        return CombinedPosInfo(leftInfo, rightInfo);
1035    }
1036public:
1037
1038    SortByTopo(const TreeNode *by)
1039        : source_pos(by),
1040          target_pos(NULp)
1041    {}
1042
1043#if defined(UNIT_TESTS)
1044    TreeRelativePosition sourcePos(const char *name) { return source_pos.relative(name); }
1045#endif
1046
1047    void reorder_subtree(TreeNode *tree) {
1048        TreePositionLookup tpos(tree);
1049        LocallyModify<const TreePositionLookup*> provide(target_pos, &tpos);
1050        reorder_subtree_rec(tree);
1051    }
1052};
1053
1054static GB_ERROR sort_tree_by_other_tree(GBDATA *gb_main, TreeNode *tree, const char *other_tree) {
1055    GB_ERROR       error = NULp;
1056    GB_transaction ta(gb_main);
1057
1058    TreeNode *otherTree   = GBT_read_tree(gb_main, other_tree, new SimpleRoot);
1059    if (!otherTree) error = GB_await_error();
1060    else {
1061        SortByTopo sorter(otherTree);
1062        destroy(otherTree);
1063        sorter.reorder_subtree(tree);
1064    }
1065    return error;
1066}
1067
1068static bool sort_dtree_by_other_tree_cb(TreeNode *tree, GB_ERROR& error) {
1069    const char *other_tree = TreeAdmin::dest_tree_awar(AW_root::SINGLETON)->read_char_pntr();
1070    error = sort_tree_by_other_tree(GLOBAL.gb_main, tree, other_tree);
1071    return !error;
1072}
1073
1074static void sort_tree_by_other_tree_cb(UNFIXED, TREE_canvas *ntw) {
1075    GB_ERROR error = NT_with_displayed_tree_do(ntw, sort_dtree_by_other_tree_cb);
1076    aw_message_if(error);
1077}
1078
1079AW_window *NT_create_sort_tree_by_other_tree_window(AW_root *aw_root, TREE_canvas *ntw) {
1080    AW_window_simple *aws = create_select_other_tree_window(aw_root, ntw->aww->local_id("SORT_BY_OTHER"), "Sort tree by other tree", "resortbyother.hlp", ntw->get_awar_tree());
1081
1082    aws->callback(makeWindowCallback(sort_tree_by_other_tree_cb, ntw));
1083    aws->create_autosize_button("RESORT", "Sort according to source tree");
1084
1085    return aws;
1086}
1087
1088// ---------------------------
1089//      multifurcate tree
1090
1091#define AWAR_MFURC                    "tree/multifurc/"
1092#define AWAR_MFURC_CONSIDER_BOOTSTRAP AWAR_MFURC "use_bs"
1093#define AWAR_MFURC_CONSIDER_LENGTH    AWAR_MFURC "use_len"
1094#define AWAR_MFURC_CONSIDER_TERMINALS AWAR_MFURC "terminals"
1095#define AWAR_MFURC_LENGTH_LIMIT       AWAR_MFURC "len"
1096#define AWAR_MFURC_BOOTSTRAP_LIMIT    AWAR_MFURC "bs"
1097
1098void NT_create_multifurcate_tree_awars(AW_root *aw_root, AW_default props) {
1099    aw_root->awar_int  (AWAR_MFURC_CONSIDER_BOOTSTRAP, 0,   props);
1100    aw_root->awar_int  (AWAR_MFURC_CONSIDER_LENGTH,    1,   props);
1101    aw_root->awar_int  (AWAR_MFURC_CONSIDER_TERMINALS, 0,   props);
1102    aw_root->awar_float(AWAR_MFURC_LENGTH_LIMIT,       0.1, props);
1103    aw_root->awar_float(AWAR_MFURC_BOOTSTRAP_LIMIT,    50,  props);
1104}
1105static void multifurcation_cb(UNFIXED, TREE_canvas *ntw) {
1106    AW_root *aw_root = ntw->aww->get_root();
1107
1108    float below_bootstrap = 101.0;
1109    float below_length    = 1000000.0;
1110    bool  applyAtLeafs    = aw_root->awar(AWAR_MFURC_CONSIDER_TERMINALS)->read_int();
1111
1112    if (aw_root->awar(AWAR_MFURC_CONSIDER_BOOTSTRAP)->read_int()) below_bootstrap = aw_root->awar(AWAR_MFURC_BOOTSTRAP_LIMIT)->read_float();
1113    if (aw_root->awar(AWAR_MFURC_CONSIDER_LENGTH)   ->read_int()) below_length    = aw_root->awar(AWAR_MFURC_LENGTH_LIMIT)   ->read_float();
1114
1115    NT_multifurcate_tree(ntw, TreeNode::multifurc_limits(below_bootstrap, below_length, applyAtLeafs));
1116}
1117AW_window *NT_create_multifurcate_tree_window(AW_root *aw_root, TREE_canvas *ntw) {
1118    AW_window_simple *aws = new AW_window_simple;
1119
1120    aws->init(aw_root, ntw->aww->local_id("multifurcate"), "Multifurcate tree");
1121    aws->at(10, 10);
1122    aws->auto_space(10, 10);
1123
1124    aws->callback(AW_POPDOWN);
1125    aws->create_button("CLOSE", "CLOSE", "C");
1126
1127    aws->callback(makeHelpCallback("multifurcate.hlp"));
1128    aws->create_button("HELP", "HELP", "H");
1129
1130    const int LABEL_LENGTH = 46;
1131    aws->label_length(LABEL_LENGTH);
1132
1133    aws->at_newline();
1134    aws->label("Multifurcate branches with branchlength below");
1135    aws->create_toggle(AWAR_MFURC_CONSIDER_LENGTH);
1136    aws->create_input_field(AWAR_MFURC_LENGTH_LIMIT, 10);
1137
1138    aws->at_newline();
1139    aws->label("                          AND bootstrap below");
1140    aws->create_toggle(AWAR_MFURC_CONSIDER_BOOTSTRAP);
1141    aws->create_input_field(AWAR_MFURC_BOOTSTRAP_LIMIT, 10);
1142
1143    aws->label_length(0);
1144    aws->at_newline();
1145    aws->label("Also apply to terminal branches");
1146    aws->create_toggle(AWAR_MFURC_CONSIDER_TERMINALS);
1147
1148    aws->at_newline();
1149    aws->callback(makeWindowCallback(multifurcation_cb, ntw));
1150    aws->create_autosize_button("MULTIFURCATE", "Multifurcate", "M");
1151
1152    return aws;
1153}
1154
1155// --------------------------------------------------------------------------------
1156
1157#ifdef UNIT_TESTS
1158#ifndef TEST_UNIT_H
1159#include <test_unit.h>
1160#endif
1161
1162static const char *getTreeComment(GBDATA *gb_main, const char *treeName) {
1163    GB_transaction ta(gb_main);
1164    return GBT_tree_info_string(gb_main, treeName, -1);
1165}
1166
1167#define TEST_EXPECT_TREE_COMMENT_CONTAINS(treeName,expected)               TEST_EXPECT_CONTAINS(getTreeComment(gb_main,treeName),expected)
1168#define TEST_EXPECT_TREE_COMMENT_DOESNT_CONTAIN(treeName,expected)         TEST_EXPECT_DOESNT_CONTAIN(getTreeComment(gb_main,treeName),expected)
1169#define TEST_EXPECT_TREE_COMMENT_DOESNT_CONTAIN__BROKEN(treeName,expected) TEST_EXPECT_DOESNT_CONTAIN__BROKEN(getTreeComment(gb_main,treeName),expected)
1170
1171static GB_ERROR sort_namedtree_by_other_tree(GBDATA *gb_main, const char *tree, const char *other_tree) {
1172    GB_ERROR        error = NULp;
1173    GB_transaction  ta(gb_main);
1174    SizeAwareTree  *Tree  = DOWNCAST(SizeAwareTree*, GBT_read_tree(gb_main, tree, new SizeAwareRoot));
1175    if (!Tree) error      = GB_await_error();
1176    else {
1177        Tree->compute_tree();
1178        error             = sort_tree_by_other_tree(gb_main, Tree, other_tree);
1179        if (!error) error = GBT_write_tree(gb_main, tree, Tree);
1180    }
1181    destroy(Tree);
1182    return error;
1183}
1184
1185void TEST_sort_tree_by_other_tree() {
1186    GB_shell  shell;
1187    GBDATA   *gb_main = GB_open("TEST_trees.arb", "rw");
1188    TEST_REJECT_NULL(gb_main);
1189
1190    const char *topo_test   = "(((((((CloTyro3:1.046,CloTyro4:0.061):0.026,CloTyro2:0.017):0.017,CloTyrob:0.009):0.274,CloInnoc:0.371):0.057,CloBifer:0.388):0.124,(((CloButy2:0.009,CloButyr:0.000):0.564,CloCarni:0.120):0.010,CloPaste:0.179):0.131):0.081,((((CorAquat:0.084,CurCitre:0.058):0.103,CorGluta:0.522):0.053,CelBiazo:0.059):0.207,CytAquat:0.711):0.081);";
1191    const char *topo_center = "(((CloPaste:0.179,((CloButy2:0.009,CloButyr:0.000):0.564,CloCarni:0.120):0.010):0.131,((CloInnoc:0.371,((CloTyro2:0.017,(CloTyro3:1.046,CloTyro4:0.061):0.026):0.017,CloTyrob:0.009):0.274):0.057,CloBifer:0.388):0.124):0.081,((CelBiazo:0.059,((CorAquat:0.084,CurCitre:0.058):0.103,CorGluta:0.522):0.053):0.207,CytAquat:0.711):0.081);";
1192    const char *topo_bottom = "((CytAquat:0.711,(CelBiazo:0.059,(CorGluta:0.522,(CorAquat:0.084,CurCitre:0.058):0.103):0.053):0.207):0.081,((CloPaste:0.179,(CloCarni:0.120,(CloButy2:0.009,CloButyr:0.000):0.564):0.010):0.131,(CloBifer:0.388,(CloInnoc:0.371,(CloTyrob:0.009,(CloTyro2:0.017,(CloTyro3:1.046,CloTyro4:0.061):0.026):0.017):0.274):0.057):0.124):0.081);";
1193
1194    const char *topo_vs_nj_bs = "(((((((CloTyro3:1.046,CloTyro4:0.061):0.026,CloTyro2:0.017):0.017,CloTyrob:0.009):0.274,CloInnoc:0.371):0.057,CloBifer:0.388):0.124,(((CloButyr:0.000,CloButy2:0.009):0.564,CloCarni:0.120):0.010,CloPaste:0.179):0.131):0.081,(((CorGluta:0.522,(CorAquat:0.084,CurCitre:0.058):0.103):0.053,CelBiazo:0.059):0.207,CytAquat:0.711):0.081);";
1195
1196    TEST_EXPECT_DIFFERENT(topo_test,   topo_center);
1197    TEST_EXPECT_DIFFERENT(topo_test,   topo_bottom);
1198    TEST_EXPECT_DIFFERENT(topo_center, topo_bottom);
1199
1200    // create sorted copies of tree_test
1201    {
1202        GB_transaction  ta(gb_main);
1203        SizeAwareTree  *tree = DOWNCAST(SizeAwareTree*, GBT_read_tree(gb_main, "tree_test", new SizeAwareRoot));
1204        TEST_REJECT_NULL(tree);
1205        TEST_EXPECT_NEWICK(nLENGTH, tree, topo_test);
1206
1207        tree->reorder_tree(BIG_BRANCHES_TO_CENTER); TEST_EXPECT_NO_ERROR(GBT_write_tree(gb_main, "tree_sorted_center", tree)); TEST_EXPECT_NEWICK(nLENGTH, tree, topo_center);
1208        tree->reorder_tree(BIG_BRANCHES_TO_BOTTOM); TEST_EXPECT_NO_ERROR(GBT_write_tree(gb_main, "tree_sorted_bottom", tree)); TEST_EXPECT_NEWICK(nLENGTH, tree, topo_bottom);
1209
1210        // test SortByTopo
1211        {
1212            SortByTopo   sbt(tree);
1213            const double EPSILON = 0.0001;
1214
1215            TEST_EXPECT_SIMILAR(sbt.sourcePos("CytAquat").value(), 0.0, EPSILON); // leftmost species (in topo_bottom)
1216            TEST_EXPECT_SIMILAR(sbt.sourcePos("CloTyro4").value(), 1.0, EPSILON); // rightmost species
1217
1218            TEST_EXPECT_SIMILAR(sbt.sourcePos("CurCitre").value(), 0.2857, EPSILON); // (5 of 15)
1219            TEST_EXPECT_SIMILAR(sbt.sourcePos("CloButy2").value(), 0.5,    EPSILON); // center species (8 of 15)
1220            TEST_EXPECT_SIMILAR(sbt.sourcePos("CloTyrob").value(), 0.7857, EPSILON); // (12 of 15)
1221
1222            TEST_REJECT(sbt.sourcePos("Un-Known").is_known()); // unknown species
1223        }
1224
1225        tree->reorder_tree(BIG_BRANCHES_TO_EDGE); TEST_EXPECT_NO_ERROR(GBT_write_tree(gb_main, "tree_work", tree));
1226
1227        destroy(tree);
1228    }
1229
1230
1231    TEST_EXPECT_NO_ERROR(sort_namedtree_by_other_tree(gb_main, "tree_work", "tree_sorted_center")); TEST_EXPECT_SAVED_NEWICK(nLENGTH, gb_main, "tree_work", topo_center);
1232    TEST_EXPECT_NO_ERROR(sort_namedtree_by_other_tree(gb_main, "tree_work", "tree_sorted_bottom")); TEST_EXPECT_SAVED_NEWICK(nLENGTH, gb_main, "tree_work", topo_bottom);
1233    TEST_EXPECT_NO_ERROR(sort_namedtree_by_other_tree(gb_main, "tree_work", "tree_test"));          TEST_EXPECT_SAVED_NEWICK(nLENGTH, gb_main, "tree_work", topo_test);
1234    TEST_EXPECT_NO_ERROR(sort_namedtree_by_other_tree(gb_main, "tree_work", "tree_nj_bs"));         TEST_EXPECT_SAVED_NEWICK(nLENGTH, gb_main, "tree_work", topo_vs_nj_bs);
1235
1236    // TEST_EXPECT_NO_ERROR(GB_save_as(gb_main, "TEST_trees_save.arb", "b")); // test-save db to examine saved trees (do not commit!)
1237
1238    // ----------------------------------------------------------------------------------------------------
1239    // test high-level function TREE_load_to_db (see #701; placed here by laziness, not related to sorting trees)
1240    TEST_EXPECT_NO_ERROR(TREE_load_to_db(gb_main, "trees/test.tree", "tree_loaded", LabelTranslator())); // ../UNIT_TESTER/run/trees/test.tree // @@@ use NOOP LabelTranslator
1241    TEST_EXPECT_ERROR_CLEAR();
1242    TEST_EXPECT_SAVED_NEWICK(nALL, gb_main, "tree_loaded", "(((s1:0.200,s2:0.400):0.600,(s3:0.300,s 4:0.100):0.100):0.000,(s5:0.020,s-6:0.040):0.060);");
1243    TEST_EXPECT_TREE_COMMENT_CONTAINS("tree_loaded", "covering most of tree reader code"); // test comment
1244
1245    GB_close(gb_main);
1246}
1247
1248void TEST_move_node_info() {
1249    GB_shell  shell;
1250    GBDATA   *gb_main = GB_open("TEST_trees.arb", "r");
1251
1252    const char *treeTarget1 = "tree_removal";
1253    const char *treeTarget2 = "tree_test";
1254    const char *treeSortby1 = "tree_removal_copy";
1255    const char *treeSortby2 = "tree_test_copy";
1256
1257    const char *treeSource1 = treeSortby2;   // contains 1 group ("test")
1258    const char *treeSource2 = "tree_tree2";  // contains 2 groups ("g2" + "outer")
1259    const char *treeSource3 = "tree_groups"; // contains 5 groups
1260
1261#define GROUP_TEST         "(CloTyrob,(CloTyro2,(CloTyro3,CloTyro4)))"
1262#define GROUP_TEST_FLIPPED "(((CloTyro3,CloTyro4),CloTyro2),CloTyrob)"
1263
1264#define NAMED_GROUP_TEST       GROUP_TEST "'test'"
1265#define OVERWRITTEN_GROUP_TEST GROUP_TEST "'g2 [was: test]'"
1266
1267    const char *org_topo1 = "((CloInnoc," GROUP_TEST "),(CloBifer,((CloCarni,CurCitre),((CloPaste,(Zombie1,(CloButy2,CloButyr))),(CytAquat,(CelBiazo,(CorGluta,(CorAquat,Zombie2))))))));";
1268    const char *org_topo2 = "((((" GROUP_TEST_FLIPPED ",CloInnoc),CloBifer),(((CloButy2,CloButyr),CloCarni),CloPaste)),((((CorAquat,CurCitre),CorGluta),CelBiazo),CytAquat));";
1269
1270    // (index convention := source target)
1271    const char *unwanted_topo11 = "((CytAquat,(CelBiazo,(CorGluta,(CorAquat,Zombie2)))),((CloPaste,(Zombie1,(CloButy2,CloButyr))),((CloCarni,CurCitre),(CloBifer,(CloInnoc," NAMED_GROUP_TEST ")))));";
1272    const char *unwanted_topo21 = "((CloButy2,CloButyr),(Zombie1,(CloPaste,((((CloInnoc," OVERWRITTEN_GROUP_TEST "),CloBifer),(CloCarni,CurCitre)),(CytAquat,(CelBiazo,(CorGluta,(CorAquat,Zombie2)))))))'outer');";
1273
1274    const char *sorted_topo11 = "(((((CloInnoc," NAMED_GROUP_TEST "),CloBifer),(CloCarni,CurCitre)),(CloPaste,(Zombie1,(CloButy2,CloButyr)))),(CytAquat,(CelBiazo,(CorGluta,(CorAquat,Zombie2)))));";
1275    const char *sorted_topo21 = "(((((((CloInnoc," OVERWRITTEN_GROUP_TEST "),CloBifer),(CloCarni,CurCitre)),(CytAquat,(CelBiazo,(CorGluta,(CorAquat,Zombie2))))),CloPaste),Zombie1)'outer',(CloButy2,CloButyr));";
1276    const char *topo32        = "((CloButy2,CloButyr)'upper',(((((" GROUP_TEST_FLIPPED "'low2',CloInnoc),CloBifer),((((CorAquat,CurCitre),CorGluta),CelBiazo),CytAquat)'low1'),CloPaste),CloCarni));";
1277    const char *topo32_rc     = "((CloButy2,CloButyr)'upper',(((((" GROUP_TEST_FLIPPED "'low2',CloInnoc),CloBifer),((((CorAquat,CurCitre),CorGluta),CelBiazo),CytAquat)'low1'),CloPaste),CloCarni)'lower');"; // @@@ should be same as topo32 (see #451)
1278    const char *topo32_rel    = "((CloButy2,CloButyr)"     ",(((((" GROUP_TEST_FLIPPED "'low2 [p=0.250000;ir=100.0%;3->4]',CloInnoc),CloBifer)'low1 [p=0.232222;ir=100.0%;7->6]',((((CorAquat,CurCitre),CorGluta),CelBiazo),CytAquat)'upper [p=0.510000;ir=100.0%;5->5]'),CloPaste),CloCarni)'lower [p=0.230769;ir=100.0%;10->13]');"; // group 'upper' and 'low1' moved to different locations by relative scoring
1279    const char *topo32_li     = "((CloButy2,CloButyr)"     ",(((((" GROUP_TEST_FLIPPED "'low2',CloInnoc),CloBifer),((((CorAquat,CurCitre),CorGluta),CelBiazo),CytAquat)'low1'),CloPaste),CloCarni)'lower');"; // group 'upper' filtered by limits
1280
1281    const char *compared_topo = "(((((((CloInnoc,(CloTyrob,(CloTyro2,(CloTyro3,CloTyro4)))),CloBifer),(CloCarni,CurCitre)'# 2')'# 2',(CytAquat,(CelBiazo,(CorGluta,(CorAquat,Zombie2)'# 1')'# 1')'# 1')'# 1')'# 1',CloPaste),Zombie1),(CloButy2,CloButyr));";
1282
1283    const char *LOG = "move_node_info.log";
1284
1285// #define TEST_AUTO_UPDATE // uncomment to auto-update expected log-files
1286#if defined(TEST_AUTO_UPDATE)
1287# define TEST_LOGS_EXPECTED(expected) TEST_COPY_FILE(LOG, expected)
1288#else
1289# define TEST_LOGS_EXPECTED(expected) TEST_EXPECT_TEXTFILES_EQUAL(expected, LOG)
1290#endif // TEST_AUTO_UPDATE
1291
1292    // create copies of 'tree_removal' + 'tree_test'
1293    {
1294        GB_transaction ta(gb_main);
1295
1296        // remove existing comments from trees (already contains some log-entries tested below)
1297        {
1298            const char  *resetComment = "<comment reset>";
1299            TEST_EXPECT_NO_ERROR(GBT_write_tree_remark(gb_main, treeTarget1, resetComment));
1300            TEST_EXPECT_NO_ERROR(GBT_write_tree_remark(gb_main, treeTarget2, resetComment));
1301        }
1302
1303        TEST_EXPECT_NO_ERROR(GBT_copy_tree(gb_main, treeTarget1, treeSortby1));
1304        TEST_EXPECT_NO_ERROR(GBT_copy_tree(gb_main, treeTarget2, treeSortby2));
1305
1306        TEST_EXPECT_SAVED_NEWICK(nSIMPLE, gb_main, treeTarget1, org_topo1);
1307        TEST_EXPECT_SAVED_NEWICK(nSIMPLE, gb_main, treeTarget2, org_topo2);
1308    }
1309
1310    GroupMatchScorer defaultScorer;
1311
1312    // move node info
1313    {
1314        const char *comment_added = "Copied node info from tree_test_copy";
1315        TEST_EXPECT_TREE_COMMENT_DOESNT_CONTAIN(treeTarget1, comment_added);
1316
1317        TEST_EXPECT_NO_ERROR(NTREE_move_tree_info(gb_main, treeSource1, treeTarget1, LOG, REMOVE_EXISTING_GROUPS, XFER_ALL_GROUPS, defaultScorer, NULp));
1318        TEST_LOGS_EXPECTED("group_xfer_11.log.expected");
1319
1320        TEST_EXPECT_SAVED_NEWICK__BROKEN(nSIMPLE, gb_main, treeTarget1, org_topo1); // @@@ moving node info modifies topology; caused by NT_tree_cmp.cxx@NAIVE_ROOTING
1321        TEST_EXPECT_SAVED_NEWICK(nGROUP, gb_main, treeTarget1, unwanted_topo11);
1322        TEST_EXPECT_TREE_COMMENT_CONTAINS(treeTarget1, comment_added);
1323
1324        // @@@ when we have a function to set the root according to another tree (#449),
1325        // use that function here. sorting tree after that, should again result in 'org_topo1'!
1326
1327        TEST_EXPECT_NO_ERROR(sort_namedtree_by_other_tree(gb_main, treeTarget1, treeSortby1));
1328        TEST_EXPECT_SAVED_NEWICK(nGROUP, gb_main, treeTarget1, sorted_topo11);
1329    }
1330    {
1331        const char *comment_added = "Copied node info from tree_groups";
1332        TEST_EXPECT_TREE_COMMENT_DOESNT_CONTAIN(treeTarget2, comment_added);
1333
1334        TEST_EXPECT_NO_ERROR(NTREE_move_tree_info(gb_main, treeSource3, treeTarget2, LOG, REMOVE_EXISTING_GROUPS, XFER_ALL_GROUPS, defaultScorer, NULp));
1335        TEST_LOGS_EXPECTED("group_xfer_32.log.expected");
1336
1337        TEST_EXPECT_SAVED_NEWICK__BROKEN(nSIMPLE, gb_main, treeTarget2, org_topo2); // @@@ moving node info modifies topology; caused by NT_tree_cmp.cxx@NAIVE_ROOTING
1338        TEST_EXPECT_TREE_COMMENT_CONTAINS(treeTarget2, comment_added);
1339        TEST_EXPECT_SAVED_NEWICK(nGROUP, gb_main, treeTarget2, topo32);
1340
1341        // perform same group-xfer after 1st xfer changed root => inserts 4 instead of 3 groups (obviously caused by changed root position; see #451)
1342        TEST_EXPECT_NO_ERROR(NTREE_move_tree_info(gb_main, treeSource3, treeTarget2, LOG, REMOVE_EXISTING_GROUPS, XFER_ALL_GROUPS, defaultScorer, NULp));
1343        TEST_LOGS_EXPECTED("group_xfer_32_rc.log.expected");
1344        TEST_EXPECT_SAVED_NEWICK(nGROUP, gb_main, treeTarget2, topo32_rc);
1345
1346        {
1347            GroupMatchScorer relativeScorer;
1348            relativeScorer.setPerErrorPenalties(0.0, 0.0, 0.0001); // remove absolute penalties for in-/outgroup
1349            relativeScorer.setRelativePenalties(1.0, 1.0);         // set relative penalties for in-/outgroup
1350
1351            TEST_EXPECT_NO_ERROR(NTREE_move_tree_info(gb_main, treeSource3, treeTarget2, LOG, REMOVE_EXISTING_GROUPS, XFER_ALL_GROUPS, relativeScorer,
1352                                                      "groupname;\" [p=\";penalty;\";ir=\";ingroup;\";\";oldsize;\"->\";newsize;\"]\""));
1353            TEST_LOGS_EXPECTED("group_xfer_32_rel.log.expected");
1354            TEST_EXPECT_SAVED_NEWICK(nGROUP, gb_main, treeTarget2, topo32_rel);
1355        }
1356
1357        // again perform same group-xfer using ingroup- and outgroup-limit
1358        {
1359            GroupMatchScorer limitedScorer;
1360            // limitedScorer.setLimits(RatioLimits(1.0, 1.0), RatioLimits(0.0, 0.0)); // filters all groups (upper, low2, low1 + lower)
1361            // limitedScorer.setLimits(RatioLimits(0.0, 1.0), RatioLimits(0.0, 1.0)); // filters no group (by definition)
1362            // limitedScorer.setLimits(RatioLimits(0.5, 1.0), RatioLimits(0.0, 1.0)); // group 'upper' placed at position with higher absolute penalty
1363            // limitedScorer.setLimits(RatioLimits(0.75, 1.0), RatioLimits(0.0, 1.0)); // weird (does keel groups)
1364            // limitedScorer.setLimits(RatioLimits(0.9, 1.0), RatioLimits(0.0, 1.0)); // removes group 'upper'
1365            // limitedScorer.setLimits(RatioLimits(0.0, 1.0), RatioLimits(0.0, 0.5)); // filters no group
1366            // limitedScorer.setLimits(RatioLimits(0.0, 1.0), RatioLimits(0.0, 0.1)); // filters groups 'twoleafs' + 'low2' (group 'lower' superseeded by 'low1')
1367            // limitedScorer.setLimits(RatioLimits(0.0, 1.0), RatioLimits(0.0, 0.3)); // filters group 'twoleafs'
1368            // limitedScorer.setLimits(RatioLimits(0.9, 1.0), RatioLimits(0.0, 0.1)); // filters all groups (weird)
1369            limitedScorer.setLimits(RatioLimits(0.7, 1.0), RatioLimits(0.0, 0.3)); // filters group 'upper' + group 'twoleafs'
1370            limitedScorer.setPerErrorPenalties(2.0, 2.0, 0.0002); // all values are 2*default -> result is same, scores are doubled!
1371
1372            TEST_EXPECT_NO_ERROR(NTREE_move_tree_info(gb_main, treeSource3, treeTarget2, LOG, REMOVE_EXISTING_GROUPS, XFER_ALL_GROUPS, limitedScorer, "")); // test empty ACI does same as passing NULp
1373            TEST_LOGS_EXPECTED("group_xfer_32_li.log.expected");
1374            TEST_EXPECT_SAVED_NEWICK(nGROUP, gb_main, treeTarget2, topo32_li);
1375        }
1376    }
1377
1378    // add node info
1379    {
1380        const char *comment_added = "Added node info from tree_tree2";
1381        TEST_EXPECT_TREE_COMMENT_DOESNT_CONTAIN(treeTarget1, comment_added);
1382
1383        TEST_EXPECT_NO_ERROR(NTREE_move_tree_info(gb_main, treeSource2, treeTarget1, LOG, KEEP_OLD_NAMES, XFER_ALL_GROUPS, defaultScorer, NULp));
1384        TEST_LOGS_EXPECTED("group_xfer_21.log.expected");
1385
1386        TEST_EXPECT_SAVED_NEWICK__BROKEN(nSIMPLE, gb_main, treeTarget1, org_topo1); // @@@ moving node info modifies topology; caused by NT_tree_cmp.cxx@NAIVE_ROOTING
1387        TEST_EXPECT_SAVED_NEWICK(nGROUP, gb_main, treeTarget1, unwanted_topo21);
1388        TEST_EXPECT_TREE_COMMENT_CONTAINS(treeTarget1, comment_added);
1389
1390        // @@@ when we have a function to set the root according to another tree (#449),
1391        // use that function here. sorting tree after that, should again result in 'org_topo1'!
1392
1393        TEST_EXPECT_NO_ERROR(sort_namedtree_by_other_tree(gb_main, treeTarget1, treeSortby1));
1394        TEST_EXPECT_SAVED_NEWICK(nGROUP, gb_main, treeTarget1, sorted_topo21);
1395    }
1396
1397    // compare node info
1398    {
1399        const char *comment_added = "Compared topology with tree_test";
1400        TEST_EXPECT_TREE_COMMENT_DOESNT_CONTAIN(treeTarget1, comment_added);
1401
1402        TEST_EXPECT_NO_ERROR(NTREE_move_tree_info(gb_main, treeSource1, treeTarget1, NULp, COMPARE_TOPOLOGY, XFER_ALL_GROUPS, defaultScorer, NULp));
1403        TEST_EXPECT_SAVED_NEWICK(nREMARK, gb_main, treeTarget1, compared_topo);
1404        TEST_EXPECT_TREE_COMMENT_CONTAINS(treeTarget1, comment_added);
1405    }
1406
1407    // test error cases:
1408    {
1409#define DOESNT_MATTER_ARGS gb_main,treeSource2,treeTarget1,LOG,REMOVE_EXISTING_GROUPS,XFER_ALL_GROUPS
1410
1411        GroupMatchScorer invalidScoring;
1412
1413        invalidScoring.setPerErrorPenalties(1.0, 0.0, 0.0001);
1414        TEST_EXPECT_ERROR_CONTAINS(NTREE_move_tree_info(DOESNT_MATTER_ARGS, invalidScoring, NULp), "one outgroup penalty has to be different from zero");
1415
1416        invalidScoring.setPerErrorPenalties(0.0, 1.0, 0.0001);
1417        TEST_EXPECT_ERROR_CONTAINS(NTREE_move_tree_info(DOESNT_MATTER_ARGS, invalidScoring, NULp), "one ingroup penalty has to be different from zero");
1418
1419        invalidScoring.setPerErrorPenalties(-1.0, 1.0, 0.0001);
1420        TEST_EXPECT_ERROR_CONTAINS(NTREE_move_tree_info(DOESNT_MATTER_ARGS, invalidScoring, NULp), "invalid negative in/outgroup penalty");
1421
1422        invalidScoring.setPerErrorPenalties(1.0, 1.0, 0.0001);
1423        invalidScoring.setRelativePenalties(100.0, -100.0);
1424        TEST_EXPECT_ERROR_CONTAINS(NTREE_move_tree_info(DOESNT_MATTER_ARGS, invalidScoring, NULp), "invalid negative in/outgroup penalty");
1425
1426#undef DOESNT_MATTER_ARGS
1427    }
1428
1429    GB_unlink(LOG);
1430    GB_close(gb_main);
1431}
1432
1433__ATTR__REDUCED_OPTIMIZE void TEST_edges() {
1434    GB_shell  shell;
1435    GBDATA   *gb_main = GB_open("TEST_trees.arb", "rw");
1436    TEST_REJECT_NULL(gb_main);
1437
1438    {
1439        GB_transaction  ta(gb_main);
1440        TreeNode       *tree = GBT_read_tree(gb_main, "tree_test", new SizeAwareRoot);
1441
1442        TreeNode *left  = tree->findLeafNamed("CloTyro3"); TEST_REJECT_NULL(left);
1443        TreeNode *node  = left->get_father();              TEST_REJECT_NULL(node);
1444        TreeNode *right = node->findLeafNamed("CloTyro4"); TEST_REJECT_NULL(right);
1445
1446        TEST_EXPECT(node == right->get_father());
1447        TEST_EXPECT(node->get_leftson()  == left);
1448        TEST_EXPECT(node->get_rightson() == right);
1449
1450        TreeNode *parent  = node->get_father();                TEST_REJECT_NULL(parent);
1451        TreeNode *brother = parent->findLeafNamed("CloTyro2"); TEST_REJECT_NULL(brother);
1452
1453        TEST_EXPECT(node->get_brother() == brother);
1454
1455        TreeNode *grandpa  = parent->get_father(); TEST_REJECT_NULL(grandpa);
1456
1457        // topology:
1458        //
1459        //            grandpa
1460        //              /
1461        //             /
1462        //            /
1463        //          parent
1464        //           /\              .
1465        //          /  \             .
1466        //         /    \            .
1467        //       node  brother
1468        //        /\                 .
1469        //       /  \                .
1470        //      /    \               .
1471        //    left right
1472
1473        // test next() and otherNext() for inner edge 'node->parent'
1474        {
1475            ARB_edge nodeUp = parentEdge(node);
1476
1477            TEST_EXPECT(node->is_leftson());                      // if child is left son..
1478            TEST_EXPECT(nodeUp.next().dest()         == grandpa); // .. next() continues rootwards
1479            TEST_EXPECT(nodeUp.counter_next().dest() == brother);
1480
1481            ARB_edge brotherUp = parentEdge(brother);
1482
1483            TEST_EXPECT(brother->is_rightson());                  // if child is right son..
1484            TEST_EXPECT(brotherUp.next().dest()         == node); // .. next() continues with other son
1485            TEST_EXPECT(brotherUp.counter_next().dest() == grandpa);
1486
1487            ARB_edge down = nodeUp.inverse();
1488
1489            TEST_EXPECT(down.next().dest()         == right); // next descends into right son
1490            TEST_EXPECT(down.counter_next().dest() == left);
1491
1492            TEST_EXPECT(nodeUp.previous().source()         == left);
1493            TEST_EXPECT(nodeUp.counter_previous().source() == right);
1494
1495            ARB_edge toLeaf(node, left);
1496            TEST_EXPECT(toLeaf.is_edge_to_leaf());
1497
1498            // all iterators should turn around at leaf:
1499            TEST_EXPECT(toLeaf.next().dest()         == node);
1500            TEST_EXPECT(toLeaf.counter_next().dest() == node);
1501
1502            ARB_edge fromLeaf(left, node);
1503            TEST_EXPECT(fromLeaf.previous().dest()         == left);
1504            TEST_EXPECT(fromLeaf.counter_previous().dest() == left);
1505
1506            ARB_edge rootEdge(tree->get_leftson(), tree->get_rightson());
1507
1508            TEST_EXPECT(rootEdge.get_type() == ROOT_EDGE);
1509            TEST_EXPECT(nodeUp.get_type()   == EDGE_TO_ROOT);
1510            TEST_EXPECT(fromLeaf.get_type() == EDGE_TO_ROOT);
1511            TEST_EXPECT(down.get_type()     == EDGE_TO_LEAF);
1512            TEST_EXPECT(toLeaf.get_type()   == EDGE_TO_LEAF);
1513
1514            // test iterators are inverse functions
1515            {
1516                ARB_edge e[] = { nodeUp, down, toLeaf, fromLeaf, rootEdge };
1517                const int EDGES = ARRAY_ELEMS(e);
1518                for (int i = 0; i<EDGES; ++i) {
1519                    TEST_ANNOTATE(GBS_global_string("i=%i", i));
1520
1521                    TEST_EXPECT(e[i].next().previous() == e[i]);
1522                    TEST_EXPECT(e[i].previous().next() == e[i]);
1523
1524                    TEST_EXPECT(e[i].counter_next().counter_previous() == e[i]);
1525                    TEST_EXPECT(e[i].counter_previous().counter_next() == e[i]);
1526
1527                    ARB_edge inv(e[i].inverse());
1528
1529                    TEST_EXPECT(e[i].counter_next().inverse().next()         == inv);
1530                    TEST_EXPECT(e[i].counter_previous().inverse().previous() == inv);
1531                    TEST_EXPECT(e[i].next().inverse().counter_next()         == inv);
1532                    TEST_EXPECT(e[i].previous().inverse().counter_previous() == inv);
1533                }
1534            }
1535
1536            // test adjacent_distance
1537            const double EPSILON = 0.000001;
1538
1539            const double NLEN = 0.025806;
1540            const double BLEN = 0.017316;
1541            const double PLEN = 0.017167;
1542            const double LLEN = 1.045690;
1543            const double RLEN = 0.060606;
1544
1545            TEST_EXPECT_SIMILAR(node->get_branchlength(),             NLEN, EPSILON);
1546            TEST_EXPECT_SIMILAR(nodeUp.length(),                      NLEN, EPSILON);
1547            TEST_EXPECT_SIMILAR(down.length(),                        NLEN, EPSILON);
1548            TEST_EXPECT_SIMILAR(nodeUp.length_or_adjacent_distance(), NLEN, EPSILON);
1549            TEST_EXPECT_SIMILAR(down.length_or_adjacent_distance(),   NLEN, EPSILON);
1550
1551            TEST_EXPECT_SIMILAR(brother->get_branchlength(), BLEN,      EPSILON);
1552            TEST_EXPECT_SIMILAR(parent ->get_branchlength(), PLEN,      EPSILON);
1553            TEST_EXPECT_SIMILAR(nodeUp.adjacent_distance(),  BLEN+PLEN, EPSILON);
1554
1555            TEST_EXPECT_SIMILAR(left ->get_branchlength(), LLEN,      EPSILON);
1556            TEST_EXPECT_SIMILAR(right->get_branchlength(), RLEN,      EPSILON);
1557            TEST_EXPECT_SIMILAR(down.adjacent_distance(),  LLEN+RLEN, EPSILON);
1558
1559            // modify lengths
1560            const double MOD_NLEN = 0.123456;
1561            const double MOD_LLEN = 0.246802;
1562
1563            toLeaf.set_length(MOD_LLEN);
1564            nodeUp.set_length(MOD_NLEN);
1565
1566            TEST_EXPECT_SIMILAR(toLeaf.length(), MOD_LLEN, EPSILON);
1567            TEST_EXPECT_SIMILAR(nodeUp.length(), MOD_NLEN, EPSILON);
1568            TEST_EXPECT_SIMILAR(down.length(),   MOD_NLEN, EPSILON);
1569        }
1570
1571        destroy(tree);
1572    }
1573
1574    GB_close(gb_main);
1575}
1576
1577void TEST_remove_bootstraps() {
1578    GB_shell  shell;
1579    GBDATA   *gb_main = GB_open("TEST_trees.arb", "rw");
1580    TEST_REJECT_NULL(gb_main);
1581
1582    {
1583        GB_transaction  ta(gb_main);
1584        TreeNode       *tree = GBT_read_tree(gb_main, "tree_test", new SizeAwareRoot);
1585        TEST_REJECT_NULL(tree);
1586
1587        const char *topo_org   = "(((((((CloTyro3,CloTyro4)'40%',CloTyro2)'0%',CloTyrob)'97%',CloInnoc)'0%',CloBifer)'53%',(((CloButy2,CloButyr),CloCarni)'33%',CloPaste)'97%'),((((CorAquat,CurCitre),CorGluta)'17%',CelBiazo)'40%',CytAquat));";
1588        const char *topo_rem   = "(((((((CloTyro3,CloTyro4)"   ",CloTyro2)"  ",CloTyrob)"   ",CloInnoc)"  ",CloBifer)"   ",(((CloButy2,CloButyr),CloCarni)"   ",CloPaste)"   "),((((CorAquat,CurCitre),CorGluta)"   ",CelBiazo)"   ",CytAquat));";
1589
1590        TEST_EXPECT_NEWICK(nREMARK, tree, topo_org);
1591
1592        tree->remove_bootstrap();
1593        TEST_EXPECT_NEWICK(nREMARK, tree, topo_rem);
1594
1595        destroy(tree);
1596    }
1597
1598    GB_close(gb_main);
1599}
1600
1601void TEST_multifurcate_tree() {
1602    GB_shell  shell;
1603    GBDATA   *gb_main = GB_open("TEST_trees.arb", "rw");
1604    TEST_REJECT_NULL(gb_main);
1605
1606    const char *topo_test               = "(((((((CloTyro3:1.046,CloTyro4:0.061)'40%':0.026,CloTyro2:0.017)'0%':0.017,CloTyrob:0.009)'97%:test':0.274,CloInnoc:0.371)'0%':0.057,CloBifer:0.388)'53%':0.124,(((CloButy2:0.009,CloButyr:0.000):0.564,CloCarni:0.120)'33%':0.010,CloPaste:0.179)'97%':0.131):0.081,((((CorAquat:0.084,CurCitre:0.058):0.103,CorGluta:0.522)'17%':0.053,CelBiazo:0.059)'40%':0.207,CytAquat:0.711):0.081);";
1607    // changes                          = "                                                                                                    +0.307         -0.371     +0.064 "
1608    const char *topo_single             = "(((((((CloTyro3:1.046,CloTyro4:0.061)'40%':0.026,CloTyro2:0.017)'0%':0.017,CloTyrob:0.009)'97%:test':0.581,CloInnoc:0.000)'0%':0.121,CloBifer:0.388)'53%':0.124,(((CloButy2:0.009,CloButyr:0.000):0.564,CloCarni:0.120)'33%':0.010,CloPaste:0.179)'97%':0.131):0.081,((((CorAquat:0.084,CurCitre:0.058):0.103,CorGluta:0.522)'17%':0.053,CelBiazo:0.059)'40%':0.207,CytAquat:0.711):0.081);";
1609    const char *topo_bs_less_101_005    = "(((((((CloTyro3:1.098,CloTyro4:0.064)"   ":0.000,CloTyro2:0.000)"  ":0.000,CloTyrob:0.000)'97%:test':0.287,CloInnoc:0.371)'0%':0.057,CloBifer:0.388)'53%':0.124,(((CloButy2:0.000,CloButyr:0.000):0.578,CloCarni:0.121)"   ":0.000,CloPaste:0.181)'97%':0.132):0.081,((((CorAquat:0.084,CurCitre:0.058):0.103,CorGluta:0.522)'17%':0.053,CelBiazo:0.059)'40%':0.207,CytAquat:0.711):0.081);";
1610    const char *topo_bs_less_101_005_NT = "(((((((CloTyro3:1.078,CloTyro4:0.062)"   ":0.000,CloTyro2:0.018)"  ":0.000,CloTyrob:0.009)'97%:test':0.282,CloInnoc:0.371)'0%':0.057,CloBifer:0.388)'53%':0.124,(((CloButy2:0.009,CloButyr:0.000):0.570,CloCarni:0.121)"   ":0.000,CloPaste:0.181)'97%':0.132):0.081,((((CorAquat:0.084,CurCitre:0.058):0.103,CorGluta:0.522)'17%':0.053,CelBiazo:0.059)'40%':0.207,CytAquat:0.711):0.081);";
1611    const char *topo_bs_less_30_005     = "(((((((CloTyro3:1.046,CloTyro4:0.061)'40%':0.027,CloTyro2:0.018)"  ":0.000,CloTyrob:0.009)'97%:test':0.288,CloInnoc:0.371)'0%':0.057,CloBifer:0.388)'53%':0.124,(((CloButy2:0.009,CloButyr:0.000):0.564,CloCarni:0.120)'33%':0.010,CloPaste:0.179)'97%':0.131):0.081,((((CorAquat:0.084,CurCitre:0.058):0.103,CorGluta:0.522)'17%':0.053,CelBiazo:0.059)'40%':0.207,CytAquat:0.711):0.081);";
1612    const char *topo_bs_less_30         = "(((((((CloTyro3:1.046,CloTyro4:0.061)'40%':0.027,CloTyro2:0.018)"  ":0.000,CloTyrob:0.009)'97%:test':0.302,CloInnoc:0.390)"  ":0.000,CloBifer:0.407)'53%':0.131,(((CloButy2:0.009,CloButyr:0.000):0.564,CloCarni:0.120)'33%':0.010,CloPaste:0.179)'97%':0.131):0.081,((((CorAquat:0.084,CurCitre:0.058):0.109,CorGluta:0.554)"   ":0.000,CelBiazo:0.062)'40%':0.220,CytAquat:0.711):0.081);";
1613    const char *topo_all                = "(((((((CloTyro3:0.000,CloTyro4:0.000)"   ":0.000,CloTyro2:0.000)"  ":0.000,CloTyrob:0.000)'"  "test':0.000,CloInnoc:0.000)"  ":0.000,CloBifer:0.000)"   ":0.000,(((CloButy2:0.000,CloButyr:0.000):0.000,CloCarni:0.000)"   ":0.000,CloPaste:0.000)"   ":0.000):0.000,((((CorAquat:0.000,CurCitre:0.000):0.000,CorGluta:0.000)"   ":0.000,CelBiazo:0.000)"   ":0.000,CytAquat:0.000):0.000);";
1614
1615    const double STABLE_LENGTH = 5.362750;
1616    const double EPSILON       = 0.000001;
1617
1618    for (int test = 1; test<=6; ++test) {
1619        GB_transaction  ta(gb_main);
1620        TreeNode       *tree = GBT_read_tree(gb_main, "tree_test", new SizeAwareRoot);
1621
1622        TEST_REJECT_NULL(tree);
1623        if (test == 1) {
1624            TEST_EXPECT_NEWICK(nALL, tree, topo_test);
1625            TEST_EXPECT_SIMILAR(tree->sum_child_lengths(), STABLE_LENGTH, EPSILON);
1626        }
1627
1628        switch (test) {
1629            case 1:
1630                tree->multifurcate_whole_tree(TreeNode::multifurc_limits(101, 0.05, true));
1631                TEST_EXPECT_NEWICK(nALL, tree, topo_bs_less_101_005);
1632                TEST_EXPECT_SIMILAR(tree->sum_child_lengths(), STABLE_LENGTH, EPSILON);
1633                break;
1634            case 6:
1635                tree->multifurcate_whole_tree(TreeNode::multifurc_limits(101, 0.05, false));
1636                TEST_EXPECT_NEWICK(nALL, tree, topo_bs_less_101_005_NT);
1637                TEST_EXPECT_SIMILAR(tree->sum_child_lengths(), STABLE_LENGTH, EPSILON);
1638                break;
1639            case 2:
1640                tree->multifurcate_whole_tree(TreeNode::multifurc_limits(30, 0.05, true));
1641                TEST_EXPECT_NEWICK(nALL, tree, topo_bs_less_30_005);
1642                TEST_EXPECT_SIMILAR(tree->sum_child_lengths(), STABLE_LENGTH, EPSILON);
1643                break;
1644            case 3:
1645                tree->multifurcate_whole_tree(TreeNode::multifurc_limits(30, 1000, true));
1646                TEST_EXPECT_NEWICK(nALL, tree, topo_bs_less_30);
1647                TEST_EXPECT_SIMILAR(tree->sum_child_lengths(), STABLE_LENGTH, EPSILON);
1648                break;
1649            case 4:
1650                tree->multifurcate_whole_tree(TreeNode::multifurc_limits(101, 1000, true)); // multifurcate all
1651                TEST_EXPECT_NEWICK(nALL, tree, topo_all);
1652                TEST_EXPECT_SIMILAR(tree->sum_child_lengths(), 0.0, EPSILON);
1653                break;
1654            case 5: {
1655                TreeNode *CloInnoc = tree->findLeafNamed("CloInnoc");
1656                TEST_REJECT_NULL(CloInnoc);
1657
1658                parentEdge(CloInnoc).multifurcate();
1659                TEST_EXPECT_NEWICK(nALL, tree, topo_single);
1660
1661                TEST_EXPECT_SIMILAR(tree->sum_child_lengths(), STABLE_LENGTH, EPSILON);
1662                break;
1663            }
1664            default:
1665                nt_assert(0);
1666                break;
1667        }
1668
1669        destroy(tree);
1670    }
1671
1672    GB_close(gb_main);
1673}
1674
1675void TEST_TreeNode_attributes() {
1676    // -> ../UNIT_TESTER/run/trees/bg_exp_p__0.tree
1677    TreeNode *tree = TREE_load("trees/bg_exp_p__0.tree", new SimpleRoot, NULp, false, NULp);
1678
1679    TreeNode *MabPelag = tree->findLeafNamed("MabPelag");
1680    TreeNode *MabSalin = tree->findLeafNamed("MabSalin");
1681    TreeNode *PaoMaris = tree->findLeafNamed("PaoMaris");
1682
1683    TEST_EXPECT(MabPelag->father == MabSalin->father); // are brothers
1684
1685    TreeNode *Mabs    = MabPelag->father;
1686    TreeNode *PaoMabs = PaoMaris->father;
1687
1688    // ((MabPelag, MabSalin), PaoMaris)
1689    //  -------- Mabs ------
1690    // -------------- PaoMabs ---------
1691
1692    TEST_EXPECT(Mabs->father == PaoMabs);
1693
1694    // is_son_of
1695    TEST_EXPECT(MabPelag->is_son_of(Mabs));
1696    TEST_EXPECT(MabSalin->is_son_of(Mabs));
1697    TEST_EXPECT(Mabs->is_son_of(PaoMabs));
1698    TEST_EXPECT(PaoMaris->is_son_of(PaoMabs));
1699
1700    // is_inside
1701    TEST_EXPECT(MabPelag->is_inside(Mabs));     // leaf in father
1702    TEST_EXPECT(Mabs->is_inside(PaoMabs));      // node in father
1703    TEST_EXPECT(MabPelag->is_inside(PaoMabs));  // leaf in grandfather
1704    TEST_EXPECT(MabPelag->is_inside(MabPelag)); // self-containment
1705    TEST_REJECT(Mabs->is_inside(MabPelag));     // not: father in child
1706    TEST_REJECT(MabPelag->is_inside(MabSalin)); // not: node in brother
1707
1708    // is_ancestor_of
1709    TEST_EXPECT(Mabs->is_ancestor_of(MabPelag));
1710    TEST_EXPECT(Mabs->is_ancestor_of(MabSalin));
1711    TEST_REJECT(Mabs->is_ancestor_of(PaoMaris)); // brother is no ancestor
1712    TEST_REJECT(Mabs->is_ancestor_of(Mabs));     // node never is ancestor of itself
1713    TEST_REJECT(Mabs->is_ancestor_of(PaoMabs));  // child cannot be ancestor
1714
1715    TEST_EXPECT(PaoMabs->is_ancestor_of(MabPelag)); // root of subtree (PaoMabs) is ancestor of all members..
1716    TEST_EXPECT(PaoMabs->is_ancestor_of(MabSalin));
1717    TEST_EXPECT(PaoMabs->is_ancestor_of(PaoMaris));
1718    TEST_EXPECT(PaoMabs->is_ancestor_of(Mabs));
1719    TEST_REJECT(PaoMabs->is_ancestor_of(PaoMabs));  // .. despite itself
1720
1721    // in_same_branch_as / in_other_branch_than
1722    TEST_EXPECT(MabPelag->in_same_branch_as(MabPelag));
1723    TEST_EXPECT(MabPelag->in_other_branch_than(MabSalin));
1724    TEST_EXPECT(MabPelag->in_other_branch_than(PaoMaris));
1725    TEST_EXPECT(MabPelag->in_same_branch_as(Mabs));
1726    TEST_EXPECT(MabPelag->in_same_branch_as(PaoMabs));
1727
1728    TEST_EXPECT(PaoMabs->in_same_branch_as(MabPelag));
1729    TEST_EXPECT(PaoMabs->in_same_branch_as(MabSalin));
1730    TEST_EXPECT(PaoMabs->in_same_branch_as(PaoMaris));
1731    TEST_EXPECT(PaoMabs->in_same_branch_as(Mabs));
1732    TEST_EXPECT(PaoMabs->in_same_branch_as(PaoMabs));
1733
1734    TEST_EXPECT(Mabs->in_same_branch_as(MabPelag));
1735    TEST_EXPECT(Mabs->in_same_branch_as(MabSalin));
1736    TEST_EXPECT(Mabs->in_other_branch_than(PaoMaris));
1737    TEST_EXPECT(Mabs->in_same_branch_as(Mabs));
1738    TEST_EXPECT(Mabs->in_same_branch_as(PaoMabs));
1739
1740    // ancestor_common_with
1741    TEST_EXPECT(MabPelag->ancestor_common_with(MabSalin) == Mabs);
1742    TEST_EXPECT(MabSalin->ancestor_common_with(MabPelag) == Mabs);
1743    TEST_EXPECT(PaoMaris->ancestor_common_with(MabPelag) == PaoMabs);
1744    TEST_EXPECT(PaoMabs->ancestor_common_with(Mabs)      == PaoMabs);
1745    TEST_EXPECT(MabPelag->ancestor_common_with(PaoMabs)  == PaoMabs);
1746
1747    destroy(tree);
1748}
1749
1750#endif // UNIT_TESTS
1751
1752// --------------------------------------------------------------------------------
1753
Note: See TracBrowser for help on using the repository browser.