source: tags/ms_ra2q56/ARBDB/adali.cxx

Last change on this file was 18159, checked in by westram, 5 years ago
  • full update from child 'fix' into 'trunk'
    • fix item name accessors (GBT_get_name + GBT_get_name_or_description)
    • add null2empty
  • adds: log:branches/fix@18140:18158
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 35.1 KB
Line 
1// =============================================================== //
2//                                                                 //
3//   File      : adali.cxx                                         //
4//   Purpose   : alignments                                        //
5//                                                                 //
6//   Institute of Microbiology (Technical University Munich)       //
7//   http://www.arb-home.de/                                       //
8//                                                                 //
9// =============================================================== //
10
11#include <arbdbt.h>
12#include <adGene.h>
13
14#include "gb_local.h"
15
16#include <arb_strarray.h>
17#include <arb_str.h>
18
19static void check_for_species_without_data(const char *species_name, long value, void *counterPtr) {
20    if (value == 1) {
21        long cnt = *((long*)counterPtr);
22        if (cnt<40) {
23            GB_warningf("Species '%s' has no data in any alignment", species_name);
24        }
25        *((long*)counterPtr) = cnt+1;
26    }
27}
28
29GBDATA *GBT_get_presets(GBDATA *gb_main) {
30    return GBT_find_or_create(gb_main, "presets", 7);
31}
32
33int GBT_count_alignments(GBDATA *gb_main) {
34    int     count      = 0;
35    GBDATA *gb_presets = GBT_get_presets(gb_main);
36    for (GBDATA *gb_ali = GB_entry(gb_presets, "alignment");
37         gb_ali;
38         gb_ali = GB_nextEntry(gb_ali))
39    {
40        ++count;
41    }
42    return count;
43}
44
45static GB_ERROR GBT_check_alignment(GBDATA *gb_main, GBDATA *preset_alignment, GB_HASH *species_name_hash) {
46    /* check
47     * - whether alignment has correct size and
48     * - whether all data is present.
49     *
50     * Sets the security deletes and writes.
51     *
52     * If 'species_name_hash' is not NULp,
53     * - it initially has to contain value == 1 for each existing species.
54     * - afterwards it will contain value  == 2 for each species where an alignment has been found.
55     */
56
57    GBDATA *gb_species_data  = GBT_get_species_data(gb_main);
58    GBDATA *gb_extended_data = GBT_get_SAI_data(gb_main);
59
60    GB_ERROR  error      = NULp;
61    char     *ali_name   = GBT_read_string(preset_alignment, "alignment_name");
62    if (!ali_name) error = "Alignment w/o 'alignment_name'";
63
64    if (!error) {
65        long    security_write = -1;
66        long    stored_ali_len = -1;
67        long    found_ali_len  = -1;
68        long    aligned        = 1;
69        GBDATA *gb_ali_len     = NULp;
70
71        {
72            GBDATA *gb_ali_wsec = GB_entry(preset_alignment, "alignment_write_security");
73            if (!gb_ali_wsec) {
74                error = "has no 'alignment_write_security' entry";
75            }
76            else {
77                security_write = GB_read_int(gb_ali_wsec);
78            }
79        }
80
81
82        if (!error) {
83            gb_ali_len = GB_entry(preset_alignment, "alignment_len");
84            if (!gb_ali_len) {
85                error = "has no 'alignment_len' entry";
86            }
87            else {
88                stored_ali_len = GB_read_int(gb_ali_len);
89            }
90        }
91
92        if (!error) {
93            GBDATA *gb_species;
94            for (gb_species = GBT_first_species_rel_species_data(gb_species_data);
95                 gb_species && !error;
96                 gb_species = GBT_next_species(gb_species))
97            {
98                GBDATA     *gb_name        = GB_entry(gb_species, "name");
99                const char *name           = NULp;
100                int         alignment_seen = 0;
101
102                if (!gb_name) {
103                    // fatal: name is missing -> create a unique name
104                    char *unique = GBT_create_unique_species_name(gb_main, "autoname.");
105                    error        = GBT_write_string(gb_species, "name", unique);
106
107                    if (!error) {
108                        gb_name = GB_entry(gb_species, "name");
109                        GBS_write_hash(species_name_hash, unique, 1); // not seen before
110                        GB_warningf("Seen unnamed species (gave name '%s')", unique);
111                    }
112                    free(unique);
113                }
114
115                if (!error) {
116                    name = GB_read_char_pntr(gb_name);
117                    if (species_name_hash) {
118                        int seen = GBS_read_hash(species_name_hash, name);
119
120                        gb_assert(seen != 0); // species_name_hash not initialized correctly
121                        if (seen == 2) alignment_seen = 1; // already seen an alignment
122                    }
123                }
124
125                if (!error) {
126                    GB_topSecurityLevel unsecured(gb_name);
127
128                    error             = GB_write_security_delete(gb_name, 7);
129                    if (!error) error = GB_write_security_write(gb_name, 6);
130
131                    if (!error) {
132                        GBDATA *gb_ali = GB_entry(gb_species, ali_name);
133                        if (gb_ali) {
134                            GBDATA *gb_data = GB_entry(gb_ali, "data");
135                            if (!gb_data) {
136                                error = GBT_write_string(gb_ali, "data", "Error: entry 'data' was missing and therefore was filled with this text.");
137                                GB_warningf("No '%s/data' entry for species '%s' (has been filled with dummy data)", ali_name, name);
138                            }
139                            else {
140                                if (GB_read_type(gb_data) != GB_STRING) {
141                                    GB_delete(gb_data);
142                                    error = GBS_global_string("'%s/data' of species '%s' had wrong DB-type (%s) and has been deleted!",
143                                                              ali_name, name, GB_read_key_pntr(gb_data));
144                                }
145                                else {
146                                    long data_len = GB_read_string_count(gb_data);
147                                    if (found_ali_len != data_len) {
148                                        if (found_ali_len>0)        aligned       = 0;
149                                        if (found_ali_len<data_len) found_ali_len = data_len;
150                                    }
151
152                                    error = GB_write_security_delete(gb_data, 7);
153
154                                    if (!alignment_seen && species_name_hash) { // mark as seen
155                                        GBS_write_hash(species_name_hash, name, 2); // 2 means "species has data in at least 1 alignment"
156                                    }
157                                }
158                            }
159                        }
160                    }
161
162                    if (!error) error = GB_write_security_delete(gb_species, security_write);
163                }
164            }
165        }
166
167        if (!error) {
168            GBDATA *gb_sai;
169            for (gb_sai = GBT_first_SAI_rel_SAI_data(gb_extended_data);
170                 gb_sai && !error;
171                 gb_sai = GBT_next_SAI(gb_sai))
172            {
173                GBDATA *gb_sai_name = GB_entry(gb_sai, "name");
174                GBDATA *gb_ali;
175
176                if (!gb_sai_name) continue;
177
178                GB_write_security_delete(gb_sai_name, 7);
179
180                gb_ali = GB_entry(gb_sai, ali_name);
181                if (gb_ali) {
182                    GBDATA *gb_sai_data;
183                    for (gb_sai_data = GB_child(gb_ali);
184                         gb_sai_data;
185                         gb_sai_data = GB_nextChild(gb_sai_data))
186                    {
187                        long type = GB_read_type(gb_sai_data);
188                        long data_len;
189
190                        if (type == GB_DB || type < GB_BITS) continue;
191                        if (GB_read_key_pntr(gb_sai_data)[0] == '_') continue; // e.g. _STRUCT (of secondary structure)
192
193                        data_len = GB_read_count(gb_sai_data);
194
195                        if (found_ali_len != data_len) {
196                            if (found_ali_len>0)        aligned       = 0;
197                            if (found_ali_len<data_len) found_ali_len = data_len;
198                        }
199                    }
200                }
201            }
202        }
203
204        if (!error && stored_ali_len != found_ali_len) error = GB_write_int(gb_ali_len, found_ali_len);
205        if (!error) error = GBT_write_int(preset_alignment, "aligned", aligned);
206
207        if (error) {
208            error = GBS_global_string("Error checking alignment '%s':\n%s\n",  ali_name, error);
209        }
210    }
211
212    free(ali_name);
213
214    return error;
215}
216
217GB_ERROR GBT_check_data(GBDATA *Main, const char *alignment_name) {
218    /* alignment_name
219     *  == 0     -> check all existing alignments
220     * otherwise -> check only one alignment
221     */
222
223    GB_ERROR  error             = NULp;
224    GBDATA   *gb_sd             = GBT_get_species_data(Main);
225    GBDATA   *gb_presets        = GBT_get_presets(Main);
226    GB_HASH  *species_name_hash = NULp;
227
228    // create rest of main containers
229    GBT_get_SAI_data(Main);
230    GBT_get_tree_data(Main);
231
232    if (alignment_name) {
233        GBDATA *gb_ali_name = GB_find_string(gb_presets, "alignment_name", alignment_name, GB_IGNORE_CASE, SEARCH_GRANDCHILD);
234        if (!gb_ali_name) {
235            error = GBS_global_string("Alignment '%s' does not exist - it can't be checked.", alignment_name);
236        }
237    }
238
239    if (!error) {
240        // check whether we have an default alignment
241        GBDATA *gb_use = GB_entry(gb_presets, "use");
242        if (!gb_use) {
243            // if we have no default alignment -> look for any alignment
244            GBDATA *gb_ali_name = GB_find_string(gb_presets, "alignment_name", alignment_name, GB_IGNORE_CASE, SEARCH_GRANDCHILD);
245
246            error = gb_ali_name ?
247                GBT_write_string(gb_presets, "use", GB_read_char_pntr(gb_ali_name)) :
248                "No alignment defined";
249        }
250    }
251
252    if (!alignment_name && !error) {
253        // if all alignments are checked -> use species_name_hash to detect duplicated species and species w/o data
254        long duplicates = 0;
255        long unnamed    = 0;
256
257        species_name_hash = GBS_create_hash(GBT_get_species_count(Main), GB_IGNORE_CASE);
258
259        if (!error) {
260            for (GBDATA *gb_species = GBT_first_species_rel_species_data(gb_sd);
261                 gb_species;
262                 gb_species = GBT_next_species(gb_species))
263            {
264                const char *name = GBT_get_name(gb_species);
265                if (name) {
266                    if (GBS_read_hash(species_name_hash, name)) duplicates++;
267                    GBS_incr_hash(species_name_hash, name);
268                }
269                else {
270                    unnamed++;
271                }
272            }
273        }
274
275        if (duplicates) {
276            error = GBS_global_string("Database is corrupted:\n"
277                                      "Found %li duplicated species with identical names!\n"
278                                      "Fix the problem using\n"
279                                      "   'Search For Equal Fields and Mark Duplicates'\n"
280                                      "in ARB_NTREE search tool, save DB and restart ARB.",
281                                      duplicates);
282        }
283        else if (unnamed) {
284            error = GBS_global_string("Database is corrupted:\n"
285                                      "Found %li species without IDs ('name')!\n"
286                                      "This is a sewere problem!\n"
287                                      "ARB will not work as expected!",
288                                      unnamed);
289        }
290    }
291
292    if (!error) {
293        for (GBDATA *gb_ali = GB_entry(gb_presets, "alignment");
294             gb_ali && !error;
295             gb_ali = GB_nextEntry(gb_ali))
296        {
297            error = GBT_check_alignment(Main, gb_ali, species_name_hash);
298        }
299    }
300
301    if (species_name_hash) {
302        if (!error) {
303            long counter = 0;
304            GBS_hash_do_const_loop(species_name_hash, check_for_species_without_data, &counter);
305            if (counter>0) {
306                GB_warningf("Found %li species without alignment data (only some were listed)", counter);
307            }
308        }
309
310        GBS_free_hash(species_name_hash);
311    }
312
313    return error;
314}
315
316void GBT_get_alignment_names(ConstStrArray& names, GBDATA *gbd) {
317    /* Get names of existing alignments from database.
318     *
319     * Returns: array of strings, the last element is NULp
320     * (Note: use GBT_free_names() to free result)
321     */
322
323    GBDATA *presets = GBT_get_presets(gbd);
324    for (GBDATA *ali = GB_entry(presets, "alignment"); ali; ali = GB_nextEntry(ali)) {
325        GBDATA *name = GB_entry(ali, "alignment_name");
326        names.put(name ? GB_read_char_pntr(name) : "<unnamed alignment>");
327    }
328}
329
330static char *gbt_nonexisting_alignment(GBDATA *gbMain) {
331    char  *ali_other = NULp;
332    int    counter;
333
334    for (counter = 1; !ali_other; ++counter) {
335        ali_other = GBS_global_string_copy("ali_x%i", counter);
336        if (GBT_get_alignment(gbMain, ali_other)) freenull(ali_other); // exists -> continue
337    }
338
339    return ali_other;
340}
341
342GB_ERROR GBT_check_alignment_name(const char *alignment_name) {
343    GB_ERROR error = GB_check_key(alignment_name);
344    if (!error && !ARB_strBeginsWith(alignment_name, "ali_")) {
345        error = GBS_global_string("alignment name '%s' has to start with 'ali_'", alignment_name);
346    }
347    return error;
348}
349
350static GB_ERROR create_ali_strEntry(GBDATA *gb_ali, const char *field, const char *strval, long write_protection) {
351    GB_ERROR  error  = NULp;
352    GBDATA   *gb_sub = GB_create(gb_ali, field, GB_STRING);
353
354    if (!gb_sub) error = GB_await_error();
355    else {
356        error             = GB_write_string(gb_sub, strval);
357        if (!error) error = GB_write_security_delete(gb_sub, 7);
358        if (!error) error = GB_write_security_write(gb_sub, write_protection);
359    }
360
361    if (error) {
362        error = GBS_global_string("failed to create alignment subentry '%s'\n"
363                                  "(Reason: %s)", field, error);
364    }
365
366    return error;
367}
368static GB_ERROR create_ali_intEntry(GBDATA *gb_ali, const char *field, int intval, long write_protection) {
369    GB_ERROR  error  = NULp;
370    GBDATA   *gb_sub = GB_create(gb_ali, field, GB_INT);
371
372    if (!gb_sub) error = GB_await_error();
373    else {
374        error             = GB_write_int(gb_sub, intval);
375        if (!error) error = GB_write_security_delete(gb_sub, 7);
376        if (!error) error = GB_write_security_write(gb_sub, write_protection);
377    }
378
379    if (error) {
380        error = GBS_global_string("failed to create alignment subentry '%s'\n"
381                                  "(Reason: %s)", field, error);
382    }
383
384    return error;
385}
386
387GBDATA *GBT_create_alignment(GBDATA *gbd, const char *name, long len, long aligned, long security, const char *type) {
388    /* create alignment
389     *
390     * returns pointer to alignment or
391     * NULp (in this case an error has been exported)
392     */
393    GB_ERROR  error      = NULp;
394    GBDATA   *gb_presets = GBT_get_presets(gbd);
395    GBDATA   *result     = NULp;
396
397    if (!gb_presets) {
398        error = GBS_global_string("can't find/create 'presets' (Reason: %s)", GB_await_error());
399    }
400    else {
401        error = GBT_check_alignment_name(name);
402        if (!error && (security<0 || security>6)) {
403            error = GBS_global_string("Illegal security value %li (allowed 0..6)", security);
404        }
405        if (!error) {
406            const char *allowed_types = ":dna:rna:ami:usr:";
407            int         tlen          = strlen(type);
408            const char *found         = strstr(allowed_types, type);
409            if (!found || found == allowed_types || found[-1] != ':' || found[tlen] != ':') {
410                error = GBS_global_string("Invalid alignment type '%s'", type);
411            }
412        }
413
414        if (!error) {
415            GBDATA *gb_name = GB_find_string(gb_presets, "alignment_name", name, GB_IGNORE_CASE, SEARCH_GRANDCHILD);
416
417            if (gb_name) error = GBS_global_string("Alignment '%s' already exists", name);
418            else {
419                GBDATA *gb_ali     = GB_create_container(gb_presets, "alignment");
420                if (!gb_ali) error = GB_await_error();
421                else {
422                    error = GB_write_security_delete(gb_ali, 6);
423                    if (!error) error = create_ali_strEntry(gb_ali, "alignment_name",           name, 6);
424                    if (!error) error = create_ali_intEntry(gb_ali, "alignment_len",            len, 0);
425                    if (!error) error = create_ali_intEntry(gb_ali, "aligned",                  aligned <= 0 ? 0 : 1, 0);
426                    if (!error) error = create_ali_intEntry(gb_ali, "alignment_write_security", security, 6);
427                    if (!error) error = create_ali_strEntry(gb_ali, "alignment_type",           type, 0);
428                }
429
430                if (!error) result = gb_ali;
431            }
432        }
433    }
434
435    if (!result) {
436        gb_assert(error);
437        GB_export_errorf("in GBT_create_alignment: %s", error);
438    }
439#if defined(DEBUG)
440    else gb_assert(!error);
441#endif // DEBUG
442
443    return result;
444}
445
446
447static GB_ERROR gbt_rename_alignment_of_item(GBDATA *gb_item_container, const char *item_name, const char *item_entry_name,
448                                             const char *source, const char *dest, int copy, int dele) // @@@ copy/dele should be bool
449{
450    GB_ERROR  error = NULp;
451    GBDATA   *gb_item;
452
453    for (gb_item = GB_entry(gb_item_container, item_entry_name);
454         gb_item && !error;
455         gb_item = GB_nextEntry(gb_item))
456    {
457        GBDATA *gb_ali = GB_entry(gb_item, source);
458        if (!gb_ali) continue;
459
460        if (copy) {
461            GBDATA *gb_new = GB_entry(gb_item, dest);
462            if (gb_new) {
463                error = GBS_global_string("Entry '%s' already exists", dest);
464            }
465            else {
466                gb_new             = GB_create_container(gb_item, dest);
467                if (!gb_new) error = GB_await_error();
468                else error         = GB_copy_dropProtectMarksAndTempstate(gb_new, gb_ali);
469            }
470        }
471        if (dele) error = GB_delete(gb_ali);
472    }
473
474    if (error && gb_item) {
475        error = GBS_global_string("%s\n(while renaming alignment for %s '%s')", error, item_name, GBT_get_name_or_description(gb_item));
476    }
477
478    return error;
479}
480
481GB_ERROR GBT_rename_alignment(GBDATA *gbMain, const char *source, const char *dest, int copy, int dele) { // @@@ copy/dele should be bool
482    /* if copy == 1 then create a copy
483     * if dele == 1 then delete old
484     */
485
486    GB_ERROR  error            = NULp;
487    int       is_case_error    = 0;
488    GBDATA   *gb_presets       = GBT_get_presets(gbMain);
489    GBDATA   *gb_species_data  = GBT_get_species_data(gbMain);
490    GBDATA   *gb_extended_data = GBT_get_SAI_data(gbMain);
491
492    if (!gb_presets || !gb_species_data || !gb_extended_data) error = GB_await_error();
493
494    // create copy and/or delete old alignment description
495    if (!error) {
496        GBDATA *gb_old_alignment = GBT_get_alignment(gbMain, source);
497
498        if (!gb_old_alignment) {
499            error = GB_await_error();
500        }
501        else {
502            if (copy) {
503                GBDATA *gbh = GBT_get_alignment(gbMain, dest);
504                if (gbh) {
505                    error         = GBS_global_string("destination alignment '%s' already exists", dest);
506                    is_case_error = (strcasecmp(source, dest) == 0); // test for case-only difference
507                }
508                else {
509                    GB_clear_error();
510                    error = GBT_check_alignment_name(dest);
511                    if (!error) {
512                        GBDATA *gb_new_alignment = GB_create_container(gb_presets, "alignment");
513                        error                    = GB_copy_dropProtectMarksAndTempstate(gb_new_alignment, gb_old_alignment);
514                        if (!error) error        = GBT_write_string(gb_new_alignment, "alignment_name", dest);
515                    }
516                }
517            }
518
519            if (dele && !error) {
520                error = GB_delete(gb_old_alignment);
521            }
522        }
523    }
524
525    // change default alignment
526    if (!error && dele && copy) {
527        error = GBT_write_string(gb_presets, "use", dest);
528    }
529
530    // copy and/or delete alignment entries in species
531    if (!error) {
532        error = gbt_rename_alignment_of_item(gb_species_data, "Species", "species", source, dest, copy, dele);
533    }
534
535    // copy and/or delete alignment entries in SAIs
536    if (!error) {
537        error = gbt_rename_alignment_of_item(gb_extended_data, "SAI", "extended", source, dest, copy, dele);
538    }
539
540    if (is_case_error) {
541        // alignments source and dest only differ in case
542        char *ali_other = gbt_nonexisting_alignment(gbMain);
543        gb_assert(copy);
544
545        printf("Renaming alignment '%s' -> '%s' -> '%s' (to avoid case-problem)\n", source, ali_other, dest);
546
547        error             = GBT_rename_alignment(gbMain, source, ali_other, 1, dele);
548        if (!error) error = GBT_rename_alignment(gbMain, ali_other, dest, 1, 1);
549
550        free(ali_other);
551    }
552
553    return error;
554}
555
556// -----------------------------------------
557//      alignment related item functions
558
559NOT4PERL GBDATA *GBT_add_data(GBDATA *species, const char *ali_name, const char *key, GB_TYPES type) {
560    // goes to header: __ATTR__DEPRECATED_TODO("better use GBT_create_sequence_data()")
561
562    /* replace this function by GBT_create_sequence_data
563     * the same as GB_search(species, 'ali_name/key', GB_CREATE)
564     *
565     * Note: The behavior is weird, cause it does sth special for GB_STRING (write default content "...")
566     *
567     * returns create database entry (or NULp; exports an error in this case)
568     */
569
570    GB_ERROR error = GB_check_key(ali_name);
571    if (error) {
572        error = GBS_global_string("Invalid alignment name '%s' (Reason: %s)", ali_name, error);
573    }
574    else {
575        error = GB_check_hkey(key);
576        if (error) {
577            error = GBS_global_string("Invalid field name '%s' (Reason: %s)", key, error);
578        }
579    }
580
581    GBDATA *gb_data = NULp;
582    if (error) {
583        GB_export_error(error);
584    }
585    else {
586        GBDATA *gb_gb     = GB_entry(species, ali_name);
587        if (!gb_gb) gb_gb = GB_create_container(species, ali_name);
588
589        if (gb_gb) {
590            if (type == GB_STRING) {
591                gb_data = GB_search(gb_gb, key, GB_FIND);
592                if (!gb_data) {
593                    gb_data = GB_search(gb_gb, key, GB_STRING);
594                    GB_write_string(gb_data, "...");
595                }
596            }
597            else {
598                gb_data = GB_search(gb_gb, key, type);
599            }
600        }
601    }
602    return gb_data;
603}
604
605NOT4PERL GBDATA *GBT_create_sequence_data(GBDATA *species, const char *ali_name, const char *key, GB_TYPES type, int security_write) {
606    GBDATA *gb_data = GBT_add_data(species, ali_name, key, type);
607    if (gb_data) {
608        GB_ERROR error = GB_write_security_write(gb_data, security_write);
609        if (error) {
610            GB_export_error(error);
611            gb_data = NULp;
612        }
613    }
614    return gb_data;
615}
616
617GBDATA *GBT_gen_accession_number(GBDATA *gb_species, const char *ali_name) {
618    GBDATA *gb_acc = GB_entry(gb_species, "acc");
619    if (!gb_acc) {
620        GBDATA *gb_data = GBT_find_sequence(gb_species, ali_name);
621        if (gb_data) {                                     // found a valid alignment
622            GB_CSTR     sequence = GB_read_char_pntr(gb_data);
623            long        id       = GBS_checksum(sequence, 1, ".-");
624            const char *acc      = GBS_global_string("ARB_%lX", id);
625            GB_ERROR    error    = GBT_write_string(gb_species, "acc", acc);
626
627            if (error) GB_export_error(error);
628        }
629    }
630    return gb_acc;
631}
632
633
634int GBT_is_partial(GBDATA *gb_species, int default_value, bool define_if_undef) {
635    // checks whether a species has a partial or full sequence
636    //
637    // Note: partial sequences should not be used for tree calculations
638    //
639    // returns: 0 if sequence is full
640    //          1 if sequence is partial
641    //          -1 in case of error (which is exported in this case)
642    //
643    // if the sequence has no 'ARB_partial' entry it returns 'default_value'
644    // if 'define_if_undef' is true then create an 'ARB_partial'-entry with the default value
645
646    int       result     = -1;
647    GB_ERROR  error      = NULp;
648    GBDATA   *gb_partial = GB_entry(gb_species, "ARB_partial");
649
650    if (gb_partial) {
651        result = GB_read_int(gb_partial);
652        if (result != 0 && result != 1) {
653            error = "Illegal value for 'ARB_partial' (only 1 or 0 allowed)";
654        }
655    }
656    else {
657        if (define_if_undef) {
658            error = GBT_write_int(gb_species, "ARB_partial", default_value);
659        }
660        result = default_value;
661    }
662
663    if (error) {
664        GB_export_error(error);
665        return -1;
666    }
667    return result;
668}
669
670GBDATA *GBT_find_sequence(GBDATA *gb_species, const char *aliname) {
671    GBDATA *gb_ali = GB_entry(gb_species, aliname);
672    return gb_ali ? GB_entry(gb_ali, "data") : NULp;
673}
674
675char *GBT_get_default_alignment(GBDATA *gb_main) {
676    gb_assert(!GB_have_error()); // illegal to enter this function when an error is exported!
677    return GBT_read_string(gb_main, GB_DEFAULT_ALIGNMENT);
678}
679
680GB_ERROR GBT_set_default_alignment(GBDATA *gb_main, const char *alignment_name) {
681    return GBT_write_string(gb_main, GB_DEFAULT_ALIGNMENT, alignment_name);
682}
683
684GBDATA *GBT_get_alignment(GBDATA *gb_main, const char *aliname) {
685    /*! @return global alignment container for alignment 'aliname' or
686     * NULp if alignment not found (error exported in that case)
687     */
688    if (!aliname) {
689        GB_export_error("no alignment given");
690        return NULp;
691    }
692
693    GBDATA *gb_presets        = GBT_get_presets(gb_main);
694    GBDATA *gb_alignment_name = GB_find_string(gb_presets, "alignment_name", aliname, GB_IGNORE_CASE, SEARCH_GRANDCHILD);
695
696    if (!gb_alignment_name) {
697        GB_export_errorf("alignment '%s' not found", aliname);
698        return NULp;
699    }
700    return GB_get_father(gb_alignment_name);
701}
702
703#if defined(WARN_TODO)
704#warning recode and change result type to long* ?
705#endif
706long GBT_get_alignment_len(GBDATA *gb_main, const char *aliname) {
707    /*! @return length of alignment 'aliname' or
708     * -1 if alignment not found (error exported in that case)
709     */
710    GBDATA *gb_alignment = GBT_get_alignment(gb_main, aliname);
711    return gb_alignment ? *GBT_read_int(gb_alignment, "alignment_len") : -1;
712}
713
714GB_ERROR GBT_set_alignment_len(GBDATA *gb_main, const char *aliname, long new_len) {
715    GB_ERROR  error        = NULp;
716    GBDATA   *gb_alignment = GBT_get_alignment(gb_main, aliname);
717
718    if (gb_alignment) {
719        GB_topSecurityLevel unsecured(gb_main);
720        error             = GBT_write_int(gb_alignment, "alignment_len", new_len); // write new len
721        if (!error) error = GBT_write_int(gb_alignment, "aligned", 0);             // mark as unaligned
722    }
723    else error = GB_export_errorf("Alignment '%s' not found", aliname);
724    return error;
725}
726
727char *GBT_get_alignment_type_string(GBDATA *gb_main, const char *aliname) {
728    /*! @return type-string of alignment 'aliname' or
729     * NULp if alignment not found (error exported in that case)
730     */
731    char   *result       = NULp;
732    GBDATA *gb_alignment = GBT_get_alignment(gb_main, aliname);
733    if (gb_alignment) {
734        result = GBT_read_string(gb_alignment, "alignment_type");
735        gb_assert(result);
736    }
737    return result;
738}
739
740GB_alignment_type GBT_get_alignment_type(GBDATA *gb_main, const char *aliname) {
741    char              *ali_type = GBT_get_alignment_type_string(gb_main, aliname);
742    GB_alignment_type  at       = GB_AT_UNKNOWN;
743
744    if (ali_type) {
745        switch (ali_type[0]) {
746            case 'r': if (strcmp(ali_type, "rna")==0) at = GB_AT_RNA; break;
747            case 'd': if (strcmp(ali_type, "dna")==0) at = GB_AT_DNA; break;
748            case 'a': if (strcmp(ali_type, "ami")==0) at = GB_AT_AA; break;
749            case 'p': if (strcmp(ali_type, "pro")==0) at = GB_AT_AA; break;
750            default: gb_assert(0); break;
751        }
752        free(ali_type);
753    }
754    return at;
755}
756
757bool GBT_is_alignment_protein(GBDATA *gb_main, const char *alignment_name) {
758    return GBT_get_alignment_type(gb_main, alignment_name) == GB_AT_AA;
759}
760
761// -----------------------
762//      gene sequence
763
764static const char *gb_cache_genome(GBDATA *gb_genome) {
765    static GBDATA *gb_last_genome = NULp;
766    static char   *last_genome    = NULp;
767
768    if (gb_genome != gb_last_genome) {
769        free(last_genome);
770
771        last_genome    = GB_read_string(gb_genome);
772        gb_last_genome = gb_genome;
773    }
774
775    return last_genome;
776}
777
778struct gene_part_pos {
779    int            parts;       // initialized for parts
780    unsigned char *certain;     // contains parts "=" chars
781    char           offset[256];
782};
783
784static gene_part_pos *gpp = NULp;
785
786static void init_gpp(int parts) {
787    if (!gpp) {
788        int i;
789        ARB_alloc(gpp, 1);
790        gpp->certain = NULp;
791
792        for (i = 0; i<256; ++i) gpp->offset[i] = 0;
793
794        gpp->offset[(int)'+'] = 1;
795        gpp->offset[(int)'-'] = -1;
796    }
797    else {
798        if (parts>gpp->parts) freenull(gpp->certain);
799    }
800
801    if (!gpp->certain) {
802        int forParts           = parts+10;
803        ARB_alloc(gpp->certain, forParts+1);
804        memset(gpp->certain, '=', forParts);
805        gpp->certain[forParts] = 0;
806        gpp->parts             = forParts;
807    }
808}
809
810static void getPartPositions(const GEN_position *pos, int part, size_t *startPos, size_t *stopPos) {
811    // returns 'startPos' and 'stopPos' of one part of a gene
812    gb_assert(part<pos->parts);
813    *startPos = pos->start_pos[part]+gpp->offset[(pos->start_uncertain ? pos->start_uncertain : gpp->certain)[part]];
814    *stopPos  = pos->stop_pos [part]+gpp->offset[(pos->stop_uncertain  ? pos->stop_uncertain  : gpp->certain)[part]];
815}
816
817NOT4PERL char *GBT_read_gene_sequence_and_length(GBDATA *gb_gene, bool use_revComplement, char partSeparator, size_t *gene_length) {
818    // return the sequence data of a gene
819    //
820    // if use_revComplement is true -> use data from complementary strand (if complement is set for gene)
821    //                    otherwise -> use data from primary strand (sort+merge parts by position)
822    //
823    // if partSeparator not is 0 -> insert partSeparator between single (non-merged) parts
824    //
825    // returns sequence as result (and length of sequence if 'gene_length' points to something)
826    //
827    // if 'pos_certain' contains '+', start behind position (or end at position)
828    //                           '-', start at position (or end before position)
829    //
830    // For zero-length genes (e.g. "711^712") this function returns an empty string.
831
832    GB_ERROR      error      = NULp;
833    char         *result     = NULp;
834    GBDATA       *gb_species = GB_get_grandfather(gb_gene);
835    GEN_position *pos        = GEN_read_position(gb_gene);
836
837    if (!pos) error = GB_await_error();
838    else {
839        GBDATA        *gb_seq        = GBT_find_sequence(gb_species, "ali_genom");
840        unsigned long  seq_length    = GB_read_count(gb_seq);
841        int            p;
842        int            parts         = pos->parts;
843        int            resultlen     = 0;
844        int            separatorSize = partSeparator ? 1 : 0;
845
846        init_gpp(parts);
847
848        // test positions and calculate overall result length
849        for (p = 0; p<parts && !error; p++) {
850            size_t start;
851            size_t stop;
852            getPartPositions(pos, p, &start, &stop);
853
854            if (start<1 || start>(stop+1) || stop > seq_length) { // do not reject zero-length genes (start == stop+1)
855                error = GBS_global_string("Illegal gene position(s): start=%zu, end=%zu, seq.length=%li",
856                                          start, stop, seq_length);
857            }
858            else {
859                resultlen += stop-start+1;
860            }
861        }
862
863        if (separatorSize) resultlen += (parts-1)*separatorSize;
864
865        if (!error) {
866            char T_or_U = 0;
867            if (use_revComplement) {
868                error = GBT_determine_T_or_U(GB_AT_DNA, &T_or_U, "reverse-complement");
869            }
870            else if (parts>1) {
871                GEN_sortAndMergeLocationParts(pos);
872                parts = pos->parts; // may have changed
873            }
874
875            if (!error) {
876                const char *seq_data = gb_cache_genome(gb_seq);
877                char       *resultpos;
878
879                ARB_alloc(result, resultlen+1);
880                resultpos = result;
881
882                if (gene_length) *gene_length = resultlen;
883
884                for (p = 0; p<parts; ++p) {
885                    size_t start;
886                    size_t stop;
887                    getPartPositions(pos, p, &start, &stop);
888
889                    int len = stop-start+1;
890
891                    if (separatorSize && p>0) *resultpos++ = partSeparator;
892
893                    memcpy(resultpos, seq_data+start-1, len);
894                    if (T_or_U && pos->complement[p]) {
895                        GBT_reverseComplementNucSequence(resultpos, len, T_or_U);
896                    }
897                    resultpos += len;
898                }
899
900                resultpos[0] = 0;
901            }
902        }
903        GEN_free_position(pos);
904    }
905
906    gb_assert(result || error);
907
908    if (error) {
909        char *id = GEN_global_gene_identifier(gb_gene, gb_species);
910        error    = GB_export_errorf("Can't read sequence of '%s' (Reason: %s)", id, error);
911        free(id);
912        free(result);
913        result   = NULp;
914    }
915
916    return result;
917}
918
919char *GBT_read_gene_sequence(GBDATA *gb_gene, bool use_revComplement, char partSeparator) {
920    return GBT_read_gene_sequence_and_length(gb_gene, use_revComplement, partSeparator, NULp);
921}
922
923// --------------------------------------------------------------------------------
924
925#ifdef UNIT_TESTS
926#include <test_unit.h>
927
928void TEST_alignment() {
929    GB_shell  shell;
930    GBDATA   *gb_main = GB_open("TEST_prot.arb", "r");
931
932    {
933        GB_transaction ta(gb_main);
934
935        TEST_EXPECT_EQUAL(GBT_count_alignments(gb_main), 2);
936
937        char *def_ali_name = GBT_get_default_alignment(gb_main);
938        TEST_EXPECT_EQUAL(def_ali_name, "ali_tuf_dna");
939
940        {
941            ConstStrArray names;
942            GBT_get_alignment_names(names, gb_main);
943            {
944                char *joined = GBT_join_strings(names, '*');
945                TEST_EXPECT_EQUAL(joined, "ali_tuf_pro*ali_tuf_dna");
946                free(joined);
947            }
948
949            for (int i = 0; names[i]; ++i) {
950                long len = GBT_get_alignment_len(gb_main, names[i]);
951                TEST_EXPECT_EQUAL(len, i ? 1462 : 487);
952
953                char *type_name = GBT_get_alignment_type_string(gb_main, names[i]);
954                TEST_EXPECT_EQUAL(type_name, i ? "dna" : "ami");
955                free(type_name);
956
957                GB_alignment_type type = GBT_get_alignment_type(gb_main, names[i]);
958                TEST_EXPECT_EQUAL(type, i ? GB_AT_DNA : GB_AT_AA);
959                TEST_EXPECT_EQUAL(GBT_is_alignment_protein(gb_main, names[i]), !i);
960            }
961        }
962
963        // test functions called with aliname==NULp
964        TEST_EXPECT_NORESULT__ERROREXPORTED_CONTAINS(GBT_get_alignment(gb_main, NULp), "no alignment");
965        TEST_EXPECT_EQUAL(GBT_get_alignment_len(gb_main, NULp), -1);
966        TEST_EXPECT_CONTAINS(GB_await_error(), "no alignment");
967        TEST_EXPECT_NORESULT__ERROREXPORTED_CONTAINS(GBT_get_alignment_type_string(gb_main, NULp), "no alignment");
968
969        free(def_ali_name);
970    }
971
972    GB_close(gb_main);
973}
974TEST_PUBLISH(TEST_alignment);
975
976#endif // UNIT_TESTS
Note: See TracBrowser for help on using the repository browser.