source: branches/alilink/ARBDB/adali.cxx

Last change on this file was 18126, checked in by westram, 5 years ago
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 34.5 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        species_name_hash  = GBS_create_hash(GBT_get_species_count(Main), GB_IGNORE_CASE);
256
257        if (!error) {
258            for (GBDATA *gb_species = GBT_first_species_rel_species_data(gb_sd);
259                 gb_species;
260                 gb_species = GBT_next_species(gb_species))
261            {
262                const char *name = GBT_read_name(gb_species);
263
264                if (GBS_read_hash(species_name_hash, name)) duplicates++;
265                GBS_incr_hash(species_name_hash, name);
266            }
267        }
268
269        if (duplicates) {
270            error = GBS_global_string("Database is corrupted:\n"
271                                      "Found %li duplicated species with identical names!\n"
272                                      "Fix the problem using\n"
273                                      "   'Search For Equal Fields and Mark Duplicates'\n"
274                                      "in ARB_NTREE search tool, save DB and restart ARB."
275                                      , duplicates);
276        }
277    }
278
279    if (!error) {
280        for (GBDATA *gb_ali = GB_entry(gb_presets, "alignment");
281             gb_ali && !error;
282             gb_ali = GB_nextEntry(gb_ali))
283        {
284            error = GBT_check_alignment(Main, gb_ali, species_name_hash);
285        }
286    }
287
288    if (species_name_hash) {
289        if (!error) {
290            long counter = 0;
291            GBS_hash_do_const_loop(species_name_hash, check_for_species_without_data, &counter);
292            if (counter>0) {
293                GB_warningf("Found %li species without alignment data (only some were listed)", counter);
294            }
295        }
296
297        GBS_free_hash(species_name_hash);
298    }
299
300    return error;
301}
302
303void GBT_get_alignment_names(ConstStrArray& names, GBDATA *gb_main) {
304    /* Get names of existing alignments from database.
305     *
306     * Returns: array of strings, the last element is NULp
307     * (Note: use GBT_free_names() to free result)
308     */
309
310    GBDATA *presets = GBT_get_presets(gb_main);
311    for (GBDATA *ali = GB_entry(presets, "alignment"); ali; ali = GB_nextEntry(ali)) {
312        GBDATA *name = GB_entry(ali, "alignment_name");
313        names.put(name ? GB_read_char_pntr(name) : "<unnamed alignment>");
314    }
315}
316
317static char *gbt_nonexisting_alignment(GBDATA *gbMain) {
318    char  *ali_other = NULp;
319    int    counter;
320
321    for (counter = 1; !ali_other; ++counter) {
322        ali_other = GBS_global_string_copy("ali_x%i", counter);
323        if (GBT_get_alignment(gbMain, ali_other)) freenull(ali_other); // exists -> continue
324    }
325
326    return ali_other;
327}
328
329GB_ERROR GBT_check_alignment_name(const char *alignment_name) {
330    GB_ERROR error = GB_check_key(alignment_name);
331    if (!error && !ARB_strBeginsWith(alignment_name, "ali_")) {
332        error = GBS_global_string("alignment name '%s' has to start with 'ali_'", alignment_name);
333    }
334    return error;
335}
336
337static GB_ERROR create_ali_strEntry(GBDATA *gb_ali, const char *field, const char *strval, long write_protection) {
338    GB_ERROR  error  = NULp;
339    GBDATA   *gb_sub = GB_create(gb_ali, field, GB_STRING);
340
341    if (!gb_sub) error = GB_await_error();
342    else {
343        error             = GB_write_string(gb_sub, strval);
344        if (!error) error = GB_write_security_delete(gb_sub, 7);
345        if (!error) error = GB_write_security_write(gb_sub, write_protection);
346    }
347
348    if (error) {
349        error = GBS_global_string("failed to create alignment subentry '%s'\n"
350                                  "(Reason: %s)", field, error);
351    }
352
353    return error;
354}
355static GB_ERROR create_ali_intEntry(GBDATA *gb_ali, const char *field, int intval, long write_protection) {
356    GB_ERROR  error  = NULp;
357    GBDATA   *gb_sub = GB_create(gb_ali, field, GB_INT);
358
359    if (!gb_sub) error = GB_await_error();
360    else {
361        error             = GB_write_int(gb_sub, intval);
362        if (!error) error = GB_write_security_delete(gb_sub, 7);
363        if (!error) error = GB_write_security_write(gb_sub, write_protection);
364    }
365
366    if (error) {
367        error = GBS_global_string("failed to create alignment subentry '%s'\n"
368                                  "(Reason: %s)", field, error);
369    }
370
371    return error;
372}
373
374GBDATA *GBT_create_alignment(GBDATA *gbd, const char *name, long len, long aligned, long security, const char *type) {
375    /* create alignment
376     *
377     * returns pointer to alignment or
378     * NULp (in this case an error has been exported)
379     */
380    GB_ERROR  error      = NULp;
381    GBDATA   *gb_presets = GBT_get_presets(gbd);
382    GBDATA   *result     = NULp;
383
384    if (!gb_presets) {
385        error = GBS_global_string("can't find/create 'presets' (Reason: %s)", GB_await_error());
386    }
387    else {
388        error = GBT_check_alignment_name(name);
389        if (!error && (security<0 || security>6)) {
390            error = GBS_global_string("Illegal security value %li (allowed 0..6)", security);
391        }
392        if (!error) {
393            const char *allowed_types = ":dna:rna:ami:usr:";
394            int         tlen          = strlen(type);
395            const char *found         = strstr(allowed_types, type);
396            if (!found || found == allowed_types || found[-1] != ':' || found[tlen] != ':') {
397                error = GBS_global_string("Invalid alignment type '%s'", type);
398            }
399        }
400
401        if (!error) {
402            GBDATA *gb_name = GB_find_string(gb_presets, "alignment_name", name, GB_IGNORE_CASE, SEARCH_GRANDCHILD);
403
404            if (gb_name) error = GBS_global_string("Alignment '%s' already exists", name);
405            else {
406                GBDATA *gb_ali     = GB_create_container(gb_presets, "alignment");
407                if (!gb_ali) error = GB_await_error();
408                else {
409                    error = GB_write_security_delete(gb_ali, 6);
410                    if (!error) error = create_ali_strEntry(gb_ali, "alignment_name",           name, 6);
411                    if (!error) error = create_ali_intEntry(gb_ali, "alignment_len",            len, 0);
412                    if (!error) error = create_ali_intEntry(gb_ali, "aligned",                  aligned <= 0 ? 0 : 1, 0);
413                    if (!error) error = create_ali_intEntry(gb_ali, "alignment_write_security", security, 6);
414                    if (!error) error = create_ali_strEntry(gb_ali, "alignment_type",           type, 0);
415                }
416
417                if (!error) result = gb_ali;
418            }
419        }
420    }
421
422    if (!result) {
423        gb_assert(error);
424        GB_export_errorf("in GBT_create_alignment: %s", error);
425    }
426#if defined(DEBUG)
427    else gb_assert(!error);
428#endif // DEBUG
429
430    return result;
431}
432
433
434static GB_ERROR gbt_rename_alignment_of_item(GBDATA *gb_item_container, const char *item_name, const char *item_entry_name,
435                                             const char *source, const char *dest, int copy, int dele) // @@@ copy/dele should be bool
436{
437    GB_ERROR  error = NULp;
438    GBDATA   *gb_item;
439
440    for (gb_item = GB_entry(gb_item_container, item_entry_name);
441         gb_item && !error;
442         gb_item = GB_nextEntry(gb_item))
443    {
444        GBDATA *gb_ali = GB_entry(gb_item, source);
445        if (!gb_ali) continue;
446
447        if (copy) {
448            GBDATA *gb_new = GB_entry(gb_item, dest);
449            if (gb_new) {
450                error = GBS_global_string("Entry '%s' already exists", dest);
451            }
452            else {
453                gb_new             = GB_create_container(gb_item, dest);
454                if (!gb_new) error = GB_await_error();
455                else error         = GB_copy_dropProtectMarksAndTempstate(gb_new, gb_ali);
456            }
457        }
458        if (dele) error = GB_delete(gb_ali);
459    }
460
461    if (error && gb_item) {
462        error = GBS_global_string("%s\n(while renaming alignment for %s '%s')", error, item_name, GBT_read_name(gb_item));
463    }
464
465    return error;
466}
467
468GB_ERROR GBT_rename_alignment(GBDATA *gbMain, const char *source, const char *dest, int copy, int dele) { // @@@ copy/dele should be bool
469    /* if copy == 1 then create a copy
470     * if dele == 1 then delete old
471     */
472
473    GB_ERROR  error            = NULp;
474    int       is_case_error    = 0;
475    GBDATA   *gb_presets       = GBT_get_presets(gbMain);
476    GBDATA   *gb_species_data  = GBT_get_species_data(gbMain);
477    GBDATA   *gb_extended_data = GBT_get_SAI_data(gbMain);
478
479    if (!gb_presets || !gb_species_data || !gb_extended_data) error = GB_await_error();
480
481    // create copy and/or delete old alignment description
482    if (!error) {
483        GBDATA *gb_old_alignment = GBT_get_alignment(gbMain, source);
484
485        if (!gb_old_alignment) {
486            error = GB_await_error();
487        }
488        else {
489            if (copy) {
490                GBDATA *gbh = GBT_get_alignment(gbMain, dest);
491                if (gbh) {
492                    error         = GBS_global_string("destination alignment '%s' already exists", dest);
493                    is_case_error = (strcasecmp(source, dest) == 0); // test for case-only difference
494                }
495                else {
496                    GB_clear_error();
497                    error = GBT_check_alignment_name(dest);
498                    if (!error) {
499                        GBDATA *gb_new_alignment = GB_create_container(gb_presets, "alignment");
500                        error                    = GB_copy_dropProtectMarksAndTempstate(gb_new_alignment, gb_old_alignment);
501                        if (!error) error        = GBT_write_string(gb_new_alignment, "alignment_name", dest);
502                    }
503                }
504            }
505
506            if (dele && !error) {
507                error = GB_delete(gb_old_alignment);
508            }
509        }
510    }
511
512    // change default alignment
513    if (!error && dele && copy) {
514        error = GBT_write_string(gb_presets, "use", dest);
515    }
516
517    // copy and/or delete alignment entries in species
518    if (!error) {
519        error = gbt_rename_alignment_of_item(gb_species_data, "Species", "species", source, dest, copy, dele);
520    }
521
522    // copy and/or delete alignment entries in SAIs
523    if (!error) {
524        error = gbt_rename_alignment_of_item(gb_extended_data, "SAI", "extended", source, dest, copy, dele);
525    }
526
527    if (is_case_error) {
528        // alignments source and dest only differ in case
529        char *ali_other = gbt_nonexisting_alignment(gbMain);
530        gb_assert(copy);
531
532        printf("Renaming alignment '%s' -> '%s' -> '%s' (to avoid case-problem)\n", source, ali_other, dest);
533
534        error             = GBT_rename_alignment(gbMain, source, ali_other, 1, dele);
535        if (!error) error = GBT_rename_alignment(gbMain, ali_other, dest, 1, 1);
536
537        free(ali_other);
538    }
539
540    return error;
541}
542
543// -----------------------------------------
544//      alignment related item functions
545
546NOT4PERL GBDATA *GBT_add_data(GBDATA *species, const char *ali_name, const char *key, GB_TYPES type) {
547    // goes to header: __ATTR__DEPRECATED_TODO("better use GBT_create_sequence_data()")
548
549    /* replace this function by GBT_create_sequence_data
550     * the same as GB_search(species, 'ali_name/key', GB_CREATE)
551     *
552     * Note: The behavior is weird, cause it does sth special for GB_STRING (write default content "...")
553     *
554     * returns create database entry (or NULp; exports an error in this case)
555     */
556
557    GB_ERROR error = GB_check_key(ali_name);
558    if (error) {
559        error = GBS_global_string("Invalid alignment name '%s' (Reason: %s)", ali_name, error);
560    }
561    else {
562        error = GB_check_hkey(key);
563        if (error) {
564            error = GBS_global_string("Invalid field name '%s' (Reason: %s)", key, error);
565        }
566    }
567
568    GBDATA *gb_data = NULp;
569    if (error) {
570        GB_export_error(error);
571    }
572    else {
573        GBDATA *gb_gb     = GB_entry(species, ali_name);
574        if (!gb_gb) gb_gb = GB_create_container(species, ali_name);
575
576        if (gb_gb) {
577            if (type == GB_STRING) {
578                gb_data = GB_search(gb_gb, key, GB_FIND);
579                if (!gb_data) {
580                    gb_data = GB_search(gb_gb, key, GB_STRING);
581                    GB_write_string(gb_data, "...");
582                }
583            }
584            else {
585                gb_data = GB_search(gb_gb, key, type);
586            }
587        }
588    }
589    return gb_data;
590}
591
592NOT4PERL GBDATA *GBT_create_sequence_data(GBDATA *species, const char *ali_name, const char *key, GB_TYPES type, int security_write) {
593    GBDATA *gb_data = GBT_add_data(species, ali_name, key, type);
594    if (gb_data) {
595        GB_ERROR error = GB_write_security_write(gb_data, security_write);
596        if (error) {
597            GB_export_error(error);
598            gb_data = NULp;
599        }
600    }
601    return gb_data;
602}
603
604GBDATA *GBT_gen_accession_number(GBDATA *gb_species, const char *ali_name) {
605    GBDATA *gb_acc = GB_entry(gb_species, "acc");
606    if (!gb_acc) {
607        GBDATA *gb_data = GBT_find_sequence(gb_species, ali_name);
608        if (gb_data) {                                     // found a valid alignment
609            GB_CSTR     sequence = GB_read_char_pntr(gb_data);
610            long        id       = GBS_checksum(sequence, 1, ".-");
611            const char *acc      = GBS_global_string("ARB_%lX", id);
612            GB_ERROR    error    = GBT_write_string(gb_species, "acc", acc);
613
614            if (error) GB_export_error(error);
615        }
616    }
617    return gb_acc;
618}
619
620
621int GBT_is_partial(GBDATA *gb_species, int default_value, bool define_if_undef) {
622    // checks whether a species has a partial or full sequence
623    //
624    // Note: partial sequences should not be used for tree calculations
625    //
626    // returns: 0 if sequence is full
627    //          1 if sequence is partial
628    //          -1 in case of error (which is exported in this case)
629    //
630    // if the sequence has no 'ARB_partial' entry it returns 'default_value'
631    // if 'define_if_undef' is true then create an 'ARB_partial'-entry with the default value
632
633    int       result     = -1;
634    GB_ERROR  error      = NULp;
635    GBDATA   *gb_partial = GB_entry(gb_species, "ARB_partial");
636
637    if (gb_partial) {
638        result = GB_read_int(gb_partial);
639        if (result != 0 && result != 1) {
640            error = "Illegal value for 'ARB_partial' (only 1 or 0 allowed)";
641        }
642    }
643    else {
644        if (define_if_undef) {
645            error = GBT_write_int(gb_species, "ARB_partial", default_value);
646        }
647        result = default_value;
648    }
649
650    if (error) {
651        GB_export_error(error);
652        return -1;
653    }
654    return result;
655}
656
657GBDATA *GBT_find_sequence(GBDATA *gb_species, const char *aliname) {
658    GBDATA *gb_ali = GB_entry(gb_species, aliname);
659    return gb_ali ? GB_entry(gb_ali, "data") : NULp;
660}
661
662char *GBT_get_default_alignment(GBDATA *gb_main) {
663    gb_assert(!GB_have_error()); // illegal to enter this function when an error is exported!
664    return GBT_read_string(gb_main, GB_DEFAULT_ALIGNMENT);
665}
666
667GB_ERROR GBT_set_default_alignment(GBDATA *gb_main, const char *alignment_name) {
668    return GBT_write_string(gb_main, GB_DEFAULT_ALIGNMENT, alignment_name);
669}
670
671GBDATA *GBT_get_alignment(GBDATA *gb_main, const char *aliname) {
672    /*! @return global alignment container for alignment 'aliname' or
673     * NULp if alignment not found (error exported in that case)
674     */
675    if (!aliname) {
676        GB_export_error("no alignment given");
677        return NULp;
678    }
679
680    GBDATA *gb_presets        = GBT_get_presets(gb_main);
681    GBDATA *gb_alignment_name = GB_find_string(gb_presets, "alignment_name", aliname, GB_IGNORE_CASE, SEARCH_GRANDCHILD);
682
683    if (!gb_alignment_name) {
684        GB_export_errorf("alignment '%s' not found", aliname);
685        return NULp;
686    }
687    return GB_get_father(gb_alignment_name);
688}
689
690#if defined(WARN_TODO)
691#warning recode and change result type to long* ?
692#endif
693long GBT_get_alignment_len(GBDATA *gb_main, const char *aliname) {
694    /*! @return length of alignment 'aliname' or
695     * -1 if alignment not found (error exported in that case)
696     */
697    GBDATA *gb_alignment = GBT_get_alignment(gb_main, aliname);
698    return gb_alignment ? *GBT_read_int(gb_alignment, "alignment_len") : -1;
699}
700
701GB_ERROR GBT_set_alignment_len(GBDATA *gb_main, const char *aliname, long new_len) {
702    GB_ERROR  error        = NULp;
703    GBDATA   *gb_alignment = GBT_get_alignment(gb_main, aliname);
704
705    if (gb_alignment) {
706        GB_topSecurityLevel unsecured(gb_main);
707        error             = GBT_write_int(gb_alignment, "alignment_len", new_len); // write new len
708        if (!error) error = GBT_write_int(gb_alignment, "aligned", 0);             // mark as unaligned
709    }
710    else error = GB_export_errorf("Alignment '%s' not found", aliname);
711    return error;
712}
713
714char *GBT_get_alignment_type_string(GBDATA *gb_main, const char *aliname) {
715    /*! @return type-string of alignment 'aliname' or
716     * NULp if alignment not found (error exported in that case)
717     */
718    char   *result       = NULp;
719    GBDATA *gb_alignment = GBT_get_alignment(gb_main, aliname);
720    if (gb_alignment) {
721        result = GBT_read_string(gb_alignment, "alignment_type");
722        gb_assert(result);
723    }
724    return result;
725}
726
727GB_alignment_type GBT_get_alignment_type(GBDATA *gb_main, const char *aliname) {
728    char              *ali_type = GBT_get_alignment_type_string(gb_main, aliname);
729    GB_alignment_type  at       = GB_AT_UNKNOWN;
730
731    if (ali_type) {
732        switch (ali_type[0]) {
733            case 'r': if (strcmp(ali_type, "rna")==0) at = GB_AT_RNA; break;
734            case 'd': if (strcmp(ali_type, "dna")==0) at = GB_AT_DNA; break;
735            case 'a': if (strcmp(ali_type, "ami")==0) at = GB_AT_AA; break;
736            case 'p': if (strcmp(ali_type, "pro")==0) at = GB_AT_AA; break;
737            default: gb_assert(0); break;
738        }
739        free(ali_type);
740    }
741    return at;
742}
743
744bool GBT_is_alignment_protein(GBDATA *gb_main, const char *alignment_name) {
745    return GBT_get_alignment_type(gb_main, alignment_name) == GB_AT_AA;
746}
747
748// -----------------------
749//      gene sequence
750
751static const char *gb_cache_genome(GBDATA *gb_genome) {
752    static GBDATA *gb_last_genome = NULp;
753    static char   *last_genome    = NULp;
754
755    if (gb_genome != gb_last_genome) {
756        free(last_genome);
757
758        last_genome    = GB_read_string(gb_genome);
759        gb_last_genome = gb_genome;
760    }
761
762    return last_genome;
763}
764
765struct gene_part_pos {
766    int            parts;       // initialized for parts
767    unsigned char *certain;     // contains parts "=" chars
768    char           offset[256];
769};
770
771static gene_part_pos *gpp = NULp;
772
773static void init_gpp(int parts) {
774    if (!gpp) {
775        int i;
776        ARB_alloc(gpp, 1);
777        gpp->certain = NULp;
778
779        for (i = 0; i<256; ++i) gpp->offset[i] = 0;
780
781        gpp->offset[(int)'+'] = 1;
782        gpp->offset[(int)'-'] = -1;
783    }
784    else {
785        if (parts>gpp->parts) freenull(gpp->certain);
786    }
787
788    if (!gpp->certain) {
789        int forParts           = parts+10;
790        ARB_alloc(gpp->certain, forParts+1);
791        memset(gpp->certain, '=', forParts);
792        gpp->certain[forParts] = 0;
793        gpp->parts             = forParts;
794    }
795}
796
797static void getPartPositions(const GEN_position *pos, int part, size_t *startPos, size_t *stopPos) {
798    // returns 'startPos' and 'stopPos' of one part of a gene
799    gb_assert(part<pos->parts);
800    *startPos = pos->start_pos[part]+gpp->offset[(pos->start_uncertain ? pos->start_uncertain : gpp->certain)[part]];
801    *stopPos  = pos->stop_pos [part]+gpp->offset[(pos->stop_uncertain  ? pos->stop_uncertain  : gpp->certain)[part]];
802}
803
804NOT4PERL char *GBT_read_gene_sequence_and_length(GBDATA *gb_gene, bool use_revComplement, char partSeparator, size_t *gene_length) {
805    // return the sequence data of a gene
806    //
807    // if use_revComplement is true -> use data from complementary strand (if complement is set for gene)
808    //                    otherwise -> use data from primary strand (sort+merge parts by position)
809    //
810    // if partSeparator not is 0 -> insert partSeparator between single (non-merged) parts
811    //
812    // returns sequence as result (and length of sequence if 'gene_length' points to something)
813    //
814    // if 'pos_certain' contains '+', start behind position (or end at position)
815    //                           '-', start at position (or end before position)
816    //
817    // For zero-length genes (e.g. "711^712") this function returns an empty string.
818
819    GB_ERROR      error      = NULp;
820    char         *result     = NULp;
821    GBDATA       *gb_species = GB_get_grandfather(gb_gene);
822    GEN_position *pos        = GEN_read_position(gb_gene);
823
824    if (!pos) error = GB_await_error();
825    else {
826        GBDATA        *gb_seq        = GBT_find_sequence(gb_species, "ali_genom");
827        unsigned long  seq_length    = GB_read_count(gb_seq);
828        int            p;
829        int            parts         = pos->parts;
830        int            resultlen     = 0;
831        int            separatorSize = partSeparator ? 1 : 0;
832
833        init_gpp(parts);
834
835        // test positions and calculate overall result length
836        for (p = 0; p<parts && !error; p++) {
837            size_t start;
838            size_t stop;
839            getPartPositions(pos, p, &start, &stop);
840
841            if (start<1 || start>(stop+1) || stop > seq_length) { // do not reject zero-length genes (start == stop+1)
842                error = GBS_global_string("Illegal gene position(s): start=%zu, end=%zu, seq.length=%li",
843                                          start, stop, seq_length);
844            }
845            else {
846                resultlen += stop-start+1;
847            }
848        }
849
850        if (separatorSize) resultlen += (parts-1)*separatorSize;
851
852        if (!error) {
853            char T_or_U = 0;
854            if (use_revComplement) {
855                error = GBT_determine_T_or_U(GB_AT_DNA, &T_or_U, "reverse-complement");
856            }
857            else if (parts>1) {
858                GEN_sortAndMergeLocationParts(pos);
859                parts = pos->parts; // may have changed
860            }
861
862            if (!error) {
863                const char *seq_data = gb_cache_genome(gb_seq);
864                char       *resultpos;
865
866                ARB_alloc(result, resultlen+1);
867                resultpos = result;
868
869                if (gene_length) *gene_length = resultlen;
870
871                for (p = 0; p<parts; ++p) {
872                    size_t start;
873                    size_t stop;
874                    getPartPositions(pos, p, &start, &stop);
875
876                    int len = stop-start+1;
877
878                    if (separatorSize && p>0) *resultpos++ = partSeparator;
879
880                    memcpy(resultpos, seq_data+start-1, len);
881                    if (T_or_U && pos->complement[p]) {
882                        GBT_reverseComplementNucSequence(resultpos, len, T_or_U);
883                    }
884                    resultpos += len;
885                }
886
887                resultpos[0] = 0;
888            }
889        }
890        GEN_free_position(pos);
891    }
892
893    gb_assert(result || error);
894
895    if (error) {
896        char *id = GEN_global_gene_identifier(gb_gene, gb_species);
897        error    = GB_export_errorf("Can't read sequence of '%s' (Reason: %s)", id, error);
898        free(id);
899        free(result);
900        result   = NULp;
901    }
902
903    return result;
904}
905
906char *GBT_read_gene_sequence(GBDATA *gb_gene, bool use_revComplement, char partSeparator) {
907    return GBT_read_gene_sequence_and_length(gb_gene, use_revComplement, partSeparator, NULp);
908}
909
910// --------------------------------------------------------------------------------
911
912#ifdef UNIT_TESTS
913#include <test_unit.h>
914
915void TEST_alignment() {
916    GB_shell  shell;
917    GBDATA   *gb_main = GB_open("TEST_prot.arb", "r");
918
919    {
920        GB_transaction ta(gb_main);
921
922        TEST_EXPECT_EQUAL(GBT_count_alignments(gb_main), 2);
923
924        char *def_ali_name = GBT_get_default_alignment(gb_main);
925        TEST_EXPECT_EQUAL(def_ali_name, "ali_tuf_dna");
926
927        {
928            ConstStrArray names;
929            GBT_get_alignment_names(names, gb_main);
930            {
931                char *joined = GBT_join_strings(names, '*');
932                TEST_EXPECT_EQUAL(joined, "ali_tuf_pro*ali_tuf_dna");
933                free(joined);
934            }
935
936            for (int i = 0; names[i]; ++i) {
937                long len = GBT_get_alignment_len(gb_main, names[i]);
938                TEST_EXPECT_EQUAL(len, i ? 1462 : 487);
939
940                char *type_name = GBT_get_alignment_type_string(gb_main, names[i]);
941                TEST_EXPECT_EQUAL(type_name, i ? "dna" : "ami");
942                free(type_name);
943
944                GB_alignment_type type = GBT_get_alignment_type(gb_main, names[i]);
945                TEST_EXPECT_EQUAL(type, i ? GB_AT_DNA : GB_AT_AA);
946                TEST_EXPECT_EQUAL(GBT_is_alignment_protein(gb_main, names[i]), !i);
947            }
948        }
949
950        // test functions called with aliname==NULp
951        TEST_EXPECT_NORESULT__ERROREXPORTED_CONTAINS(GBT_get_alignment(gb_main, NULp), "no alignment");
952        TEST_EXPECT_EQUAL(GBT_get_alignment_len(gb_main, NULp), -1);
953        TEST_EXPECT_CONTAINS(GB_await_error(), "no alignment");
954        TEST_EXPECT_NORESULT__ERROREXPORTED_CONTAINS(GBT_get_alignment_type_string(gb_main, NULp), "no alignment");
955
956        free(def_ali_name);
957    }
958
959    GB_close(gb_main);
960}
961TEST_PUBLISH(TEST_alignment);
962
963#endif // UNIT_TESTS
Note: See TracBrowser for help on using the repository browser.