source: tags/ms_ra2q2/ARBDB/adali.cxx

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