source: tags/ms_ra2q1/ARBDB/adali.cxx

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