diff --git a/.venv_haddock/include/site/python3.12/freesasa/classifier.c b/.venv_haddock/include/site/python3.12/freesasa/classifier.c new file mode 100644 index 0000000000000000000000000000000000000000..8e09233699e0d6e6207a92a41b2c211523a50bfd --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/classifier.c @@ -0,0 +1,1256 @@ +#if HAVE_CONFIG_H +#include +#endif + +#include +#include +#if HAVE_STRINGS_H +#include +#endif +#include + +#include "classifier.h" +#include "freesasa_internal.h" +#include "pdb.h" + +#define STD_CLASSIFIER_NAME "no-name-given" + +#define MAX_LINE_LEN 256 + +/** + In this file the concept class refers to polar/apolar and type to + aliphatic/aromatic/etc. See the example configurations in share/. + */ + +static const struct classifier_types empty_types = {0, NULL, NULL, NULL}; + +static const struct classifier_residue empty_residue = {0, NULL, NULL, NULL, NULL, {NULL, 0, 0, 0, 0, 0}}; + +static const struct freesasa_classifier empty_config = {0, NULL, NULL, NULL}; + +struct classifier_types * +freesasa_classifier_types_new(void) +{ + struct classifier_types *t = malloc(sizeof(struct classifier_types)); + if (t == NULL) + mem_fail(); + else + *t = empty_types; + return t; +} + +void freesasa_classifier_types_free(struct classifier_types *t) +{ + int i; + + if (t != NULL) { + free(t->type_radius); + free(t->type_class); + if (t->name) + for (i = 0; i < t->n_types; ++i) + free(t->name[i]); + free(t->name); + + free(t); + } +} + +struct classifier_residue * +freesasa_classifier_residue_new(const char *name) +{ + struct classifier_residue *res; + assert(strlen(name) > 0); + + res = malloc(sizeof(struct classifier_residue)); + + if (res == NULL) + mem_fail(); + else { + *res = empty_residue; + res->name = strdup(name); + if (res->name == NULL) { + mem_fail(); + free(res); + res = NULL; + } + } + return res; +} + +void freesasa_classifier_residue_free(struct classifier_residue *res) +{ + int i; + if (res != NULL) { + free(res->name); + + if (res->atom_name) + for (i = 0; i < res->n_atoms; ++i) + free(res->atom_name[i]); + free(res->atom_name); + + free(res->atom_radius); + free(res->atom_class); + + free(res); + } +} + +freesasa_classifier * +freesasa_classifier_new() +{ + struct freesasa_classifier *cfg = malloc(sizeof(struct freesasa_classifier)); + if (cfg == NULL) + mem_fail(); + else + *cfg = empty_config; + return cfg; +} + +void freesasa_classifier_free(freesasa_classifier *c) +{ + int i; + if (c != NULL) { + if (c->residue) + for (i = 0; i < c->n_residues; ++i) + freesasa_classifier_residue_free(c->residue[i]); + free(c->residue); + free(c->residue_name); + free(c->name); + free(c); + } +} + +/* check if array of strings has a string that matches key, + ignores trailing and leading whitespace */ +static int +find_string(char **array, + const char *key, + int array_size) +{ + int n, i, found = 0; + char *key_trimmed; + + if (array == NULL || array_size == 0) return -1; + + n = strlen(key); + key_trimmed = malloc(n + 1); + + if (key_trimmed == NULL) return mem_fail(); + + /* remove trailing and leading whitespace */ + sscanf(key, "%s", key_trimmed); + + for (i = 0; i < array_size; ++i) { + assert(array[i]); + if (strcmp(array[i], key_trimmed) == 0) { + found = 1; + break; + } + } + + free(key_trimmed); + + if (found) return i; + return FREESASA_FAIL; +} + +/** + Removes comments and strips leading and trailing + whitespace. Returns the length of the stripped line on success, + FREESASA_FAIL if malloc/realloc fails. Result will be stored in + the string line, which is assumed to have size MAX_LINE_LEN + 1. + */ +static int +strip_line(char *line, + const char *input) +{ + char *comment, *first, *last; + char linebuf[MAX_LINE_LEN + 1]; + + assert(strlen(input) <= MAX_LINE_LEN); + + strcpy(linebuf, input); + comment = strchr(linebuf, '#'); + if (comment) *comment = '\0'; /* skip comments */ + + first = linebuf; + last = linebuf + strlen(linebuf) - 1; + while (*first == ' ' || *first == '\t') + ++first; + + if (last > first) + while (*last == ' ' || *last == '\t' || *last == '\n') + --last; + + if (first >= last) { + line[0] = '\0'; + return 0; + } + + *(last + 1) = '\0'; + strncpy(line, first, MAX_LINE_LEN); + + return strlen(line); +} + +/** + Essentially a safer fscanf(input, "%s", str) limited to the + current line in input. Stores the result in 'str' (which should + be able to store a string of length MAX_LINE_LEN) +*/ +static int +get_next_string(FILE *input, char *str) +{ + char line[MAX_LINE_LEN + 1]; + long pos = ftell(input); + + if (fgets(line, MAX_LINE_LEN + 1, input) == NULL) { + if (ferror(input)) { + return freesasa_fail(strerror(errno)); + } + return 0; + } + + str[0] = '\0'; + + sscanf(line, "%s", str); + + fseek(input, pos + strlen(str), SEEK_SET); + return strlen(str); +} + +/** + Allocates space and stores a line stripped of comments in the line + pointer. Returns the length of the line on success, FREESASA_FAIL + for I/O errors. + */ +static int +next_line(char *line, + FILE *fp) +{ + char linebuf[MAX_LINE_LEN + 1]; + + if (fgets(linebuf, MAX_LINE_LEN + 1, fp) == NULL) { + if (ferror(fp)) { + return fail_msg(strerror(errno)); + } + + if (feof(fp)) { + line[0] = '\0'; + return 0; + } + } + + return strip_line(line, linebuf); +} + +/** + Find offset of str in line, returns -1 if not found + Ignores comments +*/ +static inline int +locate_string(const char *line, + const char *str) +{ + int NOT_FOUND = -1; + char *loc, buf[MAX_LINE_LEN + 1]; + + assert(line); + assert(strlen(line) <= MAX_LINE_LEN); + assert(str); + + if (strlen(line) == 0) { + return NOT_FOUND; + } + + strcpy(buf, line); + + /* skip comments */ + loc = strstr(buf, "#"); + if (loc == buf) { + return NOT_FOUND; + } else if (loc != NULL) { + *loc = '\0'; + } + + loc = strstr(buf, str); + if (loc != NULL) { + return loc - buf; + } + + return NOT_FOUND; +} + +/** + If string exists on line its location is stored in this_range, and + if prev_range is non-null it is set to end at the same location. + */ +static inline int +try_register_stringloc(const char *line, + const char *str, + long last_tell, + struct file_range *this_range, + struct file_range **prev_range) +{ + int pos, NOT_FOUND = -1; + + if (strlen(line) == 0) return NOT_FOUND; + + pos = locate_string(line, str); + if (pos >= 0) { + this_range->begin = last_tell + pos; + if (*prev_range) (*prev_range)->end = last_tell + pos; + (*prev_range) = this_range; + return last_tell + pos; + } + return NOT_FOUND; +} + +/** + Checks that input file has the required fields and locates the + 'types' and 'atoms' sections. No syntax checking. Return + FREESASA_SUCCESS if file seems ok, FREESASA_FAIL if either/both of + the sections are missing, or file invalid in some other way, or there was an error reading the file. + */ +static int +check_file(FILE *input, + struct file_range *types, + struct file_range *atoms, + struct file_range *name) +{ + long last_tell; + char line[MAX_LINE_LEN + 1]; + struct file_range *last_range = NULL; + + assert(input); + assert(types); + assert(atoms); + + last_tell = ftell(input); + + /* this allows us to detect wether a section wasn't found later */ + types->begin = atoms->begin = name->begin = -1; + + while (fgets(line, MAX_LINE_LEN + 1, input)) { + try_register_stringloc(line, "types:", last_tell, types, &last_range); + try_register_stringloc(line, "atoms:", last_tell, atoms, &last_range); + try_register_stringloc(line, "name:", last_tell, name, &last_range); + last_tell = ftell(input); + + if (strlen(line) == MAX_LINE_LEN && + line[MAX_LINE_LEN - 1] != '\n') { + return fail_msg("Lines in classifier files can only be %d characters or less", + MAX_LINE_LEN); + } + } + + if (ferror(input)) { + return fail_msg(strerror(errno)); + } + + if (last_range != NULL) { + last_range->end = last_tell; + } + rewind(input); + + if (name->begin == -1) { + freesasa_warn("input configuration lacks the entry 'name:', " + "will use '" STD_CLASSIFIER_NAME "'"); + } + + if ((types->begin == -1) || + (atoms->begin == -1)) { + return fail_msg("input configuration lacks (at least) one of " + "the entries 'types:' or 'atoms:'"); + } + + return FREESASA_SUCCESS; +} + +int freesasa_classifier_parse_class(const char *name) +{ +#if HAVE_STRNCASECMP + if (strncasecmp(name, "apolar", 6) == 0) { + return FREESASA_ATOM_APOLAR; + } else if (strncasecmp(name, "polar", 5) == 0) { + return FREESASA_ATOM_POLAR; + } else { + return fail_msg("only atom classes allowed are 'polar' and 'apolar'" + " (case insensitive)"); + } +#else + if (strncmp(name, "apolar", 6) == 0) { + return FREESASA_ATOM_APOLAR; + } else if (strncmp(name, "polar", 5) == 0) { + return FREESASA_ATOM_POLAR; + } else { + return fail_msg("only atom classes allowed are 'polar' and 'apolar'"); + } +#endif +} + +/** + Add type. Returns the index of the new type on success, + FREESASA_FAIL if realloc/strdup fails, FREESASA_WARN if type + already known (ignore duplicates). + */ +int freesasa_classifier_add_type(struct classifier_types *types, + const char *type_name, + const char *class_name, + double r) +{ + int the_class; + int n = types->n_types + 1; + char **tn = types->name; + double *tr = types->type_radius; + freesasa_atom_class *tc = types->type_class; + + if (find_string(types->name, type_name, types->n_types) >= 0) + return freesasa_warn("ignoring duplicate configuration entry for '%s'", type_name); + + the_class = freesasa_classifier_parse_class(class_name); + if (the_class == FREESASA_FAIL) return fail_msg(""); + + if ((types->name = realloc(tn, sizeof(char *) * n)) == NULL) { + types->name = tn; + return mem_fail(); + } + + if ((types->type_radius = realloc(tr, sizeof(double) * n)) == NULL) { + types->type_radius = tr; + return mem_fail(); + } + + if ((types->type_class = realloc(tc, sizeof(int) * n)) == NULL) { + types->type_class = tc; + return mem_fail(); + } + + if ((types->name[n - 1] = strdup(type_name)) == NULL) { + return mem_fail(); + } + + types->n_types++; + types->type_radius[types->n_types - 1] = r; + types->type_class[types->n_types - 1] = the_class; + + return types->n_types - 1; +} + +/** + Read a line specifying a type, store it in the config. Returns + warning for duplicates, failures for syntax errors or memory + allocation errors. + */ +static int +read_types_line(struct classifier_types *types, + const char *line) +{ + int the_type, ret = FREESASA_SUCCESS; + double r; + char buf1[MAX_LINE_LEN + 1], buf2[MAX_LINE_LEN + 1]; + + assert(strlen(line) <= MAX_LINE_LEN); + + if (sscanf(line, "%s %lf %s", buf1, &r, buf2) == 3) { + the_type = freesasa_classifier_add_type(types, buf1, buf2, r); + if (the_type == FREESASA_FAIL) ret = fail_msg(""); + if (the_type == FREESASA_WARN) ret = FREESASA_WARN; + } else { + ret = fail_msg("could not parse line '%s' in configuration, " + "expecting triplet of type 'TYPE [RADIUS] CLASS' for " + "example 'C_ALI 2.00 apolar'", + line); + } + + return ret; +} + +/** + Reads info about types from the user config. Associates each type + with a class and a radius in the config struct. Returns + FREESASA_SUCCESS on success, FREESASA_FAIL on syntax or memory + allocation errors. + */ +static int +read_types(struct classifier_types *types, + FILE *input, + struct file_range fi) +{ + char line[MAX_LINE_LEN + 1]; + int ret = FREESASA_SUCCESS, nl; + + fseek(input, fi.begin, SEEK_SET); + + /* read command (and discard) */ + if (next_line(line, input) > 0) { + char buf[7]; /* we should not get here if the line isn't "types:" (plus whitespace) */ + if (sscanf(line, "%6s", buf) == 0) return FREESASA_FAIL; + assert(strcmp(buf, "types:") == 0); + } else { + return FREESASA_FAIL; + } + + while (ftell(input) < fi.end) { + nl = next_line(line, input); + if (nl == 0) continue; + if (nl == FREESASA_FAIL) { + ret = nl; + break; + }; + ret = read_types_line(types, line); + if (ret == FREESASA_FAIL) break; + } + + return ret; +} + +/** + Add atom to residue. Returns index of the new atom on + success. FREESASA_FAIL if memory allocation fails. FREESASA_WARN + if the atom has already been added. + */ +int freesasa_classifier_add_atom(struct classifier_residue *res, + const char *name, + double radius, + int the_class) +{ + int n; + char **an = res->atom_name; + double *ar = res->atom_radius; + freesasa_atom_class *ac = res->atom_class; + + if (find_string(res->atom_name, name, res->n_atoms) >= 0) + return freesasa_warn("ignoring duplicate configuration entry for atom '%s %s'", + res->name, name); + n = res->n_atoms + 1; + + if ((res->atom_name = realloc(res->atom_name, sizeof(char *) * n)) == NULL) { + res->atom_name = an; + return mem_fail(); + } + if ((res->atom_radius = realloc(res->atom_radius, sizeof(double) * n)) == NULL) { + res->atom_radius = ar; + return mem_fail(); + } + if ((res->atom_class = realloc(res->atom_class, sizeof(int) * n)) == NULL) { + res->atom_class = ac; + return mem_fail(); + } + if ((res->atom_name[n - 1] = strdup(name)) == NULL) + return mem_fail(); + + ++res->n_atoms; + res->atom_radius[n - 1] = radius; + res->atom_class[n - 1] = the_class; + + return n - 1; +} + +/** + Add residue to config. If the residue already exists, it returns + the index of that residue, else it returns the index of the new + residue. Returns FREESASA_FAILURE if realloc/strdup fails. + */ +int freesasa_classifier_add_residue(struct freesasa_classifier *c, + const char *name) +{ + char **rn = c->residue_name; + struct classifier_residue **cr = c->residue; + int res = find_string(c->residue_name, name, c->n_residues); + + if (res >= 0) return res; + + res = c->n_residues + 1; + + if ((c->residue_name = realloc(rn, sizeof(char *) * res)) == NULL) { + c->residue_name = rn; + return mem_fail(); + } + + if ((c->residue = realloc(cr, sizeof(struct classifier_residue *) * res)) == NULL) { + c->residue = cr; + return mem_fail(); + } + + if ((c->residue[res - 1] = freesasa_classifier_residue_new(name)) == NULL) { + return mem_fail(); + } + + ++c->n_residues; + c->residue_name[res - 1] = c->residue[res - 1]->name; + return res - 1; +} + +/** + Read a line specifying an atom, store it in the config. Use + supplied types to add assign radius and class. Returns + FREESASA_WARN for duplicates. Returns FREESASA_FAIL for syntax + errors or memory allocation errors. FREESASA_SUCCESS else. + */ +static int +read_atoms_line(struct freesasa_classifier *c, + const struct classifier_types *types, + const char *line) +{ + char buf1[MAX_LINE_LEN + 1], buf2[MAX_LINE_LEN + 1], buf3[MAX_LINE_LEN + 1]; + int res, type, atom; + + assert(strlen(line) <= MAX_LINE_LEN); + + if (sscanf(line, "%s %s %s", buf1, buf2, buf3) == 3) { + if (strlen(buf1) > PDB_ATOM_RES_NAME_STRL) { + return fail_msg("residue name %s is too long in classifier file", buf1); + } + + if (strlen(buf2) > PDB_ATOM_NAME_STRL) { + return fail_msg("atom name %s is too long in classifier file", buf2); + } + + type = find_string(types->name, buf3, types->n_types); + + if (type < 0) { + return fail_msg("unknown atom type '%s' in configuration, line '%s'", + buf3, line); + } + + res = freesasa_classifier_add_residue(c, buf1); + + if (res == FREESASA_FAIL) return fail_msg(""); + + atom = freesasa_classifier_add_atom(c->residue[res], + buf2, + types->type_radius[type], + types->type_class[type]); + + if (atom == FREESASA_FAIL) return fail_msg(""); + if (atom == FREESASA_WARN) return FREESASA_WARN; + + } else { + return fail_msg("could not parse configuration, line '%s', " + "expecting triplet of type " + "'RESIDUE ATOM CLASS', for example 'ALA CB C_ALI'", + line); + } + return FREESASA_SUCCESS; +} + +/** + Reads atom configurations from config-file. Associates each atom + with a radius and class using the types that should already have + been stored in the config struct. + */ +static int +read_atoms(struct freesasa_classifier *c, + struct classifier_types *types, + FILE *input, + struct file_range fi) +{ + char line[MAX_LINE_LEN + 1], buf[MAX_LINE_LEN + 1]; + int ret = FREESASA_SUCCESS, nl; + + fseek(input, fi.begin, SEEK_SET); + + /* read command (and discard) */ + if (next_line(line, input) > 0) { + assert(strlen(line) <= MAX_LINE_LEN); + if (sscanf(line, "%s", buf) == 0) return FREESASA_FAIL; + assert(strcmp(buf, "atoms:") == 0); + } else { + return FREESASA_FAIL; + } + + while (ftell(input) < fi.end) { + nl = next_line(line, input); + if (nl == 0) continue; + if (nl == FREESASA_FAIL) return fail_msg(""); + ret = read_atoms_line(c, types, line); + if (ret == FREESASA_FAIL) break; + } + + return ret; +} + +static int +read_name(struct freesasa_classifier *classifier, + FILE *input, + struct file_range fi) +{ + char buf[MAX_LINE_LEN + 1]; + + if (fi.begin < 0) + return FREESASA_SUCCESS; /* name not set? */ + + fseek(input, fi.begin, SEEK_SET); + if (get_next_string(input, buf) <= 0) + return fail_msg(""); + + assert(strcmp(buf, "name:") == 0); + + if (get_next_string(input, buf) <= 0) { + return fail_msg("empty name for configuration?"); + } + + classifier->name = strdup(buf); + if (classifier->name == NULL) { + return mem_fail(); + } + + return FREESASA_SUCCESS; +} + +static struct freesasa_classifier * +read_config(FILE *input) +{ + struct file_range types_section, atoms_section, name_section; + struct freesasa_classifier *classifier = NULL; + struct classifier_types *types = NULL; + + assert(input); + + if (!(types = freesasa_classifier_types_new())) + goto cleanup; + if (!(classifier = freesasa_classifier_new())) + goto cleanup; + if (check_file(input, &types_section, &atoms_section, &name_section)) + goto cleanup; + if (read_name(classifier, input, name_section)) + goto cleanup; + if (read_types(types, input, types_section)) + goto cleanup; + if (read_atoms(classifier, types, input, atoms_section)) + goto cleanup; + + freesasa_classifier_types_free(types); + + return classifier; + +cleanup: + freesasa_classifier_free(classifier); + freesasa_classifier_types_free(types); + return NULL; +} + +/** + See if an atom_name has been defined for the residue ANY (writes + indices to the provided pointers). + */ +static void +find_any(const struct freesasa_classifier *c, + const char *atom_name, + int *res, int *atom) +{ + *res = find_string(c->residue_name, "ANY", c->n_residues); + if (*res >= 0) { + *atom = find_string(c->residue[*res]->atom_name, + atom_name, + c->residue[*res]->n_atoms); + } +} +/** + Find the residue and atom index of an atom in the supplied + configuration. Prints error and returns FREESASA_WARN if not + found. + */ +static int +find_atom(const struct freesasa_classifier *c, + const char *res_name, + const char *atom_name, + int *res, + int *atom) +{ + const struct classifier_residue *residue; + *atom = -1; + *res = find_string(c->residue_name, res_name, c->n_residues); + if (*res < 0) { + find_any(c, atom_name, res, atom); + } else { + residue = c->residue[*res]; + *atom = find_string(residue->atom_name, atom_name, residue->n_atoms); + if (*atom < 0) { + find_any(c, atom_name, res, atom); + } + } + if (*atom < 0) { + return FREESASA_WARN; + } + return FREESASA_SUCCESS; +} + +double +freesasa_classifier_radius(const freesasa_classifier *classifier, + const char *res_name, + const char *atom_name) +{ + int res, atom, status; + + assert(classifier); + assert(res_name); + assert(atom_name); + + status = find_atom(classifier, res_name, atom_name, &res, &atom); + if (status == FREESASA_SUCCESS) + return classifier->residue[res]->atom_radius[atom]; + return -1.0; +} + +freesasa_atom_class +freesasa_classifier_class(const freesasa_classifier *classifier, + const char *res_name, + const char *atom_name) +{ + int res, atom, status; + + assert(classifier); + assert(res_name); + assert(atom_name); + + status = find_atom(classifier, res_name, atom_name, &res, &atom); + if (status == FREESASA_SUCCESS) + return classifier->residue[res]->atom_class[atom]; + return FREESASA_ATOM_UNKNOWN; +} + +const char * +freesasa_classifier_class2str(freesasa_atom_class atom_class) +{ + switch (atom_class) { + case FREESASA_ATOM_APOLAR: + return "Apolar"; + case FREESASA_ATOM_POLAR: + return "Polar"; + case FREESASA_ATOM_UNKNOWN: + return "Unknown"; + } + fail_msg("invalid atom class"); + return NULL; +} + +freesasa_nodearea +freesasa_result_classes(const freesasa_structure *structure, + const freesasa_result *result) +{ + freesasa_nodearea area = {"whole-structure", 0, 0, 0, 0, 0}; + freesasa_range_nodearea(&area, structure, result, + 0, freesasa_structure_n(structure) - 1); + return area; +} + +freesasa_classifier * +freesasa_classifier_from_file(FILE *file) +{ + struct freesasa_classifier *classifier = read_config(file); + + if (classifier == NULL) { + fail_msg(""); + return NULL; + } + + return classifier; +} + +const freesasa_nodearea * +freesasa_classifier_residue_reference(const freesasa_classifier *classifier, + const char *res_name) +{ + int res = find_string(classifier->residue_name, res_name, classifier->n_residues); + + if (res < 0) return NULL; + + return &classifier->residue[res]->max_area; +} + +const char * +freesasa_classifier_name(const freesasa_classifier *classifier) +{ + return classifier->name; +} + +struct symbol_radius { + const char symbol[3]; + double radius; +}; + +/* Taken from: + + Mantina et al. "Consistent van der Waals Radii for + the Whole Main Group". J. Phys. Chem. A, 2009, 113 (19), pp + 5806–5812. + + Many of these elements, if they occur in a PDB file, should + probably rather be skipped than used in a SASA calculation, and + ionization will change the effective radius. + +*/ +static const struct symbol_radius symbol_radius[] = { + /* elements that actually occur in the regular amino acids and nucleotides */ + {" H", 1.10}, + {" C", 1.70}, + {" N", 1.55}, + {" O", 1.52}, + {" P", 1.80}, + {" S", 1.80}, + {"SE", 1.90}, + /* some others, values pulled from gemmi elem.hpp */ + /* Halogens */ + {" F", 1.47}, + {"CL", 1.75}, + {"BR", 1.83}, + {" I", 1.98}, + /* Alkali and Alkali Earth metals */ + {"LI", 1.81}, + {"BE", 1.53}, + {"NA", 2.27}, + {"MG", 1.73}, + {" K", 2.75}, + {"CA", 2.31}, + {"RB", 3.03}, + {"SR", 2.49}, + {"CS", 3.43}, + {"BA", 2.68}, + {"FR", 3.48}, + {"RA", 2.83}, + /* Transition metals */ + {"SC", 2.11}, + {"TI", 1.95}, + {" V", 1.06}, + {"CR", 1.13}, + {"MN", 1.19}, + {"FE", 1.26}, + {"CO", 1.13}, + {"NI", 1.63}, + {"CU", 1.40}, + {"ZN", 1.39}, + {" Y", 1.61}, + {"ZR", 1.42}, + {"NB", 1.33}, + {"MO", 1.75}, + {"TC", 2.00}, + {"RU", 1.20}, + {"RH", 1.22}, + {"PD", 1.63}, + {"AG", 1.72}, + {"CD", 1.58}, + {"HF", 1.40}, + {"TA", 1.22}, + {" W", 1.26}, + {"RE", 1.30}, + {"OS", 1.58}, + {"IR", 1.22}, + {"PT", 1.75}, + {"AU", 1.66}, + {"HG", 1.55}, + /* Post-Transition metals */ + {"AL", 1.84}, + {"GA", 1.87}, + {"IN", 1.93}, + {"SN", 2.17}, + {"TL", 1.96}, + {"PB", 2.02}, + {"BI", 2.07}, + {"PO", 1.97}, + /* Metalloid */ + {" B", 1.92}, + {"SI", 2.10}, + {"GE", 2.11}, + {"AS", 1.85}, + {"SB", 2.06}, + {"TE", 2.06}, + {"AT", 2.02}, + /* Noble gases */ + {"HE", 1.40}, + {"NE", 1.54}, + {"AR", 1.88}, + {"KR", 2.02}, + {"XE", 2.16}, + {"RN", 2.20}, + /* Lanthanoids */ + {"LA", 1.83}, + {"CE", 1.86}, + {"PR", 1.62}, + {"ND", 1.79}, + {"PM", 1.76}, + {"SM", 1.74}, + {"EU", 1.96}, + {"GD", 1.69}, + {"TB", 1.66}, + {"DY", 1.63}, + {"HO", 1.61}, + {"ER", 1.59}, + {"TM", 1.57}, + {"YB", 1.54}, + {"LU", 1.53}, + /* Actinoids */ + {"AC", 2.12}, + {"TH", 1.84}, + {"PA", 1.60}, + {" U", 1.86}, + {"NP", 1.71}, + {"PU", 1.67}, + {"AM", 1.66}, + {"CM", 1.65}, + {"BK", 1.64}, + {"CF", 1.63}, + {"ES", 1.62}, + {"FM", 1.61}, + {"MD", 1.60}, + {"NO", 1.59}, + {"LR", 1.58}, +}; + +double +freesasa_guess_radius(const char *input_symbol) +{ + int n_symbol, i; + char symbol[3]; + + assert(input_symbol); + snprintf(symbol, 3, "%2s", input_symbol); + + n_symbol = sizeof(symbol_radius) / sizeof(struct symbol_radius); + + for (i = 0; i < n_symbol; ++i) { + if (strcmp(symbol, symbol_radius[i].symbol) == 0) + return symbol_radius[i].radius; + } + return -1.0; +} + +// clang-format off +/* The residue types that are returned by freesasa_classify_residue() */ +enum residue { + /* Regular amino acids */ + ALA = 0, ARG, ASN, ASP, + CYS, GLN, GLU, GLY, + HIS, ILE, LEU, LYS, + MET, PHE, PRO, SER, + THR, TRP, TYR, VAL, + /* some non-standard ones */ + CSE, SEC, PYL, PYH, ASX, GLX, + /* residue unknown */ + RES_UNK, + /* capping N- and C-terminal groups (usually HETATM) */ + ACE, NH2, + /* DNA */ + DA, DC, DG, DT, DU, DI, + /* RNA (avoid one-letter enums) */ + RA, RC, RG, RU, RI, RT, + /* generic nucleotide */ + NN +}; + +/* Residue types, make sure this always matches the corresponding enum. */ +static const char *residue_names[] = { + /* amino acids */ + "ALA", "ARG", "ASN", "ASP", + "CYS", "GLN", "GLU", "GLY", + "HIS", "ILE", "LEU", "LYS", + "MET", "PHE", "PRO", "SER", + "THR", "TRP", "TYR", "VAL", + /* non-standard amino acids */ + "CSE", "SEC", "PYL", "PYH", /* SEC and PYL are standard names, CSE and PYH are found in some early files */ + "ASX", "GLX", + "UNK", + /* capping groups */ + "ACE", "NH2", + /* DNA */ + "DA", "DC", "DG", "DT", "DU", "DI", + /* RNA */ + "A", "C", "G", "U", "I", "T", + /* General nucleotide */ + "N"}; +// clang-format on + +int freesasa_classify_n_residue_types() +{ + return NN + 1; +} + +int freesasa_classify_residue(const char *res_name) +{ + int i; + char cpy[PDB_ATOM_RES_NAME_STRL + 1]; + + sscanf(res_name, "%s", cpy); + + for (i = ALA; i < freesasa_classify_n_residue_types(); ++i) { + if (strcmp(cpy, residue_names[i]) == 0) return i; + } + + return RES_UNK; +} + +const char * +freesasa_classify_residue_name(int residue_type) +{ + assert(residue_type >= 0 && residue_type <= NN); + return residue_names[residue_type]; +} + +int freesasa_atom_is_backbone(const char *atom_name) +{ + const char *bb[] = {"CA", "N", "O", "C", "OXT", + "P", "OP1", "OP2", "O5'", "C5'", "C4'", + "O4'", "C3'", "O3'", "C2'", "C1'"}; + char name[PDB_ATOM_NAME_STRL + 1]; + int i; + + name[0] = '\0'; + sscanf(atom_name, "%s", name); /* trim whitespace */ + + if (strlen(name) == 0) return 0; + for (i = 0; i < sizeof(bb) / sizeof(const char *); ++i) { + if (strcmp(name, bb[i]) == 0) { + return 1; + } + } + return 0; +} + +#if USE_CHECK +#include +#include + +START_TEST(test_classifier) +{ + struct classifier_types *types = freesasa_classifier_types_new(); + struct classifier_residue *residue_cfg = freesasa_classifier_residue_new("ALA"); + struct freesasa_classifier *clf = freesasa_classifier_new(); + + freesasa_set_verbosity(FREESASA_V_SILENT); + + ck_assert_int_eq(freesasa_classifier_parse_class("A"), FREESASA_FAIL); +#if HAVE_STRNCASECMP + ck_assert_int_eq(freesasa_classifier_parse_class("POLAR"), FREESASA_ATOM_POLAR); + ck_assert_int_eq(freesasa_classifier_parse_class("APOLAR"), FREESASA_ATOM_APOLAR); +#endif + ck_assert_int_eq(freesasa_classifier_parse_class("polar"), FREESASA_ATOM_POLAR); + ck_assert_int_eq(freesasa_classifier_parse_class("apolar"), FREESASA_ATOM_APOLAR); + + ck_assert_int_eq(types->n_types, 0); + ck_assert_int_eq(freesasa_classifier_add_type(types, "a", "A", 1.0), FREESASA_FAIL); + ck_assert_int_eq(freesasa_classifier_add_type(types, "a", "polar", 1.0), 0); + ck_assert_int_eq(freesasa_classifier_add_type(types, "b", "apolar", 2.0), 1); + ck_assert_int_eq(freesasa_classifier_add_type(types, "b", "polar", 1.0), FREESASA_WARN); + ck_assert_int_eq(freesasa_classifier_add_type(types, "c", "apolar", 3.0), 2); + ck_assert_int_eq(types->n_types, 3); + ck_assert_str_eq(types->name[0], "a"); + ck_assert_str_eq(types->name[1], "b"); + ck_assert_str_eq(types->name[2], "c"); + ck_assert(fabs(types->type_radius[0] - 1.0) < 1e-10); + ck_assert(fabs(types->type_radius[1] - 2.0) < 1e-10); + ck_assert(fabs(types->type_radius[2] - 3.0) < 1e-10); + + freesasa_classifier_types_free(types); + types = freesasa_classifier_types_new(); + + ck_assert_int_eq(read_types_line(types, ""), FREESASA_FAIL); + ck_assert_int_eq(read_types_line(types, "a"), FREESASA_FAIL); + ck_assert_int_eq(read_types_line(types, "a 1.0"), FREESASA_FAIL); + ck_assert_int_eq(read_types_line(types, "a b C"), FREESASA_FAIL); + ck_assert_int_eq(read_types_line(types, "a 1.0 C"), FREESASA_FAIL); + ck_assert_int_eq(read_types_line(types, "a 1.0 apolar"), FREESASA_SUCCESS); + ck_assert_int_eq(read_types_line(types, "b 2.0 polar"), FREESASA_SUCCESS); + ck_assert_int_eq(types->n_types, 2); + ck_assert_str_eq(types->name[0], "a"); + ck_assert_str_eq(types->name[1], "b"); + ck_assert(fabs(types->type_radius[0] - 1.0) < 1e-10); + ck_assert(fabs(types->type_radius[1] - 2.0) < 1e-10); + + ck_assert_int_eq(freesasa_classifier_add_atom(residue_cfg, "C", 1.0, 0), 0); + ck_assert_int_eq(freesasa_classifier_add_atom(residue_cfg, "CB", 2.0, 0), 1); + ck_assert_int_eq(freesasa_classifier_add_atom(residue_cfg, "CB", 2.0, 0), FREESASA_WARN); + ck_assert_str_eq(residue_cfg->atom_name[0], "C"); + ck_assert_str_eq(residue_cfg->atom_name[1], "CB"); + ck_assert(fabs(residue_cfg->atom_radius[0] - 1.0) < 1e-10); + ck_assert(fabs(residue_cfg->atom_radius[1] - 2.0) < 1e-10); + freesasa_classifier_residue_free(residue_cfg); + + ck_assert_int_eq(freesasa_classifier_add_residue(clf, "A"), 0); + ck_assert_int_eq(freesasa_classifier_add_residue(clf, "B"), 1); + ck_assert_int_eq(freesasa_classifier_add_residue(clf, "B"), 1); + ck_assert_int_eq(clf->n_residues, 2); + ck_assert_str_eq(clf->residue_name[0], "A"); + ck_assert_str_eq(clf->residue_name[1], "B"); + ck_assert_str_eq(clf->residue[0]->name, "A"); + + freesasa_classifier_free(clf); + clf = freesasa_classifier_new(); + + ck_assert_int_eq(read_atoms_line(clf, types, "A A"), FREESASA_FAIL); + ck_assert_int_eq(read_atoms_line(clf, types, "A A bla"), FREESASA_FAIL); + ck_assert_int_eq(read_atoms_line(clf, types, "ALA CA a"), FREESASA_SUCCESS); + ck_assert_int_eq(read_atoms_line(clf, types, "ALA CB b"), FREESASA_SUCCESS); + ck_assert_int_eq(read_atoms_line(clf, types, "ARG CA a"), FREESASA_SUCCESS); + ck_assert_int_eq(read_atoms_line(clf, types, "ARG CB b"), FREESASA_SUCCESS); + ck_assert_int_eq(read_atoms_line(clf, types, "ARG CG b"), FREESASA_SUCCESS); + ck_assert_int_eq(read_atoms_line(clf, types, "TOOLONGRESNAME CG b"), FREESASA_FAIL); + ck_assert_int_eq(read_atoms_line(clf, types, "ARG TOOLONGATOMNAME b"), FREESASA_FAIL); + ck_assert_int_eq(clf->n_residues, 2); + ck_assert_str_eq(clf->residue_name[0], "ALA"); + ck_assert_str_eq(clf->residue_name[1], "ARG"); + ck_assert_int_eq(clf->residue[0]->n_atoms, 2); + ck_assert_str_eq(clf->residue[0]->atom_name[0], "CA"); + ck_assert_str_eq(clf->residue[0]->atom_name[1], "CB"); + ck_assert(fabs(clf->residue[0]->atom_radius[0] - 1.0) < 1e-5); + ck_assert(fabs(clf->residue[0]->atom_radius[1] - 2.0) < 1e-5); + + freesasa_classifier_free(clf); + freesasa_classifier_types_free(types); + + freesasa_set_verbosity(FREESASA_V_NORMAL); +} +END_TEST + +START_TEST(test_classifier_utils) +{ + const char *strarr[] = {"A", "B", "C"}; + const char *line[] = {"# Bla", " # Bla", "Bla # Bla", " Bla # Bla", "#Bla #Alb"}; + + char dummy_str[MAX_LINE_LEN + 1]; + ck_assert_int_eq(find_string((char **)strarr, "A", 3), 0); + ck_assert_int_eq(find_string((char **)strarr, "B", 3), 1); + ck_assert_int_eq(find_string((char **)strarr, "C", 3), 2); + ck_assert_int_eq(find_string((char **)strarr, "D", 3), -1); + ck_assert_int_eq(find_string((char **)strarr, " C ", 3), 2); + ck_assert_int_eq(find_string((char **)strarr, "CC", 3), -1); + + ck_assert_int_eq(strip_line(dummy_str, line[0]), 0); + ck_assert_int_eq(strip_line(dummy_str, line[1]), 0); + ck_assert_int_eq(strip_line(dummy_str, line[2]), 3); + ck_assert_str_eq(dummy_str, "Bla"); + + ck_assert_int_eq(strip_line(dummy_str, line[3]), 3); + ck_assert_str_eq(dummy_str, "Bla"); + + ck_assert_int_eq(strip_line(dummy_str, line[4]), 0); + + const char *str = "foo bar # baz"; + ck_assert_int_eq(locate_string(str, "Foo"), -1); + ck_assert_int_eq(locate_string(str, "foo"), 0); + ck_assert_int_eq(locate_string(str, "bar"), 4); + ck_assert_int_eq(locate_string(str, "baz"), -1); + ck_assert_int_eq(locate_string(str, "ar"), 5); + + struct file_range this_range, *last_range = NULL; + ck_assert_int_eq(try_register_stringloc(str, "foo", 0, &this_range, &last_range), 0); + ck_assert_int_eq(this_range.begin, 0); + ck_assert_ptr_eq(last_range, &this_range); + ck_assert_int_eq(try_register_stringloc(str, "bar", 0, &this_range, &last_range), 4); + ck_assert_ptr_eq(last_range, &this_range); + ck_assert_int_eq(last_range->end, 4); + ck_assert_int_eq(try_register_stringloc(str, "baz", 0, &this_range, &last_range), -1); +} +END_TEST + +TCase * +test_classifier_static() +{ + TCase *tc = tcase_create("classifier.c static"); + tcase_add_test(tc, test_classifier); + tcase_add_test(tc, test_classifier_utils); + + return tc; +} + +#endif /** USE_CHECK */ diff --git a/.venv_haddock/include/site/python3.12/freesasa/classifier.h b/.venv_haddock/include/site/python3.12/freesasa/classifier.h new file mode 100644 index 0000000000000000000000000000000000000000..2344be2a06eb0f76f3916d7055e107d1d05cb7cf --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/classifier.h @@ -0,0 +1,117 @@ +#ifndef CLASSIFIER_H +#define CLASSIFIER_H + +#include "freesasa_internal.h" + +/** + This classifier only has the sasa_class() and class2str() + functions, which returns 1 for protein backbone atoms, and 0 + else. Backbone atoms are CA, N, C and O. + */ +extern const freesasa_classifier freesasa_backbone_classifier; + +/** Classifier that classifies each atom according to residue */ +extern const freesasa_classifier freesasa_residue_classifier; + +/** + The following three structs and the following functions are only + exposed in a header because the autogenerated static classifiers + need to see them, they are not intended for use outside of this + context. Therefore the functions to modify the structs are hidden + inside classifier.c. + + Names of classes, types, etc are stored in arrays to simplify + generic searching. +*/ + +/** + Struct to store information about the types-section in a user-config. + */ +struct classifier_types { + int n_types; /**< number of types */ + char **name; /**< names of types */ + double *type_radius; /**< radius of type */ + freesasa_atom_class *type_class; /**< class of each type */ +}; + +/** + Configuration info for each residue type. + */ +struct classifier_residue { + int n_atoms; /**< Number of atoms */ + char *name; /**< Name of residue */ + char **atom_name; /**< Names of atoms */ + double *atom_radius; /**< Atomic radii */ + freesasa_atom_class *atom_class; /**< Classes of atoms */ + freesasa_nodearea max_area; /**< Maximum area (for RSA) */ +}; + +/** + Stores a user-configuration as extracted from a configuration + file. No info about types, since those are only a tool used + intermediately in assigment of radii and classes. + + An array of the names of residues is stored directly in the struct + to facilitate searching for residues. The class_name array should + be a clone of that found in struct types (can be done bye + config_copy_classes()). + + Only for internal use. + */ +struct freesasa_classifier { + int n_residues; /**< Number of residues */ + char **residue_name; /**< Names of residues */ + char *name; + struct classifier_residue **residue; +}; + +/** + Get the VdW radius of an element + */ +double +freesasa_guess_radius(const char *symbol); + +const freesasa_nodearea * +freesasa_classifier_residue_reference(const freesasa_classifier *classifier, + const char *res_name); + +/* The functions below are only exposed to allow testing */ +freesasa_classifier * +freesasa_classifier_new(void); + +struct classifier_types * +freesasa_classifier_types_new(void); + +void freesasa_classifier_types_free(struct classifier_types *t); + +struct classifier_residue * +freesasa_classifier_residue_new(const char *name); + +void freesasa_classifier_residue_free(struct classifier_residue *res); + +int freesasa_classifier_add_residue(struct freesasa_classifier *c, + const char *name); + +int freesasa_classifier_add_atom(struct classifier_residue *res, + const char *name, + double radius, + int the_class); + +int freesasa_classifier_add_type(struct classifier_types *types, + const char *type_name, + const char *class_name, + double r); + +int freesasa_classifier_add_class(struct classifier_types *types, + const char *name); + +/* These three are used to calculate residue type areas */ + +int freesasa_classify_n_residue_types(void); + +int freesasa_classify_residue(const char *res_name); + +const char * +freesasa_classify_residue_name(int residue_type); + +#endif /* CLASSIFIER_H */ diff --git a/.venv_haddock/include/site/python3.12/freesasa/classifier_naccess.c b/.venv_haddock/include/site/python3.12/freesasa/classifier_naccess.c new file mode 100644 index 0000000000000000000000000000000000000000..6d5bb3e9842ebc38677c941398f9707841130fb4 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/classifier_naccess.c @@ -0,0 +1,434 @@ +#include "classifier.h" + +/* Autogenerated code from the script config2c.pl */ + +static const char *naccess_residue_name[] = {"A", "ALA", "ANY", "ARG", "ASN", "ASP", "C", "CYS", "DA", "DC", "DG", "DI", "DT", "DU", "G", "GLN", "GLU", "GLY", "HIS", "I", "ILE", "LEU", "LYS", "MET", "MSE", "PHE", "PRO", "SEC", "SER", "T", "THR", "TRP", "TYR", "U", "VAL", }; +static const char *naccess_A_atom_name[] = {"C2", "C6", "C4", "N7", "N9", "C5", "C8", "N3", "N6", "N1", }; +static double naccess_A_atom_radius[] = {1.80, 1.80, 1.80, 1.60, 1.60, 1.80, 1.80, 1.60, 1.60, 1.60, }; +static int naccess_A_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_A_cfg = { + 10, + "A", + (char**) naccess_A_atom_name, + (double*) naccess_A_atom_radius, + (freesasa_atom_class*) naccess_A_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_ALA_atom_name[] = {"CB", }; +static double naccess_ALA_atom_radius[] = {1.87, }; +static int naccess_ALA_atom_class[] = {FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_ALA_cfg = { + 1, + "ALA", + (char**) naccess_ALA_atom_name, + (double*) naccess_ALA_atom_radius, + (freesasa_atom_class*) naccess_ALA_atom_class, + {"ALA", 107.89, 43.94, 63.94, 36.71, 71.17, 0}, +}; + +static const char *naccess_ANY_atom_name[] = {"C3'", "OP1", "C", "O5'", "OXT", "C1'", "CA", "C5'", "C4'", "O2'", "O", "OP2", "CB", "N", "P", "O4'", "OP3", "C2'", "O3'", }; +static double naccess_ANY_atom_radius[] = {1.80, 1.40, 1.76, 1.40, 1.40, 1.80, 1.87, 1.80, 1.80, 1.40, 1.40, 1.40, 1.87, 1.65, 1.90, 1.40, 1.40, 1.80, 1.40, }; +static int naccess_ANY_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_ANY_cfg = { + 19, + "ANY", + (char**) naccess_ANY_atom_name, + (double*) naccess_ANY_atom_radius, + (freesasa_atom_class*) naccess_ANY_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_ARG_atom_name[] = {"CG", "CD", "NH1", "NE", "NH2", "CZ", }; +static double naccess_ARG_atom_radius[] = {1.87, 1.87, 1.65, 1.65, 1.65, 1.76, }; +static int naccess_ARG_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_ARG_cfg = { + 6, + "ARG", + (char**) naccess_ARG_atom_name, + (double*) naccess_ARG_atom_radius, + (freesasa_atom_class*) naccess_ARG_atom_class, + {"ARG", 238.33, 41.72, 196.61, 161.10, 77.23, 0}, +}; + +static const char *naccess_ASN_atom_name[] = {"OD1", "CG", "ND2", }; +static double naccess_ASN_atom_radius[] = {1.40, 1.76, 1.65, }; +static int naccess_ASN_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_ASN_cfg = { + 3, + "ASN", + (char**) naccess_ASN_atom_name, + (double*) naccess_ASN_atom_radius, + (freesasa_atom_class*) naccess_ASN_atom_class, + {"ASN", 143.97, 41.03, 102.94, 97.83, 46.14, 0}, +}; + +static const char *naccess_ASP_atom_name[] = {"OD1", "CG", "OD2", }; +static double naccess_ASP_atom_radius[] = {1.40, 1.76, 1.40, }; +static int naccess_ASP_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_ASP_cfg = { + 3, + "ASP", + (char**) naccess_ASP_atom_name, + (double*) naccess_ASP_atom_radius, + (freesasa_atom_class*) naccess_ASP_atom_class, + {"ASP", 140.48, 41.76, 98.72, 91.19, 49.29, 0}, +}; + +static const char *naccess_C_atom_name[] = {"C5", "C6", "C4", "C2", "N1", "N4", "O2", "N3", }; +static double naccess_C_atom_radius[] = {1.80, 1.80, 1.80, 1.80, 1.60, 1.60, 1.40, 1.60, }; +static int naccess_C_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_C_cfg = { + 8, + "C", + (char**) naccess_C_atom_name, + (double*) naccess_C_atom_radius, + (freesasa_atom_class*) naccess_C_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_CYS_atom_name[] = {"SG", }; +static double naccess_CYS_atom_radius[] = {1.85, }; +static int naccess_CYS_atom_class[] = {FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_CYS_cfg = { + 1, + "CYS", + (char**) naccess_CYS_atom_name, + (double*) naccess_CYS_atom_radius, + (freesasa_atom_class*) naccess_CYS_atom_class, + {"CYS", 134.24, 41.92, 92.33, 36.49, 97.75, 0}, +}; + +static const char *naccess_DA_atom_name[] = {"N6", "N1", "C8", "N3", "N9", "N7", "C5", "C2", "C6", "C4", }; +static double naccess_DA_atom_radius[] = {1.60, 1.60, 1.80, 1.60, 1.60, 1.60, 1.80, 1.80, 1.80, 1.80, }; +static int naccess_DA_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_DA_cfg = { + 10, + "DA", + (char**) naccess_DA_atom_name, + (double*) naccess_DA_atom_radius, + (freesasa_atom_class*) naccess_DA_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_DC_atom_name[] = {"C2", "C4", "C6", "C5", "O2", "N3", "N4", "N1", }; +static double naccess_DC_atom_radius[] = {1.80, 1.80, 1.80, 1.80, 1.40, 1.60, 1.60, 1.60, }; +static int naccess_DC_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_DC_cfg = { + 8, + "DC", + (char**) naccess_DC_atom_name, + (double*) naccess_DC_atom_radius, + (freesasa_atom_class*) naccess_DC_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_DG_atom_name[] = {"C8", "N3", "N1", "N2", "C2", "C6", "C4", "C5", "N9", "N7", "O6", }; +static double naccess_DG_atom_radius[] = {1.80, 1.60, 1.60, 1.60, 1.80, 1.80, 1.80, 1.80, 1.60, 1.60, 1.40, }; +static int naccess_DG_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_DG_cfg = { + 11, + "DG", + (char**) naccess_DG_atom_name, + (double*) naccess_DG_atom_radius, + (freesasa_atom_class*) naccess_DG_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_DI_atom_name[] = {"N7", "N9", "C5", "O6", "C2", "C4", "C6", "N1", "C8", "N3", }; +static double naccess_DI_atom_radius[] = {1.60, 1.60, 1.80, 1.40, 1.80, 1.80, 1.80, 1.60, 1.80, 1.60, }; +static int naccess_DI_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_DI_cfg = { + 10, + "DI", + (char**) naccess_DI_atom_name, + (double*) naccess_DI_atom_radius, + (freesasa_atom_class*) naccess_DI_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_DT_atom_name[] = {"C7", "N3", "O2", "N1", "C2", "O4", "C6", "C4", "C5", }; +static double naccess_DT_atom_radius[] = {1.80, 1.60, 1.40, 1.60, 1.80, 1.40, 1.80, 1.80, 1.80, }; +static int naccess_DT_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_DT_cfg = { + 9, + "DT", + (char**) naccess_DT_atom_name, + (double*) naccess_DT_atom_radius, + (freesasa_atom_class*) naccess_DT_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_DU_atom_name[] = {"N3", "O2", "N1", "C6", "C4", "O4", "C2", "C5", }; +static double naccess_DU_atom_radius[] = {1.60, 1.40, 1.60, 1.80, 1.80, 1.40, 1.80, 1.80, }; +static int naccess_DU_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_DU_cfg = { + 8, + "DU", + (char**) naccess_DU_atom_name, + (double*) naccess_DU_atom_radius, + (freesasa_atom_class*) naccess_DU_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_G_atom_name[] = {"N2", "C2", "C6", "C4", "N9", "N7", "C5", "O6", "C8", "N3", "N1", }; +static double naccess_G_atom_radius[] = {1.60, 1.80, 1.80, 1.80, 1.60, 1.60, 1.80, 1.40, 1.80, 1.60, 1.60, }; +static int naccess_G_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_G_cfg = { + 11, + "G", + (char**) naccess_G_atom_name, + (double*) naccess_G_atom_radius, + (freesasa_atom_class*) naccess_G_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_GLN_atom_name[] = {"NE2", "OE1", "CD", "CG", }; +static double naccess_GLN_atom_radius[] = {1.65, 1.40, 1.76, 1.87, }; +static int naccess_GLN_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_GLN_cfg = { + 4, + "GLN", + (char**) naccess_GLN_atom_name, + (double*) naccess_GLN_atom_radius, + (freesasa_atom_class*) naccess_GLN_atom_class, + {"GLN", 178.24, 41.72, 136.52, 126.35, 51.89, 0}, +}; + +static const char *naccess_GLU_atom_name[] = {"OE2", "OE1", "CD", "CG", }; +static double naccess_GLU_atom_radius[] = {1.40, 1.40, 1.76, 1.87, }; +static int naccess_GLU_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_GLU_cfg = { + 4, + "GLU", + (char**) naccess_GLU_atom_name, + (double*) naccess_GLU_atom_radius, + (freesasa_atom_class*) naccess_GLU_atom_class, + {"GLU", 172.09, 41.72, 130.37, 112.13, 59.96, 0}, +}; + +static const char *naccess_GLY_atom_name[] = {"CA", }; +static double naccess_GLY_atom_radius[] = {1.87, }; +static int naccess_GLY_atom_class[] = {FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_GLY_cfg = { + 1, + "GLY", + (char**) naccess_GLY_atom_name, + (double*) naccess_GLY_atom_radius, + (freesasa_atom_class*) naccess_GLY_atom_class, + {"GLY", 80.30, 80.30, 0.00, 42.62, 37.69, 0}, +}; + +static const char *naccess_HIS_atom_name[] = {"CG", "NE2", "CE1", "ND1", "CD2", }; +static double naccess_HIS_atom_radius[] = {1.76, 1.65, 1.76, 1.65, 1.76, }; +static int naccess_HIS_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_HIS_cfg = { + 5, + "HIS", + (char**) naccess_HIS_atom_name, + (double*) naccess_HIS_atom_radius, + (freesasa_atom_class*) naccess_HIS_atom_class, + {"HIS", 182.75, 38.76, 143.99, 85.61, 97.14, 0}, +}; + +static const char *naccess_I_atom_name[] = {"N3", "C8", "N1", "C4", "C6", "C2", "O6", "C5", "N7", "N9", }; +static double naccess_I_atom_radius[] = {1.60, 1.80, 1.60, 1.80, 1.80, 1.80, 1.40, 1.80, 1.60, 1.60, }; +static int naccess_I_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_I_cfg = { + 10, + "I", + (char**) naccess_I_atom_name, + (double*) naccess_I_atom_radius, + (freesasa_atom_class*) naccess_I_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_ILE_atom_name[] = {"CG1", "CG2", "CD1", }; +static double naccess_ILE_atom_radius[] = {1.87, 1.87, 1.87, }; +static int naccess_ILE_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_ILE_cfg = { + 3, + "ILE", + (char**) naccess_ILE_atom_name, + (double*) naccess_ILE_atom_radius, + (freesasa_atom_class*) naccess_ILE_atom_class, + {"ILE", 175.10, 41.16, 133.94, 36.10, 139.00, 0}, +}; + +static const char *naccess_LEU_atom_name[] = {"CD2", "CD1", "CG", }; +static double naccess_LEU_atom_radius[] = {1.87, 1.87, 1.87, }; +static int naccess_LEU_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_LEU_cfg = { + 3, + "LEU", + (char**) naccess_LEU_atom_name, + (double*) naccess_LEU_atom_radius, + (freesasa_atom_class*) naccess_LEU_atom_class, + {"LEU", 178.40, 39.50, 138.90, 36.45, 141.95, 0}, +}; + +static const char *naccess_LYS_atom_name[] = {"CD", "NZ", "CE", "CG", }; +static double naccess_LYS_atom_radius[] = {1.87, 1.50, 1.87, 1.87, }; +static int naccess_LYS_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_LYS_cfg = { + 4, + "LYS", + (char**) naccess_LYS_atom_name, + (double*) naccess_LYS_atom_radius, + (freesasa_atom_class*) naccess_LYS_atom_class, + {"LYS", 200.21, 41.72, 158.49, 84.31, 115.90, 0}, +}; + +static const char *naccess_MET_atom_name[] = {"CE", "CG", "SD", }; +static double naccess_MET_atom_radius[] = {1.87, 1.87, 1.85, }; +static int naccess_MET_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_MET_cfg = { + 3, + "MET", + (char**) naccess_MET_atom_name, + (double*) naccess_MET_atom_radius, + (freesasa_atom_class*) naccess_MET_atom_class, + {"MET", 193.72, 41.72, 152.00, 36.45, 157.27, 0}, +}; + +static const char *naccess_MSE_atom_name[] = {"SE", }; +static double naccess_MSE_atom_radius[] = {1.80, }; +static int naccess_MSE_atom_class[] = {FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_MSE_cfg = { + 1, + "MSE", + (char**) naccess_MSE_atom_name, + (double*) naccess_MSE_atom_radius, + (freesasa_atom_class*) naccess_MSE_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_PHE_atom_name[] = {"CG", "CD1", "CE2", "CE1", "CZ", "CD2", }; +static double naccess_PHE_atom_radius[] = {1.76, 1.76, 1.76, 1.76, 1.76, 1.76, }; +static int naccess_PHE_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_PHE_cfg = { + 6, + "PHE", + (char**) naccess_PHE_atom_name, + (double*) naccess_PHE_atom_radius, + (freesasa_atom_class*) naccess_PHE_atom_class, + {"PHE", 199.40, 38.12, 161.27, 34.25, 165.14, 0}, +}; + +static const char *naccess_PRO_atom_name[] = {"CG", "CD", }; +static double naccess_PRO_atom_radius[] = {1.87, 1.87, }; +static int naccess_PRO_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_PRO_cfg = { + 2, + "PRO", + (char**) naccess_PRO_atom_name, + (double*) naccess_PRO_atom_radius, + (freesasa_atom_class*) naccess_PRO_atom_class, + {"PRO", 135.84, 27.09, 108.76, 15.17, 120.67, 0}, +}; + +static const char *naccess_SEC_atom_name[] = {"SE", }; +static double naccess_SEC_atom_radius[] = {1.80, }; +static int naccess_SEC_atom_class[] = {FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_SEC_cfg = { + 1, + "SEC", + (char**) naccess_SEC_atom_name, + (double*) naccess_SEC_atom_radius, + (freesasa_atom_class*) naccess_SEC_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_SER_atom_name[] = {"OG", }; +static double naccess_SER_atom_radius[] = {1.40, }; +static int naccess_SER_atom_class[] = {FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_SER_cfg = { + 1, + "SER", + (char**) naccess_SER_atom_name, + (double*) naccess_SER_atom_radius, + (freesasa_atom_class*) naccess_SER_atom_class, + {"SER", 116.56, 43.38, 73.18, 68.03, 48.53, 0}, +}; + +static const char *naccess_T_atom_name[] = {"C4", "C6", "O4", "C2", "C5", "N3", "C7", "O2", "N1", }; +static double naccess_T_atom_radius[] = {1.80, 1.80, 1.40, 1.80, 1.80, 1.60, 1.80, 1.40, 1.60, }; +static int naccess_T_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_T_cfg = { + 9, + "T", + (char**) naccess_T_atom_name, + (double*) naccess_T_atom_radius, + (freesasa_atom_class*) naccess_T_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_THR_atom_name[] = {"CG2", "OG1", }; +static double naccess_THR_atom_radius[] = {1.87, 1.40, }; +static int naccess_THR_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_THR_cfg = { + 2, + "THR", + (char**) naccess_THR_atom_name, + (double*) naccess_THR_atom_radius, + (freesasa_atom_class*) naccess_THR_atom_class, + {"THR", 139.25, 41.70, 97.55, 63.50, 75.75, 0}, +}; + +static const char *naccess_TRP_atom_name[] = {"CD1", "CZ2", "CE2", "NE1", "CG", "CE3", "CH2", "CZ3", "CD2", }; +static double naccess_TRP_atom_radius[] = {1.76, 1.76, 1.76, 1.65, 1.76, 1.76, 1.76, 1.76, 1.76, }; +static int naccess_TRP_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_TRP_cfg = { + 9, + "TRP", + (char**) naccess_TRP_atom_name, + (double*) naccess_TRP_atom_radius, + (freesasa_atom_class*) naccess_TRP_atom_class, + {"TRP", 248.97, 42.38, 206.59, 59.83, 189.14, 0}, +}; + +static const char *naccess_TYR_atom_name[] = {"CG", "CZ", "CE1", "CE2", "CD1", "OH", "CD2", }; +static double naccess_TYR_atom_radius[] = {1.76, 1.76, 1.76, 1.76, 1.76, 1.40, 1.76, }; +static int naccess_TYR_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_TYR_cfg = { + 7, + "TYR", + (char**) naccess_TYR_atom_name, + (double*) naccess_TYR_atom_radius, + (freesasa_atom_class*) naccess_TYR_atom_class, + {"TYR", 212.23, 38.13, 174.10, 76.34, 135.89, 0}, +}; + +static const char *naccess_U_atom_name[] = {"C2", "C4", "C6", "O4", "C5", "N3", "O2", "N1", }; +static double naccess_U_atom_radius[] = {1.80, 1.80, 1.80, 1.40, 1.80, 1.60, 1.40, 1.60, }; +static int naccess_U_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue naccess_U_cfg = { + 8, + "U", + (char**) naccess_U_atom_name, + (double*) naccess_U_atom_radius, + (freesasa_atom_class*) naccess_U_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *naccess_VAL_atom_name[] = {"CG2", "CG1", }; +static double naccess_VAL_atom_radius[] = {1.87, 1.87, }; +static int naccess_VAL_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue naccess_VAL_cfg = { + 2, + "VAL", + (char**) naccess_VAL_atom_name, + (double*) naccess_VAL_atom_radius, + (freesasa_atom_class*) naccess_VAL_atom_class, + {"VAL", 151.40, 41.17, 110.23, 36.12, 115.28, 0}, +}; + +static struct classifier_residue *naccess_residue_cfg[] = { + &naccess_A_cfg, &naccess_ALA_cfg, &naccess_ANY_cfg, &naccess_ARG_cfg, &naccess_ASN_cfg, &naccess_ASP_cfg, &naccess_C_cfg, &naccess_CYS_cfg, &naccess_DA_cfg, &naccess_DC_cfg, &naccess_DG_cfg, &naccess_DI_cfg, &naccess_DT_cfg, &naccess_DU_cfg, &naccess_G_cfg, &naccess_GLN_cfg, &naccess_GLU_cfg, &naccess_GLY_cfg, &naccess_HIS_cfg, &naccess_I_cfg, &naccess_ILE_cfg, &naccess_LEU_cfg, &naccess_LYS_cfg, &naccess_MET_cfg, &naccess_MSE_cfg, &naccess_PHE_cfg, &naccess_PRO_cfg, &naccess_SEC_cfg, &naccess_SER_cfg, &naccess_T_cfg, &naccess_THR_cfg, &naccess_TRP_cfg, &naccess_TYR_cfg, &naccess_U_cfg, &naccess_VAL_cfg, }; + +const freesasa_classifier freesasa_naccess_classifier = { + 35, (char**) naccess_residue_name, + "NACCESS", + (struct classifier_residue **) naccess_residue_cfg, +}; + diff --git a/.venv_haddock/include/site/python3.12/freesasa/classifier_oons.c b/.venv_haddock/include/site/python3.12/freesasa/classifier_oons.c new file mode 100644 index 0000000000000000000000000000000000000000..675f39e29c0e5053fdbc1036c0ca9592764f58a3 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/classifier_oons.c @@ -0,0 +1,350 @@ +#include "classifier.h" + +/* Autogenerated code from the script config2c.pl */ + +static const char *oons_residue_name[] = {"ACE", "ANY", "ARG", "ASN", "ASP", "ASX", "CSE", "CYS", "GLN", "GLU", "GLX", "HIS", "HOH", "ILE", "LEU", "LYS", "MET", "MSE", "NH2", "PHE", "PRO", "PYL", "SEC", "SER", "THR", "TRP", "TYR", "VAL", }; +static const char *oons_ACE_atom_name[] = {"CH3", }; +static double oons_ACE_atom_radius[] = {2.00, }; +static int oons_ACE_atom_class[] = {FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_ACE_cfg = { + 1, + "ACE", + (char**) oons_ACE_atom_name, + (double*) oons_ACE_atom_radius, + (freesasa_atom_class*) oons_ACE_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *oons_ANY_atom_name[] = {"N3", "O2", "N4", "N7", "CM2", "N9", "C5'", "C3'", "C1'", "C7", "OXT", "OP3", "C2", "C4'", "C5", "C8", "N1", "OP2", "C4", "N6", "C", "CB", "N2", "P", "OP1", "O2'", "O6", "O4'", "O5'", "O", "C2'", "CA", "O4", "O3'", "C6", "N", }; +static double oons_ANY_atom_radius[] = {1.55, 1.40, 1.55, 1.55, 2.00, 1.55, 2.00, 1.75, 1.75, 1.75, 1.40, 1.40, 1.75, 1.75, 1.75, 1.75, 1.55, 1.40, 1.75, 1.55, 1.55, 2.00, 1.55, 1.80, 1.40, 1.40, 1.40, 1.40, 1.40, 1.40, 1.75, 2.00, 1.40, 1.40, 1.75, 1.55, }; +static int oons_ANY_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue oons_ANY_cfg = { + 36, + "ANY", + (char**) oons_ANY_atom_name, + (double*) oons_ANY_atom_radius, + (freesasa_atom_class*) oons_ANY_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *oons_ARG_atom_name[] = {"NH1", "NH2", "CZ", "CD", "CG", "NE", }; +static double oons_ARG_atom_radius[] = {1.55, 1.55, 2.00, 2.00, 2.00, 1.55, }; +static int oons_ARG_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue oons_ARG_cfg = { + 6, + "ARG", + (char**) oons_ARG_atom_name, + (double*) oons_ARG_atom_radius, + (freesasa_atom_class*) oons_ARG_atom_class, + {"ARG", 235.30, 38.31, 196.99, 125.27, 110.03, 0}, +}; + +static const char *oons_ASN_atom_name[] = {"ND2", "OD1", "CG", }; +static double oons_ASN_atom_radius[] = {1.55, 1.40, 1.55, }; +static int oons_ASN_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue oons_ASN_cfg = { + 3, + "ASN", + (char**) oons_ASN_atom_name, + (double*) oons_ASN_atom_radius, + (freesasa_atom_class*) oons_ASN_atom_class, + {"ASN", 143.47, 38.26, 105.21, 97.51, 45.97, 0}, +}; + +static const char *oons_ASP_atom_name[] = {"OD1", "CG", "OD2", }; +static double oons_ASP_atom_radius[] = {1.40, 1.55, 1.40, }; +static int oons_ASP_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue oons_ASP_cfg = { + 3, + "ASP", + (char**) oons_ASP_atom_name, + (double*) oons_ASP_atom_radius, + (freesasa_atom_class*) oons_ASP_atom_class, + {"ASP", 141.20, 38.87, 102.33, 95.17, 46.03, 0}, +}; + +static const char *oons_ASX_atom_name[] = {"XD1", "AD2", "XD2", "AD1", "CG", }; +static double oons_ASX_atom_radius[] = {1.5, 1.5, 1.5, 1.5, 1.55, }; +static int oons_ASX_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue oons_ASX_cfg = { + 5, + "ASX", + (char**) oons_ASX_atom_name, + (double*) oons_ASX_atom_radius, + (freesasa_atom_class*) oons_ASX_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *oons_CSE_atom_name[] = {"SE", }; +static double oons_CSE_atom_radius[] = {1.90, }; +static int oons_CSE_atom_class[] = {FREESASA_ATOM_POLAR, }; +static struct classifier_residue oons_CSE_cfg = { + 1, + "CSE", + (char**) oons_CSE_atom_name, + (double*) oons_CSE_atom_radius, + (freesasa_atom_class*) oons_CSE_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *oons_CYS_atom_name[] = {"SG", }; +static double oons_CYS_atom_radius[] = {2.00, }; +static int oons_CYS_atom_class[] = {FREESASA_ATOM_POLAR, }; +static struct classifier_residue oons_CYS_cfg = { + 1, + "CYS", + (char**) oons_CYS_atom_name, + (double*) oons_CYS_atom_radius, + (freesasa_atom_class*) oons_CYS_atom_class, + {"CYS", 140.29, 38.44, 101.85, 98.30, 41.99, 0}, +}; + +static const char *oons_GLN_atom_name[] = {"CD", "NE2", "OE1", "CG", }; +static double oons_GLN_atom_radius[] = {1.55, 1.55, 1.40, 2.00, }; +static int oons_GLN_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_GLN_cfg = { + 4, + "GLN", + (char**) oons_GLN_atom_name, + (double*) oons_GLN_atom_radius, + (freesasa_atom_class*) oons_GLN_atom_class, + {"GLN", 176.23, 38.31, 137.92, 122.17, 54.06, 0}, +}; + +static const char *oons_GLU_atom_name[] = {"CD", "OE1", "CG", "OE2", }; +static double oons_GLU_atom_radius[] = {1.55, 1.40, 2.00, 1.40, }; +static int oons_GLU_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue oons_GLU_cfg = { + 4, + "GLU", + (char**) oons_GLU_atom_name, + (double*) oons_GLU_atom_radius, + (freesasa_atom_class*) oons_GLU_atom_class, + {"GLU", 172.43, 38.31, 134.11, 115.92, 56.51, 0}, +}; + +static const char *oons_GLX_atom_name[] = {"XE1", "AE1", "AE2", "CD", "XE2", "CG", }; +static double oons_GLX_atom_radius[] = {1.5, 1.5, 1.5, 1.55, 1.5, 2.00, }; +static int oons_GLX_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_GLX_cfg = { + 6, + "GLX", + (char**) oons_GLX_atom_name, + (double*) oons_GLX_atom_radius, + (freesasa_atom_class*) oons_GLX_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *oons_HIS_atom_name[] = {"ND1", "CE1", "NE2", "CG", "CD2", }; +static double oons_HIS_atom_radius[] = {1.55, 1.75, 1.55, 1.75, 1.75, }; +static int oons_HIS_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_HIS_cfg = { + 5, + "HIS", + (char**) oons_HIS_atom_name, + (double*) oons_HIS_atom_radius, + (freesasa_atom_class*) oons_HIS_atom_class, + {"HIS", 180.78, 36.04, 144.74, 73.26, 107.52, 0}, +}; + +static const char *oons_HOH_atom_name[] = {"O", }; +static double oons_HOH_atom_radius[] = {1.40, }; +static int oons_HOH_atom_class[] = {FREESASA_ATOM_POLAR, }; +static struct classifier_residue oons_HOH_cfg = { + 1, + "HOH", + (char**) oons_HOH_atom_name, + (double*) oons_HOH_atom_radius, + (freesasa_atom_class*) oons_HOH_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *oons_ILE_atom_name[] = {"CG1", "CG2", "CD1", }; +static double oons_ILE_atom_radius[] = {2.00, 2.00, 2.00, }; +static int oons_ILE_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_ILE_cfg = { + 3, + "ILE", + (char**) oons_ILE_atom_name, + (double*) oons_ILE_atom_radius, + (freesasa_atom_class*) oons_ILE_atom_class, + {"ILE", 182.12, 37.96, 144.16, 31.67, 150.45, 0}, +}; + +static const char *oons_LEU_atom_name[] = {"CD1", "CG", "CD2", }; +static double oons_LEU_atom_radius[] = {2.00, 2.00, 2.00, }; +static int oons_LEU_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_LEU_cfg = { + 3, + "LEU", + (char**) oons_LEU_atom_name, + (double*) oons_LEU_atom_radius, + (freesasa_atom_class*) oons_LEU_atom_class, + {"LEU", 185.43, 35.34, 150.08, 31.73, 153.69, 0}, +}; + +static const char *oons_LYS_atom_name[] = {"NZ", "CE", "CG", "CD", }; +static double oons_LYS_atom_radius[] = {1.55, 2.00, 2.00, 2.00, }; +static int oons_LYS_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_LYS_cfg = { + 4, + "LYS", + (char**) oons_LYS_atom_name, + (double*) oons_LYS_atom_radius, + (freesasa_atom_class*) oons_LYS_atom_class, + {"LYS", 205.80, 38.31, 167.49, 78.02, 127.78, 0}, +}; + +static const char *oons_MET_atom_name[] = {"CE", "SD", "CG", }; +static double oons_MET_atom_radius[] = {2.00, 2.00, 2.00, }; +static int oons_MET_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_MET_cfg = { + 3, + "MET", + (char**) oons_MET_atom_name, + (double*) oons_MET_atom_radius, + (freesasa_atom_class*) oons_MET_atom_class, + {"MET", 201.66, 38.31, 163.35, 78.68, 122.98, 0}, +}; + +static const char *oons_MSE_atom_name[] = {"CE", "SE", "CG", }; +static double oons_MSE_atom_radius[] = {2.00, 1.90, 2.00, }; +static int oons_MSE_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_MSE_cfg = { + 3, + "MSE", + (char**) oons_MSE_atom_name, + (double*) oons_MSE_atom_radius, + (freesasa_atom_class*) oons_MSE_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *oons_NH2_atom_name[] = {"NH2", }; +static double oons_NH2_atom_radius[] = {1.55, }; +static int oons_NH2_atom_class[] = {FREESASA_ATOM_POLAR, }; +static struct classifier_residue oons_NH2_cfg = { + 1, + "NH2", + (char**) oons_NH2_atom_name, + (double*) oons_NH2_atom_radius, + (freesasa_atom_class*) oons_NH2_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *oons_PHE_atom_name[] = {"CD1", "CZ", "CG", "CD2", "CE2", "CE1", }; +static double oons_PHE_atom_radius[] = {1.75, 1.75, 1.75, 1.75, 1.75, 1.75, }; +static int oons_PHE_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_PHE_cfg = { + 6, + "PHE", + (char**) oons_PHE_atom_name, + (double*) oons_PHE_atom_radius, + (freesasa_atom_class*) oons_PHE_atom_class, + {"PHE", 199.28, 35.20, 164.08, 30.08, 169.20, 0}, +}; + +static const char *oons_PRO_atom_name[] = {"CD", "CG", "CB", }; +static double oons_PRO_atom_radius[] = {1.75, 1.75, 1.75, }; +static int oons_PRO_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_PRO_cfg = { + 3, + "PRO", + (char**) oons_PRO_atom_name, + (double*) oons_PRO_atom_radius, + (freesasa_atom_class*) oons_PRO_atom_class, + {"PRO", 128.18, 31.08, 97.10, 13.95, 114.23, 0}, +}; + +static const char *oons_PYL_atom_name[] = {"CD2", "CG2", "O2", "CA2", "CE2", "C2", "CG", "CD", "N2", "NZ", "CE", "CB2", }; +static double oons_PYL_atom_radius[] = {1.75, 1.75, 1.40, 1.75, 1.75, 1.55, 2.00, 2.00, 1.55, 1.55, 2.00, 2.00, }; +static int oons_PYL_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_PYL_cfg = { + 12, + "PYL", + (char**) oons_PYL_atom_name, + (double*) oons_PYL_atom_radius, + (freesasa_atom_class*) oons_PYL_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *oons_SEC_atom_name[] = {"SE", }; +static double oons_SEC_atom_radius[] = {1.90, }; +static int oons_SEC_atom_class[] = {FREESASA_ATOM_POLAR, }; +static struct classifier_residue oons_SEC_cfg = { + 1, + "SEC", + (char**) oons_SEC_atom_name, + (double*) oons_SEC_atom_radius, + (freesasa_atom_class*) oons_SEC_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *oons_SER_atom_name[] = {"OG", }; +static double oons_SER_atom_radius[] = {1.40, }; +static int oons_SER_atom_class[] = {FREESASA_ATOM_POLAR, }; +static struct classifier_residue oons_SER_cfg = { + 1, + "SER", + (char**) oons_SER_atom_name, + (double*) oons_SER_atom_radius, + (freesasa_atom_class*) oons_SER_atom_class, + {"SER", 118.43, 40.20, 78.23, 60.41, 58.02, 0}, +}; + +static const char *oons_THR_atom_name[] = {"OG1", "CG2", }; +static double oons_THR_atom_radius[] = {1.40, 2.00, }; +static int oons_THR_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_THR_cfg = { + 2, + "THR", + (char**) oons_THR_atom_name, + (double*) oons_THR_atom_radius, + (freesasa_atom_class*) oons_THR_atom_class, + {"THR", 142.41, 38.32, 104.08, 56.42, 85.99, 0}, +}; + +static const char *oons_TRP_atom_name[] = {"CD2", "CE3", "CE2", "CH2", "CD1", "CZ3", "CZ2", "NE1", "CG", }; +static double oons_TRP_atom_radius[] = {1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.75, 1.55, 1.75, }; +static int oons_TRP_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_TRP_cfg = { + 9, + "TRP", + (char**) oons_TRP_atom_name, + (double*) oons_TRP_atom_radius, + (freesasa_atom_class*) oons_TRP_atom_class, + {"TRP", 247.08, 39.43, 207.65, 52.90, 194.18, 0}, +}; + +static const char *oons_TYR_atom_name[] = {"CG", "CD2", "CD1", "CZ", "CE1", "OH", "CE2", }; +static double oons_TYR_atom_radius[] = {1.75, 1.75, 1.75, 1.75, 1.75, 1.40, 1.75, }; +static int oons_TYR_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_TYR_cfg = { + 7, + "TYR", + (char**) oons_TYR_atom_name, + (double*) oons_TYR_atom_radius, + (freesasa_atom_class*) oons_TYR_atom_class, + {"TYR", 212.31, 35.20, 177.11, 72.41, 139.90, 0}, +}; + +static const char *oons_VAL_atom_name[] = {"CG1", "CG2", }; +static double oons_VAL_atom_radius[] = {2.00, 2.00, }; +static int oons_VAL_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue oons_VAL_cfg = { + 2, + "VAL", + (char**) oons_VAL_atom_name, + (double*) oons_VAL_atom_radius, + (freesasa_atom_class*) oons_VAL_atom_class, + {"VAL", 157.64, 37.96, 119.68, 31.70, 125.94, 0}, +}; + +static struct classifier_residue *oons_residue_cfg[] = { + &oons_ACE_cfg, &oons_ANY_cfg, &oons_ARG_cfg, &oons_ASN_cfg, &oons_ASP_cfg, &oons_ASX_cfg, &oons_CSE_cfg, &oons_CYS_cfg, &oons_GLN_cfg, &oons_GLU_cfg, &oons_GLX_cfg, &oons_HIS_cfg, &oons_HOH_cfg, &oons_ILE_cfg, &oons_LEU_cfg, &oons_LYS_cfg, &oons_MET_cfg, &oons_MSE_cfg, &oons_NH2_cfg, &oons_PHE_cfg, &oons_PRO_cfg, &oons_PYL_cfg, &oons_SEC_cfg, &oons_SER_cfg, &oons_THR_cfg, &oons_TRP_cfg, &oons_TYR_cfg, &oons_VAL_cfg, }; + +const freesasa_classifier freesasa_oons_classifier = { + 28, (char**) oons_residue_name, + "OONS", + (struct classifier_residue **) oons_residue_cfg, +}; + diff --git a/.venv_haddock/include/site/python3.12/freesasa/classifier_protor.c b/.venv_haddock/include/site/python3.12/freesasa/classifier_protor.c new file mode 100644 index 0000000000000000000000000000000000000000..ce4b87ab93c69bd8bba1b9e01f90fab3f20f1a28 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/classifier_protor.c @@ -0,0 +1,494 @@ +#include "classifier.h" + +/* Autogenerated code from the script config2c.pl */ + +static const char *protor_residue_name[] = {"A", "ACE", "ALA", "ARG", "ASN", "ASP", "ASX", "C", "CYS", "DA", "DC", "DG", "DI", "DT", "DU", "G", "GLN", "GLU", "GLX", "GLY", "HIS", "HOH", "I", "ILE", "LEU", "LYS", "MET", "MSE", "NH2", "PHE", "PRO", "PYL", "SEC", "SER", "T", "THR", "TRP", "TYR", "U", "VAL", }; +static const char *protor_A_atom_name[] = {"C6", "O2'", "C2'", "OP1", "C5", "C4", "O3'", "OP3", "P", "C4'", "O4'", "C3'", "C8", "N6", "N9", "O5'", "N7", "OP2", "C5'", "N3", "C1'", "N1", "C2", }; +static double protor_A_atom_radius[] = {1.61, 1.46, 1.88, 1.42, 1.61, 1.61, 1.46, 1.46, 1.8, 1.88, 1.46, 1.88, 1.76, 1.64, 1.64, 1.46, 1.64, 1.46, 1.88, 1.64, 1.88, 1.64, 1.76, }; +static int protor_A_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_A_cfg = { + 23, + "A", + (char**) protor_A_atom_name, + (double*) protor_A_atom_radius, + (freesasa_atom_class*) protor_A_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_ACE_atom_name[] = {"O", "CH3", "C", }; +static double protor_ACE_atom_radius[] = {1.42, 1.88, 1.76, }; +static int protor_ACE_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_ACE_cfg = { + 3, + "ACE", + (char**) protor_ACE_atom_name, + (double*) protor_ACE_atom_radius, + (freesasa_atom_class*) protor_ACE_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_ALA_atom_name[] = {"N", "CB", "CA", "C", "O", "OXT", }; +static double protor_ALA_atom_radius[] = {1.64, 1.88, 1.88, 1.61, 1.42, 1.46, }; +static int protor_ALA_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_ALA_cfg = { + 6, + "ALA", + (char**) protor_ALA_atom_name, + (double*) protor_ALA_atom_radius, + (freesasa_atom_class*) protor_ALA_atom_class, + {"ALA", 108.76, 43.96, 64.80, 37.75, 71.01, 0}, +}; + +static const char *protor_ARG_atom_name[] = {"C", "CA", "CB", "NH1", "OXT", "CZ", "CG", "O", "NE", "CD", "N", "NH2", }; +static double protor_ARG_atom_radius[] = {1.61, 1.88, 1.88, 1.64, 1.46, 1.61, 1.88, 1.42, 1.64, 1.88, 1.64, 1.64, }; +static int protor_ARG_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_ARG_cfg = { + 12, + "ARG", + (char**) protor_ARG_atom_name, + (double*) protor_ARG_atom_radius, + (freesasa_atom_class*) protor_ARG_atom_class, + {"ARG", 238.17, 42.00, 196.17, 165.00, 73.17, 0}, +}; + +static const char *protor_ASN_atom_name[] = {"N", "CA", "CB", "C", "OD1", "O", "CG", "OXT", "ND2", }; +static double protor_ASN_atom_radius[] = {1.64, 1.88, 1.88, 1.61, 1.42, 1.42, 1.61, 1.46, 1.64, }; +static int protor_ASN_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_ASN_cfg = { + 9, + "ASN", + (char**) protor_ASN_atom_name, + (double*) protor_ASN_atom_radius, + (freesasa_atom_class*) protor_ASN_atom_class, + {"ASN", 145.01, 41.53, 103.48, 103.46, 41.55, 0}, +}; + +static const char *protor_ASP_atom_name[] = {"OD2", "N", "CG", "O", "OXT", "CA", "CB", "C", "OD1", }; +static double protor_ASP_atom_radius[] = {1.46, 1.64, 1.61, 1.42, 1.46, 1.88, 1.88, 1.61, 1.42, }; +static int protor_ASP_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_ASP_cfg = { + 9, + "ASP", + (char**) protor_ASP_atom_name, + (double*) protor_ASP_atom_radius, + (freesasa_atom_class*) protor_ASP_atom_class, + {"ASP", 142.76, 42.29, 100.47, 100.27, 42.49, 0}, +}; + +static const char *protor_ASX_atom_name[] = {"XD2", "N", "O", "CG", "OXT", "CA", "CB", "XD1", "C", }; +static double protor_ASX_atom_radius[] = {1.5, 1.64, 1.42, 1.61, 1.46, 1.88, 1.88, 1.5, 1.61, }; +static int protor_ASX_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_ASX_cfg = { + 9, + "ASX", + (char**) protor_ASX_atom_name, + (double*) protor_ASX_atom_radius, + (freesasa_atom_class*) protor_ASX_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_C_atom_name[] = {"C2", "N1", "N3", "C1'", "C5'", "OP2", "O5'", "C3'", "O4'", "P", "C4'", "O2", "N4", "OP3", "O3'", "C4", "C5", "OP1", "C2'", "O2'", "C6", }; +static double protor_C_atom_radius[] = {1.61, 1.64, 1.64, 1.88, 1.88, 1.46, 1.46, 1.88, 1.46, 1.8, 1.88, 1.42, 1.64, 1.46, 1.46, 1.61, 1.76, 1.42, 1.88, 1.46, 1.76, }; +static int protor_C_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_C_cfg = { + 21, + "C", + (char**) protor_C_atom_name, + (double*) protor_C_atom_radius, + (freesasa_atom_class*) protor_C_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_CYS_atom_name[] = {"O", "OXT", "SG", "CA", "CB", "C", "N", }; +static double protor_CYS_atom_radius[] = {1.42, 1.46, 1.77, 1.88, 1.88, 1.61, 1.64, }; +static int protor_CYS_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_CYS_cfg = { + 7, + "CYS", + (char**) protor_CYS_atom_name, + (double*) protor_CYS_atom_radius, + (freesasa_atom_class*) protor_CYS_atom_class, + {"CYS", 132.20, 42.55, 89.66, 92.74, 39.47, 0}, +}; + +static const char *protor_DA_atom_name[] = {"OP2", "C5'", "C1'", "N3", "N1", "C2", "N6", "N9", "O5'", "N7", "C3'", "C8", "OP3", "C4'", "P", "O4'", "C4", "O3'", "C5", "OP1", "C6", "C2'", }; +static double protor_DA_atom_radius[] = {1.46, 1.88, 1.88, 1.64, 1.64, 1.76, 1.64, 1.64, 1.46, 1.64, 1.88, 1.76, 1.46, 1.88, 1.8, 1.46, 1.61, 1.46, 1.61, 1.42, 1.61, 1.88, }; +static int protor_DA_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_DA_cfg = { + 22, + "DA", + (char**) protor_DA_atom_name, + (double*) protor_DA_atom_radius, + (freesasa_atom_class*) protor_DA_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_DC_atom_name[] = {"C5", "C4", "O3'", "C6", "C2'", "OP1", "O5'", "C5'", "OP2", "C2", "C1'", "N3", "N1", "C4'", "P", "N4", "O2", "OP3", "O4'", "C3'", }; +static double protor_DC_atom_radius[] = {1.76, 1.61, 1.46, 1.76, 1.88, 1.42, 1.46, 1.88, 1.46, 1.61, 1.88, 1.64, 1.64, 1.88, 1.8, 1.64, 1.42, 1.46, 1.46, 1.88, }; +static int protor_DC_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_DC_cfg = { + 20, + "DC", + (char**) protor_DC_atom_name, + (double*) protor_DC_atom_radius, + (freesasa_atom_class*) protor_DC_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_DG_atom_name[] = {"C8", "C3'", "N2", "P", "C4'", "OP3", "O4'", "C5'", "OP2", "C2", "C1'", "N3", "N1", "O5'", "N9", "N7", "O6", "OP1", "C6", "C2'", "C4", "O3'", "C5", }; +static double protor_DG_atom_radius[] = {1.76, 1.88, 1.64, 1.8, 1.88, 1.46, 1.46, 1.88, 1.46, 1.61, 1.88, 1.64, 1.64, 1.46, 1.64, 1.64, 1.42, 1.42, 1.61, 1.88, 1.61, 1.46, 1.61, }; +static int protor_DG_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_DG_cfg = { + 23, + "DG", + (char**) protor_DG_atom_name, + (double*) protor_DG_atom_radius, + (freesasa_atom_class*) protor_DG_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_DI_atom_name[] = {"N3", "N1", "C1'", "C2", "OP2", "C5'", "N7", "N9", "O5'", "C3'", "C8", "O4'", "OP3", "C4'", "P", "O3'", "C4", "C5", "OP1", "O6", "C2'", "C6", }; +static double protor_DI_atom_radius[] = {1.64, 1.64, 1.88, 1.76, 1.46, 1.88, 1.64, 1.64, 1.46, 1.88, 1.76, 1.46, 1.46, 1.88, 1.8, 1.46, 1.61, 1.61, 1.42, 1.42, 1.88, 1.61, }; +static int protor_DI_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_DI_cfg = { + 22, + "DI", + (char**) protor_DI_atom_name, + (double*) protor_DI_atom_radius, + (freesasa_atom_class*) protor_DI_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_DT_atom_name[] = {"OP2", "C5'", "N3", "C1'", "N1", "C2", "O5'", "C3'", "O4", "OP3", "O2", "P", "C4'", "O4'", "C4", "O3'", "C5", "C7", "OP1", "C6", "C2'", }; +static double protor_DT_atom_radius[] = {1.46, 1.88, 1.64, 1.88, 1.64, 1.61, 1.46, 1.88, 1.42, 1.46, 1.42, 1.8, 1.88, 1.46, 1.61, 1.46, 1.61, 1.88, 1.42, 1.76, 1.88, }; +static int protor_DT_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_DT_cfg = { + 21, + "DT", + (char**) protor_DT_atom_name, + (double*) protor_DT_atom_radius, + (freesasa_atom_class*) protor_DT_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_DU_atom_name[] = {"C5", "C4", "O3'", "C6", "C2'", "OP1", "O5'", "C5'", "OP2", "C2", "C1'", "N3", "N1", "C4'", "P", "OP3", "O2", "O4'", "C3'", "O4", }; +static double protor_DU_atom_radius[] = {1.76, 1.61, 1.46, 1.76, 1.88, 1.42, 1.46, 1.88, 1.46, 1.61, 1.88, 1.64, 1.64, 1.88, 1.8, 1.46, 1.42, 1.46, 1.88, 1.42, }; +static int protor_DU_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_DU_cfg = { + 20, + "DU", + (char**) protor_DU_atom_name, + (double*) protor_DU_atom_radius, + (freesasa_atom_class*) protor_DU_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_G_atom_name[] = {"O6", "OP1", "O2'", "C6", "C2'", "C4", "O3'", "C5", "C8", "C3'", "N2", "C4'", "P", "OP3", "O4'", "C5'", "OP2", "C2", "N1", "N3", "C1'", "N9", "O5'", "N7", }; +static double protor_G_atom_radius[] = {1.42, 1.42, 1.46, 1.61, 1.88, 1.61, 1.46, 1.61, 1.76, 1.88, 1.64, 1.88, 1.8, 1.46, 1.46, 1.88, 1.46, 1.61, 1.64, 1.64, 1.88, 1.64, 1.46, 1.64, }; +static int protor_G_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_G_cfg = { + 24, + "G", + (char**) protor_G_atom_name, + (double*) protor_G_atom_radius, + (freesasa_atom_class*) protor_G_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_GLN_atom_name[] = {"OE1", "CD", "N", "CG", "O", "OXT", "CB", "CA", "C", "NE2", }; +static double protor_GLN_atom_radius[] = {1.42, 1.61, 1.64, 1.88, 1.42, 1.46, 1.88, 1.88, 1.61, 1.64, }; +static int protor_GLN_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_GLN_cfg = { + 10, + "GLN", + (char**) protor_GLN_atom_name, + (double*) protor_GLN_atom_radius, + (freesasa_atom_class*) protor_GLN_atom_class, + {"GLN", 178.83, 42.00, 136.83, 131.85, 46.98, 0}, +}; + +static const char *protor_GLU_atom_name[] = {"O", "CG", "OXT", "OE2", "CA", "CB", "C", "N", "OE1", "CD", }; +static double protor_GLU_atom_radius[] = {1.42, 1.88, 1.46, 1.46, 1.88, 1.88, 1.61, 1.64, 1.42, 1.61, }; +static int protor_GLU_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_GLU_cfg = { + 10, + "GLU", + (char**) protor_GLU_atom_name, + (double*) protor_GLU_atom_radius, + (freesasa_atom_class*) protor_GLU_atom_class, + {"GLU", 174.18, 42.00, 132.18, 122.48, 51.70, 0}, +}; + +static const char *protor_GLX_atom_name[] = {"C", "CA", "CB", "XE1", "OXT", "O", "XE2", "CG", "CD", "N", }; +static double protor_GLX_atom_radius[] = {1.61, 1.88, 1.88, 1.5, 1.46, 1.42, 1.5, 1.88, 1.61, 1.64, }; +static int protor_GLX_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_GLX_cfg = { + 10, + "GLX", + (char**) protor_GLX_atom_name, + (double*) protor_GLX_atom_radius, + (freesasa_atom_class*) protor_GLX_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_GLY_atom_name[] = {"OXT", "O", "C", "CA", "N", }; +static double protor_GLY_atom_radius[] = {1.46, 1.42, 1.61, 1.88, 1.64, }; +static int protor_GLY_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_GLY_cfg = { + 5, + "GLY", + (char**) protor_GLY_atom_name, + (double*) protor_GLY_atom_radius, + (freesasa_atom_class*) protor_GLY_atom_class, + {"GLY", 81.09, 81.09, 0.00, 44.65, 36.44, 0}, +}; + +static const char *protor_HIS_atom_name[] = {"ND1", "O", "CG", "OXT", "NE2", "CB", "CA", "C", "CD2", "N", "CE1", }; +static double protor_HIS_atom_radius[] = {1.64, 1.42, 1.61, 1.46, 1.64, 1.88, 1.88, 1.61, 1.76, 1.64, 1.76, }; +static int protor_HIS_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_HIS_cfg = { + 11, + "HIS", + (char**) protor_HIS_atom_name, + (double*) protor_HIS_atom_radius, + (freesasa_atom_class*) protor_HIS_atom_class, + {"HIS", 182.97, 39.09, 143.87, 85.94, 97.03, 0}, +}; + +static const char *protor_HOH_atom_name[] = {"O", }; +static double protor_HOH_atom_radius[] = {1.46, }; +static int protor_HOH_atom_class[] = {FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_HOH_cfg = { + 1, + "HOH", + (char**) protor_HOH_atom_name, + (double*) protor_HOH_atom_radius, + (freesasa_atom_class*) protor_HOH_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_I_atom_name[] = {"O3'", "C4", "C5", "OP1", "O6", "C2'", "C6", "O2'", "N3", "N1", "C1'", "C2", "OP2", "C5'", "N7", "N9", "O5'", "C8", "C3'", "O4'", "OP3", "P", "C4'", }; +static double protor_I_atom_radius[] = {1.46, 1.61, 1.61, 1.42, 1.42, 1.88, 1.61, 1.46, 1.64, 1.64, 1.88, 1.76, 1.46, 1.88, 1.64, 1.64, 1.46, 1.76, 1.88, 1.46, 1.46, 1.8, 1.88, }; +static int protor_I_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_I_cfg = { + 23, + "I", + (char**) protor_I_atom_name, + (double*) protor_I_atom_radius, + (freesasa_atom_class*) protor_I_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_ILE_atom_name[] = {"N", "OXT", "O", "CG1", "C", "CA", "CB", "CG2", "CD1", }; +static double protor_ILE_atom_radius[] = {1.64, 1.46, 1.42, 1.88, 1.61, 1.88, 1.88, 1.88, 1.88, }; +static int protor_ILE_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_ILE_cfg = { + 9, + "ILE", + (char**) protor_ILE_atom_name, + (double*) protor_ILE_atom_radius, + (freesasa_atom_class*) protor_ILE_atom_class, + {"ILE", 175.73, 41.49, 134.23, 36.85, 138.87, 0}, +}; + +static const char *protor_LEU_atom_name[] = {"CD2", "N", "OXT", "O", "CG", "C", "CA", "CB", "CD1", }; +static double protor_LEU_atom_radius[] = {1.88, 1.64, 1.46, 1.42, 1.88, 1.61, 1.88, 1.88, 1.88, }; +static int protor_LEU_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_LEU_cfg = { + 9, + "LEU", + (char**) protor_LEU_atom_name, + (double*) protor_LEU_atom_radius, + (freesasa_atom_class*) protor_LEU_atom_class, + {"LEU", 179.56, 39.78, 139.78, 37.16, 142.39, 0}, +}; + +static const char *protor_LYS_atom_name[] = {"NZ", "N", "CD", "CA", "CB", "C", "CE", "O", "CG", "OXT", }; +static double protor_LYS_atom_radius[] = {1.64, 1.64, 1.88, 1.88, 1.88, 1.61, 1.88, 1.42, 1.88, 1.46, }; +static int protor_LYS_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_LYS_cfg = { + 10, + "LYS", + (char**) protor_LYS_atom_name, + (double*) protor_LYS_atom_radius, + (freesasa_atom_class*) protor_LYS_atom_class, + {"LYS", 204.98, 42.00, 162.98, 93.88, 111.10, 0}, +}; + +static const char *protor_MET_atom_name[] = {"N", "SD", "CA", "CB", "C", "O", "CG", "OXT", "CE", }; +static double protor_MET_atom_radius[] = {1.64, 1.77, 1.88, 1.88, 1.61, 1.42, 1.88, 1.46, 1.88, }; +static int protor_MET_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_MET_cfg = { + 9, + "MET", + (char**) protor_MET_atom_name, + (double*) protor_MET_atom_radius, + (freesasa_atom_class*) protor_MET_atom_class, + {"MET", 193.10, 42.00, 151.10, 75.48, 117.62, 0}, +}; + +static const char *protor_MSE_atom_name[] = {"SE", "N", "C", "CA", "CB", "OXT", "O", "CG", "CE", }; +static double protor_MSE_atom_radius[] = {1.9, 1.64, 1.61, 1.88, 1.88, 1.46, 1.42, 1.88, 1.88, }; +static int protor_MSE_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_MSE_cfg = { + 9, + "MSE", + (char**) protor_MSE_atom_name, + (double*) protor_MSE_atom_radius, + (freesasa_atom_class*) protor_MSE_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_NH2_atom_name[] = {"N", }; +static double protor_NH2_atom_radius[] = {1.64, }; +static int protor_NH2_atom_class[] = {FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_NH2_cfg = { + 1, + "NH2", + (char**) protor_NH2_atom_name, + (double*) protor_NH2_atom_radius, + (freesasa_atom_class*) protor_NH2_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_PHE_atom_name[] = {"CD1", "CA", "CB", "C", "CZ", "O", "CG", "OXT", "N", "CE1", "CE2", "CD2", }; +static double protor_PHE_atom_radius[] = {1.76, 1.88, 1.88, 1.61, 1.76, 1.42, 1.61, 1.46, 1.64, 1.76, 1.76, 1.76, }; +static int protor_PHE_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_PHE_cfg = { + 12, + "PHE", + (char**) protor_PHE_atom_name, + (double*) protor_PHE_atom_radius, + (freesasa_atom_class*) protor_PHE_atom_class, + {"PHE", 199.88, 38.43, 161.45, 34.94, 164.94, 0}, +}; + +static const char *protor_PRO_atom_name[] = {"C", "CB", "CA", "OXT", "O", "CG", "CD", "N", }; +static double protor_PRO_atom_radius[] = {1.61, 1.88, 1.88, 1.46, 1.42, 1.88, 1.88, 1.64, }; +static int protor_PRO_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_PRO_cfg = { + 8, + "PRO", + (char**) protor_PRO_atom_name, + (double*) protor_PRO_atom_radius, + (freesasa_atom_class*) protor_PRO_atom_class, + {"PRO", 137.21, 27.51, 109.70, 16.09, 121.12, 0}, +}; + +static const char *protor_PYL_atom_name[] = {"N2", "N", "CD", "CD2", "O2", "CA2", "C2", "CB", "OXT", "O", "CG", "NZ", "CE2", "CG2", "C", "CA", "CE", "CB2", }; +static double protor_PYL_atom_radius[] = {1.64, 1.64, 1.88, 1.88, 1.42, 1.88, 1.61, 1.88, 1.46, 1.42, 1.88, 1.64, 1.76, 1.88, 1.61, 1.88, 1.88, 1.88, }; +static int protor_PYL_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_PYL_cfg = { + 18, + "PYL", + (char**) protor_PYL_atom_name, + (double*) protor_PYL_atom_radius, + (freesasa_atom_class*) protor_PYL_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_SEC_atom_name[] = {"C", "SE", "CA", "CB", "N", "OXT", "O", }; +static double protor_SEC_atom_radius[] = {1.61, 1.9, 1.88, 1.88, 1.64, 1.46, 1.42, }; +static int protor_SEC_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_SEC_cfg = { + 7, + "SEC", + (char**) protor_SEC_atom_name, + (double*) protor_SEC_atom_radius, + (freesasa_atom_class*) protor_SEC_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_SER_atom_name[] = {"C", "CA", "CB", "N", "OXT", "O", "OG", }; +static double protor_SER_atom_radius[] = {1.61, 1.88, 1.88, 1.64, 1.46, 1.42, 1.46, }; +static int protor_SER_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_SER_cfg = { + 7, + "SER", + (char**) protor_SER_atom_name, + (double*) protor_SER_atom_radius, + (freesasa_atom_class*) protor_SER_atom_class, + {"SER", 118.34, 43.41, 74.93, 71.38, 46.96, 0}, +}; + +static const char *protor_T_atom_name[] = {"O2", "OP3", "C4'", "P", "O4'", "C3'", "O4", "O5'", "OP2", "C5'", "N3", "C1'", "N1", "C2", "C6", "C2'", "OP1", "C5", "C7", "C4", "O3'", }; +static double protor_T_atom_radius[] = {1.42, 1.46, 1.88, 1.8, 1.46, 1.88, 1.42, 1.46, 1.46, 1.88, 1.64, 1.88, 1.64, 1.61, 1.76, 1.88, 1.42, 1.61, 1.88, 1.61, 1.46, }; +static int protor_T_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_T_cfg = { + 21, + "T", + (char**) protor_T_atom_name, + (double*) protor_T_atom_radius, + (freesasa_atom_class*) protor_T_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_THR_atom_name[] = {"OXT", "O", "OG1", "C", "CA", "CB", "CG2", "N", }; +static double protor_THR_atom_radius[] = {1.46, 1.42, 1.46, 1.61, 1.88, 1.88, 1.88, 1.64, }; +static int protor_THR_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_THR_cfg = { + 8, + "THR", + (char**) protor_THR_atom_name, + (double*) protor_THR_atom_radius, + (freesasa_atom_class*) protor_THR_atom_class, + {"THR", 140.60, 41.96, 98.64, 66.15, 74.45, 0}, +}; + +static const char *protor_TRP_atom_name[] = {"CD1", "CA", "CB", "C", "CG", "O", "OXT", "CZ2", "N", "CZ3", "CE2", "NE1", "CD2", "CE3", "CH2", }; +static double protor_TRP_atom_radius[] = {1.76, 1.88, 1.88, 1.61, 1.61, 1.42, 1.46, 1.76, 1.64, 1.76, 1.61, 1.64, 1.61, 1.76, 1.76, }; +static int protor_TRP_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_TRP_cfg = { + 15, + "TRP", + (char**) protor_TRP_atom_name, + (double*) protor_TRP_atom_radius, + (freesasa_atom_class*) protor_TRP_atom_class, + {"TRP", 249.19, 42.59, 206.60, 61.64, 187.55, 0}, +}; + +static const char *protor_TYR_atom_name[] = {"CD2", "OH", "CE2", "N", "CE1", "OXT", "CZ", "CG", "O", "CD1", "C", "CA", "CB", }; +static double protor_TYR_atom_radius[] = {1.76, 1.46, 1.76, 1.64, 1.76, 1.46, 1.61, 1.61, 1.42, 1.76, 1.61, 1.88, 1.88, }; +static int protor_TYR_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_TYR_cfg = { + 13, + "TYR", + (char**) protor_TYR_atom_name, + (double*) protor_TYR_atom_radius, + (freesasa_atom_class*) protor_TYR_atom_class, + {"TYR", 214.19, 38.43, 175.76, 81.12, 133.07, 0}, +}; + +static const char *protor_U_atom_name[] = {"O4", "C3'", "O4'", "C4'", "P", "OP3", "O2", "C2", "N3", "N1", "C1'", "C5'", "OP2", "O5'", "OP1", "C2'", "O2'", "C6", "O3'", "C4", "C5", }; +static double protor_U_atom_radius[] = {1.42, 1.88, 1.46, 1.88, 1.8, 1.46, 1.42, 1.61, 1.64, 1.64, 1.88, 1.88, 1.46, 1.46, 1.42, 1.88, 1.46, 1.76, 1.46, 1.61, 1.76, }; +static int protor_U_atom_class[] = {FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, }; +static struct classifier_residue protor_U_cfg = { + 21, + "U", + (char**) protor_U_atom_name, + (double*) protor_U_atom_radius, + (freesasa_atom_class*) protor_U_atom_class, + {NULL, 0, 0, 0, 0, 0}, +}; + +static const char *protor_VAL_atom_name[] = {"CG2", "CB", "CA", "CG1", "C", "O", "OXT", "N", }; +static double protor_VAL_atom_radius[] = {1.88, 1.88, 1.88, 1.88, 1.61, 1.42, 1.46, 1.64, }; +static int protor_VAL_atom_class[] = {FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_APOLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, FREESASA_ATOM_POLAR, }; +static struct classifier_residue protor_VAL_cfg = { + 8, + "VAL", + (char**) protor_VAL_atom_name, + (double*) protor_VAL_atom_radius, + (freesasa_atom_class*) protor_VAL_atom_class, + {"VAL", 151.97, 41.50, 110.46, 36.87, 115.09, 0}, +}; + +static struct classifier_residue *protor_residue_cfg[] = { + &protor_A_cfg, &protor_ACE_cfg, &protor_ALA_cfg, &protor_ARG_cfg, &protor_ASN_cfg, &protor_ASP_cfg, &protor_ASX_cfg, &protor_C_cfg, &protor_CYS_cfg, &protor_DA_cfg, &protor_DC_cfg, &protor_DG_cfg, &protor_DI_cfg, &protor_DT_cfg, &protor_DU_cfg, &protor_G_cfg, &protor_GLN_cfg, &protor_GLU_cfg, &protor_GLX_cfg, &protor_GLY_cfg, &protor_HIS_cfg, &protor_HOH_cfg, &protor_I_cfg, &protor_ILE_cfg, &protor_LEU_cfg, &protor_LYS_cfg, &protor_MET_cfg, &protor_MSE_cfg, &protor_NH2_cfg, &protor_PHE_cfg, &protor_PRO_cfg, &protor_PYL_cfg, &protor_SEC_cfg, &protor_SER_cfg, &protor_T_cfg, &protor_THR_cfg, &protor_TRP_cfg, &protor_TYR_cfg, &protor_U_cfg, &protor_VAL_cfg, }; + +const freesasa_classifier freesasa_protor_classifier = { + 40, (char**) protor_residue_name, + "ProtOr", + (struct classifier_residue **) protor_residue_cfg, +}; + diff --git a/.venv_haddock/include/site/python3.12/freesasa/coord.c b/.venv_haddock/include/site/python3.12/freesasa/coord.c new file mode 100644 index 0000000000000000000000000000000000000000..22322c76f4582c63b64fd731158f9733ca0db4ee --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/coord.c @@ -0,0 +1,342 @@ +#if HAVE_CONFIG_H +#include +#endif +#include +#include +#include +#include + +#include "coord.h" +#include "freesasa_internal.h" + +coord_t * +freesasa_coord_new() +{ + coord_t *c = malloc(sizeof(coord_t)); + if (c != NULL) { + c->xyz = NULL; + c->n = 0; + c->is_linked = 0; + } else { + mem_fail(); + } + return c; +} + +void freesasa_coord_free(coord_t *c) +{ + if (c) { + if (c->xyz && !c->is_linked) free(c->xyz); + free(c); + } +} +static void +coord_clear(coord_t *c) +{ + assert(c); + assert(!c->is_linked); + if (c->xyz) { + free(c->xyz); + c->xyz = NULL; + } + c->n = 0; +} + +coord_t * +freesasa_coord_clone(const coord_t *src) +{ + coord_t *c = freesasa_coord_new(); + + assert(src); + + if (c == NULL) { + mem_fail(); + return NULL; + } + + if (freesasa_coord_set_all(c, src->xyz, src->n) != FREESASA_SUCCESS) { + fail_msg(""); + return NULL; + } + + return c; +} + +int freesasa_coord_copy(coord_t *target, const coord_t *src) +{ + if (src->n != target->n) return FREESASA_FAIL; + memcpy(target->xyz, src->xyz, sizeof(double) * src->n * 3); + return FREESASA_SUCCESS; +} + +coord_t * +freesasa_coord_new_linked(const double *xyz, + int n) +{ + coord_t *c = freesasa_coord_new(); + + assert(xyz); + assert(n > 0); + + if (c != NULL) { + c->xyz = (double *)xyz; + c->n = n; + c->is_linked = 1; + } else + mem_fail(); + return c; +} + +int freesasa_coord_append(coord_t *c, + const double *xyz, + int n) +{ + int n_old; + double *xyz_old; + + assert(c); + assert(xyz); + assert(!c->is_linked); + + n_old = c->n; + xyz_old = c->xyz; + + if (n == 0) return FREESASA_SUCCESS; + + c->xyz = (double *)realloc(c->xyz, sizeof(double) * 3 * (c->n + n)); + if (c->xyz == NULL) { + free(xyz_old); + return mem_fail(); + } + c->n += n; + + memcpy(&(c->xyz[3 * n_old]), xyz, sizeof(double) * n * 3); + return FREESASA_SUCCESS; +} + +int freesasa_coord_append_xyz(coord_t *c, + const double *x, + const double *y, + const double *z, int n) +{ + double *xyz; + int i; + + assert(c); + assert(x); + assert(y); + assert(z); + assert(!c->is_linked); + + if (n == 0) return FREESASA_SUCCESS; + + xyz = malloc(sizeof(double) * n * 3); + if (xyz == NULL) return mem_fail(); + + for (i = 0; i < n; ++i) { + xyz[i * 3] = x[i]; + xyz[i * 3 + 1] = y[i]; + xyz[i * 3 + 2] = z[i]; + } + if (freesasa_coord_append(c, xyz, n) == FREESASA_SUCCESS) { + free(xyz); + return FREESASA_SUCCESS; + } + return mem_fail(); +} + +void freesasa_coord_set_i(coord_t *c, + int i, + const double *xyz) +{ + assert(c); + assert(xyz); + assert(i < c->n && i >= 0); + assert(!c->is_linked); + + memcpy(&c->xyz[i * 3], xyz, 3 * sizeof(double)); +} + +void freesasa_coord_set_i_xyz(coord_t *c, + int i, + double x, + double y, + double z) +{ + double *v_i; + + assert(c); + assert(c->n > i); + assert(i >= 0); + assert(!c->is_linked); + + v_i = &c->xyz[i * 3]; + + *(v_i++) = x; + *(v_i++) = y; + *v_i = z; +} + +int freesasa_coord_set_all(coord_t *c, + const double *xyz, + int n) +{ + int result; + + assert(c); + assert(xyz); + + coord_clear(c); + result = freesasa_coord_append(c, xyz, n); + + if (result != FREESASA_SUCCESS) { + fail_msg(""); + } + + return result; +} + +int freesasa_coord_set_all_xyz(coord_t *c, + const double *x, + const double *y, + const double *z, + int n) +{ + assert(c); + assert(x); + assert(y); + assert(z); + coord_clear(c); + return freesasa_coord_append_xyz(c, x, y, z, n); +} + +void freesasa_coord_set_length_i(coord_t *c, + int i, + double l) +{ + double x, y, z, r; + + assert(c); + assert(c->xyz); + assert(!c->is_linked); + assert(i >= 0 && i < c->n); + assert(l >= 0); + + x = c->xyz[3 * i]; + y = c->xyz[3 * i + 1]; + z = c->xyz[3 * i + 2]; + r = sqrt(x * x + y * y + z * z); + c->xyz[3 * i] *= l / r; + c->xyz[3 * i + 1] *= l / r; + c->xyz[3 * i + 2] *= l / r; +} + +void freesasa_coord_set_length_all(coord_t *c, + double l) +{ + int i; + + assert(c); + assert(!c->is_linked); + + for (i = 0; i < c->n; ++i) + freesasa_coord_set_length_i(c, i, l); +} + +const double * +freesasa_coord_i(const coord_t *c, + int i) +{ + assert(c); + assert(i < c->n); + assert(i >= 0); + return &c->xyz[3 * i]; +} + +double +freesasa_coord_dist(const coord_t *c, + int i, + int j) +{ + return sqrt(freesasa_coord_dist2(c, i, j)); +} + +static inline double +dist2(const double *v1, + const double *v2) +{ + double dx = v1[0] - v2[0], dy = v1[1] - v2[1], dz = v1[2] - v2[2]; + return dx * dx + dy * dy + dz * dz; +} + +double +freesasa_coord_dist2(const coord_t *c, + int i, + int j) +{ + double *v1 = &c->xyz[3 * i]; + double *v2 = &c->xyz[3 * j]; + return dist2(v1, v2); +} + +double +freesasa_coord_dist2_12(const coord_t *c1, + const coord_t *c2, + int i1, + int i2) +{ + double *v1 = &c1->xyz[3 * i1]; + double *v2 = &c2->xyz[3 * i2]; + return dist2(v1, v2); +} + +const double * +freesasa_coord_all(const coord_t *c) +{ + assert(c); + return c->xyz; +} + +int freesasa_coord_n(const coord_t *c) +{ + assert(c); + return c->n; +} + +void freesasa_coord_translate(coord_t *c, + const double *xyz) +{ + assert(!c->is_linked); + assert(xyz); + freesasa_coord_translate_xyz(c, xyz[0], xyz[1], xyz[2]); +} + +void freesasa_coord_translate_xyz(coord_t *c, + double x, + double y, + double z) +{ + int i; + + assert(c); + assert(!c->is_linked); + + for (i = 0; i < c->n; ++i) { + c->xyz[3 * i] += x; + c->xyz[3 * i + 1] += y; + c->xyz[3 * i + 2] += z; + } +} + +void freesasa_coord_scale(coord_t *c, + double s) +{ + int i; + + assert(c); + assert(!c->is_linked); + + for (i = 0; i < c->n * 3; ++i) { + c->xyz[i] *= s; + } +} diff --git a/.venv_haddock/include/site/python3.12/freesasa/coord.h b/.venv_haddock/include/site/python3.12/freesasa/coord.h new file mode 100644 index 0000000000000000000000000000000000000000..dbe2f2500045620d3328a433682c5176d70c7acd --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/coord.h @@ -0,0 +1,340 @@ +#ifndef FREESASA_COORD_H +#define FREESASA_COORD_H + +#ifdef __GNUC__ +#define __attrib_pure__ __attribute__((pure)) +#else +#define __attrib_pure__ +#endif + +/** + @file + @author Simon Mitternacht + + This is only for interal use, error handling is done by asserts. + The header provides functions to store, copy and modify + coordinates through the type ::coord_t. + + The distance calculation functions (freesasa_dist(), + freesasa_dist2() and freesasa_dist2_12()) are useful for code that + is not performance critical. When efficieny is a priority it is + better to use freesasa_coord_all() to obtain a pointer to the + array of coordinates and calculate directly using this.. + */ + +/** Store a set of 3-dimensional coordinates in a contiguous array */ +typedef struct coord_t { + /** number of 3-vectors */ + int n; + + /** If these coordinates are only a link to an externally stored + array this is 1, else 0. If it it is set, the coordinates can + not be changed and the array not freed. */ + int is_linked; + + /** array of all coordinates, dimension 3*n, + x_1,y_1,z_1,...,x_n,y_n,z_n. */ + double *xyz; +} coord_t; + +/** + Initialize new ::coord_t object. + + Return value is dynamically allocated, should be freed with + freesasa_coord_free(). + + @return An empty ::coord_t object. Returns NULL if out of + memory. + */ +coord_t * +freesasa_coord_new(void); + +/** + Free resources allocated by ::coord_t object. + + Will not free the coordinate array itself if it was initialized by + freesasa_coord_new_linked(). + */ +void freesasa_coord_free(coord_t *coord); + +/** + Clone coordinates. + + Creates a new ::coord_t object that is a copy of the + argument `src`. + + Return value is dynamically allocated, should be freed with + freesasa_coord_free(). + + @param src Coordinates to be copied. + @return Copy of coordinates. NULL if out of memory. + */ +coord_t * +freesasa_coord_clone(const coord_t *src); + +/** + Copy coordinates + + Copies value of source coordinates to target. + + @param target Target coordinates + @param src Source coordinates + @return ::FREESASA_FAIL if size mismatch between src and target, + else ::FREESASA_SUCCESS + */ +int freesasa_coord_copy(coord_t *target, const coord_t *src); + +/** + Creates a `const` ::coord_t-object that is linked to an array of + coordinates owned by callee. + + This allows repeated calculations on a changing object without + reinitialization. The returned ::coord_t-pointer is not + explicitly const, to allow it to be freed later, but objects + initiated through this interface will not change their + coordinates. It also allows ::coord_t to be used as a wrapper + for an array controlled by the caller. + + Return value is dynamically allocated, should be freed with + freesasa_coord_free(). + + @param xyz Array of coordinates x1,y1,z1,x2,y2,z2,... + @param n Number of coordinates (array has size 3*n). + @return New linked ::coord_t object. NULL if out of memory. + */ +coord_t * +freesasa_coord_new_linked(const double *xyz, + int n); + +/** + Append coordinates to ::coord_t object from one array. + + @param coord A ::coord_t object + @param xyz Array of coordinates x1,y1,z1,x2,y2,z2,... + @param n Number of coordinates (array has size 3*n). + @return FREESASA_SUCCESS if successful, FREESASA_FAIL if out of memory. + */ +int freesasa_coord_append(coord_t *coord, + const double *xyz, + int n); + +/** + Append coordinates to ::coord_t object from three + separate arrays. + + @param coord A ::coord_t object + @param x Array of x-coordinates + @param y Array of x-coordinates + @param z Array of x-coordinates + @param n Size of arrays x, y and z. + @return FREESASA_SUCCESS if successful, FREESASA_FAIL if out of memory. + */ +int freesasa_coord_append_xyz(coord_t *coord, + const double *x, + const double *y, + const double *z, + int n); + +/** + Set given coordinate. + + Bounds-checking of i is handled by asserts for efficiency, + i.e. only done in debug-mode. + + @param coord A ::coord_t object + @param i Index + @param xyz Array with coordinates x,y,z. + */ +void freesasa_coord_set_i(coord_t *coord, + int i, + const double *xyz); + +/** + Set given coordinate. + + Bounds-checking of i is handled by asserts for efficiency, + i.e. only done in debug-mode. + + @param coord A ::coord_t object + @param i Index + @param x x-coordinate. + @param y y-coordinate. + @param z z-coordinate + */ +void freesasa_coord_set_i_xyz(coord_t *coord, + int i, + double x, + double y, + double z); + +/** + Reset everything. + + Allocates memory to allow array of size n. + + @param coord A ::coord_t object + @param xyz Array of coordinates x1,y1,z1,x2,y2,z2,... + @param n Number of coordinates (array has size 3*n). + @return FREESASA_SUCCESS if successful, FREESASA_FAIL if out of memory. + */ +int freesasa_coord_set_all(coord_t *coord, + const double *xyz, + int n); + +/** + Reset everything. + + Allocates memory to allow array of size n. + + @param coord A ::coord_t object + @param x Array of x-coordinates + @param y Array of x-coordinates + @param z Array of x-coordinates + @param n Size of arrays x, y and z. + @return FREESASA_SUCCESS if successful, FREESASA_FAIL if out of memory. + */ +int freesasa_coord_set_all_xyz(coord_t *coord, + const double *x, + const double *y, + const double *z, + int n); + +/** + Set length of a given coordinate vector. Useful for test-points in + S&R. + + Bounds-checking of `i` and `length` is handled by asserts for + efficiency, i.e. only done in debug-mode. + + @param coord A ::coord_t object + @param i Index + @param length Desired length (>= 0) + */ +void freesasa_coord_set_length_i(coord_t *coord, + int i, + double length); + +/** + Set length of all coordinate vectors to the same length. + + This means all coordinates are on the same sphere. + + Bounds-checking of length is handled by asserts for + efficiency, i.e. only done in debug-mode. + + @param coord A ::coord_t object + @param length Desired length (>= 0) + */ +void freesasa_coord_set_length_all(coord_t *coord, + double length); + +/** + Coordinates for a given index. + + Bounds-checking of `i` is handled by asserts for efficiency, + i.e. only done in debug-mode. + + @param coord A ::coord_t object + @param i Index + @return Array with coordinates x,y,z + */ +const double * +freesasa_coord_i(const coord_t *coord, + int i); + +/** + Calculate distance between two coordinate vectors. For speed, + arguments aren't checked. + + @param coord A ::coord_t object + @param i first index + @param j second index + @return Distance between coorsinate i and j. +*/ +double freesasa_coord_dist(const coord_t *coord, + int i, + int j) + __attrib_pure__; + +/** + Calculate square distance between two coordinate vectors. For + speed, arguments aren't checked. + + @param coord A ::coord_t object + @param i First index + @param j Second index + @return Square distance between coordinate i and j +*/ +double +freesasa_coord_dist2(const coord_t *coord, + int i, + int j) + __attrib_pure__; + +/** + Calculate square distance between two coordinate vectors in + separate coordinate sets. For speed, arguments aren't checked. + + @param c1 First set of coordinates + @param c2 Second set of coordinates + @param i1 Index in first set + @param i2 Index in second set + @return Square distance between coordinates i1 and i2 +*/ +double freesasa_coord_dist2_12(const coord_t *c1, + const coord_t *c2, + int i1, + int i2) + __attrib_pure__; + +/** + All coordinates as an array. + + @param coord A ::coord_t object + @return Array of coordinates x1,y1,z1,x2,y2,z2,... + */ +const double * +freesasa_coord_all(const coord_t *coord) __attrib_pure__; + +/** + Number of coordinates. + + @param coord A ::coord_t object + @return Number of coordinates + */ +int freesasa_coord_n(const coord_t *coord) __attrib_pure__; + +/** + Translate all coordinates by same vector. + + @param coord A ::coord_t object + @param xyz Array describing translation vector x,y,z. + */ +void freesasa_coord_translate(coord_t *coord, + const double *xyz); + +/** + Translate all coordinates by same vector. + + @param coord A ::coord_t object + @param x x-coordinate of translation vector + @param y y-coordinate of translation vector + @param z z-coordinate of translation vector + */ +void freesasa_coord_translate_xyz(coord_t *coord, + double x, + double y, + double z); + +/** + Scale all coordinates by given factor. + + @param coord A ::coord_t object + @param a Factor to scale by + */ +void freesasa_coord_scale(coord_t *coord, + double a); + +#undef __attrib_pure__ + +#endif diff --git a/.venv_haddock/include/site/python3.12/freesasa/freesasa.c b/.venv_haddock/include/site/python3.12/freesasa/freesasa.c new file mode 100644 index 0000000000000000000000000000000000000000..7c8a21962708de6bd352f6e9815c39eaef5dc5ac --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/freesasa.c @@ -0,0 +1,266 @@ +/** + * This source file contains everything that is in freesasa.h + * interface and does not have a natural home in any of the other + * source files. + */ + +#if HAVE_CONFIG_H +#include +#endif +#include +#include +#include + +#include "freesasa_internal.h" + +#ifdef PACKAGE_VERSION +const char *freesasa_version = PACKAGE_VERSION; +#else +const char *freesasa_version = ""; +#endif + +#ifdef PACKAGE_STRING +const char *freesasa_string = PACKAGE_STRING; +#else +const char *freesasa_string = "FreeSASA"; +#endif + +/* Allows compilation with different defaults + depending on USE_THREADS. but still exposing the value in a header + that doesn't depend on USE_THREADS */ +#if USE_THREADS +#define DEF_NUMBER_THREADS 2 +#else +#define DEF_NUMBER_THREADS 1 +#endif +const int FREESASA_DEF_NUMBER_THREADS = DEF_NUMBER_THREADS; + +const freesasa_parameters freesasa_default_parameters = { + FREESASA_DEF_ALGORITHM, + FREESASA_DEF_PROBE_RADIUS, + FREESASA_DEF_SR_N, + FREESASA_DEF_LR_N, + DEF_NUMBER_THREADS}; + +static freesasa_result * +result_new(int n) +{ + freesasa_result *result = malloc(sizeof(freesasa_result)); + + if (result == NULL) { + mem_fail(); + return NULL; + } + + result->sasa = malloc(sizeof(double) * n); + + if (result->sasa == NULL) { + mem_fail(); + freesasa_result_free(result); + return NULL; + } + + result->n_atoms = n; + + return result; +} + +void freesasa_result_free(freesasa_result *r) +{ + if (r) { + free(r->sasa); + free(r); + } +} + +freesasa_result * +freesasa_calc(const coord_t *c, + const double *radii, + const freesasa_parameters *parameters) + +{ + freesasa_result *result; + int ret = FREESASA_SUCCESS, i; + + assert(c); + assert(radii); + + result = result_new(freesasa_coord_n(c)); + + if (result == NULL) { + fail_msg(""); + return NULL; + } + + if (parameters == NULL) parameters = &freesasa_default_parameters; + + switch (parameters->alg) { + case FREESASA_SHRAKE_RUPLEY: + ret = freesasa_shrake_rupley(result->sasa, c, radii, parameters); + break; + case FREESASA_LEE_RICHARDS: + ret = freesasa_lee_richards(result->sasa, c, radii, parameters); + break; + default: + assert(0); /* should never get here */ + break; + } + if (ret == FREESASA_FAIL) { + freesasa_result_free(result); + return NULL; + } + + result->total = 0; + for (i = 0; i < freesasa_coord_n(c); ++i) { + result->total += result->sasa[i]; + } + result->parameters = *parameters; + + return result; +} + +freesasa_result * +freesasa_calc_coord(const double *xyz, + const double *radii, + int n, + const freesasa_parameters *parameters) +{ + coord_t *coord = NULL; + freesasa_result *result = NULL; + + assert(xyz); + assert(radii); + assert(n > 0); + + coord = freesasa_coord_new_linked(xyz, n); + if (coord != NULL) result = freesasa_calc(coord, radii, parameters); + if (result == NULL) fail_msg(""); + + freesasa_coord_free(coord); + + return result; +} + +freesasa_result * +freesasa_calc_structure(const freesasa_structure *structure, + const freesasa_parameters *parameters) +{ + assert(structure); + + return freesasa_calc(freesasa_structure_xyz(structure), + freesasa_structure_radius(structure), + parameters); +} + +freesasa_node * +freesasa_calc_tree(const freesasa_structure *structure, + const freesasa_parameters *parameters, + const char *name) +{ + freesasa_node *tree = NULL; + freesasa_result *result; + + assert(structure); + + result = freesasa_calc(freesasa_structure_xyz(structure), + freesasa_structure_radius(structure), + parameters); + + if (result != NULL) { + tree = freesasa_tree_init(result, structure, name); + } else { + fail_msg(""); + } + + if (tree == NULL) { + fail_msg(""); + } + + freesasa_result_free(result); + + return tree; +} + +static inline void +count_err(int return_value, int *n_err) +{ + if (return_value == FREESASA_FAIL) { + (*n_err)++; + } +} + +int freesasa_tree_export(FILE *file, + freesasa_node *root, + int options) +{ + int n_err = 0; + + assert(freesasa_node_type(root) == FREESASA_NODE_ROOT); + + if (options & FREESASA_LOG) { + count_err(freesasa_write_log(file, root), &n_err); + } + if (options & FREESASA_RES) { + count_err(freesasa_write_res(file, root), &n_err); + } + if (options & FREESASA_SEQ) { + count_err(freesasa_write_seq(file, root), &n_err); + } + if (options & FREESASA_PDB) { + count_err(freesasa_write_pdb(file, root), &n_err); + } + if (options & FREESASA_RSA) { + count_err(freesasa_write_rsa(file, root, options), &n_err); + } + if (options & FREESASA_JSON) { +#if USE_JSON + count_err(freesasa_write_json(file, root, options), &n_err); +#else + return fail_msg("library was built without support for JSON output"); +#endif + } + if (options & FREESASA_XML) { +#if USE_XML + count_err(freesasa_write_xml(file, root, options), &n_err); +#else + return fail_msg("library was built without support for XML output"); +#endif + } + if (n_err > 0) { + return fail_msg("there were errors when writing output"); + } + return FREESASA_SUCCESS; +} + +freesasa_result * +freesasa_result_clone(const freesasa_result *result) +{ + freesasa_result *clone = result_new(result->n_atoms); + + if (clone == NULL) { + fail_msg(""); + return NULL; + } + + clone->n_atoms = result->n_atoms; + clone->total = result->total; + clone->parameters = result->parameters; + memcpy(clone->sasa, result->sasa, sizeof(double) * clone->n_atoms); + + return clone; +} + +const char * +freesasa_alg_name(freesasa_algorithm alg) +{ + switch (alg) { + case FREESASA_SHRAKE_RUPLEY: + return "Shrake & Rupley"; + case FREESASA_LEE_RICHARDS: + return "Lee & Richards"; + default: + // This should never happen + assert(0 && "Illegal algorithm"); + return "Unknown algorithm"; + } +} diff --git a/.venv_haddock/include/site/python3.12/freesasa/freesasa_internal.h b/.venv_haddock/include/site/python3.12/freesasa/freesasa_internal.h new file mode 100644 index 0000000000000000000000000000000000000000..2db7069116125de5858a62e264bcae4b520fc44a --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/freesasa_internal.h @@ -0,0 +1,461 @@ +#ifndef FREESASA_INTERNAL_H +#define FREESASA_INTERNAL_H + +#ifdef _MSC_VER +#define _CRT_SECURE_NO_WARNINGS +#endif + +/* These are included here so that the _CRT_SECURE_.. macro above will have the desired effect */ +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#include "coord.h" +#include "freesasa.h" + +/** The name of the library, to be used in error messages and logging */ +extern const char *freesasa_name; + +/** The name of the package, to be used in regular output (includes version) */ +extern const char *freesasa_string; + +/** A ::freesasa_nodearea with `name == NULL` and all values 0 */ +extern const freesasa_nodearea freesasa_nodearea_null; + +/** Shortcut for memory error generation */ +#define mem_fail() freesasa_mem_fail(__FILE__, __LINE__) + +/** Shortcut for error message with position information, should be used by default */ +#define fail_msg(...) freesasa_fail_wloc(__FILE__, __LINE__, __VA_ARGS__) + +#ifdef _MSC_VER +#define inline __inline +#define strdup _strdup +#define fmax(a, b) (((a) > (b)) ? (a) : (b)) +#define fmin(a, b) (((a) < (b)) ? (a) : (b)) +#include +#define isfinite _finite +#endif + +#if defined(_MSC_VER) && !defined(__func__) +#define __func__ __FUNCTION__ +#endif + +#if defined(_MSC_VER) && _MSC_VER >= 1400 +#define restrict __restrict +#endif +#if defined(_MSC_VER) && _MSC_VER < 1400 +#define restrict +#endif + +/* The library is intended to be compiled with C99, but this macro + allows us to compile it with C89 too, to test MSC compatibility */ +#ifdef __STRICT_ANSI__ +#define restrict +#define inline +#endif + +/** + Calculate SASA using S&R algorithm. + + @param sasa The results are written to this array, the user has to + make sure it is large enough. + @param c Coordinates of the object to calculate SASA for. + @param radii Array of radii for each sphere. + @param param Parameters specifying resolution, probe radius and + number of threads. If NULL :.freesasa_default_parameters is used. + @return ::FREESASA_SUCCESS on success, ::FREESASA_WARN if multiple + threads are requested when compiled in single-threaded mode (with + error message). ::FREESASA_FAIL if memory allocation failure. + */ +int freesasa_shrake_rupley(double *sasa, + const coord_t *c, + const double *radii, + const freesasa_parameters *param); + +/** + Calculate SASA using L&R algorithm. + + Solvent accessible surface area for each atom is written to the + array 'sasa'. The user is responsible for making sure this has the + right size. The argument grid sets the distance between grid + points in Å. Returns FREESASA_SUCCESS on success, FREESASA_WARN if + multiple threads are requested when compiled in single-threaded + mode (with error message). + + @param sasa The results are written to this array, the user has to + make sure it is large enough. + @param c Coordinates of the object to calculate SASA for. + @param radii Array of radii for each sphere. + @param param Parameters specifying resolution, probe radius and + number of threads. If NULL :.freesasa_default_parameters is used. + @return ::FREESASA_SUCCESS on success, ::FREESASA_WARN if + multiple threads are requested when compiled in single-threaded + mode (with error message). ::FREESASA_FAIL if memory allocation + failure. + */ +int freesasa_lee_richards(double *sasa, + const coord_t *c, + const double *radii, + const freesasa_parameters *param); + +/** + Calculate SASA based on a coordinate object, radii and parameters + + Wrapper for freesasa_lee_richards() and freesasa_shrake_rupley() + that creates a result object. + + Return value is dynamically allocated, should be freed with + freesasa_result_free(). + + @param c Coordinates + @param radii Atomi radii + @param parameters Parameters + @return Result of calculation, NULL if something went wrong. + */ +freesasa_result * +freesasa_calc(const coord_t *c, + const double *radii, + const freesasa_parameters *parameters); + +int freesasa_write_log(FILE *log, + freesasa_node *root); + +/** + Print RSA-file + + @param output Output-file. + @param root A tree with stored results. + @param options Bitfield with option ::FREESASA_OUTPUT_SKIP_REL to specify + if REL column should be populated or not. If the classifier has no + reference values, it will be left empty either way. + @return ::FREESASA_SUCCESS on success, ::FREESASA_FAIL if problems + writing to file. + */ +int freesasa_write_rsa(FILE *output, + freesasa_node *root, + int options); + +/** + Export to JSON + + Not thread-safe. + + @param output Output-file. + @param root A tree with stored results. + @param parameters Parameters used in the calculation (NULL means + defaults are assumed). + @param options Bitfield with options ::FREESASA_OUTPUT_STRUCTURE, + ::FREESASA_OUTPUT_CHAIN and ::FREESASA_OUTPUT_RESIDUE, that specify + depth of the tree to output. If `options == 0` all levels are + written. The options ::FREESASA_OUTPUT_SKIP_REL specifies + if REL column should be populated or not. If the classifier has no + reference values, it will be left empty either way. + @return ::FREESASA_SUCCESS on success, ::FREESASA_FAIL if problems + writing to file. + */ +int freesasa_write_json(FILE *ouput, + freesasa_node *root, + int options); +/** + Export to XML + + @param output Output-file. + @param root A tree with stored results. + @param parameters Parameters used in the calculation (NULL means + defaults are assumed). + @param options Bitfield with options ::FREESASA_OUTPUT_STRUCTURE, + ::FREESASA_OUTPUT_CHAIN and ::FREESASA_OUTPUT_RESIDUE, that specify + depth of the tree to output. If `options == 0` all levels + written. The options ::FREESASA_OUTPUT_SKIP_REL specifies + if REL column should be populated or not. If the classifier has no + reference values, it will be left empty either way. + @return ::FREESASA_SUCCESS on success, ::FREESASA_FAIL if problems + writing to file. + */ +int freesasa_write_xml(FILE *ouput, + freesasa_node *root, + int options); + +/** + Write SASA values and atomic radii to new PDB-file. + + Takes PDB information from the provided structure and writes a new + PDB-file to output, where the B-factors have been replaced with + the atom's SASA values in the results, and the occupancy + factors with the radii. + + Will only work if the structure was initialized from a PDB-file, i.e. + using freesasa_structure_from_pdb() or freesasa_structure_array(). + + @param output Output-file + @param structure A ::freesasa_node of type ::FREESASA_NODE_STRUCTURE + @return ::FREESASA_SUCCESS if file written successfully. + ::FREESASA_FAIL if there is no previous PDB input to base output + on or if there were problems writing to the file. +*/ +int freesasa_write_pdb(FILE *output, + freesasa_node *structure); + +/** + Write per-residue-type output + */ +int freesasa_write_res(FILE *log, + freesasa_node *root); + +/** + Write SASA per residue in sequence output + */ +int freesasa_write_seq(FILE *log, + freesasa_node *root); + +/** + Write standard log message. + */ +int freesasa_write_log(FILE *log, + freesasa_node *root); + +/** + Clone results object +*/ +freesasa_result * +freesasa_result_clone(const freesasa_result *result); + +/** + Clone selection object +*/ +freesasa_selection * +freesasa_selection_clone(const freesasa_selection *selection); + +/** + Get coordinates. + + @param structure A structure. + @return The coordinates of the structure as a ::coord_t struct. + */ +const coord_t * +freesasa_structure_xyz(const freesasa_structure *structure); + +/** + The class of an atom, in the classifier used to initialize the structure. + + @param structure A structure. + @param i Atom index. + @return The class. + */ +freesasa_atom_class +freesasa_structure_atom_class(const freesasa_structure *structure, + int i); + +/** + The PDB line used to generate the atom. + + @param structure A structure. + @param i Atom index. + @return The line, NULL if structure wasn't generated from a PDB file. + */ +const char * +freesasa_structure_atom_pdb_line(const freesasa_structure *structure, + int i); + +/** + Add a reference number to the document used to generate the structure from a CIF file, + used when exporting to CIF file. + + @param structure A structure. + @param ref Reference number for document. >= 1. + @param release_func A function that can be called when freeing the structure, to trigger + the destructor for the CIF document. This can be NULL if one wants another mode + of control over the CIF document. + @return ::FREESASA_SUCCESS if success. + ::FREESASA_FAIL if memory allocation error. +*/ +void freesasa_structure_set_cif_ref(freesasa_structure *structure, + size_t ref, + void (*release_func)(size_t)); + +/** + Retrieve the reference number for the CIF document used to generate the structure + from a CIF file. + + @param structure A structure. + @return The reference number. 0 if structure is not from CIF file. +*/ +size_t freesasa_structure_cif_ref(const freesasa_structure *structure); + +/** + Retrieve the reference number for the CIF document used to generate the structure + from a CIF file, in a structure node. + + @param node A node of type ::FREESASA_NODE_STRUCTURE. + @return Reference to CIF document. + + @ingroup node + */ +size_t +freesasa_node_structure_cif_ref(const freesasa_node *node); + +const freesasa_nodearea * +freesasa_structure_residue_reference(const freesasa_structure *structure, + int r_i); +/** + Get the index of a chain. + + @param structure A structure. + @param chain The chain label. + @return The index of `chain` in the structure. ::FREESASA_FAIL + if `chain` not found. + */ +int freesasa_structure_chain_index(const freesasa_structure *structure, + char chain); + +/** + Extract area to provided ::freesasa_nodearea object + + Main-chain / side-chain atoms are defined by + ::freesasa_backbone_classifier. + + @param area Area will be stored here + @param structure Structure to use for classification + @param result The areas to use + @param atom_index Index of atom in question + @return ::FREESASA_SUCCESS. ::FREESASA_FAIL if memory + allocation for name fails. + */ +int freesasa_atom_nodearea(freesasa_nodearea *area, + const freesasa_structure *structure, + const freesasa_result *result, + int atom_index); + +/** + Adds all members of term to corresponding members of sum + + @param sum Object to add to + @param term Object to add + */ +void freesasa_add_nodearea(freesasa_nodearea *sum, + const freesasa_nodearea *term); + +/** + Compute nodearea for a range of atoms + */ +void freesasa_range_nodearea(freesasa_nodearea *area, + const freesasa_structure *structure, + const freesasa_result *result, + int first_atom, + int last_atom); + +/** + Calculate relative SASA values for a residue + + If the array `ref_values` does not have an entry that has the same + `name` as `abs`, `rel->name` will be `NULL`. + + @param rel Store results here, will have same name as `abs` + @param abs Absolute SASA for residue + @param reference Reference SASA for the residue + */ +void freesasa_residue_rel_nodearea(freesasa_nodearea *rel, + const freesasa_nodearea *abs, + const freesasa_nodearea *reference); + +/** + Is an atom a backbone atom + + @param atom_name Name of atom + @return 1 if the atom_name equals CA, N, O or C after whitespace + is trimmed, 0 else. (i.e. does not check if it is an actual atom) + */ +int freesasa_atom_is_backbone(const char *atom_name); + +/** + Holds range in a file, to be initalized with ftell() and used + with fseek(). + */ +struct file_range { + long begin; /**< Position of beginning of range */ + long end; /**< Position of end of range */ +}; + +/** + For convenience, get a file range that covers a whole file. + + @param file The file to study + @return the ::file_range. + */ +struct file_range +freesasa_whole_file(FILE *file); + +/** + Algorithm name + + @param algorithm The algorithm + @return Name + */ +const char * +freesasa_alg_name(freesasa_algorithm algorithm); + +/** + Print failure message using format string and arguments. + + Prefer using the macro fail_msg(). + + @param format Format string + @return ::FREESASA_FAIL +*/ +int freesasa_fail(const char *format, ...); + +/** + Print warning message using format string and arguments. + + @param format Format string + @return ::FREESASA_WARN + */ +int freesasa_warn(const char *format, ...); + +/** + Print warning message using function, file and line-number. + + Usually used via the macro mem_fail(). + + @param func Name of the function that failed + @param file The file where the function is. + @param line Line number for the error. + @return ::FREESASA_FAIL + */ +int freesasa_mem_fail(const char *file, + int line); + +/** + Returns string explaining return values of pthread_create() and + pthread_join(). + + @param error_code The error code + @return A string describing the error code. + */ +const char * +freesasa_thread_error(int error_code); + +/** + Prints fail message with function name, file name, and line number. + + Mainly intended to be used by the macros fail_msg() and mem_fail(). + + @param file The file name + @param line The line number + @param msg The error message + @return ::FREESASA_FAIL + */ +int freesasa_fail_wloc(const char *file, + int line, + const char *format, + ...); + +#ifdef __cplusplus +} +#endif + +#endif /* FREESASA_INTERNAL_H */ diff --git a/.venv_haddock/include/site/python3.12/freesasa/lexer.c b/.venv_haddock/include/site/python3.12/freesasa/lexer.c new file mode 100644 index 0000000000000000000000000000000000000000..f854f8faa5db4b1dc65941e8f6f102f3dd069ce4 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/lexer.c @@ -0,0 +1,2129 @@ +#line 2 "lexer.c" + +#line 4 "lexer.c" + +#define YY_INT_ALIGNED short int + +/* A lexical scanner generated by flex */ + +#define FLEX_SCANNER +#define YY_FLEX_MAJOR_VERSION 2 +#define YY_FLEX_MINOR_VERSION 6 +#define YY_FLEX_SUBMINOR_VERSION 1 +#if YY_FLEX_SUBMINOR_VERSION > 0 +#define FLEX_BETA +#endif + +/* First, we deal with platform-specific or compiler-specific issues. */ + +/* begin standard C headers. */ +#include +#include +#include +#include + +/* end standard C headers. */ + +/* flex integer type definitions */ + +#ifndef FLEXINT_H +#define FLEXINT_H + +/* C99 systems have . Non-C99 systems may or may not. */ + +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + +/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, + * if you want the limit (max/min) macros for int types. + */ +#ifndef __STDC_LIMIT_MACROS +#define __STDC_LIMIT_MACROS 1 +#endif + +#include +typedef int8_t flex_int8_t; +typedef uint8_t flex_uint8_t; +typedef int16_t flex_int16_t; +typedef uint16_t flex_uint16_t; +typedef int32_t flex_int32_t; +typedef uint32_t flex_uint32_t; +#else +typedef signed char flex_int8_t; +typedef short int flex_int16_t; +typedef int flex_int32_t; +typedef unsigned char flex_uint8_t; +typedef unsigned short int flex_uint16_t; +typedef unsigned int flex_uint32_t; + +/* Limits of integral types. */ +#ifndef INT8_MIN +#define INT8_MIN (-128) +#endif +#ifndef INT16_MIN +#define INT16_MIN (-32767-1) +#endif +#ifndef INT32_MIN +#define INT32_MIN (-2147483647-1) +#endif +#ifndef INT8_MAX +#define INT8_MAX (127) +#endif +#ifndef INT16_MAX +#define INT16_MAX (32767) +#endif +#ifndef INT32_MAX +#define INT32_MAX (2147483647) +#endif +#ifndef UINT8_MAX +#define UINT8_MAX (255U) +#endif +#ifndef UINT16_MAX +#define UINT16_MAX (65535U) +#endif +#ifndef UINT32_MAX +#define UINT32_MAX (4294967295U) +#endif + +#endif /* ! C99 */ + +#endif /* ! FLEXINT_H */ + +/* TODO: this is always defined, so inline it */ +#define yyconst const + +#if defined(__GNUC__) && __GNUC__ >= 3 +#define yynoreturn __attribute__((__noreturn__)) +#else +#define yynoreturn +#endif + +/* Returned upon end-of-file. */ +#define YY_NULL 0 + +/* Promotes a possibly negative, possibly signed char to an unsigned + * integer for use as an array index. If the signed char is negative, + * we want to instead treat it as an 8-bit unsigned char, hence the + * double cast. + */ +#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) + +/* An opaque pointer. */ +#ifndef YY_TYPEDEF_YY_SCANNER_T +#define YY_TYPEDEF_YY_SCANNER_T +typedef void* yyscan_t; +#endif + +/* For convenience, these vars (plus the bison vars far below) + are macros in the reentrant scanner. */ +#define yyin yyg->yyin_r +#define yyout yyg->yyout_r +#define yyextra yyg->yyextra_r +#define yyleng yyg->yyleng_r +#define yytext yyg->yytext_r +#define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) +#define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) +#define yy_flex_debug yyg->yy_flex_debug_r + +/* Enter a start condition. This macro really ought to take a parameter, + * but we do it the disgusting crufty way forced on us by the ()-less + * definition of BEGIN. + */ +#define BEGIN yyg->yy_start = 1 + 2 * + +/* Translate the current start state into a value that can be later handed + * to BEGIN to return to the state. The YYSTATE alias is for lex + * compatibility. + */ +#define YY_START ((yyg->yy_start - 1) / 2) +#define YYSTATE YY_START + +/* Action number for EOF rule of a given start state. */ +#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) + +/* Special action meaning "start processing a new file". */ +#define YY_NEW_FILE freesasa_yyrestart(yyin ,yyscanner ) + +#define YY_END_OF_BUFFER_CHAR 0 + +/* Size of default input buffer. */ +#ifndef YY_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k. + * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. + * Ditto for the __ia64__ case accordingly. + */ +#define YY_BUF_SIZE 32768 +#else +#define YY_BUF_SIZE 16384 +#endif /* __ia64__ */ +#endif + +/* The state buf must be large enough to hold one state per character in the main buffer. + */ +#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) + +#ifndef YY_TYPEDEF_YY_BUFFER_STATE +#define YY_TYPEDEF_YY_BUFFER_STATE +typedef struct yy_buffer_state *YY_BUFFER_STATE; +#endif + +#ifndef YY_TYPEDEF_YY_SIZE_T +#define YY_TYPEDEF_YY_SIZE_T +typedef size_t yy_size_t; +#endif + +#define EOB_ACT_CONTINUE_SCAN 0 +#define EOB_ACT_END_OF_FILE 1 +#define EOB_ACT_LAST_MATCH 2 + + #define YY_LESS_LINENO(n) + #define YY_LINENO_REWIND_TO(ptr) + +/* Return all but the first "n" matched characters back to the input stream. */ +#define yyless(n) \ + do \ + { \ + /* Undo effects of setting up yytext. */ \ + int yyless_macro_arg = (n); \ + YY_LESS_LINENO(yyless_macro_arg);\ + *yy_cp = yyg->yy_hold_char; \ + YY_RESTORE_YY_MORE_OFFSET \ + yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ + YY_DO_BEFORE_ACTION; /* set up yytext again */ \ + } \ + while ( 0 ) + +#define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) + +#ifndef YY_STRUCT_YY_BUFFER_STATE +#define YY_STRUCT_YY_BUFFER_STATE +struct yy_buffer_state + { + FILE *yy_input_file; + + char *yy_ch_buf; /* input buffer */ + char *yy_buf_pos; /* current position in input buffer */ + + /* Size of input buffer in bytes, not including room for EOB + * characters. + */ + int yy_buf_size; + + /* Number of characters read into yy_ch_buf, not including EOB + * characters. + */ + int yy_n_chars; + + /* Whether we "own" the buffer - i.e., we know we created it, + * and can realloc() it to grow it, and should free() it to + * delete it. + */ + int yy_is_our_buffer; + + /* Whether this is an "interactive" input source; if so, and + * if we're using stdio for input, then we want to use getc() + * instead of fread(), to make sure we stop fetching input after + * each newline. + */ + int yy_is_interactive; + + /* Whether we're considered to be at the beginning of a line. + * If so, '^' rules will be active on the next match, otherwise + * not. + */ + int yy_at_bol; + + int yy_bs_lineno; /**< The line count. */ + int yy_bs_column; /**< The column count. */ + + /* Whether to try to fill the input buffer when we reach the + * end of it. + */ + int yy_fill_buffer; + + int yy_buffer_status; + +#define YY_BUFFER_NEW 0 +#define YY_BUFFER_NORMAL 1 + /* When an EOF's been seen but there's still some text to process + * then we mark the buffer as YY_EOF_PENDING, to indicate that we + * shouldn't try reading from the input source any more. We might + * still have a bunch of tokens to match, though, because of + * possible backing-up. + * + * When we actually see the EOF, we change the status to "new" + * (via freesasa_yyrestart()), so that the user can continue scanning by + * just pointing yyin at a new input file. + */ +#define YY_BUFFER_EOF_PENDING 2 + + }; +#endif /* !YY_STRUCT_YY_BUFFER_STATE */ + +/* We provide macros for accessing buffer states in case in the + * future we want to put the buffer states in a more general + * "scanner state". + * + * Returns the top of the stack, or NULL. + */ +#define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ + ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ + : NULL) + +/* Same as previous macro, but useful when we know that the buffer stack is not + * NULL or when we need an lvalue. For internal use only. + */ +#define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] + +void freesasa_yyrestart (FILE *input_file ,yyscan_t yyscanner ); +void freesasa_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); +YY_BUFFER_STATE freesasa_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); +void freesasa_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); +void freesasa_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); +void freesasa_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); +void freesasa_yypop_buffer_state (yyscan_t yyscanner ); + +static void freesasa_yyensure_buffer_stack (yyscan_t yyscanner ); +static void freesasa_yy_load_buffer_state (yyscan_t yyscanner ); +static void freesasa_yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); + +#define YY_FLUSH_BUFFER freesasa_yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) + +YY_BUFFER_STATE freesasa_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); +YY_BUFFER_STATE freesasa_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); +YY_BUFFER_STATE freesasa_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner ); + +void *freesasa_yyalloc (yy_size_t ,yyscan_t yyscanner ); +void *freesasa_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); +void freesasa_yyfree (void * ,yyscan_t yyscanner ); + +#define yy_new_buffer freesasa_yy_create_buffer + +#define yy_set_interactive(is_interactive) \ + { \ + if ( ! YY_CURRENT_BUFFER ){ \ + freesasa_yyensure_buffer_stack (yyscanner); \ + YY_CURRENT_BUFFER_LVALUE = \ + freesasa_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ + } \ + YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ + } + +#define yy_set_bol(at_bol) \ + { \ + if ( ! YY_CURRENT_BUFFER ){\ + freesasa_yyensure_buffer_stack (yyscanner); \ + YY_CURRENT_BUFFER_LVALUE = \ + freesasa_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ + } \ + YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ + } + +#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) + +#define freesasa_yywrap(yyscanner) (/*CONSTCOND*/1) +#define YY_SKIP_YYWRAP + +typedef unsigned char YY_CHAR; + +typedef int yy_state_type; + +#define yytext_ptr yytext_r + +static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); +static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); +static int yy_get_next_buffer (yyscan_t yyscanner ); +static void yynoreturn yy_fatal_error (yyconst char* msg ,yyscan_t yyscanner ); + +/* Done after the current pattern has been matched and before the + * corresponding action - sets up yytext. + */ +#define YY_DO_BEFORE_ACTION \ + yyg->yytext_ptr = yy_bp; \ + yyleng = (int) (yy_cp - yy_bp); \ + yyg->yy_hold_char = *yy_cp; \ + *yy_cp = '\0'; \ + yyg->yy_c_buf_p = yy_cp; + +#define YY_NUM_RULES 19 +#define YY_END_OF_BUFFER 20 +/* This struct is not used in this scanner, + but its presence is necessary. */ +struct yy_trans_info + { + flex_int32_t yy_verify; + flex_int32_t yy_nxt; + }; +static yyconst flex_int16_t yy_accept[52] = + { 0, + 15, 15, 20, 19, 15, 13, 11, 4, 5, 3, + 1, 2, 16, 17, 17, 17, 17, 17, 17, 17, + 19, 12, 15, 0, 18, 17, 16, 17, 17, 17, + 17, 17, 12, 17, 17, 14, 11, 17, 17, 13, + 17, 17, 17, 9, 7, 6, 17, 10, 17, 8, + 0 + } ; + +static yyconst YY_CHAR yy_ec[256] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, + 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 2, 3, 1, 1, 1, 1, 4, 5, 6, + 7, 1, 8, 9, 10, 1, 1, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 1, 1, 1, + 1, 1, 1, 1, 12, 13, 14, 15, 16, 17, + 17, 18, 19, 17, 17, 20, 21, 22, 23, 17, + 17, 24, 25, 26, 17, 17, 17, 17, 27, 17, + 1, 28, 1, 1, 17, 1, 29, 30, 31, 32, + + 33, 17, 17, 34, 35, 17, 17, 36, 37, 38, + 39, 17, 17, 40, 41, 42, 17, 17, 17, 17, + 43, 17, 1, 44, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1 + } ; + +static yyconst YY_CHAR yy_meta[45] = + { 0, + 1, 1, 1, 1, 2, 1, 1, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 1 + } ; + +static yyconst flex_uint16_t yy_base[54] = + { 0, + 0, 0, 68, 281, 64, 281, 281, 281, 281, 56, + 281, 51, 40, 47, 53, 62, 92, 68, 74, 101, + 49, 281, 52, 44, 281, 42, 108, 115, 124, 52, + 114, 126, 118, 138, 152, 281, 147, 159, 180, 172, + 208, 187, 183, 203, 210, 214, 185, 211, 239, 232, + 281, 43, 277 + } ; + +static yyconst flex_int16_t yy_def[54] = + { 0, + 51, 1, 51, 51, 51, 51, 51, 51, 51, 52, + 51, 52, 53, 53, 53, 53, 53, 53, 53, 53, + 51, 51, 51, 52, 51, 51, 53, 53, 53, 17, + 17, 17, 17, 17, 17, 51, 17, 17, 17, 17, + 17, 17, 41, 41, 41, 41, 17, 17, 17, 17, + 0, 51, 51 + } ; + +static yyconst flex_uint16_t yy_nxt[326] = + { 0, + 4, 5, 6, 7, 4, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 15, 15, 15, 15, 15, 15, + 15, 17, 18, 19, 20, 15, 15, 21, 14, 15, + 16, 15, 15, 15, 15, 15, 15, 17, 18, 19, + 20, 15, 15, 22, 26, 24, 26, 24, 25, 24, + 27, 26, 25, 23, 24, 25, 24, 26, 36, 25, + 24, 25, 24, 38, 25, 23, 26, 51, 29, 24, + 25, 24, 26, 51, 28, 24, 25, 24, 26, 30, + 38, 24, 25, 24, 29, 51, 51, 51, 51, 34, + 28, 33, 51, 51, 51, 30, 26, 51, 51, 24, + + 25, 24, 51, 31, 51, 26, 34, 33, 24, 25, + 24, 51, 26, 51, 32, 24, 25, 24, 27, 26, + 31, 51, 24, 25, 24, 28, 51, 35, 26, 28, + 32, 24, 25, 24, 39, 51, 28, 28, 37, 51, + 28, 51, 28, 35, 51, 51, 28, 51, 28, 28, + 39, 40, 28, 51, 28, 37, 28, 51, 28, 51, + 28, 51, 41, 28, 28, 51, 28, 40, 51, 28, + 28, 51, 42, 51, 28, 28, 28, 43, 41, 51, + 28, 28, 51, 28, 51, 28, 51, 28, 42, 51, + 28, 28, 51, 43, 28, 44, 28, 28, 28, 47, + + 28, 28, 28, 51, 48, 51, 51, 49, 28, 28, + 28, 51, 44, 28, 51, 28, 47, 28, 28, 28, + 48, 28, 28, 49, 28, 28, 45, 51, 28, 46, + 28, 28, 28, 28, 51, 28, 28, 28, 51, 28, + 28, 51, 45, 28, 28, 46, 28, 28, 28, 28, + 28, 28, 51, 51, 28, 51, 51, 51, 50, 51, + 28, 28, 51, 51, 51, 51, 51, 28, 51, 51, + 28, 51, 51, 51, 50, 51, 51, 28, 28, 28, + 3, 51, 51, 51, 51, 51, 51, 51, 51, 51, + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, + + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, + 51, 51, 51, 51, 51 + } ; + +static yyconst flex_int16_t yy_chk[326] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 13, 52, 26, 13, 13, 13, + 13, 14, 24, 23, 14, 14, 14, 15, 21, 12, + 15, 15, 15, 30, 10, 5, 16, 3, 14, 16, + 16, 16, 18, 0, 30, 18, 18, 18, 19, 16, + 30, 19, 19, 19, 14, 0, 0, 0, 0, 19, + 30, 18, 0, 0, 0, 16, 17, 0, 0, 17, + + 17, 17, 0, 17, 0, 20, 19, 18, 20, 20, + 20, 0, 27, 0, 17, 27, 27, 27, 27, 28, + 17, 0, 28, 28, 28, 31, 0, 20, 29, 33, + 17, 29, 29, 29, 31, 0, 31, 32, 29, 0, + 33, 0, 31, 20, 0, 0, 33, 0, 32, 34, + 31, 32, 31, 0, 32, 29, 33, 0, 37, 0, + 34, 0, 34, 35, 32, 0, 34, 32, 0, 37, + 38, 0, 35, 0, 35, 37, 34, 38, 34, 0, + 35, 38, 0, 40, 0, 37, 0, 38, 35, 0, + 35, 39, 0, 38, 40, 39, 47, 38, 42, 42, + + 40, 43, 39, 0, 43, 0, 0, 47, 39, 42, + 40, 0, 39, 47, 0, 42, 42, 43, 39, 41, + 43, 44, 48, 47, 44, 42, 41, 0, 45, 41, + 41, 45, 46, 48, 0, 46, 41, 44, 0, 48, + 44, 0, 41, 50, 45, 41, 41, 45, 46, 48, + 49, 46, 0, 0, 50, 0, 0, 0, 49, 0, + 50, 49, 0, 0, 0, 0, 0, 49, 0, 0, + 50, 0, 0, 0, 49, 0, 0, 49, 53, 53, + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, + + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, + 51, 51, 51, 51, 51 + } ; + +/* The intent behind this definition is that it'll catch + * any uses of REJECT which flex missed. + */ +#define REJECT reject_used_but_not_detected +#define yymore() yymore_used_but_not_detected +#define YY_MORE_ADJ 0 +#define YY_RESTORE_YY_MORE_OFFSET +#line 1 "lexer.l" +#line 2 "lexer.l" + +#include "selection.h" +#include "parser.h" +#include "freesasa_internal.h" + +#include + +#define YY_NO_UNISTD_H 1 +#line 526 "lexer.c" + +#define INITIAL 0 + +#ifndef YY_EXTRA_TYPE +#define YY_EXTRA_TYPE void * +#endif + +/* Holds the entire state of the reentrant scanner. */ +struct yyguts_t + { + + /* User-defined. Not touched by flex. */ + YY_EXTRA_TYPE yyextra_r; + + /* The rest are the same as the globals declared in the non-reentrant scanner. */ + FILE *yyin_r, *yyout_r; + size_t yy_buffer_stack_top; /**< index of top of stack. */ + size_t yy_buffer_stack_max; /**< capacity of stack. */ + YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ + char yy_hold_char; + int yy_n_chars; + int yyleng_r; + char *yy_c_buf_p; + int yy_init; + int yy_start; + int yy_did_buffer_switch_on_eof; + int yy_start_stack_ptr; + int yy_start_stack_depth; + int *yy_start_stack; + yy_state_type yy_last_accepting_state; + char* yy_last_accepting_cpos; + + int yylineno_r; + int yy_flex_debug_r; + + char *yytext_r; + int yy_more_flag; + int yy_more_len; + + YYSTYPE * yylval_r; + + }; /* end struct yyguts_t */ + +static int yy_init_globals (yyscan_t yyscanner ); + + /* This must go here because YYSTYPE and YYLTYPE are included + * from bison output in section 1.*/ + # define yylval yyg->yylval_r + +int freesasa_yylex_init (yyscan_t* scanner); + +int freesasa_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); + +/* Accessor methods to globals. + These are made visible to non-reentrant scanners for convenience. */ + +int freesasa_yylex_destroy (yyscan_t yyscanner ); + +int freesasa_yyget_debug (yyscan_t yyscanner ); + +void freesasa_yyset_debug (int debug_flag ,yyscan_t yyscanner ); + +YY_EXTRA_TYPE freesasa_yyget_extra (yyscan_t yyscanner ); + +void freesasa_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); + +FILE *freesasa_yyget_in (yyscan_t yyscanner ); + +void freesasa_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); + +FILE *freesasa_yyget_out (yyscan_t yyscanner ); + +void freesasa_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); + + int freesasa_yyget_leng (yyscan_t yyscanner ); + +char *freesasa_yyget_text (yyscan_t yyscanner ); + +int freesasa_yyget_lineno (yyscan_t yyscanner ); + +void freesasa_yyset_lineno (int _line_number ,yyscan_t yyscanner ); + +int freesasa_yyget_column (yyscan_t yyscanner ); + +void freesasa_yyset_column (int _column_no ,yyscan_t yyscanner ); + +YYSTYPE * freesasa_yyget_lval (yyscan_t yyscanner ); + +void freesasa_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); + +/* Macros after this point can all be overridden by user definitions in + * section 1. + */ + +#ifndef YY_SKIP_YYWRAP +#ifdef __cplusplus +extern "C" int freesasa_yywrap (yyscan_t yyscanner ); +#else +extern int freesasa_yywrap (yyscan_t yyscanner ); +#endif +#endif + +#ifndef YY_NO_UNPUT + + static void yyunput (int c,char *buf_ptr ,yyscan_t yyscanner); + +#endif + +#ifndef yytext_ptr +static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); +#endif + +#ifdef YY_NEED_STRLEN +static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); +#endif + +#ifndef YY_NO_INPUT + +#ifdef __cplusplus +static int yyinput (yyscan_t yyscanner ); +#else +static int input (yyscan_t yyscanner ); +#endif + +#endif + +/* Amount of stuff to slurp up with each read. */ +#ifndef YY_READ_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k */ +#define YY_READ_BUF_SIZE 16384 +#else +#define YY_READ_BUF_SIZE 8192 +#endif /* __ia64__ */ +#endif + +/* Copy whatever the last rule matched to the standard output. */ +#ifndef ECHO +/* This used to be an fputs(), but since the string might contain NUL's, + * we now use fwrite(). + */ +#define ECHO do { if (fwrite( yytext, (size_t) yyleng, 1, yyout )) {} } while (0) +#endif + +/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, + * is returned in "result". + */ +#ifndef YY_INPUT +#define YY_INPUT(buf,result,max_size) \ + if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ + { \ + int c = '*'; \ + size_t n; \ + for ( n = 0; n < max_size && \ + (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ + buf[n] = (char) c; \ + if ( c == '\n' ) \ + buf[n++] = (char) c; \ + if ( c == EOF && ferror( yyin ) ) \ + YY_FATAL_ERROR( "input in flex scanner failed" ); \ + result = n; \ + } \ + else \ + { \ + errno=0; \ + while ( (result = (int) fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ + { \ + if( errno != EINTR) \ + { \ + YY_FATAL_ERROR( "input in flex scanner failed" ); \ + break; \ + } \ + errno=0; \ + clearerr(yyin); \ + } \ + }\ +\ + +#endif + +/* No semi-colon after return; correct usage is to write "yyterminate();" - + * we don't want an extra ';' after the "return" because that will cause + * some compilers to complain about unreachable statements. + */ +#ifndef yyterminate +#define yyterminate() return YY_NULL +#endif + +/* Number of entries by which start-condition stack grows. */ +#ifndef YY_START_STACK_INCR +#define YY_START_STACK_INCR 25 +#endif + +/* Report a fatal error. */ +#ifndef YY_FATAL_ERROR +#define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) +#endif + +/* end tables serialization structures and prototypes */ + +/* Default declaration of generated scanner - a define so the user can + * easily add parameters. + */ +#ifndef YY_DECL +#define YY_DECL_IS_OURS 1 + +extern int freesasa_yylex \ + (YYSTYPE * yylval_param ,yyscan_t yyscanner); + +#define YY_DECL int freesasa_yylex \ + (YYSTYPE * yylval_param , yyscan_t yyscanner) +#endif /* !YY_DECL */ + +/* Code executed at the beginning of each rule, after yytext and yyleng + * have been set up. + */ +#ifndef YY_USER_ACTION +#define YY_USER_ACTION +#endif + +/* Code executed at the end of each rule. */ +#ifndef YY_BREAK +#define YY_BREAK /*LINTED*/break; +#endif + +#define YY_RULE_SETUP \ + YY_USER_ACTION + +/** The main scanner function which does all the work. + */ +YY_DECL +{ + yy_state_type yy_current_state; + char *yy_cp, *yy_bp; + int yy_act; + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + yylval = yylval_param; + + if ( !yyg->yy_init ) + { + yyg->yy_init = 1; + +#ifdef YY_USER_INIT + YY_USER_INIT; +#endif + + if ( ! yyg->yy_start ) + yyg->yy_start = 1; /* first start state */ + + if ( ! yyin ) + yyin = stdin; + + if ( ! yyout ) + yyout = stdout; + + if ( ! YY_CURRENT_BUFFER ) { + freesasa_yyensure_buffer_stack (yyscanner); + YY_CURRENT_BUFFER_LVALUE = + freesasa_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); + } + + freesasa_yy_load_buffer_state(yyscanner ); + } + + { +#line 32 "lexer.l" + + +#line 796 "lexer.c" + + while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ + { + yy_cp = yyg->yy_c_buf_p; + + /* Support of yytext. */ + *yy_cp = yyg->yy_hold_char; + + /* yy_bp points to the position in yy_ch_buf of the start of + * the current run. + */ + yy_bp = yy_cp; + + yy_current_state = yyg->yy_start; +yy_match: + do + { + YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; + if ( yy_accept[yy_current_state] ) + { + yyg->yy_last_accepting_state = yy_current_state; + yyg->yy_last_accepting_cpos = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 52 ) + yy_c = yy_meta[(unsigned int) yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c]; + ++yy_cp; + } + while ( yy_current_state != 51 ); + yy_cp = yyg->yy_last_accepting_cpos; + yy_current_state = yyg->yy_last_accepting_state; + +yy_find_action: + yy_act = yy_accept[yy_current_state]; + + YY_DO_BEFORE_ACTION; + +do_action: /* This label is used only to access EOF actions. */ + + switch ( yy_act ) + { /* beginning of action switch */ + case 0: /* must back up */ + /* undo the effects of YY_DO_BEFORE_ACTION */ + *yy_cp = yyg->yy_hold_char; + yy_cp = yyg->yy_last_accepting_cpos; + yy_current_state = yyg->yy_last_accepting_state; + goto yy_find_action; + +case 1: +YY_RULE_SETUP +#line 34 "lexer.l" +{ return ','; } + YY_BREAK +case 2: +YY_RULE_SETUP +#line 35 "lexer.l" +{ return '-'; } + YY_BREAK +case 3: +YY_RULE_SETUP +#line 36 "lexer.l" +{ return '+'; } + YY_BREAK +case 4: +YY_RULE_SETUP +#line 37 "lexer.l" +{ return '('; } + YY_BREAK +case 5: +YY_RULE_SETUP +#line 38 "lexer.l" +{ return ')'; } + YY_BREAK +case 6: +YY_RULE_SETUP +#line 40 "lexer.l" +{ return T_RESN; } + YY_BREAK +case 7: +YY_RULE_SETUP +#line 41 "lexer.l" +{ return T_RESI; } + YY_BREAK +case 8: +YY_RULE_SETUP +#line 42 "lexer.l" +{ return T_SYMBOL; } + YY_BREAK +case 9: +YY_RULE_SETUP +#line 43 "lexer.l" +{ return T_NAME; } + YY_BREAK +case 10: +YY_RULE_SETUP +#line 44 "lexer.l" +{ return T_CHAIN; } + YY_BREAK +case 11: +YY_RULE_SETUP +#line 46 "lexer.l" +{ return T_AND; } + YY_BREAK +case 12: +YY_RULE_SETUP +#line 47 "lexer.l" +{ return T_OR; } + YY_BREAK +case 13: +YY_RULE_SETUP +#line 48 "lexer.l" +{ return T_NOT; } + YY_BREAK +case 14: +YY_RULE_SETUP +#line 49 "lexer.l" +{ return T_MINUS; } + YY_BREAK +case 15: +/* rule 15 can match eol */ +YY_RULE_SETUP +#line 51 "lexer.l" +{} + YY_BREAK +case 16: +YY_RULE_SETUP +#line 52 "lexer.l" +{ yylval->value = strdup(yytext); return T_NUMBER; } + YY_BREAK +case 17: +YY_RULE_SETUP +#line 53 "lexer.l" +{ yylval->value = strdup(yytext); return T_ID; } + YY_BREAK +case 18: +*yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ +yyg->yy_c_buf_p = yy_cp -= 1; +YY_DO_BEFORE_ACTION; /* set up yytext again */ +YY_RULE_SETUP +#line 54 "lexer.l" +{ yylval->value = strdup(yytext); return T_SELID; } + YY_BREAK +case 19: +YY_RULE_SETUP +#line 55 "lexer.l" +ECHO; + YY_BREAK +#line 948 "lexer.c" +case YY_STATE_EOF(INITIAL): + yyterminate(); + + case YY_END_OF_BUFFER: + { + /* Amount of text matched not including the EOB char. */ + int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; + + /* Undo the effects of YY_DO_BEFORE_ACTION. */ + *yy_cp = yyg->yy_hold_char; + YY_RESTORE_YY_MORE_OFFSET + + if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) + { + /* We're scanning a new file or input source. It's + * possible that this happened because the user + * just pointed yyin at a new source and called + * freesasa_yylex(). If so, then we have to assure + * consistency between YY_CURRENT_BUFFER and our + * globals. Here is the right place to do so, because + * this is the first action (other than possibly a + * back-up) that will match for the new input source. + */ + yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; + YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; + YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; + } + + /* Note that here we test for yy_c_buf_p "<=" to the position + * of the first EOB in the buffer, since yy_c_buf_p will + * already have been incremented past the NUL character + * (since all states make transitions on EOB to the + * end-of-buffer state). Contrast this with the test + * in input(). + */ + if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) + { /* This was really a NUL. */ + yy_state_type yy_next_state; + + yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state( yyscanner ); + + /* Okay, we're now positioned to make the NUL + * transition. We couldn't have + * yy_get_previous_state() go ahead and do it + * for us because it doesn't know how to deal + * with the possibility of jamming (and we don't + * want to build jamming into it because then it + * will run more slowly). + */ + + yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); + + yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; + + if ( yy_next_state ) + { + /* Consume the NUL. */ + yy_cp = ++yyg->yy_c_buf_p; + yy_current_state = yy_next_state; + goto yy_match; + } + + else + { + yy_cp = yyg->yy_last_accepting_cpos; + yy_current_state = yyg->yy_last_accepting_state; + goto yy_find_action; + } + } + + else switch ( yy_get_next_buffer( yyscanner ) ) + { + case EOB_ACT_END_OF_FILE: + { + yyg->yy_did_buffer_switch_on_eof = 0; + + if ( freesasa_yywrap(yyscanner ) ) + { + /* Note: because we've taken care in + * yy_get_next_buffer() to have set up + * yytext, we can now set up + * yy_c_buf_p so that if some total + * hoser (like flex itself) wants to + * call the scanner after we return the + * YY_NULL, it'll still work - another + * YY_NULL will get returned. + */ + yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; + + yy_act = YY_STATE_EOF(YY_START); + goto do_action; + } + + else + { + if ( ! yyg->yy_did_buffer_switch_on_eof ) + YY_NEW_FILE; + } + break; + } + + case EOB_ACT_CONTINUE_SCAN: + yyg->yy_c_buf_p = + yyg->yytext_ptr + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state( yyscanner ); + + yy_cp = yyg->yy_c_buf_p; + yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; + goto yy_match; + + case EOB_ACT_LAST_MATCH: + yyg->yy_c_buf_p = + &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; + + yy_current_state = yy_get_previous_state( yyscanner ); + + yy_cp = yyg->yy_c_buf_p; + yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; + goto yy_find_action; + } + break; + } + + default: + YY_FATAL_ERROR( + "fatal flex scanner internal error--no action found" ); + } /* end of action switch */ + } /* end of scanning one token */ + } /* end of user's declarations */ +} /* end of freesasa_yylex */ + +/* yy_get_next_buffer - try to read in a new buffer + * + * Returns a code representing an action: + * EOB_ACT_LAST_MATCH - + * EOB_ACT_CONTINUE_SCAN - continue scanning from current position + * EOB_ACT_END_OF_FILE - end of file + */ +static int yy_get_next_buffer (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; + char *source = yyg->yytext_ptr; + yy_size_t number_to_move, i; + int ret_val; + + if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) + YY_FATAL_ERROR( + "fatal flex scanner internal error--end of buffer missed" ); + + if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) + { /* Don't try to fill the buffer, so this is an EOF. */ + if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) + { + /* We matched a single character, the EOB, so + * treat this as a final EOF. + */ + return EOB_ACT_END_OF_FILE; + } + + else + { + /* We matched some text prior to the EOB, first + * process it. + */ + return EOB_ACT_LAST_MATCH; + } + } + + /* Try to read more data. */ + + /* First move last chars to start of buffer. */ + number_to_move = (yy_size_t) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; + + for ( i = 0; i < number_to_move; ++i ) + *(dest++) = *(source++); + + if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) + /* don't do the read, it's not guaranteed to return an EOF, + * just force an EOF + */ + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; + + else + { + int num_to_read = + YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; + + while ( num_to_read <= 0 ) + { /* Not enough room in the buffer - grow it. */ + + /* just a shorter name for the current buffer */ + YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE; + + int yy_c_buf_p_offset = + (int) (yyg->yy_c_buf_p - b->yy_ch_buf); + + if ( b->yy_is_our_buffer ) + { + int new_size = b->yy_buf_size * 2; + + if ( new_size <= 0 ) + b->yy_buf_size += b->yy_buf_size / 8; + else + b->yy_buf_size *= 2; + + b->yy_ch_buf = (char *) + /* Include room in for 2 EOB chars. */ + freesasa_yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); + } + else + /* Can't grow it, we don't own it. */ + b->yy_ch_buf = NULL; + + if ( ! b->yy_ch_buf ) + YY_FATAL_ERROR( + "fatal error - scanner input buffer overflow" ); + + yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; + + num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - + number_to_move - 1; + + } + + if ( num_to_read > YY_READ_BUF_SIZE ) + num_to_read = YY_READ_BUF_SIZE; + + /* Read in more data. */ + YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), + yyg->yy_n_chars, num_to_read ); + + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; + } + + if ( yyg->yy_n_chars == 0 ) + { + if ( number_to_move == YY_MORE_ADJ ) + { + ret_val = EOB_ACT_END_OF_FILE; + freesasa_yyrestart(yyin ,yyscanner); + } + + else + { + ret_val = EOB_ACT_LAST_MATCH; + YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = + YY_BUFFER_EOF_PENDING; + } + } + + else + ret_val = EOB_ACT_CONTINUE_SCAN; + + if ((int) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { + /* Extend the array by 50%, plus the number we really need. */ + int new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) freesasa_yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); + if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) + YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); + } + + yyg->yy_n_chars += number_to_move; + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; + YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; + + yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; + + return ret_val; +} + +/* yy_get_previous_state - get the state just before the EOB char was reached */ + + static yy_state_type yy_get_previous_state (yyscan_t yyscanner) +{ + yy_state_type yy_current_state; + char *yy_cp; + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + yy_current_state = yyg->yy_start; + + for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) + { + YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); + if ( yy_accept[yy_current_state] ) + { + yyg->yy_last_accepting_state = yy_current_state; + yyg->yy_last_accepting_cpos = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 52 ) + yy_c = yy_meta[(unsigned int) yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c]; + } + + return yy_current_state; +} + +/* yy_try_NUL_trans - try to make a transition on the NUL character + * + * synopsis + * next_state = yy_try_NUL_trans( current_state ); + */ + static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) +{ + int yy_is_jam; + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ + char *yy_cp = yyg->yy_c_buf_p; + + YY_CHAR yy_c = 1; + if ( yy_accept[yy_current_state] ) + { + yyg->yy_last_accepting_state = yy_current_state; + yyg->yy_last_accepting_cpos = yy_cp; + } + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 52 ) + yy_c = yy_meta[(unsigned int) yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (flex_int16_t) yy_c]; + yy_is_jam = (yy_current_state == 51); + + (void)yyg; + return yy_is_jam ? 0 : yy_current_state; +} + +#ifndef YY_NO_UNPUT + + static void yyunput (int c, char * yy_bp , yyscan_t yyscanner) +{ + char *yy_cp; + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + yy_cp = yyg->yy_c_buf_p; + + /* undo effects of setting up yytext */ + *yy_cp = yyg->yy_hold_char; + + if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) + { /* need to shift things up to make room */ + /* +2 for EOB chars. */ + int number_to_move = yyg->yy_n_chars + 2; + char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ + YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; + char *source = + &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; + + while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) + *--dest = *--source; + + yy_cp += (int) (dest - source); + yy_bp += (int) (dest - source); + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = + yyg->yy_n_chars = (int) YY_CURRENT_BUFFER_LVALUE->yy_buf_size; + + if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) + YY_FATAL_ERROR( "flex scanner push-back overflow" ); + } + + *--yy_cp = (char) c; + + yyg->yytext_ptr = yy_bp; + yyg->yy_hold_char = *yy_cp; + yyg->yy_c_buf_p = yy_cp; +} + +#endif + +#ifndef YY_NO_INPUT +#ifdef __cplusplus + static int yyinput (yyscan_t yyscanner) +#else + static int input (yyscan_t yyscanner) +#endif + +{ + int c; + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + *yyg->yy_c_buf_p = yyg->yy_hold_char; + + if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) + { + /* yy_c_buf_p now points to the character we want to return. + * If this occurs *before* the EOB characters, then it's a + * valid NUL; if not, then we've hit the end of the buffer. + */ + if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) + /* This was really a NUL. */ + *yyg->yy_c_buf_p = '\0'; + + else + { /* need more input */ + int offset = yyg->yy_c_buf_p - yyg->yytext_ptr; + ++yyg->yy_c_buf_p; + + switch ( yy_get_next_buffer( yyscanner ) ) + { + case EOB_ACT_LAST_MATCH: + /* This happens because yy_g_n_b() + * sees that we've accumulated a + * token and flags that we need to + * try matching the token before + * proceeding. But for input(), + * there's no matching to consider. + * So convert the EOB_ACT_LAST_MATCH + * to EOB_ACT_END_OF_FILE. + */ + + /* Reset buffer status. */ + freesasa_yyrestart(yyin ,yyscanner); + + /*FALLTHROUGH*/ + + case EOB_ACT_END_OF_FILE: + { + if ( freesasa_yywrap(yyscanner ) ) + return 0; + + if ( ! yyg->yy_did_buffer_switch_on_eof ) + YY_NEW_FILE; +#ifdef __cplusplus + return yyinput(yyscanner); +#else + return input(yyscanner); +#endif + } + + case EOB_ACT_CONTINUE_SCAN: + yyg->yy_c_buf_p = yyg->yytext_ptr + offset; + break; + } + } + } + + c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ + *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ + yyg->yy_hold_char = *++yyg->yy_c_buf_p; + + return c; +} +#endif /* ifndef YY_NO_INPUT */ + +/** Immediately switch to a different input stream. + * @param input_file A readable stream. + * @param yyscanner The scanner object. + * @note This function does not reset the start condition to @c INITIAL . + */ + void freesasa_yyrestart (FILE * input_file , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + if ( ! YY_CURRENT_BUFFER ){ + freesasa_yyensure_buffer_stack (yyscanner); + YY_CURRENT_BUFFER_LVALUE = + freesasa_yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); + } + + freesasa_yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); + freesasa_yy_load_buffer_state(yyscanner ); +} + +/** Switch to a different input buffer. + * @param new_buffer The new input buffer. + * @param yyscanner The scanner object. + */ + void freesasa_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + /* TODO. We should be able to replace this entire function body + * with + * freesasa_yypop_buffer_state(); + * freesasa_yypush_buffer_state(new_buffer); + */ + freesasa_yyensure_buffer_stack (yyscanner); + if ( YY_CURRENT_BUFFER == new_buffer ) + return; + + if ( YY_CURRENT_BUFFER ) + { + /* Flush out information for old buffer. */ + *yyg->yy_c_buf_p = yyg->yy_hold_char; + YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; + } + + YY_CURRENT_BUFFER_LVALUE = new_buffer; + freesasa_yy_load_buffer_state(yyscanner ); + + /* We don't actually know whether we did this switch during + * EOF (freesasa_yywrap()) processing, but the only time this flag + * is looked at is after freesasa_yywrap() is called, so it's safe + * to go ahead and always set it. + */ + yyg->yy_did_buffer_switch_on_eof = 1; +} + +static void freesasa_yy_load_buffer_state (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; + yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; + yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; + yyg->yy_hold_char = *yyg->yy_c_buf_p; +} + +/** Allocate and initialize an input buffer state. + * @param file A readable stream. + * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. + * @param yyscanner The scanner object. + * @return the allocated buffer state. + */ + YY_BUFFER_STATE freesasa_yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) +{ + YY_BUFFER_STATE b; + + b = (YY_BUFFER_STATE) freesasa_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); + if ( ! b ) + YY_FATAL_ERROR( "out of dynamic memory in freesasa_yy_create_buffer()" ); + + b->yy_buf_size = (yy_size_t)size; + + /* yy_ch_buf has to be 2 characters longer than the size given because + * we need to put in 2 end-of-buffer characters. + */ + b->yy_ch_buf = (char *) freesasa_yyalloc(b->yy_buf_size + 2 ,yyscanner ); + if ( ! b->yy_ch_buf ) + YY_FATAL_ERROR( "out of dynamic memory in freesasa_yy_create_buffer()" ); + + b->yy_is_our_buffer = 1; + + freesasa_yy_init_buffer(b,file ,yyscanner); + + return b; +} + +/** Destroy the buffer. + * @param b a buffer created with freesasa_yy_create_buffer() + * @param yyscanner The scanner object. + */ + void freesasa_yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + if ( ! b ) + return; + + if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ + YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; + + if ( b->yy_is_our_buffer ) + freesasa_yyfree((void *) b->yy_ch_buf ,yyscanner ); + + freesasa_yyfree((void *) b ,yyscanner ); +} + +/* Initializes or reinitializes a buffer. + * This function is sometimes called more than once on the same buffer, + * such as during a freesasa_yyrestart() or at EOF. + */ + static void freesasa_yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) + +{ + int oerrno = errno; + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + freesasa_yy_flush_buffer(b ,yyscanner); + + b->yy_input_file = file; + b->yy_fill_buffer = 1; + + /* If b is the current buffer, then freesasa_yy_init_buffer was _probably_ + * called from freesasa_yyrestart() or through yy_get_next_buffer. + * In that case, we don't want to reset the lineno or column. + */ + if (b != YY_CURRENT_BUFFER){ + b->yy_bs_lineno = 1; + b->yy_bs_column = 0; + } + + b->yy_is_interactive = 0; + + errno = oerrno; +} + +/** Discard all buffered characters. On the next scan, YY_INPUT will be called. + * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. + * @param yyscanner The scanner object. + */ + void freesasa_yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + if ( ! b ) + return; + + b->yy_n_chars = 0; + + /* We always need two end-of-buffer characters. The first causes + * a transition to the end-of-buffer state. The second causes + * a jam in that state. + */ + b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; + b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; + + b->yy_buf_pos = &b->yy_ch_buf[0]; + + b->yy_at_bol = 1; + b->yy_buffer_status = YY_BUFFER_NEW; + + if ( b == YY_CURRENT_BUFFER ) + freesasa_yy_load_buffer_state(yyscanner ); +} + +/** Pushes the new state onto the stack. The new state becomes + * the current state. This function will allocate the stack + * if necessary. + * @param new_buffer The new state. + * @param yyscanner The scanner object. + */ +void freesasa_yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + if (new_buffer == NULL) + return; + + freesasa_yyensure_buffer_stack(yyscanner); + + /* This block is copied from freesasa_yy_switch_to_buffer. */ + if ( YY_CURRENT_BUFFER ) + { + /* Flush out information for old buffer. */ + *yyg->yy_c_buf_p = yyg->yy_hold_char; + YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; + YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; + } + + /* Only push if top exists. Otherwise, replace top. */ + if (YY_CURRENT_BUFFER) + yyg->yy_buffer_stack_top++; + YY_CURRENT_BUFFER_LVALUE = new_buffer; + + /* copied from freesasa_yy_switch_to_buffer. */ + freesasa_yy_load_buffer_state(yyscanner ); + yyg->yy_did_buffer_switch_on_eof = 1; +} + +/** Removes and deletes the top of the stack, if present. + * The next element becomes the new top. + * @param yyscanner The scanner object. + */ +void freesasa_yypop_buffer_state (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + if (!YY_CURRENT_BUFFER) + return; + + freesasa_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); + YY_CURRENT_BUFFER_LVALUE = NULL; + if (yyg->yy_buffer_stack_top > 0) + --yyg->yy_buffer_stack_top; + + if (YY_CURRENT_BUFFER) { + freesasa_yy_load_buffer_state(yyscanner ); + yyg->yy_did_buffer_switch_on_eof = 1; + } +} + +/* Allocates the stack if it does not exist. + * Guarantees space for at least one push. + */ +static void freesasa_yyensure_buffer_stack (yyscan_t yyscanner) +{ + int num_to_alloc; + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + if (!yyg->yy_buffer_stack) { + + /* First allocation is just for 2 elements, since we don't know if this + * scanner will even need a stack. We use 2 instead of 1 to avoid an + * immediate realloc on the next call. + */ + num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */ + yyg->yy_buffer_stack = (struct yy_buffer_state**)freesasa_yyalloc + (num_to_alloc * sizeof(struct yy_buffer_state*) + , yyscanner); + if ( ! yyg->yy_buffer_stack ) + YY_FATAL_ERROR( "out of dynamic memory in freesasa_yyensure_buffer_stack()" ); + + memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); + + yyg->yy_buffer_stack_max = num_to_alloc; + yyg->yy_buffer_stack_top = 0; + return; + } + + if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ + + /* Increase the buffer to prepare for a possible push. */ + yy_size_t grow_size = 8 /* arbitrary grow size */; + + num_to_alloc = yyg->yy_buffer_stack_max + grow_size; + yyg->yy_buffer_stack = (struct yy_buffer_state**)freesasa_yyrealloc + (yyg->yy_buffer_stack, + num_to_alloc * sizeof(struct yy_buffer_state*) + , yyscanner); + if ( ! yyg->yy_buffer_stack ) + YY_FATAL_ERROR( "out of dynamic memory in freesasa_yyensure_buffer_stack()" ); + + /* zero only the new slots.*/ + memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); + yyg->yy_buffer_stack_max = num_to_alloc; + } +} + +/** Setup the input buffer state to scan directly from a user-specified character buffer. + * @param base the character buffer + * @param size the size in bytes of the character buffer + * @param yyscanner The scanner object. + * @return the newly allocated buffer state object. + */ +YY_BUFFER_STATE freesasa_yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) +{ + YY_BUFFER_STATE b; + + if ( size < 2 || + base[size-2] != YY_END_OF_BUFFER_CHAR || + base[size-1] != YY_END_OF_BUFFER_CHAR ) + /* They forgot to leave room for the EOB's. */ + return NULL; + + b = (YY_BUFFER_STATE) freesasa_yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); + if ( ! b ) + YY_FATAL_ERROR( "out of dynamic memory in freesasa_yy_scan_buffer()" ); + + b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ + b->yy_buf_pos = b->yy_ch_buf = base; + b->yy_is_our_buffer = 0; + b->yy_input_file = NULL; + b->yy_n_chars = b->yy_buf_size; + b->yy_is_interactive = 0; + b->yy_at_bol = 1; + b->yy_fill_buffer = 0; + b->yy_buffer_status = YY_BUFFER_NEW; + + freesasa_yy_switch_to_buffer(b ,yyscanner ); + + return b; +} + +/** Setup the input buffer state to scan a string. The next call to freesasa_yylex() will + * scan from a @e copy of @a str. + * @param yystr a NUL-terminated string to scan + * @param yyscanner The scanner object. + * @return the newly allocated buffer state object. + * @note If you want to scan bytes that may contain NUL values, then use + * freesasa_yy_scan_bytes() instead. + */ +YY_BUFFER_STATE freesasa_yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) +{ + + return freesasa_yy_scan_bytes(yystr,(int) strlen(yystr) ,yyscanner); +} + +/** Setup the input buffer state to scan the given bytes. The next call to freesasa_yylex() will + * scan from a @e copy of @a bytes. + * @param yybytes the byte buffer to scan + * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. + * @param yyscanner The scanner object. + * @return the newly allocated buffer state object. + */ +YY_BUFFER_STATE freesasa_yy_scan_bytes (yyconst char * yybytes, int _yybytes_len , yyscan_t yyscanner) +{ + YY_BUFFER_STATE b; + char *buf; + yy_size_t n; + yy_size_t i; + + /* Get memory for full buffer, including space for trailing EOB's. */ + n = (yy_size_t) _yybytes_len + 2; + buf = (char *) freesasa_yyalloc(n ,yyscanner ); + if ( ! buf ) + YY_FATAL_ERROR( "out of dynamic memory in freesasa_yy_scan_bytes()" ); + + for ( i = 0; i < _yybytes_len; ++i ) + buf[i] = yybytes[i]; + + buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; + + b = freesasa_yy_scan_buffer(buf,n ,yyscanner); + if ( ! b ) + YY_FATAL_ERROR( "bad buffer in freesasa_yy_scan_bytes()" ); + + /* It's okay to grow etc. this buffer, and we should throw it + * away when we're done. + */ + b->yy_is_our_buffer = 1; + + return b; +} + +#ifndef YY_EXIT_FAILURE +#define YY_EXIT_FAILURE 2 +#endif + +static void yynoreturn yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + (void)yyg; + (void) fprintf( stderr, "%s\n", msg ); + exit( YY_EXIT_FAILURE ); +} + +/* Redefine yyless() so it works in section 3 code. */ + +#undef yyless +#define yyless(n) \ + do \ + { \ + /* Undo effects of setting up yytext. */ \ + int yyless_macro_arg = (n); \ + YY_LESS_LINENO(yyless_macro_arg);\ + yytext[yyleng] = yyg->yy_hold_char; \ + yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ + yyg->yy_hold_char = *yyg->yy_c_buf_p; \ + *yyg->yy_c_buf_p = '\0'; \ + yyleng = yyless_macro_arg; \ + } \ + while ( 0 ) + +/* Accessor methods (get/set functions) to struct members. */ + +/** Get the user-defined data for this scanner. + * @param yyscanner The scanner object. + */ +YY_EXTRA_TYPE freesasa_yyget_extra (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + return yyextra; +} + +/** Get the current line number. + * @param yyscanner The scanner object. + */ +int freesasa_yyget_lineno (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + if (! YY_CURRENT_BUFFER) + return 0; + + return yylineno; +} + +/** Get the current column number. + * @param yyscanner The scanner object. + */ +int freesasa_yyget_column (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + if (! YY_CURRENT_BUFFER) + return 0; + + return yycolumn; +} + +/** Get the input stream. + * @param yyscanner The scanner object. + */ +FILE *freesasa_yyget_in (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + return yyin; +} + +/** Get the output stream. + * @param yyscanner The scanner object. + */ +FILE *freesasa_yyget_out (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + return yyout; +} + +/** Get the length of the current token. + * @param yyscanner The scanner object. + */ +int freesasa_yyget_leng (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + return yyleng; +} + +/** Get the current token. + * @param yyscanner The scanner object. + */ + +char *freesasa_yyget_text (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + return yytext; +} + +/** Set the user-defined data. This data is never touched by the scanner. + * @param user_defined The data to be associated with this scanner. + * @param yyscanner The scanner object. + */ +void freesasa_yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + yyextra = user_defined ; +} + +/** Set the current line number. + * @param _line_number line number + * @param yyscanner The scanner object. + */ +void freesasa_yyset_lineno (int _line_number , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + /* lineno is only valid if an input buffer exists. */ + if (! YY_CURRENT_BUFFER ) + YY_FATAL_ERROR( "freesasa_yyset_lineno called with no buffer" ); + + yylineno = _line_number; +} + +/** Set the current column. + * @param _column_no column number + * @param yyscanner The scanner object. + */ +void freesasa_yyset_column (int _column_no , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + /* column is only valid if an input buffer exists. */ + if (! YY_CURRENT_BUFFER ) + YY_FATAL_ERROR( "freesasa_yyset_column called with no buffer" ); + + yycolumn = _column_no; +} + +/** Set the input stream. This does not discard the current + * input buffer. + * @param _in_str A readable stream. + * @param yyscanner The scanner object. + * @see freesasa_yy_switch_to_buffer + */ +void freesasa_yyset_in (FILE * _in_str , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + yyin = _in_str ; +} + +void freesasa_yyset_out (FILE * _out_str , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + yyout = _out_str ; +} + +int freesasa_yyget_debug (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + return yy_flex_debug; +} + +void freesasa_yyset_debug (int _bdebug , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + yy_flex_debug = _bdebug ; +} + +/* Accessor methods for yylval and yylloc */ + +YYSTYPE * freesasa_yyget_lval (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + return yylval; +} + +void freesasa_yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + yylval = yylval_param; +} + +/* User-visible API */ + +/* freesasa_yylex_init is special because it creates the scanner itself, so it is + * the ONLY reentrant function that doesn't take the scanner as the last argument. + * That's why we explicitly handle the declaration, instead of using our macros. + */ + +int freesasa_yylex_init(yyscan_t* ptr_yy_globals) + +{ + if (ptr_yy_globals == NULL){ + errno = EINVAL; + return 1; + } + + *ptr_yy_globals = (yyscan_t) freesasa_yyalloc ( sizeof( struct yyguts_t ), NULL ); + + if (*ptr_yy_globals == NULL){ + errno = ENOMEM; + return 1; + } + + /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ + memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); + + return yy_init_globals ( *ptr_yy_globals ); +} + +/* freesasa_yylex_init_extra has the same functionality as freesasa_yylex_init, but follows the + * convention of taking the scanner as the last argument. Note however, that + * this is a *pointer* to a scanner, as it will be allocated by this call (and + * is the reason, too, why this function also must handle its own declaration). + * The user defined value in the first argument will be available to freesasa_yyalloc in + * the yyextra field. + */ + +int freesasa_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) + +{ + struct yyguts_t dummy_yyguts; + + freesasa_yyset_extra (yy_user_defined, &dummy_yyguts); + + if (ptr_yy_globals == NULL){ + errno = EINVAL; + return 1; + } + + *ptr_yy_globals = (yyscan_t) freesasa_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); + + if (*ptr_yy_globals == NULL){ + errno = ENOMEM; + return 1; + } + + /* By setting to 0xAA, we expose bugs in + yy_init_globals. Leave at 0x00 for releases. */ + memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); + + freesasa_yyset_extra (yy_user_defined, *ptr_yy_globals); + + return yy_init_globals ( *ptr_yy_globals ); +} + +static int yy_init_globals (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + /* Initialization is the same as for the non-reentrant scanner. + * This function is called from freesasa_yylex_destroy(), so don't allocate here. + */ + + yyg->yy_buffer_stack = NULL; + yyg->yy_buffer_stack_top = 0; + yyg->yy_buffer_stack_max = 0; + yyg->yy_c_buf_p = NULL; + yyg->yy_init = 0; + yyg->yy_start = 0; + + yyg->yy_start_stack_ptr = 0; + yyg->yy_start_stack_depth = 0; + yyg->yy_start_stack = NULL; + +/* Defined in main.c */ +#ifdef YY_STDINIT + yyin = stdin; + yyout = stdout; +#else + yyin = NULL; + yyout = NULL; +#endif + + /* For future reference: Set errno on error, since we are called by + * freesasa_yylex_init() + */ + return 0; +} + +/* freesasa_yylex_destroy is for both reentrant and non-reentrant scanners. */ +int freesasa_yylex_destroy (yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + + /* Pop the buffer stack, destroying each element. */ + while(YY_CURRENT_BUFFER){ + freesasa_yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); + YY_CURRENT_BUFFER_LVALUE = NULL; + freesasa_yypop_buffer_state(yyscanner); + } + + /* Destroy the stack itself. */ + freesasa_yyfree(yyg->yy_buffer_stack ,yyscanner); + yyg->yy_buffer_stack = NULL; + + /* Destroy the start condition stack. */ + freesasa_yyfree(yyg->yy_start_stack ,yyscanner ); + yyg->yy_start_stack = NULL; + + /* Reset the globals. This is important in a non-reentrant scanner so the next time + * freesasa_yylex() is called, initialization will occur. */ + yy_init_globals( yyscanner); + + /* Destroy the main struct (reentrant only). */ + freesasa_yyfree ( yyscanner , yyscanner ); + yyscanner = NULL; + return 0; +} + +/* + * Internal utility routines. + */ + +#ifndef yytext_ptr +static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + (void)yyg; + + int i; + for ( i = 0; i < n; ++i ) + s1[i] = s2[i]; +} +#endif + +#ifdef YY_NEED_STRLEN +static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) +{ + int n; + for ( n = 0; s[n]; ++n ) + ; + + return n; +} +#endif + +void *freesasa_yyalloc (yy_size_t size , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + (void)yyg; + return malloc(size); +} + +void *freesasa_yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + (void)yyg; + + /* The cast to (char *) in the following accommodates both + * implementations that use char* generic pointers, and those + * that use void* generic pointers. It works with the latter + * because both ANSI C and C++ allow castless assignment from + * any pointer type to void*, and deal with argument conversions + * as though doing an assignment. + */ + return realloc(ptr, size); +} + +void freesasa_yyfree (void * ptr , yyscan_t yyscanner) +{ + struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; + (void)yyg; + free( (char *) ptr ); /* see freesasa_yyrealloc() for (char *) cast */ +} + +#define YYTABLES_NAME "yytables" + +#line 55 "lexer.l" diff --git a/.venv_haddock/include/site/python3.12/freesasa/lexer.h b/.venv_haddock/include/site/python3.12/freesasa/lexer.h new file mode 100644 index 0000000000000000000000000000000000000000..f7df657d645eecc56fb671373e622eb90f2c8844 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/lexer.h @@ -0,0 +1,336 @@ +#ifndef freesasa_yyHEADER_H +#define freesasa_yyHEADER_H 1 +#define freesasa_yyIN_HEADER 1 + +#line 6 "lexer.h" + +#line 8 "lexer.h" + +#define YY_INT_ALIGNED short int + +/* A lexical scanner generated by flex */ + +#define FLEX_SCANNER +#define YY_FLEX_MAJOR_VERSION 2 +#define YY_FLEX_MINOR_VERSION 6 +#define YY_FLEX_SUBMINOR_VERSION 1 +#if YY_FLEX_SUBMINOR_VERSION > 0 +#define FLEX_BETA +#endif + +/* First, we deal with platform-specific or compiler-specific issues. */ + +/* begin standard C headers. */ +#include +#include +#include +#include + +/* end standard C headers. */ + +/* flex integer type definitions */ + +#ifndef FLEXINT_H +#define FLEXINT_H + +/* C99 systems have . Non-C99 systems may or may not. */ + +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + +/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, + * if you want the limit (max/min) macros for int types. + */ +#ifndef __STDC_LIMIT_MACROS +#define __STDC_LIMIT_MACROS 1 +#endif + +#include +typedef int8_t flex_int8_t; +typedef uint8_t flex_uint8_t; +typedef int16_t flex_int16_t; +typedef uint16_t flex_uint16_t; +typedef int32_t flex_int32_t; +typedef uint32_t flex_uint32_t; +#else +typedef signed char flex_int8_t; +typedef short int flex_int16_t; +typedef int flex_int32_t; +typedef unsigned char flex_uint8_t; +typedef unsigned short int flex_uint16_t; +typedef unsigned int flex_uint32_t; + +/* Limits of integral types. */ +#ifndef INT8_MIN +#define INT8_MIN (-128) +#endif +#ifndef INT16_MIN +#define INT16_MIN (-32767-1) +#endif +#ifndef INT32_MIN +#define INT32_MIN (-2147483647-1) +#endif +#ifndef INT8_MAX +#define INT8_MAX (127) +#endif +#ifndef INT16_MAX +#define INT16_MAX (32767) +#endif +#ifndef INT32_MAX +#define INT32_MAX (2147483647) +#endif +#ifndef UINT8_MAX +#define UINT8_MAX (255U) +#endif +#ifndef UINT16_MAX +#define UINT16_MAX (65535U) +#endif +#ifndef UINT32_MAX +#define UINT32_MAX (4294967295U) +#endif + +#endif /* ! C99 */ + +#endif /* ! FLEXINT_H */ + +/* TODO: this is always defined, so inline it */ +#define yyconst const + +#if defined(__GNUC__) && __GNUC__ >= 3 +#define yynoreturn __attribute__((__noreturn__)) +#else +#define yynoreturn +#endif + +/* An opaque pointer. */ +#ifndef YY_TYPEDEF_YY_SCANNER_T +#define YY_TYPEDEF_YY_SCANNER_T +typedef void* yyscan_t; +#endif + +/* For convenience, these vars (plus the bison vars far below) + are macros in the reentrant scanner. */ +#define yyin yyg->yyin_r +#define yyout yyg->yyout_r +#define yyextra yyg->yyextra_r +#define yyleng yyg->yyleng_r +#define yytext yyg->yytext_r +#define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) +#define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) +#define yy_flex_debug yyg->yy_flex_debug_r + +/* Size of default input buffer. */ +#ifndef YY_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k. + * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. + * Ditto for the __ia64__ case accordingly. + */ +#define YY_BUF_SIZE 32768 +#else +#define YY_BUF_SIZE 16384 +#endif /* __ia64__ */ +#endif + +#ifndef YY_TYPEDEF_YY_BUFFER_STATE +#define YY_TYPEDEF_YY_BUFFER_STATE +typedef struct yy_buffer_state *YY_BUFFER_STATE; +#endif + +#ifndef YY_TYPEDEF_YY_SIZE_T +#define YY_TYPEDEF_YY_SIZE_T +typedef size_t yy_size_t; +#endif + +#ifndef YY_STRUCT_YY_BUFFER_STATE +#define YY_STRUCT_YY_BUFFER_STATE +struct yy_buffer_state + { + FILE *yy_input_file; + + char *yy_ch_buf; /* input buffer */ + char *yy_buf_pos; /* current position in input buffer */ + + /* Size of input buffer in bytes, not including room for EOB + * characters. + */ + int yy_buf_size; + + /* Number of characters read into yy_ch_buf, not including EOB + * characters. + */ + int yy_n_chars; + + /* Whether we "own" the buffer - i.e., we know we created it, + * and can realloc() it to grow it, and should free() it to + * delete it. + */ + int yy_is_our_buffer; + + /* Whether this is an "interactive" input source; if so, and + * if we're using stdio for input, then we want to use getc() + * instead of fread(), to make sure we stop fetching input after + * each newline. + */ + int yy_is_interactive; + + /* Whether we're considered to be at the beginning of a line. + * If so, '^' rules will be active on the next match, otherwise + * not. + */ + int yy_at_bol; + + int yy_bs_lineno; /**< The line count. */ + int yy_bs_column; /**< The column count. */ + + /* Whether to try to fill the input buffer when we reach the + * end of it. + */ + int yy_fill_buffer; + + int yy_buffer_status; + + }; +#endif /* !YY_STRUCT_YY_BUFFER_STATE */ + +void freesasa_yyrestart (FILE *input_file ,yyscan_t yyscanner ); +void freesasa_yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); +YY_BUFFER_STATE freesasa_yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); +void freesasa_yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); +void freesasa_yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); +void freesasa_yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); +void freesasa_yypop_buffer_state (yyscan_t yyscanner ); + +YY_BUFFER_STATE freesasa_yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); +YY_BUFFER_STATE freesasa_yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); +YY_BUFFER_STATE freesasa_yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner ); + +void *freesasa_yyalloc (yy_size_t ,yyscan_t yyscanner ); +void *freesasa_yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); +void freesasa_yyfree (void * ,yyscan_t yyscanner ); + +#define freesasa_yywrap(yyscanner) (/*CONSTCOND*/1) +#define YY_SKIP_YYWRAP + +#define yytext_ptr yytext_r + +#ifdef YY_HEADER_EXPORT_START_CONDITIONS +#define INITIAL 0 + +#endif + +#ifndef YY_EXTRA_TYPE +#define YY_EXTRA_TYPE void * +#endif + +int freesasa_yylex_init (yyscan_t* scanner); + +int freesasa_yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); + +/* Accessor methods to globals. + These are made visible to non-reentrant scanners for convenience. */ + +int freesasa_yylex_destroy (yyscan_t yyscanner ); + +int freesasa_yyget_debug (yyscan_t yyscanner ); + +void freesasa_yyset_debug (int debug_flag ,yyscan_t yyscanner ); + +YY_EXTRA_TYPE freesasa_yyget_extra (yyscan_t yyscanner ); + +void freesasa_yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); + +FILE *freesasa_yyget_in (yyscan_t yyscanner ); + +void freesasa_yyset_in (FILE * _in_str ,yyscan_t yyscanner ); + +FILE *freesasa_yyget_out (yyscan_t yyscanner ); + +void freesasa_yyset_out (FILE * _out_str ,yyscan_t yyscanner ); + + int freesasa_yyget_leng (yyscan_t yyscanner ); + +char *freesasa_yyget_text (yyscan_t yyscanner ); + +int freesasa_yyget_lineno (yyscan_t yyscanner ); + +void freesasa_yyset_lineno (int _line_number ,yyscan_t yyscanner ); + +int freesasa_yyget_column (yyscan_t yyscanner ); + +void freesasa_yyset_column (int _column_no ,yyscan_t yyscanner ); + +YYSTYPE * freesasa_yyget_lval (yyscan_t yyscanner ); + +void freesasa_yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); + +/* Macros after this point can all be overridden by user definitions in + * section 1. + */ + +#ifndef YY_SKIP_YYWRAP +#ifdef __cplusplus +extern "C" int freesasa_yywrap (yyscan_t yyscanner ); +#else +extern int freesasa_yywrap (yyscan_t yyscanner ); +#endif +#endif + +#ifndef yytext_ptr +static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); +#endif + +#ifdef YY_NEED_STRLEN +static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); +#endif + +#ifndef YY_NO_INPUT + +#endif + +/* Amount of stuff to slurp up with each read. */ +#ifndef YY_READ_BUF_SIZE +#ifdef __ia64__ +/* On IA-64, the buffer size is 16k, not 8k */ +#define YY_READ_BUF_SIZE 16384 +#else +#define YY_READ_BUF_SIZE 8192 +#endif /* __ia64__ */ +#endif + +/* Number of entries by which start-condition stack grows. */ +#ifndef YY_START_STACK_INCR +#define YY_START_STACK_INCR 25 +#endif + +/* Default declaration of generated scanner - a define so the user can + * easily add parameters. + */ +#ifndef YY_DECL +#define YY_DECL_IS_OURS 1 + +extern int freesasa_yylex \ + (YYSTYPE * yylval_param ,yyscan_t yyscanner); + +#define YY_DECL int freesasa_yylex \ + (YYSTYPE * yylval_param , yyscan_t yyscanner) +#endif /* !YY_DECL */ + +/* yy_get_previous_state - get the state just before the EOB char was reached */ + +#undef YY_NEW_FILE +#undef YY_FLUSH_BUFFER +#undef yy_set_bol +#undef yy_new_buffer +#undef yy_set_interactive +#undef YY_DO_BEFORE_ACTION + +#ifdef YY_DECL_IS_OURS +#undef YY_DECL_IS_OURS +#undef YY_DECL +#endif + +#line 55 "lexer.l" + +#line 335 "lexer.h" +#undef freesasa_yyIN_HEADER +#endif /* freesasa_yyHEADER_H */ diff --git a/.venv_haddock/include/site/python3.12/freesasa/log.c b/.venv_haddock/include/site/python3.12/freesasa/log.c new file mode 100644 index 0000000000000000000000000000000000000000..6382d236618abda07996f3a0f0cb3509e7548239 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/log.c @@ -0,0 +1,270 @@ +#if HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +#include "classifier.h" +#include "freesasa_internal.h" + +/** to control error messages (used for debugging and testing) */ +static freesasa_verbosity verbosity; + +int freesasa_set_verbosity(freesasa_verbosity s) +{ + if (s == FREESASA_V_NORMAL || + s == FREESASA_V_NOWARNINGS || + s == FREESASA_V_SILENT || + s == FREESASA_V_DEBUG) { + verbosity = s; + return FREESASA_SUCCESS; + } + return FREESASA_WARN; +} + +freesasa_verbosity +freesasa_get_verbosity(void) +{ + return verbosity; +} + +static int +write_result(FILE *log, + freesasa_node *result) +{ + const char *name = NULL; + freesasa_node *structure = NULL, *chain = NULL; + const freesasa_nodearea *area = NULL; + + assert(log); + assert(freesasa_node_type(result) == FREESASA_NODE_RESULT); + + name = freesasa_node_name(result); + structure = freesasa_node_children(result); + assert(structure); + area = freesasa_node_area(structure); + assert(area); + + fprintf(log, "\nINPUT\n"); + if (name == NULL) + fprintf(log, "source : unknown\n"); + else + fprintf(log, "source : %s\n", name); + fprintf(log, "chains : %s\n", freesasa_node_structure_chain_labels(structure)); + fprintf(log, "model : %d\n", freesasa_node_structure_model(structure)); + fprintf(log, "atoms : %d\n", freesasa_node_structure_n_atoms(structure)); + + fprintf(log, "\nRESULTS (A^2)\n"); + fprintf(log, "Total : %10.2f\n", area->total); + fprintf(log, "Apolar : %10.2f\n", area->apolar); + fprintf(log, "Polar : %10.2f\n", area->polar); + if (area->unknown > 0) { + fprintf(log, "Unknown : %10.2f\n", area->unknown); + } + + chain = freesasa_node_children(structure); + while (chain) { + area = freesasa_node_area(chain); + assert(area); + fprintf(log, "CHAIN %s : %10.2f\n", freesasa_node_name(chain), area->total); + chain = freesasa_node_next(chain); + } + + fflush(log); + if (ferror(log)) { + return fail_msg(strerror(errno)); + } + + return FREESASA_SUCCESS; +} + +static int +write_selections(FILE *log, + freesasa_node *result) +{ + freesasa_node *structure = freesasa_node_children(result); + const freesasa_selection **selection; + + while (structure) { + selection = freesasa_node_structure_selections(structure); + if (selection && *selection) { + fprintf(log, "\nSELECTIONS\n"); + while (*selection) { + fprintf(log, "%s : %10.2f\n", + freesasa_selection_name(*selection), + freesasa_selection_area(*selection)); + ++selection; + } + } + structure = freesasa_node_next(structure); + } + + fflush(log); + if (ferror(log)) { + return fail_msg(strerror(errno)); + } + + return FREESASA_SUCCESS; +} + +static int +write_parameters(FILE *log, + const freesasa_parameters *parameters) +{ + const freesasa_parameters *p = parameters; + + assert(log); + + if (p == NULL) p = &freesasa_default_parameters; + + fprintf(log, "\nPARAMETERS\n"); + + fprintf(log, "algorithm : %s\n", freesasa_alg_name(p->alg)); + fprintf(log, "probe-radius : %.3f\n", p->probe_radius); +#if USE_THREADS + fprintf(log, "threads : %d\n", p->n_threads); +#endif + + switch (p->alg) { + case FREESASA_SHRAKE_RUPLEY: + fprintf(log, "testpoints : %d\n", p->shrake_rupley_n_points); + break; + case FREESASA_LEE_RICHARDS: + fprintf(log, "slices : %d\n", p->lee_richards_n_slices); + break; + default: + assert(0); + break; + } + + fflush(log); + if (ferror(log)) { + return fail_msg(strerror(errno)); + } + + return FREESASA_SUCCESS; +} + +int freesasa_write_res(FILE *log, + freesasa_node *root) +{ + freesasa_node *result, *structure, *chain, *residue; + int n_res = freesasa_classify_n_residue_types() + 1, i_res, i; + double *residue_area = malloc(sizeof(double) * n_res); + + assert(log); + assert(root); + assert(freesasa_node_type(root) == FREESASA_NODE_ROOT); + + if (residue_area == NULL) return mem_fail(); + + result = freesasa_node_children(root); + while (result) { + for (i = 0; i < n_res; ++i) + residue_area[i] = 0; + structure = freesasa_node_children(result); + while (structure) { + chain = freesasa_node_children(structure); + while (chain) { + residue = freesasa_node_children(chain); + while (residue) { + assert(freesasa_node_type(residue) == FREESASA_NODE_RESIDUE); + i_res = freesasa_classify_residue(freesasa_node_name(residue)); + residue_area[i_res] += freesasa_node_area(residue)->total; + residue = freesasa_node_next(residue); + } + chain = freesasa_node_next(chain); + } + structure = freesasa_node_next(structure); + } + + fprintf(log, "# Residue types in %s\n", freesasa_node_name(result)); + for (i_res = 0; i_res < n_res; ++i_res) { + double sasa = residue_area[i_res]; + if (i_res < 20 || sasa > 0) { + fprintf(log, "RES %s : %10.2f\n", + freesasa_classify_residue_name(i_res), + sasa); + } + } + fprintf(log, "\n"); + + result = freesasa_node_next(result); + } + + fflush(log); + if (ferror(log)) { + return fail_msg(strerror(errno)); + } + + return FREESASA_SUCCESS; +} + +int freesasa_write_seq(FILE *log, + freesasa_node *root) +{ + freesasa_node *result, *structure, *chain, *residue; + + assert(log); + assert(root); + assert(freesasa_node_type(root) == FREESASA_NODE_ROOT); + + result = freesasa_node_children(root); + + while (result) { + structure = freesasa_node_children(result); + fprintf(log, "# Residues in %s\n", freesasa_node_name(result)); + while (structure) { + chain = freesasa_node_children(structure); + while (chain) { + residue = freesasa_node_children(chain); + while (residue) { + assert(freesasa_node_type(residue) == FREESASA_NODE_RESIDUE); + fprintf(log, "SEQ %s %s %s : %7.2f\n", + freesasa_node_name(chain), + freesasa_node_residue_number(residue), + freesasa_node_name(residue), + freesasa_node_area(residue)->total); + residue = freesasa_node_next(residue); + } + chain = freesasa_node_next(chain); + } + structure = freesasa_node_next(structure); + } + fprintf(log, "\n"); + result = freesasa_node_next(result); + } + + fflush(log); + if (ferror(log)) { + return fail_msg(strerror(errno)); + } + + return FREESASA_SUCCESS; +} + +int freesasa_write_log(FILE *log, + freesasa_node *root) +{ + freesasa_node *result = freesasa_node_children(root); + int several = (freesasa_node_next(result) != NULL); /* are there more than one result */ + int err = 0; + + assert(log); + assert(freesasa_node_type(root) == FREESASA_NODE_ROOT); + + if (write_parameters(log, freesasa_node_result_parameters(result)) == FREESASA_FAIL) + ++err; + + while (result) { + if (several) fprintf(log, "\n\n####################\n"); + if (write_result(log, result) == FREESASA_FAIL) ++err; + if (write_selections(log, result) == FREESASA_FAIL) ++err; + result = freesasa_node_next(result); + } + if (err) return FREESASA_FAIL; + + return FREESASA_SUCCESS; +} diff --git a/.venv_haddock/include/site/python3.12/freesasa/nb.c b/.venv_haddock/include/site/python3.12/freesasa/nb.c new file mode 100644 index 0000000000000000000000000000000000000000..70145926fdcbc27a20f3e6fd30c203f60005325a --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/nb.c @@ -0,0 +1,642 @@ +#if HAVE_CONFIG_H +#include +#endif +#include +#include +#include + +#include "freesasa_internal.h" +#include "nb.h" + +#ifndef FREESASA_NB_CHUNK +#define FREESASA_NB_CHUNK 128 +#endif + +typedef struct cell cell; +struct cell { + cell *nb[17]; /** includes self, only forward neighbors */ + int *atom; /** indices of the atoms/coordinates in a cell */ + int n_nb; /** number of neighbors to cell */ + int n_atoms; /** number of atoms in cell */ +}; + +static cell empty_cell = {{NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}, + NULL, + 0, + 0}; + +/** cell lists, divide space into boxes */ +typedef struct cell_list { + cell *cell; /** the cells */ + int n; /** number of cells */ + int nx, ny, nz; /** number of cells along each axis */ + double d; /** cell size */ + double x_max, x_min; + double y_max, y_min; + double z_max, z_min; +} cell_list; + +static struct cell_list empty_cell_list = {NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + +/** Finds the bounds of the cell list and writes them to the provided cell list */ +static void +cell_list_bounds(cell_list *c, + const coord_t *coord) +{ + const int n = freesasa_coord_n(coord); + int i; + double d = c->d; + const double *restrict v = freesasa_coord_i(coord, 0); + double x = v[0], X = v[0], y = v[1], Y = v[1], z = v[2], Z = v[2]; + + for (i = 1; i < n; ++i) { + v = freesasa_coord_i(coord, i); + x = fmin(v[0], x); + X = fmax(v[0], X); + y = fmin(v[1], y); + Y = fmax(v[1], Y); + z = fmin(v[2], z); + Z = fmax(v[2], Z); + } + c->x_min = x - d / 2.; + c->x_max = X + d / 2.; + c->y_min = y - d / 2.; + c->y_max = Y + d / 2.; + c->z_min = z - d / 2.; + c->z_max = Z + d / 2.; + c->nx = (int)ceil((c->x_max - c->x_min) / d); + c->ny = (int)ceil((c->y_max - c->y_min) / d); + c->nz = (int)ceil((c->z_max - c->z_min) / d); + c->n = c->nx * c->ny * c->nz; +} + +static inline int +cell_index(const cell_list *c, + int ix, + int iy, + int iz) +{ + assert(ix >= 0 && ix < c->nx); + assert(iy >= 0 && iy < c->ny); + return ix + c->nx * (iy + c->ny * iz); +} + +/** Fill the neighbor list for a given cell, only "forward" neighbors considered */ +static void +fill_nb(cell_list *c, + int ix, + int iy, + int iz) +{ + cell *cell = &c->cell[cell_index(c, ix, iy, iz)]; + int n = 0, i, j, k; + int xmin = ix > 0 ? ix - 1 : 0; + int xmax = ix < c->nx - 1 ? ix + 1 : ix; + int ymin = iy > 0 ? iy - 1 : 0; + int ymax = iy < c->ny - 1 ? iy + 1 : iy; + int zmin = iz > 0 ? iz - 1 : 0; + int zmax = iz < c->nz - 1 ? iz + 1 : iz; + for (i = xmin; i <= xmax; ++i) { + for (j = ymin; j <= ymax; ++j) { + for (k = zmin; k <= zmax; ++k) { + /* Scalar product between (i-ix,j-iy,k-iz) and (1,1,1) should + be non-negative. Using only forward neighbors means + there's no double counting when comparing cells */ + if (i - ix + j - iy + k - iz >= 0) { + cell->nb[n] = &c->cell[cell_index(c, i, j, k)]; + ++n; + } + } + } + } + cell->n_nb = n; + assert(n > 0); +} + +/** find neighbors to all cells */ +static void +get_nb(cell_list *c) +{ + int ix, iy, iz; + + for (ix = 0; ix < c->nx; ++ix) { + for (iy = 0; iy < c->ny; ++iy) { + for (iz = 0; iz < c->nz; ++iz) { + fill_nb(c, ix, iy, iz); + } + } + } +} + +/** Get the cell index of a given atom */ +static int +coord2cell_index(const cell_list *c, + const double *restrict xyz) +{ + double d = c->d; + int ix = (int)((xyz[0] - c->x_min) / d); + int iy = (int)((xyz[1] - c->y_min) / d); + int iz = (int)((xyz[2] - c->z_min) / d); + + return cell_index(c, ix, iy, iz); +} + +/** + Assigns cells to each coordinate. Returns FREESASA_FAIL if realloc + fails, FREESASA_SUCCESS else. + */ +static int +fill_cells(cell_list *c, + const coord_t *coord) +{ + int i; + cell *cell; + int *a; + const double *restrict v; + + for (i = 0; i < c->n; ++i) { + c->cell[i].n_atoms = 0; + } + + for (i = 0; i < freesasa_coord_n(coord); ++i) { + v = freesasa_coord_i(coord, i); + cell = &c->cell[coord2cell_index(c, v)]; + ++cell->n_atoms; + a = cell->atom; + cell->atom = realloc(cell->atom, sizeof(int) * cell->n_atoms); + if (!cell->atom) { + cell->atom = a; + return mem_fail(); + } + cell->atom[cell->n_atoms - 1] = i; + } + return FREESASA_SUCCESS; +} + +/** Frees an object created by cell_list_new(). */ +static void +cell_list_free(cell_list *c) +{ + int i; + + if (c) { + if (c->cell) { + for (i = 0; i < c->n; ++i) + free(c->cell[i].atom); + } + free(c->cell); + free(c); + } +} + +/** + Creates a cell list with provided cell-size assigning cells to + each of the provided coordinates. The created cell list should be + freed using cell_list_free(). + + Returns NULL if there are malloc fails. + */ +static cell_list * +cell_list_new(double cell_size, + const coord_t *coord) +{ + int i; + cell_list *c; + + assert(cell_size > 0); + assert(coord); + + c = malloc(sizeof(cell_list)); + if (!c) { + mem_fail(); + return NULL; + } + + *c = empty_cell_list; + + c->d = cell_size; + cell_list_bounds(c, coord); + + c->cell = malloc(sizeof(cell) * c->n); + if (!c->cell) { + cell_list_free(c); + mem_fail(); + return NULL; + } + + for (i = 0; i < c->n; ++i) + c->cell[i] = empty_cell; + + if (fill_cells(c, coord)) { + cell_list_free(c); + mem_fail(); + return NULL; + } + + get_nb(c); + return c; +} + +/** assumes max value in a is positive */ +static double +max_array(const double *a, + int n) +{ + int i; + double max = 0; + + for (i = 0; i < n; ++i) { + max = fmax(a[i], max); + } + + return max; +} + +/** + Allocate memory for ::nb_list object. Tries to free everything + and returns NULL if malloc somewhere along the way. + */ +static nb_list * +freesasa_nb_alloc(int n) +{ + int i; + nb_list *nb; + + assert(n > 0); + + nb = malloc(sizeof(nb_list)); + if (!nb) { + mem_fail(); + return NULL; + } + + nb->n = n; + + /* in case the mallocs break, we can clean up in a safer way */ + nb->nn = NULL; + nb->nb = NULL; + nb->capacity = NULL; + nb->xyd = nb->xd = nb->yd = NULL; + + nb->nn = malloc(sizeof(int) * n); + nb->nb = malloc(sizeof(int *) * n); + nb->xyd = malloc(sizeof(double *) * n); + nb->xd = malloc(sizeof(double *) * n); + nb->yd = malloc(sizeof(double *) * n); + nb->capacity = malloc(sizeof(int) * n); + + if (!nb->nn || !nb->nb || !nb->xyd || + !nb->xd || !nb->yd || !nb->capacity) { + free(nb->nn); + free(nb->nb); + free(nb->xyd); + free(nb->xd); + free(nb->yd); + free(nb->capacity); + free(nb); + mem_fail(); + return NULL; + } + + for (i = 0; i < n; ++i) { + nb->nn[i] = 0; + nb->capacity[i] = FREESASA_NB_CHUNK; + /* again prepare for a potential cleanup */ + nb->nb[i] = NULL; + nb->xyd[i] = nb->xd[i] = nb->yd[i] = NULL; + } + for (i = 0; i < n; ++i) { + nb->nb[i] = malloc(sizeof(int) * FREESASA_NB_CHUNK); + nb->xyd[i] = malloc(sizeof(double) * FREESASA_NB_CHUNK); + nb->xd[i] = malloc(sizeof(double) * FREESASA_NB_CHUNK); + nb->yd[i] = malloc(sizeof(double) * FREESASA_NB_CHUNK); + if (!nb->nb[i] || !nb->xyd[i] || !nb->xd[i] || !nb->yd[i]) { + freesasa_nb_free(nb); + mem_fail(); + return NULL; + } + } + return nb; +} + +void freesasa_nb_free(nb_list *nb) +{ + int n, i; + + if (nb != NULL) { + n = nb->n; + if (nb->nb) + for (i = 0; i < n; ++i) + free(nb->nb[i]); + if (nb->xyd) + for (i = 0; i < n; ++i) + free(nb->xyd[i]); + if (nb->xd) + for (i = 0; i < n; ++i) + free(nb->xd[i]); + if (nb->yd) + for (i = 0; i < n; ++i) + free(nb->yd[i]); + free(nb->nb); + free(nb->nn); + free(nb->capacity); + free(nb->xyd); + free(nb->xd); + free(nb->yd); + free(nb); + } +} + +/** + Increases sizes of arrays when they cross a threshold. Returns + FREESASA_FAIL if realloc fails, FREESASA_SUCCESS else + */ +static int +chunk_up(nb_list *nb_list, + int i) +{ + int nni = nb_list->nn[i]; + int **nbi, *nbi_b, new_cap; + double **xydi, **xdi, **ydi, *xydi_b, *xdi_b, *ydi_b; + + if (nni > nb_list->capacity[i]) { + nbi = &nb_list->nb[i]; + nbi_b = *nbi; + xydi = &nb_list->xyd[i]; + xdi = &nb_list->xd[i]; + ydi = &nb_list->yd[i]; + xydi_b = *xydi; + xdi_b = *xdi; + ydi_b = *ydi; + new_cap = (nb_list->capacity[i] += FREESASA_NB_CHUNK); + + *nbi = realloc(*nbi, sizeof(int) * new_cap); + if (*nbi == NULL) { + nb_list->nb[i] = nbi_b; + return mem_fail(); + } + + *xydi = realloc(*xydi, sizeof(double) * new_cap); + if (*xydi == NULL) { + nb_list->xyd[i] = xydi_b; + return mem_fail(); + } + + *xdi = realloc(*xdi, sizeof(double) * new_cap); + if (*xdi == NULL) { + nb_list->xd[i] = xdi_b; + return mem_fail(); + } + + *ydi = realloc(*ydi, sizeof(double) * new_cap); + if (*ydi == NULL) { + nb_list->yd[i] = ydi_b; + return mem_fail(); + } + } + return FREESASA_SUCCESS; +} + +/** + Assumes the coordinates i and j have been determined to be + neighbors and adds them both to the provided nb lists, + symmetrically. + + Returns FREESASA_FAIL if can't allocate memory. FREESASA_SUCCESS + else. +*/ +static int +nb_add_pair(nb_list *nb_list, + int i, + int j, + double dx, + double dy) +{ + int **nb; + int *nn = nb_list->nn; + int nni, nnj; + double **xyd; + double **xd; + double **yd; + double d; + + assert(i != j); + + nni = nn[i]++; + nnj = nn[j]++; + + if (chunk_up(nb_list, i)) return mem_fail(); + if (chunk_up(nb_list, j)) return mem_fail(); + + nb = nb_list->nb; + xyd = nb_list->xyd; + xd = nb_list->xd; + yd = nb_list->yd; + + nb[i][nni] = j; + nb[j][nnj] = i; + + d = sqrt(dx * dx + dy * dy); + + xyd[i][nni] = d; + xyd[j][nnj] = d; + + xd[i][nni] = dx; + xd[j][nnj] = -dx; + yd[i][nni] = dy; + yd[j][nnj] = -dy; + + return FREESASA_SUCCESS; +} + +/** + Fills the nb list for all contacts between coordinates + belonging to the cells ci and cj. Handles the case ci == cj + correctly. +*/ +static int +nb_calc_cell_pair(nb_list *nb_list, + const coord_t *coord, + const double *radii, + const cell *ci, + const cell *cj) +{ + const double *restrict v = freesasa_coord_all(coord); + double ri, rj, xi, yi, zi, xj, yj, zj, + dx, dy, dz, cut2; + int i, j, ia, ja; + + for (i = 0; i < ci->n_atoms; ++i) { + ia = ci->atom[i]; + ri = radii[ia]; + xi = v[ia * 3]; + yi = v[ia * 3 + 1]; + zi = v[ia * 3 + 2]; + if (ci == cj) + j = i + 1; + else + j = 0; + /** the following loop is performance critical */ + for (; j < cj->n_atoms; ++j) { + ja = cj->atom[j]; + rj = radii[ja]; + xj = v[ja * 3]; + yj = v[ja * 3 + 1]; + zj = v[ja * 3 + 2]; + cut2 = (ri + rj) * (ri + rj); + dx = xj - xi; + dy = yj - yi; + dz = zj - zi; + if (dx * dx + dy * dy + dz * dz < cut2) { + if (nb_add_pair(nb_list, ia, ja, dx, dy)) + return mem_fail(); + } + } + } + return FREESASA_SUCCESS; +} + +/** + Iterates through the cells and records all contacts in the + provided nb list + */ +static int +nb_fill_list(nb_list *nb_list, + cell_list *c, + const coord_t *coord, + const double *radii) +{ + int nc = c->n, ic, jc; + cell *ci, *cj; + + for (ic = 0; ic < nc; ++ic) { + ci = &c->cell[ic]; + for (jc = 0; jc < ci->n_nb; ++jc) { + cj = ci->nb[jc]; + if (nb_calc_cell_pair(nb_list, coord, radii, ci, cj)) + return mem_fail(); + } + } + return FREESASA_SUCCESS; +} + +nb_list * +freesasa_nb_new(const coord_t *coord, + const double *radii) +{ + double cell_size; + cell_list *c; + int n; + nb_list *nb; + + if (coord == NULL || radii == NULL) return NULL; + + n = freesasa_coord_n(coord); + nb = freesasa_nb_alloc(n); + + if (!nb) { + mem_fail(); + return NULL; + } + + cell_size = 2 * max_array(radii, n); + assert(cell_size > 0); + c = cell_list_new(cell_size, coord); + if (c == NULL || + nb_fill_list(nb, c, coord, radii)) { + mem_fail(); + freesasa_nb_free(nb); + nb = NULL; + } + + /* the cell lists are only a tool to generate the neighbor lists */ + cell_list_free(c); + + return nb; +} + +int freesasa_nb_contact(const nb_list *nb, + int i, + int j) +{ + int k; + assert(nb != NULL); + assert(i < nb->n && i >= 0); + assert(j < nb->n && j >= 0); + + for (k = 0; k < nb->nn[i]; ++k) { + if (nb->nb[i][k] == j) return 1; + } + + return 0; +} + +#if USE_CHECK +#include +#include + +START_TEST(test_cell) +{ + int na, i; + const int n_atoms = 6; + static const double v[] = {0, 0, 0, 1, 1, 1, -1, 1, -1, 2, 0, -2, 2, 2, 0, -5, 5, 5}; + static const double r[] = {4, 2, 2, 2, 2, 2}; + double r_max; + cell_list *c; + coord_t *coord = freesasa_coord_new(); + cell ci; + + freesasa_coord_append(coord, v, n_atoms); + r_max = max_array(r, n_atoms); + ck_assert(fabs(r_max - 4) < 1e-10); + c = cell_list_new(r_max, coord); + ck_assert(c != NULL); + ck_assert(c->cell != NULL); + ck_assert(fabs(c->d - r_max) < 1e-10); + + /* check bounds */ + ck_assert(c->x_min < -5); + ck_assert(c->x_max > 2); + ck_assert(c->y_min < 0); + ck_assert(c->y_max > 5); + ck_assert(c->z_min < -2); + ck_assert(c->z_max > 5); + + /* check number of cells */ + ck_assert(c->nx * c->d >= 7); + ck_assert(c->nx <= ceil(7 / r_max) + 1); + ck_assert(c->ny * c->d >= 5); + ck_assert(c->ny <= ceil(5 / r_max) + 1); + ck_assert(c->nz * c->d >= 7); + ck_assert(c->nz <= ceil(7 / r_max) + 1); + ck_assert_int_eq(c->n, c->nx * c->ny * c->nz); + + /* check the individual cells */ + na = 0; + ck_assert_int_eq(c->cell[0].n_nb, 8); + ck_assert_int_eq(c->cell[c->n - 1].n_nb, 1); + for (i = 0; i < c->n; ++i) { + ci = c->cell[i]; + ck_assert(ci.n_atoms >= 0); + if (ci.n_atoms > 0) ck_assert(ci.atom != NULL); + ck_assert_int_ge(ci.n_nb, 1); + ck_assert_int_le(ci.n_nb, 17); + na += ci.n_atoms; + } + ck_assert_int_eq(na, n_atoms); + cell_list_free(c); + freesasa_coord_free(coord); +} +END_TEST + +TCase * +test_nb_static() +{ + TCase *tc = tcase_create("nb.c static"); + tcase_add_test(tc, test_cell); + + return tc; +} + +#endif /* USE_CHECK */ diff --git a/.venv_haddock/include/site/python3.12/freesasa/nb.h b/.venv_haddock/include/site/python3.12/freesasa/nb.h new file mode 100644 index 0000000000000000000000000000000000000000..b6d5c3e102f754d29bab19631c87d5ee8076a3c0 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/nb.h @@ -0,0 +1,67 @@ +#ifndef FREESASA_NB_H +#define FREESASA_NB_H + +#include + +#include "coord.h" + +/** + @file + @author Simon Mitternacht + + Functions to compute neighbor lists. The function + freesasa_nb_contact() is mainly intended for checking consistency, + in performance-critical code it is advisible to use the struct (as + demonstrated in sasa_lr.c and sasa_sr.c). + */ + +/** Neighbor list */ +typedef struct { + int n; /**< number of elements */ + int **nb; /**< neighbors to each element */ + int *nn; /**< number of neighbors to each element */ + double **xyd; /**< distance between neighbors in xy-plane */ + double **xd; /**< signed distance between neighbors along x-axis */ + double **yd; /**< signed distance between neighbors along y-axis */ + int *capacity; /**< keeps track of memory chunks (don't change this) */ +} nb_list; + +/** + Creates a neigbor list based on a set of coordinates with + corresponding sphere radii. + + Implemented using cell lists, giving O(N) performance. Should be + freed with freesasa_nb_free(). For efficient calculations + using this list the members of the returned struct should be used + directly and not freesasa_nb_contact(). + + @param coord a set of coordinates + @param radii radii for the coordinates + @return a neigbor list. Returns NULL if either argument is null or + if there were any problems constructing the list (see error + messages). + */ +nb_list * +freesasa_nb_new(const coord_t *coord, + const double *radii); + +/** + Frees a neigbor list created by freesasa_nb_new(). + + @param nb The neigbor list to free + */ +void freesasa_nb_free(nb_list *nb); + +/** + Checks if two atoms are in contact. Only included for reference. + + @param nb The neigbor list + @param i Index of first coordinate + @param j Index of second coordinate + @return 1 if contact, 0 else. + */ +int freesasa_nb_contact(const nb_list *nb, + int i, + int j); + +#endif /* FREESASA_NB_H */ diff --git a/.venv_haddock/include/site/python3.12/freesasa/parser.c b/.venv_haddock/include/site/python3.12/freesasa/parser.c new file mode 100644 index 0000000000000000000000000000000000000000..7b43573482bee80a3c876d1e3e89b40c69340d16 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/parser.c @@ -0,0 +1,1639 @@ +/* A Bison parser, made by GNU Bison 3.0.4. */ + +/* Bison implementation for Yacc-like parsers in C + + Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* As a special exception, you may create a larger work that contains + part or all of the Bison parser skeleton and distribute that work + under terms of your choice, so long as that work isn't itself a + parser generator using the skeleton or a modified version thereof + as a parser skeleton. Alternatively, if you modify or redistribute + the parser skeleton itself, you may (at your option) remove this + special exception, which will cause the skeleton and the resulting + Bison output files to be licensed under the GNU General Public + License without this special exception. + + This special exception was added by the Free Software Foundation in + version 2.2 of Bison. */ + +/* C LALR(1) parser skeleton written by Richard Stallman, by + simplifying the original so-called "semantic" parser. */ + +/* All symbols defined below should begin with yy or YY, to avoid + infringing on user name space. This should be done even for local + variables, as they might otherwise be expanded by user macros. + There are some unavoidable exceptions within include files to + define necessary library symbols; they are noted "INFRINGES ON + USER NAME SPACE" below. */ + +/* Identify Bison output. */ +#define YYBISON 1 + +/* Bison version. */ +#define YYBISON_VERSION "3.0.4" + +/* Skeleton name. */ +#define YYSKELETON_NAME "yacc.c" + +/* Pure parsers. */ +#define YYPURE 2 + +/* Push parsers. */ +#define YYPUSH 0 + +/* Pull parsers. */ +#define YYPULL 1 + + +/* Substitute the variable and function names. */ +#define yyparse freesasa_yyparse +#define yylex freesasa_yylex +#define yyerror freesasa_yyerror +#define yydebug freesasa_yydebug +#define yynerrs freesasa_yynerrs + + +/* Copy the first part of user declarations. */ +#line 1 "parser.y" /* yacc.c:339 */ + + +#include "selection.h" +#include "parser.h" +#include "lexer.h" + extern int freesasa_selection_parse_error(expression *e, yyscan_t scanner, const char *msg); + int freesasa_yyerror(expression **expression, yyscan_t scanner, const char *msg) { + return freesasa_selection_parse_error(*expression,scanner,msg); + } + + +#line 84 "parser.c" /* yacc.c:339 */ + +# ifndef YY_NULLPTR +# if defined __cplusplus && 201103L <= __cplusplus +# define YY_NULLPTR nullptr +# else +# define YY_NULLPTR 0 +# endif +# endif + +/* Enabling verbose error messages. */ +#ifdef YYERROR_VERBOSE +# undef YYERROR_VERBOSE +# define YYERROR_VERBOSE 1 +#else +# define YYERROR_VERBOSE 0 +#endif + +/* In a future release of Bison, this section will be replaced + by #include "parser.h". */ +#ifndef YY_FREESASA_YY_PARSER_H_INCLUDED +# define YY_FREESASA_YY_PARSER_H_INCLUDED +/* Debug traces. */ +#ifndef YYDEBUG +# define YYDEBUG 0 +#endif +#if YYDEBUG +extern int freesasa_yydebug; +#endif +/* "%code requires" blocks. */ +#line 13 "parser.y" /* yacc.c:355 */ + + +#ifndef FREESASA_TYPEDEF_YY_SCANNER_T +#define FREESASA_TYPEDEF_YY_SCANNER_T + typedef void* freesasa_yyscan_t; +#endif + + +#line 123 "parser.c" /* yacc.c:355 */ + +/* Token type. */ +#ifndef YYTOKENTYPE +# define YYTOKENTYPE + enum yytokentype + { + T_NUMBER = 258, + T_ID = 259, + T_SELID = 260, + T_AND = 261, + T_OR = 262, + T_NOT = 263, + T_RESN = 264, + T_RESI = 265, + T_SYMBOL = 266, + T_NAME = 267, + T_CHAIN = 268, + T_MINUS = 269, + ATOM = 270 + }; +#endif + +/* Value type. */ +#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED + +union YYSTYPE +{ +#line 30 "parser.y" /* yacc.c:355 */ + + const char *value; + expression *expression; + +#line 156 "parser.c" /* yacc.c:355 */ +}; + +typedef union YYSTYPE YYSTYPE; +# define YYSTYPE_IS_TRIVIAL 1 +# define YYSTYPE_IS_DECLARED 1 +#endif + + + +int freesasa_yyparse (expression **expression, freesasa_yyscan_t scanner); + +#endif /* !YY_FREESASA_YY_PARSER_H_INCLUDED */ + +/* Copy the second part of user declarations. */ + +#line 172 "parser.c" /* yacc.c:358 */ + +#ifdef short +# undef short +#endif + +#ifdef YYTYPE_UINT8 +typedef YYTYPE_UINT8 yytype_uint8; +#else +typedef unsigned char yytype_uint8; +#endif + +#ifdef YYTYPE_INT8 +typedef YYTYPE_INT8 yytype_int8; +#else +typedef signed char yytype_int8; +#endif + +#ifdef YYTYPE_UINT16 +typedef YYTYPE_UINT16 yytype_uint16; +#else +typedef unsigned short int yytype_uint16; +#endif + +#ifdef YYTYPE_INT16 +typedef YYTYPE_INT16 yytype_int16; +#else +typedef short int yytype_int16; +#endif + +#ifndef YYSIZE_T +# ifdef __SIZE_TYPE__ +# define YYSIZE_T __SIZE_TYPE__ +# elif defined size_t +# define YYSIZE_T size_t +# elif ! defined YYSIZE_T +# include /* INFRINGES ON USER NAME SPACE */ +# define YYSIZE_T size_t +# else +# define YYSIZE_T unsigned int +# endif +#endif + +#define YYSIZE_MAXIMUM ((YYSIZE_T) -1) + +#ifndef YY_ +# if defined YYENABLE_NLS && YYENABLE_NLS +# if ENABLE_NLS +# include /* INFRINGES ON USER NAME SPACE */ +# define YY_(Msgid) dgettext ("bison-runtime", Msgid) +# endif +# endif +# ifndef YY_ +# define YY_(Msgid) Msgid +# endif +#endif + +#ifndef YY_ATTRIBUTE +# if (defined __GNUC__ \ + && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ + || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C +# define YY_ATTRIBUTE(Spec) __attribute__(Spec) +# else +# define YY_ATTRIBUTE(Spec) /* empty */ +# endif +#endif + +#ifndef YY_ATTRIBUTE_PURE +# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) +#endif + +#ifndef YY_ATTRIBUTE_UNUSED +# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) +#endif + +#if !defined _Noreturn \ + && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112) +# if defined _MSC_VER && 1200 <= _MSC_VER +# define _Noreturn __declspec (noreturn) +# else +# define _Noreturn YY_ATTRIBUTE ((__noreturn__)) +# endif +#endif + +/* Suppress unused-variable warnings by "using" E. */ +#if ! defined lint || defined __GNUC__ +# define YYUSE(E) ((void) (E)) +#else +# define YYUSE(E) /* empty */ +#endif + +#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ +/* Suppress an incorrect diagnostic about yylval being uninitialized. */ +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ + _Pragma ("GCC diagnostic push") \ + _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ + _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") +# define YY_IGNORE_MAYBE_UNINITIALIZED_END \ + _Pragma ("GCC diagnostic pop") +#else +# define YY_INITIAL_VALUE(Value) Value +#endif +#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN +# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN +# define YY_IGNORE_MAYBE_UNINITIALIZED_END +#endif +#ifndef YY_INITIAL_VALUE +# define YY_INITIAL_VALUE(Value) /* Nothing. */ +#endif + + +#if ! defined yyoverflow || YYERROR_VERBOSE + +/* The parser invokes alloca or malloc; define the necessary symbols. */ + +# ifdef YYSTACK_USE_ALLOCA +# if YYSTACK_USE_ALLOCA +# ifdef __GNUC__ +# define YYSTACK_ALLOC __builtin_alloca +# elif defined __BUILTIN_VA_ARG_INCR +# include /* INFRINGES ON USER NAME SPACE */ +# elif defined _AIX +# define YYSTACK_ALLOC __alloca +# elif defined _MSC_VER +# include /* INFRINGES ON USER NAME SPACE */ +# define alloca _alloca +# else +# define YYSTACK_ALLOC alloca +# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS +# include /* INFRINGES ON USER NAME SPACE */ + /* Use EXIT_SUCCESS as a witness for stdlib.h. */ +# ifndef EXIT_SUCCESS +# define EXIT_SUCCESS 0 +# endif +# endif +# endif +# endif +# endif + +# ifdef YYSTACK_ALLOC + /* Pacify GCC's 'empty if-body' warning. */ +# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) +# ifndef YYSTACK_ALLOC_MAXIMUM + /* The OS might guarantee only one guard page at the bottom of the stack, + and a page size can be as small as 4096 bytes. So we cannot safely + invoke alloca (N) if N exceeds 4096. Use a slightly smaller number + to allow for a few compiler-allocated temporary stack slots. */ +# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ +# endif +# else +# define YYSTACK_ALLOC YYMALLOC +# define YYSTACK_FREE YYFREE +# ifndef YYSTACK_ALLOC_MAXIMUM +# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM +# endif +# if (defined __cplusplus && ! defined EXIT_SUCCESS \ + && ! ((defined YYMALLOC || defined malloc) \ + && (defined YYFREE || defined free))) +# include /* INFRINGES ON USER NAME SPACE */ +# ifndef EXIT_SUCCESS +# define EXIT_SUCCESS 0 +# endif +# endif +# ifndef YYMALLOC +# define YYMALLOC malloc +# if ! defined malloc && ! defined EXIT_SUCCESS +void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ +# endif +# endif +# ifndef YYFREE +# define YYFREE free +# if ! defined free && ! defined EXIT_SUCCESS +void free (void *); /* INFRINGES ON USER NAME SPACE */ +# endif +# endif +# endif +#endif /* ! defined yyoverflow || YYERROR_VERBOSE */ + + +#if (! defined yyoverflow \ + && (! defined __cplusplus \ + || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) + +/* A type that is properly aligned for any stack member. */ +union yyalloc +{ + yytype_int16 yyss_alloc; + YYSTYPE yyvs_alloc; +}; + +/* The size of the maximum gap between one aligned stack and the next. */ +# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) + +/* The size of an array large to enough to hold all stacks, each with + N elements. */ +# define YYSTACK_BYTES(N) \ + ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + + YYSTACK_GAP_MAXIMUM) + +# define YYCOPY_NEEDED 1 + +/* Relocate STACK from its old location to the new one. The + local variables YYSIZE and YYSTACKSIZE give the old and new number of + elements in the stack, and YYPTR gives the new location of the + stack. Advance YYPTR to a properly aligned location for the next + stack. */ +# define YYSTACK_RELOCATE(Stack_alloc, Stack) \ + do \ + { \ + YYSIZE_T yynewbytes; \ + YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ + Stack = &yyptr->Stack_alloc; \ + yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ + yyptr += yynewbytes / sizeof (*yyptr); \ + } \ + while (0) + +#endif + +#if defined YYCOPY_NEEDED && YYCOPY_NEEDED +/* Copy COUNT objects from SRC to DST. The source and destination do + not overlap. */ +# ifndef YYCOPY +# if defined __GNUC__ && 1 < __GNUC__ +# define YYCOPY(Dst, Src, Count) \ + __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) +# else +# define YYCOPY(Dst, Src, Count) \ + do \ + { \ + YYSIZE_T yyi; \ + for (yyi = 0; yyi < (Count); yyi++) \ + (Dst)[yyi] = (Src)[yyi]; \ + } \ + while (0) +# endif +# endif +#endif /* !YYCOPY_NEEDED */ + +/* YYFINAL -- State number of the termination state. */ +#define YYFINAL 4 +/* YYLAST -- Last index in YYTABLE. */ +#define YYLAST 45 + +/* YYNTOKENS -- Number of terminals. */ +#define YYNTOKENS 21 +/* YYNNTS -- Number of nonterminals. */ +#define YYNNTS 7 +/* YYNRULES -- Number of rules. */ +#define YYNRULES 24 +/* YYNSTATES -- Number of states. */ +#define YYNSTATES 44 + +/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned + by yylex, with out-of-bounds checking. */ +#define YYUNDEFTOK 2 +#define YYMAXUTOK 270 + +#define YYTRANSLATE(YYX) \ + ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) + +/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM + as returned by yylex, without out-of-bounds checking. */ +static const yytype_uint8 yytranslate[] = +{ + 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 19, 20, 2, 16, 18, 17, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15 +}; + +#if YYDEBUG + /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ +static const yytype_uint8 yyrline[] = +{ + 0, 68, 68, 72, 73, 74, 75, 76, 77, 78, + 79, 80, 84, 85, 89, 90, 91, 92, 93, 97, + 98, 99, 103, 104, 105 +}; +#endif + +#if YYDEBUG || YYERROR_VERBOSE || 0 +/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. + First, the terminals, then, starting at YYNTOKENS, nonterminals. */ +static const char *const yytname[] = +{ + "$end", "error", "$undefined", "T_NUMBER", "T_ID", "T_SELID", "T_AND", + "T_OR", "T_NOT", "T_RESN", "T_RESI", "T_SYMBOL", "T_NAME", "T_CHAIN", + "T_MINUS", "ATOM", "'+'", "'-'", "','", "'('", "')'", "$accept", "stmt", + "expr", "list", "r_range", "c_range", "id", YY_NULLPTR +}; +#endif + +# ifdef YYPRINT +/* YYTOKNUM[NUM] -- (External) token number corresponding to the + (internal) symbol number NUM (which must be that of a token). */ +static const yytype_uint16 yytoknum[] = +{ + 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, + 265, 266, 267, 268, 269, 270, 43, 45, 44, 40, + 41 +}; +# endif + +#define YYPACT_NINF -20 + +#define yypact_value_is_default(Yystate) \ + (!!((Yystate) == (-20))) + +#define YYTABLE_NINF -1 + +#define yytable_value_is_error(Yytable_value) \ + 0 + + /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing + STATE-NUM. */ +static const yytype_int8 yypact[] = +{ + -3, -12, 14, 26, -20, 26, 7, 1, 7, 7, + 7, 26, 10, -20, -20, -20, 19, -20, 15, 7, + 16, 12, -20, -20, 24, 25, 13, 26, 26, -20, + 7, -20, 1, 7, 7, 7, -20, -20, 35, -20, + -20, -20, -20, -20 +}; + + /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. + Performed when YYTABLE does not specify something else to do. Zero + means the default is an error. */ +static const yytype_uint8 yydefact[] = +{ + 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, + 0, 0, 2, 6, 22, 23, 0, 7, 12, 0, + 8, 14, 9, 10, 11, 19, 0, 0, 0, 24, + 0, 17, 0, 18, 0, 0, 3, 4, 5, 13, + 15, 16, 20, 21 +}; + + /* YYPGOTO[NTERM-NUM]. */ +static const yytype_int8 yypgoto[] = +{ + -20, -20, -4, 0, -19, 9, -7 +}; + + /* YYDEFGOTO[NTERM-NUM]. */ +static const yytype_int8 yydefgoto[] = +{ + -1, 2, 12, 17, 20, 24, 18 +}; + + /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If + positive, shift that token. If negative, reduce the rule whose + number is the opposite. If YYTABLE_NINF, syntax error. */ +static const yytype_uint8 yytable[] = +{ + 21, 13, 1, 25, 14, 15, 3, 26, 22, 23, + 14, 15, 31, 40, 4, 16, 27, 28, 19, 27, + 28, 16, 29, 37, 38, 21, 41, 25, 43, 33, + 39, 30, 32, 36, 5, 6, 7, 8, 9, 10, + 34, 27, 35, 42, 0, 11 +}; + +static const yytype_int8 yycheck[] = +{ + 7, 5, 5, 10, 3, 4, 18, 11, 8, 9, + 3, 4, 19, 32, 0, 14, 6, 7, 17, 6, + 7, 14, 3, 27, 28, 32, 33, 34, 35, 17, + 30, 16, 16, 20, 8, 9, 10, 11, 12, 13, + 16, 6, 17, 34, -1, 19 +}; + + /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing + symbol of state STATE-NUM. */ +static const yytype_uint8 yystos[] = +{ + 0, 5, 22, 18, 0, 8, 9, 10, 11, 12, + 13, 19, 23, 23, 3, 4, 14, 24, 27, 17, + 25, 27, 24, 24, 26, 27, 23, 6, 7, 3, + 16, 27, 16, 17, 16, 17, 20, 23, 23, 24, + 25, 27, 26, 27 +}; + + /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ +static const yytype_uint8 yyr1[] = +{ + 0, 21, 22, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 24, 24, 25, 25, 25, 25, 25, 26, + 26, 26, 27, 27, 27 +}; + + /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ +static const yytype_uint8 yyr2[] = +{ + 0, 2, 3, 3, 3, 3, 2, 2, 2, 2, + 2, 2, 1, 3, 1, 3, 3, 2, 2, 1, + 3, 3, 1, 1, 2 +}; + + +#define yyerrok (yyerrstatus = 0) +#define yyclearin (yychar = YYEMPTY) +#define YYEMPTY (-2) +#define YYEOF 0 + +#define YYACCEPT goto yyacceptlab +#define YYABORT goto yyabortlab +#define YYERROR goto yyerrorlab + + +#define YYRECOVERING() (!!yyerrstatus) + +#define YYBACKUP(Token, Value) \ +do \ + if (yychar == YYEMPTY) \ + { \ + yychar = (Token); \ + yylval = (Value); \ + YYPOPSTACK (yylen); \ + yystate = *yyssp; \ + goto yybackup; \ + } \ + else \ + { \ + yyerror (expression, scanner, YY_("syntax error: cannot back up")); \ + YYERROR; \ + } \ +while (0) + +/* Error token number */ +#define YYTERROR 1 +#define YYERRCODE 256 + + + +/* Enable debugging if requested. */ +#if YYDEBUG + +# ifndef YYFPRINTF +# include /* INFRINGES ON USER NAME SPACE */ +# define YYFPRINTF fprintf +# endif + +# define YYDPRINTF(Args) \ +do { \ + if (yydebug) \ + YYFPRINTF Args; \ +} while (0) + +/* This macro is provided for backward compatibility. */ +#ifndef YY_LOCATION_PRINT +# define YY_LOCATION_PRINT(File, Loc) ((void) 0) +#endif + + +# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ +do { \ + if (yydebug) \ + { \ + YYFPRINTF (stderr, "%s ", Title); \ + yy_symbol_print (stderr, \ + Type, Value, expression, scanner); \ + YYFPRINTF (stderr, "\n"); \ + } \ +} while (0) + + +/*----------------------------------------. +| Print this symbol's value on YYOUTPUT. | +`----------------------------------------*/ + +static void +yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, expression **expression, freesasa_yyscan_t scanner) +{ + FILE *yyo = yyoutput; + YYUSE (yyo); + YYUSE (expression); + YYUSE (scanner); + if (!yyvaluep) + return; +# ifdef YYPRINT + if (yytype < YYNTOKENS) + YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); +# endif + YYUSE (yytype); +} + + +/*--------------------------------. +| Print this symbol on YYOUTPUT. | +`--------------------------------*/ + +static void +yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, expression **expression, freesasa_yyscan_t scanner) +{ + YYFPRINTF (yyoutput, "%s %s (", + yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); + + yy_symbol_value_print (yyoutput, yytype, yyvaluep, expression, scanner); + YYFPRINTF (yyoutput, ")"); +} + +/*------------------------------------------------------------------. +| yy_stack_print -- Print the state stack from its BOTTOM up to its | +| TOP (included). | +`------------------------------------------------------------------*/ + +static void +yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) +{ + YYFPRINTF (stderr, "Stack now"); + for (; yybottom <= yytop; yybottom++) + { + int yybot = *yybottom; + YYFPRINTF (stderr, " %d", yybot); + } + YYFPRINTF (stderr, "\n"); +} + +# define YY_STACK_PRINT(Bottom, Top) \ +do { \ + if (yydebug) \ + yy_stack_print ((Bottom), (Top)); \ +} while (0) + + +/*------------------------------------------------. +| Report that the YYRULE is going to be reduced. | +`------------------------------------------------*/ + +static void +yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule, expression **expression, freesasa_yyscan_t scanner) +{ + unsigned long int yylno = yyrline[yyrule]; + int yynrhs = yyr2[yyrule]; + int yyi; + YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", + yyrule - 1, yylno); + /* The symbols being reduced. */ + for (yyi = 0; yyi < yynrhs; yyi++) + { + YYFPRINTF (stderr, " $%d = ", yyi + 1); + yy_symbol_print (stderr, + yystos[yyssp[yyi + 1 - yynrhs]], + &(yyvsp[(yyi + 1) - (yynrhs)]) + , expression, scanner); + YYFPRINTF (stderr, "\n"); + } +} + +# define YY_REDUCE_PRINT(Rule) \ +do { \ + if (yydebug) \ + yy_reduce_print (yyssp, yyvsp, Rule, expression, scanner); \ +} while (0) + +/* Nonzero means print parse trace. It is left uninitialized so that + multiple parsers can coexist. */ +int yydebug; +#else /* !YYDEBUG */ +# define YYDPRINTF(Args) +# define YY_SYMBOL_PRINT(Title, Type, Value, Location) +# define YY_STACK_PRINT(Bottom, Top) +# define YY_REDUCE_PRINT(Rule) +#endif /* !YYDEBUG */ + + +/* YYINITDEPTH -- initial size of the parser's stacks. */ +#ifndef YYINITDEPTH +# define YYINITDEPTH 200 +#endif + +/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only + if the built-in stack extension method is used). + + Do not make this value too large; the results are undefined if + YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) + evaluated with infinite-precision integer arithmetic. */ + +#ifndef YYMAXDEPTH +# define YYMAXDEPTH 10000 +#endif + + +#if YYERROR_VERBOSE + +# ifndef yystrlen +# if defined __GLIBC__ && defined _STRING_H +# define yystrlen strlen +# else +/* Return the length of YYSTR. */ +static YYSIZE_T +yystrlen (const char *yystr) +{ + YYSIZE_T yylen; + for (yylen = 0; yystr[yylen]; yylen++) + continue; + return yylen; +} +# endif +# endif + +# ifndef yystpcpy +# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE +# define yystpcpy stpcpy +# else +/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in + YYDEST. */ +static char * +yystpcpy (char *yydest, const char *yysrc) +{ + char *yyd = yydest; + const char *yys = yysrc; + + while ((*yyd++ = *yys++) != '\0') + continue; + + return yyd - 1; +} +# endif +# endif + +# ifndef yytnamerr +/* Copy to YYRES the contents of YYSTR after stripping away unnecessary + quotes and backslashes, so that it's suitable for yyerror. The + heuristic is that double-quoting is unnecessary unless the string + contains an apostrophe, a comma, or backslash (other than + backslash-backslash). YYSTR is taken from yytname. If YYRES is + null, do not copy; instead, return the length of what the result + would have been. */ +static YYSIZE_T +yytnamerr (char *yyres, const char *yystr) +{ + if (*yystr == '"') + { + YYSIZE_T yyn = 0; + char const *yyp = yystr; + + for (;;) + switch (*++yyp) + { + case '\'': + case ',': + goto do_not_strip_quotes; + + case '\\': + if (*++yyp != '\\') + goto do_not_strip_quotes; + /* Fall through. */ + default: + if (yyres) + yyres[yyn] = *yyp; + yyn++; + break; + + case '"': + if (yyres) + yyres[yyn] = '\0'; + return yyn; + } + do_not_strip_quotes: ; + } + + if (! yyres) + return yystrlen (yystr); + + return yystpcpy (yyres, yystr) - yyres; +} +# endif + +/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message + about the unexpected token YYTOKEN for the state stack whose top is + YYSSP. + + Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is + not large enough to hold the message. In that case, also set + *YYMSG_ALLOC to the required number of bytes. Return 2 if the + required number of bytes is too large to store. */ +static int +yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, + yytype_int16 *yyssp, int yytoken) +{ + YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); + YYSIZE_T yysize = yysize0; + enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; + /* Internationalized format string. */ + const char *yyformat = YY_NULLPTR; + /* Arguments of yyformat. */ + char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; + /* Number of reported tokens (one for the "unexpected", one per + "expected"). */ + int yycount = 0; + + /* There are many possibilities here to consider: + - If this state is a consistent state with a default action, then + the only way this function was invoked is if the default action + is an error action. In that case, don't check for expected + tokens because there are none. + - The only way there can be no lookahead present (in yychar) is if + this state is a consistent state with a default action. Thus, + detecting the absence of a lookahead is sufficient to determine + that there is no unexpected or expected token to report. In that + case, just report a simple "syntax error". + - Don't assume there isn't a lookahead just because this state is a + consistent state with a default action. There might have been a + previous inconsistent state, consistent state with a non-default + action, or user semantic action that manipulated yychar. + - Of course, the expected token list depends on states to have + correct lookahead information, and it depends on the parser not + to perform extra reductions after fetching a lookahead from the + scanner and before detecting a syntax error. Thus, state merging + (from LALR or IELR) and default reductions corrupt the expected + token list. However, the list is correct for canonical LR with + one exception: it will still contain any token that will not be + accepted due to an error action in a later state. + */ + if (yytoken != YYEMPTY) + { + int yyn = yypact[*yyssp]; + yyarg[yycount++] = yytname[yytoken]; + if (!yypact_value_is_default (yyn)) + { + /* Start YYX at -YYN if negative to avoid negative indexes in + YYCHECK. In other words, skip the first -YYN actions for + this state because they are default actions. */ + int yyxbegin = yyn < 0 ? -yyn : 0; + /* Stay within bounds of both yycheck and yytname. */ + int yychecklim = YYLAST - yyn + 1; + int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; + int yyx; + + for (yyx = yyxbegin; yyx < yyxend; ++yyx) + if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR + && !yytable_value_is_error (yytable[yyx + yyn])) + { + if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) + { + yycount = 1; + yysize = yysize0; + break; + } + yyarg[yycount++] = yytname[yyx]; + { + YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); + if (! (yysize <= yysize1 + && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) + return 2; + yysize = yysize1; + } + } + } + } + + switch (yycount) + { +# define YYCASE_(N, S) \ + case N: \ + yyformat = S; \ + break + YYCASE_(0, YY_("syntax error")); + YYCASE_(1, YY_("syntax error, unexpected %s")); + YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); + YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); + YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); + YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); +# undef YYCASE_ + } + + { + YYSIZE_T yysize1 = yysize + yystrlen (yyformat); + if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) + return 2; + yysize = yysize1; + } + + if (*yymsg_alloc < yysize) + { + *yymsg_alloc = 2 * yysize; + if (! (yysize <= *yymsg_alloc + && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) + *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; + return 1; + } + + /* Avoid sprintf, as that infringes on the user's name space. + Don't have undefined behavior even if the translation + produced a string with the wrong number of "%s"s. */ + { + char *yyp = *yymsg; + int yyi = 0; + while ((*yyp = *yyformat) != '\0') + if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) + { + yyp += yytnamerr (yyp, yyarg[yyi++]); + yyformat += 2; + } + else + { + yyp++; + yyformat++; + } + } + return 0; +} +#endif /* YYERROR_VERBOSE */ + +/*-----------------------------------------------. +| Release the memory associated to this symbol. | +`-----------------------------------------------*/ + +static void +yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, expression **expression, freesasa_yyscan_t scanner) +{ + YYUSE (yyvaluep); + YYUSE (expression); + YYUSE (scanner); + if (!yymsg) + yymsg = "Deleting"; + YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); + + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + YYUSE (yytype); + YY_IGNORE_MAYBE_UNINITIALIZED_END +} + + + + +/*----------. +| yyparse. | +`----------*/ + +int +yyparse (expression **expression, freesasa_yyscan_t scanner) +{ +/* The lookahead symbol. */ +int yychar; + + +/* The semantic value of the lookahead symbol. */ +/* Default value used for initialization, for pacifying older GCCs + or non-GCC compilers. */ +YY_INITIAL_VALUE (static YYSTYPE yyval_default;) +YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); + + /* Number of syntax errors so far. */ + int yynerrs; + + int yystate; + /* Number of tokens to shift before error messages enabled. */ + int yyerrstatus; + + /* The stacks and their tools: + 'yyss': related to states. + 'yyvs': related to semantic values. + + Refer to the stacks through separate pointers, to allow yyoverflow + to reallocate them elsewhere. */ + + /* The state stack. */ + yytype_int16 yyssa[YYINITDEPTH]; + yytype_int16 *yyss; + yytype_int16 *yyssp; + + /* The semantic value stack. */ + YYSTYPE yyvsa[YYINITDEPTH]; + YYSTYPE *yyvs; + YYSTYPE *yyvsp; + + YYSIZE_T yystacksize; + + int yyn; + int yyresult; + /* Lookahead token as an internal (translated) token number. */ + int yytoken = 0; + /* The variables used to return semantic value and location from the + action routines. */ + YYSTYPE yyval; + +#if YYERROR_VERBOSE + /* Buffer for error messages, and its allocated size. */ + char yymsgbuf[128]; + char *yymsg = yymsgbuf; + YYSIZE_T yymsg_alloc = sizeof yymsgbuf; +#endif + +#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) + + /* The number of symbols on the RHS of the reduced rule. + Keep to zero when no symbol should be popped. */ + int yylen = 0; + + yyssp = yyss = yyssa; + yyvsp = yyvs = yyvsa; + yystacksize = YYINITDEPTH; + + YYDPRINTF ((stderr, "Starting parse\n")); + + yystate = 0; + yyerrstatus = 0; + yynerrs = 0; + yychar = YYEMPTY; /* Cause a token to be read. */ + goto yysetstate; + +/*------------------------------------------------------------. +| yynewstate -- Push a new state, which is found in yystate. | +`------------------------------------------------------------*/ + yynewstate: + /* In all cases, when you get here, the value and location stacks + have just been pushed. So pushing a state here evens the stacks. */ + yyssp++; + + yysetstate: + *yyssp = yystate; + + if (yyss + yystacksize - 1 <= yyssp) + { + /* Get the current used size of the three stacks, in elements. */ + YYSIZE_T yysize = yyssp - yyss + 1; + +#ifdef yyoverflow + { + /* Give user a chance to reallocate the stack. Use copies of + these so that the &'s don't force the real ones into + memory. */ + YYSTYPE *yyvs1 = yyvs; + yytype_int16 *yyss1 = yyss; + + /* Each stack pointer address is followed by the size of the + data in use in that stack, in bytes. This used to be a + conditional around just the two extra args, but that might + be undefined if yyoverflow is a macro. */ + yyoverflow (YY_("memory exhausted"), + &yyss1, yysize * sizeof (*yyssp), + &yyvs1, yysize * sizeof (*yyvsp), + &yystacksize); + + yyss = yyss1; + yyvs = yyvs1; + } +#else /* no yyoverflow */ +# ifndef YYSTACK_RELOCATE + goto yyexhaustedlab; +# else + /* Extend the stack our own way. */ + if (YYMAXDEPTH <= yystacksize) + goto yyexhaustedlab; + yystacksize *= 2; + if (YYMAXDEPTH < yystacksize) + yystacksize = YYMAXDEPTH; + + { + yytype_int16 *yyss1 = yyss; + union yyalloc *yyptr = + (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); + if (! yyptr) + goto yyexhaustedlab; + YYSTACK_RELOCATE (yyss_alloc, yyss); + YYSTACK_RELOCATE (yyvs_alloc, yyvs); +# undef YYSTACK_RELOCATE + if (yyss1 != yyssa) + YYSTACK_FREE (yyss1); + } +# endif +#endif /* no yyoverflow */ + + yyssp = yyss + yysize - 1; + yyvsp = yyvs + yysize - 1; + + YYDPRINTF ((stderr, "Stack size increased to %lu\n", + (unsigned long int) yystacksize)); + + if (yyss + yystacksize - 1 <= yyssp) + YYABORT; + } + + YYDPRINTF ((stderr, "Entering state %d\n", yystate)); + + if (yystate == YYFINAL) + YYACCEPT; + + goto yybackup; + +/*-----------. +| yybackup. | +`-----------*/ +yybackup: + + /* Do appropriate processing given the current state. Read a + lookahead token if we need one and don't already have one. */ + + /* First try to decide what to do without reference to lookahead token. */ + yyn = yypact[yystate]; + if (yypact_value_is_default (yyn)) + goto yydefault; + + /* Not known => get a lookahead token if don't already have one. */ + + /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ + if (yychar == YYEMPTY) + { + YYDPRINTF ((stderr, "Reading a token: ")); + yychar = yylex (&yylval, scanner); + } + + if (yychar <= YYEOF) + { + yychar = yytoken = YYEOF; + YYDPRINTF ((stderr, "Now at end of input.\n")); + } + else + { + yytoken = YYTRANSLATE (yychar); + YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); + } + + /* If the proper action on seeing token YYTOKEN is to reduce or to + detect an error, take that action. */ + yyn += yytoken; + if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) + goto yydefault; + yyn = yytable[yyn]; + if (yyn <= 0) + { + if (yytable_value_is_error (yyn)) + goto yyerrlab; + yyn = -yyn; + goto yyreduce; + } + + /* Count tokens shifted since error; after three, turn off error + status. */ + if (yyerrstatus) + yyerrstatus--; + + /* Shift the lookahead token. */ + YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); + + /* Discard the shifted token. */ + yychar = YYEMPTY; + + yystate = yyn; + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + *++yyvsp = yylval; + YY_IGNORE_MAYBE_UNINITIALIZED_END + + goto yynewstate; + + +/*-----------------------------------------------------------. +| yydefault -- do the default action for the current state. | +`-----------------------------------------------------------*/ +yydefault: + yyn = yydefact[yystate]; + if (yyn == 0) + goto yyerrlab; + goto yyreduce; + + +/*-----------------------------. +| yyreduce -- Do a reduction. | +`-----------------------------*/ +yyreduce: + /* yyn is the number of a rule to reduce with. */ + yylen = yyr2[yyn]; + + /* If YYLEN is nonzero, implement the default value of the action: + '$$ = $1'. + + Otherwise, the following line sets YYVAL to garbage. + This behavior is undocumented and Bison + users should not rely upon it. Assigning to YYVAL + unconditionally makes the parser a bit smaller, and it avoids a + GCC warning that YYVAL may be used uninitialized. */ + yyval = yyvsp[1-yylen]; + + + YY_REDUCE_PRINT (yyn); + switch (yyn) + { + case 2: +#line 68 "parser.y" /* yacc.c:1646 */ + { *expression = freesasa_selection_create((yyvsp[0].expression), (yyvsp[-2].value)); } +#line 1277 "parser.c" /* yacc.c:1646 */ + break; + + case 3: +#line 72 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = (yyvsp[-1].expression); } +#line 1283 "parser.c" /* yacc.c:1646 */ + break; + + case 4: +#line 73 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_operation(E_AND, (yyvsp[-2].expression), (yyvsp[0].expression)); } +#line 1289 "parser.c" /* yacc.c:1646 */ + break; + + case 5: +#line 74 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_operation(E_OR, (yyvsp[-2].expression), (yyvsp[0].expression)); } +#line 1295 "parser.c" /* yacc.c:1646 */ + break; + + case 6: +#line 75 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_operation(E_NOT, NULL, (yyvsp[0].expression)); } +#line 1301 "parser.c" /* yacc.c:1646 */ + break; + + case 7: +#line 76 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_selector(E_RESN, (yyvsp[0].expression)); } +#line 1307 "parser.c" /* yacc.c:1646 */ + break; + + case 8: +#line 77 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_selector(E_RESI, (yyvsp[0].expression)); } +#line 1313 "parser.c" /* yacc.c:1646 */ + break; + + case 9: +#line 78 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_selector(E_SYMBOL, (yyvsp[0].expression)); } +#line 1319 "parser.c" /* yacc.c:1646 */ + break; + + case 10: +#line 79 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_selector(E_NAME, (yyvsp[0].expression)); } +#line 1325 "parser.c" /* yacc.c:1646 */ + break; + + case 11: +#line 80 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_selector(E_CHAIN, (yyvsp[0].expression)); } +#line 1331 "parser.c" /* yacc.c:1646 */ + break; + + case 12: +#line 84 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = (yyvsp[0].expression); } +#line 1337 "parser.c" /* yacc.c:1646 */ + break; + + case 13: +#line 85 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_operation(E_PLUS, (yyvsp[-2].expression), (yyvsp[0].expression)); } +#line 1343 "parser.c" /* yacc.c:1646 */ + break; + + case 14: +#line 89 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = (yyvsp[0].expression); } +#line 1349 "parser.c" /* yacc.c:1646 */ + break; + + case 15: +#line 90 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_operation(E_PLUS, (yyvsp[-2].expression), (yyvsp[0].expression)); } +#line 1355 "parser.c" /* yacc.c:1646 */ + break; + + case 16: +#line 91 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_operation(E_RANGE, (yyvsp[-2].expression), (yyvsp[0].expression)); } +#line 1361 "parser.c" /* yacc.c:1646 */ + break; + + case 17: +#line 92 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_operation(E_RANGE_OPEN_L, NULL, (yyvsp[0].expression)); } +#line 1367 "parser.c" /* yacc.c:1646 */ + break; + + case 18: +#line 93 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_operation(E_RANGE_OPEN_R, (yyvsp[-1].expression), NULL); } +#line 1373 "parser.c" /* yacc.c:1646 */ + break; + + case 19: +#line 97 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = (yyvsp[0].expression); } +#line 1379 "parser.c" /* yacc.c:1646 */ + break; + + case 20: +#line 98 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_operation(E_PLUS, (yyvsp[-2].expression), (yyvsp[0].expression)); } +#line 1385 "parser.c" /* yacc.c:1646 */ + break; + + case 21: +#line 99 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_operation(E_RANGE, (yyvsp[-2].expression), (yyvsp[0].expression)); } +#line 1391 "parser.c" /* yacc.c:1646 */ + break; + + case 22: +#line 103 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_atom(E_NUMBER, (yyvsp[0].value)); } +#line 1397 "parser.c" /* yacc.c:1646 */ + break; + + case 23: +#line 104 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_atom(E_ID, (yyvsp[0].value)); } +#line 1403 "parser.c" /* yacc.c:1646 */ + break; + + case 24: +#line 105 "parser.y" /* yacc.c:1646 */ + { (yyval.expression) = freesasa_selection_atom(E_NEGNUM, (yyvsp[0].value)); } +#line 1409 "parser.c" /* yacc.c:1646 */ + break; + + +#line 1413 "parser.c" /* yacc.c:1646 */ + default: break; + } + /* User semantic actions sometimes alter yychar, and that requires + that yytoken be updated with the new translation. We take the + approach of translating immediately before every use of yytoken. + One alternative is translating here after every semantic action, + but that translation would be missed if the semantic action invokes + YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or + if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an + incorrect destructor might then be invoked immediately. In the + case of YYERROR or YYBACKUP, subsequent parser actions might lead + to an incorrect destructor call or verbose syntax error message + before the lookahead is translated. */ + YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); + + YYPOPSTACK (yylen); + yylen = 0; + YY_STACK_PRINT (yyss, yyssp); + + *++yyvsp = yyval; + + /* Now 'shift' the result of the reduction. Determine what state + that goes to, based on the state we popped back to and the rule + number reduced by. */ + + yyn = yyr1[yyn]; + + yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; + if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) + yystate = yytable[yystate]; + else + yystate = yydefgoto[yyn - YYNTOKENS]; + + goto yynewstate; + + +/*--------------------------------------. +| yyerrlab -- here on detecting error. | +`--------------------------------------*/ +yyerrlab: + /* Make sure we have latest lookahead translation. See comments at + user semantic actions for why this is necessary. */ + yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); + + /* If not already recovering from an error, report this error. */ + if (!yyerrstatus) + { + ++yynerrs; +#if ! YYERROR_VERBOSE + yyerror (expression, scanner, YY_("syntax error")); +#else +# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ + yyssp, yytoken) + { + char const *yymsgp = YY_("syntax error"); + int yysyntax_error_status; + yysyntax_error_status = YYSYNTAX_ERROR; + if (yysyntax_error_status == 0) + yymsgp = yymsg; + else if (yysyntax_error_status == 1) + { + if (yymsg != yymsgbuf) + YYSTACK_FREE (yymsg); + yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); + if (!yymsg) + { + yymsg = yymsgbuf; + yymsg_alloc = sizeof yymsgbuf; + yysyntax_error_status = 2; + } + else + { + yysyntax_error_status = YYSYNTAX_ERROR; + yymsgp = yymsg; + } + } + yyerror (expression, scanner, yymsgp); + if (yysyntax_error_status == 2) + goto yyexhaustedlab; + } +# undef YYSYNTAX_ERROR +#endif + } + + + + if (yyerrstatus == 3) + { + /* If just tried and failed to reuse lookahead token after an + error, discard it. */ + + if (yychar <= YYEOF) + { + /* Return failure if at end of input. */ + if (yychar == YYEOF) + YYABORT; + } + else + { + yydestruct ("Error: discarding", + yytoken, &yylval, expression, scanner); + yychar = YYEMPTY; + } + } + + /* Else will try to reuse lookahead token after shifting the error + token. */ + goto yyerrlab1; + + +/*---------------------------------------------------. +| yyerrorlab -- error raised explicitly by YYERROR. | +`---------------------------------------------------*/ +yyerrorlab: + + /* Pacify compilers like GCC when the user code never invokes + YYERROR and the label yyerrorlab therefore never appears in user + code. */ + if (/*CONSTCOND*/ 0) + goto yyerrorlab; + + /* Do not reclaim the symbols of the rule whose action triggered + this YYERROR. */ + YYPOPSTACK (yylen); + yylen = 0; + YY_STACK_PRINT (yyss, yyssp); + yystate = *yyssp; + goto yyerrlab1; + + +/*-------------------------------------------------------------. +| yyerrlab1 -- common code for both syntax error and YYERROR. | +`-------------------------------------------------------------*/ +yyerrlab1: + yyerrstatus = 3; /* Each real token shifted decrements this. */ + + for (;;) + { + yyn = yypact[yystate]; + if (!yypact_value_is_default (yyn)) + { + yyn += YYTERROR; + if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) + { + yyn = yytable[yyn]; + if (0 < yyn) + break; + } + } + + /* Pop the current state because it cannot handle the error token. */ + if (yyssp == yyss) + YYABORT; + + + yydestruct ("Error: popping", + yystos[yystate], yyvsp, expression, scanner); + YYPOPSTACK (1); + yystate = *yyssp; + YY_STACK_PRINT (yyss, yyssp); + } + + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + *++yyvsp = yylval; + YY_IGNORE_MAYBE_UNINITIALIZED_END + + + /* Shift the error token. */ + YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); + + yystate = yyn; + goto yynewstate; + + +/*-------------------------------------. +| yyacceptlab -- YYACCEPT comes here. | +`-------------------------------------*/ +yyacceptlab: + yyresult = 0; + goto yyreturn; + +/*-----------------------------------. +| yyabortlab -- YYABORT comes here. | +`-----------------------------------*/ +yyabortlab: + yyresult = 1; + goto yyreturn; + +#if !defined yyoverflow || YYERROR_VERBOSE +/*-------------------------------------------------. +| yyexhaustedlab -- memory exhaustion comes here. | +`-------------------------------------------------*/ +yyexhaustedlab: + yyerror (expression, scanner, YY_("memory exhausted")); + yyresult = 2; + /* Fall through. */ +#endif + +yyreturn: + if (yychar != YYEMPTY) + { + /* Make sure we have latest lookahead translation. See comments at + user semantic actions for why this is necessary. */ + yytoken = YYTRANSLATE (yychar); + yydestruct ("Cleanup: discarding lookahead", + yytoken, &yylval, expression, scanner); + } + /* Do not reclaim the symbols of the rule whose action triggered + this YYABORT or YYACCEPT. */ + YYPOPSTACK (yylen); + YY_STACK_PRINT (yyss, yyssp); + while (yyssp != yyss) + { + yydestruct ("Cleanup: popping", + yystos[*yyssp], yyvsp, expression, scanner); + YYPOPSTACK (1); + } +#ifndef yyoverflow + if (yyss != yyssa) + YYSTACK_FREE (yyss); +#endif +#if YYERROR_VERBOSE + if (yymsg != yymsgbuf) + YYSTACK_FREE (yymsg); +#endif + return yyresult; +} diff --git a/.venv_haddock/include/site/python3.12/freesasa/parser.h b/.venv_haddock/include/site/python3.12/freesasa/parser.h new file mode 100644 index 0000000000000000000000000000000000000000..144b17f4f2f103a00c58d48187f44034e9483ad6 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/parser.h @@ -0,0 +1,97 @@ +/* A Bison parser, made by GNU Bison 3.0.4. */ + +/* Bison interface for Yacc-like parsers in C + + Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* As a special exception, you may create a larger work that contains + part or all of the Bison parser skeleton and distribute that work + under terms of your choice, so long as that work isn't itself a + parser generator using the skeleton or a modified version thereof + as a parser skeleton. Alternatively, if you modify or redistribute + the parser skeleton itself, you may (at your option) remove this + special exception, which will cause the skeleton and the resulting + Bison output files to be licensed under the GNU General Public + License without this special exception. + + This special exception was added by the Free Software Foundation in + version 2.2 of Bison. */ + +#ifndef YY_FREESASA_YY_PARSER_H_INCLUDED +# define YY_FREESASA_YY_PARSER_H_INCLUDED +/* Debug traces. */ +#ifndef YYDEBUG +# define YYDEBUG 0 +#endif +#if YYDEBUG +extern int freesasa_yydebug; +#endif +/* "%code requires" blocks. */ +#line 13 "parser.y" /* yacc.c:1909 */ + + +#ifndef FREESASA_TYPEDEF_YY_SCANNER_T +#define FREESASA_TYPEDEF_YY_SCANNER_T + typedef void* freesasa_yyscan_t; +#endif + + +#line 53 "parser.h" /* yacc.c:1909 */ + +/* Token type. */ +#ifndef YYTOKENTYPE +# define YYTOKENTYPE + enum yytokentype + { + T_NUMBER = 258, + T_ID = 259, + T_SELID = 260, + T_AND = 261, + T_OR = 262, + T_NOT = 263, + T_RESN = 264, + T_RESI = 265, + T_SYMBOL = 266, + T_NAME = 267, + T_CHAIN = 268, + T_MINUS = 269, + ATOM = 270 + }; +#endif + +/* Value type. */ +#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED + +union YYSTYPE +{ +#line 30 "parser.y" /* yacc.c:1909 */ + + const char *value; + expression *expression; + +#line 86 "parser.h" /* yacc.c:1909 */ +}; + +typedef union YYSTYPE YYSTYPE; +# define YYSTYPE_IS_TRIVIAL 1 +# define YYSTYPE_IS_DECLARED 1 +#endif + + + +int freesasa_yyparse (expression **expression, freesasa_yyscan_t scanner); + +#endif /* !YY_FREESASA_YY_PARSER_H_INCLUDED */ diff --git a/.venv_haddock/include/site/python3.12/freesasa/pdb.c b/.venv_haddock/include/site/python3.12/freesasa/pdb.c new file mode 100644 index 0000000000000000000000000000000000000000..396ddc4d8cf23a0cfe6d07f55161c72f0a0d9874 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/pdb.c @@ -0,0 +1,432 @@ +#if HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +#include "freesasa_internal.h" +#include "pdb.h" + +/* len >= 6 */ +static inline int +pdb_line_check(const char *line, size_t len) +{ + assert(line); + if (len < 6) return FREESASA_FAIL; + if (strlen(line) < len) return FREESASA_FAIL; + if (strncmp("ATOM", line, 4) != 0 && + strncmp("HETATM", line, 6) != 0) { + return FREESASA_FAIL; + } + return FREESASA_SUCCESS; +} + +/** + Extracts a double from the line of maximum width characters, to + allow checking for empty fields (instead of just reading the first + float that comes along. + */ +static inline int +pdb_get_double(const char *line, size_t width, double *val) +{ + /* allow truncated lines */ + char buf[PDB_LINE_STRL]; + float tmp; + + if (strlen(line) < width) width = strlen(line); + + memcpy(buf, line, width); + buf[width] = '\0'; + + if (sscanf(buf, "%f", &tmp) == 1) { + *val = tmp; + return FREESASA_SUCCESS; + } + + return FREESASA_FAIL; +} + +int freesasa_pdb_get_models(FILE *pdb, + struct file_range **ranges) +{ + char line[PDB_MAX_LINE_STRL]; + int n = 0, n_end = 0, error = 0; + long last_pos = ftell(pdb); + struct file_range *it = NULL, *itb; + + assert(pdb != NULL); + + while (fgets(line, PDB_MAX_LINE_STRL, pdb) != NULL) { + if (strncmp("MODEL", line, 5) == 0) { + ++n; + itb = it; + it = realloc(it, sizeof(struct file_range) * n); + if (!it) { + free(itb); + error = mem_fail(); + break; + } + it[n - 1].begin = last_pos; + } + if (strncmp("ENDMDL", line, 6) == 0) { + ++n_end; + if (n != n_end) { + error = fail_msg("mismatch between MODEL and ENDMDL in input"); + break; + } + it[n - 1].end = ftell(pdb); + } + last_pos = ftell(pdb); + } + if (n == 0) { /* when there are no models, the whole file is the model */ + free(it); + it = NULL; + } + if (error == FREESASA_FAIL) { + free(it); + *ranges = NULL; + return FREESASA_FAIL; + } + *ranges = it; + return n; +} + +int freesasa_pdb_get_chains(FILE *pdb, + struct file_range model, + struct file_range **ranges, + int options) +{ + /* it is assumed that 'model' is valid for 'pdb' */ + + int n_chains = 0; + char line[PDB_MAX_LINE_STRL]; + struct file_range *chains = NULL, *chb; + char last_chain = '\0'; + long last_pos = model.begin; + + assert(pdb); + assert(ranges); + + *ranges = NULL; + + /* for each model, find file ranges for each chain, store them + in the dynamically growing array chains */ + fseek(pdb, model.begin, SEEK_SET); + while (fgets(line, PDB_MAX_LINE_STRL, pdb) != NULL && + ftell(pdb) < model.end) { + if (strncmp("ATOM", line, 4) == 0 || ((options & FREESASA_INCLUDE_HETATM) && + (strncmp("HETATM", line, 6) == 0))) { + char chain = freesasa_pdb_get_chain_label(line); + if (chain != last_chain) { + if (n_chains > 0) chains[n_chains - 1].end = last_pos; + ++n_chains; + chb = chains; + chains = realloc(chains, sizeof(struct file_range) * n_chains); + if (!chains) { + free(chb); + return mem_fail(); + } + chains[n_chains - 1].begin = last_pos; + last_chain = chain; + } + } + last_pos = ftell(pdb); + } + + if (n_chains > 0) { + chains[n_chains - 1].end = last_pos; + chains[0].begin = model.begin; /* preserve model info */ + *ranges = chains; + } else { + *ranges = NULL; + } + return n_chains; +} + +int freesasa_pdb_get_atom_name(char *name, + const char *line) +{ + assert(name); + assert(line); + if (pdb_line_check(line, PDB_ATOM_NAME_STRL + 12) == FREESASA_FAIL) { + name[0] = '\0'; + return FREESASA_FAIL; + } + strncpy(name, line + 12, PDB_ATOM_NAME_STRL); + name[PDB_ATOM_NAME_STRL] = '\0'; + return FREESASA_SUCCESS; +} + +int freesasa_pdb_get_res_name(char *name, + const char *line) +{ + assert(name); + assert(line); + if (pdb_line_check(line, PDB_ATOM_RES_NAME_STRL + 17) == FREESASA_FAIL) { + name[0] = '\0'; + return FREESASA_FAIL; + } + strncpy(name, line + 17, PDB_ATOM_RES_NAME_STRL); + name[PDB_ATOM_RES_NAME_STRL] = '\0'; + return FREESASA_SUCCESS; +} + +int freesasa_pdb_get_coord(double *xyz, + const char *line) +{ + int n_coord = 24; /* 54-30+1 */ + char coord_section[25]; + + assert(xyz); + assert(line); + + if (pdb_line_check(line, 54) == FREESASA_FAIL) { + return FREESASA_FAIL; + } + + strncpy(coord_section, line + 30, n_coord); + coord_section[n_coord] = '\0'; + + if (sscanf(coord_section, "%lf%lf%lf", &xyz[0], &xyz[1], &xyz[2]) != 3) { + return fail_msg("could not read coordinates from line '%s'", line); + } + + return FREESASA_SUCCESS; +} + +int freesasa_pdb_get_res_number(char *number, + const char *line) +{ + assert(number); + assert(line); + if (pdb_line_check(line, PDB_ATOM_RES_NUMBER_STRL + 22) == FREESASA_FAIL) { + number[0] = '\0'; + return FREESASA_FAIL; + } + strncpy(number, line + 22, PDB_ATOM_RES_NUMBER_STRL); + number[PDB_ATOM_RES_NUMBER_STRL] = '\0'; + return FREESASA_SUCCESS; +} +char freesasa_pdb_get_chain_label(const char *line) +{ + assert(line); + if (pdb_line_check(line, 21) == FREESASA_FAIL) return '\0'; + return line[21]; +} + +char freesasa_pdb_get_alt_coord_label(const char *line) +{ + assert(line); + if (pdb_line_check(line, 16) == FREESASA_FAIL) return '\0'; + return line[16]; +} + +int freesasa_pdb_get_symbol(char *symbol, + const char *line) +{ + assert(line); + if (pdb_line_check(line, 76 + PDB_ATOM_SYMBOL_STRL) == FREESASA_FAIL) { + symbol[0] = '\0'; + return FREESASA_FAIL; + } + strncpy(symbol, line + 76, 2); + symbol[2] = '\0'; + return FREESASA_SUCCESS; +} + +int freesasa_pdb_get_occupancy(double *occ, + const char *line) +{ + assert(line); + /* allow truncated lines */ + if (pdb_line_check(line, 55) == FREESASA_SUCCESS) + return pdb_get_double(line + 54, 6, occ); + return FREESASA_FAIL; +} + +int freesasa_pdb_get_bfactor(double *bfac, + const char *line) +{ + assert(line); + /* allow truncated lines */ + if (pdb_line_check(line, 61) == FREESASA_SUCCESS) + return pdb_get_double(line + 60, 6, bfac); + return FREESASA_FAIL; +} + +int freesasa_pdb_ishydrogen(const char *line) +{ + assert(line); + char symbol[PDB_ATOM_SYMBOL_STRL + 1]; + freesasa_pdb_get_symbol(symbol, line); + + if (pdb_line_check(line, 13) == FREESASA_FAIL) return FREESASA_FAIL; + + /* Check symbol first */ + if (strncmp(symbol, " H", 2) == 0) return 1; + if (strncmp(symbol, " D", 2) == 0) return 1; + /* If the symbol is not blank and not H or D */ + if (!(strncmp(symbol, " ", 2) == 0)) return 0; + + /* When symbol is missing */ + /* Cover elements such as Cd, Nd, Th, etc. ("CD ", "ND ") */ + if (!(line[12] == ' ' || (line[12] >= '1' && line[12] <= '9'))) return 0; + /* Hydrogen, atom name "H**" or " H**" */ + if (line[12] == 'H' || line[13] == 'H') return 1; + /* Deuterium */ + if (line[12] == 'D' || line[13] == 'D') return 1; + return 0; +} + +static int +write_pdb_impl(FILE *output, + freesasa_node *structure) +{ + char buf[PDB_LINE_STRL + 1], buf2[6]; + int model; + double radius; + const char *line = NULL; + freesasa_node *chain = NULL, *residue = NULL, *atom = NULL; + const freesasa_nodearea *area = NULL; + const char *last_res_name = NULL, *last_res_number = NULL, *last_chain = NULL; + + assert(freesasa_node_type(structure) == FREESASA_NODE_STRUCTURE); + + model = freesasa_node_structure_model(structure); + if (model > 0) + fprintf(output, "MODEL %4d\n", model); + else + fprintf(output, "MODEL 1\n"); + + chain = freesasa_node_children(structure); + + /* Write ATOM entries */ + while (chain) { + residue = freesasa_node_children(chain); + while (residue) { + atom = freesasa_node_children(residue); + while (atom) { + line = freesasa_node_atom_pdb_line(atom); + area = freesasa_node_area(atom); + radius = freesasa_node_atom_radius(atom); + + if (line == NULL) { + return fail_msg("PDB input not valid or not present"); + } + + strncpy(buf, line, PDB_LINE_STRL); + sprintf(&buf[54], "%6.2f%6.2f", radius, area->total); + fprintf(output, "%s\n", buf); + + atom = freesasa_node_next(atom); + } + last_res_name = freesasa_node_name(residue); + last_res_number = freesasa_node_residue_number(residue); + residue = freesasa_node_next(residue); + } + last_chain = freesasa_node_name(chain); + chain = freesasa_node_next(chain); + } + + /* Write TER and ENDMDL lines */ + strncpy(buf2, &buf[6], 5); + buf2[5] = '\0'; + fprintf(output, "TER %5d %4s %c%5s\nENDMDL\n", + atoi(buf2) + 1, last_res_name, last_chain[0], last_res_number); + + fflush(output); + if (ferror(output)) { + return fail_msg(strerror(errno)); + } + + return FREESASA_SUCCESS; +} + +int freesasa_write_pdb(FILE *output, + freesasa_node *root) +{ + freesasa_node *result = freesasa_node_children(root), *structure; + + assert(output); + assert(root); + assert(freesasa_node_type(root) == FREESASA_NODE_ROOT); + + fprintf(output, "REMARK 999 This PDB file was generated by %s.\n", freesasa_string); + fprintf(output, "REMARK 999 In the ATOM records temperature factors have been\n" + "REMARK 999 replaced by the SASA of the atom, and the occupancy\n" + "REMARK 999 by the radius used in the calculation.\n"); + + while (result) { + structure = freesasa_node_children(result); + while (structure) { + if (write_pdb_impl(output, structure) == FREESASA_FAIL) { + return fail_msg(""); + } + structure = freesasa_node_next(structure); + } + result = freesasa_node_next(result); + } + + return FREESASA_SUCCESS; +} + +#if USE_CHECK +#include +#include + +START_TEST(test_pdb) +{ + double v; + ck_assert(pdb_line_check("", 6) == FREESASA_FAIL); + ck_assert(pdb_line_check("ATOM", 4) == FREESASA_FAIL); + ck_assert(pdb_line_check("ATOM", 6) == FREESASA_FAIL); + ck_assert(pdb_line_check("HETAT", 6) == FREESASA_FAIL); + ck_assert(pdb_line_check("HETAT ", 6) == FREESASA_FAIL); + ck_assert(pdb_line_check("BLA BLA BLA", 10) == FREESASA_FAIL); + ck_assert(pdb_line_check("BLA BLA BLA", 11) == FREESASA_FAIL); + ck_assert(pdb_line_check("BLA BLA BLA", 12) == FREESASA_FAIL); + + /* these will pass, although they would be useless */ + ck_assert(pdb_line_check("ATOM ", 6) == FREESASA_SUCCESS); + ck_assert(pdb_line_check("HETATM", 6) == FREESASA_SUCCESS); + + /* a more likely type of error */ + ck_assert(pdb_line_check("HETATM", 7) == FREESASA_FAIL); + + /* The normal case */ + ck_assert(pdb_line_check("ATOM 1 N MET A 1 27.340 " + "24.430 2.614 1.00 9.67 N ", + 80) == FREESASA_SUCCESS); + + v = 0; + ck_assert(pdb_get_double("1.23", 4, &v) == FREESASA_SUCCESS); + ck_assert(fabs(1.23 - v) < 1e-5); + v = 0; + ck_assert(pdb_get_double(" 1.23", 5, &v) == FREESASA_SUCCESS); + ck_assert(fabs(1.23 - v) < 1e-5); + v = 0; + ck_assert(pdb_get_double("1.23", 10, &v) == FREESASA_SUCCESS); + ck_assert(fabs(1.23 - v) < 1e-5); + v = 0; + ck_assert(pdb_get_double("1.23 4.56", 10, &v) == FREESASA_SUCCESS); + ck_assert(fabs(1.23 - v) < 1e-5); + + ck_assert(pdb_get_double(" ", 10, &v) == FREESASA_FAIL); + ck_assert(pdb_get_double(" 1.23", 4, &v) == FREESASA_FAIL); + ck_assert(pdb_get_double("abc", 10, &v) == FREESASA_FAIL); + ck_assert(pdb_get_double("a 1.23", 6, &v) == FREESASA_FAIL); +} +END_TEST + +TCase * +test_pdb_static() +{ + TCase *tc = tcase_create("pdb.c static"); + tcase_add_test(tc, test_pdb); + + return tc; +} + +#endif /* USE_CHECK */ diff --git a/.venv_haddock/include/site/python3.12/freesasa/pdb.h b/.venv_haddock/include/site/python3.12/freesasa/pdb.h new file mode 100644 index 0000000000000000000000000000000000000000..34732c773021c769b202a8b785789cc4dc332453 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/pdb.h @@ -0,0 +1,187 @@ +#ifndef FREESASA_PDB_H +#define FREESASA_PDB_H + +#include "freesasa.h" +#include "freesasa_internal.h" + +/** + @file + @author Simon Mitternacht + + The following functions all extract info from the PDB lines `ATOM` + and `HETATM`. Valid lines have to begin with either `ATOM` or + `HETATM` and be sufficiently long to contain the value in + question. +*/ + +#define PDB_ATOM_NAME_STRL 4 /**< Length of strings with atom names, such as `" CA "`. */ +#define PDB_ATOM_RES_NAME_STRL 3 /**< Length of string with residue names, such as `"ALA"`. */ +#define PDB_ATOM_RES_NUMBER_STRL 5 /**< Length of string with residue number, such as `" 123"`. */ +#define PDB_ATOM_SYMBOL_STRL 2 /**< Length for string with element symbol, such "FE". */ +#define PDB_LINE_STRL 80 /**< Length of a line in PDB file. */ +#define PDB_MAX_LINE_STRL 120 /**< for reading, allows nonstandard input with extra fields. */ + +/** + Finds the location of all MODEL entries in the file pdb, returns + the number of models found. + + The array *ranges will be dynamically allocated to contain a + file ranges for each model. + + @return Returns 0 if no MODEL lines were found (for example an + X-ray structure with only one model) and sets *ranges to + NULL. A return value of 0 doesn't have to mean the file is + empty. ::FREESASA_FAIL if malloc-failure. + */ +int freesasa_pdb_get_models(FILE *pdb, + struct file_range **ranges); + +/** + Finds the location of all chains within the file range 'model'. + + @param pdb The pdb-file + @param model The ::file_range to search for chains within. + @param ranges The address to a dynamically allocated array + containing the ::file_range of each chain will be stored here. + @param options Bitfield, can be used to set + ::FREESASA_INCLUDE_HETATM. + @return Number of chains found. Returns ::FREESASA_FAIL if memory + allocation fails. + */ +int freesasa_pdb_get_chains(FILE *pdb, + struct file_range model, + struct file_range **ranges, + int options); +/** + Get atom name from a PDB line. + + Extracts the whole atom name field from an `ATOM` or `HETATM` PDB + line, including padding, i.e. a string of ::PDB_ATOM_NAME_STRL + characters. For example `" CA "` for a regular C-alpha. If the + line is invalid, the name will be an empty string and the function + returns ::FREESASA_FAIL. + + @param name The name is written to this string. + @param line Line from a PDB file. + @return ::FREESASA_SUCCESS if input is readable, else ::FREESASA_FAIL. + */ +int freesasa_pdb_get_atom_name(char *name, + const char *line); + +/** + Get residue name from a PDB line. + + Extracts the whole residue name from an `ATOM` or `HETATM` PDB + line, i.e. a string of ::PDB_ATOM_RES_NAME_STRL characters. For + example `"ALA"` for an Alanine. If theline is invalid, the name + will be an empty string and the function returns ::FREESASA_FAIL. + + @param name The name is written to this string. + @param line Line from a PDB file. + @return ::FREESASA_SUCCESS if input is readable, else ::FREESASA_FAIL. + */ +int freesasa_pdb_get_res_name(char *name, + const char *line); + +/** + Get atom coordinates from a PDB line. + + Extracts x-, y- and z-coordinates from an `ATOM` or `HETATM` PDB + line. If the line is invalid, the function returns ::FREESASA_FAIL + and coord will remain unchanged. + + @param coord The coordiantes are written to this array as x,y,z. + @param line Line from a PDB file. + @return ::FREESASA_SUCCESS if input is readable, else ::FREESASA_FAIL. + */ +int freesasa_pdb_get_coord(double *coord, + const char *line); + +/** + Get residue number from a PDB line. + + Extracts residue number (ResSeq) as a string from an `ATOM` or + `HETATM` PDB line as a string. String format is used because not + all residue-numbers are numbers. The string should have length + ::PDB_ATOM_RES_NUMBER_STRL. If the line is invalid, the number will be an + empty string and the function returns ::FREESASA_FAIL. + + @param number The residue number will be saved to this string. + @param line Line from a PDB file. + @return ::FREESASA_SUCCESS if input is readable, else ::FREESASA_FAIL. + */ +int freesasa_pdb_get_res_number(char *number, + const char *line); + +/** + Get chain label from PDB line. + + Extracts the one character chain label (Chain identifier) from an + `ATOM` or `HETATM` PDB line (i.e. `'A'`, `'B'`, `'C'`, ...) + + @param line Line from a PDB file. + @return The chain label. If the line is invalid, the function + returns '\0'. + */ +char freesasa_pdb_get_chain_label(const char *line); + +/** + Get alternate coordinate label from PDB line. + + If there is more than one set of coordinates for an atom there + will be a label 'A', 'B', etc (Alternate location indicator). Else + the label is ' '. + + @param line Line from a PDB file. + @return The label. If line is invalid, the function returns + '\0'. + */ +char freesasa_pdb_get_alt_coord_label(const char *line); + +/** + Get element symbol from PDB line. + + Writes padded string to argument symbol, i.e. " C", "SE", etc. + + @param symbol The symbol will be written to this string. + @param line Line from a PDB file. + @return ::FREESASA_SUCCESS line has 78 or more characters. ::FREESASA_FAIL if + line too short. Does not check if symbol is valid. + */ +int freesasa_pdb_get_symbol(char *symbol, + const char *line); + +/** + Get occupancy from PDB line + + @param occ The occupancy will be written to this location. + @param line Line from a PDB file + + @return ::FREESASA_SUCCESS if line is long enough, starts with + ATOM or HETATM, and characters 55-60 contain a number. + */ +int freesasa_pdb_get_occupancy(double *occ, + const char *line); +/** + Get temperature factor (B-factor) from PDB line + + @param bfac The B-factor will be written to this location. + @param line Line from a PDB file + @return ::FREESASA_SUCCESS if line is long enough, starts with + ATOM or HETATM, and characters 61-66 contain a number. + */ +int freesasa_pdb_get_bfactor(double *bfac, + const char *line); + +/** + Is atom Hydrogen? + + Checks if an atom from an `ATOM` or `HETATM` PDB line is Hydrogen. + + @param line Line from a PDB file. + @return 1 if Hydrogen (or deuterium). 0 otherwise. If line is + invalid, the function returns ::FREESASA_FAIL. + */ +int freesasa_pdb_ishydrogen(const char *line); + +#endif /* FREESASA_PDB_H */ diff --git a/.venv_haddock/include/site/python3.12/freesasa/rsa.c b/.venv_haddock/include/site/python3.12/freesasa/rsa.c new file mode 100644 index 0000000000000000000000000000000000000000..9b9ba8fec357f7cf4a32c7944c96d494fc6ab9e1 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/rsa.c @@ -0,0 +1,174 @@ +#if HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include + +#include "classifier.h" +#include "freesasa_internal.h" +#include "pdb.h" + +void freesasa_residue_rel_nodearea(freesasa_nodearea *rel, + const freesasa_nodearea *abs, + const freesasa_nodearea *ref) +{ + rel->total = 100. * abs->total / ref->total; + rel->side_chain = 100. * abs->side_chain / ref->side_chain; + rel->main_chain = 100. * abs->main_chain / ref->main_chain; + rel->polar = 100. * abs->polar / ref->polar; + rel->apolar = 100. * abs->apolar / ref->apolar; + rel->name = abs->name; +} + +static void +rsa_print_header(FILE *output, + const char *config_name, + const char *protein_name, + const char *chains, + const freesasa_parameters *parameters, + int options) +{ + freesasa_algorithm alg = parameters->alg; +#ifdef PACKAGE_VERSION + fprintf(output, "REM FreeSASA " PACKAGE_VERSION "\n"); +#else + fprintf(output, "REM FreeSASA\n"); +#endif + fprintf(output, "REM Absolute and relative SASAs for %s\n", protein_name); + if (!(options & FREESASA_OUTPUT_SKIP_REL)) + fprintf(output, "REM Atomic radii and reference values for relative SASA: %s\n", config_name); + else + fprintf(output, "REM No reference values available to calculate relative SASA\n"); + fprintf(output, "REM Chains: %s\n", chains); + fprintf(output, "REM Algorithm: %s\n", freesasa_alg_name(alg)); + fprintf(output, "REM Probe-radius: %.2f\n", parameters->probe_radius); + if (alg == FREESASA_LEE_RICHARDS) { + fprintf(output, "REM Slices: %d\n", parameters->lee_richards_n_slices); + } else if (alg == FREESASA_SHRAKE_RUPLEY) { + fprintf(output, "REM Test-points: %d\n", parameters->shrake_rupley_n_points); + } + fprintf(output, "REM RES _ NUM All-atoms Total-Side Main-Chain Non-polar All polar\n"); + fprintf(output, "REM ABS REL ABS REL ABS REL ABS REL ABS REL\n"); +} + +static inline void +rsa_print_abs_rel(FILE *output, + double abs, + double rel) +{ + fprintf(output, "%7.2f", abs); + if (isfinite(rel)) + fprintf(output, "%6.1f", rel); + else + fprintf(output, " N/A"); +} + +static inline void +rsa_print_abs_only(FILE *output, + double abs) +{ + fprintf(output, "%7.2f", abs); + fprintf(output, " N/A"); +} + +static int +rsa_print_residue(FILE *output, + int iaa, + const freesasa_nodearea *abs, + const freesasa_nodearea *rel, + freesasa_node *residue) +{ + const char *resi_str; + char chain; + + resi_str = freesasa_node_residue_number(residue); + chain = freesasa_node_name(freesasa_node_parent(residue))[0]; + + fprintf(output, "RES %s %c%s ", abs->name, chain, resi_str); + if (rel->name != NULL) { + rsa_print_abs_rel(output, abs->total, rel->total); + rsa_print_abs_rel(output, abs->side_chain, rel->side_chain); + rsa_print_abs_rel(output, abs->main_chain, rel->main_chain); + rsa_print_abs_rel(output, abs->apolar, rel->apolar); + rsa_print_abs_rel(output, abs->polar, rel->polar); + } else { + rsa_print_abs_only(output, abs->total); + rsa_print_abs_only(output, abs->side_chain); + rsa_print_abs_only(output, abs->main_chain); + rsa_print_abs_only(output, abs->apolar); + rsa_print_abs_only(output, abs->polar); + } + fprintf(output, "\n"); + return FREESASA_SUCCESS; +} + +int freesasa_write_rsa(FILE *output, + freesasa_node *tree, + int options) +{ + freesasa_node *residue, *chain, *structure_node, *result_node; + const freesasa_nodearea *abs, *reference; + freesasa_nodearea rel; + int res_index, chain_index; + const freesasa_parameters *parameters; + + assert(output); + assert(tree); + + result_node = freesasa_node_children(tree); + parameters = freesasa_node_result_parameters(result_node); + structure_node = freesasa_node_children(result_node); + chain = freesasa_node_children(structure_node); + + rsa_print_header(output, freesasa_node_classified_by(result_node), + freesasa_node_name(result_node), freesasa_node_name(structure_node), parameters, options); + + res_index = chain_index = 0; + while (chain) { + residue = freesasa_node_children(chain); + while (residue) { + abs = freesasa_node_area(residue); + reference = freesasa_node_residue_reference(residue); + if (reference && !(options & FREESASA_OUTPUT_SKIP_REL)) { + freesasa_residue_rel_nodearea(&rel, abs, reference); + } else { + rel = freesasa_nodearea_null; + } + rsa_print_residue(output, res_index, abs, &rel, residue); + ++res_index; + residue = freesasa_node_next(residue); + } + chain = freesasa_node_next(chain); + } + + fprintf(output, "END Absolute sums over single chains surface\n"); + + chain = freesasa_node_children(structure_node); + chain_index = 0; + while (chain) { + const char *name = freesasa_node_name(chain); + abs = freesasa_node_area(chain); + + fprintf(output, "CHAIN%3d %c %10.1f %10.1f %10.1f %10.1f %10.1f\n", + chain_index + 1, name[0], abs->total, abs->side_chain, + abs->main_chain, abs->apolar, abs->polar); + + ++chain_index; + chain = freesasa_node_next(chain); + } + + abs = freesasa_node_area(structure_node); + fprintf(output, "END Absolute sums over all chains\n"); + fprintf(output, "TOTAL %10.1f %10.1f %10.1f %10.1f %10.1f\n", + abs->total, abs->side_chain, abs->main_chain, abs->apolar, abs->polar); + + fflush(output); + if (ferror(output)) { + return fail_msg(strerror(errno)); + } + + return FREESASA_SUCCESS; +} diff --git a/.venv_haddock/include/site/python3.12/freesasa/sasa_lr.c b/.venv_haddock/include/site/python3.12/freesasa/sasa_lr.c new file mode 100644 index 0000000000000000000000000000000000000000..7f693b138ac1ac9e6dd13fbe8a996dc337348fa2 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/sasa_lr.c @@ -0,0 +1,487 @@ +#if HAVE_CONFIG_H +#include +#endif +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +#define _USE_MATH_DEFINES +#endif +#include + +#if USE_THREADS +#include +#define MAX_LR_THREADS 16 +#else +#define MAX_LR_THREADS 1 +#endif + +#include "freesasa_internal.h" +#include "nb.h" + +const double TWOPI = 2 * M_PI; + +/* calculation parameters and data (results stored in *sasa) */ +typedef struct { + int n_atoms; + double *radii; /* including probe */ + const coord_t *xyz; + nb_list *adj; + int n_slices_per_atom; + double *sasa; /* results */ + double *arc[MAX_LR_THREADS], *z_nb[MAX_LR_THREADS], *R_nb[MAX_LR_THREADS]; + int n_threads; +} lr_data; + +typedef struct { + int first_atom; + int last_atom; + int thread_id; + lr_data *lr; +} lr_thread_interval; + +#if USE_THREADS +static int lr_do_threads(int n_threads, lr_data *); +static void *lr_thread(void *arg); +#endif + +/** Returns the are of atom i */ +static double +atom_area(lr_data *lr, int i, int thread_id); + +/** Sum of exposed arcs based on buried arc intervals arc, assumes no + intervals cross zero */ +static double +exposed_arc_length(double *restrict arc, int n); + +/** Release contenst of lr_data pointer*/ +static void +release_lr(lr_data *lr) +{ + int i; + + free(lr->radii); + freesasa_nb_free(lr->adj); + lr->radii = NULL; + lr->adj = NULL; + + for (i = 0; i < lr->n_threads; ++i) { + free(lr->arc[i]); + free(lr->z_nb[i]); + free(lr->R_nb[i]); + } +} + +/* Allocate some helper arrays in area calculation that need to be pre-allocated */ +static int +alloc_lr_calc_arrays(lr_data *lr, int n_threads) +{ + int max_nni = 0, i, nni; + const int n_atoms = lr->n_atoms; + + for (i = 0; i < n_atoms; ++i) { + nni = lr->adj->nn[i]; + max_nni = max_nni < nni ? nni : max_nni; + } + + for (i = 0; i < n_threads; ++i) { + lr->arc[i] = malloc(sizeof(double) * 4 * max_nni); + lr->z_nb[i] = malloc(sizeof(double) * max_nni); + lr->R_nb[i] = malloc(sizeof(double) * max_nni); + + if (!lr->arc[i] || !lr->z_nb[i] || !lr->R_nb[i]) { + return mem_fail(); + } + } + + return FREESASA_SUCCESS; +} + +/** Initialize object to be used for L&R calculation */ +static int +init_lr(lr_data *lr, + double *sasa, + const coord_t *xyz, + const double *atom_radii, + double probe_radius, + int n_slices_per_atom, + int n_threads) +{ + const int n_atoms = freesasa_coord_n(xyz); + int i; + + lr->n_atoms = n_atoms; + lr->xyz = xyz; + lr->adj = NULL; + lr->n_slices_per_atom = n_slices_per_atom; + lr->sasa = sasa; + lr->n_threads = n_threads; + + for (i = 0; i < n_threads; ++i) { + lr->arc[i] = NULL; + lr->z_nb[i] = NULL; + lr->R_nb[i] = NULL; + } + + lr->radii = malloc(sizeof(double) * n_atoms); + if (lr->radii == NULL) { + return mem_fail(); + } + + /* init some arrays */ + for (i = 0; i < n_atoms; ++i) { + lr->radii[i] = atom_radii[i] + probe_radius; + sasa[i] = 0.; + } + + /* determine which atoms are neighbours */ + lr->adj = freesasa_nb_new(xyz, lr->radii); + + if (lr->adj == NULL) { + release_lr(lr); + return fail_msg(""); + } + + if (alloc_lr_calc_arrays(lr, n_threads)) { + release_lr(lr); + return fail_msg(""); + } + + return FREESASA_SUCCESS; +} + +int freesasa_lee_richards(double *sasa, + const coord_t *xyz, + const double *atom_radii, + const freesasa_parameters *param) +{ + int return_value, n_atoms, n_threads, resolution, i; + double probe_radius; + lr_data lr; + + assert(sasa); + assert(xyz); + assert(atom_radii); + + if (param == NULL) param = &freesasa_default_parameters; + + return_value = FREESASA_SUCCESS; + n_atoms = freesasa_coord_n(xyz); + n_threads = param->n_threads; + resolution = param->lee_richards_n_slices; + probe_radius = param->probe_radius; + + if (n_threads > MAX_LR_THREADS) { + return fail_msg("L&R does not support more than %d threads", MAX_LR_THREADS); + } + + if (resolution <= 0) { + return fail_msg("%f slices per atom invalid resolution in L&R, must be > 0\n", resolution); + } + + if (n_atoms == 0) { + return freesasa_warn("in %s(): empty coordinates", __func__); + } + + if (n_threads > n_atoms) { + n_threads = n_atoms; + freesasa_warn("no sense in having more threads than atoms, only using %d threads", + n_threads); + } + + if (init_lr(&lr, sasa, xyz, atom_radii, probe_radius, resolution, n_threads)) + return FREESASA_FAIL; + + if (n_threads > 1) { +#if USE_THREADS + return_value = lr_do_threads(n_threads, &lr); +#else + return_value = freesasa_warn("in %s(): program compiled for single-threaded use, " + "but multiple threads were requested, will " + "proceed in single-threaded mode\n", + __func__); + n_threads = 1; +#endif /* pthread */ + } + if (n_threads == 1) { + for (i = 0; i < lr.n_atoms; ++i) { + lr.sasa[i] = atom_area(&lr, i, 0); + } + } + release_lr(&lr); + return return_value; +} + +#if USE_THREADS +static int +lr_do_threads(int n_threads, + lr_data *lr) +{ + pthread_t thread[MAX_LR_THREADS]; + lr_thread_interval t_data[MAX_LR_THREADS]; + int n_perthread = lr->n_atoms / n_threads, res; + int threads_created = 0, return_value = FREESASA_SUCCESS; + int t; + + for (t = 0; t < n_threads; ++t) { + t_data[t].first_atom = t * n_perthread; + if (t == n_threads - 1) { + t_data[t].last_atom = lr->n_atoms - 1; + } else { + t_data[t].last_atom = (t + 1) * n_perthread - 1; + } + t_data[t].lr = lr; + t_data[t].thread_id = t; + res = pthread_create(&thread[t], NULL, lr_thread, + (void *)&t_data[t]); + if (res) { + return_value = fail_msg(freesasa_thread_error(res)); + break; + } + ++threads_created; + } + for (int t = 0; t < threads_created; ++t) { + res = pthread_join(thread[t], NULL); + if (res) { + return_value = fail_msg(freesasa_thread_error(res)); + } + } + return return_value; +} + +static void * +lr_thread(void *arg) +{ + int i; + lr_thread_interval *ti = ((lr_thread_interval *)arg); + + for (i = ti->first_atom; i <= ti->last_atom; ++i) { + /* the different threads write to different parts of the + array, so locking shouldn't be necessary */ + ti->lr->sasa[i] = atom_area(ti->lr, i, ti->thread_id); + } + pthread_exit(NULL); +} +#endif /* USE_THREADS */ + +static double +atom_area(lr_data *lr, + int i, + int thread_id) +{ + /* This function is large because a large number of pre-calculated + arrays need to be accessed efficiently. Partially dereferenced + here to make access more efficient. + + Variables are named according to the documentation (see page + "Geometry of Lee & Richards' algorithm") */ + + const int nni = lr->adj->nn[i]; + const double *restrict const v = freesasa_coord_all(lr->xyz); + const double *restrict const R = lr->radii; + const int *restrict const nbi = lr->adj->nb[i]; + const double *restrict const xydi = lr->adj->xyd[i]; + const double *restrict const xdi = lr->adj->xd[i]; + const double *restrict const ydi = lr->adj->yd[i]; + const double zi = v[3 * i + 2], Ri = R[i]; + const int ns = lr->n_slices_per_atom; + + int j, islice, n_arcs, is_buried, narc2; + double *arc = lr->arc[thread_id], + *z_nb = lr->z_nb[thread_id], + *R_nb = lr->R_nb[thread_id]; + double z, delta, sasa = 0, alpha, beta, inf, sup; + double zj, di, dj, dij, Rj, Ri_prime2, Ri_prime, Rj_prime2, Rj_prime; + + for (j = 0; j < nni; ++j) { + z_nb[j] = v[3 * nbi[j] + 2]; + R_nb[j] = R[nbi[j]]; + } + + delta = 2 * Ri / ns; + z = zi - Ri - 0.5 * delta; + for (islice = 0; islice < ns; ++islice) { + z += delta; + di = fabs(zi - z); + Ri_prime2 = Ri * Ri - di * di; + if (Ri_prime2 < 0) continue; /* handle round-off errors */ + Ri_prime = sqrt(Ri_prime2); + if (Ri_prime <= 0) continue; /* more round-off errors */ + n_arcs = 0; + is_buried = 0; + for (j = 0; j < nni; ++j) { + zj = z_nb[j]; + dj = fabs(zj - z); + Rj = R_nb[j]; + + if (dj < Rj) { + Rj_prime2 = Rj * Rj - dj * dj; + Rj_prime = sqrt(Rj_prime2); + dij = xydi[j]; + if (dij >= Ri_prime + Rj_prime) { /* atoms aren't in contact */ + continue; + } + if (dij + Ri_prime < Rj_prime) { /* circle i is completely inside j */ + is_buried = 1; + break; + } + if (dij + Rj_prime < Ri_prime) { /* circle j is completely inside i */ + continue; + } + /* arc of circle i intersected by circle j */ + alpha = acos((Ri_prime2 + dij * dij - Rj_prime2) / (2.0 * Ri_prime * dij)); + /* position of mid-point of intersection along circle i */ + beta = atan2(ydi[j], xdi[j]) + M_PI; + inf = beta - alpha; + sup = beta + alpha; + if (inf < 0) inf += TWOPI; + if (sup > 2 * M_PI) sup -= TWOPI; + narc2 = 2 * n_arcs; + /* store the arc, if arc passes 2*PI split into two */ + if (sup < inf) { + /* store arcs as contiguous pairs of angles */ + arc[narc2] = 0; + arc[narc2 + 1] = sup; + /* second arc */ + arc[narc2 + 2] = inf; + arc[narc2 + 3] = TWOPI; + n_arcs += 2; + } else { + arc[narc2] = inf; + arc[narc2 + 1] = sup; + ++n_arcs; + } + } + } + if (is_buried == 0) { + sasa += delta * Ri * exposed_arc_length(arc, n_arcs); + } + } + return sasa; +} + +/* insertion sort (faster than qsort for these short lists) */ +inline static void +sort_arcs(double *restrict arc, + int n) +{ + double tmp[2]; + double *end = arc + 2 * n, *arcj, *arci; + for (arci = arc + 2; arci < end; arci += 2) { + *tmp = *arci; + *(tmp + 1) = *(arci + 1); + arcj = arci; + while (arcj > arc && *(arcj - 2) > tmp[0]) { + *arcj = *(arcj - 2); + *(arcj + 1) = *(arcj - 1); + arcj -= 2; + } + *arcj = *tmp; + *(arcj + 1) = *(tmp + 1); + } +} + +/* sort arcs by start-point, loop through them to sum parts of circle + not covered by any of the arcs */ +inline static double +exposed_arc_length(double *restrict arc, + int n) +{ + int i2; + double sum, sup, tmp; + + if (n == 0) return TWOPI; + + sort_arcs(arc, n); + sum = arc[0]; + sup = arc[1]; + /* in the following it is assumed that the arc[i2] <= arc[i2+1] */ + for (i2 = 2; i2 < 2 * n; i2 += 2) { + if (sup < arc[i2]) sum += arc[i2] - sup; + tmp = arc[i2 + 1]; + if (tmp > sup) sup = tmp; + } + return sum + TWOPI - sup; +} + +#if USE_CHECK +#include + +static int +is_identical(const double *l1, const double *l2, int n) +{ + int i; + + for (i = 0; i < n; ++i) { + if (l1[i] != l2[i]) return 0; + } + + return 1; +} + +static int +is_sorted(const double *list, int n) +{ + int i; + + for (i = 0; i < n - 1; ++i) + if (list[2 * i] > list[2 * i + 1]) return 0; + + return 1; +} + +START_TEST(test_sort_arcs) +{ + double a_ref[] = {0, 1, 2, 3}, b_ref[] = {-2, 0, -1, 0, -1, 1}; + double a1[4] = {0, 1, 2, 3}, a2[4] = {2, 3, 0, 1}; + double b1[6] = {-2, 0, -1, 0, -1, 1}, b2[6] = {-1, 1, -2, 0, -1, 1}; + sort_arcs(a1, 2); + sort_arcs(a2, 2); + sort_arcs(b1, 3); + sort_arcs(b2, 3); + ck_assert(is_sorted(a1, 2)); + ck_assert(is_sorted(a2, 2)); + ck_assert(is_sorted(b1, 3)); + ck_assert(is_sorted(b2, 3)); + ck_assert(is_identical(a_ref, a1, 4)); + ck_assert(is_identical(a_ref, a2, 4)); + ck_assert(is_identical(b_ref, b1, 6)); +} +END_TEST + +START_TEST(test_exposed_arc_length) +{ + double a1[4] = {0, 0.1 * TWOPI, 0.9 * TWOPI, TWOPI}, a2[4] = {0.9 * TWOPI, TWOPI, 0, 0.1 * TWOPI}; + double a3[4] = {0, TWOPI, 1, 2}, a4[4] = {1, 2, 0, TWOPI}; + double a5[4] = {0.1 * TWOPI, 0.2 * TWOPI, 0.5 * TWOPI, 0.6 * TWOPI}; + double a6[4] = {0.1 * TWOPI, 0.2 * TWOPI, 0.5 * TWOPI, 0.6 * TWOPI}; + double a7[4] = {0.1 * TWOPI, 0.3 * TWOPI, 0.15 * TWOPI, 0.2 * TWOPI}; + double a8[4] = {0.15 * TWOPI, 0.2 * TWOPI, 0.1 * TWOPI, 0.3 * TWOPI}; + double a9[10] = {0.05, 0.1, 0.5, 0.6, 0, 0.15, 0.7, 0.8, 0.75, TWOPI}; + ck_assert(fabs(exposed_arc_length(a1, 2) - 0.8 * TWOPI) < 1e-10); + ck_assert(fabs(exposed_arc_length(a2, 2) - 0.8 * TWOPI) < 1e-10); + ck_assert(fabs(exposed_arc_length(a3, 2)) < 1e-10); + ck_assert(fabs(exposed_arc_length(a4, 2)) < 1e-10); + ck_assert(fabs(exposed_arc_length(a5, 2) - 0.8 * TWOPI) < 1e-10); + ck_assert(fabs(exposed_arc_length(a6, 2) - 0.8 * TWOPI) < 1e-10); + ck_assert(fabs(exposed_arc_length(a7, 2) - 0.8 * TWOPI) < 1e-10); + ck_assert(fabs(exposed_arc_length(a8, 2) - 0.8 * TWOPI) < 1e-10); + ck_assert(fabs(exposed_arc_length(a9, 5) - 0.45) < 1e-10); + /* can't think of anything more qualitatively different here */ +} +END_TEST + +TCase * +test_LR_static() +{ + TCase *tc = tcase_create("sasa_lr.c static"); + tcase_add_test(tc, test_sort_arcs); + tcase_add_test(tc, test_exposed_arc_length); + + return tc; +} + +#endif /* USE_CHECK */ diff --git a/.venv_haddock/include/site/python3.12/freesasa/sasa_sr.c b/.venv_haddock/include/site/python3.12/freesasa/sasa_sr.c new file mode 100644 index 0000000000000000000000000000000000000000..dcd177179844afd4b17d323f9e99a50ec061e071 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/sasa_sr.c @@ -0,0 +1,338 @@ +#if HAVE_CONFIG_H +#include +#endif +#include +#include +#include +#include + +#ifdef _MSC_VER +#define _USE_MATH_DEFINES +#endif +#include + +#if USE_THREADS +#include +#define MAX_SR_THREADS 16 +#else +#define MAX_SR_THREADS 1 +#endif + +#include "freesasa_internal.h" +#include "nb.h" + +#ifdef __GNUC__ +#define __attrib_pure__ __attribute__((pure)) +#else +#define __attrib_pure__ +#endif + +/* calculation parameters (results stored in *sasa) */ +typedef struct { + int i1, i2; /* for multithreading, range of atoms */ + int thread_index; + int n_atoms; + int n_points; + int n_threads; + double probe_radius; + const coord_t *xyz; + coord_t *srp; /* test-points */ + coord_t *tp_local[MAX_SR_THREADS]; /* coord object for storing intermediates */ + int *spcount[MAX_SR_THREADS]; + double *r; + double *r2; + nb_list *nb; + double *sasa; +} sr_data; + +#if USE_THREADS +static int sr_do_threads(int n_threads, sr_data *sr); +static void *sr_thread(void *arg); +#endif + +static double +sr_atom_area(int i, const sr_data *sr, int thread_index) __attrib_pure__; + +static coord_t * +test_points(int N) +{ + /* Golden section spiral on a sphere + from http://web.archive.org/web/20120421191837/http://www.cgafaq.info/wiki/Evenly_distributed_points_on_sphere */ + double dlong = M_PI * (3 - sqrt(5)), dz = 2.0 / N, longitude = 0, z = 1 - dz / 2, r; + coord_t *coord = freesasa_coord_new(); + double *tp = malloc(3 * N * sizeof(double)), *p; + if (tp == NULL || coord == NULL) { + mem_fail(); + goto cleanup; + } + + for (p = tp; p - tp < 3 * N; p += 3) { + r = sqrt(1 - z * z); + p[0] = cos(longitude) * r; + p[1] = sin(longitude) * r; + p[2] = z; + z -= dz; + longitude += dlong; + } + + if (freesasa_coord_append(coord, tp, N) == FREESASA_FAIL) { + fail_msg(""); + goto cleanup; + } + free(tp); + + return coord; + +cleanup: + free(tp); + freesasa_coord_free(coord); + return NULL; +} + +/* free contents */ +void release_sr(sr_data *sr) +{ + int i; + + freesasa_coord_free(sr->srp); + freesasa_nb_free(sr->nb); + free(sr->r); + free(sr->r2); + + for (i = 0; i < sr->n_threads; ++i) { + freesasa_coord_free(sr->tp_local[i]); + free(sr->spcount[i]); + } +} + +int init_sr(sr_data *sr, + double *sasa, + const coord_t *xyz, + const double *r, + double probe_radius, + int n_points, + int n_threads) +{ + int n_atoms = freesasa_coord_n(xyz), i; + coord_t *srp = test_points(n_points); + double ri; + + if (srp == NULL) return fail_msg("failed to initialize test points"); + + /* store parameters and reference arrays */ + sr->n_atoms = n_atoms; + sr->n_points = n_points; + sr->n_threads = n_threads; + sr->probe_radius = probe_radius; + sr->xyz = xyz; + sr->srp = srp; + sr->sasa = sasa; + sr->nb = NULL; + + /* should be done before any mallocs (to avoid problems in potential cleanup) */ + for (i = 0; i < n_threads; ++i) { + sr->tp_local[i] = NULL; + sr->spcount[i] = NULL; + } + + sr->r = malloc(sizeof(double) * n_atoms); + sr->r2 = malloc(sizeof(double) * n_atoms); + + if (sr->r == NULL || sr->r2 == NULL) goto cleanup; + + for (i = 0; i < n_atoms; ++i) { + ri = r[i] + probe_radius; + sr->r[i] = ri; + sr->r2[i] = ri * ri; + } + + for (i = 0; i < n_threads; ++i) { + sr->tp_local[i] = freesasa_coord_clone(sr->srp); + sr->spcount[i] = malloc(sizeof(int) * n_points); + if (sr->tp_local[i] == NULL || sr->spcount[i] == NULL) { + goto cleanup; + } + } + + /* calculate distances */ + sr->nb = freesasa_nb_new(xyz, sr->r); + if (sr->nb == NULL) goto cleanup; + + return FREESASA_SUCCESS; + +cleanup: + release_sr(sr); + return mem_fail(); +} + +int freesasa_shrake_rupley(double *sasa, + const coord_t *xyz, + const double *r, + const freesasa_parameters *param) +{ + int i, n_atoms, n_threads = param->n_threads, resolution, return_value; + double probe_radius = param->probe_radius; + sr_data sr; + + assert(sasa); + assert(xyz); + assert(r); + + if (param == NULL) param = &freesasa_default_parameters; + + n_atoms = freesasa_coord_n(xyz); + n_threads = param->n_threads; + resolution = param->shrake_rupley_n_points; + return_value = FREESASA_SUCCESS; + + if (n_threads > MAX_SR_THREADS) { + return fail_msg("S&R does not support more than %d threads", MAX_SR_THREADS); + } + if (resolution <= 0) { + return fail_msg("%f test points invalid resolution in S&R, must be > 0\n", resolution); + } + if (n_atoms == 0) return freesasa_warn("in %s(): empty coordinates", __func__); + if (n_threads > n_atoms) { + n_threads = n_atoms; + freesasa_warn("no sense in having more threads than atoms, only using %d threads", + n_threads); + } + + if (init_sr(&sr, sasa, xyz, r, probe_radius, resolution, n_threads)) + return FREESASA_FAIL; + + /* calculate SASA */ + if (n_threads > 1) { +#if USE_THREADS + return_value = sr_do_threads(n_threads, &sr); +#else + return_value = freesasa_warn("in %s(): program compiled for single-threaded use, " + "but multiple threads were requested, will " + "proceed in single-threaded mode\n", + __func__); + n_threads = 1; +#endif + } + if (n_threads == 1) { + /* don't want the overhead of generating threads if only one is used */ + for (i = 0; i < n_atoms; ++i) { + sasa[i] = sr_atom_area(i, &sr, 0); + } + } + release_sr(&sr); + return return_value; +} + +#if USE_THREADS +static int +sr_do_threads(int n_threads, + sr_data *sr) +{ + pthread_t thread[MAX_SR_THREADS]; + sr_data srt[MAX_SR_THREADS]; + int thread_block_size = sr->n_atoms / n_threads; + int res, return_value = FREESASA_SUCCESS; + int threads_created = 0, t; + + /* divide atoms evenly over threads */ + for (t = 0; t < n_threads; ++t) { + srt[t] = *sr; + srt[t].i1 = t * thread_block_size; + if (t == n_threads - 1) + srt[t].i2 = sr->n_atoms; + else + srt[t].i2 = (t + 1) * thread_block_size; + srt[t].thread_index = t; + res = pthread_create(&thread[t], NULL, sr_thread, (void *)&srt[t]); + if (res) { + return_value = fail_msg(freesasa_thread_error(res)); + break; + } + ++threads_created; + } + for (t = 0; t < threads_created; ++t) { + res = pthread_join(thread[t], NULL); + if (res) { + return_value = fail_msg(freesasa_thread_error(res)); + } + } + return return_value; +} + +static void * +sr_thread(void *arg) +{ + int i; + sr_data *sr = ((sr_data *)arg); + + for (i = sr->i1; i < sr->i2; ++i) { + /* mutex should not be necessary, writes to non-overlapping regions */ + sr->sasa[i] = sr_atom_area(i, sr, sr->thread_index); + } + pthread_exit(NULL); +} +#endif + +static double +sr_atom_area(int i, + const sr_data *sr, + int thread_index) +{ + const int n_points = sr->n_points; + /* this array keeps track of which testpoints belonging to + a certain atom do not overlap with any other atoms */ + int *spcount = sr->spcount[thread_index]; + const int nni = sr->nb->nn[i]; + const int *restrict nbi = sr->nb->nb[i]; + const double ri = sr->r[i]; + const double *restrict r2 = sr->r2; + const double *restrict v = freesasa_coord_all(sr->xyz); + const double *restrict vi = v + 3 * i; + const double *restrict tp; + int n_surface = 0, current_nb, a, j, k; + double dx, dy, dz; + /* testpoints for this atom */ + coord_t *restrict tp_coord_ri = sr->tp_local[thread_index]; + + freesasa_coord_copy(tp_coord_ri, sr->srp); + freesasa_coord_scale(tp_coord_ri, ri); + freesasa_coord_translate(tp_coord_ri, vi); + tp = freesasa_coord_all(tp_coord_ri); + + /* initialize with all surface points hidden */ + memset(spcount, 0, n_points * sizeof(int)); + + /* Using the trick from NSOL to check points one by one for all + atoms, start comparing with the first neighbor. If there is no + overlap for a given test-point, try with other neighbors + instead. Would probably work even better if test points were + organized in patches and not spirals. */ + current_nb = 0; + for (j = 0; j < n_points; ++j) { + /* a is the index of the atom under consideration */ + a = nbi[current_nb]; + dx = tp[j * 3] - v[a * 3]; + dy = tp[j * 3 + 1] - v[a * 3 + 1]; + dz = tp[j * 3 + 2] - v[a * 3 + 2]; + if (dx * dx + dy * dy + dz * dz > r2[a]) { + k = 0; + for (; k < nni; ++k) { + a = nbi[k]; + dx = tp[j * 3] - v[a * 3]; + dy = tp[j * 3 + 1] - v[a * 3 + 1]; + dz = tp[j * 3 + 2] - v[a * 3 + 2]; + if (dx * dx + dy * dy + dz * dz <= r2[a]) { + current_nb = k; + break; + } + } + /* we have gone through the whole list without overlap */ + if (k == nni) spcount[j] = 1; + } + } + for (k = 0; k < n_points; ++k) { + if (spcount[k]) ++n_surface; + } + + return (4.0 * M_PI * ri * ri * n_surface) / n_points; +} diff --git a/.venv_haddock/include/site/python3.12/freesasa/selection.c b/.venv_haddock/include/site/python3.12/freesasa/selection.c new file mode 100644 index 0000000000000000000000000000000000000000..2e2833378b05d0633793882e5072678732151a9c --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/selection.c @@ -0,0 +1,1003 @@ +#if HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +#include "freesasa_internal.h" +#include "pdb.h" +#include "selection.h" + +#include "parser.h" + +#include "lexer.h" + +struct freesasa_selection { + char *name; + char *command; + double area; + int n_atoms; +}; + +struct selection { + const char *name; + int *atom; + int size; +}; + +static const char * +e_str(expression_type e) +{ + switch (e) { + case E_SELECTION: + return ""; + case E_SYMBOL: + return "symbol"; + case E_NAME: + return "name"; + case E_RESN: + return "resn"; + case E_RESI: + return "resi"; + case E_CHAIN: + return "chain"; + case E_ID: + return ""; + case E_NUMBER: + return ""; + case E_NEGNUM: + return ""; + case E_AND: + return "and"; + case E_OR: + return "or"; + case E_NOT: + return "not"; + case E_PLUS: + return "< + >"; + case E_RANGE: + return "< - >"; + case E_RANGE_OPEN_R: + return "< - R >"; + case E_RANGE_OPEN_L: + return "< - L >"; + } + return NULL; +} + +extern int freesasa_yyparse(expression **expression, yyscan_t scanner); + +static expression * +expression_new() +{ + struct expression *e = malloc(sizeof(expression)); + + if (e == NULL) + mem_fail(); + else { + e->type = E_SELECTION; + e->left = NULL; + e->right = NULL; + e->value = NULL; + } + return e; +} + +static void +expression_free(expression *expression) +{ + if (expression) { + expression_free(expression->left); + expression_free(expression->right); + free(expression->value); + free(expression); + } +} + +expression * +freesasa_selection_atom(expression_type type, + const char *val) +{ + expression *e = expression_new(); + int i, n; + char *buf; + + assert(val); + + if (e != NULL) { + if (type == E_NEGNUM) { + n = strlen(val) + 2; + buf = malloc(n); + if (buf == NULL) { + mem_fail(); + expression_free(e); + return NULL; + } + sprintf(buf, "-%s", val); + e->type = E_NUMBER; + e->value = strdup(buf); + free(buf); + } else { + e->type = type; + e->value = strdup(val); + } + + if (e->value == NULL) { + mem_fail(); + expression_free(e); + return NULL; + } + + for (i = 0; i < strlen(e->value); ++i) + e->value[i] = toupper(e->value[i]); + } + return e; +} + +expression * +freesasa_selection_create(expression *selection, + const char *id) +{ + expression *e = expression_new(); + + assert(id); + + if (e == NULL) + expression_free(selection); + else { + e->type = E_SELECTION; + e->left = selection; + e->value = strdup(id); + + if (e->value == NULL) { + mem_fail(); + expression_free(e); + e = NULL; + } + } + + return e; +} + +expression * +freesasa_selection_selector(expression_type type, + expression *list) +{ + expression *e = expression_new(); + + if (e == NULL) { + expression_free(list); + } else { + e->type = type; + e->left = list; + } + + return e; +} + +expression * +freesasa_selection_operation(expression_type type, + expression *left, + expression *right) +{ + expression *e = expression_new(); + + if (e == NULL) { + expression_free(left); + expression_free(right); + } else { + e->type = type; + e->left = left; + e->right = right; + } + + return e; +} + +/* for debugging */ +static void +print_expr(FILE *output, const expression *e, int level) +{ + int i; + fprintf(output, "\n"); + for (i = 0; i < level; ++i) + fprintf(output, " "); + + if (e == NULL) { + fprintf(output, "()"); + } else { + fprintf(output, "(%s ", e_str(e->type)); + if (e->value) fprintf(output, ": %s ", e->value); + print_expr(output, e->left, level + 1); + print_expr(output, e->right, level + 1); + fprintf(output, ")"); + } + fflush(output); +} + +static expression * +get_expression(const char *selector) +{ + freesasa_yyscan_t scanner; + YY_BUFFER_STATE state; + int err; + expression *expression = NULL; + + if (freesasa_yylex_init(&scanner)) { + fail_msg("lexer failed"); + } else { + state = freesasa_yy_scan_string(selector, scanner); + err = freesasa_yyparse(&expression, scanner); + if (err) { + if (err == 1) fail_msg("parser failed"); + if (err == 2) mem_fail(); + expression_free(expression); + expression = NULL; + } + freesasa_yy_delete_buffer(state, scanner); + freesasa_yylex_destroy(scanner); + } + + return expression; +} + +static struct selection * +selection_new(int n) +{ + struct selection *selection = malloc(sizeof(struct selection)); + int i; + + if (selection == NULL) { + mem_fail(); + } else { + selection->size = n; + selection->atom = malloc(sizeof(int) * n); + + if (selection->atom == NULL) { + free(selection); + mem_fail(); + selection = NULL; + } else { + for (i = 0; i < n; ++i) + selection->atom[i] = 0; + } + } + + return selection; +} + +static void +selection_free(struct selection *selection) +{ + if (selection) { + free(selection->atom); + free(selection); + } +} + +/* Looks for exact match between the atom-name and expr->value */ +static int +match_name(const freesasa_structure *structure, + const char *id, + int i) +{ + char atom[PDB_ATOM_NAME_STRL + 1]; + sscanf(freesasa_structure_atom_name(structure, i), "%s", atom); + if (strcmp(atom, id) == 0) + return 1; + return 0; +} + +/** Looks for match of strlen(expr->value) first characters of atom-name and expr->value */ +static int +match_symbol(const freesasa_structure *structure, + const char *id, + int i) +{ + char symbol[PDB_ATOM_SYMBOL_STRL + 1]; + sscanf(freesasa_structure_atom_symbol(structure, i), "%s", symbol); + if (strcmp(id, symbol) == 0) { + return 1; + } + return 0; +} + +static int +match_resn(const freesasa_structure *structure, + const char *id, + int i) +{ + char resn[PDB_ATOM_RES_NAME_STRL + 1]; + sscanf(freesasa_structure_atom_res_name(structure, i), "%s", resn); + if (strcmp(resn, id) == 0) + return 1; + return 0; +} + +static int +match_resi(const freesasa_structure *structure, + const char *id, + int i) +{ + char resi[PDB_ATOM_RES_NUMBER_STRL + 1]; + sscanf(freesasa_structure_atom_res_number(structure, i), "%s", resi); + if (strcmp(resi, id) == 0) + return 1; + return 0; +} + +static int +match_chain(const freesasa_structure *structure, + const char *id, + int i) +{ + return id[0] == freesasa_structure_atom_chain(structure, i); +} + +static void +select_id(expression_type parent_type, + struct selection *selection, + const freesasa_structure *structure, + const char *id) +{ + int count = 0, match, i; + + assert(id); + + for (i = 0; i < selection->size; ++i) { + match = 0; + switch (parent_type) { + case E_NAME: + match = match_name(structure, id, i); + break; + case E_SYMBOL: + match = match_symbol(structure, id, i); + break; + case E_RESN: + match = match_resn(structure, id, i); + break; + case E_RESI: + match = match_resi(structure, id, i); + break; + case E_CHAIN: + match = match_chain(structure, id, i); + break; + default: + assert(0); + break; + } + if (match) selection->atom[i] = 1; + count += match; + } + if (count == 0) freesasa_warn("Found no matches to %s '%s', typo?", + e_str(parent_type), id); +} + +static int +is_valid_id(int parent_type, + const expression *expr) +{ + int type, n, warn, i; + const char *val; + + assert(expr->type == E_NUMBER || expr->type == E_ID); + + type = expr->type; + val = expr->value; + + switch (parent_type) { + case E_NAME: + if (strlen(val) > PDB_ATOM_NAME_STRL) + return freesasa_warn("select: %s: atom name '%s' invalid (string too long), " + "will be ignored", + e_str(parent_type), val); + break; + case E_SYMBOL: + if (type != E_ID) + return freesasa_warn("select: %s: '%s' invalid (should be 1 or 2 letters, 'C', 'N', 'SE', etc), " + "will be ignored", + e_str(parent_type), val); + if (strlen(val) > 2) + return freesasa_warn("select: %s: '%s' invalid (element names have 1 or 2 characters), " + "will be ignored", + e_str(parent_type), val); + break; + case E_RESN: + if (strlen(val) > PDB_ATOM_RES_NAME_STRL) + return freesasa_warn("select: %s: '%s' invalid (string too long), " + "will be ignored", + e_str(parent_type), val); + break; + case E_RESI: + if (type == E_ID) { + /* these should have format 1, 2, 345, etc or 12A, 12B, etc. */ + n = strlen(val); + if (n > PDB_ATOM_RES_NUMBER_STRL) { + return freesasa_warn("select: %s: '%s' invalid (string too long), " + "will be ignored", + e_str(parent_type), val); + } else { + warn = 0; + if (n == 1) ++warn; + if (!warn && (toupper(val[n - 1]) < 'A' || toupper(val[n - 1]) > 'Z')) { + ++warn; + } + for (i = 0; !warn && i < n - 1; ++i) { + if (val[i] < '0' || val[i] > '9') { + ++warn; + } + } + if (warn) { + return freesasa_warn("select: %s: '%s' invalid, should either be " + "number (1, 2, 3) or number with insertion code (1A, 1B, ...), " + "will be ignored", + e_str(parent_type), val); + } + } + } else if (type != E_NUMBER) { + return freesasa_warn("select: %s: '%s' invalid, will be ignored", + e_str(parent_type), val); + } + break; + case E_CHAIN: + if (strlen(val) > 1) + return freesasa_warn("select: %s: '%s' invalid (string too long), " + "will be ignored", + e_str(parent_type), val); + break; + default: + assert(0); + break; + } + return FREESASA_SUCCESS; +} + +static int +select_range(expression_type range_type, + expression_type parent_type, + struct selection *selection, + const freesasa_structure *structure, + const expression *left, + const expression *right) +{ + int lower, upper, i, j; + + assert(range_type == E_RANGE || range_type == E_RANGE_OPEN_L || range_type == E_RANGE_OPEN_R); + assert(parent_type == E_RESI || parent_type == E_CHAIN); + + if (parent_type == E_RESI) { /* residues have integer numbering */ + if ((left && left->type != E_NUMBER) || + (right && right->type != E_NUMBER)) { + return freesasa_warn("select: %s: range '%s-%s' invalid, needs to be two numbers, " + "will be ignored", + e_str(parent_type), left->value, right->value); + } + } else { /* chains can be numbered by both letters (common) and numbers (uncommon) */ + if (left->type != right->type || + (left->type == E_ID && (strlen(left->value) > 1 || strlen(right->value) > 1))) + return freesasa_warn("select: %s: range '%s-%s' invalid, should be two letters (A-C) or numbers (1-5), " + "will be ignored", + e_str(parent_type), left->value, right->value); + } + if (range_type == E_RANGE_OPEN_L) { + lower = atoi(freesasa_structure_atom_res_number(structure, 0)); + upper = atoi(right->value); + } else if (range_type == E_RANGE_OPEN_R) { + lower = atoi(left->value); + upper = atoi(freesasa_structure_atom_res_number(structure, freesasa_structure_n(structure) - 1)); + } else if (left->type == E_NUMBER) { + lower = atoi(left->value); + upper = atoi(right->value); + } else { + lower = (int)left->value[0]; + upper = (int)right->value[0]; + } + for (i = 0; i < selection->size; ++i) { + if (parent_type == E_RESI) + j = atoi(freesasa_structure_atom_res_number(structure, i)); + else + j = (int)freesasa_structure_atom_chain(structure, i); + if (j >= lower && j <= upper) + selection->atom[i] = 1; + } + return FREESASA_SUCCESS; +} + +static int +select_list(expression_type parent_type, + struct selection *selection, + const freesasa_structure *structure, + const expression *expr) +{ + int resr, resl; + expression *left, *right; + + if (expr == NULL) + return fail_msg("NULL expression"); + + left = expr->left; + right = expr->right; + + switch (expr->type) { + case E_PLUS: + if (left == NULL || right == NULL) + return fail_msg("NULL expression"); + resl = select_list(parent_type, selection, structure, left); + resr = select_list(parent_type, selection, structure, right); + if (resl == FREESASA_WARN || resr == FREESASA_WARN) + return FREESASA_WARN; + break; + case E_RANGE: + if (left == NULL || right == NULL) + return fail_msg("NULL expression"); + return select_range(E_RANGE, parent_type, selection, structure, left, right); + case E_RANGE_OPEN_L: + if (left != NULL || right == NULL) + return fail_msg("NULL expression"); + return select_range(E_RANGE_OPEN_L, parent_type, selection, structure, left, right); + case E_RANGE_OPEN_R: + if (left == NULL || right != NULL) + return fail_msg("NULL expression"); + return select_range(E_RANGE_OPEN_R, parent_type, selection, structure, left, right); + case E_ID: + case E_NUMBER: + if (is_valid_id(parent_type, expr) == FREESASA_SUCCESS) + select_id(parent_type, selection, structure, expr->value); + else + return freesasa_warn("select: %s: '%s' invalid %s", + e_str(parent_type), expr->value, e_str(expr->type)); + break; + default: + return freesasa_fail("select: parse error (expression: '%s %s')", + e_str(parent_type), e_str(expr->type)); + } + return FREESASA_SUCCESS; +} + +static int +selection_join(struct selection *target, + const struct selection *s1, + const struct selection *s2, + int type) +{ + int n, i; + + if (s1 == NULL || s2 == NULL || target == NULL) + return fail_msg("trying to join NULL selections"); + + assert(s1->size == s2->size); + assert(s1->size == target->size); + + n = target->size; + + switch (type) { + case E_AND: + for (i = 0; i < n; ++i) + target->atom[i] = s1->atom[i] && s2->atom[i]; + break; + case E_OR: + for (i = 0; i < n; ++i) + target->atom[i] = s1->atom[i] || s2->atom[i]; + break; + default: + assert(0); + } + + return FREESASA_SUCCESS; +} + +static int +selection_not(struct selection *s) +{ + int i; + + if (s == NULL) return fail_msg("NULL selection"); + + for (i = 0; i < s->size; ++i) { + s->atom[i] = !s->atom[i]; + } + + return FREESASA_SUCCESS; +} + +/* Called recursively, the selection is built as we cover the expression tree */ +static int +select_atoms(struct selection *selection, + const expression *expr, + const freesasa_structure *structure) +{ + int warn = 0, err = 0, n, ret; + struct selection *sl, *sr; + + assert(selection); + assert(structure); + + n = selection->size; + + /* this should only happen if memory allocation failed during parsing */ + if (expr == NULL) return fail_msg("NULL expression"); + + switch (expr->type) { + case E_SELECTION: + assert(expr->value != NULL); + selection->name = expr->value; + return select_atoms(selection, expr->left, structure); + break; + case E_SYMBOL: + case E_NAME: + case E_RESN: + case E_RESI: + case E_CHAIN: + return select_list(expr->type, selection, structure, expr->left); + break; + case E_AND: + case E_OR: { + sl = selection_new(n); + sr = selection_new(n); + + if (sl != NULL && sr != NULL) { + if ((ret = select_atoms(sl, expr->left, structure))) { + if (ret == FREESASA_WARN) ++warn; + if (ret == FREESASA_FAIL) ++err; + } + if ((ret = select_atoms(sr, expr->right, structure))) { + if (ret == FREESASA_WARN) ++warn; + if (ret == FREESASA_FAIL) ++err; + } + selection_join(selection, sl, sr, expr->type); + } else { + ++err; + } + + selection_free(sl); + selection_free(sr); + + if (err) return fail_msg("error joining selections"); + break; + } + case E_NOT: { + ret = select_atoms(selection, expr->right, structure); + if (ret == FREESASA_WARN) ++warn; + if (ret == FREESASA_FAIL) return FREESASA_FAIL; + if (selection_not(selection)) return FREESASA_FAIL; + break; + } + case E_ID: + case E_NUMBER: + case E_PLUS: + case E_RANGE: + /* these four are handled by the RESN,SYMBOL,ETC */ + default: + return fail_msg("parser error"); + } + if (warn) return FREESASA_WARN; + return FREESASA_SUCCESS; +} + +static int +select_area_impl(const char *command, + char *name, + double *area, + const freesasa_structure *structure, + const freesasa_result *result) +{ + struct selection *selection = NULL; + struct expression *expression = NULL; + const int maxlen = FREESASA_MAX_SELECTION_NAME; + double sasa = 0; + int err = 0, warn = 0, n_atoms = 0, j, len; + + assert(name); + assert(area); + assert(command); + assert(structure); + assert(result); + assert(freesasa_structure_n(structure) == result->n_atoms); + + *area = 0; + name[0] = '\0'; + + expression = get_expression(command); + selection = selection_new(result->n_atoms); + + if (selection == NULL) { + return fail_msg(""); + } + + if (expression != NULL && selection != NULL) { + switch (select_atoms(selection, expression, structure)) { + case FREESASA_FAIL: + err = 1; + break; + case FREESASA_WARN: + warn = 1; /* proceed with calculation, print warning later */ + case FREESASA_SUCCESS: { + for (j = 0; j < selection->size; ++j) { + ++n_atoms; + sasa += selection->atom[j] * result->sasa[j]; + } + + *area = sasa; + len = strlen(selection->name); + strncpy(name, selection->name, maxlen); + + if (len > maxlen) { + name[maxlen] = '\0'; + } else { + name[len] = '\0'; + } + + break; + } + default: + assert(0); + } + } else { + err = 1; + } + selection_free(selection); + expression_free(expression); + + if (err) + return fail_msg("problems parsing expression '%s'", command); + if (warn) + return freesasa_warn("in %s(): There were warnings", __func__); + return n_atoms; +} + +freesasa_selection * +freesasa_selection_alloc(const char *name, const char *command) +{ + freesasa_selection *selection = malloc(sizeof(freesasa_selection)); + + if (selection == NULL) { + mem_fail(); + return NULL; + } + + selection->name = NULL; + selection->command = NULL; + selection->area = 0; + selection->n_atoms = 0; + + selection->name = strdup(name); + if (selection->name == NULL) { + mem_fail(); + goto cleanup; + } + + selection->command = strdup(command); + if (selection->command == NULL) { + mem_fail(); + goto cleanup; + } + + return selection; + +cleanup: + freesasa_selection_free(selection); + return NULL; +} + +void freesasa_selection_free(freesasa_selection *selection) +{ + if (selection != NULL) { + free(selection->name); + free(selection->command); + free(selection); + } +} + +freesasa_selection * +freesasa_selection_clone(const freesasa_selection *src) +{ + freesasa_selection *cpy = freesasa_selection_alloc(src->name, src->command); + + if (cpy == NULL) { + fail_msg(""); + goto cleanup; + } + + cpy->area = src->area; + cpy->n_atoms = src->n_atoms; + + return cpy; + +cleanup: + freesasa_selection_free(cpy); + return NULL; +} + +const char * +freesasa_selection_name(const freesasa_selection *selection) +{ + assert(selection); + return selection->name; +} + +const char * +freesasa_selection_command(const freesasa_selection *selection) +{ + assert(selection); + return selection->command; +} + +double +freesasa_selection_area(const freesasa_selection *selection) +{ + assert(selection); + return selection->area; +} + +freesasa_selection * +freesasa_selection_new(const char *command, + const freesasa_structure *structure, + const freesasa_result *result) +{ + char name[FREESASA_MAX_SELECTION_NAME]; + double area; + freesasa_selection *selection; + int n_atoms; + + n_atoms = select_area_impl(command, name, &area, structure, result); + + if (n_atoms == FREESASA_FAIL) { + fail_msg(""); + return NULL; + } + + selection = freesasa_selection_alloc(name, command); + if (selection == NULL) { + mem_fail(); + return NULL; + } + + selection->area = area; + selection->n_atoms = n_atoms; + + return selection; +} + +int freesasa_select_area(const char *command, + char *name, + double *area, + const freesasa_structure *structure, + const freesasa_result *result) +{ + int ret = select_area_impl(command, name, area, structure, result); + if (ret >= 0) return FREESASA_SUCCESS; + return ret; +} + +int freesasa_selection_parse_error(expression *e, + yyscan_t scanner, + const char *msg) +{ + if (freesasa_get_verbosity() == FREESASA_V_DEBUG) print_expr(stderr, e, 0); + if (freesasa_get_verbosity() == FREESASA_V_NORMAL) fprintf(stderr, "\n"); + return freesasa_fail(msg); +} + +#if USE_CHECK +#include + +START_TEST(test_selection) +{ + struct selection *s1, *s2, *s3, *s4; + static const expression empty_expression = { + .right = NULL, .left = NULL, .value = NULL, .type = E_SELECTION}; + freesasa_structure *structure = freesasa_structure_new(); + expression r, l, e, e_symbol; + + freesasa_structure_add_atom(structure, " CA ", "ALA", " 1", 'A', 0, 0, 0); + freesasa_structure_add_atom(structure, " O ", "ALA", " 1", 'A', 10, 10, 10); + + s1 = selection_new(freesasa_structure_n(structure)); + s2 = selection_new(freesasa_structure_n(structure)); + s3 = selection_new(freesasa_structure_n(structure)); + s4 = selection_new(freesasa_structure_n(structure)); + + r = l = e = e_symbol = empty_expression; + e.type = E_PLUS; + e.right = &r; + e.left = &l; + r.value = "C"; + r.type = E_ID; + l.value = "O"; + l.type = E_ID; + e_symbol.type = E_SYMBOL; + e_symbol.left = &e; + + /* select_symbol */ + select_list(E_SYMBOL, s1, structure, &r); + ck_assert_int_eq(s1->atom[0], 1); + ck_assert_int_eq(s1->atom[1], 0); + select_list(E_SYMBOL, s2, structure, &l); + ck_assert_int_eq(s2->atom[0], 0); + ck_assert_int_eq(s2->atom[1], 1); + select_list(E_SYMBOL, s3, structure, &e); + ck_assert_int_eq(s3->atom[0], 1); + ck_assert_int_eq(s3->atom[1], 1); + select_atoms(s4, &e_symbol, structure); + ck_assert_int_eq(s4->atom[0], 1); + ck_assert_int_eq(s4->atom[1], 1); + + /* selection_join */ + selection_join(s3, s1, s2, E_AND); + ck_assert_int_eq(s3->atom[0], 0); + ck_assert_int_eq(s3->atom[1], 0); + selection_join(s3, s1, s2, E_OR); + ck_assert_int_eq(s3->atom[0], 1); + ck_assert_int_eq(s3->atom[1], 1); + freesasa_set_verbosity(FREESASA_V_SILENT); + ck_assert_int_eq(selection_join(NULL, s1, s2, E_OR), FREESASA_FAIL); + ck_assert_int_eq(selection_join(s3, NULL, s1, E_OR), FREESASA_FAIL); + ck_assert_int_eq(selection_join(NULL, NULL, NULL, E_OR), FREESASA_FAIL); + + /* selection_not */ + ck_assert_int_eq(selection_not(s3), FREESASA_SUCCESS); + ck_assert_int_eq(s3->atom[0], 0); + ck_assert_int_eq(s3->atom[1], 0); + ck_assert_int_eq(selection_not(NULL), FREESASA_FAIL); + freesasa_set_verbosity(FREESASA_V_NORMAL); +} +END_TEST + +START_TEST(test_expression) +{ + int i; + expression *e = get_expression("c1, symbol O+C"); + + ck_assert_ptr_ne(e, NULL); + ck_assert_int_eq(e->type, E_SELECTION); + ck_assert_ptr_ne(e->left, NULL); + ck_assert_ptr_eq(e->right, NULL); + ck_assert_str_eq(e->value, "c1"); + ck_assert_int_eq(e->left->type, E_SYMBOL); + ck_assert_ptr_ne(e->left->left, NULL); + ck_assert_ptr_eq(e->left->right, NULL); + ck_assert_int_eq(e->left->left->type, E_PLUS); + ck_assert_int_eq(e->left->left->left->type, E_ID); + ck_assert_int_eq(e->left->left->right->type, E_ID); + ck_assert_str_eq(e->left->left->right->value, "C"); + ck_assert_str_eq(e->left->left->left->value, "O"); + for (i = E_SELECTION; i <= E_RANGE_OPEN_R; ++i) { + ck_assert_ptr_ne(e_str(i), NULL); + } + ck_assert_ptr_eq(e_str(E_RANGE_OPEN_R + 1), NULL); +} +END_TEST + +START_TEST(test_debug) /* this test just runs the debug output code to not get artificially low coverage */ +{ + FILE *devnull = fopen("/dev/null", "w"); + expression *e = get_expression("c1, symbol O+C"); + print_expr(devnull, e, 0); +} +END_TEST + +struct selection selection_dummy = {.size = 1, .name = NULL, .atom = NULL}; + +void *freesasa_selection_dummy_ptr = &selection_dummy; + +int freesasa_wrap_select_atoms(struct selection *selection, + const expression *expr, + const freesasa_structure *structure) +{ + return select_atoms(selection, expr, structure); +} + +TCase * +test_selection_static() +{ + TCase *tc = tcase_create("selection.c static"); + tcase_add_test(tc, test_selection); + tcase_add_test(tc, test_expression); + tcase_add_test(tc, test_debug); + + return tc; +} + +#endif /* USE_CHECK */ diff --git a/.venv_haddock/include/site/python3.12/freesasa/selection.h b/.venv_haddock/include/site/python3.12/freesasa/selection.h new file mode 100644 index 0000000000000000000000000000000000000000..3d3b5538c3e87ca725b2553bbc54b699b59b3341 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/selection.h @@ -0,0 +1,49 @@ +#ifndef SELECTION_H +#define SELECTION_H + +typedef enum { E_SELECTION, + E_SYMBOL, + E_NAME, + E_RESN, + E_RESI, + E_CHAIN, + E_ID, + E_NUMBER, + E_NEGNUM, + E_AND, + E_OR, + E_NOT, + E_PLUS, + E_RANGE, + E_RANGE_OPEN_L, + E_RANGE_OPEN_R } expression_type; + +typedef struct expression { + struct expression *left; + struct expression *right; + expression_type type; + char *value; +} expression; + +/** Create an atomic value E_ID or E_NUMBER */ +expression * +freesasa_selection_atom(expression_type type, + const char *val); + +/** Create a top level selection (E_SELECTION) */ +expression * +freesasa_selection_create(expression *selection, + const char *id); + +/** Create a property selector (E_SYMBOL, E_NAME, E_RESN, E_RESI or E_CHAIN) */ +expression * +freesasa_selection_selector(expression_type type, + expression *list); + +/** Create an operation (E_AND, E_OR, E_NOT, E_PLUS or E_RANGE) */ +expression * +freesasa_selection_operation(expression_type type, + expression *left, + expression *right); + +#endif /* SELECTION_H */ diff --git a/.venv_haddock/include/site/python3.12/freesasa/structure.c b/.venv_haddock/include/site/python3.12/freesasa/structure.c new file mode 100644 index 0000000000000000000000000000000000000000..9dfdb710daeb85e1e53a8c8a48942152169dae83 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/structure.c @@ -0,0 +1,1243 @@ +#if HAVE_CONFIG_H +#include +#endif + +#include +#include + +#include "classifier.h" +#include "coord.h" +#include "freesasa_internal.h" +#include "pdb.h" + +/** + This file contains the functions that turn lines in PDB files to + atom records. It's all pretty messy because one needs to keep track + of when a new chain/new residue is encountered, and skip atoms that + are duplicates (only first of alt coordinates are used). It is both + possible to add atoms one by one, or by reading a whole file at + once, and the user can supply some options about what to do when + encountering atoms that are not recognized, whether to include + hydrogrens, hetatm, etc. The current implementation results in a + rather convoluted logic, that is difficult to maintain, debug and + extend. + + TODO: Refactor. +*/ +#define ATOMS_CHUNK 512 +#define RESIDUES_CHUNK 64 +#define CHAINS_CHUNK 64 + +struct atom { + char *res_name; + char *res_number; + char *atom_name; + char *symbol; + char *line; + int res_index; + char chain_label; + freesasa_atom_class the_class; +}; + +static const struct atom empty_atom = { + NULL, /* res_name */ + NULL, /* res_number */ + NULL, /* atom_name */ + NULL, /* symbol */ + NULL, /* line */ + -1, /* res_index */ + '\0', /* chain_label */ + FREESASA_ATOM_UNKNOWN /* the_class */ +}; + +struct atoms { + int n; + int n_alloc; + struct atom **atom; + double *radius; +}; + +struct residues { + int n; + int n_alloc; + int *first_atom; + freesasa_nodearea **reference_area; +}; + +struct chains { + int n; + int n_alloc; + char *labels; /* all chain labels found (as string) */ + int *first_atom; /* first atom of each chain */ +}; + +struct freesasa_structure { + struct atoms atoms; + struct residues residues; + struct chains chains; + char *classifier_name; + coord_t *xyz; + int model; /* model number */ + size_t cif_ref; + void (*release_cif_ref)(size_t); +}; + +static int +guess_symbol(char *symbol, + const char *name); + +static void +atom_free(struct atom *a) +{ + if (a != NULL) { + free(a->res_name); + free(a->res_number); + free(a->atom_name); + free(a->symbol); + free(a->line); + free(a); + } +} + +struct atoms +atoms_init(void) +{ + struct atoms atoms; + atoms.n = 0; + atoms.n_alloc = 0; + atoms.atom = NULL; + atoms.radius = NULL; + return atoms; +} + +/* Allocates memory in chunks, ticks up atoms->n if allocation successful */ +static int +atoms_alloc(struct atoms *atoms) +{ + int i, new_size; + void *aa, *ar; + + assert(atoms); + assert(atoms->n <= atoms->n_alloc); + + if (atoms->n == atoms->n_alloc) { + new_size = atoms->n_alloc + ATOMS_CHUNK; + aa = atoms->atom; + ar = atoms->radius; + + atoms->atom = realloc(atoms->atom, sizeof(struct atom *) * new_size); + if (atoms->atom == NULL) { + atoms->atom = aa; + return mem_fail(); + } + + for (i = atoms->n_alloc; i < new_size; ++i) { + atoms->atom[i] = NULL; + } + + atoms->radius = realloc(atoms->radius, sizeof(double) * new_size); + if (atoms->radius == NULL) { + atoms->radius = ar; + return mem_fail(); + } + + atoms->n_alloc = new_size; + } + ++atoms->n; + return FREESASA_SUCCESS; +} + +static void +atoms_dealloc(struct atoms *atoms) +{ + int i; + struct atom **atom; + + if (atoms) { + atom = atoms->atom; + if (atom) { + for (i = 0; i < atoms->n; ++i) + if (atom[i]) atom_free(atom[i]); + free(atom); + } + free(atoms->radius); + *atoms = atoms_init(); + } +} + +static struct atom * +atom_new(const char *residue_name, + const char *residue_number, + const char *atom_name, + const char *symbol, + char chain_label) +{ + struct atom *a = malloc(sizeof(struct atom)); + if (a == NULL) goto memerr; + + *a = empty_atom; + + a->line = NULL; + a->chain_label = chain_label; + a->res_index = -1; + + a->res_name = strdup(residue_name); + a->res_number = strdup(residue_number); + a->atom_name = strdup(atom_name); + a->symbol = strdup(symbol); + a->the_class = FREESASA_ATOM_UNKNOWN; + + if (!a->res_name || !a->res_number || !a->atom_name || + !a->symbol) { + goto memerr; + } + + return a; + +memerr: + mem_fail(); + atom_free(a); + return NULL; +} + +static struct atom * +atom_new_from_line(const char *line, + char *alt_label) +{ + char aname[PDB_ATOM_NAME_STRL + 1], rname[PDB_ATOM_RES_NAME_STRL + 1], + rnumber[PDB_ATOM_RES_NUMBER_STRL + 1], symbol[PDB_ATOM_SYMBOL_STRL + 1]; + int flag; + struct atom *a; + + assert(line); + + if (alt_label) *alt_label = freesasa_pdb_get_alt_coord_label(line); + + freesasa_pdb_get_atom_name(aname, line); + freesasa_pdb_get_res_name(rname, line); + freesasa_pdb_get_res_number(rnumber, line); + + flag = freesasa_pdb_get_symbol(symbol, line); + if (flag == FREESASA_FAIL || (symbol[0] == ' ' && symbol[1] == ' ')) { + guess_symbol(symbol, aname); + } + + a = atom_new(rname, rnumber, aname, symbol, freesasa_pdb_get_chain_label(line)); + + if (a != NULL) { + a->line = strdup(line); + if (a->line == NULL) { + mem_fail(); + atom_free(a); + a = NULL; + } + } + + return a; +} + +static struct residues +residues_init(void) +{ + struct residues res; + + res.n = 0; + res.n_alloc = 0; + res.first_atom = 0; + res.reference_area = 0; + + return res; +} + +static int +residues_alloc(struct residues *residues) +{ + int new_size; + void *fa, *ra; + + assert(residues); + assert(residues->n <= residues->n_alloc); + + if (residues->n == residues->n_alloc) { + new_size = residues->n_alloc + RESIDUES_CHUNK; + fa = residues->first_atom; + ra = residues->reference_area; + + residues->first_atom = realloc(residues->first_atom, + sizeof(int) * new_size); + if (residues->first_atom == NULL) { + residues->first_atom = fa; + return mem_fail(); + } + + residues->reference_area = realloc(residues->reference_area, + sizeof(freesasa_nodearea *) * new_size); + if (residues->reference_area == NULL) { + residues->reference_area = ra; + return mem_fail(); + } + + residues->n_alloc = new_size; + } + ++residues->n; + return FREESASA_SUCCESS; +} + +static void +residues_dealloc(struct residues *residues) +{ + int i; + + if (residues) { + free(residues->first_atom); + if (residues->reference_area) { + for (i = 0; i < residues->n; ++i) { + free(residues->reference_area[i]); + } + } + free(residues->reference_area); + *residues = residues_init(); + } +} + +static struct chains +chains_init(void) +{ + struct chains ch; + + ch.n = 0; + ch.n_alloc = 0; + ch.first_atom = NULL; + ch.labels = NULL; + + return ch; +} + +static int +chains_alloc(struct chains *chains) +{ + int new_size; + void *fa, *lbl; + + assert(chains); + assert(chains->n <= chains->n_alloc); + + if (chains->n == chains->n_alloc) { + new_size = chains->n_alloc + CHAINS_CHUNK; + fa = chains->first_atom; + lbl = chains->labels; + + chains->first_atom = realloc(chains->first_atom, + sizeof(int) * new_size); + if (chains->first_atom == NULL) { + chains->first_atom = fa; + return mem_fail(); + } + + chains->labels = realloc(chains->labels, new_size + 1); + if (chains->labels == NULL) { + chains->labels = lbl; + return mem_fail(); + } + + chains->n_alloc = new_size; + } + ++chains->n; + return FREESASA_SUCCESS; +} + +static void +chains_dealloc(struct chains *chains) +{ + if (chains) { + free(chains->first_atom); + free(chains->labels); + *chains = chains_init(); + } +} + +freesasa_structure * +freesasa_structure_new(void) +{ + freesasa_structure *s = malloc(sizeof(freesasa_structure)); + + if (s == NULL) goto memerr; + + s->atoms = atoms_init(); + s->residues = residues_init(); + s->chains = chains_init(); + s->xyz = freesasa_coord_new(); + s->model = 1; + s->classifier_name = NULL; + s->cif_ref = 0; + s->release_cif_ref = 0; + + if (s->xyz == NULL) goto memerr; + + return s; +memerr: + freesasa_structure_free(s); + mem_fail(); + return NULL; +} + +void freesasa_structure_free(freesasa_structure *s) +{ + if (s != NULL) { + atoms_dealloc(&s->atoms); + residues_dealloc(&s->residues); + chains_dealloc(&s->chains); + + if (s->xyz != NULL) { + freesasa_coord_free(s->xyz); + } + + free(s->classifier_name); + + if (s->cif_ref > 0 && s->release_cif_ref != NULL) { + s->release_cif_ref(s->cif_ref); + } + + free(s); + } +} + +/** + This function is called when either the symbol field is missing + from an ATOM record, or when an atom is added directly using + freesasa_structure_add_atom() or + freesasa_structure_add_atom_wopt(). The symbol is in turn only + used if the atom cannot be recognized by the classifier. +*/ +static int +guess_symbol(char *symbol, + const char *name) +{ + /* if the first position is empty, or a number, assume that it is + a one letter element e.g. " C ", or "1H " */ + if (name[0] == ' ' || (name[0] >= '1' && name[0] <= '9')) { + symbol[0] = ' '; + symbol[1] = name[1]; + symbol[2] = '\0'; + } else { + /* if the string has padding to the right, it's a + two-letter element, e.g. "FE " */ + if (name[3] == ' ') { + strncpy(symbol, name, 2); + symbol[2] = '\0'; + } else { + /* If it's a four-letter string, it's hard to say, + assume only the first letter signifies the element */ + symbol[0] = ' '; + symbol[1] = name[0]; + symbol[2] = '\0'; + return freesasa_warn("guessing that atom '%s' is symbol '%s'", + name, symbol); + } + } + return FREESASA_SUCCESS; +} +static int +structure_add_chain(freesasa_structure *s, + char chain_label, + int i_latest_atom) +{ + int n; + if (s->chains.n == 0 || strchr(s->chains.labels, chain_label) == NULL) { + + if (chains_alloc(&s->chains) == FREESASA_FAIL) + return fail_msg(""); + + n = s->chains.n; + s->chains.labels[n - 1] = chain_label; + s->chains.labels[n] = '\0'; + + assert(strlen(s->chains.labels) == s->chains.n); + + s->chains.first_atom[n - 1] = i_latest_atom; + } + return FREESASA_SUCCESS; +} + +static int +structure_add_residue(freesasa_structure *s, + const freesasa_classifier *classifier, + const struct atom *a, + int i_latest_atom) +{ + int n = s->residues.n + 1; + const freesasa_nodearea *reference = NULL; + + /* register a new residue if it's the first atom, or if the + residue number or chain label of the current atom is different + from the previous one */ + if (!(s->residues.n == 0 || + (i_latest_atom > 0 && + (strcmp(a->res_number, s->atoms.atom[i_latest_atom - 1]->res_number) || + a->chain_label != s->atoms.atom[i_latest_atom - 1]->chain_label)))) { + return FREESASA_SUCCESS; + } + + if (residues_alloc(&s->residues) == FREESASA_FAIL) { + return fail_msg(""); + } + s->residues.first_atom[n - 1] = i_latest_atom; + + s->residues.reference_area[n - 1] = NULL; + reference = freesasa_classifier_residue_reference(classifier, a->res_name); + if (reference != NULL) { + s->residues.reference_area[n - 1] = malloc(sizeof(freesasa_nodearea)); + if (s->residues.reference_area[n - 1] == NULL) + return mem_fail(); + *s->residues.reference_area[n - 1] = *reference; + } + + return FREESASA_SUCCESS; +} + +/** + Get the radius of an atom, and fail, warn and/or guess depending + on the options. + */ +static int +structure_check_atom_radius(double *radius, + struct atom *a, + const freesasa_classifier *classifier, + int options) +{ + *radius = freesasa_classifier_radius(classifier, a->res_name, a->atom_name); + if (*radius < 0) { + if (options & FREESASA_HALT_AT_UNKNOWN) { + return fail_msg("atom '%s %s' unknown", + a->res_name, a->atom_name); + } else if (options & FREESASA_SKIP_UNKNOWN) { + return freesasa_warn("skipping unknown atom '%s %s'", + a->res_name, a->atom_name, a->symbol, *radius); + } else { + *radius = freesasa_guess_radius(a->symbol); + if (*radius < 0) { + *radius = +0.; + freesasa_warn("atom '%s %s' unknown and " + "can't guess radius of symbol '%s', " + "assigning radius 0 A", + a->res_name, a->atom_name, a->symbol); + } else { + freesasa_warn("atom '%s %s' unknown, guessing element is '%s', " + "and radius %.3f A", + a->res_name, a->atom_name, a->symbol, *radius); + } + /* do not return FREESASA_WARN here, because we will keep the atom */ + } + } + return FREESASA_SUCCESS; +} + +static int +structure_register_classifier(freesasa_structure *structure, + const freesasa_classifier *classifier) +{ + if (structure->classifier_name == NULL) { + structure->classifier_name = strdup(freesasa_classifier_name(classifier)); + if (structure->classifier_name == NULL) { + return mem_fail(); + } + } else if (strcmp(structure->classifier_name, freesasa_classifier_name(classifier)) != 0) { + structure->classifier_name = strdup(FREESASA_CONFLICTING_CLASSIFIERS); + if (structure->classifier_name == NULL) { + return mem_fail(); + } + return FREESASA_WARN; + } + + return FREESASA_SUCCESS; +} + +/** + Adds an atom to the structure using the rules specified by + 'options'. If it includes FREESASA_RADIUS_FROM_* a dummy radius is + assigned and the caller is expected to replace it with a correct + radius later. + + The atom a should be a pointer to a heap address, this will not be cloned. + */ +static int +structure_add_atom(freesasa_structure *structure, + struct atom *atom, + double *xyz, + const freesasa_classifier *classifier, + int options) +{ + int na, ret; + double r; + + assert(structure); + assert(atom); + assert(xyz); + + /* let the stricter option override if both are specified */ + if (options & FREESASA_SKIP_UNKNOWN && options & FREESASA_HALT_AT_UNKNOWN) + options &= ~FREESASA_SKIP_UNKNOWN; + + if (classifier == NULL) { + classifier = &freesasa_default_classifier; + } + structure_register_classifier(structure, classifier); + + /* calculate radius and check if we should keep the atom (based on options) */ + if (options & FREESASA_RADIUS_FROM_OCCUPANCY) { + r = 1; /* fix it later */ + } else { + ret = structure_check_atom_radius(&r, atom, classifier, options); + if (ret == FREESASA_FAIL) return fail_msg("halting at unknown atom"); + if (ret == FREESASA_WARN) return FREESASA_WARN; + } + assert(r >= 0); + + /* If it's a keeper, allocate memory */ + if (atoms_alloc(&structure->atoms) == FREESASA_FAIL) + return fail_msg(""); + na = structure->atoms.n; + + /* Store coordinates */ + if (freesasa_coord_append(structure->xyz, xyz, 1) == FREESASA_FAIL) + return mem_fail(); + + /* Check if this is a new chain and if so add it */ + if (structure_add_chain(structure, atom->chain_label, na - 1) == FREESASA_FAIL) + return mem_fail(); + + /* Check if this is a new residue, and if so add it */ + if (structure_add_residue(structure, classifier, atom, na - 1) == FREESASA_FAIL) + return mem_fail(); + + atom->the_class = freesasa_classifier_class(classifier, atom->res_name, atom->atom_name); + atom->res_index = structure->residues.n - 1; + structure->atoms.radius[na - 1] = r; + structure->atoms.atom[na - 1] = atom; + + return FREESASA_SUCCESS; +} + +/** + Handles the reading of PDB-files, returns NULL if problems reading + or input or malloc failure. Error-messages should explain what + went wrong. + */ +static freesasa_structure * +from_pdb_impl(FILE *pdb_file, + struct file_range it, + const freesasa_classifier *classifier, + int options) +{ + char line[PDB_MAX_LINE_STRL]; + char alt, the_alt = ' '; + double v[3], r; + int ret; + struct atom *a = NULL; + freesasa_structure *s = freesasa_structure_new(); + + assert(pdb_file); + + if (s == NULL) return NULL; + + fseek(pdb_file, it.begin, SEEK_SET); + + while (fgets(line, PDB_MAX_LINE_STRL, pdb_file) != NULL && ftell(pdb_file) <= it.end) { + + if (strncmp("ATOM", line, 4) == 0 || ((options & FREESASA_INCLUDE_HETATM) && + (strncmp("HETATM", line, 6) == 0))) { + if (freesasa_pdb_ishydrogen(line) && + !(options & FREESASA_INCLUDE_HYDROGEN)) + continue; + + a = atom_new_from_line(line, &alt); + if (a == NULL) + goto cleanup; + + if ((alt != ' ' && the_alt == ' ') || (alt == ' ')) + the_alt = alt; + else if (alt != ' ' && alt != the_alt) { + atom_free(a); + a = NULL; + continue; + } + + ret = freesasa_pdb_get_coord(v, line); + if (ret == FREESASA_FAIL) + goto cleanup; + + ret = structure_add_atom(s, a, v, classifier, options); + if (ret == FREESASA_FAIL) { + goto cleanup; + } else if (ret == FREESASA_WARN) { + atom_free(a); + a = NULL; + continue; + } + + if (options & FREESASA_RADIUS_FROM_OCCUPANCY) { + ret = freesasa_pdb_get_occupancy(&r, line); + if (ret == FREESASA_FAIL) + goto cleanup; + s->atoms.radius[s->atoms.n - 1] = r; + } + } + + if (!(options & FREESASA_JOIN_MODELS)) { + if (strncmp("MODEL", line, 5) == 0) sscanf(line + 10, "%d", &s->model); + if (strncmp("ENDMDL", line, 6) == 0) break; + } + } + + if (s->atoms.n == 0) { + fail_msg("input had no valid ATOM or HETATM lines"); + goto cleanup; + } + + return s; + +cleanup: + fail_msg(""); + atom_free(a); + freesasa_structure_free(s); + return NULL; +} + +static int +structure_add_atom_wopt_impl(freesasa_structure *structure, + const char *atom_name, + const char *residue_name, + const char *residue_number, + const char *symbol, + char chain_label, + double x, double y, double z, + const freesasa_classifier *classifier, + int options) +{ + struct atom *a; + char my_symbol[PDB_ATOM_SYMBOL_STRL + 1]; + double v[3] = {x, y, z}; + int ret, warn = 0; + + assert(structure); + assert(atom_name); + assert(residue_name); + assert(residue_number); + + /* this option can not be used here, and needs to be unset */ + options &= ~FREESASA_RADIUS_FROM_OCCUPANCY; + + if (symbol != NULL) { + strncpy(my_symbol, symbol, sizeof(my_symbol)); + } else if (guess_symbol(my_symbol, atom_name) == FREESASA_WARN && + options & FREESASA_SKIP_UNKNOWN) { + ++warn; + } + + a = atom_new(residue_name, residue_number, atom_name, my_symbol, chain_label); + if (a == NULL) return mem_fail(); + + ret = structure_add_atom(structure, a, v, classifier, options); + + if (ret == FREESASA_FAIL || + (ret == FREESASA_WARN && options & FREESASA_SKIP_UNKNOWN)) + atom_free(a); + + if (!ret && warn) return FREESASA_WARN; + + return ret; +} + +int freesasa_structure_add_atom_wopt(freesasa_structure *structure, + const char *atom_name, + const char *residue_name, + const char *residue_number, + char chain_label, + double x, double y, double z, + const freesasa_classifier *classifier, + int options) +{ + return structure_add_atom_wopt_impl(structure, atom_name, residue_name, residue_number, NULL, + chain_label, x, y, z, classifier, options); +} +int freesasa_structure_add_atom(freesasa_structure *structure, + const char *atom_name, + const char *residue_name, + const char *residue_number, + char chain_label, + double x, double y, double z) +{ + return structure_add_atom_wopt_impl(structure, atom_name, residue_name, residue_number, NULL, + chain_label, x, y, z, NULL, 0); +} + +int freesasa_structure_add_cif_atom(freesasa_structure *structure, + freesasa_cif_atom *atom, + const freesasa_classifier *classifier, + int options) +{ + char res_number[PDB_ATOM_RES_NUMBER_STRL + 1]; + + if (atom->pdbx_PDB_ins_code[0] != '?') { + snprintf(res_number, sizeof res_number, "%s%c", atom->auth_seq_id, atom->pdbx_PDB_ins_code[0]); + } else { + snprintf(res_number, sizeof res_number, "%s", atom->auth_seq_id); + } + + return structure_add_atom_wopt_impl(structure, atom->auth_atom_id, atom->auth_comp_id, + res_number, atom->type_symbol, atom->auth_asym_id, + atom->Cartn_x, atom->Cartn_y, atom->Cartn_z, + classifier, options); +} + +freesasa_structure * +freesasa_structure_from_pdb(FILE *pdb_file, + const freesasa_classifier *classifier, + int options) +{ + assert(pdb_file); + return from_pdb_impl(pdb_file, freesasa_whole_file(pdb_file), + classifier, options); +} + +freesasa_structure ** +freesasa_structure_array(FILE *pdb, + int *n, + const freesasa_classifier *classifier, + int options) +{ + struct file_range *models = NULL, *chains = NULL; + struct file_range whole_file; + int n_models = 0, n_chains = 0, j0, n_new_chains, i, j; + freesasa_structure **ss = NULL, **ssb; + + assert(pdb); + assert(n); + + if (!(options & FREESASA_SEPARATE_MODELS || + options & FREESASA_SEPARATE_CHAINS)) { + fail_msg("options need to specify at least one of FREESASA_SEPARATE_CHAINS " + "and FREESASA_SEPARATE_MODELS"); + return NULL; + } + + whole_file = freesasa_whole_file(pdb); + n_models = freesasa_pdb_get_models(pdb, &models); + + if (n_models == FREESASA_FAIL) { + fail_msg("problems reading PDB-file"); + return NULL; + } + if (n_models == 0) { + models = &whole_file; + n_models = 1; + } + + /* only keep first model if option not provided */ + if (!(options & FREESASA_SEPARATE_MODELS)) n_models = 1; + + /* for each model read chains if requested */ + if (options & FREESASA_SEPARATE_CHAINS) { + for (i = 0; i < n_models; ++i) { + chains = NULL; + n_new_chains = freesasa_pdb_get_chains(pdb, models[i], &chains, options); + + if (n_new_chains == FREESASA_FAIL) goto cleanup; + if (n_new_chains == 0) { + freesasa_warn("in %s(): no chains found (in model %d)", __func__, i + 1); + continue; + } + + ssb = ss; + ss = realloc(ss, sizeof(freesasa_structure *) * (n_chains + n_new_chains)); + + if (!ss) { + ss = ssb; + mem_fail(); + goto cleanup; + } + + j0 = n_chains; + n_chains += n_new_chains; + + for (j = 0; j < n_new_chains; ++j) + ss[j0 + j] = NULL; + + for (j = 0; j < n_new_chains; ++j) { + ss[j0 + j] = from_pdb_impl(pdb, chains[j], classifier, options); + if (ss[j0 + j] == NULL) goto cleanup; + ss[j0 + j]->model = i + 1; + } + + free(chains); + } + *n = n_chains; + } else { + ss = malloc(sizeof(freesasa_structure *) * n_models); + if (!ss) { + mem_fail(); + goto cleanup; + } + + for (i = 0; i < n_models; ++i) + ss[i] = NULL; + *n = n_models; + + for (i = 0; i < n_models; ++i) { + ss[i] = from_pdb_impl(pdb, models[i], classifier, options); + if (ss[i] == NULL) goto cleanup; + ss[i]->model = i + 1; + } + } + + if (*n == 0) goto cleanup; + + if (models != &whole_file) free(models); + + return ss; + +cleanup: + if (ss) + for (i = 0; i < *n; ++i) + freesasa_structure_free(ss[i]); + if (models != &whole_file) free(models); + free(chains); + *n = 0; + free(ss); + return NULL; +} + +freesasa_structure * +freesasa_structure_get_chains(const freesasa_structure *structure, + const char *chains, + const freesasa_classifier *classifier, + int options) +{ + freesasa_structure *new_s; + struct atom *ai; + int i, res; + char c; + const double *v; + + assert(structure); + if (strlen(chains) == 0) return NULL; + + new_s = freesasa_structure_new(); + + if (!new_s) { + mem_fail(); + return NULL; + } + + new_s->model = structure->model; + + for (i = 0; i < structure->atoms.n; ++i) { + ai = structure->atoms.atom[i]; + c = ai->chain_label; + if (strchr(chains, c) != NULL) { + v = freesasa_coord_i(structure->xyz, i); + res = structure_add_atom_wopt_impl(new_s, ai->atom_name, + ai->res_name, ai->res_number, ai->symbol, + c, v[0], v[1], v[2], classifier, options); + if (res == FREESASA_FAIL) { + fail_msg(""); + goto cleanup; + } + } + } + + /* the following two tests could have been done by comparing the + chain-strings before the loop, but this logic is simpler. */ + if (new_s->atoms.n == 0) { + goto cleanup; + } + if (strlen(new_s->chains.labels) != strlen(chains)) { + fail_msg("structure has chains '%s', but '%s' requested", + structure->chains.labels, chains); + goto cleanup; + } + + return new_s; + +cleanup: + freesasa_structure_free(new_s); + return NULL; +} + +const char * +freesasa_structure_chain_labels(const freesasa_structure *structure) +{ + assert(structure); + return structure->chains.labels; +} + +const coord_t * +freesasa_structure_xyz(const freesasa_structure *structure) +{ + assert(structure); + return structure->xyz; +} + +int freesasa_structure_n(const freesasa_structure *structure) +{ + assert(structure); + return structure->atoms.n; +} + +int freesasa_structure_n_residues(const freesasa_structure *structure) +{ + assert(structure); + return structure->residues.n; +} + +const char * +freesasa_structure_atom_name(const freesasa_structure *structure, + int i) +{ + assert(structure); + assert(i < structure->atoms.n && i >= 0); + return structure->atoms.atom[i]->atom_name; +} + +const char * +freesasa_structure_atom_res_name(const freesasa_structure *structure, + int i) +{ + assert(structure); + assert(i < structure->atoms.n && i >= 0); + return structure->atoms.atom[i]->res_name; +} + +const char * +freesasa_structure_atom_res_number(const freesasa_structure *structure, + int i) +{ + assert(structure); + assert(i < structure->atoms.n && i >= 0); + return structure->atoms.atom[i]->res_number; +} + +char freesasa_structure_atom_chain(const freesasa_structure *structure, + int i) +{ + assert(structure); + assert(i < structure->atoms.n && i >= 0); + return structure->atoms.atom[i]->chain_label; +} +const char * +freesasa_structure_atom_symbol(const freesasa_structure *structure, + int i) +{ + assert(structure); + assert(i < structure->atoms.n && i >= 0); + return structure->atoms.atom[i]->symbol; +} + +double +freesasa_structure_atom_radius(const freesasa_structure *structure, + int i) +{ + assert(structure); + assert(i < structure->atoms.n && i >= 0); + return structure->atoms.radius[i]; +} + +void freesasa_structure_atom_set_radius(freesasa_structure *structure, + int i, + double radius) +{ + assert(structure); + assert(i < structure->atoms.n && i >= 0); + structure->atoms.radius[i] = radius; +} + +freesasa_atom_class +freesasa_structure_atom_class(const freesasa_structure *structure, + int i) +{ + assert(structure); + assert(i < structure->atoms.n && i >= 0); + return structure->atoms.atom[i]->the_class; +} + +const char * +freesasa_structure_atom_pdb_line(const freesasa_structure *structure, + int i) +{ + assert(structure); + assert(i < structure->atoms.n && i >= 0); + return structure->atoms.atom[i]->line; +} +const freesasa_nodearea * +freesasa_structure_residue_reference(const freesasa_structure *structure, + int r_i) +{ + assert(structure); + assert(r_i >= 0 && r_i < structure->residues.n); + + return structure->residues.reference_area[r_i]; +} +int freesasa_structure_residue_atoms(const freesasa_structure *structure, + int r_i, + int *first, + int *last) +{ + int naa; + assert(structure); + assert(first); + assert(last); + + naa = structure->residues.n; + + assert(r_i >= 0 && r_i < naa); + + *first = structure->residues.first_atom[r_i]; + if (r_i == naa - 1) + *last = structure->atoms.n - 1; + else + *last = structure->residues.first_atom[r_i + 1] - 1; + assert(*last >= *first); + + return FREESASA_SUCCESS; +} + +const char * +freesasa_structure_residue_name(const freesasa_structure *structure, + int r_i) +{ + assert(structure); + assert(r_i < structure->residues.n && r_i >= 0); + return structure->atoms.atom[structure->residues.first_atom[r_i]]->res_name; +} + +const char * +freesasa_structure_residue_number(const freesasa_structure *structure, + int r_i) +{ + assert(structure); + assert(r_i < structure->residues.n && r_i >= 0); + return structure->atoms.atom[structure->residues.first_atom[r_i]]->res_number; +} + +char freesasa_structure_residue_chain(const freesasa_structure *structure, + int r_i) +{ + assert(structure); + assert(r_i < structure->residues.n && r_i >= 0); + + return structure->atoms.atom[structure->residues.first_atom[r_i]]->chain_label; +} + +int freesasa_structure_n_chains(const freesasa_structure *structure) +{ + return structure->chains.n; +} + +int freesasa_structure_chain_index(const freesasa_structure *structure, + char chain) +{ + int i; + + assert(structure); + + for (i = 0; i < structure->chains.n; ++i) { + if (structure->chains.labels[i] == chain) return i; + } + return fail_msg("chain %c not found", chain); +} + +int freesasa_structure_chain_atoms(const freesasa_structure *structure, + char chain, + int *first, + int *last) +{ + int c_i, n; + + assert(structure); + + c_i = freesasa_structure_chain_index(structure, chain); + n = freesasa_structure_n_chains(structure); + + if (c_i < 0) return fail_msg(""); + + *first = structure->chains.first_atom[c_i]; + if (c_i == n - 1) + *last = freesasa_structure_n(structure) - 1; + else + *last = structure->chains.first_atom[c_i + 1] - 1; + assert(*last >= *first); + + return FREESASA_SUCCESS; +} + +int freesasa_structure_chain_residues(const freesasa_structure *structure, + char chain, + int *first, + int *last) +{ + int first_atom, last_atom; + + assert(structure); + + if (freesasa_structure_chain_atoms(structure, chain, &first_atom, &last_atom)) + return fail_msg(""); + + *first = structure->atoms.atom[first_atom]->res_index; + *last = structure->atoms.atom[last_atom]->res_index; + + return FREESASA_SUCCESS; +} + +const char * +freesasa_structure_classifier_name(const freesasa_structure *structure) +{ + assert(structure); + return structure->classifier_name; +} + +int freesasa_structure_model(const freesasa_structure *structure) +{ + return structure->model; +} + +const double * +freesasa_structure_coord_array(const freesasa_structure *structure) +{ + return freesasa_coord_all(structure->xyz); +} + +const double * +freesasa_structure_radius(const freesasa_structure *structure) +{ + assert(structure); + return structure->atoms.radius; +} + +void freesasa_structure_set_radius(freesasa_structure *structure, + const double *radii) +{ + assert(structure); + assert(radii); + memcpy(structure->atoms.radius, radii, structure->atoms.n * sizeof(double)); +} + +void freesasa_structure_set_model(freesasa_structure *structure, + int model) +{ + structure->model = model; +} + +void freesasa_structure_set_cif_ref(freesasa_structure *structure, + size_t ref, + void (*release_func)(size_t)) +{ + assert(structure); + structure->cif_ref = ref; + structure->release_cif_ref = release_func; +} + +size_t freesasa_structure_cif_ref(const freesasa_structure *structure) +{ + assert(structure); + return structure->cif_ref; +} diff --git a/.venv_haddock/include/site/python3.12/freesasa/util.c b/.venv_haddock/include/site/python3.12/freesasa/util.c new file mode 100644 index 0000000000000000000000000000000000000000..e382e4b6e2516bba74e59abc4a07bdc3ce3b71d5 --- /dev/null +++ b/.venv_haddock/include/site/python3.12/freesasa/util.c @@ -0,0 +1,141 @@ +#if HAVE_CONFIG_H +#include +#endif +#include +#include +#include +#include +#include + +#include "freesasa_internal.h" + +#ifdef PACKAGE_NAME +const char *freesasa_name = PACKAGE_NAME; +#else +const char *freesasa_name = "freesasa"; +#endif + +static FILE *errlog = NULL; + +struct file_range +freesasa_whole_file(FILE *file) +{ + struct file_range range; + + assert(file); + rewind(file); + range.begin = ftell(file); + fseek(file, 0, SEEK_END); + range.end = ftell(file); + rewind(file); + assert(range.begin <= range.end); + + return range; +} + +static void +freesasa_err_impl(int err, + const char *format, + va_list arg) +{ + FILE *fp = stderr; + + if (errlog != NULL) fp = errlog; + + fprintf(fp, "%s: ", freesasa_name); + switch (err) { + case FREESASA_FAIL: + fputs("error: ", fp); + break; + case FREESASA_WARN: + fputs("warning: ", fp); + break; + default: + break; + } + vfprintf(fp, format, arg); + va_end(arg); + fputc('\n', fp); + fflush(fp); +} + +int freesasa_fail(const char *format, ...) +{ + va_list arg; + + if (freesasa_get_verbosity() == FREESASA_V_SILENT) return FREESASA_FAIL; + + va_start(arg, format); + freesasa_err_impl(FREESASA_FAIL, format, arg); + va_end(arg); + + return FREESASA_FAIL; +} + +int freesasa_warn(const char *format, ...) +{ + va_list arg; + int v = freesasa_get_verbosity(); + + if (v == FREESASA_V_NOWARNINGS || v == FREESASA_V_SILENT) return FREESASA_WARN; + + va_start(arg, format); + freesasa_err_impl(FREESASA_WARN, format, arg); + va_end(arg); + + return FREESASA_WARN; +} + +int freesasa_fail_wloc(const char *file, + int line, + const char *format, + ...) +{ + FILE *fp = stderr; + va_list arg; + + if (freesasa_get_verbosity() == FREESASA_V_SILENT) return FREESASA_FAIL; + if (errlog != NULL) fp = errlog; + + fprintf(fp, "%s:%s:%d: error: ", freesasa_name, file, line); + va_start(arg, format); + vfprintf(fp, format, arg); + va_end(arg); + fputc('\n', fp); + fflush(fp); + + return FREESASA_FAIL; +} + +int freesasa_mem_fail(const char *file, int line) +{ + return freesasa_fail_wloc(file, line, "Out of memory"); +} + +const char * +freesasa_thread_error(int error_code) +{ + switch (error_code) { + case EDEADLK: + return "deadlock (EDEADLK)"; + case EINVAL: + return "(EINVAL)"; + case ESRCH: + return "no matching thread (ESRCH)"; + case EAGAIN: + return "no resources to create thread (EAGAIN)"; + } + return "Unknown thread error"; +} + +void freesasa_set_err_out(FILE *fp) +{ + assert(fp); + errlog = fp; +} + +FILE * +freesasa_get_err_out() +{ + return errlog; +} diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/CelFile.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/CelFile.py new file mode 100644 index 0000000000000000000000000000000000000000..98791b99dc782a1e5d9a2ecce75fe7e53a70ed38 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/CelFile.py @@ -0,0 +1,577 @@ +# Copyright 2004 by Harry Zuzan. All rights reserved. +# Copyright 2016 by Adam Kurkiewicz. All rights reserved. +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Reading information from Affymetrix CEL files version 3 and 4.""" + +import struct + +try: + import numpy as np +except ImportError: + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Install NumPy if you want to use Bio.Affy.CelFile" + ) from None + + +class ParserError(ValueError): + """Affymetrix parser error.""" + + def __init__(self, *args): + """Initialise class.""" + super().__init__(*args) + + +class Record: + """Stores the information in a cel file. + + Example usage: + + >>> from Bio.Affy import CelFile + >>> with open("Affy/affy_v3_example.CEL") as handle: + ... c = CelFile.read(handle) + ... + >>> print(c.ncols, c.nrows) + 5 5 + >>> print(c.intensities) + [[ 234. 170. 22177. 164. 22104.] + [ 188. 188. 21871. 168. 21883.] + [ 188. 193. 21455. 198. 21300.] + [ 188. 182. 21438. 188. 20945.] + [ 193. 20370. 174. 20605. 168.]] + >>> print(c.stdevs) + [[ 24. 34.5 2669. 19.7 3661.2] + [ 29.8 29.8 2795.9 67.9 2792.4] + [ 29.8 88.7 2976.5 62. 2914.5] + [ 29.8 76.2 2759.5 49.2 2762. ] + [ 38.8 2611.8 26.6 2810.7 24.1]] + >>> print(c.npix) + [[25 25 25 25 25] + [25 25 25 25 25] + [25 25 25 25 25] + [25 25 25 25 25] + [25 25 25 25 25]] + + """ + + def __init__(self): + """Initialize the class.""" + self.version = None + self.GridCornerUL = None + self.GridCornerUR = None + self.GridCornerLR = None + self.GridCornerLL = None + self.DatHeader = None + self.Algorithm = None + self.AlgorithmParameters = None + self.NumberCells = None + self.intensities = None + self.stdevs = None + self.npix = None + self.nrows = None + self.ncols = None + self.nmask = None + self.mask = None + self.noutliers = None + self.outliers = None + self.modified = None + + +def read(handle, version=None): + """Read Affymetrix CEL file and return Record object. + + CEL files format versions 3 and 4 are supported. + Please specify the CEL file format as 3 or 4 if known for the version + argument. If the version number is not specified, the parser will attempt + to detect the version from the file contents. + + The Record object returned by this function stores the intensities from + the CEL file in record.intensities. + Currently, record.mask and record.outliers are not set in when parsing + version 4 CEL files. + + Example Usage: + + >>> from Bio.Affy import CelFile + >>> with open("Affy/affy_v3_example.CEL") as handle: + ... record = CelFile.read(handle) + ... + >>> record.version == 3 + True + >>> print("%i by %i array" % record.intensities.shape) + 5 by 5 array + + >>> with open("Affy/affy_v4_example.CEL", "rb") as handle: + ... record = CelFile.read(handle, version=4) + ... + >>> record.version == 4 + True + >>> print("%i by %i array" % record.intensities.shape) + 5 by 5 array + + """ + try: + data = handle.read(0) + except AttributeError: + raise ValueError("handle should be a file handle") from None + data = handle.read(4) + if not data: + raise ValueError("Empty file.") + if data == b"[CEL": + raise ValueError("CEL file in version 3 format should be opened in text mode") + if data == "[CEL": + # Version 3 format. Continue to read the header here before passing + # control to _read_v3 to avoid having to seek to the beginning of + # the file. + data += next(handle) + if data.strip() != "[CEL]": + raise ValueError("Failed to parse Affy Version 3 CEL file.") + line = next(handle) + keyword, value = line.split("=", 1) + if keyword != "Version": + raise ValueError("Failed to parse Affy Version 3 CEL file.") + version = int(value) + if version != 3: + raise ValueError("Incorrect version number in Affy Version 3 CEL file.") + return _read_v3(handle) + try: + magicNumber = struct.unpack("= 0: + min_max_pixel_intensity, filename = value[:i].split() + record.DatHeader["filename"] = filename + assert min_max_pixel_intensity[0] == "[" + assert min_max_pixel_intensity[-1] == "]" + ( + min_pixel_intensity, + max_pixel_intensity, + ) = min_max_pixel_intensity[1:-1].split("..") + record.DatHeader["min-pixel_intensity"] = int( + min_pixel_intensity + ) + record.DatHeader["max-pixel_intensity"] = int( + max_pixel_intensity + ) + value = value[i + 1 :] + index = 0 + field = value[index : index + 9] + if field[:4] != "CLS=" or field[8] != " ": + raise ValueError( + "Field does not start with 'CLS=' or have a blank space at position 8" + ) + record.DatHeader["CLS"] = int(field[4:8]) + index += 9 + field = value[index : index + 9] + if field[:4] != "RWS=" or field[8] != " ": + raise ValueError( + "Field does not start with 'RWS=' or have a blank space at position 8" + ) + record.DatHeader["RWS"] = int(field[4:8]) + index += 9 + field = value[index : index + 7] + if field[:4] != "XIN=" or field[6] != " ": + raise ValueError( + "Field does not start with 'XIN=' or have a blank space at position 6" + ) + record.DatHeader["XIN"] = int(field[4:6]) + index += 7 + field = value[index : index + 7] + if field[:4] != "YIN=" or field[6] != " ": + raise ValueError( + "Field does not start with 'YIN=' or have a blank space at poition 6" + ) + record.DatHeader["YIN"] = int(field[4:6]) + index += 7 + field = value[index : index + 6] + if field[:3] != "VE=" or field[5] != " ": + raise ValueError( + "Field does not start with 'VE=' or have a blank space at position 5" + ) + record.DatHeader["VE"] = int(field[3:5]) + index += 6 + field = value[index : index + 7] + if field[6] != " ": + raise ValueError( + "Field value for position 6 isn't a blank space" + ) + temperature = field[:6].strip() + if temperature: + record.DatHeader["temperature"] = int(temperature) + else: + record.DatHeader["temperature"] = None + index += 7 + field = value[index : index + 4] + if not field.endswith(" "): + raise ValueError("Field doesn't end with a blank space") + record.DatHeader["laser-power"] = float(field) + index += 4 + field = value[index : index + 18] + if field[8] != " ": + raise ValueError( + "Field value for position 8 isn't a blank space" + ) + record.DatHeader["scan-date"] = field[:8] + if field[17] != " ": + raise ValueError( + "Field value for position 17 isn't a blank space" + ) + record.DatHeader["scan-date"] = field[:8] + record.DatHeader["scan-time"] = field[9:17] + index += 18 + value = value[index:] + subfields = value.split("\x14") + if len(subfields) != 12: + ValueError("Subfields length isn't 12") + subfield = subfields[0] + try: + scanner_id, scanner_type = subfield.split() + except ValueError: + scanner_id = subfield.strip() + else: + record.DatHeader["scanner-type"] = scanner_type + record.DatHeader["scanner-id"] = scanner_id + record.DatHeader["array-type"] = subfields[2].strip() + field = subfields[7].strip() + if field: + record.DatHeader["filter-wavelength"] = int(field) + field = subfields[8].strip() + if field: + record.DatHeader["arc-radius"] = float(field) + field = subfields[9].strip() + if field: + record.DatHeader["laser-spotsize"] = float(field) + field = subfields[10].strip() + if field: + record.DatHeader["pixel-size"] = float(field) + field = subfields[11].strip() + if field: + record.DatHeader["image-orientation"] = int(field) + elif key == "Algorithm": + record.Algorithm = value + elif key == "AlgorithmParameters": + parameters = value.split(";") + values = {} + for parameter in parameters: + key, value = parameter.split(":", 1) + if key in ( + "Percentile", + "CellMargin", + "FullFeatureWidth", + "FullFeatureHeight", + "PoolWidthExtenstion", + "PoolHeightExtension", + "NumPixelsToUse", + "ExtendPoolWidth", + "ExtendPoolHeight", + "OutlierRatioLowPercentile", + "OutlierRatioHighPercentile", + "HalfCellRowsDivisor", + "HalfCellRowsRemainder", + "HighCutoff", + "LowCutoff", + "featureRows", + "featureColumns", + ): + values[key] = int(value) + elif key in ( + "OutlierHigh", + "OutlierLow", + "StdMult", + "PercentileSpread", + "PairCutoff", + "featureWidth", + "featureHeight", + ): + values[key] = float(value) + elif key in ( + "FixedCellSize", + "IgnoreOutliersInShiftRows", + "FeatureExtraction", + "UseSubgrids", + "RandomizePixels", + "ImageCalibration", + "IgnoreShiftRowOutliers", + ): + if value == "TRUE": + value = True + elif value == "FALSE": + value = False + else: + raise ValueError("Unexpected boolean value") + values[key] = value + elif key in ( + "AlgVersion", + "ErrorBasis", + "CellIntensityCalculationType", + ): + values[key] = value + else: + raise ValueError("Unexpected tag in AlgorithmParameters") + record.AlgorithmParameters = values + elif section == "INTENSITY": + if line.startswith("NumberCells="): + key, value = line.split("=", 1) + record.NumberCells = int(value) + elif line.startswith("CellHeader="): + key, value = line.split("=", 1) + if value.split() != ["X", "Y", "MEAN", "STDV", "NPIXELS"]: + raise ParserError( + "Unexpected CellHeader in INTENSITY " + "section CEL version 3 file" + ) + else: + words = line.split() + y = int(words[0]) + x = int(words[1]) + record.intensities[x, y] = float(words[2]) + record.stdevs[x, y] = float(words[3]) + record.npix[x, y] = int(words[4]) + elif section == "MASKS": + if line.startswith("NumberCells="): + key, value = line.split("=", 1) + record.nmask = int(value) + elif line.startswith("CellHeader="): + key, value = line.split("=", 1) + if value.split() != ["X", "Y"]: + raise ParserError( + "Unexpected CellHeader in MASKS " + "section in CEL version 3 file" + ) + else: + words = line.split() + y = int(words[0]) + x = int(words[1]) + record.mask[x, y] = True + elif section == "OUTLIERS": + if line.startswith("NumberCells="): + key, value = line.split("=", 1) + record.noutliers = int(value) + elif line.startswith("CellHeader="): + key, value = line.split("=", 1) + if value.split() != ["X", "Y"]: + raise ParserError( + "Unexpected CellHeader in OUTLIERS " + "section in CEL version 3 file" + ) + else: + words = line.split() + y = int(words[0]) + x = int(words[1]) + record.outliers[x, y] = True + elif section == "MODIFIED": + if line.startswith("NumberCells="): + key, value = line.split("=", 1) + record.nmodified = int(value) + elif line.startswith("CellHeader="): + key, value = line.split("=", 1) + if value.split() != ["X", "Y", "ORIGMEAN"]: + raise ParserError( + "Unexpected CellHeader in MODIFIED " + "section in CEL version 3 file" + ) + else: + words = line.split() + y = int(words[0]) + x = int(words[1]) + record.modified[x, y] = float(words[2]) + return record + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5871430793f3b9dadcfb860038675fc269c61230 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/__init__.py @@ -0,0 +1,6 @@ +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Deal with Affymetrix related data such as cel files.""" diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/__pycache__/CelFile.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/__pycache__/CelFile.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59209acd635e5ffb2dfa8082bbb9f9c2658b7741 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/__pycache__/CelFile.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c35993c850a4a23979896e29b8fbeb0703a004f Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/AlignInfo.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/AlignInfo.py new file mode 100644 index 0000000000000000000000000000000000000000..22db803752a813285de8aa5a1194aa97ab253bd6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/AlignInfo.py @@ -0,0 +1,54 @@ +# Copyright 2000 Brad Chapman. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Extract information from alignment objects. + +In order to try and avoid huge alignment objects with tons of functions, +functions which return summary type information about alignments should +be put into classes in this module. +""" + +import warnings + +from Bio import BiopythonDeprecationWarning + + +class SummaryInfo: + """Calculate summary info about the alignment. (DEPRECATED) + + This class should be used to calculate information summarizing the + results of an alignment. This may either be straight consensus info + or more complicated things. + """ + + def __init__(self, alignment): + """Initialize with the alignment to calculate information on. + + ic_vector attribute. A list of ic content for each column number. + """ + warnings.warn( + """\ +The class SummaryInfo has been deprecated. Instead of + +>>> align_info = AlignInfo.SummaryInfo(msa) +>>> sequence = align_info.get_column(1) + +please use + +>>> alignment = msa.alignment # to get a new-style Alignment object +>>> sequence = alignment[:, 1] + +Here, `msa` is a MultipleSeqAlignment object and `alignment` is an +`Alignment` object.""", + BiopythonDeprecationWarning, + ) + self.alignment = alignment + self.ic_vector = [] + + def get_column(self, col): + """Return column of alignment.""" + # TODO - Deprecate this and implement slicing? + return self.alignment[:, col] diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..027b8fb008895f1145be70e77001e4322f7f44ce --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__init__.py @@ -0,0 +1,4967 @@ +# Copyright 2000, 2004 by Brad Chapman. +# Revisions copyright 2010-2013, 2015-2018 by Peter Cock. +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Code for dealing with sequence alignments. + +One of the most important things in this module is the MultipleSeqAlignment +class, used in the Bio.AlignIO module. + +""" + +import copy +import importlib +import numbers +import sys +import types +import warnings +from abc import ABC +from abc import abstractmethod +from itertools import zip_longest + +try: + import numpy as np +except ImportError: + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Please install NumPy if you want to use Bio.Align. See http://www.numpy.org/" + ) from None + +from Bio import BiopythonDeprecationWarning +from Bio.Align import _aligncore # type: ignore +from Bio.Align import _codonaligner # type: ignore +from Bio.Align import _pairwisealigner # type: ignore +from Bio.Align import _alignmentcounts # type: ignore +from Bio.Align import substitution_matrices +from Bio.Data import CodonTable +from Bio.Seq import MutableSeq +from Bio.Seq import reverse_complement +from Bio.Seq import Seq +from Bio.Seq import translate +from Bio.Seq import UndefinedSequenceError +from Bio.Seq import SequenceDataAbstractBaseClass +from Bio.SeqRecord import _RestrictedDict +from Bio.SeqRecord import SeqRecord + + +# Import errors may occur here if a compiled _pairwisealigner.c file or +# compiled _codonaligner.c file (_pairwisealigner.pyd or _pairwisealigner.so, +# or _codonaligner.pyd or _codonaligner.so) is missing or if the user is +# importing from within the Biopython source tree, see PR #2007: +# https://github.com/biopython/biopython/pull/2007 + + +class MultipleSeqAlignment: + """Represents a classical multiple sequence alignment (MSA). + + By this we mean a collection of sequences (usually shown as rows) which + are all the same length (usually with gap characters for insertions or + padding). The data can then be regarded as a matrix of letters, with well + defined columns. + + You would typically create an MSA by loading an alignment file with the + AlignIO module: + + >>> from Bio import AlignIO + >>> align = AlignIO.read("Clustalw/opuntia.aln", "clustal") + >>> print(align) + Alignment with 7 rows and 156 columns + TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191 + TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191 + TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191 + TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191 + TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191 + TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191 + TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191 + + In some respects you can treat these objects as lists of SeqRecord objects, + each representing a row of the alignment. Iterating over an alignment gives + the SeqRecord object for each row: + + >>> len(align) + 7 + >>> for record in align: + ... print("%s %i" % (record.id, len(record))) + ... + gi|6273285|gb|AF191659.1|AF191 156 + gi|6273284|gb|AF191658.1|AF191 156 + gi|6273287|gb|AF191661.1|AF191 156 + gi|6273286|gb|AF191660.1|AF191 156 + gi|6273290|gb|AF191664.1|AF191 156 + gi|6273289|gb|AF191663.1|AF191 156 + gi|6273291|gb|AF191665.1|AF191 156 + + You can also access individual rows as SeqRecord objects via their index: + + >>> print(align[0].id) + gi|6273285|gb|AF191659.1|AF191 + >>> print(align[-1].id) + gi|6273291|gb|AF191665.1|AF191 + + And extract columns as strings: + + >>> print(align[:, 1]) + AAAAAAA + + Or, take just the first ten columns as a sub-alignment: + + >>> print(align[:, :10]) + Alignment with 7 rows and 10 columns + TATACATTAA gi|6273285|gb|AF191659.1|AF191 + TATACATTAA gi|6273284|gb|AF191658.1|AF191 + TATACATTAA gi|6273287|gb|AF191661.1|AF191 + TATACATAAA gi|6273286|gb|AF191660.1|AF191 + TATACATTAA gi|6273290|gb|AF191664.1|AF191 + TATACATTAA gi|6273289|gb|AF191663.1|AF191 + TATACATTAA gi|6273291|gb|AF191665.1|AF191 + + Combining this alignment slicing with alignment addition allows you to + remove a section of the alignment. For example, taking just the first + and last ten columns: + + >>> print(align[:, :10] + align[:, -10:]) + Alignment with 7 rows and 20 columns + TATACATTAAGTGTACCAGA gi|6273285|gb|AF191659.1|AF191 + TATACATTAAGTGTACCAGA gi|6273284|gb|AF191658.1|AF191 + TATACATTAAGTGTACCAGA gi|6273287|gb|AF191661.1|AF191 + TATACATAAAGTGTACCAGA gi|6273286|gb|AF191660.1|AF191 + TATACATTAAGTGTACCAGA gi|6273290|gb|AF191664.1|AF191 + TATACATTAAGTATACCAGA gi|6273289|gb|AF191663.1|AF191 + TATACATTAAGTGTACCAGA gi|6273291|gb|AF191665.1|AF191 + + Note - This object does NOT attempt to model the kind of alignments used + in next generation sequencing with multiple sequencing reads which are + much shorter than the alignment, and where there is usually a consensus or + reference sequence with special status. + """ + + def __init__( + self, records, alphabet=None, annotations=None, column_annotations=None + ): + """Initialize a new MultipleSeqAlignment object. + + Arguments: + - records - A list (or iterator) of SeqRecord objects, whose + sequences are all the same length. This may be an empty + list. + - alphabet - For backward compatibility only; its value should always + be None. + - annotations - Information about the whole alignment (dictionary). + - column_annotations - Per column annotation (restricted dictionary). + This holds Python sequences (lists, strings, tuples) + whose length matches the number of columns. A typical + use would be a secondary structure consensus string. + + You would normally load a MSA from a file using Bio.AlignIO, but you + can do this from a list of SeqRecord objects too: + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import MultipleSeqAlignment + >>> a = SeqRecord(Seq("AAAACGT"), id="Alpha") + >>> b = SeqRecord(Seq("AAA-CGT"), id="Beta") + >>> c = SeqRecord(Seq("AAAAGGT"), id="Gamma") + >>> align = MultipleSeqAlignment([a, b, c], + ... annotations={"tool": "demo"}, + ... column_annotations={"stats": "CCCXCCC"}) + >>> print(align) + Alignment with 3 rows and 7 columns + AAAACGT Alpha + AAA-CGT Beta + AAAAGGT Gamma + >>> align.annotations + {'tool': 'demo'} + >>> align.column_annotations + {'stats': 'CCCXCCC'} + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + + self._records = [] + if records: + self.extend(records) + + # Annotations about the whole alignment + if annotations is None: + annotations = {} + elif not isinstance(annotations, dict): + raise TypeError("annotations argument should be a dict") + self.annotations = annotations + + # Annotations about each column of the alignment + if column_annotations is None: + column_annotations = {} + # Handle this via the property set function which will validate it + self.column_annotations = column_annotations + + def _set_per_column_annotations(self, value): + if not isinstance(value, dict): + raise TypeError( + "The per-column-annotations should be a (restricted) dictionary." + ) + # Turn this into a restricted-dictionary (and check the entries) + if len(self): + # Use the standard method to get the length + expected_length = self.get_alignment_length() + self._per_col_annotations = _RestrictedDict(length=expected_length) + self._per_col_annotations.update(value) + else: + # Bit of a problem case... number of columns is undefined + self._per_col_annotations = None + if value: + raise ValueError( + "Can't set per-column-annotations without an alignment" + ) + + def _get_per_column_annotations(self): + if self._per_col_annotations is None: + # This happens if empty at initialisation + if len(self): + # Use the standard method to get the length + expected_length = self.get_alignment_length() + else: + # Should this raise an exception? Compare SeqRecord behaviour... + expected_length = 0 + self._per_col_annotations = _RestrictedDict(length=expected_length) + return self._per_col_annotations + + column_annotations = property( + fget=_get_per_column_annotations, + fset=_set_per_column_annotations, + doc="""Dictionary of per-letter-annotation for the sequence.""", + ) + + def _str_line(self, record, length=50): + """Return a truncated string representation of a SeqRecord (PRIVATE). + + This is a PRIVATE function used by the __str__ method. + """ + if record.seq.__class__.__name__ == "CodonSeq": + if len(record.seq) <= length: + return f"{record.seq} {record.id}" + else: + return "%s...%s %s" % ( + record.seq[: length - 3], + record.seq[-3:], + record.id, + ) + else: + if len(record.seq) <= length: + return f"{record.seq} {record.id}" + else: + return "%s...%s %s" % ( + record.seq[: length - 6], + record.seq[-3:], + record.id, + ) + + def __str__(self): + """Return a multi-line string summary of the alignment. + + This output is intended to be readable, but large alignments are + shown truncated. A maximum of 20 rows (sequences) and 50 columns + are shown, with the record identifiers. This should fit nicely on a + single screen. e.g. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import MultipleSeqAlignment + >>> a = SeqRecord(Seq("ACTGCTAGCTAG"), id="Alpha") + >>> b = SeqRecord(Seq("ACT-CTAGCTAG"), id="Beta") + >>> c = SeqRecord(Seq("ACTGCTAGATAG"), id="Gamma") + >>> align = MultipleSeqAlignment([a, b, c]) + >>> print(align) + Alignment with 3 rows and 12 columns + ACTGCTAGCTAG Alpha + ACT-CTAGCTAG Beta + ACTGCTAGATAG Gamma + + See also the alignment's format method. + """ + rows = len(self._records) + lines = [ + "Alignment with %i rows and %i columns" + % (rows, self.get_alignment_length()) + ] + if rows <= 20: + lines.extend(self._str_line(rec) for rec in self._records) + else: + lines.extend(self._str_line(rec) for rec in self._records[:18]) + lines.append("...") + lines.append(self._str_line(self._records[-1])) + return "\n".join(lines) + + def __repr__(self): + """Return a representation of the object for debugging. + + The representation cannot be used with eval() to recreate the object, + which is usually possible with simple python objects. For example: + + + + The hex string is the memory address of the object, see help(id). + This provides a simple way to visually distinguish alignments of + the same size. + """ + # A doctest for __repr__ would be nice, but __class__ comes out differently + # if run via the __main__ trick. + return "<%s instance (%i records of length %i) at %x>" % ( + self.__class__, + len(self._records), + self.get_alignment_length(), + id(self), + ) + # This version is useful for doing eval(repr(alignment)), + # but it can be VERY long: + # return "%s(%r)" \ + # % (self.__class__, self._records) + + def __format__(self, format_spec): + """Return the alignment as a string in the specified file format. + + The format should be a lower case string supported as an output + format by Bio.AlignIO (such as "fasta", "clustal", "phylip", + "stockholm", etc), which is used to turn the alignment into a + string. + + e.g. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import MultipleSeqAlignment + >>> a = SeqRecord(Seq("ACTGCTAGCTAG"), id="Alpha", description="") + >>> b = SeqRecord(Seq("ACT-CTAGCTAG"), id="Beta", description="") + >>> c = SeqRecord(Seq("ACTGCTAGATAG"), id="Gamma", description="") + >>> align = MultipleSeqAlignment([a, b, c]) + >>> print(format(align, "fasta")) + >Alpha + ACTGCTAGCTAG + >Beta + ACT-CTAGCTAG + >Gamma + ACTGCTAGATAG + + >>> print(format(align, "phylip")) + 3 12 + Alpha ACTGCTAGCT AG + Beta ACT-CTAGCT AG + Gamma ACTGCTAGAT AG + + """ + if format_spec: + from io import StringIO + + from Bio import AlignIO + + handle = StringIO() + AlignIO.write([self], handle, format_spec) + return handle.getvalue() + else: + # Follow python convention and default to using __str__ + return str(self) + + def __iter__(self): + """Iterate over alignment rows as SeqRecord objects. + + e.g. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import MultipleSeqAlignment + >>> a = SeqRecord(Seq("ACTGCTAGCTAG"), id="Alpha") + >>> b = SeqRecord(Seq("ACT-CTAGCTAG"), id="Beta") + >>> c = SeqRecord(Seq("ACTGCTAGATAG"), id="Gamma") + >>> align = MultipleSeqAlignment([a, b, c]) + >>> for record in align: + ... print(record.id) + ... print(record.seq) + ... + Alpha + ACTGCTAGCTAG + Beta + ACT-CTAGCTAG + Gamma + ACTGCTAGATAG + """ + return iter(self._records) + + def __len__(self): + """Return the number of sequences in the alignment. + + Use len(alignment) to get the number of sequences (i.e. the number of + rows), and alignment.get_alignment_length() to get the length of the + longest sequence (i.e. the number of columns). + + This is easy to remember if you think of the alignment as being like a + list of SeqRecord objects. + """ + return len(self._records) + + def get_alignment_length(self): + """Return the maximum length of the alignment. + + All objects in the alignment should (hopefully) have the same + length. This function will go through and find this length + by finding the maximum length of sequences in the alignment. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import MultipleSeqAlignment + >>> a = SeqRecord(Seq("ACTGCTAGCTAG"), id="Alpha") + >>> b = SeqRecord(Seq("ACT-CTAGCTAG"), id="Beta") + >>> c = SeqRecord(Seq("ACTGCTAGATAG"), id="Gamma") + >>> align = MultipleSeqAlignment([a, b, c]) + >>> align.get_alignment_length() + 12 + + If you want to know the number of sequences in the alignment, + use len(align) instead: + + >>> len(align) + 3 + + """ + max_length = 0 + + for record in self._records: + if len(record.seq) > max_length: + max_length = len(record.seq) + + return max_length + + def extend(self, records): + """Add more SeqRecord objects to the alignment as rows. + + They must all have the same length as the original alignment. For + example, + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import MultipleSeqAlignment + >>> a = SeqRecord(Seq("AAAACGT"), id="Alpha") + >>> b = SeqRecord(Seq("AAA-CGT"), id="Beta") + >>> c = SeqRecord(Seq("AAAAGGT"), id="Gamma") + >>> d = SeqRecord(Seq("AAAACGT"), id="Delta") + >>> e = SeqRecord(Seq("AAA-GGT"), id="Epsilon") + + First we create a small alignment (three rows): + + >>> align = MultipleSeqAlignment([a, b, c]) + >>> print(align) + Alignment with 3 rows and 7 columns + AAAACGT Alpha + AAA-CGT Beta + AAAAGGT Gamma + + Now we can extend this alignment with another two rows: + + >>> align.extend([d, e]) + >>> print(align) + Alignment with 5 rows and 7 columns + AAAACGT Alpha + AAA-CGT Beta + AAAAGGT Gamma + AAAACGT Delta + AAA-GGT Epsilon + + Because the alignment object allows iteration over the rows as + SeqRecords, you can use the extend method with a second alignment + (provided its sequences have the same length as the original alignment). + """ + if len(self): + # Use the standard method to get the length + expected_length = self.get_alignment_length() + else: + # Take the first record's length + records = iter(records) # records arg could be list or iterator + try: + rec = next(records) + except StopIteration: + # Special case, no records + return + expected_length = len(rec) + self._append(rec, expected_length) + # Can now setup the per-column-annotations as well, set to None + # while missing the length: + self.column_annotations = {} + # Now continue to the rest of the records as usual + + for rec in records: + self._append(rec, expected_length) + + def append(self, record): + """Add one more SeqRecord object to the alignment as a new row. + + This must have the same length as the original alignment (unless this is + the first record). + + >>> from Bio import AlignIO + >>> align = AlignIO.read("Clustalw/opuntia.aln", "clustal") + >>> print(align) + Alignment with 7 rows and 156 columns + TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191 + TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191 + TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191 + TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191 + TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191 + TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191 + TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191 + >>> len(align) + 7 + + We'll now construct a dummy record to append as an example: + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> dummy = SeqRecord(Seq("N"*156), id="dummy") + + Now append this to the alignment, + + >>> align.append(dummy) + >>> print(align) + Alignment with 8 rows and 156 columns + TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191 + TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191 + TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191 + TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191 + TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191 + TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191 + TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191 + NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN...NNN dummy + >>> len(align) + 8 + + """ + if self._records: + self._append(record, self.get_alignment_length()) + else: + self._append(record) + + def _append(self, record, expected_length=None): + """Validate and append a record (PRIVATE).""" + if not isinstance(record, SeqRecord): + raise TypeError("New sequence is not a SeqRecord object") + + # Currently the get_alignment_length() call is expensive, so we need + # to avoid calling it repeatedly for __init__ and extend, hence this + # private _append method + if expected_length is not None and len(record) != expected_length: + # TODO - Use the following more helpful error, but update unit tests + # raise ValueError("New sequence is not of length %i" + # % self.get_alignment_length()) + raise ValueError("Sequences must all be the same length") + + self._records.append(record) + + def __add__(self, other): + """Combine two alignments with the same number of rows by adding them. + + If you have two multiple sequence alignments (MSAs), there are two ways to think + about adding them - by row or by column. Using the extend method adds by row. + Using the addition operator adds by column. For example, + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import MultipleSeqAlignment + >>> a1 = SeqRecord(Seq("AAAAC"), id="Alpha") + >>> b1 = SeqRecord(Seq("AAA-C"), id="Beta") + >>> c1 = SeqRecord(Seq("AAAAG"), id="Gamma") + >>> a2 = SeqRecord(Seq("GT"), id="Alpha") + >>> b2 = SeqRecord(Seq("GT"), id="Beta") + >>> c2 = SeqRecord(Seq("GT"), id="Gamma") + >>> left = MultipleSeqAlignment([a1, b1, c1], + ... annotations={"tool": "demo", "name": "start"}, + ... column_annotations={"stats": "CCCXC"}) + >>> right = MultipleSeqAlignment([a2, b2, c2], + ... annotations={"tool": "demo", "name": "end"}, + ... column_annotations={"stats": "CC"}) + + Now, let's look at these two alignments: + + >>> print(left) + Alignment with 3 rows and 5 columns + AAAAC Alpha + AAA-C Beta + AAAAG Gamma + >>> print(right) + Alignment with 3 rows and 2 columns + GT Alpha + GT Beta + GT Gamma + + And add them: + + >>> combined = left + right + >>> print(combined) + Alignment with 3 rows and 7 columns + AAAACGT Alpha + AAA-CGT Beta + AAAAGGT Gamma + + For this to work, both alignments must have the same number of records (here + they both have 3 rows): + + >>> len(left) + 3 + >>> len(right) + 3 + >>> len(combined) + 3 + + The individual rows are SeqRecord objects, and these can be added together. Refer + to the SeqRecord documentation for details of how the annotation is handled. This + example is a special case in that both original alignments shared the same names, + meaning when the rows are added they also get the same name. + + Any common annotations are preserved, but differing annotation is lost. This is + the same behaviour used in the SeqRecord annotations and is designed to prevent + accidental propagation of inappropriate values: + + >>> combined.annotations + {'tool': 'demo'} + + Similarly any common per-column-annotations are combined: + + >>> combined.column_annotations + {'stats': 'CCCXCCC'} + + """ + if not isinstance(other, MultipleSeqAlignment): + raise NotImplementedError + if len(self) != len(other): + raise ValueError( + "When adding two alignments they must have the same length" + " (i.e. same number of rows)" + ) + merged = (left + right for left, right in zip(self, other)) + # Take any common annotation: + annotations = {} + for k, v in self.annotations.items(): + if k in other.annotations and other.annotations[k] == v: + annotations[k] = v + column_annotations = {} + for k, v in self.column_annotations.items(): + if k in other.column_annotations: + column_annotations[k] = v + other.column_annotations[k] + return MultipleSeqAlignment( + merged, annotations=annotations, column_annotations=column_annotations + ) + + def __getitem__(self, index): + """Access part of the alignment. + + Depending on the indices, you can get a SeqRecord object + (representing a single row), a Seq object (for a single column), + a string (for a single character) or another alignment + (representing some part or all of the alignment). + + align[r,c] gives a single character as a string + align[r] gives a row as a SeqRecord + align[r,:] gives a row as a SeqRecord + align[:,c] gives a column as a Seq + + align[:] and align[:,:] give a copy of the alignment + + Anything else gives a sub alignment, e.g. + align[0:2] or align[0:2,:] uses only row 0 and 1 + align[:,1:3] uses only columns 1 and 2 + align[0:2,1:3] uses only rows 0 & 1 and only cols 1 & 2 + + We'll use the following example alignment here for illustration: + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import MultipleSeqAlignment + >>> a = SeqRecord(Seq("AAAACGT"), id="Alpha") + >>> b = SeqRecord(Seq("AAA-CGT"), id="Beta") + >>> c = SeqRecord(Seq("AAAAGGT"), id="Gamma") + >>> d = SeqRecord(Seq("AAAACGT"), id="Delta") + >>> e = SeqRecord(Seq("AAA-GGT"), id="Epsilon") + >>> align = MultipleSeqAlignment([a, b, c, d, e]) + + You can access a row of the alignment as a SeqRecord using an integer + index (think of the alignment as a list of SeqRecord objects here): + + >>> first_record = align[0] + >>> print("%s %s" % (first_record.id, first_record.seq)) + Alpha AAAACGT + >>> last_record = align[-1] + >>> print("%s %s" % (last_record.id, last_record.seq)) + Epsilon AAA-GGT + + You can also access use python's slice notation to create a sub-alignment + containing only some of the SeqRecord objects: + + >>> sub_alignment = align[2:5] + >>> print(sub_alignment) + Alignment with 3 rows and 7 columns + AAAAGGT Gamma + AAAACGT Delta + AAA-GGT Epsilon + + This includes support for a step, i.e. align[start:end:step], which + can be used to select every second sequence: + + >>> sub_alignment = align[::2] + >>> print(sub_alignment) + Alignment with 3 rows and 7 columns + AAAACGT Alpha + AAAAGGT Gamma + AAA-GGT Epsilon + + Or to get a copy of the alignment with the rows in reverse order: + + >>> rev_alignment = align[::-1] + >>> print(rev_alignment) + Alignment with 5 rows and 7 columns + AAA-GGT Epsilon + AAAACGT Delta + AAAAGGT Gamma + AAA-CGT Beta + AAAACGT Alpha + + You can also use two indices to specify both rows and columns. Using simple + integers gives you the entry as a single character string. e.g. + + >>> align[3, 4] + 'C' + + This is equivalent to: + + >>> align[3][4] + 'C' + + or: + + >>> align[3].seq[4] + 'C' + + To get a single column (as a string) use this syntax: + + >>> align[:, 4] + 'CCGCG' + + Or, to get part of a column, + + >>> align[1:3, 4] + 'CG' + + However, in general you get a sub-alignment, + + >>> print(align[1:5, 3:6]) + Alignment with 4 rows and 3 columns + -CG Beta + AGG Gamma + ACG Delta + -GG Epsilon + + This should all seem familiar to anyone who has used the NumPy + array or matrix objects. + """ + if isinstance(index, int): + # e.g. result = align[x] + # Return a SeqRecord + return self._records[index] + elif isinstance(index, slice): + # e.g. sub_align = align[i:j:k] + new = MultipleSeqAlignment(self._records[index]) + if self.column_annotations and len(new) == len(self): + # All rows kept (although could have been reversed) + # Preserve the column annotations too, + for k, v in self.column_annotations.items(): + new.column_annotations[k] = v + return new + elif len(index) != 2: + raise TypeError("Invalid index type.") + + # Handle double indexing + row_index, col_index = index + if isinstance(row_index, int): + # e.g. row_or_part_row = align[6, 1:4], gives a SeqRecord + return self._records[row_index][col_index] + elif isinstance(col_index, int): + # e.g. col_or_part_col = align[1:5, 6], gives a string + return "".join(rec[col_index] for rec in self._records[row_index]) + else: + # e.g. sub_align = align[1:4, 5:7], gives another alignment + new = MultipleSeqAlignment( + rec[col_index] for rec in self._records[row_index] + ) + if self.column_annotations and len(new) == len(self): + # All rows kept (although could have been reversed) + # Preserve the column annotations too, + for k, v in self.column_annotations.items(): + new.column_annotations[k] = v[col_index] + return new + + def __delitem__(self, index): + """Delete SeqRecord by index or multiple SeqRecords by slice.""" + if not isinstance(index, int) and not isinstance(index, slice): + raise TypeError("Invalid index type.") + + del self._records[index] + + def sort(self, key=None, reverse=False): + """Sort the rows (SeqRecord objects) of the alignment in place. + + This sorts the rows alphabetically using the SeqRecord object id by + default. The sorting can be controlled by supplying a key function + which must map each SeqRecord to a sort value. + + This is useful if you want to add two alignments which use the same + record identifiers, but in a different order. For example, + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import MultipleSeqAlignment + >>> align1 = MultipleSeqAlignment([ + ... SeqRecord(Seq("ACGT"), id="Human"), + ... SeqRecord(Seq("ACGG"), id="Mouse"), + ... SeqRecord(Seq("ACGC"), id="Chicken"), + ... ]) + >>> align2 = MultipleSeqAlignment([ + ... SeqRecord(Seq("CGGT"), id="Mouse"), + ... SeqRecord(Seq("CGTT"), id="Human"), + ... SeqRecord(Seq("CGCT"), id="Chicken"), + ... ]) + + If you simple try and add these without sorting, you get this: + + >>> print(align1 + align2) + Alignment with 3 rows and 8 columns + ACGTCGGT + ACGGCGTT + ACGCCGCT Chicken + + Consult the SeqRecord documentation which explains why you get a + default value when annotation like the identifier doesn't match up. + However, if we sort the alignments first, then add them we get the + desired result: + + >>> align1.sort() + >>> align2.sort() + >>> print(align1 + align2) + Alignment with 3 rows and 8 columns + ACGCCGCT Chicken + ACGTCGTT Human + ACGGCGGT Mouse + + As an example using a different sort order, you could sort on the + GC content of each sequence. + + >>> from Bio.SeqUtils import gc_fraction + >>> print(align1) + Alignment with 3 rows and 4 columns + ACGC Chicken + ACGT Human + ACGG Mouse + >>> align1.sort(key = lambda record: gc_fraction(record.seq)) + >>> print(align1) + Alignment with 3 rows and 4 columns + ACGT Human + ACGC Chicken + ACGG Mouse + + There is also a reverse argument, so if you wanted to sort by ID + but backwards: + + >>> align1.sort(reverse=True) + >>> print(align1) + Alignment with 3 rows and 4 columns + ACGG Mouse + ACGT Human + ACGC Chicken + + """ + if key is None: + self._records.sort(key=lambda r: r.id, reverse=reverse) + else: + self._records.sort(key=key, reverse=reverse) + + @property + def substitutions(self): + """Return an Array with the number of substitutions of letters in the alignment. + + As an example, consider a multiple sequence alignment of three DNA sequences: + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import MultipleSeqAlignment + >>> seq1 = SeqRecord(Seq("ACGT"), id="seq1") + >>> seq2 = SeqRecord(Seq("A--A"), id="seq2") + >>> seq3 = SeqRecord(Seq("ACGT"), id="seq3") + >>> seq4 = SeqRecord(Seq("TTTC"), id="seq4") + >>> alignment = MultipleSeqAlignment([seq1, seq2, seq3, seq4]) + >>> print(alignment) + Alignment with 4 rows and 4 columns + ACGT seq1 + A--A seq2 + ACGT seq3 + TTTC seq4 + + >>> m = alignment.substitutions + >>> print(m) + A C G T + A 3.0 0.5 0.0 2.5 + C 0.5 1.0 0.0 2.0 + G 0.0 0.0 1.0 1.0 + T 2.5 2.0 1.0 1.0 + + + Note that the matrix is symmetric, with counts divided equally on both + sides of the diagonal. For example, the total number of substitutions + between A and T in the alignment is 3.5 + 3.5 = 7. + + Any weights associated with the sequences are taken into account when + calculating the substitution matrix. For example, given the following + multiple sequence alignment:: + + GTATC 0.5 + AT--C 0.8 + CTGTC 1.0 + + For the first column we have:: + + ('A', 'G') : 0.5 * 0.8 = 0.4 + ('C', 'G') : 0.5 * 1.0 = 0.5 + ('A', 'C') : 0.8 * 1.0 = 0.8 + + """ + letters = set.union(*(set(record.seq) for record in self)) + try: + letters.remove("-") + except KeyError: + pass + letters = "".join(sorted(letters)) + m = substitution_matrices.Array(letters, dims=2) + for rec_num1, alignment1 in enumerate(self): + seq1 = alignment1.seq + weight1 = alignment1.annotations.get("weight", 1.0) + for rec_num2, alignment2 in enumerate(self): + if rec_num1 == rec_num2: + break + seq2 = alignment2.seq + weight2 = alignment2.annotations.get("weight", 1.0) + for residue1, residue2 in zip(seq1, seq2): + if residue1 == "-": + continue + if residue2 == "-": + continue + m[(residue1, residue2)] += weight1 * weight2 + + m += m.transpose() + m /= 2.0 + + return m + + @property + def alignment(self): + """Return an Alignment object based on the MultipleSeqAlignment object. + + This makes a copy of each SeqRecord with a gap-less sequence. Any + future changes to the original records in the MultipleSeqAlignment will + not affect the new records in the Alignment. + """ + records = [copy.copy(record) for record in self._records] + if records: + lines = [bytes(record.seq) for record in records] + seqdata, coordinates = Alignment.parse_printed_alignment(lines) + for record, seqrow in zip(records, seqdata): + if record.letter_annotations: + indices = [i for i, c in enumerate(record.seq) if c != "-"] + letter_annotations = dict(record.letter_annotations) + record.letter_annotations.clear() + record.seq = Seq(seqrow) + for key, value in letter_annotations.items(): + if isinstance(value, str): + value = "".join([value[i] for i in indices]) + else: # list, tuple + cls = type(value) + value = cls(value[i] for i in indices) + letter_annotations[key] = value + record.letter_annotations = letter_annotations + else: + record.seq = Seq(seqrow) + alignment = Alignment(records, coordinates) + else: + alignment = Alignment([]) + alignment.annotations = self.annotations + alignment.column_annotations = self.column_annotations + return alignment + + +class Alignment: + """Represents a sequence alignment. + + An Alignment object has a `.sequences` attribute storing the sequences + (Seq, MutableSeq, SeqRecord, or string objects) that were aligned, as well + as a `.coordinates` attribute storing the sequence coordinates defining the + alignment as a NumPy array. + + Other commonly used attributes (which may or may not be present) are: + - annotations - A dictionary with annotations describing the + alignment; + - column_annotations - A dictionary with annotations describing each + column in the alignment; + - score - The alignment score. + """ + + @classmethod + def parse_printed_alignment(cls, lines): + """Infer the sequences and coordinates from a printed alignment. + + This method is primarily employed in Biopython's alignment parsers, + though it may be useful for other purposes. + + For an alignment consisting of N sequences, printed as N lines with + the same number of columns, where gaps are represented by dashes, + this method will calculate the sequence coordinates that define the + alignment. It returns the tuple (sequences, coordinates), where + sequences is the list of N sequences after removing the gaps, and + the coordinates is a 2D NumPy array of integers. Together, the + sequences and coordinates can be used to create an Alignment object. + + This is an example for the alignment of three sequences TAGGCATACGTG, + AACGTACGT, and ACGCATACTTG, with gaps in the second and third sequence. + Note that the input sequences are bytes objects. + + >>> from Bio.Align import Alignment + >>> from Bio.Seq import Seq + >>> lines = [b"TAGGCATACGTG", + ... b"AACG--TACGT-", + ... b"-ACGCATACTTG", + ... ] + >>> sequences, coordinates = Alignment.parse_printed_alignment(lines) + >>> sequences + [b'TAGGCATACGTG', b'AACGTACGT', b'ACGCATACTTG'] + >>> print(coordinates) + [[ 0 1 4 6 11 12] + [ 0 1 4 4 9 9] + [ 0 0 3 5 10 11]] + >>> sequences = [Seq(sequence) for sequence in sequences] + >>> sequences + [Seq('TAGGCATACGTG'), Seq('AACGTACGT'), Seq('ACGCATACTTG')] + >>> alignment = Alignment(sequences, coordinates) + >>> print(alignment) + 0 TAGGCATACGTG 12 + 0 AACG--TACGT- 9 + 0 -ACGCATACTTG 11 + + """ + parser = _aligncore.PrintedAlignmentParser(b"\0") + sequences = [] + for line in lines: + nbytes, sequence = parser.feed(line) + sequences.append(sequence) + shape = parser.shape + coordinates = np.empty(shape, np.intp) + parser.fill(coordinates) + return sequences, coordinates + + @classmethod + def from_alignments_with_same_reference( + cls, alignments: list["Alignment"] | tuple["Alignment"] + ) -> "Alignment": + """Create an Alignment from a list of alignments in which the first sequence is the same (reference sequence). + + This method combines multiple alignments into a single multiple sequence alignment. + All alignments must share the same reference sequence (ignoring gaps). + + Args: + alignments: A list or tuple of Alignment objects. + + Returns: + An Alignment object representing a multiple sequence alignment. + + Raises: + ValueError: If no alignments are provided or if the reference + sequences do not match across all alignments. + + Example 1: Basic Usage with Strings + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import PairwiseAligner, Alignment + >>> import numpy as np + + Consider the following reference and sequences: + >>> reference_str = "ACGT" + >>> seq1_str = "ACT" + >>> seq2_str = "ACGGT" + >>> seq3_str = "AT" + + To produce a pairwise alignment: + >>> aligner = PairwiseAligner() + >>> pwa = next(aligner.align(reference_str, seq1_str)) + + To produce a three sequence alignment: + >>> coords = np.array([ + ... [0, 1, 2, 3, 3, 4], + ... [0, 1, 2, 3, 4, 5], + ... [0, 1, 1, 1, 1, 2] + ... ]) + + >>> not_pwa = Alignment([reference_str, seq2_str, seq3_str], coords) + + The pairwise alignment would look like + >>> print(f"Reference: {pwa[0]}") + Reference: ACGT + >>> print(f"Seq1: {pwa[1]}") + Seq1: AC-T + + The three sequence alignment would look like + >>> str(not_pwa[0]) + 'ACG-T' + >>> str(not_pwa[1]) + 'ACGGT' + >>> str(not_pwa[2]) + 'A---T' + + Now, we can combine these alignments into a multiple sequence alignment: + >>> msa = Alignment.from_alignments_with_same_reference([pwa, not_pwa]) + >>> str(msa[0]) + 'ACG-T' + >>> str(msa[1]) + 'AC--T' + >>> str(msa[2]) + 'ACGGT' + >>> str(msa[3]) + 'A---T' + + Example 2: Using SeqRecord Objects with Metadata + Consider the following reference and sequences with metadata: + >>> reference_seqr = SeqRecord(Seq("ACGT"), id="reference", description="desc 1") + >>> seq1 = SeqRecord(Seq("ACGGT"), id="seq1", description="desc 2") + >>> seq2 = SeqRecord(Seq("AT"), id="seq2", description="desc 3") + + To produce pairwise alignments: + >>> aligner = PairwiseAligner() + >>> pwa1 = next(aligner.align(reference_seqr, seq1)) + >>> pwa2 = next(aligner.align(reference_seqr, seq2)) + + The msa retains the metadata from the original SeqRecord objects: + >>> msa = Alignment.from_alignments_with_same_reference([pwa1, pwa2]) + >>> print(msa.format("fasta")) + >reference desc 1 + ACG-T + >seq1 desc 2 + ACGGT + >seq2 desc 3 + A---T + + + """ + + if len(alignments) == 0: + raise ValueError("No pairwise alignments provided.") + + # Validate that all pairwise alignments share the same reference + first_seqs = [alignment.sequences[0] for alignment in alignments] + # Same length (all types of references) + if not all(len(first_seq) == len(first_seqs[0]) for first_seq in first_seqs): + raise ValueError("All reference sequences must have the same length.") + + # Same sequence (defined sequences only) + string_first_seqs = set() + for first_seq in first_seqs: + try: + # Extract Seq from SeqRecord + first_seq = first_seq.seq + except AttributeError: # Seq or string + pass + try: + # Convert Seq or string to uppercase string + string_first_seqs.add(str(first_seq).upper()) + except UndefinedSequenceError: + continue + + if len(string_first_seqs) > 1: + raise ValueError("All reference sequences must match (excluding gaps).") + + # Collect sequences + reference_seq = alignments[0].sequences[0] + other_sequences = [ + seq for alignment in alignments for seq in alignment.sequences[1:] + ] + sequences = [reference_seq] + other_sequences + + # Build per-query pairwise coordinate arrays of reference vs query. + paired_coordinates = [] + for alignment in alignments: + coords = alignment.coordinates + for row_index in range(1, coords.shape[0]): + paired_coordinates.append(coords[[0, row_index], :].transpose()) + + # Validate that reference coordinate start and end positions are the same + reference_starts = {c[0, 0] for c in paired_coordinates} + reference_ends = {c[-1, 0] for c in paired_coordinates} + if len(reference_starts) != 1 or len(reference_ends) != 1: + raise ValueError( + "Reference coordinates do not align consistently across pairwise alignments." + ) + + reference_position = reference_starts.pop() + # Create iterators for each pairwise coordinate array + coordinates = [iter(c) for c in paired_coordinates] + + msa_coordinates = [] + # Initialize positions and next_positions arrays + positions = np.array([next(c) for c in coordinates]) + next_positions = np.array([next(c) for c in coordinates]) + # Add initial positions + msa_coordinates.append([reference_position] + list(positions[:, 1])) + + while True: + # Iterate until all sequences are fully processed + if (next_positions == sys.maxsize).all(): + break + # For each sequence, determine the step size to the next reference position + target_steps = next_positions[:, 0] - reference_position + # Find the minimum positive step size + index = np.argmin(target_steps) + target_step = target_steps[index] + # For each sequence, determine the step size to the next non-reference position + query_steps = next_positions[:, 1] - positions[:, 1] + query_step = query_steps[index] + # Move the reference position forward to the next + reference_position += target_step + # Update positions and next_positions for the sequence with the minimum step + positions[index, :] = next_positions[index, :] + next_positions[index, :] = next(coordinates[index], sys.maxsize) + # If the reference and query both didn't advance, don't change positions + if target_step == 0: + if query_step == 0: + continue + else: + # The reference did advance + for i, query_step in enumerate(query_steps): + if i != index: # Skip the sequence that just advanced + if query_step > 0: + # The query also advanced, so move both reference and query positions + positions[i, :] += target_step + else: + # The query did not advance, so move only the reference position + positions[i, 0] += target_step + # Append the current positions to msa_coordinates + msa_coordinates.append([reference_position] + list(positions[:, 1])) + + msa_coordinates = np.array(msa_coordinates).transpose() + return cls(sequences, msa_coordinates) + + def __init__(self, sequences, coordinates=None): + """Initialize a new Alignment object. + + Arguments: + - sequences - A list of the sequences (Seq, MutableSeq, SeqRecord, + or string objects) that were aligned. + - coordinates - The sequence coordinates that define the alignment. + If None (the default value), assume that the sequences + align to each other without any gaps. + """ + self.sequences = sequences + if coordinates is None: + try: + lengths = {len(sequence) for sequence in sequences} + except TypeError: + # this may happen if sequences contain a SeqRecord where + # the seq attribute is None, as neither the sequence nor + # its length are known. + pass + else: + if len(lengths) == 0: + coordinates = np.empty((0, 0), np.intp) + elif len(lengths) == 1: + length = lengths.pop() + coordinates = np.array([[0, length]] * len(sequences), np.intp) + else: + raise ValueError( + "sequences must have the same length if coordinates is None" + ) + self.coordinates = coordinates + + def __array__(self, dtype=None, copy=None): + if copy is False: + raise ValueError( + "As calling array on an alignment must return a new array, the copy argument cannot be False" + ) + coordinates = self.coordinates.copy() + sequences = list(self.sequences) + steps = np.diff(self.coordinates, 1) + aligned = sum(steps != 0, 0) > 1 + # True for steps in which at least two sequences align, False if a gap + for i, sequence in enumerate(sequences): + row = steps[i, aligned] + if (row >= 0).all(): + pass + elif (row <= 0).all(): + sequences[i] = reverse_complement(sequence) + coordinates[i, :] = len(sequence) - coordinates[i, :] + steps[i, :] = -steps[i, :] + else: + raise ValueError(f"Inconsistent steps in row {i}") + gaps = steps.max(0) + if not ((steps == gaps) | (steps <= 0)).all(): + raise ValueError("Unequal step sizes in alignment") + n = len(steps) + m = sum(gaps) + data = np.empty((n, m), "S1") + for i in range(n): + sequence = sequences[i] + k = coordinates[i, 0] + m = 0 + for step, gap in zip(steps[i], gaps): + if step > 0: + j = k + step + n = m + step + try: + subsequence = bytes(sequence[k:j]) + except TypeError: # str + subsequence = bytes(sequence[k:j], "UTF8") + data[i, :].data.cast("B")[m:n] = subsequence + k = j + m = n + elif step < 0: + k += step + else: # step == 0 + n = m + gap + data[i, m:n] = b"-" + m = n + if dtype is not None: + data = np.array(data, dtype) + return data + + def __add__(self, other): + """Combine two alignments by adding them row-wise. + + For example, + + >>> import numpy as np + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> from Bio.Align import Alignment + >>> a1 = SeqRecord(Seq("AAAAC"), id="Alpha") + >>> b1 = SeqRecord(Seq("AAAC"), id="Beta") + >>> c1 = SeqRecord(Seq("AAAAG"), id="Gamma") + >>> a2 = SeqRecord(Seq("GTT"), id="Alpha") + >>> b2 = SeqRecord(Seq("TT"), id="Beta") + >>> c2 = SeqRecord(Seq("GT"), id="Gamma") + >>> left = Alignment([a1, b1, c1], + ... coordinates=np.array([[0, 3, 4, 5], + ... [0, 3, 3, 4], + ... [0, 3, 4, 5]])) + >>> left.annotations = {"tool": "demo", "name": "start"} + >>> left.column_annotations = {"stats": "CCCXC"} + >>> right = Alignment([a2, b2, c2], + ... coordinates=np.array([[0, 1, 2, 3], + ... [0, 0, 1, 2], + ... [0, 1, 1, 2]])) + >>> right.annotations = {"tool": "demo", "name": "end"} + >>> right.column_annotations = {"stats": "CXC"} + + Now, let's look at these two alignments: + + >>> print(left) + Alpha 0 AAAAC 5 + Beta 0 AAA-C 4 + Gamma 0 AAAAG 5 + + >>> print(right) + Alpha 0 GTT 3 + Beta 0 -TT 2 + Gamma 0 G-T 2 + + + And add them: + + >>> combined = left + right + >>> print(combined) + Alpha 0 AAAACGTT 8 + Beta 0 AAA-C-TT 6 + Gamma 0 AAAAGG-T 7 + + + For this to work, both alignments must have the same number of sequences + (here they both have 3 rows): + + >>> len(left) + 3 + >>> len(right) + 3 + >>> len(combined) + 3 + + The sequences are SeqRecord objects, and these can be added together. Refer + to the SeqRecord documentation for details of how the annotation is handled. This + example is a special case in that both original alignments shared the same names, + meaning when the rows are added they also get the same name. + + Any common annotations are preserved, but differing annotation is lost. This is + the same behavior used in the SeqRecord annotations and is designed to prevent + accidental propagation of inappropriate values: + + >>> combined.annotations + {'tool': 'demo'} + + Similarly any common per-column-annotations are combined: + + >>> combined.column_annotations + {'stats': 'CCCXCCXC'} + + """ + if not isinstance(other, Alignment): + raise NotImplementedError + if len(self) != len(other): + raise ValueError( + "When adding two alignments they must have the same length" + " (i.e. same number of rows)" + ) + starts1 = self.coordinates[:, 0] + ends1 = self.coordinates[:, -1] + sequences1 = self.sequences + starts2 = other.coordinates[:, 0] + ends2 = other.coordinates[:, -1] + sequences2 = other.sequences + sequences = [] + for start1, end1, seq1, start2, end2, seq2 in zip( + starts1, ends1, sequences1, starts2, ends2, sequences2 + ): + sequence = seq1[start1:end1] + seq2[start2:end2] + sequences.append(sequence) + offset = starts2 - ends1 + starts1 + coordinates1 = self.coordinates - starts1[:, None] + coordinates2 = other.coordinates - offset[:, None] + coordinates = np.append(coordinates1, coordinates2, axis=1) + alignment = Alignment(sequences, coordinates) + # Take any common annotation: + annotations = {} + try: + for k, v in self.annotations.items(): + try: + if other.annotations[k] == v: + annotations[k] = v + except KeyError: + continue + except AttributeError: + pass + else: + alignment.annotations = annotations + column_annotations = {} + try: + for k, v in self.column_annotations.items(): + try: + column_annotations[k] = v + other.column_annotations[k] + except KeyError: + continue + except AttributeError: + pass + else: + alignment.column_annotations = column_annotations + return alignment + + @property + def frequencies(self): + """Return the frequency of each letter in each column of the alignment. + + Gaps are represented by a dash ("-") character. + For example, + + >>> from Bio import Align + >>> aligner = Align.PairwiseAligner() + >>> aligner.mode = "global" + >>> alignments = aligner.align("GACCTG", "CGATCG") + >>> alignment = alignments[0] + >>> print(alignment) + target 0 -GACCTG 6 + 0 -||.|-| 7 + query 0 CGATC-G 6 + + >>> alignment.frequencies + {'-': array([1., 0., 0., 0., 0., 1., 0.]), 'G': array([0., 2., 0., 0., 0., 0., 2.]), 'A': array([0., 0., 2., 0., 0., 0., 0.]), 'C': array([1., 0., 0., 1., 2., 0., 0.]), 'T': array([0., 0., 0., 1., 0., 1., 0.])} + >>> aligner.mode = "local" + >>> alignments = aligner.align("GACCTG", "CGATCG") + >>> alignment = alignments[0] + >>> print(alignment) + target 0 GACC 4 + 0 ||.| 4 + query 1 GATC 5 + + >>> alignment.frequencies + {'G': array([2., 0., 0., 0.]), 'A': array([0., 2., 0., 0.]), 'C': array([0., 0., 1., 2.]), 'T': array([0., 0., 1., 0.])} + """ + coordinates = self.coordinates.copy() + sequences = list(self.sequences) + steps = np.diff(self.coordinates, 1) + aligned = sum(steps != 0, 0) > 1 + # True for steps in which at least two sequences align, False if a gap + for i, sequence in enumerate(sequences): + row = steps[i, aligned] + if (row >= 0).all(): + pass + elif (row <= 0).all(): + sequences[i] = reverse_complement(sequence) + coordinates[i, :] = len(sequence) - coordinates[i, :] + steps[i, :] = -steps[i, :] + else: + raise ValueError(f"Inconsistent steps in row {i}") + gaps = steps.max(0) + if not ((steps == gaps) | (steps <= 0)).all(): + raise ValueError("Unequal step sizes in alignment") + n = len(steps) + length = sum(gaps) + counts = {} + for i in range(n): + sequence = sequences[i] + try: + weight = sequence.annotations.get("weight", 1.0) + except AttributeError: + weight = 1.0 + k = coordinates[i, 0] + m = 0 + for step, gap in zip(steps[i], gaps): + if step > 0: + j = k + step + n = m + step + try: + subsequence = bytes(sequence[k:j]) + except TypeError: # str + subsequence = bytes(sequence[k:j], "UTF8") + for index, letter in zip(range(m, n), subsequence): + character = chr(letter) + row = counts.get(character) + if row is None: + row = np.zeros(length) + counts[character] = row + row[index] += weight + k = j + m = n + elif step < 0: + k += step + else: # step == 0 + n = m + gap + character = "-" + row = counts.get(character) + if row is None: + row = np.zeros(length) + counts[character] = row + row[m:n] += weight + m = n + return counts + + @property + def target(self): + """Return self.sequences[0] for a pairwise alignment.""" + n = len(self.sequences) + if n > 2: + # also allow alignments in which only the target alignment is defined + raise ValueError( + "self.target is defined for pairwise alignments only (found alignment of %d sequences)" + % n + ) + return self.sequences[0] + + @target.setter + def target(self, value): + """For a pairwise alignment, set self.sequences[0].""" + n = len(self.sequences) + if n != 2: + raise ValueError( + "self.target is defined for pairwise alignments only (found alignment of %d sequences)" + % n + ) + self.sequences[0] = value + + @property + def query(self): + """Return self.sequences[1] for a pairwise alignment.""" + n = len(self.sequences) + if n != 2: + raise ValueError( + "self.query is defined for pairwise alignments only (found alignment of %d sequences)" + % n + ) + return self.sequences[1] + + @query.setter + def query(self, value): + """For a pairwise alignment, set self.sequences[1].""" + n = len(self.sequences) + if n != 2: + raise ValueError( + "self.query is defined for pairwise alignments only (found alignment of %d sequences)" + % n + ) + self.sequences[1] = value + + def __eq__(self, other): + """Check if two Alignment objects specify the same alignment.""" + for left, right in zip_longest(self.sequences, other.sequences): + try: + left = left.seq + except AttributeError: + pass + try: + right = right.seq + except AttributeError: + pass + if left != right: + return False + return np.array_equal(self.coordinates, other.coordinates) + + def __ne__(self, other): + """Check if two Alignment objects have different alignments.""" + for left, right in zip_longest(self.sequences, other.sequences): + try: + left = left.seq + except AttributeError: + pass + try: + right = right.seq + except AttributeError: + pass + if left != right: + return True + + return not np.array_equal(self.coordinates, other.coordinates) + + def __lt__(self, other): + """Check if self should come before other.""" + for left, right in zip_longest(self.sequences, other.sequences): + try: + left = left.seq + except AttributeError: + pass + try: + right = right.seq + except AttributeError: + pass + if left < right: + return True + if left > right: + return False + for left, right in zip( + self.coordinates.transpose(), other.coordinates.transpose() + ): + left, right = tuple(left), tuple(right) + if left < right: + return True + if left > right: + return False + return False + + def __le__(self, other): + """Check if self should come before or is equal to other.""" + for left, right in zip_longest(self.sequences, other.sequences): + try: + left = left.seq + except AttributeError: + pass + try: + right = right.seq + except AttributeError: + pass + if left < right: + return True + if left > right: + return False + for left, right in zip( + self.coordinates.transpose(), other.coordinates.transpose() + ): + left, right = tuple(left), tuple(right) + if left < right: + return True + if left > right: + return False + return True + + def __gt__(self, other): + """Check if self should come after other.""" + for left, right in zip_longest(self.sequences, other.sequences): + try: + left = left.seq + except AttributeError: + pass + try: + right = right.seq + except AttributeError: + pass + if left < right: + return False + if left > right: + return True + for left, right in zip( + self.coordinates.transpose(), other.coordinates.transpose() + ): + left, right = tuple(left), tuple(right) + if left > right: + return True + if left < right: + return False + return False + + def __ge__(self, other): + """Check if self should come after or is equal to other.""" + for left, right in zip_longest(self.sequences, other.sequences): + try: + left = left.seq + except AttributeError: + pass + try: + right = right.seq + except AttributeError: + pass + if left < right: + return False + if left > right: + return True + for left, right in zip( + self.coordinates.transpose(), other.coordinates.transpose() + ): + left, right = tuple(left), tuple(right) + if left > right: + return True + if left < right: + return False + return True + + def _get_row(self, index): + """Return self[index], where index is an integer (PRIVATE). + + This method is called by __getitem__ for invocations of the form + + self[row] + + where row is an integer. + Return value is a string if the aligned sequences are string, Seq, + or SeqRecord objects, otherwise the return value is a list. + """ + steps = np.diff(self.coordinates, 1) + n = len(steps) + if index < 0: + index += n + if index < 0: + raise IndexError("row index out of range") + elif index >= n: + raise IndexError("row index out of range") + aligned = sum(steps != 0, 0) > 1 + # True for steps in which at least two sequences align, False if a gap + coordinates = self.coordinates[index, :] + sequence = self.sequences[index] + for i in range(n): + aligned_steps = steps[i, aligned] + if sum(aligned_steps > 0) < sum(aligned_steps < 0): + steps[i, :] = -steps[i, :] + if i == index: + sequence = reverse_complement(sequence) + coordinates = len(sequence) - coordinates + gaps = steps.max(0) + try: + sequence = sequence.seq # SeqRecord confusion + except AttributeError: + pass + steps = steps[index] + k = coordinates[0] + if isinstance(sequence, (str, Seq)): + line = "" + for step, gap in zip(steps, gaps): + if step > 0: + j = k + step + line += str(sequence[k:j]) + k = j + elif step < 0: + k += step + else: # step == 0 + line += "-" * gap + else: + line = [] + for step, gap in zip(steps, gaps): + if step > 0: + j = k + step + line.extend(sequence[k:j]) + k = j + else: + line.extend([None] * gap) + return line + + def _get_rows(self, key): + """Return self[key], where key is a slice object (PRIVATE). + + This method is called by __getitem__ for invocations of the form + + self[rows] + + where rows is a slice object. Return value is an Alignment object. + """ + sequences = self.sequences[key] + coordinates = self.coordinates[key].copy() + alignment = Alignment(sequences, coordinates) + if np.array_equal(self.coordinates, coordinates): + try: + alignment.score = self.score + except AttributeError: + pass + try: + alignment.column_annotations = self.column_annotations + except AttributeError: + pass + return alignment + + def _get_row_col(self, j, col, steps, gaps, sequence): + """Return the sequence contents at alignment column j (PRIVATE). + + This method is called by __getitem__ for invocations of the form + + self[row, col] + + where both row and col are integers. + Return value is a string of length 1. + """ + indices = gaps.cumsum() + index = indices.searchsorted(col, side="right") + if steps[index]: + offset = col - indices[index] + j += sum(steps[: index + 1]) + offset + return sequence[j] + else: + return "-" + + def _get_row_cols_slice( + self, coordinate, start_index, stop_index, steps, gaps, sequence + ): + """Return the alignment contents of one row and consecutive columns (PRIVATE). + + This method is called by __getitem__ for invocations of the form + + self[row, cols] + + where row is an integer and cols is a slice object with step 1. + Return value is a string if the aligned sequences are string, Seq, + or SeqRecord objects, otherwise the return value is a list. + """ + indices = gaps.cumsum() + i = indices.searchsorted(start_index, side="right") + j = i + indices[i:].searchsorted(stop_index, side="right") + try: + sequence = sequence.seq # stupid SeqRecord + except AttributeError: + pass + if isinstance(sequence, (str, Seq)): + if i == j: + length = stop_index - start_index + if steps[i] == 0: + line = "-" * length + else: + start = coordinate[i] + start_index + if i > 0: + start -= indices[i - 1] + stop = start + length + line = str(sequence[start:stop]) + else: + length = indices[i] - start_index + if steps[i] == 0: + line = "-" * length + else: + stop = coordinate[i + 1] + start = stop - length + line = str(sequence[start:stop]) + i += 1 + while i < j: + step = gaps[i] + if steps[i] == 0: + line += "-" * step + else: + start = coordinate[i] + stop = coordinate[i + 1] + line += str(sequence[start:stop]) + i += 1 + length = stop_index - indices[i - 1] + if length > 0: + if steps[i] == 0: + line += "-" * length + else: + start = coordinate[i] + stop = start + length + line += str(sequence[start:stop]) + else: + if i == j: + length = stop_index - start_index + if steps[i] == 0: + line = [None] * length + else: + start = coordinate[i] + start_index + if i > 0: + start -= indices[i - 1] + stop = start + length + line = sequence[start:stop] + else: + length = indices[i] - start_index + if steps[i] == 0: + line = [None] * length + else: + stop = coordinate[i + 1] + start = stop - length + line = sequence[start:stop] + i += 1 + while i < j: + step = gaps[i] + if steps[i] == 0: + line.extend([None] * step) + else: + start = coordinate[i] + stop = coordinate[i + 1] + line.extend(sequence[start:stop]) + i += 1 + length = stop_index - indices[i - 1] + if length > 0: + if steps[j] == 0: + line.extend([None] * length) + else: + start = coordinate[i] + stop = start + length + line.extend(sequence[start:stop]) + return line + + def _get_row_cols_iterable(self, coordinate, cols, gaps, sequence): + """Return the alignment contents of one row and multiple columns (PRIVATE). + + This method is called by __getitem__ for invocations of the form + + self[row, cols] + + where row is an integer and cols is an iterable of integers. + Return value is a string if the aligned sequences are string, Seq, + or SeqRecord objects, otherwise the return value is a list. + """ + try: + sequence = sequence.seq # stupid SeqRecord + except AttributeError: + pass + if isinstance(sequence, (str, Seq)): + line = "" + start = coordinate[0] + for end, gap in zip(coordinate[1:], gaps): + if start < end: + line += str(sequence[start:end]) + else: + line += "-" * gap + start = end + try: + line = "".join(line[col] for col in cols) + except IndexError: + raise + except Exception: + raise TypeError( + "second index must be an integer, slice, or iterable of integers" + ) from None + else: + line = [] + start = coordinate[0] + for end, gap in zip(coordinate[1:], gaps): + if start < end: + line.extend(sequence[start:end]) + else: + line.extend([None] * gap) + start = end + try: + line = [line[col] for col in cols] + except IndexError: + raise + except Exception: + raise TypeError( + "second index must be an integer, slice, or iterable of integers" + ) from None + return line + + def _get_rows_col(self, coordinates, col, steps, gaps, sequences): + """Return the alignment contents of multiple rows and one column (PRIVATE). + + This method is called by __getitem__ for invocations of the form + + self[rows, col] + + where rows is a slice object, and col is an integer. + Return value is a string. + """ + indices = gaps.cumsum() + j = indices.searchsorted(col, side="right") + offset = indices[j] - col + line = "" + for sequence, coordinate, step in zip(sequences, coordinates, steps): + if step[j] == 0: + line += "-" + else: + index = coordinate[j] + step[j] - offset + line += sequence[index] + return line + + def _get_rows_cols_slice( + self, coordinates, row, start_index, stop_index, steps, gaps + ): + """Return a subalignment of multiple rows and consecutive columns (PRIVATE). + + This method is called by __getitem__ for invocations of the form + + self[rows, cols] + + where rows is an arbitrary slice object, and cols is a slice object + with step 1, allowing the alignment sequences to be reused in the + subalignment. Return value is an Alignment object. + """ + rcs = np.any(coordinates != self.coordinates[row], axis=1) + indices = gaps.cumsum() + i = indices.searchsorted(start_index, side="right") + j = i + indices[i:].searchsorted(stop_index, side="left") + 1 + offset = steps[:, i] - indices[i] + start_index + coordinates[:, i] += offset * (steps[:, i] > 0) + offset = indices[j - 1] - stop_index + coordinates[:, j] -= offset * (steps[:, j - 1] > 0) + coordinates = coordinates[:, i : j + 1] + sequences = self.sequences[row] + for coordinate, rc, sequence in zip(coordinates, rcs, sequences): + if rc: + # mapped to reverse strand + coordinate[:] = len(sequence) - coordinate[:] + alignment = Alignment(sequences, coordinates) + if np.array_equal(self.coordinates, coordinates): + try: + alignment.score = self.score + except AttributeError: + pass + try: + column_annotations = self.column_annotations + except AttributeError: + pass + else: + alignment.column_annotations = {} + for key, value in column_annotations.items(): + value = value[start_index:stop_index] + try: + value = value.copy() + except AttributeError: + # immutable tuples like str, tuple + pass + alignment.column_annotations[key] = value + return alignment + + def _get_rows_cols_iterable(self, coordinates, col, steps, gaps, sequences): + """Return a subalignment of multiple rows and columns (PRIVATE). + + This method is called by __getitem__ for invocations of the form + + self[rows, cols] + + where rows is a slice object and cols is an iterable of integers. + This method will create new sequences for use by the subalignment + object. Return value is an Alignment object. + """ + indices = tuple(col) + lines = [] + for i, sequence in enumerate(sequences): + try: + s = sequence.seq # stupid SeqRecord + except AttributeError: + s = sequence + line = "" + k = coordinates[i, 0] + for step, gap in zip(steps[i], gaps): + if step: + j = k + step + line += str(s[k:j]) + k = j + else: + line += "-" * gap + try: + line = "".join(line[index] for index in indices) + except IndexError: + raise + except Exception: + raise TypeError( + "second index must be an integer, slice, or iterable of integers" + ) from None + line = line.encode() + lines.append(line) + seqdata, coordinates = self.parse_printed_alignment(lines) + for i, sequence in enumerate(sequences): + line = seqdata[i] + try: + s = sequence.seq + except AttributeError: + if isinstance(sequence, str): # str + sequence = line.decode() + else: + sequence = sequence.__class__(line) # Seq, MutableSeq + else: # SeqRecord + sequence = copy.deepcopy(sequence) + sequence.seq = s.__class__(line) + sequences[i] = sequence + alignment = Alignment(sequences, coordinates) + try: + column_annotations = self.column_annotations + except AttributeError: + pass + else: + alignment.column_annotations = {} + for key, value in column_annotations.items(): + values = (value[index] for index in indices) + if isinstance(value, str): + value = "".join(values) + else: + value = value.__class__(values) + alignment.column_annotations[key] = value + return alignment + + def __getitem__(self, key): + """Return self[key]. + + Indices of the form + + self[:, :] + + return a copy of the Alignment object; + + self[:, i:] + self[:, :j] + self[:, i:j] + self[:, iterable] (where iterable returns integers) + + return a new Alignment object spanning the selected columns; + + self[k, i] + self[k, i:] + self[k, :j] + self[k, i:j] + self[k, iterable] (where iterable returns integers) + self[k] (equivalent to self[k, :]) + + return a string with the aligned sequence (including gaps) for the + selected columns, where k = 0 represents the target and k = 1 + represents the query sequence; and + + self[:, i] + + returns a string with the selected column in the alignment. + + >>> from Bio.Align import PairwiseAligner + >>> aligner = PairwiseAligner() + >>> alignments = aligner.align("ACCGGTTT", "ACGGGTT") + >>> alignment = alignments[0] + >>> print(alignment) + target 0 ACCGGTTT 8 + 0 ||.||||- 8 + query 0 ACGGGTT- 7 + + >>> alignment[0, :] + 'ACCGGTTT' + >>> alignment[1, :] + 'ACGGGTT-' + >>> alignment[0] + 'ACCGGTTT' + >>> alignment[1] + 'ACGGGTT-' + >>> alignment[0, 1:-2] + 'CCGGT' + >>> alignment[1, 1:-2] + 'CGGGT' + >>> alignment[1, (1, 7, 2)] + 'C-G' + >>> alignment[1, ::2] + 'AGGT' + >>> alignment[1, range(0, 8, 2)] + 'AGGT' + >>> alignment[:, 0] + 'AA' + >>> alignment[:, 5] + 'TT' + >>> alignment[:, 1:] # doctest:+ELLIPSIS + + >>> print(alignment[:, 1:]) + target 1 CCGGTTT 8 + 0 |.||||- 7 + query 1 CGGGTT- 7 + + >>> print(alignment[:, 2:]) + target 2 CGGTTT 8 + 0 .||||- 6 + query 2 GGGTT- 7 + + >>> print(alignment[:, 3:]) + target 3 GGTTT 8 + 0 ||||- 5 + query 3 GGTT- 7 + + >>> print(alignment[:, 3:-1]) + target 3 GGTT 7 + 0 |||| 4 + query 3 GGTT 7 + + >>> print(alignment[:, ::2]) + target 0 ACGT 4 + 0 |.|| 4 + query 0 AGGT 4 + + >>> print(alignment[:, range(1, 8, 2)]) + target 0 CGTT 4 + 0 |||- 4 + query 0 CGT- 3 + + >>> print(alignment[:, (2, 7, 3)]) + target 0 CTG 3 + 0 .-| 3 + query 0 G-G 2 + + """ + if isinstance(key, numbers.Integral): + return self._get_row(key) + if isinstance(key, slice): + return self._get_rows(key) + sequences = list(self.sequences) + coordinates = self.coordinates.copy() + steps = np.diff(coordinates, 1) + aligned = sum(steps != 0, 0) > 1 + # True for steps in which at least two sequences align, False if a gap + for i, sequence in enumerate(sequences): + row = steps[i, aligned] + if (row >= 0).all(): + pass + elif (row <= 0).all(): + steps[i, :] = -steps[i, :] + coordinates[i, :] = len(sequence) - coordinates[i, :] + sequences[i] = reverse_complement(sequence) + try: + sequences[i].id = sequence.id + except AttributeError: + pass + else: + raise ValueError(f"Inconsistent steps in row {i}") + gaps = steps.max(0) + if not ((steps == gaps) | (steps <= 0)).all(): + raise ValueError("Unequal step sizes in alignment") + m = sum(gaps) + if isinstance(key, tuple): + try: + row, col = key + except ValueError: + raise ValueError("only tuples of length 2 can be alignment indices") + else: + raise TypeError("alignment indices must be integers, slices, or tuples") + if isinstance(col, numbers.Integral): + if col < 0: + col += m + if col < 0 or col >= m: + raise IndexError( + "column index %d is out of bounds (%d columns)" % (col, m) + ) + steps = steps[row] + if isinstance(row, numbers.Integral): + sequence = sequences[row] + if isinstance(col, numbers.Integral): + return self._get_row_col( + coordinates[row, 0], col, steps, gaps, sequence + ) + coordinate = coordinates[row, :] + if isinstance(col, slice): + start_index, stop_index, step = col.indices(m) + if start_index < stop_index and step == 1: + return self._get_row_cols_slice( + coordinate, start_index, stop_index, steps, gaps, sequence + ) + # make an iterable if step != 1 + col = range(start_index, stop_index, step) + return self._get_row_cols_iterable(coordinate, col, gaps, sequence) + if isinstance(row, slice): + sequences = sequences[row] + coordinates = coordinates[row] + if isinstance(col, numbers.Integral): + return self._get_rows_col(coordinates, col, steps, gaps, sequences) + if isinstance(col, slice): + start_index, stop_index, step = col.indices(m) + if start_index < stop_index and step == 1: + return self._get_rows_cols_slice( + coordinates, + row, + start_index, + stop_index, + steps, + gaps, + ) + # make an iterable if step != 1 + col = range(start_index, stop_index, step) + # try if we can use col as an iterable + return self._get_rows_cols_iterable( + coordinates, col, steps, gaps, sequences + ) + raise TypeError("first index must be an integer or slice") + + def _convert_sequence_string(self, sequence): + """Convert given sequence to string using the appropriate method (PRIVATE).""" + if isinstance(sequence, (bytes, bytearray)): + return sequence.decode() + if isinstance(sequence, str): + return sequence + if isinstance(sequence, Seq): + return str(sequence) + try: # check if target is a SeqRecord + sequence = sequence.seq + except AttributeError: + pass + else: + return str(sequence) + try: + view = memoryview(sequence) + except TypeError: + pass + else: + if view.format == "c": + return str(sequence) + return None + + def __format__(self, format_spec): + """Return the alignment as a string in the specified file format. + + Wrapper for self.format(). + """ + return self.format(format_spec) + + def format(self, fmt="", *args, **kwargs): + """Return the alignment as a string in the specified file format. + + Arguments: + - fmt - File format. Acceptable values are an empty string to + create a human-readable representation of the alignment, + or any of the alignment file formats supported by + `Bio.Align` (some have not yet been implemented). + - scoring - Optional keyword-only parameter; default=None. + If provided, can be: + + - A substitution matrix (typically from the + `Bio.Align.substitution_matrices` submodule) + used to mark positive matches (:) in the alignment string + when two different residues have a positive score. + + - A PairwiseAligner object, in which case its substitution + matrix and settings are used for determining positive matches. + + All other arguments are passed to the format-specific writer functions: + - mask - PSL format only. Specify if repeat regions in the target + sequence are masked and should be reported in the + `repMatches` field of the PSL file instead of in the + `matches` field. Acceptable values are + None : no masking (default); + "lower": masking by lower-case characters; + "upper": masking by upper-case characters. + - wildcard - PSL format only. Report alignments to the wildcard + character in the target or query sequence in the + `nCount` field of the PSL file instead of in the + `matches`, `misMatches`, or `repMatches` fields. + Default value is 'N'. + - md - SAM format only. If True, calculate the MD tag from + the alignment and include it in the output. If False + (default), do not include the MD tag in the output. + """ + scoring = kwargs.pop("scoring", None) + substitution_matrix = None + if scoring is None and args: + first = args[0] + if isinstance(first, PairwiseAligner): + substitution_matrix = first.substitution_matrix + args = args[1:] + elif isinstance(first, (np.ndarray, substitution_matrices.Array)): + substitution_matrix = first + args = args[1:] + if substitution_matrix is None and scoring is not None: + if isinstance(scoring, PairwiseAligner): + substitution_matrix = scoring.substitution_matrix + elif isinstance(scoring, (np.ndarray, substitution_matrices.Array)): + substitution_matrix = scoring + if fmt == "": + return self._format_pretty(substitution_matrix) + module = _load(fmt) + if module.AlignmentIterator.mode == "b": + raise ValueError(f"{fmt} is a binary file format") + try: + writer = module.AlignmentWriter(None, *args, **kwargs) + except AttributeError: + raise ValueError( + f"Formatting alignments has not yet been implemented for the {fmt} format" + ) from None + return writer.format_alignment(self) + + def _format_pretty(self, matrix=None): + """Return default string representation (PRIVATE). + + Helper for self.format(). + + Arguments: + - matrix - Optional; default=None + A substitution matrix (typically from the + `Bio.Align.substitution_matrices` submodule) + used to mark positive matches (:) in the alignment string + when two different residues have a positive score. + """ + n = len(self.sequences) + if n == 2: + write_pattern = True + else: + write_pattern = False + steps = np.diff(self.coordinates, 1) + aligned = sum(steps != 0, 0) > 1 + # True for steps in which at least two sequences align, False if a gap + name_width = 10 + names = [] + seqs = [] + indices = np.zeros(self.coordinates.shape, np.intp) + for i, (seq, positions, row) in enumerate( + zip(self.sequences, self.coordinates, indices) + ): + try: + name = seq.id + if name is None: + raise AttributeError + except AttributeError: + if n == 2: + if i == 0: + name = "target" + else: + name = "query" + else: + name = "" + else: + name = name[: name_width - 1] + name = name.ljust(name_width) + names.append(name) + try: + seq = seq.seq # SeqRecord confusion + except AttributeError: + pass + start = min(positions) + end = max(positions) + seq = seq[start:end] + aligned_steps = steps[i, aligned] + if len(aligned_steps) == 0: + aligned_steps = steps[i] + if sum(aligned_steps > 0) >= sum(aligned_steps < 0): + start = min(positions) + row[:] = positions - start + else: + steps[i, :] = -steps[i, :] + seq = reverse_complement(seq) + end = max(positions) + row[:] = end - positions + if isinstance(seq, str): + if not seq.isascii(): + return self._format_unicode(matrix) + elif isinstance(seq, (Seq, MutableSeq)): + try: + seq = bytes(seq) + except UndefinedSequenceError: + s = bytearray(b"?" * (end - start)) + for start, end in seq.defined_ranges: + s[start:end] = bytes(seq[start:end]) + seq = s + seq = seq.decode() + else: + return self._format_generalized(matrix) + seqs.append(seq) + minstep = steps.min(0) + maxstep = steps.max(0) + steps = np.where(-minstep > maxstep, minstep, maxstep) + for i, row in enumerate(indices): + row_steps = np.diff(row) + row_aligned = (row_steps > 0) & aligned + row_steps = row_steps[row_aligned] + aligned_steps = steps[row_aligned] + if (row_steps == aligned_steps).all(): + pass + elif (3 * row_steps == aligned_steps).all(): + row[:] *= 3 + seqs[i] = " ".join(seqs[i]) + " " + write_pattern = False + else: + raise ValueError("Inconsistent coordinates") + prefix_width = 10 + position_width = 10 + line_width = 80 + lines = [] + steps = indices[:, 1:] - indices[:, :-1] + minstep = steps.min(0) + maxstep = steps.max(0) + steps = np.where(-minstep > maxstep, minstep, maxstep) + for name, seq, positions, row in zip(names, seqs, self.coordinates, indices): + start = positions[0] + column = line_width + start_index = row[0] + for step, end, end_index in zip(steps, positions[1:], row[1:]): + if step < 0: + if prefix_width + position_width < column: + position_text = str(start) + offset = position_width - len(position_text) - 1 + if offset < 0: + lines[-1] += " .." + position_text[-offset + 3 :] + else: + lines[-1] += " " + position_text + column = line_width + start = end + start_index = end_index + continue + elif end_index == start_index: + s = "-" * step + else: + s = seq[start_index:end_index] + while column + len(s) >= line_width: + rest = line_width - column + if rest > 0: + lines[-1] += s[:rest] + s = s[rest:] + if start != end: + if (end_index - start_index) == abs(end - start): + step = rest + else: + # protein to dna alignment; + # integer division, but round up: + step = -(rest // -3) + if start < end: + start += step + else: + start -= step + start_index += rest + line = name + position_text = str(start) + offset = position_width - len(position_text) - 1 + if offset < 0: + line += " .." + position_text[-offset + 3 :] + else: + line += " " * offset + position_text + line += " " + lines.append(line) + column = name_width + position_width + lines[-1] += s + if start_index != end_index: + start_index = end_index + start = end + column += len(s) + if write_pattern is True: + dash = "-" + position = 0 + m = len(lines) // 2 + lines1 = lines[:m] + lines2 = lines[m:] + pattern_lines = [] + for line1, line2 in zip(lines1, lines2): + aligned_seq1 = line1[name_width + position_width :] + aligned_seq2 = line2[name_width + position_width :] + pattern = "" + for c1, c2 in zip(aligned_seq1, aligned_seq2): + if c1 == c2: + if c1 == " ": + break + c = "|" + elif c1 == dash or c2 == dash: + c = "-" + else: + c = "." + if matrix is not None and c1 != " " and c2 != " ": + c1u, c2u = c1.upper(), c2.upper() + if matrix[c1u, c2u] > 0: + c = ":" + pattern += c + pattern_line = " %9d %s" % (position, pattern) + pattern_lines.append(pattern_line) + position += len(pattern) + final_position_width = len(str(max(max(self.coordinates[:, -1]), position))) + if column + final_position_width <= line_width: + if prefix_width + position_width < column: + fmt = f" %{final_position_width}d" + lines1[-1] += fmt % self.coordinates[0, -1] + lines2[-1] += fmt % self.coordinates[1, -1] + pattern_lines[-1] += fmt % position + else: + name1, name2 = names + fmt = "%s%9d" + line = name1 + format(self.coordinates[0, -1], "9d") + lines1.append(line) + line = fmt % (" ", position) + pattern_lines.append(line) + line = fmt % (name2, self.coordinates[1, -1]) + lines2.append(line) + lines.append("") + return "\n".join( + f"{line1}\n{pattern_line}\n{line2}\n" + for (line1, line2, pattern_line) in zip(lines1, lines2, pattern_lines) + ) + else: + m = len(lines) // n + final_position_width = len(str(max(self.coordinates[:, -1]))) + if column + final_position_width < line_width: + if prefix_width + position_width < column: + fmt = f" %{final_position_width}d" + for i in range(n): + lines[m - 1 + i * m] += fmt % self.coordinates[i, -1] + blocks = ["\n".join(lines[j::m]) + "\n" for j in range(m)] + else: + blocks = ["\n".join(lines[j::m]) + "\n" for j in range(m)] + lines = [] + fmt = "%s%9d" + for i in range(n): + line = names[i] + format(self.coordinates[i, -1], "9d") + lines.append(line) + block = "\n".join(lines) + "\n" + blocks.append(block) + return "\n".join(blocks) + + def _format_unicode(self, matrix=None): + """Return default string representation (PRIVATE). + + Helper for self.format(). + + Arguments: + - matrix - Optional; default=None + A substitution matrix (typically from the + `Bio.Align.substitution_matrices` submodule) + used to mark positive matches (:) in the alignment string + when two different residues have a positive score. + """ + seqs = [] + names = [] + coordinates = self.coordinates.copy() + for seq, row in zip(self.sequences, coordinates): + seq = self._convert_sequence_string(seq) + if seq is None: + return self._format_generalized(matrix) + if row[0] > row[-1]: # mapped to reverse strand + row[:] = len(seq) - row[:] + seq = reverse_complement(seq) + seqs.append(seq) + try: + name = seq.id + except AttributeError: + if len(self.sequences) == 2: + if len(names) == 0: + name = "target" + else: + name = "query" + else: + name = "" + else: + name = name[:9] + name = name.ljust(10) + names.append(name) + steps = np.diff(coordinates, 1).max(0) + aligned_seqs = [] + for row, seq in zip(coordinates, seqs): + aligned_seq = "" + start = row[0] + for step, end in zip(steps, row[1:]): + if end == start: + aligned_seq += "-" * step + else: + aligned_seq += seq[start:end] + start = end + aligned_seqs.append(aligned_seq) + if len(seqs) > 2: + return "\n".join(aligned_seqs) + "\n" + aligned_seq1, aligned_seq2 = aligned_seqs + pattern = "" + for c1, c2 in zip(aligned_seq1, aligned_seq2): + if c1 == c2: + c = "|" + elif c1 == "-" or c2 == "-": + c = "-" + else: + c = "." + if matrix is not None and c1 != " " and c2 != " ": + c1u, c2u = c1.upper(), c2.upper() + if matrix[c1u, c2u] > 0: + c = ":" + pattern += c + return f"{aligned_seq1}\n{pattern}\n{aligned_seq2}\n" + + def _format_generalized(self, matrix=None): + """Return generalized string representation (PRIVATE). + + Helper for self._format_pretty(). + + Arguments: + - matrix - Optional; default=None + A substitution matrix (typically from the + `Bio.Align.substitution_matrices` submodule) + used to mark positive matches (:) in the alignment string + when two different residues have a positive score. + """ + seq1, seq2 = self.sequences + aligned_seq1 = [] + aligned_seq2 = [] + pattern = [] + end1, end2 = self.coordinates[:, 0] + if end1 > 0 or end2 > 0: + if end1 <= end2: + for c2 in seq2[: end2 - end1]: + s2 = str(c2) + s1 = " " * len(s2) + aligned_seq1.append(s1) + aligned_seq2.append(s2) + pattern.append(s1) + else: # end1 > end2 + for c1 in seq1[: end1 - end2]: + s1 = str(c1) + s2 = " " * len(s1) + aligned_seq1.append(s1) + aligned_seq2.append(s2) + pattern.append(s2) + start1 = end1 + start2 = end2 + for end1, end2 in self.coordinates[:, 1:].transpose(): + if end1 == start1: + for c2 in seq2[start2:end2]: + s2 = str(c2) + s1 = "-" * len(s2) + aligned_seq1.append(s1) + aligned_seq2.append(s2) + pattern.append(s1) + start2 = end2 + elif end2 == start2: + for c1 in seq1[start1:end1]: + s1 = str(c1) + s2 = "-" * len(s1) + aligned_seq1.append(s1) + aligned_seq2.append(s2) + pattern.append(s2) + start1 = end1 + else: + t1 = seq1[start1:end1] + t2 = seq2[start2:end2] + if len(t1) != len(t2): + raise ValueError("Unequal step sizes in alignment") + for c1, c2 in zip(t1, t2): + s1 = str(c1) + s2 = str(c2) + m1 = len(s1) + m2 = len(s2) + if c1 == c2: + p = "|" + else: + p = "." + if matrix is not None: + c1u, c2u = c1.upper(), c2.upper() + if matrix[c1u, c2u] > 0: + p = ":" + if m1 < m2: + space = (m2 - m1) * " " + s1 += space + pattern.append(p * m1 + space) + elif m1 > m2: + space = (m1 - m2) * " " + s2 += space + pattern.append(p * m2 + space) + else: + pattern.append(p * m1) + aligned_seq1.append(s1) + aligned_seq2.append(s2) + start1 = end1 + start2 = end2 + aligned_seq1 = " ".join(aligned_seq1) + aligned_seq2 = " ".join(aligned_seq2) + pattern = " ".join(pattern) + return f"{aligned_seq1}\n{pattern}\n{aligned_seq2}\n" + + def __str__(self): + """Return a human-readable string representation of the alignment. + + For sequence alignments, each line has at most 80 columns. + The first 10 columns show the (possibly truncated) sequence name, + which may be the id attribute of a SeqRecord, or otherwise 'target' + or 'query' for pairwise alignments. + The next 10 columns show the sequence coordinate, using zero-based + counting as usual in Python. + The remaining 60 columns shown the sequence, using dashes to represent + gaps. + At the end of the alignment, the end coordinates are shown on the right + of the sequence, again in zero-based coordinates. + + Pairwise alignments have an additional line between the two sequences + showing whether the sequences match ('|') or mismatch ('.'), or if + there is a gap ('-'). + The coordinates shown for this line are the column indices, which can + be useful when extracting a subalignment. + + For example, + + >>> from Bio.Align import PairwiseAligner + >>> aligner = PairwiseAligner() + + >>> seqA = "TTAACCCCATTTG" + >>> seqB = "AAGCCCCTTT" + >>> seqC = "AAAGGGGCTT" + + >>> alignments = aligner.align(seqA, seqB) + >>> len(alignments) + 3 + >>> alignment = alignments[0] + >>> print(alignment) + target 0 TTAACCCCATTTG 13 + 0 .-|.||||-|||- 13 + query 0 A-AGCCCC-TTT- 10 + + >>> alignment = alignments[1] + >>> print(alignment) + target 0 TTAACCCCATTTG 13 + 0 -.|.||||-|||- 13 + query 0 -AAGCCCC-TTT- 10 + + >>> alignment = alignments[2] + >>> print(alignment) + target 0 TTAACCCCATTTG 13 + 0 --||.|||.|||- 13 + query 0 --AAGCCCCTTT- 10 + + + Note that seqC is the reverse complement of seqB. Aligning it to the + reverse strand gives the same alignment, but the query coordinates are + switched: + + >>> alignments = aligner.align(seqA, seqC, strand="-") + >>> len(alignments) + 3 + >>> alignment = alignments[0] + >>> print(alignment) + target 0 TTAACCCCATTTG 13 + 0 .-|.||||-|||- 13 + query 10 A-AGCCCC-TTT- 0 + + >>> alignment = alignments[1] + >>> print(alignment) + target 0 TTAACCCCATTTG 13 + 0 -.|.||||-|||- 13 + query 10 -AAGCCCC-TTT- 0 + + >>> alignment = alignments[2] + >>> print(alignment) + target 0 TTAACCCCATTTG 13 + 0 --||.|||.|||- 13 + query 10 --AAGCCCCTTT- 0 + + + """ + return self.format() + + def __repr__(self): + """Return a representation of the alignment, including its shape. + + The representation cannot be used with eval() to recreate the object, + which is usually possible with simple python objects. For example: + + + + The hex string is the memory address of the object and can be used to + distinguish different Alignment objects. See help(id) for more + information. + + >>> import numpy as np + >>> from Bio.Align import Alignment + >>> alignment = Alignment(("ACCGT", "ACGT"), + ... coordinates = np.array([[0, 2, 3, 5], + ... [0, 2, 2, 4], + ... ])) + >>> print(alignment) + target 0 ACCGT 5 + 0 ||-|| 5 + query 0 AC-GT 4 + + >>> alignment # doctest:+ELLIPSIS + + """ + if self.coordinates is None: + return "<%s object at 0x%x>" % ( + self.__class__.__name__, + id(self), + ) + n, m = self.shape + return "<%s object (%i rows x %i columns) at 0x%x>" % ( + self.__class__.__name__, + n, + m, + id(self), + ) + + def __len__(self): + """Return the number of sequences in the alignment.""" + return len(self.sequences) + + @property + def length(self): + """Return the alignment length, i.e. the number of columns when printed.. + + The alignment length is the number of columns in the alignment when it + is printed, and is equal to the sum of the number of matches, number of + mismatches, and the total length of gaps in the target and query. + Sequence sections beyond the aligned segment are not included in the + number of columns. + + For example, + + >>> from Bio import Align + >>> aligner = Align.PairwiseAligner() + >>> aligner.mode = "global" + >>> alignments = aligner.align("GACCTG", "CGATCG") + >>> alignment = alignments[0] + >>> print(alignment) + target 0 -GACCTG 6 + 0 -||.|-| 7 + query 0 CGATC-G 6 + + >>> alignment.length + 7 + >>> aligner.mode = "local" + >>> alignments = aligner.align("GACCTG", "CGATCG") + >>> alignment = alignments[0] + >>> print(alignment) + target 0 GACC 4 + 0 ||.| 4 + query 1 GATC 5 + + >>> len(alignment) + 2 + >>> alignment.length + 4 + """ + n = len(self.coordinates) + if n == 0: # no sequences + return 0 + steps = np.diff(self.coordinates, 1) + aligned = sum(steps != 0, 0) > 1 + # True for steps in which at least two sequences align, False if a gap + for i in range(n): + row = steps[i, aligned] + if (row >= 0).all(): + pass + elif (row <= 0).all(): + steps[i, :] = -steps[i, :] + else: + raise ValueError(f"Inconsistent steps in row {i}") + gaps = steps.max(0) + if not ((steps == gaps) | (steps <= 0)).all(): + raise ValueError("Unequal step sizes in alignment") + return int(sum(gaps)) + + @property + def shape(self): + """Return the shape of the alignment as a tuple of two integer values. + + The first integer value is the number of sequences in the alignment as + returned by len(alignment), which is always 2 for pairwise alignments. + + The second integer value is the number of columns in the alignment when + it is printed, and is equal to the sum of the number of matches, number + of mismatches, and the total length of gaps in the target and query. + Sequence sections beyond the aligned segment are not included in the + number of columns. + + For example, + + >>> from Bio import Align + >>> aligner = Align.PairwiseAligner() + >>> aligner.mode = "global" + >>> alignments = aligner.align("GACCTG", "CGATCG") + >>> alignment = alignments[0] + >>> print(alignment) + target 0 -GACCTG 6 + 0 -||.|-| 7 + query 0 CGATC-G 6 + + >>> len(alignment) + 2 + >>> alignment.shape + (2, 7) + >>> aligner.mode = "local" + >>> alignments = aligner.align("GACCTG", "CGATCG") + >>> alignment = alignments[0] + >>> print(alignment) + target 0 GACC 4 + 0 ||.| 4 + query 1 GATC 5 + + >>> len(alignment) + 2 + >>> alignment.shape + (2, 4) + """ + n = len(self.coordinates) + m = self.length + return (n, m) + + @property + def aligned(self): + """Return the indices of subsequences aligned to each other. + + This property returns the start and end indices of subsequences + in the target and query sequence that were aligned to each other. + If the alignment between target (t) and query (q) consists of N + chunks, you get two tuples of length N: + + (((t_start1, t_end1), (t_start2, t_end2), ..., (t_startN, t_endN)), + ((q_start1, q_end1), (q_start2, q_end2), ..., (q_startN, q_endN))) + + For example, + + >>> from Bio import Align + >>> aligner = Align.PairwiseAligner() + >>> alignments = aligner.align("GAACT", "GAT") + >>> alignment = alignments[0] + >>> print(alignment) + target 0 GAACT 5 + 0 ||--| 5 + query 0 GA--T 3 + + >>> alignment.aligned + array([[[0, 2], + [4, 5]], + + [[0, 2], + [2, 3]]]) + >>> alignment = alignments[1] + >>> print(alignment) + target 0 GAACT 5 + 0 |-|-| 5 + query 0 G-A-T 3 + + >>> alignment.aligned + array([[[0, 1], + [2, 3], + [4, 5]], + + [[0, 1], + [1, 2], + [2, 3]]]) + + Note that different alignments may have the same subsequences + aligned to each other. In particular, this may occur if alignments + differ from each other in terms of their gap placement only: + + >>> aligner.mismatch_score = -10 + >>> alignments = aligner.align("AAACAAA", "AAAGAAA") + >>> len(alignments) + 2 + >>> print(alignments[0]) + target 0 AAAC-AAA 7 + 0 |||--||| 8 + query 0 AAA-GAAA 7 + + >>> alignments[0].aligned + array([[[0, 3], + [4, 7]], + + [[0, 3], + [4, 7]]]) + >>> print(alignments[1]) + target 0 AAA-CAAA 7 + 0 |||--||| 8 + query 0 AAAG-AAA 7 + + >>> alignments[1].aligned + array([[[0, 3], + [4, 7]], + + [[0, 3], + [4, 7]]]) + + The property can be used to identify alignments that are identical + to each other in terms of their aligned sequences. + """ + if len(self.sequences) > 2: + raise NotImplementedError( + "aligned is currently implemented for pairwise alignments only" + ) + coordinates = self.coordinates.copy() + steps = np.diff(coordinates, 1) + aligned = sum(steps != 0, 0) > 1 + # True for steps in which at least two sequences align, False if a gap + for i, sequence in enumerate(self.sequences): + row = steps[i, aligned] + if (row >= 0).all(): + pass + elif (row <= 0).all(): + steps[i, :] = -steps[i, :] + coordinates[i, :] = len(sequence) - coordinates[i, :] + else: + raise ValueError(f"Inconsistent steps in row {i}") + coordinates = coordinates.transpose() + steps = np.diff(coordinates, axis=0) + steps = abs(steps).min(1) + indices = np.flatnonzero(steps) + starts = coordinates[indices, :] + ends = coordinates[indices + 1, :] + segments = np.stack([starts, ends], axis=0).transpose() + steps = np.diff(self.coordinates, 1) + for i, sequence in enumerate(self.sequences): + row = steps[i, aligned] + if (row >= 0).all(): + pass + elif (row <= 0).all(): # mapped to reverse strand + segments[i, :] = len(sequence) - segments[i, :] + else: + raise ValueError(f"Inconsistent steps in row {i}") + return segments + + @property + def indices(self): + """Return the sequence index of each lettter in the alignment. + + This property returns a 2D NumPy array with the sequence index of each + letter in the alignment. Gaps are indicated by -1. The array has the + same number of rows and columns as the alignment, as given by + `self.shape`. + + For example, + + >>> from Bio import Align + >>> aligner = Align.PairwiseAligner() + >>> aligner.mode = "local" + + >>> alignments = aligner.align("GAACTGG", "AATG") + >>> alignment = alignments[0] + >>> print(alignment) + target 1 AACTG 6 + 0 ||-|| 5 + query 0 AA-TG 4 + + >>> alignment.indices + array([[ 1, 2, 3, 4, 5], + [ 0, 1, -1, 2, 3]]) + >>> alignment = alignments[1] + >>> print(alignment) + target 2 ACTG 6 + 0 |.|| 4 + query 0 AATG 4 + + >>> alignment.indices + array([[2, 3, 4, 5], + [0, 1, 2, 3]]) + + >>> alignments = aligner.align("GAACTGG", "CATT", strand="-") + >>> alignment = alignments[0] + >>> print(alignment) + target 1 AACTG 6 + 0 ||-|| 5 + query 4 AA-TG 0 + + >>> alignment.indices + array([[ 1, 2, 3, 4, 5], + [ 3, 2, -1, 1, 0]]) + >>> alignment = alignments[1] + >>> print(alignment) + target 2 ACTG 6 + 0 |.|| 4 + query 4 AATG 0 + + >>> alignment.indices + array([[2, 3, 4, 5], + [3, 2, 1, 0]]) + + """ + a = -np.ones(self.shape, int) + n, m = self.coordinates.shape + steps = np.diff(self.coordinates, 1) + aligned = sum(steps != 0, 0) > 1 + # True for steps in which at least two sequences align, False if a gap + steps = steps[:, aligned] + rcs = np.zeros(n, bool) + for i, row in enumerate(steps): + if (row >= 0).all(): + rcs[i] = False + elif (row <= 0).all(): + rcs[i] = True + else: + raise ValueError(f"Inconsistent steps in row {i}") + i = 0 + j = 0 + ends = self.coordinates[:, 0] + for k in range(1, m): + starts = ends + ends = self.coordinates[:, k] + for row, start, end, rc in zip(a, starts, ends, rcs): + if rc == False and start < end: # noqa: E712 + j = i + end - start + row[i:j] = range(start, end) + elif rc == True and start > end: # noqa: E712 + j = i + start - end + row[i:j] = range(start - 1, end - 1, -1) + i = j + return a + + @property + def inverse_indices(self): + """Return the alignment column index for each letter in each sequence. + + This property returns a list of 1D NumPy arrays; the number of arrays + is equal to the number of aligned sequences, and the length of each + array is equal to the length of the corresponding sequence. For each + letter in each sequence, the array contains the corresponding column + index in the alignment. Letters not included in the alignment are + indicated by -1. + + For example, + + >>> from Bio import Align + >>> aligner = Align.PairwiseAligner() + >>> aligner.mode = "local" + + >>> alignments = aligner.align("GAACTGG", "AATG") + >>> alignment = alignments[0] + >>> print(alignment) + target 1 AACTG 6 + 0 ||-|| 5 + query 0 AA-TG 4 + + >>> alignment.inverse_indices + [array([-1, 0, 1, 2, 3, 4, -1]), array([0, 1, 3, 4])] + >>> alignment = alignments[1] + >>> print(alignment) + target 2 ACTG 6 + 0 |.|| 4 + query 0 AATG 4 + + >>> alignment.inverse_indices + [array([-1, -1, 0, 1, 2, 3, -1]), array([0, 1, 2, 3])] + >>> alignments = aligner.align("GAACTGG", "CATT", strand="-") + >>> alignment = alignments[0] + >>> print(alignment) + target 1 AACTG 6 + 0 ||-|| 5 + query 4 AA-TG 0 + + >>> alignment.inverse_indices + [array([-1, 0, 1, 2, 3, 4, -1]), array([4, 3, 1, 0])] + >>> alignment = alignments[1] + >>> print(alignment) + target 2 ACTG 6 + 0 |.|| 4 + query 4 AATG 0 + + >>> alignment.inverse_indices + [array([-1, -1, 0, 1, 2, 3, -1]), array([3, 2, 1, 0])] + + """ + a = [-np.ones(len(sequence), int) for sequence in self.sequences] + n, m = self.coordinates.shape + steps = np.diff(self.coordinates, 1) + aligned = sum(steps != 0, 0) > 1 + # True for steps in which at least two sequences align, False if a gap + steps = steps[:, aligned] + rcs = np.zeros(n, bool) + for i, row in enumerate(steps): + if (row >= 0).all(): + rcs[i] = False + elif (row <= 0).all(): + rcs[i] = True + else: + raise ValueError(f"Inconsistent steps in row {i}") + i = 0 + j = 0 + for k in range(m - 1): + starts = self.coordinates[:, k] + ends = self.coordinates[:, k + 1] + for row, start, end, rc in zip(a, starts, ends, rcs): + if rc == False and start < end: # noqa: E712 + j = i + end - start + row[start:end] = range(i, j) + elif rc == True and start > end: # noqa: E712 + j = i + start - end + if end > 0: + row[start - 1 : end - 1 : -1] = range(i, j) + elif start > 0: + row[start - 1 :: -1] = range(i, j) + i = j + return a + + def sort(self, key=None, reverse=False): + """Sort the sequences of the alignment in place. + + By default, this sorts the sequences alphabetically using their id + attribute if available, or by their sequence contents otherwise. + For example, + + >>> from Bio.Align import PairwiseAligner + >>> aligner = PairwiseAligner() + >>> aligner.gap_score = -1 + >>> alignments = aligner.align("AATAA", "AAGAA") + >>> len(alignments) + 1 + >>> alignment = alignments[0] + >>> print(alignment) + target 0 AATAA 5 + 0 ||.|| 5 + query 0 AAGAA 5 + + >>> alignment.sort() + >>> print(alignment) + target 0 AAGAA 5 + 0 ||.|| 5 + query 0 AATAA 5 + + + Alternatively, a key function can be supplied that maps each sequence + to a sort value. For example, you could sort on the GC content of each + sequence. + + >>> from Bio.SeqUtils import gc_fraction + >>> alignment.sort(key=gc_fraction) + >>> print(alignment) + target 0 AATAA 5 + 0 ||.|| 5 + query 0 AAGAA 5 + + + You can reverse the sort order by passing `reverse=True`: + + >>> alignment.sort(key=gc_fraction, reverse=True) + >>> print(alignment) + target 0 AAGAA 5 + 0 ||.|| 5 + query 0 AATAA 5 + + + The sequences are now sorted by decreasing GC content value. + """ + sequences = self.sequences + if key is None: + try: + values = [sequence.id for sequence in sequences] + except AttributeError: + values = sequences + else: + values = [key(sequence) for sequence in sequences] + indices = sorted(range(len(sequences)), key=values.__getitem__, reverse=reverse) + self.sequences = [sequences[index] for index in indices] + self.coordinates = self.coordinates.take(indices, 0) + + def map(self, alignment): + r"""Map the alignment to self.target and return the resulting alignment. + + Here, self.query and alignment.target are the same sequence. + + A typical example is where self is the pairwise alignment between a + chromosome and a transcript, the argument is the pairwise alignment + between the transcript and a sequence (e.g., as obtained by RNA-seq), + and we want to find the alignment of the sequence to the chromosome: + + >>> from Bio import Align + >>> aligner = Align.PairwiseAligner() + >>> aligner.mode = 'local' + >>> aligner.open_gap_score = -1 + >>> aligner.extend_gap_score = 0 + >>> chromosome = "AAAAAAAACCCCCCCAAAAAAAAAAAGGGGGGAAAAAAAA" + >>> transcript = "CCCCCCCGGGGGG" + >>> alignments1 = aligner.align(chromosome, transcript) + >>> len(alignments1) + 1 + >>> alignment1 = alignments1[0] + >>> print(alignment1) + target 8 CCCCCCCAAAAAAAAAAAGGGGGG 32 + 0 |||||||-----------|||||| 24 + query 0 CCCCCCC-----------GGGGGG 13 + + >>> sequence = "CCCCGGGG" + >>> alignments2 = aligner.align(transcript, sequence) + >>> len(alignments2) + 1 + >>> alignment2 = alignments2[0] + >>> print(alignment2) + target 3 CCCCGGGG 11 + 0 |||||||| 8 + query 0 CCCCGGGG 8 + + >>> alignment = alignment1.map(alignment2) + >>> print(alignment) + target 11 CCCCAAAAAAAAAAAGGGG 30 + 0 ||||-----------|||| 19 + query 0 CCCC-----------GGGG 8 + + >>> format(alignment, "psl") + '8\t0\t0\t0\t0\t0\t1\t11\t+\tquery\t8\t0\t8\ttarget\t40\t11\t30\t2\t4,4,\t0,4,\t11,26,\n' + + Mapping the alignment does not depend on the sequence contents. If we + delete the sequence contents, the same alignment is found in PSL format + (though we obviously lose the ability to print the sequence alignment): + + >>> alignment1.target = Seq(None, len(alignment1.target)) + >>> alignment1.query = Seq(None, len(alignment1.query)) + >>> alignment2.target = Seq(None, len(alignment2.target)) + >>> alignment2.query = Seq(None, len(alignment2.query)) + >>> alignment = alignment1.map(alignment2) + >>> format(alignment, "psl") + '8\t0\t0\t0\t0\t0\t1\t11\t+\tquery\t8\t0\t8\ttarget\t40\t11\t30\t2\t4,4,\t0,4,\t11,26,\n' + + The map method can also be used to lift over an alignment between + different genome assemblies. In this case, self is a DNA alignment + between two genome assemblies, and the argument is an alignment of a + transcript against one of the genome assemblies: + + >>> np.set_printoptions(threshold=5) # print 5 array elements per row + >>> chain = Align.read("Blat/panTro5ToPanTro6.over.chain", "chain") + >>> chain.sequences[0].id + 'chr1' + >>> len(chain.sequences[0].seq) + 228573443 + >>> chain.sequences[1].id + 'chr1' + >>> len(chain.sequences[1].seq) + 224244399 + >>> print(chain.coordinates) + [[122250000 122250400 122250400 ... 122909818 122909819 122909835] + [111776384 111776784 111776785 ... 112019962 112019962 112019978]] + + showing that the range 122250000:122909835 of chr1 on chimpanzee genome + assembly panTro5 aligns to range 111776384:112019978 of chr1 of + chimpanzee genome assembly panTro6. + + >>> alignment = Align.read("Blat/est.panTro5.psl", "psl") + >>> alignment.sequences[0].id + 'chr1' + >>> len(alignment.sequences[0].seq) + 228573443 + >>> alignment.sequences[1].id + 'DC525629' + >>> len(alignment.sequences[1].seq) + 407 + >>> print(alignment.coordinates) + [[122835789 122835847 122840993 122841145 122907212 122907314] + [ 32 90 90 242 242 344]] + + This shows that nucleotide range 32:344 of expressed sequence tag + DC525629 aligns to range 122835789:122907314 of chr1 of chimpanzee + genome assembly panTro5. + + Note that the target sequence chain.sequences[0].seq and the target + sequence alignment.sequences[0] have the same length: + + >>> len(chain.sequences[0].seq) == len(alignment.sequences[0].seq) + True + + We swap the target and query of the chain such that the query of the + chain corresponds to the target of alignment: + + >>> chain = chain[::-1] + >>> chain.sequences[0].id + 'chr1' + >>> len(chain.sequences[0].seq) + 224244399 + >>> chain.sequences[1].id + 'chr1' + >>> len(chain.sequences[1].seq) + 228573443 + >>> print(chain.coordinates) + [[111776384 111776784 111776785 ... 112019962 112019962 112019978] + [122250000 122250400 122250400 ... 122909818 122909819 122909835]] + + Now we can get the coordinates of DC525629 against chimpanzee genome + assembly panTro6 by calling map on the chain, with alignment as the + argument: + + >>> lifted_alignment = chain.map(alignment) + >>> lifted_alignment.sequences[0].id + 'chr1' + >>> len(lifted_alignment.sequences[0].seq) + 224244399 + >>> lifted_alignment.sequences[1].id + 'DC525629' + >>> len(lifted_alignment.sequences[1].seq) + 407 + >>> print(lifted_alignment.coordinates) + [[111982717 111982775 111987921 111988073 112009200 112009302] + [ 32 90 90 242 242 344]] + + This shows that nucleotide range 32:344 of expressed sequence tag + DC525629 aligns to range 111982717:112009302 of chr1 of chimpanzee + genome assembly panTro6. Note that the genome span of DC525629 on + chimpanzee genome assembly panTro5 is 122907314 - 122835789 = 71525 bp, + while on panTro6 the genome span is 112009302 - 111982717 = 26585 bp. + """ + alignment1, alignment2 = self, alignment + if len(alignment1.query) != len(alignment2.target): + raise ValueError( + "length of alignment1 query sequence (%d) != length of alignment2 target sequence (%d)" + % (len(alignment1.query), len(alignment2.target)) + ) + target = alignment1.target + query = alignment2.query + coordinates1 = alignment1.coordinates + coordinates2 = alignment2.coordinates + n1 = len(alignment1.query) + n2 = len(alignment2.query) + steps1 = np.diff(coordinates1, 1) + row = np.prod(np.sign(steps1), 0) + if (row >= 0).all(): + strand1 = "+" + elif (row <= 0).all(): + strand1 = "-" + else: + raise ValueError("Inconsistent steps in the first alignment") + steps2 = np.diff(coordinates2, 1) + row = np.prod(np.sign(steps2), 0) + if (row >= 0).all(): + strand2 = "+" + elif (row <= 0).all(): + strand2 = "-" + else: + raise ValueError("Inconsistent steps in the second alignment") + if strand1 == "+": + if strand2 == "-": # mapped to reverse strand + coordinates2 = coordinates2.copy() + coordinates2[1, :] = n2 - coordinates2[1, :] + else: # mapped to reverse strand + coordinates1 = coordinates1.copy() + coordinates1[1, :] = n1 - coordinates1[1, :] + coordinates2 = coordinates2.copy() + coordinates2[0, :] = n1 - coordinates2[0, ::-1] + if strand2 == "+": + coordinates2[1, :] = n2 - coordinates2[1, ::-1] + else: # mapped to reverse strand + coordinates2[1, :] = coordinates2[1, ::-1] + steps1 = np.diff(coordinates1, 1) + gaps1 = steps1.max(0) + if not ((steps1 == gaps1) | (steps1 <= 0)).all(): + raise ValueError("Unequal step sizes in first alignment") + steps2 = np.diff(coordinates2, 1) + gaps2 = steps2.max(0) + if not ((steps2 == gaps2) | (steps2 <= 0)).all(): + raise ValueError("Unequal step sizes in second alignment") + path = [] + tEnd, qEnd = sys.maxsize, sys.maxsize + coordinates1 = iter(coordinates1.transpose()) + tStart1, qStart1 = sys.maxsize, sys.maxsize + for tEnd1, qEnd1 in coordinates1: + if tStart1 < tEnd1 and qStart1 < qEnd1: + break + tStart1, qStart1 = tEnd1, qEnd1 + tStart2, qStart2 = sys.maxsize, sys.maxsize + for tEnd2, qEnd2 in coordinates2.transpose(): + while qStart2 < qEnd2 and tStart2 < tEnd2: + while True: + if tStart2 < qStart1: + if tEnd2 < qStart1: + size = tEnd2 - tStart2 + else: + size = qStart1 - tStart2 + break + if tStart2 < qEnd1: + offset = tStart2 - qStart1 + if tEnd2 < qEnd1: + size = tEnd2 - tStart2 + else: + size = qEnd1 - tStart2 + qStart = qStart2 + tStart = tStart1 + offset + if tStart != tEnd or qStart != qEnd: + if tStart > tEnd and qStart > qEnd: + # adding a gap both in target and in query; + # add gap to target first: + path.append([tStart, qEnd]) + path.append([tStart, qStart]) + qEnd = qStart2 + size + tEnd = tStart + size + path.append([tEnd, qEnd]) + break + tStart1, qStart1 = tEnd1, qEnd1 + for tEnd1, qEnd1 in coordinates1: + if tStart1 < tEnd1 and qStart1 < qEnd1: + break + tStart1, qStart1 = tEnd1, qEnd1 + else: + size = qEnd2 - qStart2 + break + qStart2 += size + tStart2 += size + tStart2, qStart2 = tEnd2, qEnd2 + coordinates = np.array(path, dtype=np.intp).transpose() + if strand1 != strand2: + coordinates[1, :] = n2 - coordinates[1, :] + sequences = [target, query] + alignment = Alignment(sequences, coordinates) + return alignment + + def mapall(self, alignments): + """Map each of the alignments to self, and return the mapped alignment.""" + factor = None + alignments = list(alignments) + for alignment in alignments: + steps = np.diff(alignment.coordinates, 1) + aligned = sum(steps != 0, 0) > 1 + steps = steps[:, aligned] + step1, step2 = steps.sum(1) + if step1 == step2: + step = 1 # nucleotide-nucleotide or protein-protein alignment + elif step1 == -step2: + step = 1 # nucleotide-nucleotide alignment on reverse strand + elif step2 == 3 * step1: + step = 3 # protein-nucleotide alignment + else: + raise ValueError(f"unexpected steps {step1}, {step2}") + if factor is None: + factor = step + elif factor != step: + raise ValueError("inconsistent step sizes in alignments") + steps = abs(self.coordinates[:, 1:] - self.coordinates[:, :-1]).max(0).clip(0) + coordinates = np.empty((2, len(steps) + 1), np.intp) + coordinates[0, 0] = 0 + coordinates[0, 1:] = factor * np.cumsum(steps) + sequences = [Seq(None, length=coordinates[0, -1]), None] + for i, alignment in enumerate(alignments): + coordinates[1, :] = factor * self.coordinates[i, :] + sequences[1] = Seq(None, length=coordinates[1, -1]) + alignment1 = Alignment(sequences, coordinates) + coordinates2 = alignment.coordinates.copy() + coordinates2[0, :] *= factor + sequences2 = [sequences[1], alignment.sequences[1]] + alignment2 = Alignment(sequences2, coordinates2) + alignments[i] = alignment1.map(alignment2) + coordinates = [[] for i in range(len(alignments))] + done = False + while done is False: + done = True + position = min( + alignment.coordinates[0, 0] + for alignment in alignments + if alignment.coordinates.size + ) + for i, alignment in enumerate(alignments): + if alignment.coordinates.size == 0: + coordinates[i].append(coordinates[i][-1]) + elif alignment.coordinates[0, 0] == position: + coordinates[i].append(alignment.coordinates[1, 0]) + alignment.coordinates = alignment.coordinates[:, 1:] + if alignment.coordinates.any(): + done = False + elif alignment.coordinates[0, 0] > position: + if len(coordinates[i]): + if alignment.coordinates[1, 0] > coordinates[i][-1]: + step = position - previous # noqa: F821 + else: + step = 0 + coordinates[i].append(coordinates[i][-1] + step) + else: + coordinates[i].append(alignment.coordinates[1, 0]) + else: + raise Exception + previous = position + sequences = [alignment.sequences[1] for alignment in alignments] + coordinates = np.array(coordinates, np.intp) + alignment = Alignment(sequences, coordinates) + return alignment + + @property + def substitutions(self): + """Return an Array with the number of substitutions of letters in the alignment. + + As an example, consider a sequence alignment of two RNA sequences: + + >>> from Bio.Align import PairwiseAligner + >>> target = "ATACTTACCTGGCAGGGGAGATACCATGATCACGAAGGTGGTTTTCCCAGGGCGAGGCTTATCCATTGCACTCCGGATGTGCTGACCCCTGCGATTTCCCCAAATGTGGGAAACTCGACTGCATAATTTGTGGTAGTGGGGGACTGCGTTCGCGCTTTCCCCTG" # human spliceosomal small nuclear RNA U1 + >>> query = "ATACTTACCTGACAGGGGAGGCACCATGATCACACAGGTGGTCCTCCCAGGGCGAGGCTCTTCCATTGCACTGCGGGAGGGTTGACCCCTGCGATTTCCCCAAATGTGGGAAACTCGACTGTATAATTTGTGGTAGTGGGGGACTGCGTTCGCGCTATCCCCCG" # sea lamprey spliceosomal small RNA U1 + >>> aligner = PairwiseAligner() + >>> aligner.gap_score = -10 + >>> alignments = aligner.align(target, query) + >>> len(alignments) + 1 + >>> alignment = alignments[0] + >>> print(alignment) + target 0 ATACTTACCTGGCAGGGGAGATACCATGATCACGAAGGTGGTTTTCCCAGGGCGAGGCTT + 0 |||||||||||.||||||||..|||||||||||..|||||||..|||||||||||||||. + query 0 ATACTTACCTGACAGGGGAGGCACCATGATCACACAGGTGGTCCTCCCAGGGCGAGGCTC + + target 60 ATCCATTGCACTCCGGATGTGCTGACCCCTGCGATTTCCCCAAATGTGGGAAACTCGACT + 60 .|||||||||||.|||..|.|.|||||||||||||||||||||||||||||||||||||| + query 60 TTCCATTGCACTGCGGGAGGGTTGACCCCTGCGATTTCCCCAAATGTGGGAAACTCGACT + + target 120 GCATAATTTGTGGTAGTGGGGGACTGCGTTCGCGCTTTCCCCTG 164 + 120 |.||||||||||||||||||||||||||||||||||.|||||.| 164 + query 120 GTATAATTTGTGGTAGTGGGGGACTGCGTTCGCGCTATCCCCCG 164 + + >>> m = alignment.substitutions + >>> print(m) + A C G T + A 28.0 1.0 2.0 1.0 + C 0.0 39.0 1.0 2.0 + G 2.0 0.0 45.0 0.0 + T 2.0 5.0 1.0 35.0 + + + Note that the matrix is not symmetric: rows correspond to the target + sequence, and columns to the query sequence. For example, the number + of T's in the target sequence that are aligned to a C in the query + sequence is + + >>> m['T', 'C'] + 5.0 + + and the number of C's in the query sequence tat are aligned to a T in + the query sequence is + + >>> m['C', 'T'] + 2.0 + + For some applications (for example, to define a scoring matrix from + the substitution matrix), a symmetric matrix may be preferred, which + can be calculated as follows: + + >>> m += m.transpose() + >>> m /= 2.0 + >>> print(m) + A C G T + A 28.0 0.5 2.0 1.5 + C 0.5 39.0 0.5 3.5 + G 2.0 0.5 45.0 0.5 + T 1.5 3.5 0.5 35.0 + + + The matrix is now symmetric, with counts divided equally on both sides + of the diagonal: + + >>> m['C', 'T'] + 3.5 + >>> m['T', 'C'] + 3.5 + + The total number of substitutions between T's and C's in the alignment + is 3.5 + 3.5 = 7. + """ + coordinates = self.coordinates.copy() + sequences = list(self.sequences) + steps = np.diff(self.coordinates, 1) + aligned = sum(steps != 0, 0) > 1 + # True for steps in which at least two sequences align, False if a gap + for i, sequence in enumerate(sequences): + row = steps[i, aligned] + if (row >= 0).all(): + pass + elif (row <= 0).all(): + sequences[i] = reverse_complement(sequence) + coordinates[i, :] = len(sequence) - coordinates[i, :] + else: + raise ValueError(f"Inconsistent steps in row {i}") + letters = set() + for sequence in sequences: + try: + s = set(sequence) + except UndefinedSequenceError: + try: + sequence = sequence.seq # SeqRecord confusion + except AttributeError: + pass + for start, end in sequence.defined_ranges: + s = set(sequence[start:end]) + letters.update(s) + else: + letters.update(s) + letters = "".join(sorted(letters)) + m = substitution_matrices.Array(letters, dims=2) + n = len(sequences) + for i1 in range(n): + sequence1 = sequences[i1] + coordinates1 = coordinates[i1, :] + for i2 in range(i1 + 1, n): + sequence2 = sequences[i2] + coordinates2 = coordinates[i2, :] + start1, start2 = sys.maxsize, sys.maxsize + for end1, end2 in zip(coordinates1, coordinates2): + if start1 < end1 and start2 < end2: # aligned + segment1 = sequence1[start1:end1] + segment2 = sequence2[start2:end2] + if len(segment1) != len(segment2): + raise ValueError("Unequal step sizes in alignment") + for c1, c2 in zip(segment1, segment2): + m[c1, c2] += 1.0 + start1, start2 = end1, end2 + return m + + def counts(self, scoring=None): + """Count the number of identities, mismatches, and gaps of an alignment. + + This method takes a single optional argument named scoring, which can be either None + (default), a substitution matrix, a wildcard character, or a pairwise + aligner object: + + - If the argument is a substitution matrix, (typically from the + ``Bio.Align.substitution_matrices`` submodule), then use it to + calculate the total substitution score for the alignment, as well as + the number of positive matches. + - If the argument is a single character, then it is interpreted as the + wildcard character. This character is ignored in the calculation of + the number of matches, mismatches, and positives. + - If the argument is pairwise aligner object, then use it to set the + wildcard character (if set) and also calculate the alignment score, + the gap scores, and the total substitution score. If the aligner has + an associated substitution matrix, then use it to calculate these + scores, and also calculate the number of positive matches. + + >>> aligner = PairwiseAligner(mode='global', match_score=2, mismatch_score=-1) + >>> for alignment in aligner.align("TACCG", "ACG"): + ... print("Score = %.1f:" % alignment.score) + ... c = alignment.counts() + ... print(f"{c.gaps} gaps, {c.identities} identities, {c.mismatches} mismatches") + ... print(alignment) + ... + Score = 4.0: + 2 gaps, 3 identities, 0 mismatches + target 0 TACCG 5 + 0 -||-| 5 + query 0 -AC-G 3 + + Score = 4.0: + 2 gaps, 3 identities, 0 mismatches + target 0 TACCG 5 + 0 -|-|| 5 + query 0 -A-CG 3 + + + The counts are calculated by summing over all pairs of sequences in the + alignment. + + An `AlignmentCounts` object has the following properties: + + - score - the alignment score (calculated only if the + argument is a pairwise aligner, and set to None + otherwise); + - aligned - the number of letters aligned to each other in + the alignment; + - substitution_score - the total substitution score of letters aligned + to each other (calculated only if the argument + is a pairwise aligner or a substitution matrix, + and set to None otherwise); + - identities - the number of identical letters in the + alignment; + - mismatches - the number of mismatched letters in the + alignment; + - positives - the number of aligned letters with a positive + score (set to None if no substitution matrix is + defined); + - gap_score - the total gap score (calculated only if the + argument is a pairwise aligner, and set to None + otherwise); + - gaps - the total gap length; + - open_gaps - the number of gaps opened in the alignment; + - extend_gaps - the number of gap extensions in the alignment; + - open_left_gaps - the number of gaps opened on the left side of + the alignment; + - open_right_gaps - the number of gaps opened on the right side of + the alignment; + - open_internal_gaps - the number of gaps opened in the interior of the + alignment; + - extend_left_gaps - the number of gap extensions on the left side of + the alignment; + - extend_right_gaps - the number of gap extensions on the right side + of the alignment; + - extend_internal_gaps - the number of gap extensions in the interior of + the alignment; + - open_left_insertions - the number of insertion gaps opened on the left + side of the alignment; + - open_left_deletions - the number of deletion gaps opened on the left + side of the alignment; + - open_right_insertions - the number of insertion gaps opened on the right + side of the alignment; + - open_right_deletions - the number of deletion gaps opened on the right + side of the alignment; + - open_internal_insertions - the number of insertion gaps opened in the + interior of the alignment; + - open_internal_deletions - the number of deletion gaps opened in the + interior of the alignment; + - extend_left_insertions - the number of insertion gap extensions on the + left side of the alignment; + - extend_left_deletions - the number of deletion gap extensions on the + left side of the alignment; + - extend_right_insertions - the number of insertion gap extensions on the + right side of the alignment; + - extend_right_deletions - the number of deletion gap extensions on the + right side of the alignment; + - extend_internal_insertions - the number of insertion gap extensions in the + interior of the alignment; + - extend_internal_deletions - the number of deletion gap extensions in the + interior of the alignment; + - left_insertions - the number of letters inserted on the left side + of the alignment; + - left_deletions - the number of letters deleted on the left side + of the alignment; + - right_insertions - the number of letters inserted on the right side + of the alignment; + - right_deletions - the number of letters deleted on the right side + of the alignment; + - internal_insertions - the number of letters inserted in the interior + of the alignment; + - internal_deletions - the number of letters deleted in the interior of + the alignment; + - insertions - the total number of letters inserted; + - deletions - the total number of letters deleted; + - left_gaps - the total gap length on the left side of the + alignment; + - right_gaps - the total gap length on the right side of the + alignment; + - internal_gaps - the total gap length in the interior of the + alignment. + """ + aligner = None + wildcard = None + substitution_matrix = None + if isinstance(scoring, PairwiseAligner): + aligner = scoring + substitution_matrix = aligner.substitution_matrix + elif isinstance(scoring, str): + wildcard = scoring + elif isinstance(scoring, (np.ndarray, substitution_matrices.Array)): + substitution_matrix = scoring + elif scoring is not None: + raise ValueError(f"unexpected argument {scoring!r}") + if substitution_matrix is None: + alphabet = [] + codec = "utf-32-le" if sys.byteorder == "little" else "utf-32-be" + n = len(self.sequences) + sequences = [None] * n + strands = np.zeros(n, bool) + coordinates = self.coordinates.copy() + steps = np.diff(coordinates, 1) + aligned_flags = sum(steps != 0, 0) > 1 + # True for steps in which at least two sequences align, False if a gap + for i, sequence in enumerate(self.sequences): + aligned_steps = steps[i, aligned_flags] + if sum(aligned_steps > 0) < sum(aligned_steps < 0): + sequence = reverse_complement(sequence) + coordinates[i, :] = len(sequence) - coordinates[i, :] + strands[i] = True + try: + sequence = sequence.seq # stupid SeqRecord + except AttributeError: + pass + try: + data = sequence._data + except AttributeError: + data = sequence + if isinstance(data, (bytes, bytearray)): + sequences[i] = data + elif isinstance(data, str): + sequences[i] = np.frombuffer(bytearray(data, codec), dtype="i") + elif isinstance(data, SequenceDataAbstractBaseClass): + sequences[i] = data + elif isinstance(data, np.ndarray): + # data is a numpy array of int32 + # (to be checked in the C code) + sequences[i] = data + elif data is None: + sequences[i] = data + else: + if substitution_matrix is None: + for item in data: + if not any(item == letter for letter in alphabet): + alphabet.append(item) + else: + alphabet = substitution_matrix.alphabet + sequences[i] = np.fromiter( + map(alphabet.index, data), dtype="i", count=len(data) + ) + if aligner is not None: + return _alignmentcounts.AlignmentCounts( + sequences, coordinates, strands, aligner + ) + elif wildcard is not None: + return _alignmentcounts.AlignmentCounts( + sequences, coordinates, strands, wildcard + ) + elif substitution_matrix is not None: + return _alignmentcounts.AlignmentCounts( + sequences, coordinates, strands, substitution_matrix + ) + else: + return _alignmentcounts.AlignmentCounts(sequences, coordinates, strands) + + def reverse_complement(self): + """Reverse-complement the alignment and return it. + + >>> sequences = ["ATCG", "AAG", "ATC"] + >>> coordinates = np.array([[0, 2, 3, 4], [0, 2, 2, 3], [0, 2, 3, 3]]) + >>> alignment = Alignment(sequences, coordinates) + >>> print(alignment) + 0 ATCG 4 + 0 AA-G 3 + 0 ATC- 3 + + >>> rc_alignment = alignment.reverse_complement() + >>> print(rc_alignment) + 0 CGAT 4 + 0 C-TT 3 + 0 -GAT 3 + + + The attribute `column_annotations`, if present, is associated with the + reverse-complemented alignment, with its values in reverse order. + + >>> alignment.column_annotations = {"score": [3, 2, 2, 2]} + >>> rc_alignment = alignment.reverse_complement() + >>> print(rc_alignment.column_annotations) + {'score': [2, 2, 2, 3]} + """ + sequences = [reverse_complement(sequence) for sequence in self.sequences] + coordinates = np.array( + [ + len(sequence) - row[::-1] + for sequence, row in zip(sequences, self.coordinates) + ], + dtype=np.intp, + ) + alignment = Alignment(sequences, coordinates) + try: + column_annotations = self.column_annotations + except AttributeError: + pass + else: + alignment.column_annotations = {} + for key, value in column_annotations.items(): + if isinstance(value, np.ndarray): + value = value[::-1].copy() + else: + value = value[::-1] + alignment.column_annotations[key] = value + return alignment + + +class AlignmentsAbstractBaseClass(ABC): + """Abstract base class for sequence alignments. + + Most users will not need to use this class. It is used internally as a base + class for the list-like Alignments class, and for the AlignmentIterator + class in Bio.Align.interfaces, which itself is the abstract base class for + the alignment parsers in Bio/Align/. + """ + + def __iter__(self): + """Iterate over the alignments as Alignment objects. + + This method SHOULD NOT be overridden by any subclass. + """ + self.rewind() + return self + + @abstractmethod + def __next__(self): + """Return the next alignment.""" + + @abstractmethod + def rewind(self): + """Rewind the iterator to let it loop over the alignments from the beginning.""" + + @abstractmethod + def __len__(self): + """Return the number of alignments.""" + + +class Alignments(AlignmentsAbstractBaseClass, list): # noqa: D101 + def __init__(self, alignments=()): # noqa: D107 + super().__init__(alignments) + self._index = -1 + + def __next__(self): + index = self._index + 1 + try: + item = self[index] + except IndexError: + raise StopIteration + self._index = index + return item + + def rewind(self): # noqa: D102 + self._index = -1 + + def __len__(self): + return list.__len__(self) + + +class PairwiseAlignments(AlignmentsAbstractBaseClass): + """Implements an iterator over pairwise alignments returned by the aligner. + + This class also supports indexing, which is fast for increasing indices, + but may be slow for random access of a large number of alignments. + + Note that pairwise aligners can return an astronomical number of alignments, + even for relatively short sequences, if they align poorly to each other. We + therefore recommend to first check the number of alignments, accessible as + len(alignments), which can be calculated quickly even if the number of + alignments is very large. + """ + + def __init__(self, seqA, seqB, score, paths): + """Initialize a new PairwiseAlignments object. + + Arguments: + - seqA - The first sequence, as a plain string, without gaps. + - seqB - The second sequence, as a plain string, without gaps. + - score - The alignment score. + - paths - An iterator over the paths in the traceback matrix; + each path defines one alignment. + + You would normally obtain a PairwiseAlignments object by calling + aligner.align(seqA, seqB), where aligner is a PairwiseAligner object + or a CodonAligner object. + """ + self.sequences = [seqA, seqB] + self.score = score + self._paths = paths + self._index = -1 + + def __len__(self): + return len(self._paths) + + def __repr__(self): + try: + length = len(self._paths) + except OverflowError: + length = f">{sys.maxsize} alignments" + else: + if length == 1: + length = "1 alignment" + else: + length = f"{length} alignments" + pointer = hex(id(self)) + score = format(self.score, "g") + return f"" + + def __getitem__(self, index): + if not isinstance(index, int): + raise TypeError(f"index must be an integer, not {index.__class__.__name__}") + if index < 0: + index += len(self._paths) + if index == self._index: + return self._alignment + if index < self._index: + self._paths.reset() + self._index = -1 + while True: + try: + alignment = next(self) + except StopIteration: + raise IndexError("index out of range") from None + if self._index == index: + break + return alignment + + def __next__(self): + path = next(self._paths) + self._index += 1 + coordinates = np.array(path, dtype=np.intp) + alignment = Alignment(self.sequences, coordinates) + alignment.score = self.score + self._alignment = alignment + return alignment + + def rewind(self): # noqa: D102 + self._paths.reset() + self._index = -1 + + +class PairwiseAligner(_pairwisealigner.PairwiseAligner): + """Performs pairwise sequence alignment using dynamic programming. + + This provides functions to get global and local alignments between two + sequences. A global alignment finds the best concordance between all + characters in two sequences. A local alignment finds just the + subsequences that align the best. + + To perform a pairwise sequence alignment, first create a PairwiseAligner + object. This object stores the match and mismatch scores, as well as the + gap scores. Typically, match scores are positive, while mismatch scores + and gap scores are negative or zero. By default, the match score is 1, + and the mismatch and gap scores are zero. Based on the values of the gap + scores, a PairwiseAligner object automatically chooses the appropriate + alignment algorithm (the Needleman-Wunsch, Smith-Waterman, Gotoh, or + Waterman-Smith-Beyer global or local alignment algorithm, or the Fast + Optimal Global Sequence Alignment Algorithm). + + The Fast Optimal Global Sequence Alignment Algorithm (FOGSAA) will never be + automatically selected. If you wish to use FOGSAA, you must set the "mode" + attribute to "fogsaa". As its name suggests, it only finds global + alignments and cannot be used for local alignment. FOGSAA will raise a + warning and may return incorrect results if the match score is less than + the mismatch score or any gap score or if any gap score is greater than the + mismatch score. + + Calling the "score" method on the aligner with two sequences as arguments + will calculate the alignment score between the two sequences. + Calling the "align" method on the aligner with two sequences as arguments + will return a generator yielding the alignments between the two + sequences. + + Some examples: + + >>> from Bio import Align + >>> aligner = Align.PairwiseAligner() + >>> alignments = aligner.align("TACCG", "ACG") + >>> for alignment in sorted(alignments): + ... print("Score = %.1f:" % alignment.score) + ... print(alignment) + ... + Score = 1.0: + target 0 TACCG 5 + 0 -|-|| 5 + query 0 -A-CG 3 + + Score = 1.0: + target 0 TACCG 5 + 0 -||-| 5 + query 0 -AC-G 3 + + + Specify the aligner mode as local to generate local alignments: + + >>> aligner.mode = 'local' + >>> alignments = aligner.align("TACCG", "ACG") + >>> for alignment in sorted(alignments): + ... print("Score = %.1f:" % alignment.score) + ... print(alignment) + ... + Score = 2.0: + target 1 AC 3 + 0 || 2 + query 0 AC 2 + + Score = 2.0: + target 3 CG 5 + 0 || 2 + query 1 CG 3 + + + Do a global alignment. Identical characters are given 2 points, + 1 point is deducted for each non-identical character. + + >>> aligner.mode = 'global' + >>> aligner.match_score = 2 + >>> aligner.mismatch_score = -1 + >>> for alignment in aligner.align("TACCG", "ACG"): + ... print("Score = %.1f:" % alignment.score) + ... print(alignment) + ... + Score = 4.0: + target 0 TACCG 5 + 0 -||-| 5 + query 0 -AC-G 3 + + Score = 4.0: + target 0 TACCG 5 + 0 -|-|| 5 + query 0 -A-CG 3 + + + Same as above, except now 0.5 points are deducted when opening a + gap, and 0.1 points are deducted when extending it. + + >>> aligner.open_gap_score = -0.5 + >>> aligner.extend_gap_score = -0.1 + >>> aligner.end_gap_score = 0.0 + >>> for alignment in aligner.align("TACCG", "ACG"): + ... print("Score = %.1f:" % alignment.score) + ... print(alignment) + ... + Score = 5.5: + target 0 TACCG 5 + 0 -|-|| 5 + query 0 -A-CG 3 + + Score = 5.5: + target 0 TACCG 5 + 0 -||-| 5 + query 0 -AC-G 3 + + + The alignment function can also use known matrices already included in + Biopython: + + >>> from Bio.Align import substitution_matrices + >>> aligner = Align.PairwiseAligner() + >>> aligner.substitution_matrix = substitution_matrices.load("BLOSUM62") + >>> alignments = aligner.align("KEVLA", "EVL") + >>> alignments = list(alignments) + >>> print("Number of alignments: %d" % len(alignments)) + Number of alignments: 1 + >>> alignment = alignments[0] + >>> print("Score = %.1f" % alignment.score) + Score = 11.0 + >>> print(alignment) + target 0 KEVLA 5 + 0 -|||- 5 + query 0 -EVL- 3 + + + You can also set the value of attributes directly during construction + of the PairwiseAligner object by providing them as keyword arguments: + + >>> aligner = Align.PairwiseAligner(mode='global', match_score=2, mismatch_score=-1) + >>> for alignment in aligner.align("TACCG", "ACG"): + ... print("Score = %.1f:" % alignment.score) + ... print(alignment) + ... + Score = 4.0: + target 0 TACCG 5 + 0 -||-| 5 + query 0 -AC-G 3 + + Score = 4.0: + target 0 TACCG 5 + 0 -|-|| 5 + query 0 -A-CG 3 + + + """ + + codec = "utf-32-le" if sys.byteorder == "little" else "utf-32-be" + + def __init__(self, scoring=None, **kwargs): + """Initialize a PairwiseAligner as specified by the keyword arguments. + + If scoring is None, use the default scoring scheme match = 1.0, + mismatch = 0.0, gap score = 0.0 + If scoring is "blastn", "megablast", or "blastp", use the default + substitution matrix and gap scores for BLASTN, MEGABLAST, or BLASTP, + respectively. + + Loops over the remaining keyword arguments and sets them as attributes + on the object. + """ + super().__init__() + if scoring is None: + # use default values: + # match = 1.0 + # mismatch = 0.0 + # gap_score = -1.0 + pass + elif scoring == "blastn": + self.substitution_matrix = substitution_matrices.load("BLASTN") + self.open_gap_score = -7.0 + self.extend_gap_score = -2.0 + elif scoring == "megablast": + self.substitution_matrix = substitution_matrices.load("MEGABLAST") + self.open_gap_score = -2.5 + self.extend_gap_score = -2.5 + elif scoring == "blastp": + self.substitution_matrix = substitution_matrices.load("BLASTP") + self.open_gap_score = -12.0 + self.extend_gap_score = -1.0 + else: + raise ValueError("Unknown scoring scheme '%s'" % scoring) + for name, value in kwargs.items(): + setattr(self, name, value) + + _new_keys = { + "target_internal_open_gap_score": "open_internal_insertion_score", + "target_internal_extend_gap_score": "extend_internal_insertion_score", + "target_internal_gap_score": "internal_insertion_score", + "target_left_open_gap_score": "open_left_insertion_score", + "target_left_extend_gap_score": "extend_left_insertion_score", + "target_left_gap_score": "left_insertion_score", + "target_right_open_gap_score": "open_right_insertion_score", + "target_right_extend_gap_score": "extend_right_insertion_score", + "target_right_gap_score": "right_insertion_score", + "query_internal_open_gap_score": "open_internal_deletion_score", + "query_internal_extend_gap_score": "extend_internal_deletion_score", + "query_left_open_gap_score": "open_left_deletion_score", + "query_left_extend_gap_score": "extend_left_deletion_score", + "query_right_open_gap_score": "open_right_deletion_score", + "query_right_extend_gap_score": "extend_right_deletion_score", + "target_gap_function": "insertion_score_function", + "query_gap_function": "deletion_score_function", + "internal_open_gap_score": "open_internal_gap_score", + "internal_extend_gap_score": "extend_internal_gap_score", + "left_open_gap_score": "open_left_gap_score", + "left_extend_gap_score": "extend_left_gap_score", + "right_open_gap_score": "open_right_gap_score", + "right_extend_gap_score": "extend_right_gap_score", + "end_open_gap_score": "open_end_gap_score", + "end_extend_gap_score": "extend_end_gap_score", + "target_gap_score": "insertion_score", + "target_open_gap_score": "open_insertion_score", + "target_extend_gap_score": "extend_insertion_score", + "target_end_gap_score": "end_insertion_score", + "target_end_open_gap_score": "open_end_insertion_score", + "target_end_extend_gap_score": "extend_end_insertion_score", + "query_gap_score": "deletion_score", + "query_open_gap_score": "open_deletion_score", + "query_extend_gap_score": "extend_deletion_score", + "query_end_gap_score": "end_deletion_score", + "query_end_open_gap_score": "open_end_deletion_score", + "query_end_extend_gap_score": "extend_end_deletion_score", + "query_internal_gap_score": "internal_deletion_score", + "query_left_gap_score": "left_deletion_score", + "query_right_gap_score": "right_deletion_score", + } + + def __setattr__(self, key, value): + try: + new_key = self._new_keys[key] + except KeyError: + if key == "alphabet": + warnings.warn( + "The alphabet property is deprecated. The current " + "implementation stores the alphabet, but does not use it.", + BiopythonDeprecationWarning, + ) + _pairwisealigner.PairwiseAligner.__setattr__(self, key, value) + return + if key not in dir(_pairwisealigner.PairwiseAligner): + # To prevent confusion, don't allow users to create new attributes. + # On CPython, __slots__ can be used for this, but currently + # __slots__ does not behave the same way on PyPy at least. + raise AttributeError( + "'PairwiseAligner' object has no attribute '%s'" % key + ) + else: + warnings.warn( + """\ +The attribute '%s' was renamed to '%s'. This was done to be consistent with the +AlignmentCounts object returned by the .counts method of an Alignment object.""" + % (key, new_key), + BiopythonDeprecationWarning, + ) + key = new_key + _pairwisealigner.PairwiseAligner.__setattr__(self, key, value) + + def __getattr__(self, key): + try: + new_key = self._new_keys[key] + except KeyError: + if key == "alphabet": + warnings.warn( + "The alphabet property is deprecated. The current " + "implementation stores the alphabet, but does not use it.", + BiopythonDeprecationWarning, + ) + try: + return _pairwisealigner.PairwiseAligner.__getattr__(self, key) + except AttributeError: + return None + else: + warnings.warn( + """\ +The attribute '%s' was renamed to '%s'. This was done to be consistent with the +AlignmentCounts object returned by the .counts method of an Alignment object.""" + % (key, new_key), + BiopythonDeprecationWarning, + ) + key = new_key + return _pairwisealigner.PairwiseAligner.__getattribute__(self, key) + + def align(self, seqA, seqB, strand="+"): + """Return the alignments of two sequences using PairwiseAligner.""" + # self.warn_defaults_changed() # FIXME remove this after 1.87 is out + if isinstance(seqA, (bytes, Seq, MutableSeq, SeqRecord)): + sA = bytes(seqA) + sA = np.frombuffer(sA, dtype=np.uint8).astype(np.int32) + elif isinstance(seqA, str): + sA = np.frombuffer(bytearray(seqA, self.codec), dtype=np.int32) + else: + try: + memoryview(seqA) + except TypeError: + substitution_matrix = self.substitution_matrix + if substitution_matrix is None: + alphabet = [] + for item in seqA: + if not any(item == letter for letter in alphabet): + alphabet.append(item) + else: + alphabet = substitution_matrix.alphabet + sA = np.fromiter( + map(alphabet.index, seqA), dtype=np.int32, count=len(seqA) + ) + else: + sA = seqA # C code will check the dtype + if strand == "+": + sB = seqB + else: # strand == "-": + sB = reverse_complement(seqB) + if isinstance(seqB, (bytes, Seq, MutableSeq, SeqRecord)): + sB = bytes(sB) + sB = np.frombuffer(sB, dtype=np.uint8).astype(np.int32) + elif isinstance(seqB, str): + sB = np.frombuffer(bytearray(sB, self.codec), dtype=np.int32) + else: + try: + memoryview(seqB) + except TypeError: + substitution_matrix = self.substitution_matrix + if substitution_matrix is None: + try: + alphabet + except NameError: + alphabet = [] + for item in seqB: + if not any(item == letter for letter in alphabet): + alphabet.append(item) + else: + alphabet = substitution_matrix.alphabet + sB = np.fromiter( + map(alphabet.index, seqB), dtype=np.int32, count=len(seqB) + ) + else: + sB = seqB # C code will test the dtype + score, paths = super().align(sA, sB, strand) + alignments = PairwiseAlignments(seqA, seqB, score, paths) + return alignments + + def score(self, seqA, seqB, strand="+"): + """Return the alignment score of two sequences using PairwiseAligner.""" + # self.warn_defaults_changed() # FIXME remove this after 1.87 is out + if isinstance(seqA, (bytes, Seq, MutableSeq, SeqRecord)): + seqA = bytes(seqA) + seqA = np.frombuffer(seqA, dtype=np.uint8).astype(np.int32) + elif isinstance(seqA, str): + seqA = np.frombuffer(bytearray(seqA, self.codec), dtype="i") + else: + try: + memoryview(seqA) + except TypeError: + substitution_matrix = self.substitution_matrix + if substitution_matrix is None: + alphabet = [] + for item in seqA: + if not any(item == letter for letter in alphabet): + alphabet.append(item) + else: + alphabet = substitution_matrix.alphabet + seqA = np.fromiter( + map(alphabet.index, seqA), dtype=np.int32, count=len(seqA) + ) + if strand == "-": + seqB = reverse_complement(seqB) + if isinstance(seqB, (bytes, Seq, MutableSeq, SeqRecord)): + seqB = bytes(seqB) + seqB = np.frombuffer(seqB, dtype=np.uint8).astype(np.int32) + elif isinstance(seqB, str): + seqB = np.frombuffer(bytearray(seqB, self.codec), dtype="i") + else: + try: + memoryview(seqB) + except TypeError: + substitution_matrix = self.substitution_matrix + if substitution_matrix is None: + try: + alphabet + except NameError: + alphabet = [] + for item in seqB: + if not any(item == letter for letter in alphabet): + alphabet.append(item) + else: + alphabet = substitution_matrix.alphabet + seqB = np.fromiter( + map(alphabet.index, seqB), dtype=np.int32, count=len(seqB) + ) + return super().score(seqA, seqB, strand) + + def __getstate__(self): + state = { + "wildcard": self.wildcard, + "open_internal_insertion_score": self.open_internal_insertion_score, + "extend_internal_insertion_score": self.extend_internal_insertion_score, + "open_left_insertion_score": self.open_left_insertion_score, + "extend_left_insertion_score": self.extend_left_insertion_score, + "open_right_insertion_score": self.open_right_insertion_score, + "extend_right_insertion_score": self.extend_right_insertion_score, + "open_internal_deletion_score": self.open_internal_deletion_score, + "extend_internal_deletion_score": self.extend_internal_deletion_score, + "open_left_deletion_score": self.open_left_deletion_score, + "extend_left_deletion_score": self.extend_left_deletion_score, + "open_right_deletion_score": self.open_right_deletion_score, + "extend_right_deletion_score": self.extend_right_deletion_score, + "mode": self.mode, + "epsilon": self.epsilon, + } + if self.substitution_matrix is None: + state["match_score"] = self.match_score + state["mismatch_score"] = self.mismatch_score + else: + state["substitution_matrix"] = self.substitution_matrix + return state + + def __setstate__(self, state): + self.wildcard = state["wildcard"] + self.open_internal_insertion_score = state["open_internal_insertion_score"] + self.extend_internal_insertion_score = state["extend_internal_insertion_score"] + self.open_left_insertion_score = state["open_left_insertion_score"] + self.extend_left_insertion_score = state["extend_left_insertion_score"] + self.open_right_insertion_score = state["open_right_insertion_score"] + self.extend_right_insertion_score = state["extend_right_insertion_score"] + self.open_internal_deletion_score = state["open_internal_deletion_score"] + self.extend_internal_deletion_score = state["extend_internal_deletion_score"] + self.open_left_deletion_score = state["open_left_deletion_score"] + self.extend_left_deletion_score = state["extend_left_deletion_score"] + self.open_right_deletion_score = state["open_right_deletion_score"] + self.extend_right_deletion_score = state["extend_right_deletion_score"] + self.mode = state["mode"] + self.epsilon = state["epsilon"] + substitution_matrix = state.get("substitution_matrix") + if substitution_matrix is None: + self.match_score = state["match_score"] + self.mismatch_score = state["mismatch_score"] + else: + self.substitution_matrix = substitution_matrix + + +class CodonAligner(_codonaligner.CodonAligner): + """Aligns a nucleotide sequence to an amino acid sequence. + + This class implements a dynamic programming algorithm to align a nucleotide + sequence to an amino acid sequence. + """ + + def __init__(self, codon_table=None, anchor_len=10): + """Initialize a CodonAligner for a specific genetic code. + + Arguments: + - codon_table - a CodonTable object representing the genetic code. + If codon_table is None, the standard genetic code is used. + + """ + super().__init__() + if codon_table is None: + codon_table = CodonTable.generic_by_id[1] + elif not isinstance(codon_table, CodonTable.CodonTable): + raise TypeError("Input table is not a CodonTable object") + self.codon_table = codon_table + + def score(self, seqA, seqB): + """Return the alignment score of a protein sequence and nucleotide sequence. + + Arguments: + - seqA - the protein sequence of amino acids (plain string, Seq, + MutableSeq, or SeqRecord). + - seqB - the nucleotide sequence (plain string, Seq, MutableSeq, or + SeqRecord); both DNA and RNA sequences are accepted. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> aligner = CodonAligner() + >>> dna = SeqRecord(Seq('ATGTCTCGT'), id='dna') + >>> pro = SeqRecord(Seq('MSR'), id='pro') + >>> score = aligner.score(pro, dna) + >>> print(score) + 3.0 + >>> rna = SeqRecord(Seq('AUGUCUCGU'), id='rna') + >>> score = aligner.score(pro, rna) + >>> print(score) + 3.0 + + This is an example with a frame shift in the DNA sequence: + + >>> dna = "ATGCTGGGCTCGAACGAGTCCGTGTATGCCCTAAGCTGAGCCCGTCG" + >>> pro = "MLGSNESRVCPKLSPS" + >>> len(pro) + 16 + >>> aligner.frameshift_score = -3.0 + >>> score = aligner.score(pro, dna) + >>> print(score) + 13.0 + + In the following example, the position of the frame shift is ambiguous: + + >>> dna = 'TTTAAAAAAAAAAATTT' + >>> pro = 'FKKKKF' + >>> len(pro) + 6 + >>> aligner.frameshift_score = -1.0 + >>> alignments = aligner.align(pro, dna) + >>> print(alignments.score) + 5.0 + >>> len(alignments) + 3 + >>> print(next(alignments)) + target 0 F K K K 4 + query 0 TTTAAAAAAAAA 12 + + target 4 K F 6 + query 11 AAATTT 17 + + >>> print(next(alignments)) + target 0 F K K 3 + query 0 TTTAAAAAA 9 + + target 3 K K F 6 + query 8 AAAAAATTT 17 + + >>> print(next(alignments)) + target 0 F K 2 + query 0 TTTAAA 6 + + target 2 K K K F 6 + query 5 AAAAAAAAATTT 17 + + >>> print(next(alignments)) + Traceback (most recent call last): + ... + StopIteration + + """ + codon_table = self.codon_table + if isinstance(seqA, (Seq, MutableSeq, SeqRecord)): + sA = bytes(seqA) + elif isinstance(seqA, str): + sA = seqA.encode() + else: + raise ValueError( + "seqA must be a string, Seq, MutableSeq, or SeqRecord object" + ) + seqB0 = seqB[: 3 * (len(seqB) // 3)] + seqB1 = seqB[1 : 1 + 3 * ((len(seqB) - 1) // 3)] + seqB2 = seqB[2 : 2 + 3 * ((len(seqB) - 2) // 3)] + if isinstance(seqB, (Seq, MutableSeq, SeqRecord)): + sB0 = seqB0.translate(codon_table) + sB1 = seqB1.translate(codon_table) + sB2 = seqB2.translate(codon_table) + sB0 = bytes(sB0) + sB1 = bytes(sB1) + sB2 = bytes(sB2) + elif isinstance(seqA, str): + sB0 = translate(seqB0, codon_table) + sB1 = translate(seqB1, codon_table) + sB2 = translate(seqB2, codon_table) + sB0 = sB0.encode() + sB1 = sB1.encode() + sB2 = sB2.encode() + else: + raise ValueError( + "seqB must be a string, Seq, MutableSeq, or SeqRecord object" + ) + return super().score(sA, sB0, sB1, sB2) + + def align(self, seqA, seqB): + """Align a nucleotide sequence to its corresponding protein sequence. + + Arguments: + - seqA - the protein sequence of amino acids (plain string, Seq, + MutableSeq, or SeqRecord). + - seqB - the nucleotide sequence (plain string, Seq, MutableSeq, or + SeqRecord); both DNA and RNA sequences are accepted. + + Returns an iterator of Alignment objects. + + >>> from Bio.Seq import Seq + >>> from Bio.SeqRecord import SeqRecord + >>> aligner = CodonAligner() + >>> dna = SeqRecord(Seq('ATGTCTCGT'), id='dna') + >>> pro = SeqRecord(Seq('MSR'), id='pro') + >>> alignments = aligner.align(pro, dna) + >>> alignment = alignments[0] + >>> print(alignment) + pro 0 M S R 3 + dna 0 ATGTCTCGT 9 + + >>> rna = SeqRecord(Seq('AUGUCUCGU'), id='rna') + >>> alignments = aligner.align(pro, rna) + >>> alignment = alignments[0] + >>> print(alignment) + pro 0 M S R 3 + rna 0 AUGUCUCGU 9 + + + This is an example with a frame shift in the DNA sequence: + + >>> dna = "ATGCTGGGCTCGAACGAGTCCGTGTATGCCCTAAGCTGAGCCCGTCG" + >>> pro = "MLGSNESRVCPKLSPS" + >>> alignments = aligner.align(pro, dna) + >>> alignment = alignments[0] + >>> print(alignment) + target 0 M L G S N E S 7 + query 0 ATGCTGGGCTCGAACGAGTCC 21 + + target 7 R V C P K L S P S 16 + query 20 CGTGTATGCCCTAAGCTGAGCCCGTCG 47 + + + """ + codon_table = self.codon_table + if isinstance(seqA, (Seq, MutableSeq, SeqRecord)): + sA = bytes(seqA) + elif isinstance(seqA, str): + sA = seqA.encode() + else: + raise ValueError( + "seqA must be a string, Seq, MutableSeq, or SeqRecord object" + ) + seqB0 = seqB[: 3 * (len(seqB) // 3)] + seqB1 = seqB[1 : 1 + 3 * ((len(seqB) - 1) // 3)] + seqB2 = seqB[2 : 2 + 3 * ((len(seqB) - 2) // 3)] + if isinstance(seqB, (Seq, MutableSeq, SeqRecord)): + sB0 = seqB0.translate(codon_table) + sB1 = seqB1.translate(codon_table) + sB2 = seqB2.translate(codon_table) + sB0 = bytes(sB0) + sB1 = bytes(sB1) + sB2 = bytes(sB2) + elif isinstance(seqA, str): + sB0 = translate(seqB0, codon_table) + sB1 = translate(seqB1, codon_table) + sB2 = translate(seqB2, codon_table) + sB0 = sB0.encode() + sB1 = sB1.encode() + sB2 = sB2.encode() + else: + raise ValueError( + "seqB must be a string, Seq, MutableSeq, or SeqRecord object" + ) + score, paths = super().align(sA, sB0, sB1, sB2) + alignments = PairwiseAlignments(seqA, seqB, score, paths) + return alignments + # alignment.column_annotations = {"consensus": consensus} + + +# fmt: off +formats = ( + "a2m", # A2M files created by align2model or hmmscore + "bed", # BED (Browser Extensible Data) files + "bigbed", # bigBed format + "bigmaf", # MAF file saved as a bigBed file + "bigpsl", # PSL file saved as a bigBed file + "chain", # UCSC chain file format + "clustal", # clustal output from CLUSTAL W and other tools. + "emboss", # emboss output from EMBOSS tools such as needle, water + "exonerate", # Exonerate pairwise alignment output + "fasta", # FASTA format with gaps represented by dashes + "hhr", # hhr files generated by HHsearch, HHblits in HH-suite + "maf", # MAF (Multiple Alignment Format) format. + "mauve", # xmfa output from Mauve/ProgressiveMauve + "msf", # MSF format produced by GCG PileUp and LocalPileUp + "nexus", # Nexus file format + "phylip", # Alignment format for input files for PHYLIP tools + "psl", # Pattern Space Layout (PSL) format generated by Blat + "sam", # Sequence Alignment/Map (SAM) format + "stockholm", # Stockholm file format used by PFAM and others + "tabular", # Tabular output from BLAST or FASTA +) +# fmt: on + +_modules: dict[str, types.ModuleType] = {} + + +def _load(fmt: str) -> types.ModuleType: + fmt = fmt.lower() + try: + return _modules[fmt] + except KeyError: + pass + if fmt not in formats: + raise ValueError("Unknown file format %s" % fmt) + module = importlib.import_module(f"Bio.Align.{fmt}") + _modules[fmt] = module + return module + + +def write(alignments, target, fmt, *args, **kwargs): + """Write alignments to a file. + + Arguments: + - alignments - An Alignments object, an iterator of Alignment objects, or + a single Alignment. + - target - File or file-like object to write to, or filename as string. + - fmt - String describing the file format (case-insensitive). + + Note if providing a file or file-like object, your code should close the + target after calling this function, or call .flush(), to ensure the data + gets flushed to disk. + + Returns the number of alignments written (as an integer). + """ + if isinstance(alignments, Alignment): + alignments = [alignments] + + module = _load(fmt) + try: + writer = module.AlignmentWriter + except AttributeError: + raise ValueError( + f"File writing has not yet been implemented for the {fmt} format" + ) + return writer(target, *args, **kwargs).write(alignments) + + +def parse(source, fmt): + """Parse an alignment file and return an iterator over alignments. + + Arguments: + - source - File or file-like object to read from, or filename as string. + - fmt - String describing the file format (case-insensitive). + + Typical usage, opening a file to read in, and looping over the alignments: + + >>> from Bio import Align + >>> filename = "Exonerate/exn_22_m_ner_cigar.exn" + >>> for alignment in Align.parse(filename, "exonerate"): + ... print("Number of sequences in alignment", len(alignment)) + ... print("Alignment score:", alignment.score) + Number of sequences in alignment 2 + Alignment score: 6150.0 + Number of sequences in alignment 2 + Alignment score: 502.0 + Number of sequences in alignment 2 + Alignment score: 440.0 + + For lazy-loading file formats such as bigMaf, for which the file contents + is read on demand only, ensure that the file remains open while extracting + alignment data. + + You can use the Bio.Align.read(...) function when the file contains only + one alignment. + """ + module = _load(fmt) + alignments = module.AlignmentIterator(source) + return alignments + + +def read(handle, fmt): + """Parse a file containing one alignment, and return it. + + Arguments: + - source - File or file-like object to read from, or filename as string. + - fmt - String describing the file format (case-insensitive). + + This function is for use parsing alignment files containing exactly one + alignment. For example, reading a Clustal file: + + >>> from Bio import Align + >>> alignment = Align.read("Clustalw/opuntia.aln", "clustal") + >>> print("Alignment shape:", alignment.shape) + Alignment shape: (7, 156) + >>> for sequence in alignment.sequences: + ... print(sequence.id, len(sequence)) + gi|6273285|gb|AF191659.1|AF191 146 + gi|6273284|gb|AF191658.1|AF191 148 + gi|6273287|gb|AF191661.1|AF191 146 + gi|6273286|gb|AF191660.1|AF191 146 + gi|6273290|gb|AF191664.1|AF191 150 + gi|6273289|gb|AF191663.1|AF191 150 + gi|6273291|gb|AF191665.1|AF191 156 + + If the file contains no records, or more than one record, an exception is + raised. For example: + + >>> from Bio import Align + >>> filename = "Exonerate/exn_22_m_ner_cigar.exn" + >>> alignment = Align.read(filename, "exonerate") + Traceback (most recent call last): + ... + ValueError: More than one alignment found in file + + Use the Bio.Align.parse function if you want to read a file containing + more than one alignment. + """ + with parse(handle, fmt) as alignments: + try: + alignment = next(alignments) + except StopIteration: + raise ValueError("No alignments found in file") from None + try: + next(alignments) + raise ValueError("More than one alignment found in file") + except StopIteration: + pass + return alignment + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/AlignInfo.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/AlignInfo.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de7d5234f70013af693da97afea3e90803b490df Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/AlignInfo.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/a2m.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/a2m.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ce8dc99c3c8261dfb3ee32d25256bd44cb3f850 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/a2m.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/analysis.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/analysis.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..182143793b08ceb03867f784f7067346bec0e475 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/analysis.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/bed.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/bed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f9fa2137e68602c219668dcf8daed94f7c6efca Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/bed.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/bigbed.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/bigbed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3603570411df1662ec03d95a0af2cd781312fa78 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/bigbed.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/bigmaf.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/bigmaf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..506fb6a1db54d12b2909852a73141a7824e88840 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/bigmaf.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/bigpsl.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/bigpsl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ba4fc04d9a4f3246063fe9f631a47e8d6e0d7bf Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/bigpsl.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/chain.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/chain.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37db1f0212cfa3412c88a0a0cea8a3e402bb38e9 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/chain.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/clustal.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/clustal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e80466fa1a211fc993a76bc5dff48573f5c5af67 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/clustal.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/emboss.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/emboss.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6ccfa7212092a8ae7ef357bbab21c67be362adb Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/emboss.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/exonerate.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/exonerate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba6de57886e2e2120f555caadac2a3d4f87e301e Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/exonerate.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/fasta.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/fasta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b185261c664c3456a082f03a332703f6f915507 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/fasta.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/hhr.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/hhr.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7df6ae2b8bdf9bcba20b2f46a5386810027ae77 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/hhr.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/interfaces.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/interfaces.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1818a22bd4e8e749ebf703d9134afd403e60c642 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/interfaces.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/maf.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/maf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e491d6febe39c2a2532f5a9142392bf6c11484c2 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/maf.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/mauve.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/mauve.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9e85407b98f8fc5169cb31fcca38d6fc40d9d09 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/mauve.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/msf.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/msf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbd865d03e5bbd6ed4da6b914f77d24e45a38a63 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/msf.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/nexus.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/nexus.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9faa8aa96617d8a477f0a82024edfe2b919a1e0f Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/nexus.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/phylip.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/phylip.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21c623dd6444b75bcae8121167afc739644e1f45 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/phylip.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/psl.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/psl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a36fc959ee8032c10e8fa1cf6446a6663d04a8da Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/psl.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/sam.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/sam.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a4aef2092284cef7b21a860b2fb066bb4bb0b7f Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/sam.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/stockholm.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/stockholm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..143516e7d4b0500f69bbf9b935d785c0ac595bad Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/stockholm.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/tabular.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/tabular.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c7b5b31a6d30b284728f2916d0c501d3cbe13d0b Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/__pycache__/tabular.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_aligncore.c b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_aligncore.c new file mode 100644 index 0000000000000000000000000000000000000000..2375267bcc0afeb931bc7e8641e32d8a9d1595cd --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_aligncore.c @@ -0,0 +1,508 @@ +/* Copyright 2024 by Michiel de Hoon. All rights reserved. + * This file is part of the Biopython distribution and governed by your + * choice of the "Biopython License Agreement" or the "BSD 3-Clause License". + * Please see the LICENSE file that should have been included as part of this + * package. + */ + + +#include +#include + + +static PyTypeObject ParserType; + +typedef struct { + PyObject_HEAD + Py_uintptr_t** data; + /* Array of n Py_uintptr_t* pointers; each pointer points to an array of + Py_uintptr_t of variable length. This array contains, for each sequence, + the positions in the printed alignment at which a letter is followed by + a gap, or vice-versa. If the first character is a gap, then the first + column in data is 0. + */ + Py_ssize_t n; /* number of sequences in the alignment */ + Py_ssize_t m; /* number of columns in the printed alignment */ + Py_ssize_t k; /* number of columns of the coordinates array */ + char eol; /* optional end-of-line character (set to '\n' by default) */ +} Parser; + +static void +Parser_dealloc(Parser *self) +{ + Py_ssize_t i; + const Py_ssize_t n = self->n; + Py_uintptr_t** data = self->data; + if (data) { + for (i = 0; i < n; i++) { + if (data[i] == NULL) break; + PyMem_Free(data[i]); + } + PyMem_Free(data); + } + Py_TYPE(self)->tp_free((PyObject *)self); +} + +static int +array_converter(PyObject* argument, void* pointer) +/* Check if the NumPy array received in argument has the correct shape and + * data type, and fill the Py_buffer structure referred to by pointer. + */ +{ + Py_buffer* view = pointer; + Parser* self; + + if (!PyObject_TypeCheck(view->obj, &ParserType)) { + PyErr_SetString(PyExc_RuntimeError, + "expected an object of the PrintedAlignmentParser class"); + return 0; + } + + self = (Parser*) view->obj; + + if (PyObject_GetBuffer(argument, view, PyBUF_CONTIG) != 0) { + PyErr_SetString(PyExc_RuntimeError, + "argument does not implement the buffer protocol"); + return 0; + } + if (view->ndim != 2) { + PyErr_Format(PyExc_RuntimeError, + "buffer has incorrect rank %d (expected 2)", + view->ndim); + } + else if (view->shape[0] != self->n) { + PyErr_Format(PyExc_RuntimeError, + "buffer has incorrect number of rows %zd (expected %zd)", + view->shape[0], self->n); + } + else if (view->shape[1] != self->k) { + PyErr_Format(PyExc_RuntimeError, + "buffer has incorrect number of columns %zd (expected %zd)", + view->shape[1], self->k); + } + else if (view->itemsize != sizeof(Py_ssize_t)) { + PyErr_Format(PyExc_RuntimeError, + "buffer has unexpected item byte size " + "(%ld, expected %ld)", view->itemsize, sizeof(Py_ssize_t)); + } + else return 1; /* return status 1 to indicate a successful converstion */ + + PyBuffer_Release(view); + return 0; /* return status 0 to indicate that converstion failed */ +} + +PyDoc_STRVAR( + Parser_feed__doc__, + "feed(self, line, offset=0)\n" + "--\n" + "\n" + "Feed one line of the printed alignment into the parser.\n" + "\n" + "The line must be a bytes object. The parser will read from line\n" + "until it finds the end-of-line character (defined by self->eol)\n" + "or a null character.\n" + "\n" + "The parser skips the first offset bytes.\n" + "\n" + "Any dashes in line are interpreted as gaps.\n" + "This method finds the gap locations and stores them in self.\n" + "\n" + "The return value is the tuple (nbytes, sequence), in which\n" + " - nbytes is the number of bytes read from line (not counting\n" + " the end-of-line character); this is equal to the number of\n" + " columns in the printed alignment.\n" + " - sequence is a bytes object with the contents of line after\n" + " removal of the dashes; sequence can be used to create the\n" + " ungapped sequence object stored in the sequences attribute\n" + " of the Alignment object."); + +static PyObject* +Parser_feed(Parser* self, PyObject* args, PyObject *kwds) +{ + PyObject* line = NULL; + PyObject* sequence; + PyObject* result; + const char* buffer; + const char* s; + char* d; + const char eol = self->eol; + Py_ssize_t n = self->n; + Py_ssize_t m = self->m; + Py_ssize_t size = 2; + Py_ssize_t i = 0; + Py_ssize_t p = 0; + Py_ssize_t offset = 0; + Py_ssize_t start, end, step; + Py_uintptr_t** data; + Py_uintptr_t* row; + char c; + bool gap = false; + + if (!PyArg_ParseTuple(args, "S|n:feed", &line, &offset)) return NULL; + + buffer = PyBytes_AS_STRING(line) + offset; + + s = buffer; + row = PyMem_Malloc(size*sizeof(Py_uintptr_t)); + if (!row) return NULL; + if (*s == '-') row[i++] = 0; + + data = PyMem_Realloc(self->data, (n+1)*size*sizeof(Py_uintptr_t*)); + if (!data) { + PyMem_Free(row); + return NULL; + } + self->data = data; + data[n] = row; + + while (*s != '\0' && *s != eol) { + if (*s == '-') { + do s++; while (*s == '-'); + } + else { + start = s - buffer; + do c = *(++s); while (c != '-' && c != eol && c != '\0'); + end = s - buffer; + step = end - start; + p += step; + } + + if (i == size) { + size *= 2; + row = PyMem_Realloc(row, size*sizeof(Py_uintptr_t)); + if (!row) { + PyMem_Free(data[n]); + return NULL; + } + data[n] = row; + } + row[i++] = s - buffer; + } + row = PyMem_Realloc(row, i*sizeof(Py_uintptr_t)); + if (!row) { + PyMem_Free(data[n]); + return NULL; + } + data[n] = row; + m = s - buffer; + if (n == 0) self->m = m; + else if (buffer + m != s) { + PyErr_Format(PyExc_ValueError, + "line has length %zd (expected %zd)", m, self->m); + PyMem_Free(row); + return NULL; + } + + n++; + self->n = n; + + sequence = PyBytes_FromStringAndSize(NULL, p); + if (!sequence) return NULL; + d = PyBytes_AS_STRING(sequence); + end = 0; + s = buffer; + p = 0; + if (row[p] == 0) { + gap = true; + p++; + } + for ( ; p < i; p++) { + start = end; + end = row[p]; + step = end - start; + gap = !gap; + if (gap) { + s = buffer + start; + memcpy(d, s, step); + d += step; + } + } + *d = '\0'; + + result = Py_BuildValue("nN", m, sequence); + if (result == NULL) Py_DECREF(sequence); + return result; +} + +PyDoc_STRVAR( + Parser_fill__doc__, + "fill(self, arr)\n" + "--\n" + "\n" + "Fill in the coordinates array based on the alignment lines fed\n" + "to the parser so far.\n" + "\n" + "The argument arr must be a 2D numpy array of data type intp,\n" + "with the number of rows equal to the number of lines fed into\n" + "the parser so far, and the number of columns equal to the number\n" + "of columns needed to store the coordinates array.\n" + "The appropriate number of rows and columns can be obtained in\n" + "advance using the self.shape attribute.\n" + "\n" + "This method stores the alignment coordinates in arr, and returns\n" + "None.\n" +); + +static PyObject* +Parser_fill(Parser* self, PyObject* args) +{ + Py_buffer view; + Py_ssize_t i, j, k, n, m, p; + Py_ssize_t start; + Py_ssize_t step; + Py_ssize_t end; + Py_ssize_t* starts = NULL; + Py_uintptr_t** data = NULL; + bool* gaps = NULL; + Py_ssize_t* buffer; + + n = self->n; + if (n == 0) Py_RETURN_NONE; + + view.obj = (PyObject*) self; + + if (!PyArg_ParseTuple(args, "O&:fill", array_converter, &view)) + return NULL; + + buffer = view.buf; + k = view.shape[1]; + if (n != view.shape[0]) { + PyErr_Format(PyExc_ValueError, + "expected an array with %zd rows (found %zd rows)", + n, view.shape[0]); + goto exit; + } + for (i = 0; i < n; i++) buffer[i*k] = 0; + + m = self->m; + + starts = PyMem_Calloc(n, sizeof(Py_ssize_t)); + if (!starts) goto exit; + + gaps = PyMem_Malloc(n * sizeof(bool)); + if (!gaps) goto exit; + + data = PyMem_Malloc(n * sizeof(Py_ssize_t*)); + if (!data) goto exit; + + for (i = 0; i < n; i++) { + data[i] = self->data[i]; + if (data[i][0] == 0) { + gaps[i] = true; + data[i]++; + } + else { + gaps[i] = false; + } + } + + j = 0; + start = 0; + do { + j++; + for (i = 0; i < n; i++) { + if (start == starts[i]) starts[i] = *data[i]; + } + end = m; + for (i = 0; i < n; i++) if (starts[i] < end) end = starts[i]; + step = end - start; + for (i = 0; i < n; i++) { + p = i*k+j; + if (gaps[i] == true) buffer[p] = buffer[p-1]; + else buffer[i*k+j] = (Py_ssize_t) (buffer[p-1] + step); + if (end == starts[i]) { + data[i]++; + gaps[i] = !gaps[i]; + } + } + start = end; + } + while (start < m); + +exit: + PyBuffer_Release(&view); + if (starts) PyMem_Free(starts); + if (data) PyMem_Free(data); + if (gaps) PyMem_Free(gaps); + Py_RETURN_NONE; +} + +PyDoc_STRVAR( + Parser_shape__doc__, + "Return the required shape of the coordinates array.\n" + "Typically, this attribute is used before calling the fill method.\n" +); + +static PyObject* +Parser_get_shape(Parser* self, void* closure) +{ + Py_ssize_t i; + Py_ssize_t index; + Py_ssize_t min_index; + Py_uintptr_t** data = self->data; + const Py_ssize_t n = self->n; + const Py_ssize_t m = self->m; + Py_ssize_t k = 1; + + if (n > 0) { + data = PyMem_Malloc(n * sizeof(Py_uintptr_t*)); + if (!data) return NULL; + memcpy(data, self->data, n*sizeof(Py_uintptr_t*)); + for (i = 0; i < n; i++) { + index = *(data[i]); + if (index == 0) { + k = 0; + break; + } + } + while (1) { + k++; + min_index = m; + for (i = 0; i < n; i++) { + index = *(data[i]); + if (index < min_index) min_index = index; + } + if (min_index == m) break; + for (i = 0; i < n; i++) { + index = *(data[i]); + if (index == min_index) data[i]++; + } + } + } + + self->k = k; + return Py_BuildValue("nn", n, k); +} + +static PyGetSetDef Parser_getset[] = { + {"shape", (getter)Parser_get_shape, + NULL, + Parser_shape__doc__, + NULL, + }, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +static PyMethodDef Parser_methods[] = { + {"feed", + (PyCFunction)Parser_feed, + METH_VARARGS, + Parser_feed__doc__, + }, + {"fill", + (PyCFunction)Parser_fill, + METH_VARARGS, + Parser_fill__doc__, + }, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +static PyObject* +Parser_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + char eol = '\n'; /* end-of-line character */ + static char *kwlist[] = {"eol", NULL}; + + Parser *self; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|c", kwlist, &eol)) + return NULL; + + self = (Parser *)type->tp_alloc(type, 0); + if (!self) return NULL; + self->eol = eol; + self->n = 0; + return (PyObject *)self; +} + +PyDoc_STRVAR( + Parser__doc__, + "PrintedAlignmentParser(eol=b'\n')\n" + "--\n" + "\n" + "Create a fast parser for printed alignments.\n" + "\n" + "The argument eol must be a bytes object of length 1, and specifies\n" + "the end-of-line character, defaulting to '\\n'" + "\n" + "As an example, to parse this printed alignment:\n" + "\n" + "ACCGGGTTTT\n" + "AC-GAG--TT\n" + "AC--AG--TT\n" + "\n" + "use\n" + "\n" + ">>> parser = PrintedAlignmentParser()\n" + ">>> nbytes1, seq1 = parser.feed(b'ACCGGGTTTT')\n" + ">>> nbytes2, seq2 = parser.feed(b'AC-GAG--TT')\n" + ">>> nbytes3, seq3 = parser.feed(b'AC--AG--TT')\n" + ">>> nbytes1\n" + "10\n" + ">>> nbytes2\n" + "10\n" + ">>> nbytes3\n" + "10\n" + ">>> seq1\n" + "b'ACCGGGTTTT'\n" + ">>> seq2\n" + "b'ACGAGTT'\n" + ">>> seq3\n" + "b'ACAGTT'\n" + ">>> parser.shape\n" + "(3, 7)\n" + ">>> import numpy as np\n" + ">>> coordinates = np.zeros((3, 7), np.intp)\n" + ">>> parser.fill(coordinates)\n" + ">>> coordinates\n" + "array([[ 0, 2, 3, 4, 6, 8, 10],\n" + " [ 0, 2, 2, 3, 5, 5, 7],\n" + " [ 0, 2, 2, 2, 4, 4, 6]])\n" + ">>> from Bio.Align import Alignment\n" + ">>> from Bio.Seq import Seq\n" + ">>> sequences = (Seq(seq1), Seq(seq2), Seq(seq3))\n" + ">>> alignment = Alignment(sequences, coordinates)\n" + ">>> print(alignment)\n" + " 0 ACCGGGTTTT 10\n" + " 0 AC-GAG--TT 7\n" + " 0 AC--AG--TT 6\n" + "\n" +); + +static PyTypeObject ParserType = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "_aligncore.PrintedAlignmentParser", + .tp_doc = Parser__doc__, + .tp_basicsize = sizeof(Parser), + .tp_itemsize = 0, + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_dealloc = (destructor)Parser_dealloc, + .tp_methods = Parser_methods, + .tp_getset = Parser_getset, + .tp_new = (newfunc)Parser_new, +}; + +/* Module initialization function */ +static PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + .m_name = "_aligncore", + .m_doc = "fast C implementation of a parser for printed alignments; for internal use.", + .m_size = -1, +}; + +PyMODINIT_FUNC +PyInit__aligncore(void) +{ + PyObject *module; + + if (PyType_Ready(&ParserType) < 0) + return NULL; + + module = PyModule_Create(&moduledef); + if (module == NULL) + return NULL; + + Py_INCREF(&ParserType); + PyModule_AddObject(module, "PrintedAlignmentParser", (PyObject *)&ParserType); + return module; +} diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_aligncore.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_aligncore.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..63d3468dc5532940c7654222af712173697346b8 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_aligncore.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_alignmentcounts.c b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_alignmentcounts.c new file mode 100644 index 0000000000000000000000000000000000000000..357e03f9e30dce2ec68d8b6bb2f0d8e0bde17118 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_alignmentcounts.c @@ -0,0 +1,1694 @@ +/* Copyright 2018-2025 by Michiel de Hoon. All rights reserved. + * This file is part of the Biopython distribution and governed by your + * choice of the "Biopython License Agreement" or the "BSD 3-Clause License". + * Please see the LICENSE file that should have been included as part of this + * package. + */ + + + +#define PY_SSIZE_T_CLEAN +#include "Python.h" +#include +#include +#include +#include "_pairwisealigner.h" +#include "substitution_matrices/_arraycore.h" + + +static PyTypeObject* Aligner_Type = NULL; +static PyTypeObject* Array_Type = NULL; +/* these will be set when initializing the module */ + +static PyTypeObject AlignmentCounts_Type; +/* defined in this module */ + + +typedef struct { + PyObject_HEAD + Py_ssize_t open_left_insertions; + Py_ssize_t extend_left_insertions; + Py_ssize_t open_left_deletions; + Py_ssize_t extend_left_deletions; + Py_ssize_t open_internal_insertions; + Py_ssize_t extend_internal_insertions; + Py_ssize_t open_internal_deletions; + Py_ssize_t extend_internal_deletions; + Py_ssize_t open_right_insertions; + Py_ssize_t extend_right_insertions; + Py_ssize_t open_right_deletions; + Py_ssize_t extend_right_deletions; + Py_ssize_t aligned; + Py_ssize_t identities; + Py_ssize_t mismatches; + Py_ssize_t positives; + double gap_score; // Py_NAN + double substitution_score; // Py_NAN +} AlignmentCounts; + +static PyObject* +AlignmentCounts_str(AlignmentCounts* self) +{ + const double gap_score = self->gap_score; + const double substitution_score = self->substitution_score; + const double score = gap_score + substitution_score; + const Py_ssize_t open_left_insertions = self->open_left_insertions; + const Py_ssize_t extend_left_insertions = self->extend_left_insertions; + const Py_ssize_t open_left_deletions = self->open_left_deletions; + const Py_ssize_t extend_left_deletions = self->extend_left_deletions; + const Py_ssize_t open_internal_insertions = self->open_internal_insertions; + const Py_ssize_t extend_internal_insertions = self->extend_internal_insertions; + const Py_ssize_t open_internal_deletions = self->open_internal_deletions; + const Py_ssize_t extend_internal_deletions = self->extend_internal_deletions; + const Py_ssize_t open_right_insertions = self->open_right_insertions; + const Py_ssize_t extend_right_insertions = self->extend_right_insertions; + const Py_ssize_t open_right_deletions = self->open_right_deletions; + const Py_ssize_t extend_right_deletions = self->extend_right_deletions; + const Py_ssize_t aligned = self->aligned; + const Py_ssize_t identities = self->identities; + const Py_ssize_t mismatches = self->mismatches; + const Py_ssize_t positives = self->positives; + const Py_ssize_t left_insertions = open_left_insertions + + extend_left_insertions; + const Py_ssize_t internal_insertions = open_internal_insertions + + extend_internal_insertions; + const Py_ssize_t right_insertions = open_right_insertions + + extend_right_insertions; + const Py_ssize_t left_deletions = open_left_deletions + + extend_left_deletions; + const Py_ssize_t internal_deletions = open_internal_deletions + + extend_internal_deletions; + const Py_ssize_t right_deletions = open_right_deletions + + extend_right_deletions; + const Py_ssize_t left_gaps = left_insertions + left_deletions; + const Py_ssize_t internal_gaps = internal_insertions + internal_deletions; + const Py_ssize_t right_gaps = right_insertions + right_deletions; + const Py_ssize_t gaps = left_gaps + internal_gaps + right_gaps; + char text[2048]; + char* p = text; + p += sprintf(p, "AlignmentCounts object with\n"); + /* using arguments to PyOS_double_to_string as in + * float_repr in the Python C source code. + */ + if (!isnan(score)) { + char* s = PyOS_double_to_string(score, 'r', 0, Py_DTSF_ADD_DOT_0, NULL); + if (!s) return NULL; + p += sprintf(p, " score = %s:\n", s); + PyMem_Free(s); + if (!isnan(substitution_score)) { + char* s = PyOS_double_to_string(substitution_score, 'r', 0, Py_DTSF_ADD_DOT_0, NULL); + if (!s) return NULL; + p += sprintf(p, " substitution_score = %s,\n", s); + PyMem_Free(s); + } + if (!isnan(gap_score)) { + char* s = PyOS_double_to_string(gap_score, 'r', 0, Py_DTSF_ADD_DOT_0, NULL); + if (!s) return NULL; + p += sprintf(p, " gap_score = %s.\n", s); + PyMem_Free(s); + } + } + else { + if (!isnan(substitution_score)) { + char* s = PyOS_double_to_string(substitution_score, 'r', 0, Py_DTSF_ADD_DOT_0, NULL); + if (!s) return NULL; + p += sprintf(p, " substitution_score = %s,\n", s); + PyMem_Free(s); + } + if (!isnan(gap_score)) { + char* s = PyOS_double_to_string(gap_score, 'r', 0, Py_DTSF_ADD_DOT_0, NULL); + if (!s) return NULL; + p += sprintf(p, " gap_score = %s.\n", s); + PyMem_Free(s); + } + } + p += sprintf(p, " aligned = %zd:\n", aligned); + p += sprintf(p, " identities = %zd,\n", identities); + if (positives != -1) + p += sprintf(p, " positives = %zd,\n", positives); + p += sprintf(p, " mismatches = %zd.\n", mismatches); + p += sprintf(p, " gaps = %zd:\n", gaps); + p += sprintf(p, " left_gaps = %zd:\n", left_gaps); + p += sprintf(p, " left_insertions = %zd:\n", left_insertions); + p += sprintf(p, " open_left_insertions = %zd,\n", open_left_insertions); + p += sprintf(p, " extend_left_insertions = %zd;\n", extend_left_insertions); + p += sprintf(p, " left_deletions = %zd:\n", left_deletions); + p += sprintf(p, " open_left_deletions = %zd,\n", open_left_deletions); + p += sprintf(p, " extend_left_deletions = %zd;\n", extend_left_deletions); + p += sprintf(p, " internal_gaps = %zd:\n", internal_gaps); + p += sprintf(p, " internal_insertions = %zd:\n", internal_insertions); + p += sprintf(p, " open_internal_insertions = %zd,\n", open_internal_insertions); + p += sprintf(p, " extend_internal_insertions = %zd;\n", extend_internal_insertions); + p += sprintf(p, " internal_deletions = %zd:\n", internal_deletions); + p += sprintf(p, " open_internal_deletions = %zd,\n", open_internal_deletions); + p += sprintf(p, " extend_internal_deletions = %zd;\n", extend_internal_deletions); + p += sprintf(p, " right_gaps = %zd:\n", right_gaps); + p += sprintf(p, " right_insertions = %zd:\n", right_insertions); + p += sprintf(p, " open_right_insertions = %zd,\n", open_right_insertions); + p += sprintf(p, " extend_right_insertions = %zd;\n", extend_right_insertions); + p += sprintf(p, " right_deletions = %zd:\n", right_deletions); + p += sprintf(p, " open_right_deletions = %zd,\n", open_right_deletions); + p += sprintf(p, " extend_right_deletions = %zd.\n", extend_right_deletions); + return PyUnicode_FromString(text); +} + +static PyObject* +AlignmentCounts_repr(AlignmentCounts* self) +{ + Py_uintptr_t id = 0; + const double substitution_score = self->substitution_score; + const double gap_score = self->gap_score; + const double score = gap_score + substitution_score; + const Py_ssize_t aligned = self->aligned; + const Py_ssize_t identities = self->identities; + const Py_ssize_t mismatches = self->mismatches; + const Py_ssize_t positives = self->positives; + const Py_ssize_t gaps = self->open_left_insertions + + self->extend_left_insertions + + self->open_internal_insertions + + self->extend_internal_insertions + + self->open_right_insertions + + self->extend_right_insertions + + self->open_left_deletions + + self->extend_left_deletions + + self->open_internal_deletions + + self->extend_internal_deletions + + self->open_right_deletions + + self->extend_right_deletions; + char text[1024]; + char* p = text; + p += sprintf(p, "", gaps, id); + + return PyUnicode_FromString(text); +} + +static char AlignmentCounts_doc[] = +"AlignmentCounts objects store the number of aligned characters, identities,\n" +"mismatches, gaps, and score of an alignment.\n"; + +static char AlignmentCounts_aligned__doc__[] = "number of aligned characters in the alignment"; + +static PyObject* +AlignmentCounts_get_aligned(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->aligned); +} + +static char AlignmentCounts_identities__doc__[] = "number of matched letters in the alignment"; + +static PyObject* +AlignmentCounts_get_identities(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->identities); +} + +static char AlignmentCounts_mismatches__doc__[] = "number of mismatched letters in the alignment"; + +static PyObject* +AlignmentCounts_get_mismatches(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->mismatches); +} + +static char AlignmentCounts_positives__doc__[] = "number of aligned letters with a positive substitution score"; + +static PyObject* +AlignmentCounts_get_positives(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t positives = self->positives; + if (positives == -1) { + Py_INCREF(Py_None); + return Py_None; + } + else return PyLong_FromSsize_t(positives); +} + +static char AlignmentCounts_score__doc__[] = "alignment score, or None if unknown"; + +static PyObject* +AlignmentCounts_get_score(AlignmentCounts* self, void* closure) +{ + const double score = self->gap_score + self->substitution_score; + if (isnan(score)) { + Py_INCREF(Py_None); + return Py_None; + } + return PyFloat_FromDouble(score); +} + +static char AlignmentCounts_gap_score__doc__[] = "total gap score, or None if unknown"; + +static PyObject* +AlignmentCounts_get_gap_score(AlignmentCounts* self, void* closure) +{ + const double gap_score = self->gap_score; + if (isnan(gap_score)) { + Py_INCREF(Py_None); + return Py_None; + } + return PyFloat_FromDouble(gap_score); +} + +static char AlignmentCounts_substitution_score__doc__[] = "total substitution score of letters aligned to each other, or None if unknown"; + +static PyObject* +AlignmentCounts_get_substitution_score(AlignmentCounts* self, void* closure) +{ + const double substitution_score = self->substitution_score; + if (isnan(substitution_score)) { + Py_INCREF(Py_None); + return Py_None; + } + return PyFloat_FromDouble(substitution_score); +} + +static char AlignmentCounts_open_left_insertions__doc__[] = "number of insertion gaps opened on the left side of the alignment"; + +static PyObject* +AlignmentCounts_get_open_left_insertions(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->open_left_insertions); +} + +static char AlignmentCounts_extend_left_insertions__doc__[] = "number of insertion gap extensions on the left side of the alignment"; + +static PyObject* +AlignmentCounts_get_extend_left_insertions(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->extend_left_insertions); +} + +static char AlignmentCounts_left_insertions__doc__[] = "number of letters inserted on the left side of the alignment"; + +static PyObject* +AlignmentCounts_get_left_insertions(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_left_insertions = self->open_left_insertions; + const Py_ssize_t extend_left_insertions = self->extend_left_insertions; + return PyLong_FromSsize_t(open_left_insertions + extend_left_insertions); +} + +static char AlignmentCounts_open_left_deletions__doc__[] = "the number of deletion gaps opened on the left side of the alignment"; + +static PyObject* +AlignmentCounts_get_open_left_deletions(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->open_left_deletions); +} + +static char AlignmentCounts_extend_left_deletions__doc__[] = "number of deletion gap extensions on the left side of the alignment"; + +static PyObject* +AlignmentCounts_get_extend_left_deletions(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->extend_left_deletions); +} + +static char AlignmentCounts_left_deletions__doc__[] = "number of characters deleted on the left side of the alignment"; + +static PyObject* +AlignmentCounts_get_left_deletions(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_left_deletions = self->open_left_deletions; + const Py_ssize_t extend_left_deletions = self->extend_left_deletions; + return PyLong_FromSsize_t(open_left_deletions + extend_left_deletions); +} + +static char AlignmentCounts_open_left_gaps__doc__[] = "number of gaps opened on the left side of the alignment"; + +static PyObject* +AlignmentCounts_get_open_left_gaps(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_left_insertions = self->open_left_insertions; + const Py_ssize_t open_left_deletions = self->open_left_deletions; + return PyLong_FromSsize_t(open_left_insertions + open_left_deletions); +} + +static char AlignmentCounts_extend_left_gaps__doc__[] = "number of gap extensions on the left side of the alignment"; + +static PyObject* +AlignmentCounts_get_extend_left_gaps(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t extend_left_insertions = self->extend_left_insertions; + const Py_ssize_t extend_left_deletions = self->extend_left_deletions; + return PyLong_FromSsize_t(extend_left_insertions + extend_left_deletions); +} + +static char AlignmentCounts_left_gaps__doc__[] = "total gap length on the left side of the alignment"; + +static PyObject* +AlignmentCounts_get_left_gaps(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_left_insertions = self->open_left_insertions; + const Py_ssize_t extend_left_insertions = self->extend_left_insertions; + const Py_ssize_t open_left_deletions = self->open_left_deletions; + const Py_ssize_t extend_left_deletions = self->extend_left_deletions; + return PyLong_FromSsize_t(open_left_insertions + + extend_left_insertions + + open_left_deletions + + extend_left_deletions); +} + +static char AlignmentCounts_open_internal_insertions__doc__[] = "number of insertion gaps opened in the interior of the alignment"; + +static PyObject* +AlignmentCounts_get_open_internal_insertions(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->open_internal_insertions); +} + +static char AlignmentCounts_extend_internal_insertions__doc__[] = "number of insertion gas extensions in the interior of the alignment"; + +static PyObject* +AlignmentCounts_get_extend_internal_insertions(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->extend_internal_insertions); +} + +static char AlignmentCounts_internal_insertions__doc__[] = "number of letters inserted in the interior of the alignment"; + +static PyObject* +AlignmentCounts_get_internal_insertions(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_internal_insertions = self->open_internal_insertions; + const Py_ssize_t extend_internal_insertions = self->extend_internal_insertions; + return PyLong_FromSsize_t(open_internal_insertions + extend_internal_insertions); +} + +static char AlignmentCounts_open_internal_deletions__doc__[] = "number of deletion gaps opened in the interior of the alignment"; + +static PyObject* +AlignmentCounts_get_open_internal_deletions(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->open_internal_deletions); +} + +static char AlignmentCounts_extend_internal_deletions__doc__[] = "number of deletion gap exensions in the interior of the alignment"; + +static PyObject* +AlignmentCounts_get_extend_internal_deletions(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->extend_internal_deletions); +} + +static char AlignmentCounts_internal_deletions__doc__[] = "number of characters deleted from the alignment"; + +static PyObject* +AlignmentCounts_get_internal_deletions(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_internal_deletions = self->open_internal_deletions; + const Py_ssize_t extend_internal_deletions = self->extend_internal_deletions; + return PyLong_FromSsize_t(open_internal_deletions + extend_internal_deletions); +} + +static PyObject* +AlignmentCounts_get_open_internal_gaps(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_internal_insertions = self->open_internal_insertions; + const Py_ssize_t open_internal_deletions = self->open_internal_deletions; + return PyLong_FromSsize_t(open_internal_insertions + + open_internal_deletions); +} + +static char AlignmentCounts_open_internal_gaps__doc__[] = "number of gaps opened in the interior of the alignment"; + +static PyObject* +AlignmentCounts_get_extend_internal_gaps(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t extend_internal_insertions = self->extend_internal_insertions; + const Py_ssize_t extend_internal_deletions = self->extend_internal_deletions; + return PyLong_FromSsize_t(extend_internal_insertions + + extend_internal_deletions); +} + +static char AlignmentCounts_extend_internal_gaps__doc__[] = "number of gap extensions in the interior of the alignment"; + +static PyObject* +AlignmentCounts_get_internal_gaps(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_internal_insertions = self->open_internal_insertions; + const Py_ssize_t extend_internal_insertions = self->extend_internal_insertions; + const Py_ssize_t open_internal_deletions = self->open_internal_deletions; + const Py_ssize_t extend_internal_deletions = self->extend_internal_deletions; + return PyLong_FromSsize_t(open_internal_insertions + + extend_internal_insertions + + open_internal_deletions + + extend_internal_deletions); +} + +static char AlignmentCounts_internal_gaps__doc__[] = "total length of gaps within the alignment"; + +static char AlignmentCounts_open_right_insertions__doc__[] = "the number of insertion gaps opened on the right side of the alignment"; + +static PyObject* +AlignmentCounts_get_open_right_insertions(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->open_right_insertions); +} + +static char AlignmentCounts_extend_right_insertions__doc__[] = "the number of insertion gap extensions on the right side of the alignment"; + +static PyObject* +AlignmentCounts_get_extend_right_insertions(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->extend_right_insertions); +} + +static char AlignmentCounts_right_insertions__doc__[] = "number of letters inserted on the right side of the alignment"; + +static PyObject* +AlignmentCounts_get_right_insertions(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_right_insertions = self->open_right_insertions; + const Py_ssize_t extend_right_insertions = self->extend_right_insertions; + return PyLong_FromSsize_t(open_right_insertions + extend_right_insertions); +} + +static char AlignmentCounts_open_right_deletions__doc__[] = "number of deletion gaps opened on the right side of the alignment"; + +static PyObject* +AlignmentCounts_get_open_right_deletions(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->open_right_deletions); +} + +static char AlignmentCounts_extend_right_deletions__doc__[] = "number of deletion gap extensions on the right side of the alignment"; + +static PyObject* +AlignmentCounts_get_extend_right_deletions(AlignmentCounts* self, void* closure) +{ + return PyLong_FromSsize_t(self->extend_right_deletions); +} + +static char AlignmentCounts_right_deletions__doc__[] = "number of letters deleted on the right side of the alignment"; + +static PyObject* +AlignmentCounts_get_right_deletions(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_right_deletions = self->open_right_deletions; + const Py_ssize_t extend_right_deletions = self->extend_right_deletions; + return PyLong_FromSsize_t(open_right_deletions + extend_right_deletions); +} + +static char AlignmentCounts_open_right_gaps__doc__[] = "number of gaps opened on the right side of the alignment"; + +static PyObject* +AlignmentCounts_get_open_right_gaps(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_right_insertions = self->open_right_insertions; + const Py_ssize_t open_right_deletions = self->open_right_deletions; + return PyLong_FromSsize_t(open_right_insertions + open_right_deletions); +} + +static char AlignmentCounts_extend_right_gaps__doc__[] = "number of gap extensions on the right side of the alignment"; + +static PyObject* +AlignmentCounts_get_extend_right_gaps(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t extend_right_insertions = self->extend_right_insertions; + const Py_ssize_t extend_right_deletions = self->extend_right_deletions; + return PyLong_FromSsize_t(extend_right_insertions + extend_right_deletions); +} + +static char AlignmentCounts_right_gaps__doc__[] = "total gap length on the right side of the alignment"; + +static PyObject* +AlignmentCounts_get_right_gaps(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_right_insertions = self->open_right_insertions; + const Py_ssize_t extend_right_insertions = self->extend_right_insertions; + const Py_ssize_t open_right_deletions = self->open_right_deletions; + const Py_ssize_t extend_right_deletions = self->extend_right_deletions; + return PyLong_FromSsize_t(open_right_insertions + + extend_right_insertions + + open_right_deletions + + extend_right_deletions); +} + +static char AlignmentCounts_open_gaps__doc__[] = "number of geps opened in the alignment"; + +static PyObject* +AlignmentCounts_get_open_gaps(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_left_insertions = self->open_left_insertions; + const Py_ssize_t open_left_deletions = self->open_left_deletions; + const Py_ssize_t open_internal_insertions = self->open_internal_insertions; + const Py_ssize_t open_internal_deletions = self->open_internal_deletions; + const Py_ssize_t open_right_insertions = self->open_right_insertions; + const Py_ssize_t open_right_deletions = self->open_right_deletions; + const Py_ssize_t open_gaps = open_left_insertions + + open_left_deletions + + open_internal_insertions + + open_internal_deletions + + open_right_insertions + + open_right_deletions; + return PyLong_FromSsize_t(open_gaps); +} + +static char AlignmentCounts_extend_gaps__doc__[] = "number of gep extensions in the alignment"; + +static PyObject* +AlignmentCounts_get_extend_gaps(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t extend_left_insertions = self->extend_left_insertions; + const Py_ssize_t extend_left_deletions = self->extend_left_deletions; + const Py_ssize_t extend_internal_insertions = self->extend_internal_insertions; + const Py_ssize_t extend_internal_deletions = self->extend_internal_deletions; + const Py_ssize_t extend_right_insertions = self->extend_right_insertions; + const Py_ssize_t extend_right_deletions = self->extend_right_deletions; + const Py_ssize_t extend_gaps = extend_left_insertions + + extend_left_deletions + + extend_internal_insertions + + extend_internal_deletions + + extend_right_insertions + + extend_right_deletions; + return PyLong_FromSsize_t(extend_gaps); +} + +static char AlignmentCounts_insertions__doc__[] = "total number of letters inserted"; + +static PyObject* +AlignmentCounts_get_insertions(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_left_insertions = self->open_left_insertions; + const Py_ssize_t extend_left_insertions = self->extend_left_insertions; + const Py_ssize_t open_internal_insertions = self->open_internal_insertions; + const Py_ssize_t extend_internal_insertions = self->extend_internal_insertions; + const Py_ssize_t open_right_insertions = self->open_right_insertions; + const Py_ssize_t extend_right_insertions = self->extend_right_insertions; + return PyLong_FromSsize_t(open_left_insertions + + extend_left_insertions + + open_internal_insertions + + extend_internal_insertions + + open_right_insertions + + extend_right_insertions); +} + +static char AlignmentCounts_open_insertions__doc__[] = "number of insertion geps opened in the alignment"; + +static PyObject* +AlignmentCounts_get_open_insertions(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_left_insertions = self->open_left_insertions; + const Py_ssize_t open_internal_insertions = self->open_internal_insertions; + const Py_ssize_t open_right_insertions = self->open_right_insertions; + const Py_ssize_t open_insertions = open_left_insertions + + open_internal_insertions + + open_right_insertions; + return PyLong_FromSsize_t(open_insertions); +} + +static char AlignmentCounts_extend_insertions__doc__[] = "number of insertion gap extensions in the alignment"; + +static PyObject* +AlignmentCounts_get_extend_insertions(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t extend_left_insertions = self->extend_left_insertions; + const Py_ssize_t extend_internal_insertions = self->extend_internal_insertions; + const Py_ssize_t extend_right_insertions = self->extend_right_insertions; + const Py_ssize_t extend_insertions = extend_left_insertions + + extend_internal_insertions + + extend_right_insertions; + return PyLong_FromSsize_t(extend_insertions); +} + +static char AlignmentCounts_deletions__doc__[] = "total number of letters deleted"; + +static PyObject* +AlignmentCounts_get_deletions(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_left_deletions = self->open_left_deletions; + const Py_ssize_t extend_left_deletions = self->extend_left_deletions; + const Py_ssize_t open_internal_deletions = self->open_internal_deletions; + const Py_ssize_t extend_internal_deletions = self->extend_internal_deletions; + const Py_ssize_t open_right_deletions = self->open_right_deletions; + const Py_ssize_t extend_right_deletions = self->extend_right_deletions; + return PyLong_FromSsize_t(open_left_deletions + + extend_left_deletions + + open_internal_deletions + + extend_internal_deletions + + open_right_deletions + + extend_right_deletions); +} + +static char AlignmentCounts_open_deletions__doc__[] = "number of deletion geps opened in the alignment"; + +static PyObject* +AlignmentCounts_get_open_deletions(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_left_deletions = self->open_left_deletions; + const Py_ssize_t open_internal_deletions = self->open_internal_deletions; + const Py_ssize_t open_right_deletions = self->open_right_deletions; + const Py_ssize_t open_gaps = open_left_deletions + + open_internal_deletions + + open_right_deletions; + return PyLong_FromSsize_t(open_gaps); +} + +static char AlignmentCounts_extend_deletions__doc__[] = "number of deletion gep extensions in the alignment"; + +static PyObject* +AlignmentCounts_get_extend_deletions(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t extend_left_deletions = self->extend_left_deletions; + const Py_ssize_t extend_internal_deletions = self->extend_internal_deletions; + const Py_ssize_t extend_right_deletions = self->extend_right_deletions; + const Py_ssize_t extend_gaps = extend_left_deletions + + extend_internal_deletions + + extend_right_deletions; + return PyLong_FromSsize_t(extend_gaps); +} + +static char AlignmentCounts_gaps__doc__[] = "total gap length"; + +static PyObject* +AlignmentCounts_get_gaps(AlignmentCounts* self, void* closure) +{ + const Py_ssize_t open_left_insertions = self->open_left_insertions; + const Py_ssize_t extend_left_insertions = self->extend_left_insertions; + const Py_ssize_t open_left_deletions = self->open_left_deletions; + const Py_ssize_t extend_left_deletions = self->extend_left_deletions; + const Py_ssize_t open_internal_insertions = self->open_internal_insertions; + const Py_ssize_t extend_internal_insertions = self->extend_internal_insertions; + const Py_ssize_t open_internal_deletions = self->open_internal_deletions; + const Py_ssize_t extend_internal_deletions = self->extend_internal_deletions; + const Py_ssize_t open_right_insertions = self->open_right_insertions; + const Py_ssize_t extend_right_insertions = self->extend_right_insertions; + const Py_ssize_t open_right_deletions = self->open_right_deletions; + const Py_ssize_t extend_right_deletions = self->extend_right_deletions; + const Py_ssize_t gaps = open_left_insertions + + extend_left_insertions + + open_left_deletions + + extend_left_deletions + + open_internal_insertions + + extend_internal_insertions + + open_internal_deletions + + extend_internal_deletions + + open_right_insertions + + extend_right_insertions + + open_right_deletions + + extend_right_deletions; + return PyLong_FromSsize_t(gaps); +} + +static PyGetSetDef AlignmentCounts_getset[] = { + {"score", + (getter)AlignmentCounts_get_score, NULL, + AlignmentCounts_score__doc__, NULL}, + {"aligned", + (getter)AlignmentCounts_get_aligned, NULL, + AlignmentCounts_aligned__doc__, NULL}, + {"substitution_score", + (getter)AlignmentCounts_get_substitution_score, NULL, + AlignmentCounts_substitution_score__doc__, NULL}, + {"identities", + (getter)AlignmentCounts_get_identities, NULL, + AlignmentCounts_identities__doc__, NULL}, + {"mismatches", + (getter)AlignmentCounts_get_mismatches, NULL, + AlignmentCounts_mismatches__doc__, NULL}, + {"positives", + (getter)AlignmentCounts_get_positives, NULL, + AlignmentCounts_positives__doc__, NULL}, + {"gap_score", + (getter)AlignmentCounts_get_gap_score, NULL, + AlignmentCounts_gap_score__doc__, NULL}, + {"gaps", + (getter)AlignmentCounts_get_gaps, NULL, + AlignmentCounts_gaps__doc__, NULL}, + {"open_gaps", + (getter)AlignmentCounts_get_open_gaps, NULL, + AlignmentCounts_open_gaps__doc__, NULL}, + {"extend_gaps", + (getter)AlignmentCounts_get_extend_gaps, NULL, + AlignmentCounts_extend_gaps__doc__, NULL}, + {"open_left_gaps", + (getter)AlignmentCounts_get_open_left_gaps, NULL, + AlignmentCounts_open_left_gaps__doc__, NULL}, + {"open_right_gaps", + (getter)AlignmentCounts_get_open_right_gaps, NULL, + AlignmentCounts_open_right_gaps__doc__, NULL}, + {"open_internal_gaps", + (getter)AlignmentCounts_get_open_internal_gaps, NULL, + AlignmentCounts_open_internal_gaps__doc__, NULL}, + {"extend_left_gaps", + (getter)AlignmentCounts_get_extend_left_gaps, NULL, + AlignmentCounts_extend_left_gaps__doc__, NULL}, + {"extend_right_gaps", + (getter)AlignmentCounts_get_extend_right_gaps, NULL, + AlignmentCounts_extend_right_gaps__doc__, NULL}, + {"extend_internal_gaps", + (getter)AlignmentCounts_get_extend_internal_gaps, NULL, + AlignmentCounts_extend_internal_gaps__doc__, NULL}, + {"open_left_insertions", + (getter)AlignmentCounts_get_open_left_insertions, NULL, + AlignmentCounts_open_left_insertions__doc__, NULL}, + {"open_left_deletions", + (getter)AlignmentCounts_get_open_left_deletions, NULL, + AlignmentCounts_open_left_deletions__doc__, NULL}, + {"open_right_insertions", + (getter)AlignmentCounts_get_open_right_insertions, NULL, + AlignmentCounts_open_right_insertions__doc__, NULL}, + {"open_right_deletions", + (getter)AlignmentCounts_get_open_right_deletions, NULL, + AlignmentCounts_open_right_deletions__doc__, NULL}, + {"open_internal_insertions", + (getter)AlignmentCounts_get_open_internal_insertions, NULL, + AlignmentCounts_open_internal_insertions__doc__, NULL}, + {"open_internal_deletions", + (getter)AlignmentCounts_get_open_internal_deletions, NULL, + AlignmentCounts_open_internal_deletions__doc__, NULL}, + {"extend_left_insertions", + (getter)AlignmentCounts_get_extend_left_insertions, NULL, + AlignmentCounts_extend_left_insertions__doc__, NULL}, + {"extend_left_deletions", + (getter)AlignmentCounts_get_extend_left_deletions, NULL, + AlignmentCounts_extend_left_deletions__doc__, NULL}, + {"extend_right_insertions", + (getter)AlignmentCounts_get_extend_right_insertions, NULL, + AlignmentCounts_extend_right_insertions__doc__, NULL}, + {"extend_right_deletions", + (getter)AlignmentCounts_get_extend_right_deletions, NULL, + AlignmentCounts_extend_right_deletions__doc__, NULL}, + {"extend_internal_insertions", + (getter)AlignmentCounts_get_extend_internal_insertions, NULL, + AlignmentCounts_extend_internal_insertions__doc__, NULL}, + {"extend_internal_deletions", + (getter)AlignmentCounts_get_extend_internal_deletions, NULL, + AlignmentCounts_extend_internal_deletions__doc__, NULL}, + {"left_insertions", + (getter)AlignmentCounts_get_left_insertions, NULL, + AlignmentCounts_left_insertions__doc__, NULL}, + {"left_deletions", + (getter)AlignmentCounts_get_left_deletions, NULL, + AlignmentCounts_left_deletions__doc__, NULL}, + {"right_insertions", + (getter)AlignmentCounts_get_right_insertions, NULL, + AlignmentCounts_right_insertions__doc__, NULL}, + {"right_deletions", + (getter)AlignmentCounts_get_right_deletions, NULL, + AlignmentCounts_right_deletions__doc__, NULL}, + {"internal_insertions", + (getter)AlignmentCounts_get_internal_insertions, NULL, + AlignmentCounts_internal_insertions__doc__, NULL}, + {"internal_deletions", + (getter)AlignmentCounts_get_internal_deletions, NULL, + AlignmentCounts_internal_deletions__doc__, NULL}, + {"insertions", + (getter)AlignmentCounts_get_insertions, NULL, + AlignmentCounts_insertions__doc__, NULL}, + {"open_insertions", + (getter)AlignmentCounts_get_open_insertions, NULL, + AlignmentCounts_open_insertions__doc__, NULL}, + {"extend_insertions", + (getter)AlignmentCounts_get_extend_insertions, NULL, + AlignmentCounts_extend_insertions__doc__, NULL}, + {"deletions", + (getter)AlignmentCounts_get_deletions, NULL, + AlignmentCounts_deletions__doc__, NULL}, + {"open_deletions", + (getter)AlignmentCounts_get_open_deletions, NULL, + AlignmentCounts_open_deletions__doc__, NULL}, + {"extend_deletions", + (getter)AlignmentCounts_get_extend_deletions, NULL, + AlignmentCounts_extend_deletions__doc__, NULL}, + {"left_gaps", + (getter)AlignmentCounts_get_left_gaps, NULL, + AlignmentCounts_left_gaps__doc__, NULL}, + {"right_gaps", + (getter)AlignmentCounts_get_right_gaps, NULL, + AlignmentCounts_right_gaps__doc__, NULL}, + {"internal_gaps", + (getter)AlignmentCounts_get_internal_gaps, NULL, + AlignmentCounts_internal_gaps__doc__, NULL}, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +static int +sequence_converter(PyObject* argument, void* pointer) +{ + Py_buffer* view = pointer; + const int flag = PyBUF_FORMAT | PyBUF_C_CONTIGUOUS; + + if (PyObject_GetBuffer(argument, view, flag) == 0) { + if (view->ndim == 1 && view->len > 0) { + if ((strcmp(view->format, "i") == 0 + || strcmp(view->format, "l") == 0) + && view->itemsize == sizeof(int)) { + /* buffer contains int values */ return 1; +} + if ((strcmp(view->format, "c") == 0 + || strcmp(view->format, "b") == 0 + || strcmp(view->format, "B") == 0) + && view->itemsize == sizeof(char)) + /* buffer contains int values */ return 1; + } + PyBuffer_Release(view); + } else PyErr_Clear(); + view->buf = NULL; + if (PySequence_Check(argument)) { + view->obj = argument; + return 1; + } + else if (argument == Py_None) { + view->obj = NULL; + return 1; + } + else return 0; +} + +static int +coordinates_converter(PyObject* argument, void* pointer) +{ + Py_buffer* view = pointer; + if (argument == NULL) { + PyBuffer_Release(view); + return 1; + } + + if (PyObject_GetBuffer(argument, view, PyBUF_STRIDED) != 0) return 0; + if (view->ndim != 2 || view->itemsize != sizeof(Py_ssize_t)) { + PyErr_SetString(PyExc_ValueError, + "coordinates must be a 2D array of Py_ssize_t integers"); + PyBuffer_Release(view); + return 0; + } + return Py_CLEANUP_SUPPORTED; +} + +static int +strands_converter(PyObject* argument, void* pointer) +{ + Py_buffer* view = pointer; + if (argument == NULL) { + PyBuffer_Release(view); + return 1; + } + + if (PyObject_GetBuffer(argument, view, PyBUF_CONTIG_RO) != 0) return 0; + if (view->ndim != 1 || view->itemsize != sizeof(bool)) { + PyErr_SetString(PyExc_ValueError, + "strands must be a 1D array of bool variables"); + PyBuffer_Release(view); + return 0; + } + return Py_CLEANUP_SUPPORTED; +} + +static int +substitution_matrix_converter(PyObject* argument, void* pointer) +{ + const int flag = PyBUF_FORMAT | PyBUF_ND; + Py_buffer* view = pointer; + if (argument == NULL) { + PyBuffer_Release(view); + return 1; + } + if (PyObject_GetBuffer(argument, view, flag) != 0) { + PyErr_SetString(PyExc_ValueError, "expected a matrix"); + return 0; + } + if (view->ndim != 2) { + PyErr_Format(PyExc_ValueError, + "substitution matrix has incorrect rank (%d expected 2)", + view->ndim); + PyBuffer_Release(view); + return 0; + } + if (view->len == 0) { + PyErr_SetString(PyExc_ValueError, "substitution matrix has zero size"); + PyBuffer_Release(view); + return 0; + } + if (strcmp(view->format, "d") != 0) { + PyErr_SetString(PyExc_ValueError, + "substitution matrix should contain float values"); + PyBuffer_Release(view); + return 0; + } + if (view->itemsize != sizeof(double)) { + PyErr_Format(PyExc_RuntimeError, + "substitution matrix has unexpected item byte size " + "(%zd, expected %zd)", view->itemsize, sizeof(double)); + PyBuffer_Release(view); + return 0; + } + if (view->shape[0] != view->shape[1]) { + PyErr_Format(PyExc_ValueError, + "substitution matrix should be square " + "(found a %zd x %zd matrix)", + view->shape[0], view->shape[1]); + PyBuffer_Release(view); + return 0; + } + return Py_CLEANUP_SUPPORTED; +} + +static bool inline +check_indices(int c, Py_ssize_t j, Py_ssize_t l, Py_ssize_t m) +{ + if (c < 0) { + PyErr_Format(PyExc_ValueError, + "sequences[%zd][%zd] is negative (%d)", j, l, c); + return false; + } + if (c >= m) { \ + PyErr_Format(PyExc_ValueError, + "sequence[%zd][%zd] is out of bound" + " (%d, should be < %zd)", j, l, c, m); + return false; + } + return true; +} + +static bool inline +map_indices(int* cA, int* cB, int* mapping) +{ + *cA = mapping[*cA]; + *cB = mapping[*cB]; + if (*cA == MISSING_LETTER || *cB == MISSING_LETTER) { + PyErr_SetString(PyExc_ValueError, + "sequence contains letters not in the alphabet"); + return false; + } + return true; +} + +static inline PyObject* get_lazy_data(PyObject* sequence, Py_ssize_t start, Py_ssize_t end, Py_ssize_t j, char** b) +{ + PyObject* obj = PySequence_GetSlice(sequence, start, end); + if (!obj) return NULL; + if (PyBytes_Check(obj)) { + if (PyBytes_GET_SIZE(obj) == end - start) { + *b = PyBytes_AS_STRING(obj) - start; + return obj; + } + PyErr_Format(PyExc_ValueError, + "alignment.sequences[%zd][%zd:%zd] did not return a bytes object of size %zd", + j, start, end, end - start); + Py_DECREF(obj); + } + return obj; +} + +static inline void reset_lazy_data(PyObject* obj, char** b) { + if (obj) { + Py_DECREF(obj); + *b = NULL; + } +} + +static void inline +add_identities_mismatches(int cA, int cB, int wildcard, + Py_ssize_t* identities, Py_ssize_t* mismatches) +{ + if (cA == wildcard || cB == wildcard) return; + else if (cA == cB) (*identities)++; + else (*mismatches)++; +} + +static void inline +add_identities_mismatches_score(int cA, int cB, int wildcard, + Py_buffer* substitution_matrix, + Py_ssize_t* identities, + Py_ssize_t* mismatches, + Py_ssize_t* positives, + double* substitution_score) +{ + const double value = *((double*)substitution_matrix->buf + + cA * substitution_matrix->shape[0] + + cB); + if (cA == cB) (*identities)++; + else (*mismatches)++; + if (value > 0) (*positives)++; + *substitution_score += value; +} + +static inline bool add_gaps(int* path, const int direction, bool strand, + PyObject* score_function, + Py_ssize_t start, Py_ssize_t end, + Py_ssize_t left, Py_ssize_t right, + Py_ssize_t gapsize, + Py_ssize_t* open_left_gaps, + Py_ssize_t* extend_left_gaps, + Py_ssize_t* open_internal_gaps, + Py_ssize_t* extend_internal_gaps, + Py_ssize_t* open_right_gaps, + Py_ssize_t* extend_right_gaps, + double* gap_score) +{ + if (*path == direction) { + if (start == left) + *extend_left_gaps += gapsize; + else if (end == right) + *extend_right_gaps += gapsize; + else + *extend_internal_gaps += gapsize; + } + else { + if (start == left) { + (*open_left_gaps)++; + *extend_left_gaps += gapsize - 1; + } + else if (end == right) { + (*open_right_gaps)++; + *extend_right_gaps += gapsize - 1; + } + else { + (*open_internal_gaps)++; + *extend_internal_gaps += gapsize - 1; \ + } \ + if (score_function) { + double value; + PyObject* result; + if (strand) + result = PyObject_CallFunction(score_function, "ii", + right - start, gapsize); + else + result = PyObject_CallFunction(score_function, + "ii", start, gapsize); + if (result == NULL) return false; + value = PyFloat_AsDouble(result); + Py_DECREF(result); + if (value == -1.0 && PyErr_Occurred()) return false; + *gap_score += value; + } + *path = direction; + } + return true; +} + +static inline Py_buffer* get_buffer(Py_buffer *sequence, int** i, char** b) +{ + *i = NULL; + *b = NULL; + if (sequence->buf) { + switch (sequence->format[0]) { + case 'i': + case 'l': + *i = sequence->buf; + break; + case 'c': + case 'b': + case 'B': + *b = sequence->buf; + break; + } + } + return sequence; +} + +static PyObject* +AlignmentCounts_new(PyTypeObject *type, PyObject *args, PyObject *keywords) +{ + Py_ssize_t jA, jB; + Py_ssize_t n = 0; + PyObject* sequence; + Aligner* aligner = NULL; + PyObject* sequences; + Py_buffer* sequence_buffers = NULL; + Py_buffer coordinates = {0}; + Py_buffer strands = {0}; + AlignmentCounts* counts = NULL; + int wildcard = -1; + Py_buffer substitution_matrix = {0}; + PyObject* argument = NULL; + + Py_ssize_t k, lA, lB; + int cA, cB; + + Py_buffer* sequenceA; + Py_buffer* sequenceB; + int* iA = NULL; + int* iB = NULL; + char* bA = NULL; + char* bB = NULL; + bool strandA; + bool strandB; + + int* mapping = NULL; + Py_ssize_t m = 0; + + PyObject* insertion_score_function = NULL; + PyObject* deletion_score_function = NULL; + + Py_ssize_t open_left_insertions = 0, extend_left_insertions = 0; + Py_ssize_t open_left_deletions = 0, extend_left_deletions = 0; + Py_ssize_t open_internal_insertions = 0, extend_internal_insertions = 0; + Py_ssize_t open_internal_deletions = 0, extend_internal_deletions = 0; + Py_ssize_t open_right_insertions = 0, extend_right_insertions = 0; + Py_ssize_t open_right_deletions = 0, extend_right_deletions = 0; + + Py_ssize_t aligned = 0; + Py_ssize_t identities = 0; + Py_ssize_t mismatches = 0; + Py_ssize_t positives = -1; + + double gap_score = 0.0; + double substitution_score = 0.0; + + Py_ssize_t n_columns; + Py_ssize_t row_stride; + Py_ssize_t column_stride; + + int path = 0; + + Py_ssize_t leftA, leftB; + Py_ssize_t rightA, rightB; + Py_ssize_t startA, startB; + Py_ssize_t endA, endB; + Py_ssize_t* buffer; + + PyObject* oA = NULL; + PyObject* oB = NULL; + + static char *kwlist[] = {"sequences", "coordinates", "strands", "argument", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, keywords, "O!O&O&|O", kwlist, + &PyList_Type, &sequences, + coordinates_converter, &coordinates, + strands_converter , &strands, + &argument)) + return 0; + + if (argument == NULL) { + } + else if (PyObject_TypeCheck(argument, Aligner_Type)) { + aligner = (Aligner*)argument; + if (aligner->substitution_matrix.obj) { + substitution_matrix = aligner->substitution_matrix; + Py_INCREF(substitution_matrix.obj); + } + wildcard = aligner->wildcard; + } + else if (PyUnicode_Check(argument)) { + if (PyUnicode_READY(argument) == -1) goto exit; + if (PyUnicode_GET_LENGTH(argument) != 1) { + PyErr_SetString(PyExc_ValueError, + "wildcard should be a single character, or None"); + goto exit; + } + wildcard = PyUnicode_READ_CHAR(argument, 0); + } + else { + if (!substitution_matrix_converter(argument, + &substitution_matrix)) { + if (!Aligner_Type) + PyErr_SetString(PyExc_RuntimeError, "Aligner_Type is NULL"); + goto exit; + } + } + + n_columns = coordinates.shape[1]; + row_stride = coordinates.strides[0] / sizeof(Py_ssize_t); + column_stride = coordinates.strides[1] / sizeof(Py_ssize_t); + buffer = coordinates.buf; + + if (substitution_matrix.obj) positives = 0; + + n = PyList_GET_SIZE(sequences); + if (n != coordinates.shape[0]) { + PyErr_SetString(PyExc_ValueError, + "number of rows in coordinates must equal the number of sequences"); + goto exit; + } + if (n != strands.shape[0]) { + PyErr_SetString(PyExc_ValueError, + "size of strands must equal the number of sequences"); + goto exit; + } + + sequence_buffers = PyMem_Calloc(n, sizeof(Py_buffer)); + if (!sequence_buffers) goto exit; + + for (k = 0; k < n; k++) { + sequence = PyList_GET_ITEM(sequences, k); + if (!sequence_converter(sequence, &sequence_buffers[k])) { + n = k; + goto exit; + } + } + + if (aligner) { + insertion_score_function = aligner->insertion_score_function; + deletion_score_function = aligner->deletion_score_function; + } + + counts = (AlignmentCounts*)PyType_GenericAlloc(&AlignmentCounts_Type, 0); + if (!counts) goto exit; + + if (substitution_matrix.obj) { + m = substitution_matrix.shape[0]; + if (PyObject_IsInstance(substitution_matrix.obj, + (PyObject*)Array_Type)) { + PyTypeObject* basetype = Array_Type->tp_base; + Fields* fields = (Fields*)((intptr_t)substitution_matrix.obj + basetype->tp_basicsize); + Py_buffer* mapping_buffer = &fields->mapping; + mapping = mapping_buffer->buf; + if (mapping) m = mapping_buffer->len / mapping_buffer->itemsize; + } + } + + for (jA = 0; jA < n; jA++) { + oA = NULL; + sequenceA = get_buffer(&sequence_buffers[jA], &iA, &bA); + strandA = ((bool*)(strands.buf))[jA]; + for (jB = jA + 1; jB < n; jB++) { + oB = NULL; + sequenceB = get_buffer(&sequence_buffers[jB], &iB, &bB); + strandB = ((bool*)(strands.buf))[jB]; + leftA = buffer[jA * row_stride + 0]; + leftB = buffer[jB * row_stride + 0]; + rightA = buffer[jA * row_stride + (n_columns - 1) * column_stride]; + rightB = buffer[jB * row_stride + (n_columns - 1) * column_stride]; + startA = leftA; + startB = leftB; + for (k = 1; k < n_columns; k++) { + endA = buffer[jA * row_stride + k * column_stride]; + endB = buffer[jB * row_stride + k * column_stride]; + if (startA == endA && startB == endB) { + } + else if (startA == endA) { + if (!add_gaps(&path, HORIZONTAL, strandA, + insertion_score_function, + startA, endA, leftA, rightA, endB - startB, + &open_left_insertions, + &extend_left_insertions, + &open_internal_insertions, + &extend_internal_insertions, + &open_right_insertions, + &extend_right_insertions, + &gap_score)) goto error; + } + else if (startB == endB) { + if (!add_gaps(&path, VERTICAL, strandB, + deletion_score_function, + startB, endB, leftB, rightB, endA - startA, + &open_left_deletions, + &extend_left_deletions, + &open_internal_deletions, + &extend_internal_deletions, + &open_right_deletions, + &extend_right_deletions, + &gap_score)) goto error; + } + else if (sequenceA->obj == NULL || sequenceB->obj == NULL) { + path = DIAGONAL; + aligned += endA - startA; + } + else { + path = DIAGONAL; + aligned += endA - startA; + if (iA == NULL && bA == NULL) { + oA = get_lazy_data(sequenceA->obj, startA, endA, jA, &bA); + if (!oA) goto error; + } + if (iB == NULL && bB == NULL) { + oB = get_lazy_data(sequenceB->obj, startB, endB, jB, &bB); + if (!oB) goto error; + } + if (substitution_matrix.obj == NULL) { + if (iA && iB) { + for (lA = startA, lB = startB; + lA < endA && lB < endB; + lA++, lB++) { + add_identities_mismatches(iA[lA], + iB[lB], + wildcard, + &identities, + &mismatches); + } + } + else if (iA && bB) { + for (lA = startA, lB = startB; + lA < endA && lB < endB; + lA++, lB++) { + add_identities_mismatches(iA[lA], + (int) bB[lB], + wildcard, + &identities, + &mismatches); + } + } + else if (iB && bA) { + for (lA = startA, lB = startB; + lA < endA && lB < endB; + lA++, lB++) { + add_identities_mismatches((int) bA[lA], + iB[lB], + wildcard, + &identities, + &mismatches); + } + } + else if (bA && bB) { + for (lA = startA, lB = startB; + lA < endA && lB < endB; + lA++, lB++) { + add_identities_mismatches((int) bA[lA], + (int) bB[lB], + wildcard, + &identities, + &mismatches); + } + } + } + else if (mapping == NULL) { + if (iA && iB) { + for (lA = startA, lB = startB; + lA < endA && lB < endB; + lA++, lB++) { + cA = iA[lA]; + cB = iB[lB]; + if (!check_indices(cA, jA, lA, m)) goto error; + if (!check_indices(cB, jB, lB, m)) goto error; + add_identities_mismatches_score(cA, cB, + wildcard, + &substitution_matrix, + &identities, + &mismatches, + &positives, + &substitution_score); + } + } else if (iA && bB) { + for (lA = startA, lB = startB; + lA < endA && lB < endB; + lA++, lB++) { + cA = iA[lA]; + cB = (int)bB[lB]; + if (!check_indices(cA, jA, lA, m)) goto error; + if (!check_indices(cB, jB, lB, m)) goto error; + add_identities_mismatches_score(cA, cB, + wildcard, + &substitution_matrix, + &identities, + &mismatches, + &positives, + &substitution_score); + } + } else if (iB && bA) { + for (lA = startA, lB = startB; + lA < endA && lB < endB; + lA++, lB++) { + cA = (int) bA[lA]; + cB = iB[lB]; + if (!check_indices(cA, jA, lA, m)) goto error; + if (!check_indices(cB, jB, lB, m)) goto error; + add_identities_mismatches_score(cA, cB, + wildcard, + &substitution_matrix, + &identities, + &mismatches, + &positives, + &substitution_score); + } + } + else if (bA && bB) { + for (lA = startA, lB = startB; + lA < endA && lB < endB; + lA++, lB++) { + cA = (int) bA[lA]; + cB = (int) bB[lB]; + if (!check_indices(cA, jA, lA, m)) goto error; + if (!check_indices(cB, jB, lB, m)) goto error; + add_identities_mismatches_score(cA, cB, + wildcard, + &substitution_matrix, + &identities, + &mismatches, + &positives, + &substitution_score); + } + } + } + else { + if (iA && iB) { + for (lA = startA, lB = startB; + lA < endA && lB < endB; + lA++, lB++) { + cA = iA[lA]; + cB = iB[lB]; + if (!check_indices(cA, jA, lA, m)) goto error; + if (!check_indices(cB, jB, lB, m)) goto error; + if (!map_indices(&cA, &cB, mapping)) goto error; + add_identities_mismatches_score(cA, cB, + wildcard, + &substitution_matrix, + &identities, + &mismatches, + &positives, + &substitution_score); + } + } else if (iA && bB) { + for (lA = startA, lB = startB; + lA < endA && lB < endB; + lA++, lB++) { + cA = iA[lA]; + cB = (int)bB[lB]; + if (!check_indices(cA, jA, lA, m)) goto error; + if (!check_indices(cB, jB, lB, m)) goto error; + if (!map_indices(&cA, &cB, mapping)) goto error; + add_identities_mismatches_score(cA, cB, + wildcard, + &substitution_matrix, + &identities, + &mismatches, + &positives, + &substitution_score); + } + } else if (iB && bA) { + for (lA = startA, lB = startB; + lA < endA && lB < endB; + lA++, lB++) { + cA = (int) bA[lA]; + cB = iB[lB]; + if (!check_indices(cA, jA, lA, m)) goto error; + if (!check_indices(cB, jB, lB, m)) goto error; + if (!map_indices(&cA, &cB, mapping)) goto error; + add_identities_mismatches_score(cA, cB, + wildcard, + &substitution_matrix, + &identities, + &mismatches, + &positives, + &substitution_score); + } + } + else if (bA && bB) { + for (lA = startA, lB = startB; + lA < endA && lB < endB; + lA++, lB++) { + cA = (int) bA[lA]; + cB = (int) bB[lB]; + if (!check_indices(cA, jA, lA, m)) goto error; + if (!check_indices(cB, jB, lB, m)) goto error; + if (!map_indices(&cA, &cB, mapping)) goto error; + add_identities_mismatches_score(cA, cB, + wildcard, + &substitution_matrix, + &identities, + &mismatches, + &positives, + &substitution_score); + } + } + } + reset_lazy_data(oA, &bA); + reset_lazy_data(oB, &bB); + } + startA = endA; + startB = endB; + } + } + } + + counts->open_left_insertions = open_left_insertions; + counts->extend_left_insertions = extend_left_insertions; + counts->open_left_deletions = open_left_deletions; + counts->extend_left_deletions = extend_left_deletions; + counts->open_internal_insertions = open_internal_insertions; + counts->extend_internal_insertions = extend_internal_insertions; + counts->open_internal_deletions = open_internal_deletions; + counts->extend_internal_deletions = extend_internal_deletions; + counts->open_right_insertions = open_right_insertions; + counts->extend_right_insertions = extend_right_insertions; + counts->open_right_deletions = open_right_deletions; + counts->extend_right_deletions = extend_right_deletions; + counts->aligned = aligned; + counts->identities = identities; + counts->mismatches = mismatches; + counts->positives = positives; + + if (substitution_matrix.obj == NULL) { + if (aligner) { + substitution_score = aligner->match * counts->identities + + aligner->mismatch * counts->mismatches; + } + else substitution_score = Py_NAN; + } + counts->substitution_score = substitution_score; + + if (aligner) { + if (aligner->insertion_score_function == NULL) { + gap_score += counts->open_left_insertions + * aligner->open_left_insertion_score + + counts->extend_left_insertions + * aligner->extend_left_insertion_score + + counts->open_internal_insertions + * aligner->open_internal_insertion_score + + counts->extend_internal_insertions + * aligner->extend_internal_insertion_score + + counts->open_right_insertions + * aligner->open_right_insertion_score + + counts->extend_right_insertions + * aligner->extend_right_insertion_score; + } + if (aligner->deletion_score_function == NULL) { + gap_score += counts->open_left_deletions + * aligner->open_left_deletion_score + + counts->extend_left_deletions + * aligner->extend_left_deletion_score + + counts->open_internal_deletions + * aligner->open_internal_deletion_score + + counts->extend_internal_deletions + * aligner->extend_internal_deletion_score + + counts->open_right_deletions + * aligner->open_right_deletion_score + + counts->extend_right_deletions + * aligner->extend_right_deletion_score; + } + } + else gap_score = Py_NAN; + counts->gap_score = gap_score; + + goto exit; + +error: + Py_XDECREF(oA); + Py_XDECREF(oB); + Py_DECREF(counts); + counts = NULL; + +exit: + if (sequence_buffers) { + for (k = 0; k < n; k++) + if (sequence_buffers[k].buf) PyBuffer_Release(&sequence_buffers[k]); + PyMem_Free(sequence_buffers); + } + coordinates_converter(NULL, &coordinates); + strands_converter(NULL, &strands); + substitution_matrix_converter(NULL, &substitution_matrix); + + return (PyObject*) counts; +} + +static PyTypeObject AlignmentCounts_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "AlignmentCounts", + .tp_basicsize = sizeof(AlignmentCounts), + .tp_repr = (reprfunc)AlignmentCounts_repr, + .tp_str = (reprfunc)AlignmentCounts_str, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + .tp_doc = AlignmentCounts_doc, + .tp_getset = AlignmentCounts_getset, + .tp_new = (newfunc)AlignmentCounts_new, +}; + + +static char _alignmentcounts__doc__[] = +"C extension module implementing the AlignmentCounts class"; + +/* Module definition */ + +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + .m_name = "_alignmentcounts", + .m_doc = _alignmentcounts__doc__, + .m_size = -1, +}; + +PyObject * +PyInit__alignmentcounts(void) +{ + PyObject* module; + + if (PyType_Ready(&AlignmentCounts_Type) < 0) + return NULL; + + module = PyModule_Create(&moduledef); + if (!module) return NULL; + + PyObject *mod; + mod = PyImport_ImportModule("Bio.Align.substitution_matrices._arraycore"); + if (!mod) { + Py_DECREF(module); + return NULL; + } + Array_Type = (PyTypeObject*)PyObject_GetAttrString(mod, "Array"); + Py_DECREF(mod); + + mod = PyImport_ImportModule("Bio.Align._pairwisealigner"); + if (!mod) { + Py_DECREF(module); + return NULL; + } + Aligner_Type = (PyTypeObject*)PyObject_GetAttrString(mod, "PairwiseAligner"); + Py_DECREF(mod); + if (!Aligner_Type) { + Py_DECREF(module); + return NULL; + } + + Py_INCREF(&AlignmentCounts_Type); + if (PyModule_AddObject(module, + "AlignmentCounts", + (PyObject*) &AlignmentCounts_Type) < 0) { + Py_DECREF(module); + Py_DECREF(&AlignmentCounts_Type); + return NULL; + } + + return module; +} diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_alignmentcounts.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_alignmentcounts.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..bc53e4705d726ac26c953a340fa28ce4cc743914 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_alignmentcounts.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_codonaligner.c b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_codonaligner.c new file mode 100644 index 0000000000000000000000000000000000000000..76f9ca982d7b6b92295be2166dd090416b13f76c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_codonaligner.c @@ -0,0 +1,1106 @@ +/* Copyright 2023-2025 by Michiel de Hoon. All rights reserved. + * This file is part of the Biopython distribution and governed by your + * choice of the "Biopython License Agreement" or the "BSD 3-Clause License". + * Please see the LICENSE file that should have been included as part of this + * package. + */ + + +#define PY_SSIZE_T_CLEAN +#include "Python.h" +#include "float.h" + + +#define FRAMESHIFT_MINUS_TWO 0x1 +#define FRAMESHIFT_MINUS_ONE 0x2 +#define FRAMESHIFT_NONE 0x4 +#define FRAMESHIFT_PLUS_ONE 0x8 +#define FRAMESHIFT_PLUS_TWO 0x10 + +#define DONE 6 +#define NONE 7 + +#define OVERFLOW_ERROR -1 +#define MEMORY_ERROR -2 + +#define SAFE_ADD(t, s) \ +{ if (s != OVERFLOW_ERROR) { \ + term = t; \ + if (term > PY_SSIZE_T_MAX - s) s = OVERFLOW_ERROR; \ + else s += term; \ + } \ +} + + +typedef struct { + unsigned char trace : 5; + unsigned char path : 3; +} Trace; + +typedef struct { + PyObject_HEAD + Trace** M; + int nA; + int nB; + Py_ssize_t length; +} PathGenerator; + +static PyObject* +PathGenerator_create_path(PathGenerator* self, int j) { + PyObject* tuple; + PyObject* target_row; + PyObject* query_row; + PyObject* value; + int path; + int i = 0; + int k, l; + int n = 1; + int direction = 0; + Trace** M = self->M; + + k = i; + l = j; + while (1) { + path = M[k][l].path; + if (!path) break; + if (path % 3 != 0) { + n += 2; + direction = 3; + } + else if (path != direction) { + n++; + direction = path; + } + l += path; + k++; + } + + direction = 0; + tuple = PyTuple_New(2); + if (!tuple) return NULL; + target_row = PyTuple_New(n); + query_row = PyTuple_New(n); + PyTuple_SET_ITEM(tuple, 0, target_row); + PyTuple_SET_ITEM(tuple, 1, query_row); + + if (target_row && query_row) { + k = 0; + while (1) { + path = M[i][j].path; + if (path % 3 != 0) { + value = PyLong_FromLong(i); + if (!value) break; + PyTuple_SET_ITEM(target_row, k, value); + value = PyLong_FromLong(j); + if (!value) break; + PyTuple_SET_ITEM(query_row, k, value); + k++; + j += path - 3; + value = PyLong_FromLong(i); + if (!value) break; + PyTuple_SET_ITEM(target_row, k, value); + value = PyLong_FromLong(j); + if (!value) break; + PyTuple_SET_ITEM(query_row, k, value); + k++; + direction = 3; + } + else if (path != direction) { + value = PyLong_FromLong(i); + if (!value) break; + PyTuple_SET_ITEM(target_row, k, value); + value = PyLong_FromLong(j); + if (!value) break; + PyTuple_SET_ITEM(query_row, k, value); + k++; + direction = path; + if (path == 0) return tuple; + } + i++; + j += 3; + } + } + Py_DECREF(tuple); /* all references were stolen */ + return PyErr_NoMemory(); +} + +static Py_ssize_t PathGenerator_length(PathGenerator* self) { + Py_ssize_t count = self->length; + if (count == 0) { + int i; + int j; + int trace; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + Py_ssize_t term; + Py_ssize_t* counts1 = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + Py_ssize_t* counts2 = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (counts1 == NULL || counts2 == NULL) { + PyErr_NoMemory(); + count = MEMORY_ERROR; + goto exit; + } + for (j = 0; j <= nB; j++) counts2[j] = 1; + for (i = 1; i <= nA; i++) { + memcpy(counts1, counts2, (nB+1)*sizeof(Py_ssize_t)); + for (j = 0; j <= nB; j++) { + trace = M[i][j].trace; + count = 0; + if (trace & FRAMESHIFT_MINUS_TWO) SAFE_ADD(counts1[j-1], count); + if (trace & FRAMESHIFT_MINUS_ONE) SAFE_ADD(counts1[j-2], count); + if (trace & FRAMESHIFT_NONE) SAFE_ADD(counts1[j-3], count); + if (trace & FRAMESHIFT_PLUS_ONE) SAFE_ADD(counts1[j-4], count); + if (trace & FRAMESHIFT_PLUS_TWO) SAFE_ADD(counts1[j-5], count); + counts2[j] = count; + } + } + count = 0; + for (j = 0; j <= nB; j++) count += counts2[j]; + self->length = count; +exit: + PyMem_Free(counts1); + PyMem_Free(counts2); + } + if (count == OVERFLOW_ERROR) + PyErr_Format(PyExc_OverflowError, + "number of optimal alignments is larger than %zd", + PY_SSIZE_T_MAX); + return count; +} + +static void +PathGenerator_dealloc(PathGenerator* self) +{ + int i; + const int nA = self->nA; + Trace** M = self->M; + if (M) { + for (i = 0; i <= nA; i++) { + if (!M[i]) break; + PyMem_Free(M[i]); + } + PyMem_Free(M); + } + Py_TYPE(self)->tp_free((PyObject*)self); +} + +static PyObject * +PathGenerator_next(PathGenerator* self) +{ + int i = 0; + int j; + int path; + int trace = 0; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + + if (M[0][0].path == DONE) return NULL; + for (j = 0; j <= nB; j++) { + path = M[0][j].path; + if (path) { + /* We already have a path. Prune the path to see if there are + * any alternative paths. */ + M[0][j].path = 0; + while (1) { + j += path; + trace = M[i+1][j].trace; + if (path == 1 && trace & FRAMESHIFT_MINUS_ONE) { + path = 2; + break; + } + else if (path <= 2 && trace & FRAMESHIFT_NONE) { + path = 3; + break; + } + else if (path <= 3 && trace & FRAMESHIFT_PLUS_ONE) { + path = 4; + break; + } + else if (path <= 4 && trace & FRAMESHIFT_PLUS_TWO) { + path = 5; + break; + } + i++; + path = M[i][j].path; + if (!path) + /* we reached the end of the alignment without finding + * an alternative path */ + break; + } + if (path) { + j -= path; + M[i][j].path = path; + } + break; + } + } + if (path == 0) { + /* Find the next end point. */ + if (i == 0) { + j = 0; + i = nA; + } + else j++; + for ( ; j <= nB; j++) { + if (M[nA][j].trace) break; + } + if (j > nB) { + /* No further end points, so we are done. */ + M[0][0].path = DONE; + return NULL; + } + } + /* Follow the traceback until we reach the origin. */ + while (1) { + trace = M[i][j].trace; + if (trace & FRAMESHIFT_MINUS_TWO) path = 1; + else if (trace & FRAMESHIFT_MINUS_ONE) path = 2; + else if (trace & FRAMESHIFT_NONE) path = 3; + else if (trace & FRAMESHIFT_PLUS_ONE) path = 4; + else if (trace & FRAMESHIFT_PLUS_TWO) path = 5; + else break; + j -= path; + i--; + M[i][j].path = path; + } + return PathGenerator_create_path(self, j); +} + +static const char PathGenerator_reset__doc__[] = "reset the iterator"; + +static PyObject* +PathGenerator_reset(PathGenerator* self) +{ + Trace** M = self->M; + if (M[0][0].path != NONE) M[0][0].path = 0; + Py_INCREF(Py_None); + return Py_None; +} + +static PyMethodDef PathGenerator_methods[] = { + {"reset", + (PyCFunction)PathGenerator_reset, + METH_NOARGS, + PathGenerator_reset__doc__ + }, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +static PySequenceMethods PathGenerator_as_sequence = { + .sq_length = (lenfunc)PathGenerator_length, +}; + +static PyTypeObject PathGenerator_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "Path generator", + .tp_basicsize = sizeof(PathGenerator), + .tp_dealloc = (destructor)PathGenerator_dealloc, + .tp_as_sequence = &PathGenerator_as_sequence, + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_iter = PyObject_SelfIter, + .tp_iternext = (iternextfunc)PathGenerator_next, + .tp_methods = PathGenerator_methods, +}; + +typedef struct { + PyObject_HEAD + double match; + double mismatch; + double epsilon; + char wildcard; + double frameshift_minus_two_score; + double frameshift_minus_one_score; + double frameshift_plus_one_score; + double frameshift_plus_two_score; +} Aligner; + + +static int +Aligner_init(Aligner *self, PyObject *args, PyObject *kwds) +{ + self->match = 1.0; + self->mismatch = 0.0; + self->epsilon = 1.e-6; + self->wildcard = 'X'; + self->frameshift_minus_two_score = -3.0; + self->frameshift_minus_one_score = -3.0; + self->frameshift_plus_one_score = -3.0; + self->frameshift_plus_two_score = -3.0; + return 0; +} + + +static void +Aligner_dealloc(Aligner* self) +{ + Py_TYPE(self)->tp_free((PyObject*)self); +} + +static PyObject* +Aligner_repr(Aligner* self) +{ + const char text[] = "Codon aligner, implementing a dynamic programming algorithm to align a nucleotide sequence to an amino acid sequence"; + return PyUnicode_FromString(text); +} + +static PyObject* +Aligner_str(Aligner* self) +{ + PyObject* match; + PyObject* mismatch = NULL; + PyObject* text = NULL; + PyObject* frameshift_minus_two_score = NULL; + PyObject* frameshift_minus_one_score = NULL; + PyObject* frameshift_plus_one_score = NULL; + PyObject* frameshift_plus_two_score = NULL; + match = PyFloat_FromDouble(self->match); + if (match == NULL) goto exit; + mismatch = PyFloat_FromDouble(self->mismatch); + if (mismatch == NULL) goto exit; + frameshift_minus_two_score = PyFloat_FromDouble(self->frameshift_minus_two_score); + if (frameshift_minus_two_score == NULL) goto exit; + frameshift_minus_one_score = PyFloat_FromDouble(self->frameshift_minus_one_score); + if (frameshift_minus_one_score == NULL) goto exit; + frameshift_plus_one_score = PyFloat_FromDouble(self->frameshift_plus_one_score); + if (frameshift_plus_one_score == NULL) goto exit; + frameshift_plus_two_score = PyFloat_FromDouble(self->frameshift_plus_two_score); + if (frameshift_plus_two_score == NULL) goto exit; + text = PyUnicode_FromFormat("Codon aligner with parameters\n" + " wildcard: '%c'\n" + " match_score: %S\n" + " mismatch_score: %S\n" + " frameshift_minus_two_score: %S\n" + " frameshift_minus_one_score: %S\n" + " frameshift_plus_one_score: %S\n" + " frameshift_plus_two_score: %S\n", + self->wildcard, + match, + mismatch, + frameshift_minus_two_score, + frameshift_minus_one_score, + frameshift_plus_one_score, + frameshift_plus_two_score); +exit: + Py_XDECREF(match); + Py_XDECREF(mismatch); + Py_XDECREF(frameshift_minus_two_score); + Py_XDECREF(frameshift_minus_one_score); + Py_XDECREF(frameshift_plus_one_score); + Py_XDECREF(frameshift_plus_two_score); + return text; +} + +static char Aligner_match_score__doc__[] = "match score"; + +static PyObject* +Aligner_get_match_score(Aligner* self, void* closure) +{ + return PyFloat_FromDouble(self->match); +} + +static int +Aligner_set_match_score(Aligner* self, PyObject* value, void* closure) +{ + const double match = PyFloat_AsDouble(value); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, "invalid match score"); + return -1; + } + self->match = match; + return 0; +} + +static char Aligner_mismatch_score__doc__[] = "mismatch score"; + +static PyObject* +Aligner_get_mismatch_score(Aligner* self, void* closure) +{ + return PyFloat_FromDouble(self->mismatch); +} + +static int +Aligner_set_mismatch_score(Aligner* self, PyObject* value, void* closure) +{ + const double mismatch = PyFloat_AsDouble(value); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, "invalid mismatch score"); + return -1; + } + self->mismatch = mismatch; + return 0; +} + +static char Aligner_epsilon__doc__[] = "roundoff epsilon"; + +static PyObject* +Aligner_get_epsilon(Aligner* self, void* closure) +{ + return PyFloat_FromDouble(self->epsilon); +} + +static int +Aligner_set_epsilon(Aligner* self, PyObject* value, void* closure) +{ const double epsilon = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->epsilon = epsilon; + return 0; +} + +static PyObject* +Aligner_get_wildcard(Aligner* self, void* closure) +{ + return PyUnicode_FromFormat("%c", self->wildcard); +} + +static int +Aligner_set_wildcard(Aligner* self, PyObject* value, void* closure) +{ + Py_UCS4 wildcard; + if (!PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "wildcard should be a single ASCII character"); + return -1; + } + if (PyUnicode_READY(value) == -1) return -1; + if (PyUnicode_GET_LENGTH(value) != 1) { + PyErr_SetString(PyExc_ValueError, + "wildcard should be a single ASCII character"); + return -1; + } + wildcard = PyUnicode_READ_CHAR(value, 0); + if (wildcard >= 256) { + PyErr_SetString(PyExc_ValueError, + "wildcard should be a single ASCII character"); + return -1; + } + self->wildcard = (char)wildcard; + return 0; +} + +static char Aligner_wildcard__doc__[] = "wildcard character"; + +static PyObject* +Aligner_get_frameshift_minus_two_score(Aligner* self, void* closure) +{ + return PyFloat_FromDouble(self->frameshift_minus_two_score); +} + +static int +Aligner_set_frameshift_minus_two_score(Aligner* self, PyObject* value, void* closure) +{ + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->frameshift_minus_two_score = score; + return 0; +} + +static char Aligner_frameshift_minus_two_score__doc__[] = "score for a -2 frame shift"; + +static PyObject* +Aligner_get_frameshift_minus_one_score(Aligner* self, void* closure) +{ + return PyFloat_FromDouble(self->frameshift_minus_one_score); +} + +static int +Aligner_set_frameshift_minus_one_score(Aligner* self, PyObject* value, void* closure) +{ + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->frameshift_minus_one_score = score; + return 0; +} + +static char Aligner_frameshift_minus_one_score__doc__[] = "score for a -1 frame shift"; + +static PyObject* +Aligner_get_frameshift_plus_one_score(Aligner* self, void* closure) +{ + return PyFloat_FromDouble(self->frameshift_plus_one_score); +} + +static int +Aligner_set_frameshift_plus_one_score(Aligner* self, PyObject* value, void* closure) +{ + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->frameshift_plus_one_score = score; + return 0; +} + +static char Aligner_frameshift_plus_one_score__doc__[] = "score for a +1 frame shift"; + +static PyObject* +Aligner_get_frameshift_plus_two_score(Aligner* self, void* closure) +{ + return PyFloat_FromDouble(self->frameshift_plus_two_score); +} + +static int +Aligner_set_frameshift_plus_two_score(Aligner* self, PyObject* value, void* closure) +{ + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->frameshift_plus_two_score = score; + return 0; +} + +static char Aligner_frameshift_plus_two_score__doc__[] = "score for a +2 frame shift"; + + +static PyObject* +Aligner_get_frameshift_minus_score(Aligner* self, void* closure) +{ + const double score = self->frameshift_minus_two_score; + if (score != self->frameshift_minus_one_score) { + PyErr_SetString(PyExc_ValueError, "-2 and -1 frame shift scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); +} + +static int +Aligner_set_frameshift_minus_score(Aligner* self, PyObject* value, void* closure) +{ + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->frameshift_minus_one_score = score; + self->frameshift_minus_two_score = score; + return 0; +} + +static char Aligner_frameshift_minus_score__doc__[] = "score for a negative frame shift"; + + +static PyObject* +Aligner_get_frameshift_plus_score(Aligner* self, void* closure) +{ + const double score = self->frameshift_plus_two_score; + if (score != self->frameshift_plus_one_score) { + PyErr_SetString(PyExc_ValueError, "+2 and +1 frame shift scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); +} + +static int +Aligner_set_frameshift_plus_score(Aligner* self, PyObject* value, void* closure) +{ + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->frameshift_plus_one_score = score; + self->frameshift_plus_two_score = score; + return 0; +} + +static char Aligner_frameshift_plus_score__doc__[] = "score for a positive frame shift"; + + +static PyObject* +Aligner_get_frameshift_two_score(Aligner* self, void* closure) +{ + const double score = self->frameshift_minus_two_score; + if (score != self->frameshift_plus_two_score) { + PyErr_SetString(PyExc_ValueError, "-2 and +2 frame shift scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); +} + +static int +Aligner_set_frameshift_two_score(Aligner* self, PyObject* value, void* closure) +{ + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->frameshift_minus_two_score = score; + self->frameshift_plus_two_score = score; + return 0; +} + +static char Aligner_frameshift_two_score__doc__[] = "score for a -2 or +2 frame shift"; + + +static PyObject* +Aligner_get_frameshift_one_score(Aligner* self, void* closure) +{ + const double score = self->frameshift_minus_one_score; + if (score != self->frameshift_plus_one_score) { + PyErr_SetString(PyExc_ValueError, "-1 and +1 frame shift scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); +} + +static int +Aligner_set_frameshift_one_score(Aligner* self, PyObject* value, void* closure) +{ + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->frameshift_minus_one_score = score; + self->frameshift_plus_one_score = score; + return 0; +} + +static char Aligner_frameshift_one_score__doc__[] = "score for a -1 or +1 frame shift"; + + +static PyObject* +Aligner_get_frameshift_score(Aligner* self, void* closure) +{ + const double score = self->frameshift_minus_one_score; + if (score != self->frameshift_minus_two_score || + score != self->frameshift_plus_one_score || + score != self->frameshift_plus_two_score) { + PyErr_SetString(PyExc_ValueError, "frame shift scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); +} + +static int +Aligner_set_frameshift_score(Aligner* self, PyObject* value, void* closure) +{ + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->frameshift_minus_two_score = score; + self->frameshift_minus_one_score = score; + self->frameshift_plus_one_score = score; + self->frameshift_plus_two_score = score; + return 0; +} + +static char Aligner_frameshift_score__doc__[] = "frame shift score"; + + +static PyGetSetDef Aligner_getset[] = { + {"match_score", + (getter)Aligner_get_match_score, + (setter)Aligner_set_match_score, + Aligner_match_score__doc__, NULL}, + {"mismatch_score", + (getter)Aligner_get_mismatch_score, + (setter)Aligner_set_mismatch_score, + Aligner_mismatch_score__doc__, NULL}, + {"match", /* synonym for match_score */ + (getter)Aligner_get_match_score, + (setter)Aligner_set_match_score, + Aligner_match_score__doc__, NULL}, + {"mismatch", /* synonym for mismatch_score */ + (getter)Aligner_get_mismatch_score, + (setter)Aligner_set_mismatch_score, + Aligner_mismatch_score__doc__, NULL}, + {"epsilon", + (getter)Aligner_get_epsilon, + (setter)Aligner_set_epsilon, + Aligner_epsilon__doc__, NULL}, + {"wildcard", + (getter)Aligner_get_wildcard, + (setter)Aligner_set_wildcard, + Aligner_wildcard__doc__, NULL}, + {"frameshift_minus_two_score", + (getter)Aligner_get_frameshift_minus_two_score, + (setter)Aligner_set_frameshift_minus_two_score, + Aligner_frameshift_minus_two_score__doc__, NULL}, + {"frameshift_minus_one_score", + (getter)Aligner_get_frameshift_minus_one_score, + (setter)Aligner_set_frameshift_minus_one_score, + Aligner_frameshift_minus_one_score__doc__, NULL}, + {"frameshift_plus_one_score", + (getter)Aligner_get_frameshift_plus_one_score, + (setter)Aligner_set_frameshift_plus_one_score, + Aligner_frameshift_plus_one_score__doc__, NULL}, + {"frameshift_plus_two_score", + (getter)Aligner_get_frameshift_plus_two_score, + (setter)Aligner_set_frameshift_plus_two_score, + Aligner_frameshift_plus_two_score__doc__, NULL}, + {"frameshift_minus_score", + (getter)Aligner_get_frameshift_minus_score, + (setter)Aligner_set_frameshift_minus_score, + Aligner_frameshift_minus_score__doc__, NULL}, + {"frameshift_plus_score", + (getter)Aligner_get_frameshift_plus_score, + (setter)Aligner_set_frameshift_plus_score, + Aligner_frameshift_plus_score__doc__, NULL}, + {"frameshift_one_score", + (getter)Aligner_get_frameshift_one_score, + (setter)Aligner_set_frameshift_one_score, + Aligner_frameshift_one_score__doc__, NULL}, + {"frameshift_two_score", + (getter)Aligner_get_frameshift_two_score, + (setter)Aligner_set_frameshift_two_score, + Aligner_frameshift_two_score__doc__, NULL}, + {"frameshift_score", + (getter)Aligner_get_frameshift_score, + (setter)Aligner_set_frameshift_score, + Aligner_frameshift_score__doc__, NULL}, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +/* ----------------- alignment algorithms ----------------- */ + +#define COMPARE_SCORE (cA == wildcard || cB == wildcard) ? 0 : (cA == cB) ? match : mismatch + + +static const char Aligner_score__doc__[] = "calculates the alignment score"; + +static PyObject* +Aligner_score(Aligner* self, PyObject* args, PyObject* keywords) +{ + char* sA; + char* sB[3]; + Py_ssize_t nA; + Py_ssize_t nB; + Py_ssize_t nB0; + Py_ssize_t nB1; + Py_ssize_t nB2; + Py_buffer bA; + Py_buffer bB0; + Py_buffer bB1; + Py_buffer bB2; + PyObject* result = NULL; + + const double match = self->match; + const double mismatch = self->mismatch; + const char wildcard = self->wildcard; + int i; + int j; + int div; + int mod; + char cA; + char cB; + const double frameshift_minus_two_score = self->frameshift_minus_two_score; + const double frameshift_minus_one_score = self->frameshift_minus_one_score; + const double frameshift_plus_one_score = self->frameshift_plus_one_score; + const double frameshift_plus_two_score = self->frameshift_plus_two_score; + double score; + double temp; + double* row = NULL; + + static char *kwlist[] = {"sA", "sB0", "sB1", "sB2", NULL}; + + if(!PyArg_ParseTupleAndKeywords(args, keywords, "y*y*y*y*", + kwlist, &bA, &bB0, &bB1, &bB2)) + return NULL; + + nA = bA.len; + nB0 = bB0.len; + nB1 = bB1.len; + nB2 = bB2.len; + if (nB1 == nB0 && nB2 == nB0) nB = 3 * nB0 + 2; + else if (nB1 == nB0 && nB2 == nB0 - 1) nB = 3 * nB0 + 1; + else if (nB1 == nB0 - 1 && nB2 == nB0 - 1) nB = 3 * nB0; + else { + PyErr_Format(PyExc_RuntimeError, + "unexpected length of buffers (%zd, %zd, %zd)", + nB0, nB1, nB2); + PyBuffer_Release(&bA); + PyBuffer_Release(&bB0); + PyBuffer_Release(&bB1); + PyBuffer_Release(&bB2); + return NULL; + } + + sA = bA.buf; + sB[0] = bB0.buf; + sB[1] = bB1.buf; + sB[2] = bB2.buf; + + row = PyMem_Malloc((nB+1)*sizeof(double)); + if (!row) goto exit; + memset(row, '\0', (nB+1)*sizeof(double)); + + for (i = 1; i <= nA; i++) { + cA = sA[i-1]; + for (j = (int)nB; j > 0; j--) { + score = -DBL_MAX; + if (j >= 3) { + div = (j - 3) / 3; + mod = (j - 3) % 3; + cB = sB[mod][div]; + temp = row[j-1] + (COMPARE_SCORE) + frameshift_minus_two_score; + if (temp > score) score = temp; + temp = row[j-2] + (COMPARE_SCORE) + frameshift_minus_one_score; + if (temp > score) score = temp; + temp = row[j-3] + (COMPARE_SCORE); + if (temp > score) score = temp; + } + if (j >= 4) { + temp = row[j-4] + (COMPARE_SCORE) + frameshift_plus_one_score; + if (temp > score) score = temp; + } + if (j >= 5) { + temp = row[j-5] + (COMPARE_SCORE) + frameshift_plus_two_score; + if (temp > score) score = temp; + } + row[j] = score; + } + } + score = -DBL_MAX; + for (j = 0; j <= nB; j++) { + temp = row[j]; + if (temp > score) score = temp; + } + + result = PyFloat_FromDouble(score); + +exit: + PyBuffer_Release(&bA); + PyBuffer_Release(&bB0); + PyBuffer_Release(&bB1); + PyBuffer_Release(&bB2); + PyMem_Free(row); + if (result == NULL) { + return PyErr_NoMemory(); + } + return result; +} + +static const char Aligner_align__doc__[] = "align two sequences"; + +static PyObject* +Aligner_align(Aligner* self, PyObject* args, PyObject* keywords) +{ + char* sA; + char* sB[3]; + Py_ssize_t nA; + Py_ssize_t nB; + Py_ssize_t nB0; + Py_ssize_t nB1; + Py_ssize_t nB2; + Py_buffer bA; + Py_buffer bB0; + Py_buffer bB1; + Py_buffer bB2; + PyObject* result = NULL; + + const double match = self->match; + const double mismatch = self->mismatch; + const char wildcard = self->wildcard; + int i; + int j; + int div; + int mod; + char cA; + char cB; + const double epsilon = self->epsilon; + const double frameshift_minus_two_score = self->frameshift_minus_two_score; + const double frameshift_minus_one_score = self->frameshift_minus_one_score; + const double frameshift_plus_one_score = self->frameshift_plus_one_score; + const double frameshift_plus_two_score = self->frameshift_plus_two_score; + Trace** M; + double score; + double temp; + unsigned char trace; + double* row = NULL; + PathGenerator* paths; + + static char *kwlist[] = {"sA", "sB0", "sB1", "sB2", NULL}; + + if(!PyArg_ParseTupleAndKeywords(args, keywords, "y*y*y*y*", + kwlist, &bA, &bB0, &bB1, &bB2)) + return NULL; + + nA = bA.len; + nB0 = bB0.len; + nB1 = bB1.len; + nB2 = bB2.len; + if (nB1 == nB0 && nB2 == nB0) nB = 3 * nB0 + 2; + else if (nB1 == nB0 && nB2 == nB0 - 1) nB = 3 * nB0 + 1; + else if (nB1 == nB0 - 1 && nB2 == nB0 - 1) nB = 3 * nB0; + else { + PyErr_Format(PyExc_RuntimeError, + "unexpected length of buffers (%zd, %zd, %zd)", + nB0, nB1, nB2); + PyBuffer_Release(&bA); + PyBuffer_Release(&bB0); + PyBuffer_Release(&bB1); + PyBuffer_Release(&bB2); + return NULL; + } + + sA = bA.buf; + sB[0] = bB0.buf; + sB[1] = bB1.buf; + sB[2] = bB2.buf; + + paths = (PathGenerator*)PyType_GenericAlloc(&PathGenerator_Type, 0); + if (!paths) goto exit; + + paths->nA = (int)nA; + paths->nB = (int)nB; + paths->M = NULL; + paths->length = 0; + + M = PyMem_Malloc((nA+1)*sizeof(Trace*)); + if (!M) goto exit; + paths->M = M; + for (i = 0; i <= nA; i++) { + M[i] = PyMem_Malloc((nB+1)*sizeof(Trace)); + if (!M[i]) { + Py_DECREF(paths); + PyErr_NoMemory(); + goto exit; + } + M[i][0].trace = 0; + } + memset(M[0], '\0', (nB+1)*sizeof(Trace)); + + row = PyMem_Malloc((nB+1)*sizeof(double)); + if (!row) goto exit; + memset(row, '\0', (nB+1)*sizeof(double)); + + M = paths->M; + for (i = 1; i <= nA; i++) { + cA = sA[i-1]; + for (j = (int)nB; j > 0; j--) { + score = -DBL_MAX; + trace = 0; + if (j >= 3) { + div = (j - 3) / 3; + mod = (j - 3) % 3; + cB = sB[mod][div]; + temp = row[j-1] + (COMPARE_SCORE) + frameshift_minus_two_score; + if (temp > score + epsilon) { + score = temp; + trace = FRAMESHIFT_MINUS_TWO; + } + else if (temp > score - epsilon) { + trace |= FRAMESHIFT_MINUS_TWO; + } + temp = row[j-2] + (COMPARE_SCORE) + frameshift_minus_one_score; + if (temp > score + epsilon) { + score = temp; + trace = FRAMESHIFT_MINUS_ONE; + } + else if (temp > score - epsilon) { + trace |= FRAMESHIFT_MINUS_ONE; + } + temp = row[j-3] + (COMPARE_SCORE); + if (temp > score + epsilon) { + score = temp; + trace = FRAMESHIFT_NONE; + } + else if (temp > score - epsilon) { + trace |= FRAMESHIFT_NONE; + } + } + if (j >= 4) { + temp = row[j-4] + (COMPARE_SCORE) + frameshift_plus_one_score; + if (temp > score + epsilon) { + score = temp; + trace = FRAMESHIFT_PLUS_ONE; + } + else if (temp > score - epsilon) { + trace |= FRAMESHIFT_PLUS_ONE; + } + } + if (j >= 5) { + temp = row[j-5] + (COMPARE_SCORE) + frameshift_plus_two_score; + if (temp > score + epsilon) { + score = temp; + trace = FRAMESHIFT_PLUS_TWO; + } + else if (temp > score - epsilon) { + trace |= FRAMESHIFT_PLUS_TWO; + } + } + M[i][j].trace = trace; + row[j] = score; + } + } + score = -DBL_MAX; + for (j = 0; j <= nB; j++) { + temp = row[j]; + if (temp > score) score = temp; + } + for (j = 0; j <= nB; j++) { + temp = row[j]; + if (temp < score - epsilon) M[nA][j].trace = 0; + else M[nA][j].path = 0; + } + result = Py_BuildValue("fN", score, paths); + +exit: + PyBuffer_Release(&bA); + PyBuffer_Release(&bB0); + PyBuffer_Release(&bB1); + PyBuffer_Release(&bB2); + PyMem_Free(row); + if (result == NULL) { + Py_XDECREF(paths); + return PyErr_NoMemory(); + } + return result; +} + +static char Aligner_doc[] = +"The CodonAligner class implements a dynamic programming algorithm to\n" +"align a nucleotide sequence to an amino acid sequence.\n"; + +static PyMethodDef Aligner_methods[] = { + {"score", + (PyCFunction)Aligner_score, + METH_VARARGS | METH_KEYWORDS, + Aligner_score__doc__ + }, + {"align", + (PyCFunction)Aligner_align, + METH_VARARGS | METH_KEYWORDS, + Aligner_align__doc__ + }, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +static PyTypeObject AlignerType = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "_codonaligner.CodonAligner", + .tp_basicsize = sizeof(Aligner), + .tp_dealloc = (destructor)Aligner_dealloc, + .tp_repr = (reprfunc)Aligner_repr, + .tp_str = (reprfunc)Aligner_str, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + .tp_doc = Aligner_doc, + .tp_methods = Aligner_methods, + .tp_getset = Aligner_getset, + .tp_init = (initproc)Aligner_init, +}; + + +/* Module definition */ + +static char _codonaligner__doc__[] = +"C extension module implementing a dynamic programming algorithm to align a nucleotide sequence to an amino acid sequence"; + +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + .m_name = "_codonaligner", + .m_doc = _codonaligner__doc__, + .m_size = -1, +}; + +PyObject * +PyInit__codonaligner(void) +{ + PyObject* module; + AlignerType.tp_new = PyType_GenericNew; + + if (PyType_Ready(&AlignerType) < 0 || PyType_Ready(&PathGenerator_Type) < 0) + return NULL; + + module = PyModule_Create(&moduledef); + if (!module) return NULL; + + Py_INCREF(&AlignerType); + /* Reference to AlignerType will be stolen by PyModule_AddObject + * only if it is successful. */ + if (PyModule_AddObject(module, + "CodonAligner", (PyObject*) &AlignerType) < 0) { + Py_DECREF(&AlignerType); + Py_DECREF(module); + return NULL; + } + + return module; +} diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_codonaligner.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_codonaligner.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..870de95d3da417ca8e64e124b7bc1b8b6166536e Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_codonaligner.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.c b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.c new file mode 100644 index 0000000000000000000000000000000000000000..143fe0ea21723c7043956dcdc6f362c523395d7d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.c @@ -0,0 +1,7740 @@ +/* Copyright 2018-2025 by Michiel de Hoon. All rights reserved. + * This file is part of the Biopython distribution and governed by your + * choice of the "Biopython License Agreement" or the "BSD 3-Clause License". + * Please see the LICENSE file that should have been included as part of this + * package. + */ + + +#define PY_SSIZE_T_CLEAN +#include "Python.h" +#include +#include +#include "_pairwisealigner.h" +#include "substitution_matrices/_arraycore.h" + + +static bool warned = false; // FIXME remove once Biopython 1.87 is out. + + +#define STARTPOINT 0x8 +#define ENDPOINT 0x10 +#define M_MATRIX 0x1 +#define Ix_MATRIX 0x2 +#define Iy_MATRIX 0x4 +#define DONE 0x3 +#define NONE 0x7 + +#define OVERFLOW_ERROR -1 +#define MEMORY_ERROR -2 +#define OTHER_ERROR -3 + +#define SAFE_ADD(t, s) \ +{ if (s != OVERFLOW_ERROR) { \ + term = t; \ + if (term > PY_SSIZE_T_MAX - s) s = OVERFLOW_ERROR; \ + else s += term; \ + } \ +} + +static PyTypeObject *Array_Type = NULL; +/* this will be set when initializing the module */ + + +#define ERR_UNEXPECTED_MODE \ + PyErr_Format(PyExc_RuntimeError, "mode has unexpected value (in "__FILE__" on line %d)", __LINE__); + +#define ERR_UNEXPECTED_ALGORITHM \ + PyErr_Format(PyExc_RuntimeError, "algorithm has unexpected value (in "__FILE__" on line %d)", __LINE__); + +typedef struct { + unsigned char trace : 5; + unsigned char path : 3; +} Trace; + +typedef struct { + unsigned char Ix : 4; + unsigned char Iy : 4; +} TraceGapsGotoh; + +typedef struct { + int* MIx; + int* IyIx; + int* MIy; + int* IxIy; +} TraceGapsWatermanSmithBeyer; + +typedef struct { + PyObject_HEAD + Trace** M; + union { TraceGapsGotoh** gotoh; + TraceGapsWatermanSmithBeyer** waterman_smith_beyer; } gaps; + int nA; + int nB; + int iA; + int iB; + Mode mode; + Algorithm algorithm; + Py_ssize_t length; + unsigned char strand; +} PathGenerator; + +static PyObject* +PathGenerator_create_path(PathGenerator* self, int i, int j) { + PyObject* tuple; + PyObject* target_row; + PyObject* query_row; + PyObject* value; + int path; + int k, l; + int n = 1; + int direction = 0; + Trace** M = self->M; + const unsigned char strand = self->strand; + + k = i; + l = j; + while (1) { + path = M[k][l].path; + if (!path) break; + if (path != direction) { + n++; + direction = path; + } + switch (path) { + case HORIZONTAL: l++; break; + case VERTICAL: k++; break; + case DIAGONAL: k++; l++; break; + } + } + + direction = 0; + tuple = PyTuple_New(2); + if (!tuple) return NULL; + target_row = PyTuple_New(n); + query_row = PyTuple_New(n); + PyTuple_SET_ITEM(tuple, 0, target_row); + PyTuple_SET_ITEM(tuple, 1, query_row); + + if (target_row && query_row) { + k = 0; + switch (strand) { + case '+': + while (1) { + path = M[i][j].path; + if (path != direction) { + value = PyLong_FromLong(i); + if (!value) break; + PyTuple_SET_ITEM(target_row, k, value); + value = PyLong_FromLong(j); + if (!value) break; + PyTuple_SET_ITEM(query_row, k, value); + k++; + direction = path; + } + switch (path) { + case HORIZONTAL: j++; break; + case VERTICAL: i++; break; + case DIAGONAL: i++; j++; break; + default: return tuple; + } + } + break; + case '-': { + const int nB = self->nB; + while (1) { + path = M[i][j].path; + if (path != direction) { + value = PyLong_FromLong(i); + if (!value) break; + PyTuple_SET_ITEM(target_row, k, value); + value = PyLong_FromLong(nB-j); + if (!value) break; + PyTuple_SET_ITEM(query_row, k, value); + k++; + direction = path; + } + switch (path) { + case HORIZONTAL: j++; break; + case VERTICAL: i++; break; + case DIAGONAL: i++; j++; break; + default: return tuple; + } + } + break; + } + } + } + Py_DECREF(tuple); /* all references were stolen */ + return PyErr_NoMemory(); +} + +static Py_ssize_t +PathGenerator_needlemanwunsch_length(PathGenerator* self) +{ + int i; + int j; + int trace; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + Py_ssize_t term; + Py_ssize_t count = MEMORY_ERROR; + Py_ssize_t temp; + Py_ssize_t* counts; + counts = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!counts) goto exit; + counts[0] = 1; + for (j = 1; j <= nB; j++) { + trace = M[0][j].trace; + count = 0; + if (trace & HORIZONTAL) SAFE_ADD(counts[j-1], count); + counts[j] = count; + } + for (i = 1; i <= nA; i++) { + trace = M[i][0].trace; + count = 0; + if (trace & VERTICAL) SAFE_ADD(counts[0], count); + temp = counts[0]; + counts[0] = count; + for (j = 1; j <= nB; j++) { + trace = M[i][j].trace; + count = 0; + if (trace & HORIZONTAL) SAFE_ADD(counts[j-1], count); + if (trace & VERTICAL) SAFE_ADD(counts[j], count); + if (trace & DIAGONAL) SAFE_ADD(temp, count); + temp = counts[j]; + counts[j] = count; + } + } + PyMem_Free(counts); +exit: + return count; +} + +static Py_ssize_t +PathGenerator_smithwaterman_length(PathGenerator* self) +{ + int i; + int j; + int trace; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + Py_ssize_t term; + Py_ssize_t count = MEMORY_ERROR; + Py_ssize_t total = 0; + Py_ssize_t temp; + Py_ssize_t* counts; + counts = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!counts) goto exit; + counts[0] = 1; + for (j = 1; j <= nB; j++) counts[j] = 1; + for (i = 1; i <= nA; i++) { + temp = counts[0]; + counts[0] = 1; + for (j = 1; j <= nB; j++) { + trace = M[i][j].trace; + count = 0; + if (trace & DIAGONAL) SAFE_ADD(temp, count); + if (M[i][j].trace & ENDPOINT) SAFE_ADD(count, total); + if (trace & HORIZONTAL) SAFE_ADD(counts[j-1], count); + if (trace & VERTICAL) SAFE_ADD(counts[j], count); + temp = counts[j]; + if (count == 0 && (trace & STARTPOINT)) count = 1; + counts[j] = count; + } + } + count = total; + PyMem_Free(counts); +exit: + return count; +} + +static Py_ssize_t +PathGenerator_gotoh_global_length(PathGenerator* self) +{ + int i; + int j; + int trace; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + TraceGapsGotoh** gaps = self->gaps.gotoh; + Py_ssize_t count = MEMORY_ERROR; + Py_ssize_t term; + Py_ssize_t M_temp; + Py_ssize_t Ix_temp; + Py_ssize_t Iy_temp; + Py_ssize_t* M_counts = NULL; + Py_ssize_t* Ix_counts = NULL; + Py_ssize_t* Iy_counts = NULL; + M_counts = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!M_counts) goto exit; + Ix_counts = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!Ix_counts) goto exit; + Iy_counts = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!Iy_counts) goto exit; + M_counts[0] = 1; + Ix_counts[0] = 0; + Iy_counts[0] = 0; + for (j = 1; j <= nB; j++) { + M_counts[j] = 0; + Ix_counts[j] = 0; + Iy_counts[j] = 1; + } + for (i = 1; i <= nA; i++) { + M_temp = M_counts[0]; + M_counts[0] = 0; + Ix_temp = Ix_counts[0]; + Ix_counts[0] = 1; + Iy_temp = Iy_counts[0]; + Iy_counts[0] = 0; + for (j = 1; j <= nB; j++) { + count = 0; + trace = M[i][j].trace; + if (trace & M_MATRIX) SAFE_ADD(M_temp, count); + if (trace & Ix_MATRIX) SAFE_ADD(Ix_temp, count); + if (trace & Iy_MATRIX) SAFE_ADD(Iy_temp, count); + M_temp = M_counts[j]; + M_counts[j] = count; + count = 0; + trace = gaps[i][j].Ix; + if (trace & M_MATRIX) SAFE_ADD(M_temp, count); + if (trace & Ix_MATRIX) SAFE_ADD(Ix_counts[j], count); + if (trace & Iy_MATRIX) SAFE_ADD(Iy_counts[j], count); + Ix_temp = Ix_counts[j]; + Ix_counts[j] = count; + count = 0; + trace = gaps[i][j].Iy; + if (trace & M_MATRIX) SAFE_ADD(M_counts[j-1], count); + if (trace & Ix_MATRIX) SAFE_ADD(Ix_counts[j-1], count); + if (trace & Iy_MATRIX) SAFE_ADD(Iy_counts[j-1], count); + Iy_temp = Iy_counts[j]; + Iy_counts[j] = count; + } + } + count = 0; + if (M[nA][nB].trace) SAFE_ADD(M_counts[nB], count); + if (gaps[nA][nB].Ix) SAFE_ADD(Ix_counts[nB], count); + if (gaps[nA][nB].Iy) SAFE_ADD(Iy_counts[nB], count); +exit: + if (M_counts) PyMem_Free(M_counts); + if (Ix_counts) PyMem_Free(Ix_counts); + if (Iy_counts) PyMem_Free(Iy_counts); + return count; +} + +static Py_ssize_t +PathGenerator_gotoh_local_length(PathGenerator* self) +{ + int i; + int j; + int trace; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + TraceGapsGotoh** gaps = self->gaps.gotoh; + Py_ssize_t term; + Py_ssize_t count = MEMORY_ERROR; + Py_ssize_t total = 0; + Py_ssize_t M_temp; + Py_ssize_t Ix_temp; + Py_ssize_t Iy_temp; + Py_ssize_t* M_counts = NULL; + Py_ssize_t* Ix_counts = NULL; + Py_ssize_t* Iy_counts = NULL; + M_counts = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!M_counts) goto exit; + Ix_counts = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!Ix_counts) goto exit; + Iy_counts = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!Iy_counts) goto exit; + M_counts[0] = 1; + Ix_counts[0] = 0; + Iy_counts[0] = 0; + for (j = 1; j <= nB; j++) { + M_counts[j] = 1; + Ix_counts[j] = 0; + Iy_counts[j] = 0; + } + for (i = 1; i <= nA; i++) { + M_temp = M_counts[0]; + M_counts[0] = 1; + Ix_temp = Ix_counts[0]; + Ix_counts[0] = 0; + Iy_temp = Iy_counts[0]; + Iy_counts[0] = 0; + for (j = 1; j <= nB; j++) { + count = 0; + trace = M[i][j].trace; + if (trace & M_MATRIX) SAFE_ADD(M_temp, count); + if (trace & Ix_MATRIX) SAFE_ADD(Ix_temp, count); + if (trace & Iy_MATRIX) SAFE_ADD(Iy_temp, count); + if (count == 0 && (trace & STARTPOINT)) count = 1; + M_temp = M_counts[j]; + M_counts[j] = count; + if (M[i][j].trace & ENDPOINT) SAFE_ADD(count, total); + count = 0; + trace = gaps[i][j].Ix; + if (trace & M_MATRIX) SAFE_ADD(M_temp, count); + if (trace & Ix_MATRIX) SAFE_ADD(Ix_counts[j], count); + if (trace & Iy_MATRIX) SAFE_ADD(Iy_counts[j], count); + Ix_temp = Ix_counts[j]; + Ix_counts[j] = count; + count = 0; + trace = gaps[i][j].Iy; + if (trace & M_MATRIX) SAFE_ADD(M_counts[j-1], count); + if (trace & Ix_MATRIX) SAFE_ADD(Ix_counts[j-1], count); + if (trace & Iy_MATRIX) SAFE_ADD(Iy_counts[j-1], count); + Iy_temp = Iy_counts[j]; + Iy_counts[j] = count; + } + } + count = total; +exit: + if (M_counts) PyMem_Free(M_counts); + if (Ix_counts) PyMem_Free(Ix_counts); + if (Iy_counts) PyMem_Free(Iy_counts); + return count; +} + +static Py_ssize_t +PathGenerator_waterman_smith_beyer_global_length(PathGenerator* self) +{ + int i; + int j; + int trace; + int* p; + int gap; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + TraceGapsWatermanSmithBeyer** gaps = self->gaps.waterman_smith_beyer; + Py_ssize_t count = MEMORY_ERROR; + Py_ssize_t term; + Py_ssize_t** M_count = NULL; + Py_ssize_t** Ix_count = NULL; + Py_ssize_t** Iy_count = NULL; + M_count = PyMem_Malloc((nA+1)*sizeof(Py_ssize_t*)); + if (!M_count) goto exit; + Ix_count = PyMem_Malloc((nA+1)*sizeof(Py_ssize_t*)); + if (!Ix_count) goto exit; + Iy_count = PyMem_Malloc((nA+1)*sizeof(Py_ssize_t*)); + if (!Iy_count) goto exit; + for (i = 0; i <= nA; i++) { + M_count[i] = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!M_count[i]) goto exit; + Ix_count[i] = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!Ix_count[i]) goto exit; + Iy_count[i] = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!Iy_count[i]) goto exit; + } + for (i = 0; i <= nA; i++) { + for (j = 0; j <= nB; j++) { + count = 0; + trace = M[i][j].trace; + if (trace & M_MATRIX) SAFE_ADD(M_count[i-1][j-1], count); + if (trace & Ix_MATRIX) SAFE_ADD(Ix_count[i-1][j-1], count); + if (trace & Iy_MATRIX) SAFE_ADD(Iy_count[i-1][j-1], count); + if (count == 0) count = 1; /* happens at M[0][0] only */ + M_count[i][j] = count; + count = 0; + p = gaps[i][j].MIx; + if (p) { + while (1) { + gap = *p; + if (!gap) break; + SAFE_ADD(M_count[i-gap][j], count); + p++; + } + } + p = gaps[i][j].IyIx; + if (p) { + while (1) { + gap = *p; + if (!gap) break; + SAFE_ADD(Iy_count[i-gap][j], count); + p++; + } + } + Ix_count[i][j] = count; + count = 0; + p = gaps[i][j].MIy; + if (p) { + while (1) { + gap = *p; + if (!gap) break; + SAFE_ADD(M_count[i][j-gap], count); + p++; + } + } + p = gaps[i][j].IxIy; + if (p) { + while (1) { + gap = *p; + if (!gap) break; + SAFE_ADD(Ix_count[i][j-gap], count); + p++; + } + } + Iy_count[i][j] = count; + } + } + count = 0; + if (M[nA][nB].trace) + SAFE_ADD(M_count[nA][nB], count); + if (gaps[nA][nB].MIx[0] || gaps[nA][nB].IyIx[0]) + SAFE_ADD(Ix_count[nA][nB], count); + if (gaps[nA][nB].MIy[0] || gaps[nA][nB].IxIy[0]) + SAFE_ADD(Iy_count[nA][nB], count); +exit: + if (M_count) { + if (Ix_count) { + if (Iy_count) { + for (i = 0; i <= nA; i++) { + if (!M_count[i]) break; + PyMem_Free(M_count[i]); + if (!Ix_count[i]) break; + PyMem_Free(Ix_count[i]); + if (!Iy_count[i]) break; + PyMem_Free(Iy_count[i]); + } + PyMem_Free(Iy_count); + } + PyMem_Free(Ix_count); + } + PyMem_Free(M_count); + } + return count; +} + +static Py_ssize_t +PathGenerator_waterman_smith_beyer_local_length(PathGenerator* self) +{ + int i; + int j; + int trace; + int* p; + int gap; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + TraceGapsWatermanSmithBeyer** gaps = self->gaps.waterman_smith_beyer; + Py_ssize_t term; + Py_ssize_t count = MEMORY_ERROR; + Py_ssize_t total = 0; + Py_ssize_t** M_count = NULL; + Py_ssize_t** Ix_count = NULL; + Py_ssize_t** Iy_count = NULL; + M_count = PyMem_Malloc((nA+1)*sizeof(Py_ssize_t*)); + if (!M_count) goto exit; + Ix_count = PyMem_Malloc((nA+1)*sizeof(Py_ssize_t*)); + if (!Ix_count) goto exit; + Iy_count = PyMem_Malloc((nA+1)*sizeof(Py_ssize_t*)); + if (!Iy_count) goto exit; + for (i = 0; i <= nA; i++) { + M_count[i] = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!M_count[i]) goto exit; + Ix_count[i] = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!Ix_count[i]) goto exit; + Iy_count[i] = PyMem_Malloc((nB+1)*sizeof(Py_ssize_t)); + if (!Iy_count[i]) goto exit; + } + for (i = 0; i <= nA; i++) { + for (j = 0; j <= nB; j++) { + count = 0; + trace = M[i][j].trace; + if (trace & M_MATRIX) SAFE_ADD(M_count[i-1][j-1], count); + if (trace & Ix_MATRIX) SAFE_ADD(Ix_count[i-1][j-1], count); + if (trace & Iy_MATRIX) SAFE_ADD(Iy_count[i-1][j-1], count); + if (count == 0 && (trace & STARTPOINT)) count = 1; + M_count[i][j] = count; + if (M[i][j].trace & ENDPOINT) SAFE_ADD(count, total); + count = 0; + p = gaps[i][j].MIx; + if (p) { + while (1) { + gap = *p; + if (!gap) break; + SAFE_ADD(M_count[i-gap][j], count); + p++; + } + } + p = gaps[i][j].IyIx; + if (p) { + while (1) { + gap = *p; + if (!gap) break; + SAFE_ADD(Iy_count[i-gap][j], count); + p++; + } + } + Ix_count[i][j] = count; + count = 0; + p = gaps[i][j].MIy; + if (p) { + while (1) { + gap = *p; + if (!gap) break; + SAFE_ADD(M_count[i][j-gap], count); + p++; + } + } + p = gaps[i][j].IxIy; + if (p) { + while (1) { + gap = *p; + if (!gap) break; + SAFE_ADD(Ix_count[i][j-gap], count); + p++; + } + } + Iy_count[i][j] = count; + } + } + count = total; +exit: + if (M_count) { + if (Ix_count) { + if (Iy_count) { + for (i = 0; i <= nA; i++) { + if (!M_count[i]) break; + PyMem_Free(M_count[i]); + if (!Ix_count[i]) break; + PyMem_Free(Ix_count[i]); + if (!Iy_count[i]) break; + PyMem_Free(Iy_count[i]); + } + PyMem_Free(Iy_count); + } + PyMem_Free(Ix_count); + } + PyMem_Free(M_count); + } + return count; +} + + +static Py_ssize_t +PathGenerator_fogsaa_length(PathGenerator* self) +{ + return 1; +} + +static Py_ssize_t PathGenerator_length(PathGenerator* self) { + Py_ssize_t length = self->length; + if (length == 0) { + switch (self->algorithm) { + case NeedlemanWunschSmithWaterman: + switch (self->mode) { + case Global: + length = PathGenerator_needlemanwunsch_length(self); + break; + case Local: + length = PathGenerator_smithwaterman_length(self); + break; + default: + /* should not happen, but some compilers complain that + * that length can be used uninitialized. + */ + ERR_UNEXPECTED_MODE + return OTHER_ERROR; + } + break; + case Gotoh: + switch (self->mode) { + case Global: + length = PathGenerator_gotoh_global_length(self); + break; + case Local: + length = PathGenerator_gotoh_local_length(self); + break; + default: + /* should not happen, but some compilers complain that + * that length can be used uninitialized. + */ + ERR_UNEXPECTED_MODE + return OTHER_ERROR; + } + break; + case WatermanSmithBeyer: + switch (self->mode) { + case Global: + length = PathGenerator_waterman_smith_beyer_global_length(self); + break; + case Local: + length = PathGenerator_waterman_smith_beyer_local_length(self); + break; + default: + /* should not happen, but some compilers complain that + * that length can be used uninitialized. + */ + ERR_UNEXPECTED_MODE + return OTHER_ERROR; + } + break; + case FOGSAA: + if (self->mode != FOGSAA_Mode) { + ERR_UNEXPECTED_MODE + return OTHER_ERROR; + } + length = PathGenerator_fogsaa_length(self); + break; + case Unknown: + default: + ERR_UNEXPECTED_ALGORITHM + return OTHER_ERROR; + } + self->length = length; + } + switch (length) { + case OVERFLOW_ERROR: + PyErr_Format(PyExc_OverflowError, + "number of optimal alignments is larger than %zd", + PY_SSIZE_T_MAX); + break; + case MEMORY_ERROR: + PyErr_SetNone(PyExc_MemoryError); + break; + case OTHER_ERROR: + default: + break; + } + return length; +} + +static void +PathGenerator_dealloc(PathGenerator* self) +{ + int i; + const int nA = self->nA; + const Algorithm algorithm = self->algorithm; + Trace** M = self->M; + if (M) { + for (i = 0; i <= nA; i++) { + if (!M[i]) break; + PyMem_Free(M[i]); + } + PyMem_Free(M); + } + switch (algorithm) { + case NeedlemanWunschSmithWaterman: + case FOGSAA: + break; + case Gotoh: { + TraceGapsGotoh** gaps = self->gaps.gotoh; + if (gaps) { + for (i = 0; i <= nA; i++) { + if (!gaps[i]) break; + PyMem_Free(gaps[i]); + } + PyMem_Free(gaps); + } + break; + } + case WatermanSmithBeyer: { + TraceGapsWatermanSmithBeyer** gaps = self->gaps.waterman_smith_beyer; + if (gaps) { + int j; + const int nB = self->nB; + int* trace; + for (i = 0; i <= nA; i++) { + if (!gaps[i]) break; + for (j = 0; j <= nB; j++) { + trace = gaps[i][j].MIx; + if (trace) PyMem_Free(trace); + trace = gaps[i][j].IyIx; + if (trace) PyMem_Free(trace); + trace = gaps[i][j].MIy; + if (trace) PyMem_Free(trace); + trace = gaps[i][j].IxIy; + if (trace) PyMem_Free(trace); + } + PyMem_Free(gaps[i]); + } + PyMem_Free(gaps); + } + break; + } + case Unknown: + default: + PyErr_WriteUnraisable((PyObject*)self); + break; + } + Py_TYPE(self)->tp_free((PyObject*)self); +} + +static PyObject* PathGenerator_next_needlemanwunsch(PathGenerator* self) +{ + int i = 0; + int j = 0; + int path; + int trace = 0; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + + path = M[i][j].path; + if (path == DONE) return NULL; + if (path == 0) { + /* Generate the first path. */ + i = nA; + j = nB; + } + else { + /* We already have a path. Prune the path to see if there are + * any alternative paths. */ + while (1) { + if (path == HORIZONTAL) { + trace = M[i][++j].trace; + if (trace & VERTICAL) { + M[--i][j].path = VERTICAL; + break; + } + if (trace & DIAGONAL) { + M[--i][--j].path = DIAGONAL; + break; + } + } + else if (path == VERTICAL) { + trace = M[++i][j].trace; + if (trace & DIAGONAL) { + M[--i][--j].path = DIAGONAL; + break; + } + } + else /* DIAGONAL */ { + i++; + j++; + } + path = M[i][j].path; + if (!path) { + /* we reached the end of the alignment without finding + * an alternative path */ + M[0][0].path = DONE; + return NULL; + } + } + } + /* Follow the traceback until we reach the origin. */ + while (1) { + trace = M[i][j].trace; + if (trace & HORIZONTAL) M[i][--j].path = HORIZONTAL; + else if (trace & VERTICAL) M[--i][j].path = VERTICAL; + else if (trace & DIAGONAL) M[--i][--j].path = DIAGONAL; + else break; + } + return PathGenerator_create_path(self, 0, 0); +} + +static PyObject* PathGenerator_next_smithwaterman(PathGenerator* self) +{ + int trace = 0; + int i = self->iA; + int j = self->iB; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + int path = M[0][0].path; + + if (path == DONE || path == NONE) return NULL; + + path = M[i][j].path; + if (path) { + /* We already have a path. Prune the path to see if there are + * any alternative paths. */ + while (1) { + if (path == HORIZONTAL) { + trace = M[i][++j].trace; + if (trace & VERTICAL) { + M[--i][j].path = VERTICAL; + break; + } + else if (trace & DIAGONAL) { + M[--i][--j].path = DIAGONAL; + break; + } + } + else if (path == VERTICAL) { + trace = M[++i][j].trace; + if (trace & DIAGONAL) { + M[--i][--j].path = DIAGONAL; + break; + } + } + else /* DIAGONAL */ { + i++; + j++; + } + path = M[i][j].path; + if (!path) break; + } + } + + if (path) { + trace = M[i][j].trace; + } else { + /* Find a suitable end point for a path. + * Only allow end points ending at the M matrix. */ + while (1) { + if (j < nB) j++; + else if (i < nA) { + i++; + j = 0; + } + else { + /* we reached the end of the sequences without finding + * an alternative path */ + M[0][0].path = DONE; + return NULL; + } + trace = M[i][j].trace; + if (trace & ENDPOINT) { + trace &= DIAGONAL; /* exclude paths ending in a gap */ + break; + } + } + M[i][j].path = 0; + } + + /* Follow the traceback until we reach the origin. */ + while (1) { + if (trace & HORIZONTAL) M[i][--j].path = HORIZONTAL; + else if (trace & VERTICAL) M[--i][j].path = VERTICAL; + else if (trace & DIAGONAL) M[--i][--j].path = DIAGONAL; + else if (trace & STARTPOINT) { + self->iA = i; + self->iB = j; + return PathGenerator_create_path(self, i, j); + } + else { + PyErr_SetString(PyExc_RuntimeError, + "Unexpected trace in PathGenerator_next_smithwaterman"); + return NULL; + } + trace = M[i][j].trace; + } +} + +static PyObject* PathGenerator_next_gotoh_global(PathGenerator* self) +{ + int i = 0; + int j = 0; + int m; + int path; + int trace = 0; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + TraceGapsGotoh** gaps = self->gaps.gotoh; + + m = M_MATRIX; + path = M[i][j].path; + if (path == DONE) return NULL; + if (path == 0) { + i = nA; + j = nB; + } + else { + /* We already have a path. Prune the path to see if there are + * any alternative paths. */ + while (1) { + path = M[i][j].path; + if (path == 0) { + switch (m) { + case M_MATRIX: m = Ix_MATRIX; break; + case Ix_MATRIX: m = Iy_MATRIX; break; + case Iy_MATRIX: m = 0; break; + } + break; + } + switch (path) { + case HORIZONTAL: trace = gaps[i][++j].Iy; break; + case VERTICAL: trace = gaps[++i][j].Ix; break; + case DIAGONAL: trace = M[++i][++j].trace; break; + } + switch (m) { + case M_MATRIX: + if (trace & Ix_MATRIX) { + m = Ix_MATRIX; + break; + } + case Ix_MATRIX: + if (trace & Iy_MATRIX) { + m = Iy_MATRIX; + break; + } + case Iy_MATRIX: + default: + switch (path) { + case HORIZONTAL: m = Iy_MATRIX; break; + case VERTICAL: m = Ix_MATRIX; break; + case DIAGONAL: m = M_MATRIX; break; + } + continue; + } + switch (path) { + case HORIZONTAL: j--; break; + case VERTICAL: i--; break; + case DIAGONAL: i--; j--; break; + } + M[i][j].path = path; + break; + } + } + + if (path == 0) { + /* Generate a new path. */ + switch (m) { + case M_MATRIX: + if (M[nA][nB].trace) { + /* m = M_MATRIX; */ + break; + } + case Ix_MATRIX: + if (gaps[nA][nB].Ix) { + m = Ix_MATRIX; + break; + } + case Iy_MATRIX: + if (gaps[nA][nB].Iy) { + m = Iy_MATRIX; + break; + } + default: + /* exhausted this generator */ + M[0][0].path = DONE; + return NULL; + } + } + + switch (m) { + case M_MATRIX: + trace = M[i][j].trace; + path = DIAGONAL; + i--; j--; + break; + case Ix_MATRIX: + trace = gaps[i][j].Ix; + path = VERTICAL; + i--; + break; + case Iy_MATRIX: + trace = gaps[i][j].Iy; + path = HORIZONTAL; + j--; + break; + } + + while (1) { + if (trace & M_MATRIX) { + trace = M[i][j].trace; + M[i][j].path = path; + path = DIAGONAL; + i--; j--; + } + else if (trace & Ix_MATRIX) { + M[i][j].path = path; + trace = gaps[i][j].Ix; + path = VERTICAL; + i--; + } + else if (trace & Iy_MATRIX) { + M[i][j].path = path; + trace = gaps[i][j].Iy; + path = HORIZONTAL; + j--; + } + else break; + } + return PathGenerator_create_path(self, 0, 0); +} + +static PyObject* PathGenerator_next_gotoh_local(PathGenerator* self) +{ + int trace = 0; + int i; + int j; + int m = M_MATRIX; + int iA = self->iA; + int iB = self->iB; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + TraceGapsGotoh** gaps = self->gaps.gotoh; + int path = M[0][0].path; + + if (path == DONE) return NULL; + + path = M[iA][iB].path; + + if (path) { + i = iA; + j = iB; + while (1) { + /* We already have a path. Prune the path to see if there are + * any alternative paths. */ + path = M[i][j].path; + if (path == 0) { + m = M_MATRIX; + iA = i; + iB = j; + break; + } + switch (path) { + case HORIZONTAL: trace = gaps[i][++j].Iy; break; + case VERTICAL: trace = gaps[++i][j].Ix; break; + case DIAGONAL: trace = M[++i][++j].trace; break; + } + switch (m) { + case M_MATRIX: + if (trace & Ix_MATRIX) { + m = Ix_MATRIX; + break; + } + case Ix_MATRIX: + if (trace & Iy_MATRIX) { + m = Iy_MATRIX; + break; + } + case Iy_MATRIX: + default: + switch (path) { + case HORIZONTAL: m = Iy_MATRIX; break; + case VERTICAL: m = Ix_MATRIX; break; + case DIAGONAL: m = M_MATRIX; break; + } + continue; + } + switch (path) { + case HORIZONTAL: j--; break; + case VERTICAL: i--; break; + case DIAGONAL: i--; j--; break; + } + M[i][j].path = path; + break; + } + } + + if (path == 0) { + /* Find the end point for a new path. */ + while (1) { + if (iB < nB) iB++; + else if (iA < nA) { + iA++; + iB = 0; + } + else { + /* we reached the end of the alignment without finding + * an alternative path */ + M[0][0].path = DONE; + return NULL; + } + if (M[iA][iB].trace & ENDPOINT) { + M[iA][iB].path = 0; + break; + } + } + m = M_MATRIX; + i = iA; + j = iB; + } + + while (1) { + switch (m) { + case M_MATRIX: trace = M[i][j].trace; break; + case Ix_MATRIX: trace = gaps[i][j].Ix; break; + case Iy_MATRIX: trace = gaps[i][j].Iy; break; + } + if (trace == STARTPOINT) { + self->iA = i; + self->iB = j; + return PathGenerator_create_path(self, i, j); + } + switch (m) { + case M_MATRIX: + path = DIAGONAL; + i--; + j--; + break; + case Ix_MATRIX: + path = VERTICAL; + i--; + break; + case Iy_MATRIX: + path = HORIZONTAL; + j--; + break; + } + if (trace & M_MATRIX) m = M_MATRIX; + else if (trace & Ix_MATRIX) m = Ix_MATRIX; + else if (trace & Iy_MATRIX) m = Iy_MATRIX; + else { + PyErr_SetString(PyExc_RuntimeError, + "Unexpected trace in PathGenerator_next_gotoh_local"); + return NULL; + } + M[i][j].path = path; + } + return NULL; +} + +static PyObject* +PathGenerator_next_waterman_smith_beyer_global(PathGenerator* self) +{ + int i = 0, j = 0; + int iA, iB; + int trace; + int* gapM; + int* gapXY; + + int m = M_MATRIX; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + TraceGapsWatermanSmithBeyer** gaps = self->gaps.waterman_smith_beyer; + + int gap; + int path = M[0][0].path; + + if (path == DONE) return NULL; + + if (path) { + /* We already have a path. Prune the path to see if there are + * any alternative paths. */ + while (1) { + if (!path) { + m <<= 1; + break; + } + switch (path) { + case HORIZONTAL: + iA = i; + iB = j; + while (M[i][iB].path == HORIZONTAL) iB++; + break; + case VERTICAL: + iA = i; + while (M[iA][j].path == VERTICAL) iA++; + iB = j; + break; + case DIAGONAL: + iA = i + 1; + iB = j + 1; + break; + default: + PyErr_SetString(PyExc_RuntimeError, + "Unexpected path in PathGenerator_next_waterman_smith_beyer_global"); + return NULL; + } + if (i == iA) { /* HORIZONTAL */ + gapM = gaps[iA][iB].MIy; + gapXY = gaps[iA][iB].IxIy; + if (m == M_MATRIX) { + gap = iB - j; + while (*gapM != gap) gapM++; + gapM++; + gap = *gapM; + if (gap) { + j = iB - gap; + while (j < iB) M[i][--iB].path = HORIZONTAL; + break; + } + } else if (m == Ix_MATRIX) { + gap = iB - j; + while (*gapXY != gap) gapXY++; + gapXY++; + } + gap = *gapXY; + if (gap) { + m = Ix_MATRIX; + j = iB - gap; + while (j < iB) M[i][--iB].path = HORIZONTAL; + break; + } + /* no alternative found; continue pruning */ + m = Iy_MATRIX; + j = iB; + } + else if (j == iB) { /* VERTICAL */ + gapM = gaps[iA][iB].MIx; + gapXY = gaps[iA][iB].IyIx; + if (m == M_MATRIX) { + gap = iA - i; + while (*gapM != gap) gapM++; + gapM++; + gap = *gapM; + if (gap) { + i = iA - gap; + while (i < iA) M[--iA][j].path = VERTICAL; + break; + } + } else if (m == Iy_MATRIX) { + gap = iA - i; + while (*gapXY != gap) gapXY++; + gapXY++; + } + gap = *gapXY; + if (gap) { + m = Iy_MATRIX; + i = iA - gap; + while (i < iA) M[--iA][j].path = VERTICAL; + break; + } + /* no alternative found; continue pruning */ + m = Ix_MATRIX; + i = iA; + } + else { /* DIAGONAL */ + i = iA - 1; + j = iB - 1; + trace = M[iA][iB].trace; + switch (m) { + case M_MATRIX: + if (trace & Ix_MATRIX) { + m = Ix_MATRIX; + M[i][j].path = DIAGONAL; + break; + } + case Ix_MATRIX: + if (trace & Iy_MATRIX) { + m = Iy_MATRIX; + M[i][j].path = DIAGONAL; + break; + } + case Iy_MATRIX: + default: + /* no alternative found; continue pruning */ + m = M_MATRIX; + i = iA; + j = iB; + path = M[i][j].path; + continue; + } + /* alternative found; build path until starting point */ + break; + } + path = M[i][j].path; + } + } + + if (!path) { + /* Find a suitable end point for a path. */ + switch (m) { + case M_MATRIX: + if (M[nA][nB].trace) { + /* m = M_MATRIX; */ + break; + } + case Ix_MATRIX: + if (gaps[nA][nB].MIx[0] || gaps[nA][nB].IyIx[0]) { + m = Ix_MATRIX; + break; + } + case Iy_MATRIX: + if (gaps[nA][nB].MIy[0] || gaps[nA][nB].IxIy[0]) { + m = Iy_MATRIX; + break; + } + default: + M[0][0].path = DONE; + return NULL; + } + i = nA; + j = nB; + } + + /* Follow the traceback until we reach the origin. */ + while (1) { + switch (m) { + case M_MATRIX: + trace = M[i][j].trace; + if (trace & M_MATRIX) m = M_MATRIX; + else if (trace & Ix_MATRIX) m = Ix_MATRIX; + else if (trace & Iy_MATRIX) m = Iy_MATRIX; + else return PathGenerator_create_path(self, i, j); + i--; + j--; + M[i][j].path = DIAGONAL; + break; + case Ix_MATRIX: + gap = gaps[i][j].MIx[0]; + if (gap) m = M_MATRIX; + else { + gap = gaps[i][j].IyIx[0]; + m = Iy_MATRIX; + } + iA = i - gap; + while (iA < i) M[--i][j].path = VERTICAL; + M[i][j].path = VERTICAL; + break; + case Iy_MATRIX: + gap = gaps[i][j].MIy[0]; + if (gap) m = M_MATRIX; + else { + gap = gaps[i][j].IxIy[0]; + m = Ix_MATRIX; + } + iB = j - gap; + while (iB < j) M[i][--j].path = HORIZONTAL; + M[i][j].path = HORIZONTAL; + break; + } + } +} + +static PyObject* +PathGenerator_next_waterman_smith_beyer_local(PathGenerator* self) +{ + int i, j, m; + int trace = 0; + int* gapM; + int* gapXY; + + int iA = self->iA; + int iB = self->iB; + const int nA = self->nA; + const int nB = self->nB; + Trace** M = self->M; + TraceGapsWatermanSmithBeyer** gaps = self->gaps.waterman_smith_beyer; + + int gap; + int path = M[0][0].path; + + if (path == DONE) return NULL; + m = 0; + path = M[iA][iB].path; + if (path) { + /* We already have a path. Prune the path to see if there are + * any alternative paths. */ + m = M_MATRIX; + i = iA; + j = iB; + while (1) { + path = M[i][j].path; + switch (path) { + case HORIZONTAL: + iA = i; + iB = j; + while (M[i][iB].path == HORIZONTAL) iB++; + break; + case VERTICAL: + iA = i; + iB = j; + while (M[iA][j].path == VERTICAL) iA++; + break; + case DIAGONAL: + iA = i + 1; + iB = j + 1; + break; + default: + iA = -1; + break; + } + if (iA < 0) { + m = 0; + iA = i; + iB = j; + break; + } + if (i == iA) { /* HORIZONTAL */ + gapM = gaps[iA][iB].MIy; + gapXY = gaps[iA][iB].IxIy; + if (m == M_MATRIX) { + gap = iB - j; + while (*gapM != gap) gapM++; + gapM++; + gap = *gapM; + if (gap) { + j = iB - gap; + while (j < iB) M[i][--iB].path = HORIZONTAL; + break; + } + } else if (m == Ix_MATRIX) { + gap = iB - j; + while (*gapXY != gap) gapXY++; + gapXY++; + } + gap = *gapXY; + if (gap) { + m = Ix_MATRIX; + j = iB - gap; + M[i][j].path = HORIZONTAL; + while (iB > j) M[i][--iB].path = HORIZONTAL; + break; + } + /* no alternative found; continue pruning */ + m = Iy_MATRIX; + j = iB; + } + else if (j == iB) { /* VERTICAL */ + gapM = gaps[iA][iB].MIx; + gapXY = gaps[iA][iB].IyIx; + if (m == M_MATRIX) { + gap = iA - i; + while (*gapM != gap) gapM++; + gapM++; + gap = *gapM; + if (gap) { + i = iA - gap; + while (i < iA) M[--iA][j].path = VERTICAL; + break; + } + } else if (m == Iy_MATRIX) { + gap = iA - i; + while (*gapXY != gap) gapXY++; + gapXY++; + } + gap = *gapXY; + if (gap) { + m = Iy_MATRIX; + i = iA - gap; + M[i][j].path = VERTICAL; + while (iA > i) M[--iA][j].path = VERTICAL; + break; + } + /* no alternative found; continue pruning */ + m = Ix_MATRIX; + i = iA; + } + else { /* DIAGONAL */ + i = iA - 1; + j = iB - 1; + trace = M[iA][iB].trace; + switch (m) { + case M_MATRIX: + if (trace & Ix_MATRIX) { + m = Ix_MATRIX; + M[i][j].path = DIAGONAL; + break; + } + case Ix_MATRIX: + if (trace & Iy_MATRIX) { + m = Iy_MATRIX; + M[i][j].path = DIAGONAL; + break; + } + case Iy_MATRIX: + default: + /* no alternative found; continue pruning */ + m = M_MATRIX; + i = iA; + j = iB; + continue; + } + /* alternative found; build path until starting point */ + break; + } + } + } + + if (m == 0) { + /* We are at [nA][nB]. Find a suitable end point for a path. */ + while (1) { + if (iB < nB) iB++; + else if (iA < nA) { + iA++; + iB = 0; + } + else { + /* exhausted this generator */ + M[0][0].path = DONE; + return NULL; + } + if (M[iA][iB].trace & ENDPOINT) break; + } + M[iA][iB].path = 0; + m = M_MATRIX; + i = iA; + j = iB; + } + + /* Follow the traceback until we reach the origin. */ + while (1) { + switch (m) { + case Ix_MATRIX: + gapM = gaps[i][j].MIx; + gapXY = gaps[i][j].IyIx; + iB = j; + gap = *gapM; + if (gap) m = M_MATRIX; + else { + gap = *gapXY; + m = Iy_MATRIX; + } + iA = i - gap; + while (i > iA) M[--i][iB].path = VERTICAL; + break; + case Iy_MATRIX: + gapM = gaps[i][j].MIy; + gapXY = gaps[i][j].IxIy; + iA = i; + gap = *gapM; + if (gap) m = M_MATRIX; + else { + gap = *gapXY; + m = Ix_MATRIX; + } + iB = j - gap; + while (j > iB) M[iA][--j].path = HORIZONTAL; + break; + case M_MATRIX: + iA = i-1; + iB = j-1; + trace = M[i][j].trace; + if (trace & M_MATRIX) m = M_MATRIX; + else if (trace & Ix_MATRIX) m = Ix_MATRIX; + else if (trace & Iy_MATRIX) m = Iy_MATRIX; + else if (trace == STARTPOINT) { + self->iA = i; + self->iB = j; + return PathGenerator_create_path(self, i, j); + } + else { + PyErr_SetString(PyExc_RuntimeError, + "Unexpected trace in PathGenerator_next_waterman_smith_beyer_local"); + return NULL; + } + M[iA][iB].path = DIAGONAL; + break; + } + i = iA; + j = iB; + } +} + +static PyObject* +PathGenerator_next_FOGSAA(PathGenerator* self) +{ + /* No need to create path because FOGSAA only finds one optimal alignment + * the .path fields should be populated by FOGSAA_EXIT_ALIGN. To indicate + * we've exhausted the iterator, just set self->M[0][0].path to DONE */ + Trace *last = &self->M[self->nA][self->nB]; + PyObject *path; + + if (last->path == DONE) { + return NULL; + } + + path = PathGenerator_create_path(self, 0, 0); + last->path = DONE; + return path; +} + +static PyObject * +PathGenerator_next(PathGenerator* self) +{ + const Mode mode = self->mode; + const Algorithm algorithm = self->algorithm; + switch (algorithm) { + case NeedlemanWunschSmithWaterman: + switch (mode) { + case Global: + return PathGenerator_next_needlemanwunsch(self); + case Local: + return PathGenerator_next_smithwaterman(self); + default: + ERR_UNEXPECTED_MODE + return NULL; + } + case Gotoh: + switch (mode) { + case Global: + return PathGenerator_next_gotoh_global(self); + case Local: + return PathGenerator_next_gotoh_local(self); + default: + ERR_UNEXPECTED_MODE + return NULL; + } + case WatermanSmithBeyer: + switch (mode) { + case Global: + return PathGenerator_next_waterman_smith_beyer_global(self); + case Local: + return PathGenerator_next_waterman_smith_beyer_local(self); + default: + ERR_UNEXPECTED_MODE + return NULL; + } + case FOGSAA: + return PathGenerator_next_FOGSAA(self); + break; + case Unknown: + default: + ERR_UNEXPECTED_ALGORITHM + return NULL; + } +} + +static const char PathGenerator_reset__doc__[] = "reset the iterator"; + +static PyObject* +PathGenerator_reset(PathGenerator* self) +{ + switch (self->mode) { + case Local: + self->iA = 0; + self->iB = 0; + case Global: { + Trace** M = self->M; + switch (self->algorithm) { + case NeedlemanWunschSmithWaterman: + case Gotoh: { + if (M[0][0].path != NONE) M[0][0].path = 0; + break; + } + case WatermanSmithBeyer: { + M[0][0].path = 0; + break; + } + case Unknown: + default: + break; + } + break; + } + case FOGSAA_Mode: + self->M[self->nA][self->nB].path = 0; + break; + } + Py_INCREF(Py_None); + return Py_None; +} + +static PyMethodDef PathGenerator_methods[] = { + {"reset", + (PyCFunction)PathGenerator_reset, + METH_NOARGS, + PathGenerator_reset__doc__ + }, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +static PySequenceMethods PathGenerator_as_sequence = { + .sq_length = (lenfunc)PathGenerator_length, +}; + +static PyTypeObject PathGenerator_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "Path generator", + .tp_basicsize = sizeof(PathGenerator), + .tp_dealloc = (destructor)PathGenerator_dealloc, + .tp_as_sequence = &PathGenerator_as_sequence, + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_iter = PyObject_SelfIter, + .tp_iternext = (iternextfunc)PathGenerator_next, + .tp_methods = PathGenerator_methods, +}; + +static Algorithm _get_algorithm(Aligner* self) +{ + Algorithm algorithm = self->algorithm; + if (algorithm == Unknown) { + const double open_internal_insertion_score = self->open_internal_insertion_score; + const double open_internal_deletion_score = self->open_internal_deletion_score; + const double extend_internal_insertion_score = self->extend_internal_insertion_score; + const double extend_internal_deletion_score = self->extend_internal_deletion_score; + const double open_left_insertion_score = self->open_left_insertion_score; + const double extend_left_insertion_score = self->extend_left_insertion_score; + const double open_left_deletion_score = self->open_left_deletion_score; + const double open_right_insertion_score = self->open_right_insertion_score; + const double open_right_deletion_score = self->open_right_deletion_score; + const double extend_right_insertion_score = self->extend_right_insertion_score; + const double extend_left_deletion_score = self->extend_left_deletion_score; + const double extend_right_deletion_score = self->extend_right_deletion_score; + if (self->mode == FOGSAA_Mode) + algorithm = FOGSAA; + else if (self->insertion_score_function || self->deletion_score_function) + algorithm = WatermanSmithBeyer; + else if (open_internal_insertion_score == extend_internal_insertion_score + && open_internal_deletion_score == extend_internal_deletion_score + && open_left_insertion_score == extend_left_insertion_score + && open_right_insertion_score == extend_right_insertion_score + && open_left_deletion_score == extend_left_deletion_score + && open_right_deletion_score == extend_right_deletion_score) + algorithm = NeedlemanWunschSmithWaterman; + else + algorithm = Gotoh; + self->algorithm = algorithm; + } + return algorithm; +} + +static int +Aligner_init(Aligner *self, PyObject *args, PyObject *kwds) +{ + self->mode = Global; + self->match = 1.0; + self->mismatch = 0.0; + self->epsilon = 1.e-6; + self->open_internal_insertion_score = -1.0; + self->extend_internal_insertion_score = -1.0; + self->open_internal_deletion_score = -1.0; + self->extend_internal_deletion_score = -1.0; + self->open_left_insertion_score = -1.0; + self->extend_left_insertion_score = -1.0; + self->open_right_insertion_score = -1.0; + self->extend_right_insertion_score = -1.0; + self->open_left_deletion_score = -1.0; + self->extend_left_deletion_score = -1.0; + self->open_right_deletion_score = -1.0; + self->extend_right_deletion_score = -1.0; + self->open_internal_insertion_score_set = false; + self->extend_internal_insertion_score_set = false; + self->open_left_insertion_score_set = false; + self->extend_left_insertion_score_set = false; + self->open_right_insertion_score_set = false; + self->extend_right_insertion_score_set = false; + self->open_internal_deletion_score_set = false; + self->extend_internal_deletion_score_set = false; + self->open_left_deletion_score_set = false; + self->extend_left_deletion_score_set = false; + self->open_right_deletion_score_set = false; + self->extend_right_deletion_score_set = false; + self->insertion_score_function = NULL; + self->deletion_score_function = NULL; + self->substitution_matrix.obj = NULL; + self->substitution_matrix.buf = NULL; + self->algorithm = Unknown; + self->alphabet = NULL; + self->wildcard = -1; + return 0; +} + +static void +Aligner_dealloc(Aligner* self) +{ Py_XDECREF(self->insertion_score_function); + Py_XDECREF(self->deletion_score_function); + PyBuffer_Release(&self->substitution_matrix); + Py_XDECREF(self->alphabet); + Py_TYPE(self)->tp_free((PyObject*)self); +} + +static PyObject* +Aligner_repr(Aligner* self) +{ + const char text[] = "Pairwise aligner, implementing the Needleman-Wunsch, " + "Smith-Waterman, Gotoh, or Waterman-Smith-Beyer global or local " + "alignment algorithm, or the Fast Optimal Global Sequence Alignment " + "Algorithm"; + return PyUnicode_FromString(text); +} + +static PyObject* +Aligner_str(Aligner* self) +{ + Py_uintptr_t id; + char text[1024]; + char* p = text; + char* value; + PyObject* substitution_matrix = self->substitution_matrix.obj; + void* args[3]; + int n = 0; + PyObject* wildcard = NULL; + PyObject* s = NULL; + + p += sprintf(p, "Pairwise sequence aligner with parameters\n"); + if (substitution_matrix) { +#ifdef PYPY_VERSION + // For PyPy, use PyObject_CallFunction to get id(self) + PyObject* builtins = PyEval_GetBuiltins(); + PyObject* id_func = PyDict_GetItemString(builtins, "id"); + PyObject* id_result = PyObject_CallFunctionObjArgs(id_func, + substitution_matrix, + NULL); + if (id_result) { + if (PyLong_Check(id_result)) { + id = (Py_uintptr_t)PyLong_AsUnsignedLongLong(id_result); + } + Py_DECREF(id_result); + } +#else + // In CPython, id(self) is just the address + id = (Py_uintptr_t)substitution_matrix; +#endif + p += sprintf(p, " substitution_matrix: <%s object at 0x%" PRIxPTR ">\n", + Py_TYPE(substitution_matrix)->tp_name, id); + } else { + if (self->wildcard == -1) { + p += sprintf(p, " wildcard: None\n"); + } + else { + wildcard = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, + &self->wildcard, 1); + if (!wildcard) return NULL; + p += sprintf(p, " wildcard: '%%U'\n"); + args[n++] = wildcard; + } + /* Use PyOS_double_to_string to ensure that the locale does + * not change the decimal point into a comma. + */ + value = PyOS_double_to_string(self->match, 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " match_score: %s\n", value); + PyMem_Free(value); + value = PyOS_double_to_string(self->mismatch, 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " mismatch_score: %s\n", value); + PyMem_Free(value); + } + if (self->insertion_score_function) { + p += sprintf(p, " insertion_score_function: %%R\n"); + args[n++] = self->insertion_score_function; + } + else { + value = PyOS_double_to_string(self->open_internal_insertion_score, + 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " open_internal_insertion_score: %s\n", value); + PyMem_Free(value); + value = PyOS_double_to_string(self->extend_internal_insertion_score, + 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " extend_internal_insertion_score: %s\n", value); + PyMem_Free(value); + value = PyOS_double_to_string(self->open_left_insertion_score, + 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " open_left_insertion_score: %s\n", value); + PyMem_Free(value); + value = PyOS_double_to_string(self->extend_left_insertion_score, + 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " extend_left_insertion_score: %s\n", value); + PyMem_Free(value); + value = PyOS_double_to_string(self->open_right_insertion_score, + 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " open_right_insertion_score: %s\n", value); + PyMem_Free(value); + value = PyOS_double_to_string(self->extend_right_insertion_score, + 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " extend_right_insertion_score: %s\n", value); + PyMem_Free(value); + } + if (self->deletion_score_function) { + p += sprintf(p, " deletion_score_function: %%R\n"); + args[n++] = self->deletion_score_function; + } + else { + value = PyOS_double_to_string(self->open_internal_deletion_score, + 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " open_internal_deletion_score: %s\n", value); + PyMem_Free(value); + value = PyOS_double_to_string(self->extend_internal_deletion_score, + 'f', 6, 0, NULL); + p += sprintf(p, " extend_internal_deletion_score: %s\n", value); + PyMem_Free(value); + value = PyOS_double_to_string(self->open_left_deletion_score, + 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " open_left_deletion_score: %s\n", value); + PyMem_Free(value); + value = PyOS_double_to_string(self->extend_left_deletion_score, + 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " extend_left_deletion_score: %s\n", value); + PyMem_Free(value); + value = PyOS_double_to_string(self->open_right_deletion_score, + 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " open_right_deletion_score: %s\n", value); + PyMem_Free(value); + value = PyOS_double_to_string(self->extend_right_deletion_score, + 'f', 6, 0, NULL); + if (!value) goto exit; + p += sprintf(p, " extend_right_deletion_score: %s\n", value); + PyMem_Free(value); + } + switch (self->mode) { + case Global: sprintf(p, " mode: global\n"); break; + case Local: sprintf(p, " mode: local\n"); break; + case FOGSAA_Mode: sprintf(p, " mode: fogsaa\n"); break; + default: + ERR_UNEXPECTED_MODE + return NULL; + } + s = PyUnicode_FromFormat(text, args[0], args[1], args[2]); + +exit: + Py_XDECREF(wildcard); + return s; +} + +static char Aligner_mode__doc__[] = "alignment mode ('global', 'local', 'fogsaa')"; + +static PyObject* +Aligner_get_mode(Aligner* self, void* closure) +{ const char* message = NULL; + switch (self->mode) { + case Global: message = "global"; break; + case Local: message = "local"; break; + case FOGSAA_Mode: message = "fogsaa"; break; + } + return PyUnicode_FromString(message); +} + +static int +Aligner_set_mode(Aligner* self, PyObject* value, void* closure) +{ + self->algorithm = Unknown; + if (PyUnicode_Check(value)) { + if (PyUnicode_CompareWithASCIIString(value, "global") == 0) { + self->mode = Global; + return 0; + } + if (PyUnicode_CompareWithASCIIString(value, "local") == 0) { + self->mode = Local; + return 0; + } + if (PyUnicode_CompareWithASCIIString(value, "fogsaa") == 0) { + self->mode = FOGSAA_Mode; + return 0; + } + } + PyErr_SetString(PyExc_ValueError, + "invalid mode (expected 'global', 'local', or 'fogsaa'"); + return -1; +} + +static char Aligner_match_score__doc__[] = "match score"; + +static PyObject* +Aligner_get_match_score(Aligner* self, void* closure) +{ if (self->substitution_matrix.obj) { + Py_INCREF(Py_None); + return Py_None; + } + return PyFloat_FromDouble(self->match); +} + +static int +Aligner_set_match_score(Aligner* self, PyObject* value, void* closure) +{ + const double match = PyFloat_AsDouble(value); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, "invalid match score"); + return -1; + } + PyBuffer_Release(&self->substitution_matrix); + /* does nothing if self->substitution_matrix.obj is NULL */ + self->match = match; + return 0; +} + +static char Aligner_mismatch_score__doc__[] = "mismatch score"; + +static PyObject* +Aligner_get_mismatch_score(Aligner* self, void* closure) +{ if (self->substitution_matrix.obj) { + Py_INCREF(Py_None); + return Py_None; + } + return PyFloat_FromDouble(self->mismatch); +} + +static int +Aligner_set_mismatch_score(Aligner* self, PyObject* value, void* closure) +{ + const double mismatch = PyFloat_AsDouble(value); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, "invalid mismatch score"); + return -1; + } + PyBuffer_Release(&self->substitution_matrix); + /* does nothing if self->substitution_matrix.obj is NULL */ + self->mismatch = mismatch; + return 0; +} + +static char Aligner_substitution_matrix__doc__[] = "substitution_matrix"; + +static PyObject* +Aligner_get_substitution_matrix(Aligner* self, void* closure) +{ PyObject* object = self->substitution_matrix.obj; + if (!object) object = Py_None; + Py_INCREF(object); + return object; +} + +static int +substitution_matrix_converter(PyObject* argument, void* pointer) +{ + const int flag = PyBUF_FORMAT | PyBUF_ND; + Py_buffer* view = pointer; + if (argument == NULL) { + PyBuffer_Release(view); + return 1; + } + if (PyObject_GetBuffer(argument, view, flag) != 0) { + PyErr_SetString(PyExc_ValueError, "expected a matrix"); + return 0; + } + if (view->ndim != 2) { + PyErr_Format(PyExc_ValueError, + "substitution matrix has incorrect rank (%d expected 2)", + view->ndim); + PyBuffer_Release(view); + return 0; + } + if (view->len == 0) { + PyErr_SetString(PyExc_ValueError, "substitution matrix has zero size"); + PyBuffer_Release(view); + return 0; + } + if (strcmp(view->format, "d") != 0) { + PyErr_SetString(PyExc_ValueError, + "substitution matrix should contain float values"); + PyBuffer_Release(view); + return 0; + } + if (view->itemsize != sizeof(double)) { + PyErr_Format(PyExc_RuntimeError, + "substitution matrix has unexpected item byte size " + "(%zd, expected %zd)", view->itemsize, sizeof(double)); + PyBuffer_Release(view); + return 0; + } + if (view->shape[0] != view->shape[1]) { + PyErr_Format(PyExc_ValueError, + "substitution matrix should be square " + "(found a %zd x %zd matrix)", + view->shape[0], view->shape[1]); + PyBuffer_Release(view); + return 0; + } + return Py_CLEANUP_SUPPORTED; +} + +static int +Aligner_set_substitution_matrix(Aligner* self, PyObject* values, void* closure) +{ + Py_buffer view; + if (values == Py_None) { + PyBuffer_Release(&self->substitution_matrix); + return 0; + } + if (substitution_matrix_converter(values, &view) == 0) return -1; + PyBuffer_Release(&self->substitution_matrix); + self->substitution_matrix = view; + return 0; +} + +static char Aligner_gap_score__doc__[] = "gap score"; + +static PyObject* +Aligner_get_gap_score(Aligner* self, void* closure) +{ + if (self->insertion_score_function || self->deletion_score_function) { + if (self->insertion_score_function != self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + Py_INCREF(self->insertion_score_function); + return self->insertion_score_function; + } + else { + const double score = self->open_internal_insertion_score; + if (score != self->extend_internal_insertion_score + || score != self->open_left_insertion_score + || score != self->extend_left_insertion_score + || score != self->open_right_insertion_score + || score != self->extend_right_insertion_score + || score != self->open_internal_deletion_score + || score != self->extend_internal_deletion_score + || score != self->open_left_deletion_score + || score != self->extend_left_deletion_score + || score != self->open_right_deletion_score + || score != self->extend_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_gap_score(Aligner* self, PyObject* value, void* closure) +{ if (PyCallable_Check(value)) { + Py_XDECREF(self->insertion_score_function); + Py_XDECREF(self->deletion_score_function); + Py_INCREF(value); + Py_INCREF(value); + self->insertion_score_function = value; + self->deletion_score_function = value; + } + else { + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->open_internal_insertion_score = score; + self->open_internal_insertion_score_set = true; + self->extend_internal_insertion_score = score; + self->extend_internal_insertion_score_set = true; + self->open_left_insertion_score = score; + self->open_left_insertion_score_set = true; + self->extend_left_insertion_score = score; + self->extend_left_insertion_score_set = true; + self->open_right_insertion_score = score; + self->open_right_insertion_score_set = true; + self->extend_right_insertion_score = score; + self->extend_right_insertion_score_set = true; + self->open_internal_deletion_score = score; + self->open_internal_deletion_score_set = true; + self->extend_internal_deletion_score = score; + self->extend_internal_deletion_score_set = true; + self->open_left_deletion_score = score; + self->open_left_deletion_score_set = true; + self->extend_left_deletion_score = score; + self->extend_left_deletion_score_set = true; + self->open_right_deletion_score = score; + self->open_right_deletion_score_set = true; + self->extend_right_deletion_score = score; + self->extend_right_deletion_score_set = true; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_gap_score__doc__[] = "internal and end open gap score"; + +static PyObject* +Aligner_get_open_gap_score(Aligner* self, void* closure) +{ + if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_internal_insertion_score; + if (score != self->open_left_insertion_score + || score != self->open_right_insertion_score + || score != self->open_internal_deletion_score + || score != self->open_left_deletion_score + || score != self->open_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_open_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->open_internal_insertion_score = score; + self->open_internal_insertion_score_set = true; + self->open_left_insertion_score = score; + self->open_left_insertion_score_set = true; + self->open_right_insertion_score = score; + self->open_right_insertion_score_set = true; + self->open_internal_deletion_score = score; + self->open_internal_deletion_score_set = true; + self->open_left_deletion_score = score; + self->open_left_deletion_score_set = true; + self->open_right_deletion_score = score; + self->open_right_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_gap_score__doc__[] = "extend gap score"; + +static PyObject* +Aligner_get_extend_gap_score(Aligner* self, void* closure) +{ + if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->extend_internal_insertion_score; + if (score != self->extend_left_insertion_score + || score != self->extend_right_insertion_score + || score != self->extend_internal_deletion_score + || score != self->extend_left_deletion_score + || score != self->extend_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_extend_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->extend_internal_insertion_score = score; + self->extend_internal_insertion_score_set = true; + self->extend_left_insertion_score = score; + self->extend_left_insertion_score_set = true; + self->extend_right_insertion_score = score; + self->extend_right_insertion_score_set = true; + self->extend_internal_deletion_score = score; + self->extend_internal_deletion_score_set = true; + self->extend_left_deletion_score = score; + self->extend_left_deletion_score_set = true; + self->extend_right_deletion_score = score; + self->extend_right_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_internal_gap_score__doc__[] = "internal gap score"; + +static PyObject* +Aligner_get_internal_gap_score(Aligner* self, void* closure) +{ if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_internal_insertion_score; + if (score != self->extend_internal_insertion_score + || score != self->open_internal_deletion_score + || score != self->extend_internal_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_internal_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->open_internal_insertion_score = score; + self->open_internal_insertion_score_set = true; + self->extend_internal_insertion_score = score; + self->extend_internal_insertion_score_set = true; + self->open_internal_deletion_score = score; + self->open_internal_deletion_score_set = true; + self->extend_internal_deletion_score = score; + self->extend_internal_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_internal_gap_score__doc__[] = "open internal gap score"; + +static PyObject* +Aligner_get_open_internal_gap_score(Aligner* self, void* closure) +{ if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_internal_insertion_score; + if (score != self->open_internal_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_open_internal_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->open_internal_insertion_score = score; + self->open_internal_insertion_score_set = true; + self->open_internal_deletion_score = score; + self->open_internal_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_internal_gap_score__doc__[] = "extend internal gap score"; + +static PyObject* +Aligner_get_extend_internal_gap_score(Aligner* self, void* closure) +{ if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->extend_internal_insertion_score; + if (score != self->extend_internal_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_extend_internal_gap_score(Aligner* self, PyObject* value, + void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->extend_internal_insertion_score = score; + self->extend_internal_insertion_score_set = true; + self->extend_internal_deletion_score = score; + self->extend_internal_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_end_gap_score__doc__[] = "end gap score"; + +static PyObject* +Aligner_get_end_gap_score(Aligner* self, void* closure) +{ if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_left_insertion_score; + if (score != self->extend_left_insertion_score + || score != self->open_right_insertion_score + || score != self->extend_right_insertion_score + || score != self->open_left_deletion_score + || score != self->extend_left_deletion_score + || score != self->open_right_deletion_score + || score != self->extend_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_end_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->open_left_insertion_score = score; + self->open_left_insertion_score_set = true; + self->extend_left_insertion_score = score; + self->extend_left_insertion_score_set = true; + self->open_right_insertion_score = score; + self->open_right_insertion_score_set = true; + self->extend_right_insertion_score = score; + self->extend_right_insertion_score_set = true; + self->open_left_deletion_score = score; + self->open_left_deletion_score_set = true; + self->extend_left_deletion_score = score; + self->extend_left_deletion_score_set = true; + self->open_right_deletion_score = score; + self->open_right_deletion_score_set = true; + self->extend_right_deletion_score = score; + self->extend_right_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_end_gap_score__doc__[] = "open end gap score"; + +static PyObject* +Aligner_get_open_end_gap_score(Aligner* self, void* closure) +{ if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_left_insertion_score; + if (score != self->open_right_insertion_score + || score != self->open_left_deletion_score + || score != self->open_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_open_end_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->open_left_insertion_score = score; + self->open_left_insertion_score_set = true; + self->open_right_insertion_score = score; + self->open_right_insertion_score_set = true; + self->open_left_deletion_score = score; + self->open_left_deletion_score_set = true; + self->open_right_deletion_score = score; + self->open_right_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_end_gap_score__doc__[] = "extend end gap score"; + +static PyObject* +Aligner_get_extend_end_gap_score(Aligner* self, void* closure) +{ if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->extend_left_insertion_score; + if (score != self->extend_right_insertion_score + || score != self->extend_left_deletion_score + || score != self->extend_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_extend_end_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->extend_left_insertion_score = score; + self->extend_left_insertion_score_set = true; + self->extend_right_insertion_score = score; + self->extend_right_insertion_score_set = true; + self->extend_left_deletion_score = score; + self->extend_left_deletion_score_set = true; + self->extend_right_deletion_score = score; + self->extend_right_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_left_gap_score__doc__[] = "left gap score"; + +static PyObject* +Aligner_get_left_gap_score(Aligner* self, void* closure) +{ if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_left_insertion_score; + if (score != self->extend_left_insertion_score + || score != self->open_left_deletion_score + || score != self->extend_left_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_left_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->open_left_insertion_score = score; + self->open_left_insertion_score_set = true; + self->extend_left_insertion_score = score; + self->extend_left_insertion_score_set = true; + self->open_left_deletion_score = score; + self->open_left_deletion_score_set = true; + self->extend_left_deletion_score = score; + self->extend_left_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_right_gap_score__doc__[] = "right gap score"; + +static PyObject* +Aligner_get_right_gap_score(Aligner* self, void* closure) +{ if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_right_insertion_score; + if (score != self->extend_right_insertion_score + || score != self->open_right_deletion_score + || score != self->extend_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_right_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->open_right_insertion_score = score; + self->open_right_insertion_score_set = true; + self->extend_right_insertion_score = score; + self->extend_right_insertion_score_set = true; + self->open_right_deletion_score = score; + self->open_right_deletion_score_set = true; + self->extend_right_deletion_score = score; + self->extend_right_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_left_gap_score__doc__[] = "open left gap score"; + +static PyObject* +Aligner_get_open_left_gap_score(Aligner* self, void* closure) +{ if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_left_insertion_score; + if (score != self->open_left_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_open_left_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->open_left_insertion_score = score; + self->open_left_insertion_score_set = true; + self->open_left_deletion_score = score; + self->open_left_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_left_gap_score__doc__[] = "extend left gap score"; + +static PyObject* +Aligner_get_extend_left_gap_score(Aligner* self, void* closure) +{ if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->extend_left_insertion_score; + if (score != self->extend_left_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_extend_left_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->extend_left_insertion_score = score; + self->extend_left_insertion_score_set = true; + self->extend_left_deletion_score = score; + self->extend_left_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_right_gap_score__doc__[] = "open right gap score"; + +static PyObject* +Aligner_get_open_right_gap_score(Aligner* self, void* closure) +{ if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_right_insertion_score; + if (score != self->open_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_open_right_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->open_right_insertion_score = score; + self->open_right_insertion_score_set = true; + self->open_right_deletion_score = score; + self->open_right_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_right_gap_score__doc__[] = "extend right gap score"; + +static PyObject* +Aligner_get_extend_right_gap_score(Aligner* self, void* closure) +{ if (self->insertion_score_function || self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->extend_right_insertion_score; + if (score != self->extend_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_extend_right_gap_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->extend_right_insertion_score = score; + self->extend_right_insertion_score_set = true; + self->extend_right_deletion_score = score; + self->extend_right_deletion_score_set = true; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_insertion_score__doc__[] = "open insertion score"; + +static PyObject* +Aligner_get_open_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_internal_insertion_score; + if (score != self->open_left_insertion_score + || score != self->open_right_insertion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_open_insertion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_internal_insertion_score = score; + self->open_internal_insertion_score_set = true; + self->open_left_insertion_score = score; + self->open_left_insertion_score_set = true; + self->open_right_insertion_score = score; + self->open_right_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_insertion_score__doc__[] = "extend insertion score"; + +static PyObject* +Aligner_get_extend_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->extend_internal_insertion_score; + if (score != self->extend_left_insertion_score + || score != self->extend_right_insertion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_extend_insertion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->extend_internal_insertion_score = score; + self->extend_internal_insertion_score_set = true; + self->extend_left_insertion_score = score; + self->extend_left_insertion_score_set = true; + self->extend_right_insertion_score = score; + self->extend_right_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_insertion_score__doc__[] = "insertion score"; + +static PyObject* +Aligner_get_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + Py_INCREF(self->insertion_score_function); + return self->insertion_score_function; + } + else { + const double score = self->open_internal_insertion_score; + if (score != self->extend_internal_insertion_score + || score != self->open_left_insertion_score + || score != self->extend_left_insertion_score + || score != self->open_right_insertion_score + || score != self->extend_right_insertion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_insertion_score(Aligner* self, PyObject* value, void* closure) +{ + if (PyCallable_Check(value)) { + Py_XDECREF(self->insertion_score_function); + Py_INCREF(value); + self->insertion_score_function = value; + } + else { + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "gap score should be numerical or callable"); + return -1; + } + self->open_internal_insertion_score = score; + self->open_internal_insertion_score_set = true; + self->extend_internal_insertion_score = score; + self->extend_internal_insertion_score_set = true; + self->open_left_insertion_score = score; + self->open_left_insertion_score_set = true; + self->extend_left_insertion_score = score; + self->extend_left_insertion_score_set = true; + self->open_right_insertion_score = score; + self->open_right_insertion_score_set = true; + self->extend_right_insertion_score = score; + self->extend_right_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_deletion_score__doc__[] = "open deletion score"; + +static PyObject* +Aligner_get_open_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_internal_deletion_score; + if (score != self->open_left_deletion_score + || score != self->open_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_open_deletion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_internal_deletion_score = score; + self->open_internal_deletion_score_set = true; + self->open_left_deletion_score = score; + self->open_left_deletion_score_set = true; + self->open_right_deletion_score = score; + self->open_right_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_deletion_score__doc__[] = "extend deletion score"; + +static PyObject* +Aligner_get_extend_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->extend_internal_deletion_score; + if (score != self->extend_left_deletion_score + || score != self->extend_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_extend_deletion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->extend_internal_deletion_score = score; + self->extend_internal_deletion_score_set = true; + self->extend_left_deletion_score = score; + self->extend_left_deletion_score_set = true; + self->extend_right_deletion_score = score; + self->extend_right_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_deletion_score__doc__[] = "deletion score"; + +static PyObject* +Aligner_get_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + Py_INCREF(self->deletion_score_function); + return self->deletion_score_function; + } + else { + const double score = self->open_internal_deletion_score; + if (score != self->open_left_deletion_score + || score != self->open_right_deletion_score + || score != self->extend_internal_deletion_score + || score != self->extend_left_deletion_score + || score != self->extend_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_deletion_score(Aligner* self, PyObject* value, void* closure) +{ if (PyCallable_Check(value)) { + Py_XDECREF(self->deletion_score_function); + Py_INCREF(value); + self->deletion_score_function = value; + } + else { + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) { + PyErr_SetString(PyExc_ValueError, + "gap score should be numerical or callable"); + return -1; + } + self->open_internal_deletion_score = score; + self->open_internal_deletion_score_set = true; + self->extend_internal_deletion_score = score; + self->extend_internal_deletion_score_set = true; + self->open_left_deletion_score = score; + self->open_left_deletion_score_set = true; + self->extend_left_deletion_score = score; + self->extend_left_deletion_score_set = true; + self->open_right_deletion_score = score; + self->open_right_deletion_score_set = true; + self->extend_right_deletion_score = score; + self->extend_right_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_internal_insertion_score__doc__[] = "open internal insertion score"; + +static PyObject* +Aligner_get_open_internal_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + return PyFloat_FromDouble(self->open_internal_insertion_score); +} + +static int +Aligner_set_open_internal_insertion_score(Aligner* self, + PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_internal_insertion_score = score; + self->open_internal_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_internal_insertion_score__doc__[] = "extend internal insertion score"; + +static PyObject* +Aligner_get_extend_internal_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + return PyFloat_FromDouble(self->extend_internal_insertion_score); +} + +static int +Aligner_set_extend_internal_insertion_score(Aligner* self, + PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->extend_internal_insertion_score = score; + self->extend_internal_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_internal_insertion_score__doc__[] = "internal insertion score"; + +static PyObject* +Aligner_get_internal_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_internal_insertion_score; + if (score != self->extend_internal_insertion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_internal_insertion_score(Aligner* self, PyObject* value, + void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_internal_insertion_score = score; + self->open_internal_insertion_score_set = true; + self->extend_internal_insertion_score = score; + self->extend_internal_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_end_insertion_score__doc__[] = "end insertion score"; + +static PyObject* +Aligner_get_end_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_left_insertion_score; + if (score != self->extend_left_insertion_score + || score != self->open_right_insertion_score + || score != self->extend_right_insertion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_end_insertion_score(Aligner* self, PyObject* value, void* closure) { + const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_left_insertion_score = score; + self->open_left_insertion_score_set = true; + self->extend_left_insertion_score = score; + self->extend_left_insertion_score_set = true; + self->open_right_insertion_score = score; + self->open_right_insertion_score_set = true; + self->extend_right_insertion_score = score; + self->extend_right_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_end_insertion_score__doc__[] = "open end insertion score"; + +static PyObject* +Aligner_get_open_end_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_left_insertion_score; + if (score != self->open_right_insertion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_open_end_insertion_score(Aligner* self, PyObject* value, + void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_left_insertion_score = score; + self->open_left_insertion_score_set = true; + self->open_right_insertion_score = score; + self->open_right_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_end_insertion_score__doc__[] = "extend end insertion score"; + +static PyObject* +Aligner_get_extend_end_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->extend_left_insertion_score; + if (score != self->extend_right_insertion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_extend_end_insertion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->extend_left_insertion_score = score; + self->extend_left_insertion_score_set = true; + self->extend_right_insertion_score = score; + self->extend_right_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_left_insertion_score__doc__[] = "open left insertion score"; + +static PyObject* +Aligner_get_open_left_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + return PyFloat_FromDouble(self->open_left_insertion_score); +} + +static int +Aligner_set_open_left_insertion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_left_insertion_score = score; + self->open_left_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_left_insertion_score__doc__[] = "extend left insertion score"; + +static PyObject* +Aligner_get_extend_left_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + return PyFloat_FromDouble(self->extend_left_insertion_score); +} + +static int +Aligner_set_extend_left_insertion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->extend_left_insertion_score = score; + self->extend_left_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_left_insertion_score__doc__[] = "left insertion score"; + +static PyObject* +Aligner_get_left_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_left_insertion_score; + if (score != self->extend_left_insertion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_left_insertion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_left_insertion_score = score; + self->open_left_insertion_score_set = true; + self->extend_left_insertion_score = score; + self->extend_left_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_right_insertion_score__doc__[] = "open right insertion score"; + +static PyObject* +Aligner_get_open_right_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + return PyFloat_FromDouble(self->open_right_insertion_score); +} + +static int +Aligner_set_open_right_insertion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_right_insertion_score = score; + self->open_right_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_right_insertion_score__doc__[] = "extend right insertion score"; + +static PyObject* +Aligner_get_extend_right_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + return PyFloat_FromDouble(self->extend_right_insertion_score); +} + +static int +Aligner_set_extend_right_insertion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->extend_right_insertion_score = score; + self->extend_right_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_right_insertion_score__doc__[] = "right insertion score"; + +static PyObject* +Aligner_get_right_insertion_score(Aligner* self, void* closure) +{ if (self->insertion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_right_insertion_score; + if (score != self->extend_right_insertion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_right_insertion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_right_insertion_score = score; + self->open_right_insertion_score_set = true; + self->extend_right_insertion_score = score; + self->extend_right_insertion_score_set = true; + if (self->insertion_score_function) { + Py_DECREF(self->insertion_score_function); + self->insertion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_end_deletion_score__doc__[] = "end deletion score"; + +static PyObject* +Aligner_get_end_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_left_deletion_score; + if (score != self->extend_left_deletion_score + || score != self->open_right_deletion_score + || score != self->extend_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_end_deletion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_left_deletion_score = score; + self->open_left_deletion_score_set = true; + self->extend_left_deletion_score = score; + self->extend_left_deletion_score_set = true; + self->open_right_deletion_score = score; + self->open_right_deletion_score_set = true; + self->extend_right_deletion_score = score; + self->extend_right_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_end_deletion_score__doc__[] = "open end deletion score"; + +static PyObject* +Aligner_get_open_end_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_left_deletion_score; + if (score != self->open_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_open_end_deletion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_left_deletion_score = score; + self->open_left_deletion_score_set = true; + self->open_right_deletion_score = score; + self->open_right_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_end_deletion_score__doc__[] = "extend end deletion score"; + +static PyObject* +Aligner_get_extend_end_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->extend_left_deletion_score; + if (score != self->extend_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_extend_end_deletion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->extend_left_deletion_score = score; + self->extend_left_deletion_score_set = true; + self->extend_right_deletion_score = score; + self->extend_right_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_internal_deletion_score__doc__[] = "open internal deletion score"; + +static PyObject* +Aligner_get_open_internal_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + return PyFloat_FromDouble(self->open_internal_deletion_score); +} + +static int +Aligner_set_open_internal_deletion_score(Aligner* self, PyObject* value, + void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_internal_deletion_score = score; + self->open_internal_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_internal_deletion_score__doc__[] = "extend internal deletion score"; + +static PyObject* +Aligner_get_extend_internal_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + return PyFloat_FromDouble(self->extend_internal_deletion_score); +} + +static int +Aligner_set_extend_internal_deletion_score(Aligner* self, PyObject* value, + void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->extend_internal_deletion_score = score; + self->extend_internal_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_internal_deletion_score__doc__[] = "internal deletion score"; + +static PyObject* +Aligner_get_internal_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_internal_deletion_score; + if (score != self->extend_internal_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_internal_deletion_score(Aligner* self, PyObject* value, + void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_internal_deletion_score = score; + self->open_internal_deletion_score_set = true; + self->extend_internal_deletion_score = score; + self->extend_internal_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_left_deletion_score__doc__[] = "open left deletion score"; + +static PyObject* +Aligner_get_open_left_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + return PyFloat_FromDouble(self->open_left_deletion_score); +} + +static int +Aligner_set_open_left_deletion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_left_deletion_score = score; + self->open_left_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_left_deletion_score__doc__[] = "extend left deletion score"; + +static PyObject* +Aligner_get_extend_left_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + return PyFloat_FromDouble(self->extend_left_deletion_score); +} + +static int +Aligner_set_extend_left_deletion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->extend_left_deletion_score = score; + self->extend_left_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_left_deletion_score__doc__[] = "left deletion score"; + +static PyObject* +Aligner_get_left_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_left_deletion_score; + if (score != self->extend_left_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_left_deletion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_left_deletion_score = score; + self->open_left_deletion_score_set = true; + self->extend_left_deletion_score = score; + self->extend_left_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_open_right_deletion_score__doc__[] = "open right deletion score"; + +static PyObject* +Aligner_get_open_right_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + return PyFloat_FromDouble(self->open_right_deletion_score); +} + +static int +Aligner_set_open_right_deletion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_right_deletion_score = score; + self->open_right_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_extend_right_deletion_score__doc__[] = "extend right deletion score"; + +static PyObject* +Aligner_get_extend_right_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + return PyFloat_FromDouble(self->extend_right_deletion_score); +} + +static int +Aligner_set_extend_right_deletion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->extend_right_deletion_score = score; + self->extend_right_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_right_deletion_score__doc__[] = "right deletion score"; + +static PyObject* +Aligner_get_right_deletion_score(Aligner* self, void* closure) +{ if (self->deletion_score_function) { + PyErr_SetString(PyExc_ValueError, "using a gap score function"); + return NULL; + } + else { + const double score = self->open_right_deletion_score; + if (score != self->extend_right_deletion_score) { + PyErr_SetString(PyExc_ValueError, "gap scores are different"); + return NULL; + } + return PyFloat_FromDouble(score); + } +} + +static int +Aligner_set_right_deletion_score(Aligner* self, PyObject* value, void* closure) +{ const double score = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->open_right_deletion_score = score; + self->open_right_deletion_score_set = true; + self->extend_right_deletion_score = score; + self->extend_right_deletion_score_set = true; + if (self->deletion_score_function) { + Py_DECREF(self->deletion_score_function); + self->deletion_score_function = NULL; + } + self->algorithm = Unknown; + return 0; +} + +static char Aligner_epsilon__doc__[] = "roundoff epsilon"; + +static PyObject* +Aligner_get_epsilon(Aligner* self, void* closure) +{ return PyFloat_FromDouble(self->epsilon); +} + +static int +Aligner_set_epsilon(Aligner* self, PyObject* value, void* closure) +{ const double epsilon = PyFloat_AsDouble(value); + if (PyErr_Occurred()) return -1; + self->epsilon = epsilon; + self->algorithm = Unknown; + return 0; +} + +static char Aligner_wildcard__doc__[] = "wildcard character"; + +static PyObject* +Aligner_get_wildcard(Aligner* self, void* closure) +{ + if (self->wildcard == -1) { + Py_INCREF(Py_None); + return Py_None; + } + else { + return PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, &self->wildcard, 1); + } +} + +static int +Aligner_set_wildcard(Aligner* self, PyObject* value, void* closure) +{ + if (value == Py_None) { + self->wildcard = -1; + return 0; + } + if (!PyUnicode_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "wildcard should be a single character, or None"); + return -1; + } + if (PyUnicode_READY(value) == -1) return -1; + if (PyUnicode_GET_LENGTH(value) != 1) { + PyErr_SetString(PyExc_ValueError, + "wildcard should be a single character, or None"); + return -1; + } + self->wildcard = PyUnicode_READ_CHAR(value, 0); + return 0; +} + +static char Aligner_algorithm__doc__[] = "alignment algorithm"; + +static PyObject* +Aligner_get_algorithm(Aligner* self, void* closure) +{ + const char* s = NULL; + const Mode mode = self->mode; + const Algorithm algorithm = _get_algorithm(self); + switch (algorithm) { + case NeedlemanWunschSmithWaterman: + switch (mode) { + case Global: + s = "Needleman-Wunsch"; + break; + case Local: + s = "Smith-Waterman"; + break; + default: + ERR_UNEXPECTED_MODE + return NULL; + } + break; + case Gotoh: + switch (mode) { + case Global: + s = "Gotoh global alignment algorithm"; + break; + case Local: + s = "Gotoh local alignment algorithm"; + break; + default: + ERR_UNEXPECTED_MODE + return NULL; + } + break; + case WatermanSmithBeyer: + switch (mode) { + case Global: + s = "Waterman-Smith-Beyer global alignment algorithm"; + break; + case Local: + s = "Waterman-Smith-Beyer local alignment algorithm"; + break; + default: + ERR_UNEXPECTED_MODE + return NULL; + } + break; + case FOGSAA: + // self->mode must be FOGSAA_Mode + s = "Fast Optimal Global Sequence Alignment Algorithm"; + break; + case Unknown: + default: + break; + } + return PyUnicode_FromString(s); +} + +static PyGetSetDef Aligner_getset[] = { + {"mode", + (getter)Aligner_get_mode, + (setter)Aligner_set_mode, + Aligner_mode__doc__, NULL}, + {"match_score", + (getter)Aligner_get_match_score, + (setter)Aligner_set_match_score, + Aligner_match_score__doc__, NULL}, + {"mismatch_score", + (getter)Aligner_get_mismatch_score, + (setter)Aligner_set_mismatch_score, + Aligner_mismatch_score__doc__, NULL}, + {"match", /* synonym for match_score */ + (getter)Aligner_get_match_score, + (setter)Aligner_set_match_score, + Aligner_match_score__doc__, NULL}, + {"mismatch", /* synonym for mismatch_score */ + (getter)Aligner_get_mismatch_score, + (setter)Aligner_set_mismatch_score, + Aligner_mismatch_score__doc__, NULL}, + {"substitution_matrix", + (getter)Aligner_get_substitution_matrix, + (setter)Aligner_set_substitution_matrix, + Aligner_substitution_matrix__doc__, NULL}, + {"gap_score", + (getter)Aligner_get_gap_score, + (setter)Aligner_set_gap_score, + Aligner_gap_score__doc__, NULL}, + {"open_gap_score", + (getter)Aligner_get_open_gap_score, + (setter)Aligner_set_open_gap_score, + Aligner_open_gap_score__doc__, NULL}, + {"extend_gap_score", + (getter)Aligner_get_extend_gap_score, + (setter)Aligner_set_extend_gap_score, + Aligner_extend_gap_score__doc__, NULL}, + {"internal_gap_score", + (getter)Aligner_get_internal_gap_score, + (setter)Aligner_set_internal_gap_score, + Aligner_internal_gap_score__doc__, NULL}, + {"open_internal_gap_score", + (getter)Aligner_get_open_internal_gap_score, + (setter)Aligner_set_open_internal_gap_score, + Aligner_open_internal_gap_score__doc__, NULL}, + {"extend_internal_gap_score", + (getter)Aligner_get_extend_internal_gap_score, + (setter)Aligner_set_extend_internal_gap_score, + Aligner_extend_internal_gap_score__doc__, NULL}, + {"end_gap_score", + (getter)Aligner_get_end_gap_score, + (setter)Aligner_set_end_gap_score, + Aligner_end_gap_score__doc__, NULL}, + {"open_end_gap_score", + (getter)Aligner_get_open_end_gap_score, + (setter)Aligner_set_open_end_gap_score, + Aligner_open_end_gap_score__doc__, NULL}, + {"extend_end_gap_score", + (getter)Aligner_get_extend_end_gap_score, + (setter)Aligner_set_extend_end_gap_score, + Aligner_extend_end_gap_score__doc__, NULL}, + {"left_gap_score", + (getter)Aligner_get_left_gap_score, + (setter)Aligner_set_left_gap_score, + Aligner_left_gap_score__doc__, NULL}, + {"open_left_gap_score", + (getter)Aligner_get_open_left_gap_score, + (setter)Aligner_set_open_left_gap_score, + Aligner_open_left_gap_score__doc__, NULL}, + {"extend_left_gap_score", + (getter)Aligner_get_extend_left_gap_score, + (setter)Aligner_set_extend_left_gap_score, + Aligner_extend_left_gap_score__doc__, NULL}, + {"right_gap_score", + (getter)Aligner_get_right_gap_score, + (setter)Aligner_set_right_gap_score, + Aligner_right_gap_score__doc__, NULL}, + {"open_right_gap_score", + (getter)Aligner_get_open_right_gap_score, + (setter)Aligner_set_open_right_gap_score, + Aligner_open_right_gap_score__doc__, NULL}, + {"extend_right_gap_score", + (getter)Aligner_get_extend_right_gap_score, + (setter)Aligner_set_extend_right_gap_score, + Aligner_extend_right_gap_score__doc__, NULL}, + {"open_insertion_score", + (getter)Aligner_get_open_insertion_score, + (setter)Aligner_set_open_insertion_score, + Aligner_open_insertion_score__doc__, NULL}, + {"extend_insertion_score", + (getter)Aligner_get_extend_insertion_score, + (setter)Aligner_set_extend_insertion_score, + Aligner_extend_insertion_score__doc__, NULL}, + {"insertion_score", + (getter)Aligner_get_insertion_score, + (setter)Aligner_set_insertion_score, + Aligner_insertion_score__doc__, NULL}, + {"open_deletion_score", + (getter)Aligner_get_open_deletion_score, + (setter)Aligner_set_open_deletion_score, + Aligner_open_deletion_score__doc__, NULL}, + {"extend_deletion_score", + (getter)Aligner_get_extend_deletion_score, + (setter)Aligner_set_extend_deletion_score, + Aligner_extend_deletion_score__doc__, NULL}, + {"deletion_score", + (getter)Aligner_get_deletion_score, + (setter)Aligner_set_deletion_score, + Aligner_deletion_score__doc__, NULL}, + {"end_insertion_score", + (getter)Aligner_get_end_insertion_score, + (setter)Aligner_set_end_insertion_score, + Aligner_end_insertion_score__doc__, NULL}, + {"open_end_insertion_score", + (getter)Aligner_get_open_end_insertion_score, + (setter)Aligner_set_open_end_insertion_score, + Aligner_open_end_insertion_score__doc__, NULL}, + {"extend_end_insertion_score", + (getter)Aligner_get_extend_end_insertion_score, + (setter)Aligner_set_extend_end_insertion_score, + Aligner_extend_end_insertion_score__doc__, NULL}, + {"open_internal_insertion_score", + (getter)Aligner_get_open_internal_insertion_score, + (setter)Aligner_set_open_internal_insertion_score, + Aligner_open_internal_insertion_score__doc__, NULL}, + {"extend_internal_insertion_score", + (getter)Aligner_get_extend_internal_insertion_score, + (setter)Aligner_set_extend_internal_insertion_score, + Aligner_extend_internal_insertion_score__doc__, NULL}, + {"internal_insertion_score", + (getter)Aligner_get_internal_insertion_score, + (setter)Aligner_set_internal_insertion_score, + Aligner_internal_insertion_score__doc__, NULL}, + {"open_left_insertion_score", + (getter)Aligner_get_open_left_insertion_score, + (setter)Aligner_set_open_left_insertion_score, + Aligner_open_left_insertion_score__doc__, NULL}, + {"extend_left_insertion_score", + (getter)Aligner_get_extend_left_insertion_score, + (setter)Aligner_set_extend_left_insertion_score, + Aligner_extend_left_insertion_score__doc__, NULL}, + {"left_insertion_score", + (getter)Aligner_get_left_insertion_score, + (setter)Aligner_set_left_insertion_score, + Aligner_left_insertion_score__doc__, NULL}, + {"open_right_insertion_score", + (getter)Aligner_get_open_right_insertion_score, + (setter)Aligner_set_open_right_insertion_score, + Aligner_open_right_insertion_score__doc__, NULL}, + {"extend_right_insertion_score", + (getter)Aligner_get_extend_right_insertion_score, + (setter)Aligner_set_extend_right_insertion_score, + Aligner_extend_right_insertion_score__doc__, NULL}, + {"right_insertion_score", + (getter)Aligner_get_right_insertion_score, + (setter)Aligner_set_right_insertion_score, + Aligner_right_insertion_score__doc__, NULL}, + {"end_deletion_score", + (getter)Aligner_get_end_deletion_score, + (setter)Aligner_set_end_deletion_score, + Aligner_end_deletion_score__doc__, NULL}, + {"open_end_deletion_score", + (getter)Aligner_get_open_end_deletion_score, + (setter)Aligner_set_open_end_deletion_score, + Aligner_open_end_deletion_score__doc__, NULL}, + {"extend_end_deletion_score", + (getter)Aligner_get_extend_end_deletion_score, + (setter)Aligner_set_extend_end_deletion_score, + Aligner_extend_end_deletion_score__doc__, NULL}, + {"open_internal_deletion_score", + (getter)Aligner_get_open_internal_deletion_score, + (setter)Aligner_set_open_internal_deletion_score, + Aligner_open_internal_deletion_score__doc__, NULL}, + {"extend_internal_deletion_score", + (getter)Aligner_get_extend_internal_deletion_score, + (setter)Aligner_set_extend_internal_deletion_score, + Aligner_extend_internal_deletion_score__doc__, NULL}, + {"internal_deletion_score", + (getter)Aligner_get_internal_deletion_score, + (setter)Aligner_set_internal_deletion_score, + Aligner_internal_deletion_score__doc__, NULL}, + {"open_left_deletion_score", + (getter)Aligner_get_open_left_deletion_score, + (setter)Aligner_set_open_left_deletion_score, + Aligner_open_left_deletion_score__doc__, NULL}, + {"extend_left_deletion_score", + (getter)Aligner_get_extend_left_deletion_score, + (setter)Aligner_set_extend_left_deletion_score, + Aligner_extend_left_deletion_score__doc__, NULL}, + {"left_deletion_score", + (getter)Aligner_get_left_deletion_score, + (setter)Aligner_set_left_deletion_score, + Aligner_left_deletion_score__doc__, NULL}, + {"open_right_deletion_score", + (getter)Aligner_get_open_right_deletion_score, + (setter)Aligner_set_open_right_deletion_score, + Aligner_open_right_deletion_score__doc__, NULL}, + {"extend_right_deletion_score", + (getter)Aligner_get_extend_right_deletion_score, + (setter)Aligner_set_extend_right_deletion_score, + Aligner_extend_right_deletion_score__doc__, NULL}, + {"right_deletion_score", + (getter)Aligner_get_right_deletion_score, + (setter)Aligner_set_right_deletion_score, + Aligner_right_deletion_score__doc__, NULL}, + {"epsilon", + (getter)Aligner_get_epsilon, + (setter)Aligner_set_epsilon, + Aligner_epsilon__doc__, NULL}, + {"wildcard", + (getter)Aligner_get_wildcard, + (setter)Aligner_set_wildcard, + Aligner_wildcard__doc__, NULL}, + {"algorithm", + (getter)Aligner_get_algorithm, + (setter)NULL, + Aligner_algorithm__doc__, NULL}, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +#define SELECT_SCORE_GLOBAL(score1, score2, score3) \ + score = score1; \ + temp = score2; \ + if (temp > score) score = temp; \ + temp = score3; \ + if (temp > score) score = temp; + +#define SELECT_SCORE_WATERMAN_SMITH_BEYER(score1, score2) \ + temp = score1 + gapscore; \ + if (temp > score) score = temp; \ + temp = score2 + gapscore; \ + if (temp > score) score = temp; + +#define SELECT_SCORE_GOTOH_LOCAL_ALIGN(score1, score2, score3, score4) \ + score = score1; \ + temp = score2; \ + if (temp > score) score = temp; \ + temp = score3; \ + if (temp > score) score = temp; \ + score += score4; \ + if (score < 0) score = 0; \ + else if (score > maximum) maximum = score; + +#define SELECT_SCORE_LOCAL3(score1, score2, score3) \ + score = score1; \ + temp = score2; \ + if (temp > score) score = temp; \ + temp = score3; \ + if (temp > score) score = temp; \ + if (score < 0) score = 0; \ + else if (score > maximum) maximum = score; + +#define SELECT_SCORE_LOCAL1(score1) \ + score = score1; \ + if (score < 0) score = 0; \ + else if (score > maximum) maximum = score; + +#define SELECT_TRACE_NEEDLEMAN_WUNSCH(hgap, vgap, align_score) \ + score = temp + (align_score); \ + trace = DIAGONAL; \ + temp = row[j-1] + hgap; \ + if (temp > score + epsilon) { \ + score = temp; \ + trace = HORIZONTAL; \ + } \ + else if (temp > score - epsilon) trace |= HORIZONTAL; \ + temp = row[j] + vgap; \ + if (temp > score + epsilon) { \ + score = temp; \ + trace = VERTICAL; \ + } \ + else if (temp > score - epsilon) trace |= VERTICAL; \ + temp = row[j]; \ + row[j] = score; \ + M[i][j].trace = trace; + +#define SELECT_TRACE_SMITH_WATERMAN_HVD(align_score) \ + trace = DIAGONAL; \ + score = temp + (align_score); \ + temp = row[j-1] + gap_extend_A; \ + if (temp > score + epsilon) { \ + score = temp; \ + trace = HORIZONTAL; \ + } \ + else if (temp > score - epsilon) trace |= HORIZONTAL; \ + temp = row[j] + gap_extend_B; \ + if (temp > score + epsilon) { \ + score = temp; \ + trace = VERTICAL; \ + } \ + else if (temp > score - epsilon) trace |= VERTICAL; \ + if (score < epsilon) { \ + score = 0; \ + trace = STARTPOINT; \ + } \ + else if (trace & DIAGONAL && score > maximum - epsilon) { \ + if (score > maximum + epsilon) { \ + for ( ; im < i; im++, jm = 0) \ + for ( ; jm <= nB; jm++) M[im][jm].trace &= ~ENDPOINT; \ + for ( ; jm < j; jm++) M[im][jm].trace &= ~ENDPOINT; \ + im = i; \ + jm = j; \ + } \ + trace |= ENDPOINT; \ + } \ + M[i][j].trace = trace; \ + if (score > maximum) maximum = score; \ + temp = row[j]; \ + row[j] = score; + +#define SELECT_TRACE_SMITH_WATERMAN_D(align_score) \ + score = temp + (align_score); \ + trace = DIAGONAL; \ + if (score < epsilon) { \ + score = 0; \ + } \ + else if (trace & DIAGONAL && score > maximum - epsilon) { \ + if (score > maximum + epsilon) { \ + for ( ; im < i; im++, jm = 0) \ + for ( ; jm <= nB; jm++) M[im][jm].trace &= ~ENDPOINT; \ + for ( ; jm < j; jm++) M[im][jm].trace &= ~ENDPOINT; \ + im = i; \ + jm = j; \ + } \ + trace |= ENDPOINT; \ + } \ + M[i][j].trace = trace; \ + if (score > maximum) maximum = score; \ + temp = row[j]; \ + row[j] = score + +#define SELECT_TRACE_GOTOH_GLOBAL_GAP(matrix, score1, score2, score3) \ + trace = M_MATRIX; \ + score = score1; \ + temp = score2; \ + if (temp > score + epsilon) { \ + score = temp; \ + trace = Ix_MATRIX; \ + } \ + else if (temp > score - epsilon) trace |= Ix_MATRIX; \ + temp = score3; \ + if (temp > score + epsilon) { \ + score = temp; \ + trace = Iy_MATRIX; \ + } \ + else if (temp > score - epsilon) trace |= Iy_MATRIX; \ + gaps[i][j].matrix = trace; + +#define SELECT_TRACE_GOTOH_GLOBAL_ALIGN \ + trace = M_MATRIX; \ + score = M_temp; \ + temp = Ix_temp; \ + if (temp > score + epsilon) { \ + score = Ix_temp; \ + trace = Ix_MATRIX; \ + } \ + else if (temp > score - epsilon) trace |= Ix_MATRIX; \ + temp = Iy_temp; \ + if (temp > score + epsilon) { \ + score = temp; \ + trace = Iy_MATRIX; \ + } \ + else if (temp > score - epsilon) trace |= Iy_MATRIX; \ + M[i][j].trace = trace; + +#define SELECT_TRACE_GOTOH_LOCAL_ALIGN(align_score) \ + trace = M_MATRIX; \ + score = M_temp; \ + if (Ix_temp > score + epsilon) { \ + score = Ix_temp; \ + trace = Ix_MATRIX; \ + } \ + else if (Ix_temp > score - epsilon) trace |= Ix_MATRIX; \ + if (Iy_temp > score + epsilon) { \ + score = Iy_temp; \ + trace = Iy_MATRIX; \ + } \ + else if (Iy_temp > score - epsilon) trace |= Iy_MATRIX; \ + score += (align_score); \ + if (score < epsilon) { \ + score = 0; \ + trace = STARTPOINT; \ + } \ + else if (score > maximum - epsilon) { \ + if (score > maximum + epsilon) { \ + maximum = score; \ + for ( ; im < i; im++, jm = 0) \ + for ( ; jm <= nB; jm++) M[im][jm].trace &= ~ENDPOINT; \ + for ( ; jm < j; jm++) M[im][jm].trace &= ~ENDPOINT; \ + im = i; \ + jm = j; \ + } \ + trace |= ENDPOINT; \ + } \ + M[i][j].trace = trace; + +#define SELECT_TRACE_GOTOH_LOCAL_GAP(matrix, score1, score2, score3) \ + trace = M_MATRIX; \ + score = score1; \ + temp = score2; \ + if (temp > score + epsilon) { \ + score = temp; \ + trace = Ix_MATRIX; \ + } \ + else if (temp > score - epsilon) trace |= Ix_MATRIX; \ + temp = score3; \ + if (temp > score + epsilon) { \ + score = temp; \ + trace = Iy_MATRIX; \ + } \ + else if (temp > score - epsilon) trace |= Iy_MATRIX; \ + if (score < epsilon) { \ + score = -DBL_MAX; \ + trace = 0; \ + } \ + gaps[i][j].matrix = trace; + +#define SELECT_TRACE_WATERMAN_SMITH_BEYER_GLOBAL_ALIGN(score4) \ + trace = M_MATRIX; \ + score = M_row[i-1][j-1]; \ + temp = Ix_row[i-1][j-1]; \ + if (temp > score + epsilon) { \ + score = temp; \ + trace = Ix_MATRIX; \ + } \ + else if (temp > score - epsilon) trace |= Ix_MATRIX; \ + temp = Iy_row[i-1][j-1]; \ + if (temp > score + epsilon) { \ + score = temp; \ + trace = Iy_MATRIX; \ + } \ + else if (temp > score - epsilon) trace |= Iy_MATRIX; \ + M_row[i][j] = score + score4; \ + M[i][j].trace = trace; + +#define SELECT_TRACE_WATERMAN_SMITH_BEYER_GAP(score1, score2) \ + temp = score1 + gapscore; \ + if (temp > score - epsilon) { \ + if (temp > score + epsilon) { \ + score = temp; \ + nm = 0; \ + ng = 0; \ + } \ + gapM[nm] = gap; \ + nm++; \ + } \ + temp = score2 + gapscore; \ + if (temp > score - epsilon) { \ + if (temp > score + epsilon) { \ + score = temp; \ + nm = 0; \ + ng = 0; \ + } \ + gapXY[ng] = gap; \ + ng++; \ + } + +#define SELECT_TRACE_WATERMAN_SMITH_BEYER_ALIGN(score1, score2, score3, score4) \ + trace = M_MATRIX; \ + score = score1; \ + if (score2 > score + epsilon) { \ + score = score2; \ + trace = Ix_MATRIX; \ + } \ + else if (score2 > score - epsilon) trace |= Ix_MATRIX; \ + if (score3 > score + epsilon) { \ + score = score3; \ + trace = Iy_MATRIX; \ + } \ + else if (score3 > score - epsilon) trace |= Iy_MATRIX; \ + score += score4; \ + if (score < epsilon) { \ + score = 0; \ + trace = STARTPOINT; \ + } \ + else if (score > maximum - epsilon) { \ + if (score > maximum + epsilon) { \ + maximum = score; \ + for ( ; im < i; im++, jm = 0) \ + for ( ; jm <= nB; jm++) M[im][jm].trace &= ~ENDPOINT; \ + for ( ; jm < j; jm++) M[im][jm].trace &= ~ENDPOINT; \ + im = i; \ + jm = j; \ + } \ + trace |= ENDPOINT; \ + } \ + M_row[i][j] = score; \ + M[i][j].trace = trace; + +struct fogsaa_cell { + double present_score, lower, upper; + int type, filled, is_left_gap; +}; + +struct fogsaa_queue { + struct fogsaa_queue_node *array; + int size, capacity; +}; + +struct fogsaa_queue_node { + int pA, pB, type_upto_next, next_type; + double next_lower, next_upper; +}; + +#define MATRIX(a, b) matrix[a * (nB+1) + b] + +#define FOGSAA_SORT() \ + for (i = 0; i < 2; i++) { \ + for (j = 0; j < 2 - i; j++) { \ + if ((child_lbounds[j] < child_lbounds[j + 1]) || ((child_lbounds[j] == child_lbounds[j + 1]) && (child_ubounds[j] < child_ubounds[j + 1]))) { \ + t = child_lbounds[j]; \ + child_lbounds[j] = child_lbounds[j + 1]; \ + child_lbounds[j + 1] = t; \ + \ + t = child_types[j]; \ + child_types[j] = child_types[j + 1]; \ + child_types[j + 1] = t; \ + \ + t = child_ubounds[j]; \ + child_ubounds[j] = child_ubounds[j + 1]; \ + child_ubounds[j + 1] = t; \ + } \ + } \ + } + +/* This doesn't always work if the gap score is less than the mismatch score */ +#define FOGSAA_CALCULATE_SCORE(curr_score, curr_type, lower, upper, pA, pB) \ + if (nA - (pA) <= nB - (pB)) { \ + if (pA == nA && (curr_type) == HORIZONTAL) { \ + /* If we're already at the end and a gap is already open */ \ + lower = curr_score + right_gap_extend_A * (nB - (pB)); \ + upper = curr_score + right_gap_extend_A * (nB - (pB)); \ + } else { \ + lower = curr_score + (nA - (pA)) * mismatch; \ + upper = curr_score + (nA - (pA)) * match; \ + t = right_gap_open_A + right_gap_extend_A * ((nB - (pB)) - (nA - (pA)) - 1); \ + t2 = gap_extend_A * ((nB - (pB)) - (nA - (pA))); \ + if ((curr_type) == HORIZONTAL && t2 > t) { \ + /* if we already have a gap open, then we can just extend */ \ + /* from the open gap and match/mismatch later. we don't */ \ + /* need to open a new one */ \ + lower += t2; \ + upper += t2; \ + } else { \ + lower += t; \ + upper += t; \ + } \ + } \ + } else { \ + if (pB == nB && (curr_type) == VERTICAL) { \ + /* If we're already at the end and a gap is already open */ \ + lower = curr_score + right_gap_extend_B * (nA - (pA)); \ + upper = curr_score + right_gap_extend_B * (nA - (pA)); \ + } else { \ + lower = curr_score + (nB - (pB)) * mismatch; \ + upper = curr_score + (nB - (pB)) * match; \ + t = right_gap_open_B + right_gap_extend_B * ((nA - (pA)) - (nB - (pB)) - 1); \ + t2 = gap_extend_B * ((nA - (pA)) - (nB - (pB))); \ + if ((curr_type) == VERTICAL && t2 > t) { \ + /* if we already have a gap open, then we can just extend */ \ + /* from the open gap and match/mismatch later. we don't */ \ + /* need to open a new one */ \ + lower += t2; \ + upper += t2; \ + } else { \ + lower += t; \ + upper += t; \ + } \ + } \ + } + +// node has higher priority if upper bound is higher, or if upper bounds are +// equal, if lower bound is higher +#define FOGSAA_QUEUE_HEAP_COND(a, b) \ + (queue->array[a].next_upper > queue->array[b].next_upper || \ + (queue->array[a].next_upper == queue->array[b].next_upper && \ + queue->array[a].next_lower > queue->array[b].next_lower)) + +static int +fogsaa_queue_insert(struct fogsaa_queue *queue, int pA, int pB, + int type_total, int next_type, double next_lower, double next_upper) { + // max heap implementation for the priority queue by next_upper + struct fogsaa_queue_node temp; + int i; + + if (queue->size + 1 >= queue->capacity) { + struct fogsaa_queue_node *old_array = queue->array; + queue->array = PyMem_Realloc(queue->array, + sizeof(struct fogsaa_queue_node) * (queue->capacity + 1) * 2); + if (queue->array == NULL) { + PyMem_Free(old_array); + return 0; // caller should return PyErr_NoMemory(); + } + queue->capacity = (queue->capacity + 1) * 2; + } + + i = queue->size; + queue->array[i].pA = pA; + queue->array[i].pB = pB; + queue->array[i].next_type = next_type; + queue->array[i].next_lower = next_lower; + queue->array[i].type_upto_next = type_total; + queue->array[i].next_upper = next_upper; + + while (i != 0 && !FOGSAA_QUEUE_HEAP_COND((i-1)/2, i)) { + // swap the child and the smaller parent + temp = queue->array[i]; + queue->array[i] = queue->array[(i-1)/2]; + queue->array[(i-1)/2] = temp; + i = (i-1)/2; + } + queue->size += 1; + return 1; +} + +static struct fogsaa_queue_node fogsaa_queue_pop(struct fogsaa_queue *queue) { + // caller code must check queue is not empty + struct fogsaa_queue_node temp, root = queue->array[0]; + int largest_child, i = 0; + queue->size -= 1; + queue->array[i] = queue->array[queue->size]; + while (1) { + largest_child = i; + if (2*i+1 < queue->size && !FOGSAA_QUEUE_HEAP_COND(i, 2*i+1)) + largest_child = 2*i+1; + if (2*i+2 < queue->size && !FOGSAA_QUEUE_HEAP_COND(largest_child, 2*i+2)) + largest_child = 2*i+2; + if (largest_child != i) { + // swap the parent and the larger child + temp = queue->array[i]; + queue->array[i] = queue->array[largest_child]; + queue->array[largest_child] = temp; + i = largest_child; + } else { + break; + } + } + return root; +} + +/* ----------------- alignment algorithms ----------------- */ + +#define NEEDLEMANWUNSCH_SCORE(align_score) \ + int i; \ + int j; \ + int kA; \ + int kB; \ + const double gap_extend_A = self->extend_internal_insertion_score; \ + const double gap_extend_B = self->extend_internal_deletion_score; \ + double score; \ + double temp; \ + double* row; \ + double left_gap_extend_A; \ + double right_gap_extend_A; \ + double left_gap_extend_B; \ + double right_gap_extend_B; \ + switch (strand) { \ + case '+': \ + left_gap_extend_A = self->extend_left_insertion_score; \ + right_gap_extend_A = self->extend_right_insertion_score; \ + left_gap_extend_B = self->extend_left_deletion_score; \ + right_gap_extend_B = self->extend_right_deletion_score; \ + break; \ + case '-': \ + left_gap_extend_A = self->extend_right_insertion_score; \ + right_gap_extend_A = self->extend_left_insertion_score; \ + left_gap_extend_B = self->extend_right_deletion_score; \ + right_gap_extend_B = self->extend_left_deletion_score; \ + break; \ + default: \ + PyErr_SetString(PyExc_RuntimeError, "strand was neither '+' nor '-'"); \ + return NULL; \ + } \ +\ + /* Needleman-Wunsch algorithm */ \ + row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!row) return PyErr_NoMemory(); \ +\ + /* The top row of the score matrix is a special case, \ + * as there are no previously aligned characters. \ + */ \ + row[0] = 0.0; \ + for (j = 1; j <= nB; j++) row[j] = j * left_gap_extend_A; \ + for (i = 1; i < nA; i++) { \ + kA = sA[i-1]; \ + temp = row[0]; \ + row[0] = i * left_gap_extend_B; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_SCORE_GLOBAL(temp + (align_score), \ + row[j] + gap_extend_B, \ + row[j-1] + gap_extend_A); \ + temp = row[j]; \ + row[j] = score; \ + } \ + kB = sB[nB-1]; \ + SELECT_SCORE_GLOBAL(temp + (align_score), \ + row[nB] + right_gap_extend_B, \ + row[nB-1] + gap_extend_A); \ + temp = row[nB]; \ + row[nB] = score; \ + } \ + kA = sA[nA-1]; \ + temp = row[0]; \ + row[0] = nA * right_gap_extend_B; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_SCORE_GLOBAL(temp + (align_score), \ + row[j] + gap_extend_B, \ + row[j-1] + right_gap_extend_A); \ + temp = row[j]; \ + row[j] = score; \ + } \ + kB = sB[nB-1]; \ + SELECT_SCORE_GLOBAL(temp + (align_score), \ + row[nB] + right_gap_extend_B, \ + row[nB-1] + right_gap_extend_A); \ + PyMem_Free(row); \ + return PyFloat_FromDouble(score); + + +#define SMITHWATERMAN_SCORE(align_score) \ + int i; \ + int j; \ + int kA; \ + int kB; \ + const double gap_extend_A = self->extend_internal_insertion_score; \ + const double gap_extend_B = self->extend_internal_deletion_score; \ + double score; \ + double* row; \ + double temp; \ + double maximum = 0; \ +\ + /* Smith-Waterman algorithm */ \ + row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!row) return PyErr_NoMemory(); \ +\ + /* The top row of the score matrix is a special case, \ + * as there are no previously aligned characters. \ + */ \ + for (j = 0; j <= nB; j++) \ + row[j] = 0; \ + for (i = 1; i < nA; i++) { \ + kA = sA[i-1]; \ + temp = 0; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_SCORE_LOCAL3(temp + (align_score), \ + row[j] + gap_extend_B, \ + row[j-1] + gap_extend_A); \ + temp = row[j]; \ + row[j] = score; \ + } \ + kB = sB[nB-1]; \ + SELECT_SCORE_LOCAL1(temp + (align_score)); \ + temp = row[nB]; \ + row[nB] = score; \ + } \ + kA = sA[nA-1]; \ + temp = 0; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_SCORE_LOCAL1(temp + (align_score)); \ + temp = row[j]; \ + row[j] = score; \ + } \ + kB = sB[nB-1]; \ + SELECT_SCORE_LOCAL1(temp + (align_score)); \ + PyMem_Free(row); \ + return PyFloat_FromDouble(maximum); + + +#define NEEDLEMANWUNSCH_ALIGN(align_score) \ + int i; \ + int j; \ + int kA; \ + int kB; \ + const double gap_extend_A = self->extend_internal_insertion_score; \ + const double gap_extend_B = self->extend_internal_deletion_score; \ + const double epsilon = self->epsilon; \ + Trace** M; \ + double score; \ + int trace; \ + double temp; \ + double* row = NULL; \ + PathGenerator* paths; \ + double left_gap_extend_A; \ + double right_gap_extend_A; \ + double left_gap_extend_B; \ + double right_gap_extend_B; \ + switch (strand) { \ + case '+': \ + left_gap_extend_A = self->extend_left_insertion_score; \ + right_gap_extend_A = self->extend_right_insertion_score; \ + left_gap_extend_B = self->extend_left_deletion_score; \ + right_gap_extend_B = self->extend_right_deletion_score; \ + break; \ + case '-': \ + left_gap_extend_A = self->extend_right_insertion_score; \ + right_gap_extend_A = self->extend_left_insertion_score; \ + left_gap_extend_B = self->extend_right_deletion_score; \ + right_gap_extend_B = self->extend_left_deletion_score; \ + break; \ + default: \ + PyErr_SetString(PyExc_RuntimeError, "strand was neither '+' nor '-'"); \ + return NULL; \ + } \ +\ + /* Needleman-Wunsch algorithm */ \ + paths = PathGenerator_create_NWSW(nA, nB, Global, strand); \ + if (!paths) return NULL; \ + row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!row) { \ + Py_DECREF(paths); \ + return PyErr_NoMemory(); \ + } \ + M = paths->M; \ + row[0] = 0; \ + for (j = 1; j <= nB; j++) row[j] = j * left_gap_extend_A; \ + for (i = 1; i < nA; i++) { \ + temp = row[0]; \ + row[0] = i * left_gap_extend_B; \ + kA = sA[i-1]; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_TRACE_NEEDLEMAN_WUNSCH(gap_extend_A, gap_extend_B, align_score); \ + } \ + kB = sB[j-1]; \ + SELECT_TRACE_NEEDLEMAN_WUNSCH(gap_extend_A, right_gap_extend_B, align_score); \ + } \ + temp = row[0]; \ + row[0] = i * left_gap_extend_B; \ + kA = sA[nA-1]; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_TRACE_NEEDLEMAN_WUNSCH(right_gap_extend_A, gap_extend_B, align_score); \ + } \ + kB = sB[j-1]; \ + SELECT_TRACE_NEEDLEMAN_WUNSCH(right_gap_extend_A, right_gap_extend_B, align_score); \ + PyMem_Free(row); \ + M[nA][nB].path = 0; \ + return Py_BuildValue("fN", score, paths); + + +#define SMITHWATERMAN_ALIGN(align_score) \ + int i; \ + int j; \ + int im = nA; \ + int jm = nB; \ + int kA; \ + int kB; \ + const double gap_extend_A = self->extend_internal_insertion_score; \ + const double gap_extend_B = self->extend_internal_deletion_score; \ + const double epsilon = self->epsilon; \ + Trace** M = NULL; \ + double maximum = 0; \ + double score = 0; \ + double* row = NULL; \ + double temp; \ + int trace; \ + PathGenerator* paths = NULL; \ +\ + /* Smith-Waterman algorithm */ \ + paths = PathGenerator_create_NWSW(nA, nB, Local, strand); \ + if (!paths) return NULL; \ + row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!row) { \ + Py_DECREF(paths); \ + return PyErr_NoMemory(); \ + } \ + M = paths->M; \ + for (j = 0; j <= nB; j++) row[j] = 0; \ + for (i = 1; i < nA; i++) { \ + temp = 0; \ + kA = sA[i-1]; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_TRACE_SMITH_WATERMAN_HVD(align_score); \ + } \ + kB = sB[nB-1]; \ + SELECT_TRACE_SMITH_WATERMAN_D(align_score); \ + } \ + temp = 0; \ + kA = sA[nA-1]; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_TRACE_SMITH_WATERMAN_D(align_score); \ + } \ + kB = sB[nB-1]; \ + SELECT_TRACE_SMITH_WATERMAN_D(align_score); \ + PyMem_Free(row); \ +\ + /* As we don't allow zero-score extensions to alignments, \ + * we need to remove all traces towards an ENDPOINT. \ + * In addition, some points then won't have any path to a STARTPOINT. \ + * Here, use path as a temporary variable to indicate if the point \ + * is reachable from a STARTPOINT. If it is unreachable, remove all \ + * traces from it, and don't allow it to be an ENDPOINT. It may still \ + * be a valid STARTPOINT. */ \ + for (j = 0; j <= nB; j++) M[0][j].path = 1; \ + for (i = 1; i <= nA; i++) { \ + M[i][0].path = 1; \ + for (j = 1; j <= nB; j++) { \ + trace = M[i][j].trace; \ + /* Remove traces to unreachable points. */ \ + if (!M[i-1][j-1].path) trace &= ~DIAGONAL; \ + if (!M[i][j-1].path) trace &= ~HORIZONTAL; \ + if (!M[i-1][j].path) trace &= ~VERTICAL; \ + if (trace & (STARTPOINT | HORIZONTAL | VERTICAL | DIAGONAL)) { \ + /* The point is reachable. */ \ + if (trace & ENDPOINT) M[i][j].path = 0; /* no extensions after ENDPOINT */ \ + else M[i][j].path = 1; \ + } \ + else { \ + /* The point is not reachable. Then it is not a STARTPOINT, \ + * all traces from it can be removed, and it cannot act as \ + * an ENDPOINT. */ \ + M[i][j].path = 0; \ + trace = 0; \ + } \ + M[i][j].trace = trace; \ + } \ + } \ + if (maximum == 0) M[0][0].path = NONE; \ + else M[0][0].path = 0; \ + return Py_BuildValue("fN", maximum, paths); + + +#define GOTOH_GLOBAL_SCORE(align_score) \ + int i; \ + int j; \ + int kA; \ + int kB; \ + const double gap_open_A = self->open_internal_insertion_score; \ + const double gap_open_B = self->open_internal_deletion_score; \ + const double gap_extend_A = self->extend_internal_insertion_score; \ + const double gap_extend_B = self->extend_internal_deletion_score; \ + double left_gap_open_A; \ + double left_gap_open_B; \ + double left_gap_extend_A; \ + double left_gap_extend_B; \ + double right_gap_open_A; \ + double right_gap_open_B; \ + double right_gap_extend_A; \ + double right_gap_extend_B; \ + double* M_row = NULL; \ + double* Ix_row = NULL; \ + double* Iy_row = NULL; \ + double score; \ + double temp; \ + double M_temp; \ + double Ix_temp; \ + double Iy_temp; \ + switch (strand) { \ + case '+': \ + left_gap_open_A = self->open_left_insertion_score; \ + left_gap_open_B = self->open_left_deletion_score; \ + left_gap_extend_A = self->extend_left_insertion_score; \ + left_gap_extend_B = self->extend_left_deletion_score; \ + right_gap_open_A = self->open_right_insertion_score; \ + right_gap_open_B = self->open_right_deletion_score; \ + right_gap_extend_A = self->extend_right_insertion_score; \ + right_gap_extend_B = self->extend_right_deletion_score; \ + break; \ + case '-': \ + left_gap_open_A = self->open_right_insertion_score; \ + left_gap_open_B = self->open_right_deletion_score; \ + left_gap_extend_A = self->extend_right_insertion_score; \ + left_gap_extend_B = self->extend_right_deletion_score; \ + right_gap_open_A = self->open_left_insertion_score; \ + right_gap_open_B = self->open_left_deletion_score; \ + right_gap_extend_A = self->extend_left_insertion_score; \ + right_gap_extend_B = self->extend_left_deletion_score; \ + break; \ + default: \ + PyErr_SetString(PyExc_RuntimeError, "strand was neither '+' nor '-'"); \ + return NULL; \ + } \ +\ + /* Gotoh algorithm with three states */ \ + M_row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!M_row) goto exit; \ + Ix_row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!Ix_row) goto exit; \ + Iy_row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!Iy_row) goto exit; \ +\ + /* The top row of the score matrix is a special case, \ + * as there are no previously aligned characters. \ + */ \ + M_row[0] = 0; \ + Ix_row[0] = -DBL_MAX; \ + Iy_row[0] = -DBL_MAX; \ + for (j = 1; j <= nB; j++) { \ + M_row[j] = -DBL_MAX; \ + Ix_row[j] = -DBL_MAX; \ + Iy_row[j] = left_gap_open_A + left_gap_extend_A * (j-1); \ + } \ +\ + for (i = 1; i < nA; i++) { \ + M_temp = M_row[0]; \ + Ix_temp = Ix_row[0]; \ + Iy_temp = Iy_row[0]; \ + M_row[0] = -DBL_MAX; \ + Ix_row[0] = left_gap_open_B + left_gap_extend_B * (i-1); \ + Iy_row[0] = -DBL_MAX; \ + kA = sA[i-1]; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_SCORE_GLOBAL(M_temp, \ + Ix_temp, \ + Iy_temp); \ + M_temp = M_row[j]; \ + M_row[j] = score + (align_score); \ + SELECT_SCORE_GLOBAL(M_temp + gap_open_B, \ + Ix_row[j] + gap_extend_B, \ + Iy_row[j] + gap_open_B); \ + Ix_temp = Ix_row[j]; \ + Ix_row[j] = score; \ + SELECT_SCORE_GLOBAL(M_row[j-1] + gap_open_A, \ + Ix_row[j-1] + gap_open_A, \ + Iy_row[j-1] + gap_extend_A); \ + Iy_temp = Iy_row[j]; \ + Iy_row[j] = score; \ + } \ + kB = sB[nB-1]; \ + SELECT_SCORE_GLOBAL(M_temp, \ + Ix_temp, \ + Iy_temp); \ + M_temp = M_row[nB]; \ + M_row[nB] = score + (align_score); \ + SELECT_SCORE_GLOBAL(M_temp + right_gap_open_B, \ + Ix_row[nB] + right_gap_extend_B, \ + Iy_row[nB] + right_gap_open_B); \ + Ix_row[nB] = score; \ + SELECT_SCORE_GLOBAL(M_row[nB-1] + gap_open_A, \ + Iy_row[nB-1] + gap_extend_A, \ + Ix_row[nB-1] + gap_open_A); \ + Iy_row[nB] = score; \ + } \ +\ + M_temp = M_row[0]; \ + Ix_temp = Ix_row[0]; \ + Iy_temp = Iy_row[0]; \ + M_row[0] = -DBL_MAX; \ + Ix_row[0] = left_gap_open_B + left_gap_extend_B * (i-1); \ + Iy_row[0] = -DBL_MAX; \ + kA = sA[nA-1]; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_SCORE_GLOBAL(M_temp, \ + Ix_temp, \ + Iy_temp); \ + M_temp = M_row[j]; \ + M_row[j] = score + (align_score); \ + SELECT_SCORE_GLOBAL(M_temp + gap_open_B, \ + Ix_row[j] + gap_extend_B, \ + Iy_row[j] + gap_open_B); \ + Ix_temp = Ix_row[j]; \ + Ix_row[j] = score; \ + SELECT_SCORE_GLOBAL(M_row[j-1] + right_gap_open_A, \ + Iy_row[j-1] + right_gap_extend_A, \ + Ix_row[j-1] + right_gap_open_A); \ + Iy_temp = Iy_row[j]; \ + Iy_row[j] = score; \ + } \ +\ + kB = sB[nB-1]; \ + SELECT_SCORE_GLOBAL(M_temp, \ + Ix_temp, \ + Iy_temp); \ + M_temp = M_row[nB]; \ + M_row[nB] = score + (align_score); \ + SELECT_SCORE_GLOBAL(M_temp + right_gap_open_B, \ + Ix_row[nB] + right_gap_extend_B, \ + Iy_row[nB] + right_gap_open_B); \ + Ix_temp = Ix_row[nB]; \ + Ix_row[nB] = score; \ + SELECT_SCORE_GLOBAL(M_row[nB-1] + right_gap_open_A, \ + Ix_row[nB-1] + right_gap_open_A, \ + Iy_row[nB-1] + right_gap_extend_A); \ + Iy_temp = Iy_row[nB]; \ + Iy_row[nB] = score; \ +\ + SELECT_SCORE_GLOBAL(M_row[nB], Ix_row[nB], Iy_row[nB]); \ + PyMem_Free(M_row); \ + PyMem_Free(Ix_row); \ + PyMem_Free(Iy_row); \ + return PyFloat_FromDouble(score); \ +\ +exit: \ + if (M_row) PyMem_Free(M_row); \ + if (Ix_row) PyMem_Free(Ix_row); \ + if (Iy_row) PyMem_Free(Iy_row); \ + return PyErr_NoMemory(); \ + + +#define GOTOH_LOCAL_SCORE(align_score) \ + int i; \ + int j; \ + int kA; \ + int kB; \ + const double gap_open_A = self->open_internal_insertion_score; \ + const double gap_open_B = self->open_internal_deletion_score; \ + const double gap_extend_A = self->extend_internal_insertion_score; \ + const double gap_extend_B = self->extend_internal_deletion_score; \ + double* M_row = NULL; \ + double* Ix_row = NULL; \ + double* Iy_row = NULL; \ + double score; \ + double temp; \ + double M_temp; \ + double Ix_temp; \ + double Iy_temp; \ + double maximum = 0.0; \ +\ + /* Gotoh algorithm with three states */ \ + M_row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!M_row) goto exit; \ + Ix_row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!Ix_row) goto exit; \ + Iy_row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!Iy_row) goto exit; \ + \ + /* The top row of the score matrix is a special case, \ + * as there are no previously aligned characters. \ + */ \ + M_row[0] = 0; \ + Ix_row[0] = -DBL_MAX; \ + Iy_row[0] = -DBL_MAX; \ + for (j = 1; j <= nB; j++) { \ + M_row[j] = -DBL_MAX; \ + Ix_row[j] = -DBL_MAX; \ + Iy_row[j] = 0; \ + } \ + for (i = 1; i < nA; i++) { \ + M_temp = M_row[0]; \ + Ix_temp = Ix_row[0]; \ + Iy_temp = Iy_row[0]; \ + M_row[0] = -DBL_MAX; \ + Ix_row[0] = 0; \ + Iy_row[0] = -DBL_MAX; \ + kA = sA[i-1]; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_SCORE_GOTOH_LOCAL_ALIGN(M_temp, \ + Ix_temp, \ + Iy_temp, \ + (align_score)); \ + M_temp = M_row[j]; \ + M_row[j] = score; \ + SELECT_SCORE_LOCAL3(M_temp + gap_open_B, \ + Ix_row[j] + gap_extend_B, \ + Iy_row[j] + gap_open_B); \ + Ix_temp = Ix_row[j]; \ + Ix_row[j] = score; \ + SELECT_SCORE_LOCAL3(M_row[j-1] + gap_open_A, \ + Ix_row[j-1] + gap_open_A, \ + Iy_row[j-1] + gap_extend_A); \ + Iy_temp = Iy_row[j]; \ + Iy_row[j] = score; \ + } \ + kB = sB[nB-1]; \ + Ix_row[nB] = 0; \ + Iy_row[nB] = 0; \ + SELECT_SCORE_GOTOH_LOCAL_ALIGN(M_temp, \ + Ix_temp, \ + Iy_temp, \ + (align_score)); \ + M_temp = M_row[nB]; \ + M_row[nB] = score; \ + } \ + M_temp = M_row[0]; \ + Ix_temp = Ix_row[0]; \ + Iy_temp = Iy_row[0]; \ + M_row[0] = -DBL_MAX; \ + Ix_row[0] = 0; \ + Iy_row[0] = -DBL_MAX; \ + kA = sA[nA-1]; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_SCORE_GOTOH_LOCAL_ALIGN(M_temp, \ + Ix_temp, \ + Iy_temp, \ + (align_score)); \ + M_temp = M_row[j]; \ + M_row[j] = score; \ + Ix_temp = Ix_row[j]; \ + Iy_temp = Iy_row[j]; \ + Ix_row[j] = 0; \ + Iy_row[j] = 0; \ + } \ + kB = sB[nB-1]; \ + SELECT_SCORE_GOTOH_LOCAL_ALIGN(M_temp, \ + Ix_temp, \ + Iy_temp, \ + (align_score)); \ + PyMem_Free(M_row); \ + PyMem_Free(Ix_row); \ + PyMem_Free(Iy_row); \ + return PyFloat_FromDouble(maximum); \ +exit: \ + if (M_row) PyMem_Free(M_row); \ + if (Ix_row) PyMem_Free(Ix_row); \ + if (Iy_row) PyMem_Free(Iy_row); \ + return PyErr_NoMemory(); \ + + +#define GOTOH_GLOBAL_ALIGN(align_score) \ + int i; \ + int j; \ + int kA; \ + int kB; \ + const double gap_open_A = self->open_internal_insertion_score; \ + const double gap_open_B = self->open_internal_deletion_score; \ + const double gap_extend_A = self->extend_internal_insertion_score; \ + const double gap_extend_B = self->extend_internal_deletion_score; \ + double left_gap_open_A; \ + double left_gap_open_B; \ + double left_gap_extend_A; \ + double left_gap_extend_B; \ + double right_gap_open_A; \ + double right_gap_open_B; \ + double right_gap_extend_A; \ + double right_gap_extend_B; \ + const double epsilon = self->epsilon; \ + TraceGapsGotoh** gaps = NULL; \ + Trace** M = NULL; \ + double* M_row = NULL; \ + double* Ix_row = NULL; \ + double* Iy_row = NULL; \ + double score; \ + int trace; \ + double temp; \ + double M_temp; \ + double Ix_temp; \ + double Iy_temp; \ + PathGenerator* paths; \ + switch (strand) { \ + case '+': \ + left_gap_open_A = self->open_left_insertion_score; \ + left_gap_open_B = self->open_left_deletion_score; \ + left_gap_extend_A = self->extend_left_insertion_score; \ + left_gap_extend_B = self->extend_left_deletion_score; \ + right_gap_open_A = self->open_right_insertion_score; \ + right_gap_open_B = self->open_right_deletion_score; \ + right_gap_extend_A = self->extend_right_insertion_score; \ + right_gap_extend_B = self->extend_right_deletion_score; \ + break; \ + case '-': \ + left_gap_open_A = self->open_right_insertion_score; \ + left_gap_open_B = self->open_right_deletion_score; \ + left_gap_extend_A = self->extend_right_insertion_score; \ + left_gap_extend_B = self->extend_right_deletion_score; \ + right_gap_open_A = self->open_left_insertion_score; \ + right_gap_open_B = self->open_left_deletion_score; \ + right_gap_extend_A = self->extend_left_insertion_score; \ + right_gap_extend_B = self->extend_left_deletion_score; \ + break; \ + default: \ + PyErr_SetString(PyExc_RuntimeError, "strand was neither '+' nor '-'"); \ + return NULL; \ + } \ +\ + /* Gotoh algorithm with three states */ \ + paths = PathGenerator_create_Gotoh(nA, nB, Global, strand); \ + if (!paths) return NULL; \ + M_row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!M_row) goto exit; \ + Ix_row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!Ix_row) goto exit; \ + Iy_row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!Iy_row) goto exit; \ + M = paths->M; \ + gaps = paths->gaps.gotoh; \ + \ + /* Gotoh algorithm with three states */ \ + M_row[0] = 0; \ + Ix_row[0] = -DBL_MAX; \ + Iy_row[0] = -DBL_MAX; \ + for (j = 1; j <= nB; j++) { \ + M_row[j] = -DBL_MAX; \ + Ix_row[j] = -DBL_MAX; \ + Iy_row[j] = left_gap_open_A + left_gap_extend_A * (j-1); \ + } \ + for (i = 1; i < nA; i++) { \ + kA = sA[i-1]; \ + M_temp = M_row[0]; \ + Ix_temp = Ix_row[0]; \ + Iy_temp = Iy_row[0]; \ + M_row[0] = -DBL_MAX; \ + Ix_row[0] = left_gap_open_B + left_gap_extend_B * (i-1); \ + Iy_row[0] = -DBL_MAX; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_TRACE_GOTOH_GLOBAL_ALIGN; \ + M_temp = M_row[j]; \ + M_row[j] = score + (align_score); \ + SELECT_TRACE_GOTOH_GLOBAL_GAP(Ix, \ + M_temp + gap_open_B, \ + Ix_row[j] + gap_extend_B, \ + Iy_row[j] + gap_open_B); \ + Ix_temp = Ix_row[j]; \ + Ix_row[j] = score; \ + SELECT_TRACE_GOTOH_GLOBAL_GAP(Iy, \ + M_row[j-1] + gap_open_A, \ + Ix_row[j-1] + gap_open_A, \ + Iy_row[j-1] + gap_extend_A); \ + Iy_temp = Iy_row[j]; \ + Iy_row[j] = score; \ + } \ + kB = sB[nB-1]; \ + SELECT_TRACE_GOTOH_GLOBAL_ALIGN; \ + M_temp = M_row[nB]; \ + M_row[nB] = score + (align_score); \ + SELECT_TRACE_GOTOH_GLOBAL_GAP(Ix, \ + M_temp + right_gap_open_B, \ + Ix_row[nB] + right_gap_extend_B, \ + Iy_row[nB] + right_gap_open_B); \ + Ix_temp = Ix_row[nB]; \ + Ix_row[nB] = score; \ + SELECT_TRACE_GOTOH_GLOBAL_GAP(Iy, \ + M_row[nB-1] + gap_open_A, \ + Ix_row[nB-1] + gap_open_A, \ + Iy_row[nB-1] + gap_extend_A); \ + Iy_temp = Iy_row[nB]; \ + Iy_row[nB] = score; \ + } \ + kA = sA[nA-1]; \ + M_temp = M_row[0]; \ + Ix_temp = Ix_row[0]; \ + Iy_temp = Iy_row[0]; \ + M_row[0] = -DBL_MAX; \ + Ix_row[0] = left_gap_open_B + left_gap_extend_B * (nA-1); \ + Iy_row[0] = -DBL_MAX; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_TRACE_GOTOH_GLOBAL_ALIGN; \ + M_temp = M_row[j]; \ + M_row[j] = score + (align_score); \ + SELECT_TRACE_GOTOH_GLOBAL_GAP(Ix, \ + M_temp + gap_open_B, \ + Ix_row[j] + gap_extend_B, \ + Iy_row[j] + gap_open_B); \ + Ix_temp = Ix_row[j]; \ + Ix_row[j] = score; \ + SELECT_TRACE_GOTOH_GLOBAL_GAP(Iy, \ + M_row[j-1] + right_gap_open_A, \ + Ix_row[j-1] + right_gap_open_A, \ + Iy_row[j-1] + right_gap_extend_A); \ + Iy_temp = Iy_row[j]; \ + Iy_row[j] = score; \ + } \ + kB = sB[nB-1]; \ + SELECT_TRACE_GOTOH_GLOBAL_ALIGN; \ + M_temp = M_row[j]; \ + M_row[j] = score + (align_score); \ + SELECT_TRACE_GOTOH_GLOBAL_GAP(Ix, \ + M_temp + right_gap_open_B, \ + Ix_row[j] + right_gap_extend_B, \ + Iy_row[j] + right_gap_open_B); \ + Ix_row[nB] = score; \ + SELECT_TRACE_GOTOH_GLOBAL_GAP(Iy, \ + M_row[j-1] + right_gap_open_A, \ + Ix_row[j-1] + right_gap_open_A, \ + Iy_row[j-1] + right_gap_extend_A); \ + Iy_row[nB] = score; \ + M[nA][nB].path = 0; \ + \ + /* traceback */ \ + SELECT_SCORE_GLOBAL(M_row[nB], Ix_row[nB], Iy_row[nB]); \ + if (M_row[nB] < score - epsilon) M[nA][nB].trace = 0; \ + if (Ix_row[nB] < score - epsilon) gaps[nA][nB].Ix = 0; \ + if (Iy_row[nB] < score - epsilon) gaps[nA][nB].Iy = 0; \ + PyMem_Free(M_row); \ + PyMem_Free(Ix_row); \ + PyMem_Free(Iy_row); \ + return Py_BuildValue("fN", score, paths); \ +exit: \ + Py_DECREF(paths); \ + if (M_row) PyMem_Free(M_row); \ + if (Ix_row) PyMem_Free(Ix_row); \ + if (Iy_row) PyMem_Free(Iy_row); \ + return PyErr_NoMemory(); \ + + +#define GOTOH_LOCAL_ALIGN(align_score) \ + int i; \ + int j; \ + int im = nA; \ + int jm = nB; \ + int kA; \ + int kB; \ + const double gap_open_A = self->open_internal_insertion_score; \ + const double gap_open_B = self->open_internal_deletion_score; \ + const double gap_extend_A = self->extend_internal_insertion_score; \ + const double gap_extend_B = self->extend_internal_deletion_score; \ + const double epsilon = self->epsilon; \ + Trace** M = NULL; \ + TraceGapsGotoh** gaps = NULL; \ + double* M_row = NULL; \ + double* Ix_row = NULL; \ + double* Iy_row = NULL; \ + double score; \ + int trace; \ + double temp; \ + double M_temp; \ + double Ix_temp; \ + double Iy_temp; \ + double maximum = 0.0; \ + PathGenerator* paths; \ + \ + /* Gotoh algorithm with three states */ \ + paths = PathGenerator_create_Gotoh(nA, nB, Local, strand); \ + if (!paths) return NULL; \ + M = paths->M; \ + gaps = paths->gaps.gotoh; \ + M_row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!M_row) goto exit; \ + Ix_row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!Ix_row) goto exit; \ + Iy_row = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!Iy_row) goto exit; \ + M_row[0] = 0; \ + Ix_row[0] = -DBL_MAX; \ + Iy_row[0] = -DBL_MAX; \ + for (j = 1; j <= nB; j++) { \ + M_row[j] = 0; \ + Ix_row[j] = -DBL_MAX; \ + Iy_row[j] = -DBL_MAX; \ + } \ + for (i = 1; i < nA; i++) { \ + M_temp = M_row[0]; \ + Ix_temp = Ix_row[0]; \ + Iy_temp = Iy_row[0]; \ + M_row[0] = 0; \ + Ix_row[0] = -DBL_MAX; \ + Iy_row[0] = -DBL_MAX; \ + kA = sA[i-1]; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_TRACE_GOTOH_LOCAL_ALIGN(align_score) \ + M_temp = M_row[j]; \ + M_row[j] = score; \ + SELECT_TRACE_GOTOH_LOCAL_GAP(Ix, \ + M_temp + gap_open_B, \ + Ix_row[j] + gap_extend_B, \ + Iy_row[j] + gap_open_B); \ + Ix_temp = Ix_row[j]; \ + Ix_row[j] = score; \ + SELECT_TRACE_GOTOH_LOCAL_GAP(Iy, \ + M_row[j-1] + gap_open_A, \ + Ix_row[j-1] + gap_open_A, \ + Iy_row[j-1] + gap_extend_A); \ + Iy_temp = Iy_row[j]; \ + Iy_row[j] = score; \ + } \ + kB = sB[nB-1]; \ + SELECT_TRACE_GOTOH_LOCAL_ALIGN(align_score) \ + M_temp = M_row[j]; \ + M_row[j] = score; \ + Ix_temp = Ix_row[nB]; \ + Ix_row[nB] = 0; \ + gaps[i][nB].Ix = 0; \ + Iy_temp = Iy_row[nB]; \ + Iy_row[nB] = 0; \ + gaps[i][nB].Iy = 0; \ + } \ + M_temp = M_row[0]; \ + M_row[0] = 0; \ + M[nA][0].trace = 0; \ + Ix_temp = Ix_row[0]; \ + Ix_row[0] = -DBL_MAX; \ + gaps[nA][0].Ix = 0; \ + gaps[nA][0].Iy = 0; \ + Iy_temp = Iy_row[0]; \ + Iy_row[0] = -DBL_MAX; \ + kA = sA[nA-1]; \ + for (j = 1; j < nB; j++) { \ + kB = sB[j-1]; \ + SELECT_TRACE_GOTOH_LOCAL_ALIGN(align_score) \ + M_temp = M_row[j]; \ + M_row[j] = score; \ + Ix_temp = Ix_row[j]; \ + Ix_row[j] = 0; \ + gaps[nA][j].Ix = 0; \ + Iy_temp = Iy_row[j]; \ + Iy_row[j] = 0; \ + gaps[nA][j].Iy = 0; \ + } \ + kB = sB[nB-1]; \ + SELECT_TRACE_GOTOH_LOCAL_ALIGN(align_score) \ + gaps[nA][nB].Ix = 0; \ + gaps[nA][nB].Iy = 0; \ +\ + PyMem_Free(M_row); \ + PyMem_Free(Ix_row); \ + PyMem_Free(Iy_row); \ +\ + /* As we don't allow zero-score extensions to alignments, \ + * we need to remove all traces towards an ENDPOINT. \ + * In addition, some points then won't have any path to a STARTPOINT. \ + * Here, use path as a temporary variable to indicate if the point \ + * is reachable from a STARTPOINT. If it is unreachable, remove all \ + * traces from it, and don't allow it to be an ENDPOINT. It may still \ + * be a valid STARTPOINT. */ \ + for (j = 0; j <= nB; j++) M[0][j].path = M_MATRIX; \ + for (i = 1; i <= nA; i++) { \ + M[i][0].path = M_MATRIX; \ + for (j = 1; j <= nB; j++) { \ + /* Remove traces to unreachable points. */ \ + trace = M[i][j].trace; \ + if (!(M[i-1][j-1].path & M_MATRIX)) trace &= ~M_MATRIX; \ + if (!(M[i-1][j-1].path & Ix_MATRIX)) trace &= ~Ix_MATRIX; \ + if (!(M[i-1][j-1].path & Iy_MATRIX)) trace &= ~Iy_MATRIX; \ + if (trace & (STARTPOINT | M_MATRIX | Ix_MATRIX | Iy_MATRIX)) { \ + /* The point is reachable. */ \ + if (trace & ENDPOINT) M[i][j].path = 0; /* no extensions after ENDPOINT */ \ + else M[i][j].path |= M_MATRIX; \ + } \ + else { \ + /* The point is not reachable. Then it is not a STARTPOINT, \ + * all traces from it can be removed, and it cannot act as \ + * an ENDPOINT. */ \ + M[i][j].path &= ~M_MATRIX; \ + trace = 0; \ + } \ + M[i][j].trace = trace; \ + trace = gaps[i][j].Ix; \ + if (!(M[i-1][j].path & M_MATRIX)) trace &= ~M_MATRIX; \ + if (!(M[i-1][j].path & Ix_MATRIX)) trace &= ~Ix_MATRIX; \ + if (!(M[i-1][j].path & Iy_MATRIX)) trace &= ~Iy_MATRIX; \ + if (trace & (M_MATRIX | Ix_MATRIX | Iy_MATRIX)) { \ + /* The point is reachable. */ \ + M[i][j].path |= Ix_MATRIX; \ + } \ + else { \ + /* The point is not reachable. Then \ + * all traces from it can be removed. */ \ + M[i][j].path &= ~Ix_MATRIX; \ + trace = 0; \ + } \ + gaps[i][j].Ix = trace; \ + trace = gaps[i][j].Iy; \ + if (!(M[i][j-1].path & M_MATRIX)) trace &= ~M_MATRIX; \ + if (!(M[i][j-1].path & Ix_MATRIX)) trace &= ~Ix_MATRIX; \ + if (!(M[i][j-1].path & Iy_MATRIX)) trace &= ~Iy_MATRIX; \ + if (trace & (M_MATRIX | Ix_MATRIX | Iy_MATRIX)) { \ + /* The point is reachable. */ \ + M[i][j].path |= Iy_MATRIX; \ + } \ + else { \ + /* The point is not reachable. Then \ + * all traces from it can be removed. */ \ + M[i][j].path &= ~Iy_MATRIX; \ + trace = 0; \ + } \ + gaps[i][j].Iy = trace; \ + } \ + } \ +\ + /* traceback */ \ + if (maximum == 0) M[0][0].path = DONE; \ + else M[0][0].path = 0; \ + return Py_BuildValue("fN", maximum, paths); \ +\ +exit: \ + Py_DECREF(paths); \ + if (M_row) PyMem_Free(M_row); \ + if (Ix_row) PyMem_Free(Ix_row); \ + if (Iy_row) PyMem_Free(Iy_row); \ + return PyErr_NoMemory(); \ + + +#define WATERMANSMITHBEYER_ENTER_SCORE \ + int i; \ + int j = 0; \ + int k; \ + int kA; \ + int kB; \ + double** M = NULL; \ + double** Ix = NULL; \ + double** Iy = NULL; \ + double score = 0.0; \ + double gapscore = 0.0; \ + double temp; \ + int ok = 1; \ + PyObject* result = NULL; \ +\ + /* Waterman-Smith-Beyer algorithm */ \ + M = PyMem_Malloc((nA+1)*sizeof(double*)); \ + if (!M) goto exit; \ + Ix = PyMem_Malloc((nA+1)*sizeof(double*)); \ + if (!Ix) goto exit; \ + Iy = PyMem_Malloc((nA+1)*sizeof(double*)); \ + if (!Iy) goto exit; \ + for (i = 0; i <= nA; i++) { \ + M[i] = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!M[i]) goto exit; \ + Ix[i] = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!Ix[i]) goto exit; \ + Iy[i] = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!Iy[i]) goto exit; \ + } \ + + +#define WATERMANSMITHBEYER_GLOBAL_SCORE(align_score, query_gap_start) \ + /* The top row of the score matrix is a special case, \ + * as there are no previously aligned characters. \ + */ \ + M[0][0] = 0; \ + Ix[0][0] = -DBL_MAX; \ + Iy[0][0] = -DBL_MAX; \ + for (i = 1; i <= nA; i++) { \ + M[i][0] = -DBL_MAX; \ + Iy[i][0] = -DBL_MAX; \ + ok = _call_deletion_score_function(self, query_gap_start, i, nB, &score); \ + if (!ok) goto exit; \ + Ix[i][0] = score; \ + } \ + for (j = 1; j <= nB; j++) { \ + M[0][j] = -DBL_MAX; \ + Ix[0][j] = -DBL_MAX; \ + ok = _call_insertion_score_function(self, 0, j, nA, &score); \ + if (!ok) goto exit; \ + Iy[0][j] = score; \ + } \ + for (i = 1; i <= nA; i++) { \ + kA = sA[i-1]; \ + for (j = 1; j <= nB; j++) { \ + kB = sB[j-1]; \ + SELECT_SCORE_GLOBAL(M[i-1][j-1], Ix[i-1][j-1], Iy[i-1][j-1]); \ + M[i][j] = score + (align_score); \ + score = -DBL_MAX; \ + for (k = 1; k <= i; k++) { \ + ok = _call_deletion_score_function(self, query_gap_start, k, nB, &gapscore); \ + if (!ok) goto exit; \ + SELECT_SCORE_WATERMAN_SMITH_BEYER(M[i-k][j], Iy[i-k][j]); \ + } \ + Ix[i][j] = score; \ + score = -DBL_MAX; \ + for (k = 1; k <= j; k++) { \ + ok = _call_insertion_score_function(self, i, k, nA, &gapscore); \ + if (!ok) goto exit; \ + SELECT_SCORE_WATERMAN_SMITH_BEYER(M[i][j-k], Ix[i][j-k]); \ + } \ + Iy[i][j] = score; \ + } \ + } \ + SELECT_SCORE_GLOBAL(M[nA][nB], Ix[nA][nB], Iy[nA][nB]); \ +\ + result = PyFloat_FromDouble(score); \ + + +#define WATERMANSMITHBEYER_LOCAL_SCORE(align_score, query_gap_start) \ + /* The top row of the score matrix is a special case, \ + * as there are no previously aligned characters. \ + */ \ + M[0][0] = 0; \ + Ix[0][0] = -DBL_MAX; \ + Iy[0][0] = -DBL_MAX; \ + for (i = 1; i <= nA; i++) { \ + M[i][0] = -DBL_MAX; \ + Ix[i][0] = 0; \ + Iy[i][0] = -DBL_MAX; \ + } \ + for (j = 1; j <= nB; j++) { \ + M[0][j] = -DBL_MAX; \ + Ix[0][j] = -DBL_MAX; \ + Iy[0][j] = 0; \ + } \ + for (i = 1; i <= nA; i++) { \ + kA = sA[i-1]; \ + for (j = 1; j <= nB; j++) { \ + kB = sB[j-1]; \ + SELECT_SCORE_GOTOH_LOCAL_ALIGN(M[i-1][j-1], \ + Ix[i-1][j-1], \ + Iy[i-1][j-1], \ + (align_score)); \ + M[i][j] = score; \ + if (i == nA || j == nB) { \ + Ix[i][j] = 0; \ + Iy[i][j] = 0; \ + continue; \ + } \ + score = 0.0; \ + for (k = 1; k <= i; k++) { \ + ok = _call_deletion_score_function(self, query_gap_start, k, nB, &gapscore); \ + SELECT_SCORE_WATERMAN_SMITH_BEYER(M[i-k][j], Iy[i-k][j]); \ + if (!ok) goto exit; \ + } \ + if (score > maximum) maximum = score; \ + Ix[i][j] = score; \ + score = 0.0; \ + for (k = 1; k <= j; k++) { \ + ok = _call_insertion_score_function(self, i, k, nA, &gapscore); \ + if (!ok) goto exit; \ + SELECT_SCORE_WATERMAN_SMITH_BEYER(M[i][j-k], Ix[i][j-k]); \ + } \ + if (score > maximum) maximum = score; \ + Iy[i][j] = score; \ + } \ + } \ + SELECT_SCORE_GLOBAL(M[nA][nB], Ix[nA][nB], Iy[nA][nB]); \ + if (score > maximum) maximum = score; \ + result = PyFloat_FromDouble(maximum); \ + + +#define WATERMANSMITHBEYER_EXIT_SCORE \ +exit: \ + if (M) { \ + /* If M is NULL, then Ix is also NULL. */ \ + if (Ix) { \ + /* If Ix is NULL, then Iy is also NULL. */ \ + if (Iy) { \ + /* If Iy is NULL, then M[i], Ix[i], and Iy[i] are \ + * also NULL. */ \ + for (i = 0; i <= nA; i++) { \ + if (!M[i]) break; \ + PyMem_Free(M[i]); \ + if (!Ix[i]) break; \ + PyMem_Free(Ix[i]); \ + if (!Iy[i]) break; \ + PyMem_Free(Iy[i]); \ + } \ + PyMem_Free(Iy); \ + } \ + PyMem_Free(Ix); \ + } \ + PyMem_Free(M); \ + } \ + if (!ok) return NULL; \ + if (!result) return PyErr_NoMemory(); \ + return result; \ + + +#define WATERMANSMITHBEYER_ENTER_ALIGN(mode) \ + int i; \ + int j = 0; \ + int gap; \ + int kA; \ + int kB; \ + const double epsilon = self->epsilon; \ + Trace** M; \ + TraceGapsWatermanSmithBeyer** gaps; \ + double** M_row = NULL; \ + double** Ix_row = NULL; \ + double** Iy_row = NULL; \ + int ng; \ + int nm; \ + double score; \ + double gapscore; \ + double temp; \ + int trace; \ + int* gapM; \ + int* gapXY; \ + int ok = 1; \ + PathGenerator* paths = NULL; \ + \ + /* Waterman-Smith-Beyer algorithm */ \ + paths = PathGenerator_create_WSB(nA, nB, mode, strand); \ + if (!paths) return NULL; \ + M = paths->M; \ + gaps = paths->gaps.waterman_smith_beyer; \ + M_row = PyMem_Malloc((nA+1)*sizeof(double*)); \ + if (!M_row) goto exit; \ + Ix_row = PyMem_Malloc((nA+1)*sizeof(double*)); \ + if (!Ix_row) goto exit; \ + Iy_row = PyMem_Malloc((nA+1)*sizeof(double*)); \ + if (!Iy_row) goto exit; \ + for (i = 0; i <= nA; i++) { \ + M_row[i] = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!M_row[i]) goto exit; \ + Ix_row[i] = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!Ix_row[i]) goto exit; \ + Iy_row[i] = PyMem_Malloc((nB+1)*sizeof(double)); \ + if (!Iy_row[i]) goto exit; \ + } \ + + +#define WATERMANSMITHBEYER_GLOBAL_ALIGN(align_score, query_gap_start) \ + M_row[0][0] = 0; \ + Ix_row[0][0] = -DBL_MAX; \ + Iy_row[0][0] = -DBL_MAX; \ + for (i = 1; i <= nA; i++) { \ + M_row[i][0] = -DBL_MAX; \ + Iy_row[i][0] = -DBL_MAX; \ + ok = _call_deletion_score_function(self, query_gap_start, i, nB, &score); \ + if (!ok) goto exit; \ + Ix_row[i][0] = score; \ + } \ + for (j = 1; j <= nB; j++) { \ + M_row[0][j] = -DBL_MAX; \ + Ix_row[0][j] = -DBL_MAX; \ + ok = _call_insertion_score_function(self, 0, j, nA, &score); \ + if (!ok) goto exit; \ + Iy_row[0][j] = score; \ + } \ + for (i = 1; i <= nA; i++) { \ + kA = sA[i-1]; \ + for (j = 1; j <= nB; j++) { \ + kB = sB[j-1]; \ + SELECT_TRACE_WATERMAN_SMITH_BEYER_GLOBAL_ALIGN((align_score)); \ + gapM = PyMem_Malloc((i+1)*sizeof(int)); \ + if (!gapM) goto exit; \ + gaps[i][j].MIx = gapM; \ + gapXY = PyMem_Malloc((i+1)*sizeof(int)); \ + if (!gapXY) goto exit; \ + gaps[i][j].IyIx = gapXY; \ + nm = 0; \ + ng = 0; \ + score = -DBL_MAX; \ + for (gap = 1; gap <= i; gap++) { \ + ok = _call_deletion_score_function(self, query_gap_start, gap, nB, &gapscore); \ + if (!ok) goto exit; \ + SELECT_TRACE_WATERMAN_SMITH_BEYER_GAP(M_row[i-gap][j], \ + Iy_row[i-gap][j]); \ + } \ + gapM = PyMem_Realloc(gapM, (nm+1)*sizeof(int)); \ + if (!gapM) goto exit; \ + gaps[i][j].MIx = gapM; \ + gapM[nm] = 0; \ + gapXY = PyMem_Realloc(gapXY, (ng+1)*sizeof(int)); \ + if (!gapXY) goto exit; \ + gapXY[ng] = 0; \ + gaps[i][j].IyIx = gapXY; \ + Ix_row[i][j] = score; \ + gapM = PyMem_Malloc((j+1)*sizeof(int)); \ + if (!gapM) goto exit; \ + gaps[i][j].MIy = gapM; \ + gapXY = PyMem_Malloc((j+1)*sizeof(int)); \ + if (!gapXY) goto exit; \ + gaps[i][j].IxIy = gapXY; \ + nm = 0; \ + ng = 0; \ + score = -DBL_MAX; \ + for (gap = 1; gap <= j; gap++) { \ + ok = _call_insertion_score_function(self, i, gap, nA, &gapscore); \ + if (!ok) goto exit; \ + SELECT_TRACE_WATERMAN_SMITH_BEYER_GAP(M_row[i][j-gap], \ + Ix_row[i][j-gap]); \ + } \ + Iy_row[i][j] = score; \ + gapM = PyMem_Realloc(gapM, (nm+1)*sizeof(int)); \ + if (!gapM) goto exit; \ + gaps[i][j].MIy = gapM; \ + gapM[nm] = 0; \ + gapXY = PyMem_Realloc(gapXY, (ng+1)*sizeof(int)); \ + if (!gapXY) goto exit; \ + gaps[i][j].IxIy = gapXY; \ + gapXY[ng] = 0; \ + } \ + } \ + /* traceback */ \ + SELECT_SCORE_GLOBAL(M_row[nA][nB], Ix_row[nA][nB], Iy_row[nA][nB]); \ + M[nA][nB].path = 0; \ + if (M_row[nA][nB] < score - epsilon) M[nA][nB].trace = 0; \ + if (Ix_row[nA][nB] < score - epsilon) { \ + gapM = PyMem_Realloc(gaps[nA][nB].MIx, sizeof(int)); \ + if (!gapM) goto exit; \ + gapM[0] = 0; \ + gaps[nA][nB].MIx = gapM; \ + gapXY = PyMem_Realloc(gaps[nA][nB].IyIx, sizeof(int)); \ + if (!gapXY) goto exit; \ + gapXY[0] = 0; \ + gaps[nA][nB].IyIx = gapXY; \ + } \ + if (Iy_row[nA][nB] < score - epsilon) { \ + gapM = PyMem_Realloc(gaps[nA][nB].MIy, sizeof(int)); \ + if (!gapM) goto exit; \ + gapM[0] = 0; \ + gaps[nA][nB].MIy = gapM; \ + gapXY = PyMem_Realloc(gaps[nA][nB].IxIy, sizeof(int)); \ + if (!gapXY) goto exit; \ + gapXY[0] = 0; \ + gaps[nA][nB].IxIy = gapXY; \ + } \ + for (i = 0; i <= nA; i++) { \ + PyMem_Free(M_row[i]); \ + PyMem_Free(Ix_row[i]); \ + PyMem_Free(Iy_row[i]); \ + } \ + PyMem_Free(M_row); \ + PyMem_Free(Ix_row); \ + PyMem_Free(Iy_row); \ + return Py_BuildValue("fN", score, paths); \ + + +#define WATERMANSMITHBEYER_LOCAL_ALIGN(align_score, query_gap_start) \ + M_row[0][0] = 0; \ + Ix_row[0][0] = -DBL_MAX; \ + Iy_row[0][0] = -DBL_MAX; \ + for (i = 1; i <= nA; i++) { \ + M_row[i][0] = 0; \ + Ix_row[i][0] = -DBL_MAX; \ + Iy_row[i][0] = -DBL_MAX; \ + } \ + for (i = 1; i <= nB; i++) { \ + M_row[0][i] = 0; \ + Ix_row[0][i] = -DBL_MAX; \ + Iy_row[0][i] = -DBL_MAX; \ + } \ + for (i = 1; i <= nA; i++) { \ + kA = sA[i-1]; \ + for (j = 1; j <= nB; j++) { \ + kB = sB[j-1]; \ + nm = 0; \ + ng = 0; \ + SELECT_TRACE_WATERMAN_SMITH_BEYER_ALIGN( \ + M_row[i-1][j-1], \ + Ix_row[i-1][j-1], \ + Iy_row[i-1][j-1], \ + (align_score)); \ + M[i][j].path = 0; \ + if (i == nA || j == nB) { \ + Ix_row[i][j] = score; \ + gaps[i][j].MIx = NULL; \ + gaps[i][j].IyIx = NULL; \ + gaps[i][j].MIy = NULL; \ + gaps[i][j].IxIy = NULL; \ + Iy_row[i][j] = score; \ + continue; \ + } \ + gapM = PyMem_Malloc((i+1)*sizeof(int)); \ + if (!gapM) goto exit; \ + gaps[i][j].MIx = gapM; \ + gapXY = PyMem_Malloc((i+1)*sizeof(int)); \ + if (!gapXY) goto exit; \ + gaps[i][j].IyIx = gapXY; \ + score = -DBL_MAX; \ + for (gap = 1; gap <= i; gap++) { \ + ok = _call_deletion_score_function(self, query_gap_start, gap, nB, &gapscore); \ + if (!ok) goto exit; \ + SELECT_TRACE_WATERMAN_SMITH_BEYER_GAP(M_row[i-gap][j], \ + Iy_row[i-gap][j]); \ + } \ + if (score < epsilon) { \ + score = -DBL_MAX; \ + nm = 0; \ + ng = 0; \ + } \ + else if (score > maximum) maximum = score; \ + gapM[nm] = 0; \ + gapXY[ng] = 0; \ + Ix_row[i][j] = score; \ + M[i][j].path = 0; \ + gapM = PyMem_Realloc(gapM, (nm+1)*sizeof(int)); \ + if (!gapM) goto exit; \ + gaps[i][j].MIx = gapM; \ + gapM[nm] = 0; \ + gapXY = PyMem_Realloc(gapXY, (ng+1)*sizeof(int)); \ + if (!gapXY) goto exit; \ + gaps[i][j].IyIx = gapXY; \ + gapXY[ng] = 0; \ + gapM = PyMem_Malloc((j+1)*sizeof(int)); \ + if (!gapM) goto exit; \ + gaps[i][j].MIy = gapM; \ + gapXY = PyMem_Malloc((j+1)*sizeof(int)); \ + if (!gapXY) goto exit; \ + gaps[i][j].IxIy = gapXY; \ + nm = 0; \ + ng = 0; \ + score = -DBL_MAX; \ + gapM[0] = 0; \ + for (gap = 1; gap <= j; gap++) { \ + ok = _call_insertion_score_function(self, i, gap, nA, &gapscore); \ + if (!ok) goto exit; \ + SELECT_TRACE_WATERMAN_SMITH_BEYER_GAP(M_row[i][j-gap], \ + Ix_row[i][j-gap]); \ + } \ + if (score < epsilon) { \ + score = -DBL_MAX; \ + nm = 0; \ + ng = 0; \ + } \ + else if (score > maximum) maximum = score; \ + gapM = PyMem_Realloc(gapM, (nm+1)*sizeof(int)); \ + if (!gapM) goto exit; \ + gaps[i][j].MIy = gapM; \ + gapXY = PyMem_Realloc(gapXY, (ng+1)*sizeof(int)); \ + if (!gapXY) goto exit; \ + gaps[i][j].IxIy = gapXY; \ + gapM[nm] = 0; \ + gapXY[ng] = 0; \ + Iy_row[i][j] = score; \ + M[i][j].path = 0; \ + } \ + } \ + for (i = 0; i <= nA; i++) PyMem_Free(M_row[i]); \ + PyMem_Free(M_row); \ + for (i = 0; i <= nA; i++) PyMem_Free(Ix_row[i]); \ + PyMem_Free(Ix_row); \ + for (i = 0; i <= nA; i++) PyMem_Free(Iy_row[i]); \ + PyMem_Free(Iy_row); \ +\ + /* As we don't allow zero-score extensions to alignments, \ + * we need to remove all traces towards an ENDPOINT. \ + * In addition, some points then won't have any path to a STARTPOINT. \ + * Here, use path as a temporary variable to indicate if the point \ + * is reachable from a STARTPOINT. If it is unreachable, remove all \ + * traces from it, and don't allow it to be an ENDPOINT. It may still \ + * be a valid STARTPOINT. */ \ + for (j = 0; j <= nB; j++) M[0][j].path = M_MATRIX; \ + for (i = 1; i <= nA; i++) { \ + M[i][0].path = M_MATRIX; \ + for (j = 1; j <= nB; j++) { \ + /* Remove traces to unreachable points. */ \ + trace = M[i][j].trace; \ + if (!(M[i-1][j-1].path & M_MATRIX)) trace &= ~M_MATRIX; \ + if (!(M[i-1][j-1].path & Ix_MATRIX)) trace &= ~Ix_MATRIX; \ + if (!(M[i-1][j-1].path & Iy_MATRIX)) trace &= ~Iy_MATRIX; \ + if (trace & (STARTPOINT | M_MATRIX | Ix_MATRIX | Iy_MATRIX)) { \ + /* The point is reachable. */ \ + if (trace & ENDPOINT) M[i][j].path = 0; /* no extensions after ENDPOINT */ \ + else M[i][j].path |= M_MATRIX; \ + } \ + else { \ + /* The point is not reachable. Then it is not a STARTPOINT, \ + * all traces from it can be removed, and it cannot act as \ + * an ENDPOINT. */ \ + M[i][j].path &= ~M_MATRIX; \ + trace = 0; \ + } \ + M[i][j].trace = trace; \ + if (i == nA || j == nB) continue; \ + gapM = gaps[i][j].MIx; \ + gapXY = gaps[i][j].IyIx; \ + nm = 0; \ + ng = 0; \ + for (im = 0; (gap = gapM[im]); im++) \ + if (M[i-gap][j].path & M_MATRIX) gapM[nm++] = gap; \ + gapM = PyMem_Realloc(gapM, (nm+1)*sizeof(int)); \ + if (!gapM) goto exit; \ + gapM[nm] = 0; \ + gaps[i][j].MIx = gapM; \ + for (im = 0; (gap = gapXY[im]); im++) \ + if (M[i-gap][j].path & Iy_MATRIX) gapXY[ng++] = gap; \ + gapXY = PyMem_Realloc(gapXY, (ng+1)*sizeof(int)); \ + if (!gapXY) goto exit; \ + gapXY[ng] = 0; \ + gaps[i][j].IyIx = gapXY; \ + if (nm==0 && ng==0) M[i][j].path &= ~Ix_MATRIX; /* not reachable */ \ + else M[i][j].path |= Ix_MATRIX; /* reachable */ \ + gapM = gaps[i][j].MIy; \ + gapXY = gaps[i][j].IxIy; \ + nm = 0; \ + ng = 0; \ + for (im = 0; (gap = gapM[im]); im++) \ + if (M[i][j-gap].path & M_MATRIX) gapM[nm++] = gap; \ + gapM = PyMem_Realloc(gapM, (nm+1)*sizeof(int)); \ + if (!gapM) goto exit; \ + gapM[nm] = 0; \ + gaps[i][j].MIy = gapM; \ + for (im = 0; (gap = gapXY[im]); im++) \ + if (M[i][j-gap].path & Ix_MATRIX) gapXY[ng++] = gap; \ + gapXY = PyMem_Realloc(gapXY, (ng+1)*sizeof(int)); \ + if (!gapXY) goto exit; \ + gapXY[ng] = 0; \ + gaps[i][j].IxIy = gapXY; \ + if (nm==0 && ng==0) M[i][j].path &= ~Iy_MATRIX; /* not reachable */ \ + else M[i][j].path |= Iy_MATRIX; /* reachable */ \ + } \ + } \ + /* traceback */ \ + if (maximum == 0) M[0][0].path = DONE; \ + else M[0][0].path = 0; \ + return Py_BuildValue("fN", maximum, paths); \ + + +#define WATERMANSMITHBEYER_EXIT_ALIGN \ +exit: \ + if (ok) /* otherwise, an exception was already set */ \ + PyErr_SetNone(PyExc_MemoryError); \ + Py_DECREF(paths); \ + if (M_row) { \ + /* If M is NULL, then Ix is also NULL. */ \ + if (Ix_row) { \ + /* If Ix is NULL, then Iy is also NULL. */ \ + if (Iy_row) { \ + /* If Iy is NULL, then M[i], Ix[i], and Iy[i] are also NULL. */ \ + for (i = 0; i <= nA; i++) { \ + if (!M_row[i]) break; \ + PyMem_Free(M_row[i]); \ + if (!Ix_row[i]) break; \ + PyMem_Free(Ix_row[i]); \ + if (!Iy_row[i]) break; \ + PyMem_Free(Iy_row[i]); \ + } \ + PyMem_Free(Iy_row); \ + } \ + PyMem_Free(Ix_row); \ + } \ + PyMem_Free(M_row); \ + } \ + return NULL; \ + + +#define FOGSAA_ENTER \ + int i, j; \ + double t, t2; /* temporary variables */ \ + int kA, kB; \ + int curpA = 0, curpB = 0; /* optimal and current pointers */ \ + int pathend = 1, child_types[3]; \ + double lower_bound, child_lbounds[3], child_ubounds[3]; \ + /* pathend denotes if the current path is active, expanded is the number of \ + * expanded nodes, lower_bound contains the global lower_bound, a and b \ + * contain the lower bounds for the current cell. ch contains the types of \ + * the potential children */ \ + int type_total = 1; \ + /* The initial values for new_type, npA, npB, new_score, new_lower, \ + new_upper, next_lower, and next_upper don't mean anything; they're never \ + used and are only initialized to stop compiler warnings */ \ + int new_type = 0, npA = 0, npB = 0; \ + double new_score = 0, new_lower = 0, new_upper = 0, next_lower = 0, \ + next_upper = 0; \ + const double gap_open_A = self->open_internal_insertion_score; \ + const double gap_open_B = self->open_internal_deletion_score; \ + const double gap_extend_A = self->extend_internal_insertion_score; \ + const double gap_extend_B = self->extend_internal_deletion_score; \ + struct fogsaa_cell* matrix = NULL; \ + struct fogsaa_queue queue; \ + double left_gap_open_A; \ + double left_gap_open_B; \ + double left_gap_extend_A; \ + double left_gap_extend_B; \ + double right_gap_open_A; \ + double right_gap_open_B; \ + double right_gap_extend_A; \ + double right_gap_extend_B; \ + switch (strand) { \ + case '+': \ + left_gap_open_A = self->open_left_insertion_score; \ + left_gap_open_B = self->open_left_deletion_score; \ + left_gap_extend_A = self->extend_left_insertion_score; \ + left_gap_extend_B = self->extend_left_deletion_score; \ + right_gap_open_A = self->open_right_insertion_score; \ + right_gap_open_B = self->open_right_deletion_score; \ + right_gap_extend_A = self->extend_right_insertion_score; \ + right_gap_extend_B = self->extend_right_deletion_score; \ + break; \ + case '-': \ + left_gap_open_A = self->open_right_insertion_score; \ + left_gap_open_B = self->open_right_deletion_score; \ + left_gap_extend_A = self->extend_right_insertion_score; \ + left_gap_extend_B = self->extend_right_deletion_score; \ + right_gap_open_A = self->open_left_insertion_score; \ + right_gap_open_B = self->open_left_deletion_score; \ + right_gap_extend_A = self->extend_left_insertion_score; \ + right_gap_extend_B = self->extend_left_deletion_score; \ + break; \ + default: \ + PyErr_SetString(PyExc_RuntimeError, "strand was neither '+' nor '-'"); \ + return NULL; \ + } \ + +#define FOGSAA_DO(align_score) \ + /* allocate and initialize matrix */ \ + matrix = PyMem_Calloc((nA+1) * (nB+1), sizeof(struct fogsaa_cell)); \ + if (!matrix) \ + return PyErr_NoMemory(); \ + MATRIX(0, 0).present_score = 0; \ + MATRIX(0, 0).type = STARTPOINT; \ + FOGSAA_CALCULATE_SCORE(MATRIX(0, 0).present_score, STARTPOINT, MATRIX(0, 0).lower, MATRIX(0, 0).upper, 0, 0); \ + MATRIX(0, 0).is_left_gap = 1; \ + lower_bound = MATRIX(0, 0).lower; \ + \ + /* initialize queue */ \ + queue.array = NULL; \ + queue.size = 0; \ + queue.capacity = 0; \ + /* main loop */ \ + do { \ + pathend = 1; \ + while (curpA < nA || curpB < nB) { \ + struct fogsaa_cell *curr = &(MATRIX(curpA, curpB)); \ + if (type_total == DIAGONAL || type_total == HORIZONTAL || type_total == VERTICAL) { \ + /* current is a 1st child */ \ + if (curpA <= nA - 1 && curpB <= nB - 1) { \ + /* neither sequence is at the end, so we can advance in both sequences */ \ + kA = sA[curpA]; \ + kB = sB[curpB]; \ + double p = align_score; \ + /* score the match/mismatch */ \ + FOGSAA_CALCULATE_SCORE(curr->present_score + p, DIAGONAL, child_lbounds[0], child_ubounds[0], curpA + 1, curpB + 1); \ + /* score the gaps */ \ + if (curr->type == DIAGONAL || curr->type == STARTPOINT) { \ + if (!curr->is_left_gap) { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_open_A, HORIZONTAL, child_lbounds[1], child_ubounds[1], curpA, curpB + 1) \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_open_B, VERTICAL, child_lbounds[2], child_ubounds[2], curpA + 1, curpB) \ + } else { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_open_A, HORIZONTAL, child_lbounds[1], child_ubounds[1], curpA, curpB + 1) \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_open_B, VERTICAL, child_lbounds[2], child_ubounds[2], curpA + 1, curpB) \ + } \ + } else if (curr->type == HORIZONTAL) { \ + /* gap is already opened in the first chain */ \ + if (!curr->is_left_gap) { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_extend_A, HORIZONTAL, child_lbounds[1], child_ubounds[1], curpA, curpB + 1) \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_open_B, VERTICAL, child_lbounds[2], child_ubounds[2], curpA + 1, curpB) \ + } else { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_extend_A, HORIZONTAL, child_lbounds[1], child_ubounds[1], curpA, curpB + 1) \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_open_B, VERTICAL, child_lbounds[2], child_ubounds[2], curpA + 1, curpB) \ + } \ + } else { \ + /* gap is already opened in the 2nd chain */ \ + if (!curr->is_left_gap) { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_open_A, HORIZONTAL, child_lbounds[1], child_ubounds[1], curpA, curpB + 1) \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_extend_B, VERTICAL, child_lbounds[2], child_ubounds[2], curpA + 1, curpB) \ + } else { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_open_A, HORIZONTAL, child_lbounds[1], child_ubounds[1], curpA, curpB + 1) \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_extend_B, VERTICAL, child_lbounds[2], child_ubounds[2], curpA + 1, curpB) \ + } \ + } \ + \ + /* sort and select the best new child as the new type */ \ + child_types[0] = DIAGONAL; \ + child_types[1] = HORIZONTAL; \ + child_types[2] = VERTICAL; \ + FOGSAA_SORT() \ + new_type = child_types[0]; \ + if (new_type == DIAGONAL) { \ + npA = curpA + 1; \ + npB = curpB + 1; \ + new_score = curr->present_score + p; \ + } else if (new_type == HORIZONTAL) { \ + npA = curpA; \ + npB = curpB + 1; \ + if (curr->is_left_gap) { \ + new_score = curr->present_score + (curr->type == HORIZONTAL ? left_gap_extend_A : left_gap_open_A); \ + } else { \ + new_score = curr->present_score + (curr->type == HORIZONTAL ? gap_extend_A : gap_open_A); \ + } \ + } else { \ + /* new_type is VERTICAL */ \ + npA = curpA + 1; \ + npB = curpB; \ + if (curr->is_left_gap) { \ + new_score = curr->present_score + (curr->type == VERTICAL ? left_gap_extend_B : left_gap_open_B); \ + } else { \ + new_score = curr->present_score + (curr->type == VERTICAL ? gap_extend_B : gap_open_B); \ + } \ + } \ + if (child_ubounds[1] >= MATRIX(0, 0).lower) { \ + /* insert 2nd best new child to the queue */ \ + if (!fogsaa_queue_insert(&queue, curpA, curpB, new_type + child_types[1], child_types[1], child_lbounds[1], child_ubounds[1])) \ + return PyErr_NoMemory(); \ + } \ + } else if (curpA <= nA - 1) { \ + /* we're at the end of B, so must put a gap in B */ \ + new_type = VERTICAL; \ + npA = curpA + 1; \ + npB = curpB; \ + new_score = curr->present_score + (curr->type == VERTICAL ? right_gap_extend_B : right_gap_open_B); \ + } else { \ + /* we're at the end of A, so must put a gap in A */ \ + new_type = HORIZONTAL; \ + npA = curpA; \ + npB = curpB + 1; \ + new_score = curr->present_score + (curr->type == HORIZONTAL ? right_gap_extend_A : right_gap_open_A); \ + } \ + } else if (type_total == DIAGONAL + HORIZONTAL || \ + type_total == DIAGONAL + VERTICAL || \ + type_total == HORIZONTAL + VERTICAL) { \ + /* current is a 2nd child (sum of two types) */ \ + if (new_type == DIAGONAL) { \ + npA = curpA + 1; \ + npB = curpB + 1; \ + new_score = curr->present_score + (sA[curpA] == sB[curpB] ? match : mismatch); \ + /* find what the 3rd child was (will later be added to the queue) */ \ + /* NOTE: DIAGONAL + HORIZONTAL + VERTICAL = 7 */ \ + if (7 - type_total == HORIZONTAL) { \ + if (curr->type != HORIZONTAL) { \ + if (curr->is_left_gap) { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_open_A, HORIZONTAL, next_lower, next_upper, curpA, curpB + 1) \ + } else { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_open_A, HORIZONTAL, next_lower, next_upper, curpA, curpB + 1) \ + } \ + } else { \ + if (curr->is_left_gap) { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_extend_A, HORIZONTAL, next_lower, next_upper, curpA, curpB + 1) \ + } else { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_extend_A, HORIZONTAL, next_lower, next_upper, curpA, curpB + 1) \ + } \ + } \ + } else { \ + /* 3rd child was VERTICAL */ \ + if (curr->type != VERTICAL) { \ + if (curr->is_left_gap) { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_open_B, VERTICAL, next_lower, next_upper, curpA, curpB + 1) \ + } else { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_open_B, VERTICAL, next_lower, next_upper, curpA, curpB + 1) \ + } \ + } else { \ + if (curr->is_left_gap) { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_extend_B, VERTICAL, next_lower, next_upper, curpA, curpB + 1) \ + } else { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_extend_B, VERTICAL, next_lower, next_upper, curpA, curpB + 1) \ + } \ + } \ + } \ + } else if (new_type == HORIZONTAL) { \ + npA = curpA; \ + npB = curpB + 1; \ + new_score = curr->present_score + (curr->type == HORIZONTAL ? gap_extend_A : gap_open_A); \ + /* again, find what 3rd child was */ \ + if (7 - type_total == DIAGONAL) { \ + kA = sA[curpA]; \ + kB = sB[curpB]; \ + FOGSAA_CALCULATE_SCORE(curr->present_score + (align_score), DIAGONAL, next_lower, next_upper, curpA + 1, curpB + 1); \ + } else { \ + /* 3rd child was VERTICAL */ \ + if (curr->type != VERTICAL) { \ + if (curr->is_left_gap) { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_open_B, VERTICAL, next_lower, next_upper, curpA, curpB + 1) \ + } else { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_open_B, VERTICAL, next_lower, next_upper, curpA, curpB + 1) \ + } \ + } else { \ + if (curr->is_left_gap) { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_extend_B, VERTICAL, next_lower, next_upper, curpA, curpB + 1) \ + } else { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_extend_B, VERTICAL, next_lower, next_upper, curpA, curpB + 1) \ + } \ + } \ + } \ + } else { \ + /* new_type is VERTICAL */ \ + npA = curpA + 1; \ + npB = curpB; \ + new_score = curr->present_score + (curr->type == VERTICAL ? gap_extend_B : gap_open_B); \ + /* again, find what 3rd child was */ \ + if (7 - type_total == DIAGONAL) { \ + kA = sA[curpA]; \ + kB = sB[curpB]; \ + FOGSAA_CALCULATE_SCORE(curr->present_score + (align_score), DIAGONAL, next_lower, next_upper, curpA + 1, curpB + 1); \ + } else { \ + /* 3rd child was HORIZONTAL */ \ + if (curr->type != HORIZONTAL) { \ + if (curr->is_left_gap) { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_open_A, HORIZONTAL, next_lower, next_upper, curpA, curpB + 1) \ + } else { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_open_A, HORIZONTAL, next_lower, next_upper, curpA, curpB + 1) \ + } \ + } else { \ + if (curr->is_left_gap) { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + left_gap_extend_A, HORIZONTAL, next_lower, next_upper, curpA, curpB + 1) \ + } else { \ + FOGSAA_CALCULATE_SCORE(curr->present_score + gap_extend_A, HORIZONTAL, next_lower, next_upper, curpA, curpB + 1) \ + } \ + } \ + } \ + } \ + if (next_upper >= MATRIX(0, 0).lower) { \ + if (!fogsaa_queue_insert(&queue, curpA, curpB, 7, 7 - type_total, next_lower, next_upper)) \ + return PyErr_NoMemory(); \ + } \ + } else if (type_total == DIAGONAL + HORIZONTAL + VERTICAL) { \ + /* current is a 3rd child */ \ + if (new_type == DIAGONAL) { \ + kA = sA[curpA]; \ + kB = sB[curpB]; \ + npA = curpA + 1; \ + npB = curpB + 1; \ + new_score = curr->present_score + (align_score); \ + } else if (new_type == HORIZONTAL) { \ + npA = curpA; \ + npB = curpB + 1; \ + if (curr->type != HORIZONTAL) { \ + new_score = curr->present_score + (curr->is_left_gap ? left_gap_open_A : gap_open_A); \ + } else { \ + new_score = curr->present_score + (curr->is_left_gap ? left_gap_extend_A : gap_extend_A); \ + } \ + } else { \ + /* new_type is VERTICAL */ \ + npA = curpA + 1; \ + npB = curpB; \ + if (curr->type != VERTICAL) { \ + new_score = curr->present_score + (curr->is_left_gap ? left_gap_open_B : gap_open_B); \ + } else { \ + new_score = curr->present_score + (curr->is_left_gap ? left_gap_extend_B : gap_extend_B); \ + } \ + } \ + /* no more nodes to insert into the queue */ \ + } \ + \ + /* write the new node to the matrix, but skip if there's already a better path there */ \ + if (MATRIX(npA, npB).filled == 1 && MATRIX(npA, npB).type <= 4 && \ + MATRIX(npA, npB).present_score >= new_score) { \ + pathend = 0; \ + break; \ + } else { \ + FOGSAA_CALCULATE_SCORE(new_score, new_type, new_lower, new_upper, npA, npB) \ + MATRIX(npA, npB).present_score = new_score; \ + MATRIX(npA, npB).lower = new_lower; \ + MATRIX(npA, npB).upper = new_upper; \ + MATRIX(npA, npB).type = new_type; \ + MATRIX(npA, npB).filled = 1; \ + if (new_type == HORIZONTAL || new_type == VERTICAL) { \ + MATRIX(npA, npB).is_left_gap = curr->is_left_gap; \ + } else { \ + MATRIX(npA, npB).is_left_gap = 0; \ + } \ + } \ + \ + /* make the child the new current node */ \ + curpA = npA; \ + curpB = npB; \ + type_total = 1; \ + \ + if (MATRIX(npA, npB).upper < lower_bound && \ + lower_bound - MATRIX(npA, npB).upper > self->epsilon) { \ + pathend = 0; \ + break; \ + } \ + } \ + \ + if (MATRIX(curpA, curpB).present_score > lower_bound && \ + MATRIX(curpA, curpB).present_score - lower_bound > self->epsilon && \ + pathend == 1) { \ + /* if this is the best score and we've fully expanded the branch, set it as the new lower bound */ \ + lower_bound = MATRIX(curpA, curpB).present_score; \ + } \ + \ + /* If possible, pop the next best from the queue */ \ + if (queue.size > 0) { \ + struct fogsaa_queue_node root = fogsaa_queue_pop(&queue); \ + curpA = root.pA; \ + curpB = root.pB; \ + type_total = root.type_upto_next; \ + new_lower = root.next_lower; \ + new_upper = root.next_upper; \ + new_type = root.next_type; \ + } else { \ + break; \ + } \ + } while (lower_bound < new_upper && new_upper - lower_bound > self->epsilon); \ + \ + /* cleanup and return */ \ + PyMem_Free(queue.array); + + +#define FOGSAA_EXIT_SCORE \ + if (lower_bound < new_upper && new_upper - lower_bound > self->epsilon) { \ + PyErr_Format(PyExc_RuntimeError, "Algorithm ended incomplete. Report this as a bug."); \ + return NULL; \ + } \ + t = MATRIX(nA, nB).present_score; \ + PyMem_Free(matrix); \ + return PyFloat_FromDouble((double)t); + +#define FOGSAA_EXIT_ALIGN \ + if (lower_bound < new_upper && new_upper - lower_bound > self->epsilon) { \ + PyErr_SetString(PyExc_RuntimeError, "Algorithm ended incomplete. Report this as a bug."); \ + return NULL; \ + } \ + paths = PathGenerator_create_FOGSAA(nA, nB, strand); \ + M = paths->M; \ + if (!paths) return NULL; \ + \ + /* copy only the cells of the optimal path to trace and path */ \ + i = nA; \ + j = nB; \ + while (1) { \ + switch (MATRIX(i, j).type) { \ + case 0: \ + case STARTPOINT: \ + M[i][j].trace = 0; \ + goto end_loop; \ + case DIAGONAL: \ + M[i][j].trace = DIAGONAL; \ + M[--i][--j].path = DIAGONAL; \ + break; \ + case HORIZONTAL: \ + M[i][j].trace = HORIZONTAL; \ + M[i][--j].path = HORIZONTAL; \ + break; \ + case VERTICAL: \ + M[i][j].trace = VERTICAL; \ + M[--i][j].path = VERTICAL; \ + break; \ + default: \ + PyErr_SetString(PyExc_RuntimeError, "Unexpected FOGSAA cell type. Report this as a bug."); \ + return NULL; \ + } \ + } \ +end_loop: \ + M[nA][nB].path = 0; \ + t = MATRIX(nA, nB).present_score; \ + PyMem_Free(matrix); \ + return Py_BuildValue("fN", (double)t, paths); + + +/* -------------- allocation & deallocation ------------- */ + +static PathGenerator* +PathGenerator_create_NWSW(int nA, int nB, Mode mode, unsigned char strand) +{ + int i; + unsigned char trace = 0; + Trace** M; + PathGenerator* paths; + + paths = (PathGenerator*)PyType_GenericAlloc(&PathGenerator_Type, 0); + if (!paths) return NULL; + + paths->iA = 0; + paths->iB = 0; + paths->nA = nA; + paths->nB = nB; + paths->M = NULL; + paths->gaps.gotoh = NULL; + paths->gaps.waterman_smith_beyer = NULL; + paths->algorithm = NeedlemanWunschSmithWaterman; + paths->mode = mode; + paths->length = 0; + paths->strand = strand; + + M = PyMem_Malloc((nA+1)*sizeof(Trace*)); + paths->M = M; + if (!M) goto exit; + switch (mode) { + case Global: trace = VERTICAL; break; + case Local: trace = STARTPOINT; break; + default: + ERR_UNEXPECTED_MODE + return NULL; + } + for (i = 0; i <= nA; i++) { + M[i] = PyMem_Malloc((nB+1)*sizeof(Trace)); + if (!M[i]) goto exit; + M[i][0].trace = trace; + } + if (mode == Global) { + M[0][0].trace = 0; + trace = HORIZONTAL; + } + for (i = 1; i <= nB; i++) M[0][i].trace = trace; + M[0][0].path = 0; + return paths; +exit: + Py_DECREF(paths); + PyErr_SetNone(PyExc_MemoryError); + return NULL; +} + +static PathGenerator* +PathGenerator_create_Gotoh(int nA, int nB, Mode mode, unsigned char strand) +{ + int i; + unsigned char trace; + Trace** M; + TraceGapsGotoh** gaps; + PathGenerator* paths; + + switch (mode) { + case Global: trace = 0; break; + case Local: trace = STARTPOINT; break; + default: + ERR_UNEXPECTED_MODE + return NULL; + } + + paths = (PathGenerator*)PyType_GenericAlloc(&PathGenerator_Type, 0); + if (!paths) return NULL; + + paths->iA = 0; + paths->iB = 0; + paths->nA = nA; + paths->nB = nB; + paths->M = NULL; + paths->gaps.gotoh = NULL; + paths->algorithm = Gotoh; + paths->mode = mode; + paths->length = 0; + paths->strand = strand; + + M = PyMem_Malloc((nA+1)*sizeof(Trace*)); + if (!M) goto exit; + paths->M = M; + for (i = 0; i <= nA; i++) { + M[i] = PyMem_Malloc((nB+1)*sizeof(Trace)); + if (!M[i]) goto exit; + M[i][0].trace = trace; + } + gaps = PyMem_Malloc((nA+1)*sizeof(TraceGapsGotoh*)); + if (!gaps) goto exit; + paths->gaps.gotoh = gaps; + for (i = 0; i <= nA; i++) { + gaps[i] = PyMem_Malloc((nB+1)*sizeof(TraceGapsGotoh)); + if (!gaps[i]) goto exit; + } + + gaps[0][0].Ix = 0; + gaps[0][0].Iy = 0; + if (mode == Global) { + for (i = 1; i <= nA; i++) { + gaps[i][0].Ix = Ix_MATRIX; + gaps[i][0].Iy = 0; + } + gaps[1][0].Ix = M_MATRIX; + for (i = 1; i <= nB; i++) { + M[0][i].trace = 0; + gaps[0][i].Ix = 0; + gaps[0][i].Iy = Iy_MATRIX; + } + gaps[0][1].Iy = M_MATRIX; + } + else if (mode == Local) { + for (i = 1; i < nA; i++) { + gaps[i][0].Ix = 0; + gaps[i][0].Iy = 0; + } + for (i = 1; i <= nB; i++) { + M[0][i].trace = trace; + gaps[0][i].Ix = 0; + gaps[0][i].Iy = 0; + } + } + M[0][0].path = 0; + + return paths; +exit: + Py_DECREF(paths); + PyErr_SetNone(PyExc_MemoryError); + return NULL; +} + +static PathGenerator* +PathGenerator_create_WSB(int nA, int nB, Mode mode, unsigned char strand) +{ + int i, j; + int* trace; + Trace** M = NULL; + TraceGapsWatermanSmithBeyer** gaps = NULL; + PathGenerator* paths; + + paths = (PathGenerator*)PyType_GenericAlloc(&PathGenerator_Type, 0); + if (!paths) return NULL; + + paths->iA = 0; + paths->iB = 0; + paths->nA = nA; + paths->nB = nB; + paths->M = NULL; + paths->gaps.waterman_smith_beyer = NULL; + paths->algorithm = WatermanSmithBeyer; + paths->mode = mode; + paths->length = 0; + paths->strand = strand; + + M = PyMem_Malloc((nA+1)*sizeof(Trace*)); + if (!M) goto exit; + paths->M = M; + for (i = 0; i <= nA; i++) { + M[i] = PyMem_Malloc((nB+1)*sizeof(Trace)); + if (!M[i]) goto exit; + } + gaps = PyMem_Malloc((nA+1)*sizeof(TraceGapsWatermanSmithBeyer*)); + if (!gaps) goto exit; + paths->gaps.waterman_smith_beyer = gaps; + for (i = 0; i <= nA; i++) gaps[i] = NULL; + for (i = 0; i <= nA; i++) { + gaps[i] = PyMem_Malloc((nB+1)*sizeof(TraceGapsWatermanSmithBeyer)); + if (!gaps[i]) goto exit; + for (j = 0; j <= nB; j++) { + gaps[i][j].MIx = NULL; + gaps[i][j].IyIx = NULL; + gaps[i][j].MIy = NULL; + gaps[i][j].IxIy = NULL; + } + M[i][0].path = 0; + switch (mode) { + case Global: + M[i][0].trace = 0; + trace = PyMem_Malloc(2*sizeof(int)); + if (!trace) goto exit; + gaps[i][0].MIx = trace; + trace[0] = i; + trace[1] = 0; + trace = PyMem_Malloc(sizeof(int)); + if (!trace) goto exit; + gaps[i][0].IyIx = trace; + trace[0] = 0; + break; + case Local: + M[i][0].trace = STARTPOINT; + break; + default: + ERR_UNEXPECTED_MODE + return NULL; + } + } + for (i = 1; i <= nB; i++) { + switch (mode) { + case Global: + M[0][i].trace = 0; + trace = PyMem_Malloc(2*sizeof(int)); + if (!trace) goto exit; + gaps[0][i].MIy = trace; + trace[0] = i; + trace[1] = 0; + trace = PyMem_Malloc(sizeof(int)); + if (!trace) goto exit; + gaps[0][i].IxIy = trace; + trace[0] = 0; + break; + case Local: + M[0][i].trace = STARTPOINT; + break; + default: + ERR_UNEXPECTED_MODE + return NULL; + } + } + M[0][0].path = 0; + return paths; +exit: + Py_DECREF(paths); + PyErr_SetNone(PyExc_MemoryError); + return NULL; +} + +static PathGenerator* +PathGenerator_create_FOGSAA(int nA, int nB, unsigned char strand) +{ + int i; + Trace** M; + PathGenerator* paths; + + paths = (PathGenerator*)PyType_GenericAlloc(&PathGenerator_Type, 0); + if (!paths) return NULL; + + paths->iA = 0; + paths->iB = 0; + paths->nA = nA; + paths->nB = nB; + paths->M = NULL; + paths->gaps.gotoh = NULL; + paths->gaps.waterman_smith_beyer = NULL; + paths->algorithm = FOGSAA; + paths->mode = FOGSAA_Mode; + paths->length = 0; + paths->strand = strand; + + M = PyMem_Malloc((nA+1)*sizeof(Trace*)); + paths->M = M; + if (!M) goto exit; + for (i = 0; i <= nA; i++) { + M[i] = PyMem_Malloc((nB+1)*sizeof(Trace)); + if (!M[i]) goto exit; + } + M[0][0].path = 0; + return paths; +exit: + Py_DECREF(paths); + PyErr_SetNone(PyExc_MemoryError); + return NULL; +} + + +/* ----------------- alignment algorithms ----------------- */ + +#define MATRIX_SCORE substitution_matrix[kA*n+kB] +#define COMPARE_SCORE (kA == wildcard || kB == wildcard) ? 0 : (kA == kB) ? match : mismatch + + +static PyObject* +Aligner_needlemanwunsch_score_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + NEEDLEMANWUNSCH_SCORE(COMPARE_SCORE); +} + +static PyObject* +Aligner_needlemanwunsch_score_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + NEEDLEMANWUNSCH_SCORE(MATRIX_SCORE); +} + +static PyObject* +Aligner_smithwaterman_score_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + SMITHWATERMAN_SCORE(COMPARE_SCORE); +} + +static PyObject* +Aligner_smithwaterman_score_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + SMITHWATERMAN_SCORE(MATRIX_SCORE); +} + +static PyObject* +Aligner_needlemanwunsch_align_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + NEEDLEMANWUNSCH_ALIGN(COMPARE_SCORE); +} + +static PyObject* +Aligner_needlemanwunsch_align_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + NEEDLEMANWUNSCH_ALIGN(MATRIX_SCORE); +} + +static PyObject* +Aligner_smithwaterman_align_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + SMITHWATERMAN_ALIGN(COMPARE_SCORE); +} + +static PyObject* +Aligner_smithwaterman_align_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + SMITHWATERMAN_ALIGN(MATRIX_SCORE); +} + +static PyObject* +Aligner_gotoh_global_score_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + GOTOH_GLOBAL_SCORE(COMPARE_SCORE); +} + +static PyObject* +Aligner_gotoh_global_score_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + GOTOH_GLOBAL_SCORE(MATRIX_SCORE); +} + +static PyObject* +Aligner_gotoh_local_score_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + GOTOH_LOCAL_SCORE(COMPARE_SCORE); +} + +static PyObject* +Aligner_gotoh_local_score_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + GOTOH_LOCAL_SCORE(MATRIX_SCORE); +} + +static PyObject* +Aligner_gotoh_global_align_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + GOTOH_GLOBAL_ALIGN(COMPARE_SCORE); +} + +static PyObject* +Aligner_gotoh_global_align_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + GOTOH_GLOBAL_ALIGN(MATRIX_SCORE); +} + +static PyObject* +Aligner_gotoh_local_align_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + GOTOH_LOCAL_ALIGN(COMPARE_SCORE); +} + +static PyObject* +Aligner_gotoh_local_align_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + GOTOH_LOCAL_ALIGN(MATRIX_SCORE); +} + +static int +_call_deletion_score_function(Aligner* aligner, int i, int j, int n, double* score) +{ + double value; + PyObject* result; + PyObject* function = aligner->deletion_score_function; + if (!function) { + if (i == 0) { + value = aligner->open_left_deletion_score + + (j-1) * aligner->extend_left_deletion_score; + } + else if (i == n) { + value = aligner->open_right_deletion_score + + (j-1) * aligner->extend_right_deletion_score; + } + else { + value = aligner->open_internal_deletion_score + + (j-1) * aligner->extend_internal_deletion_score; + } + } + else { + result = PyObject_CallFunction(function, "ii", i, j); + if (result == NULL) return 0; + value = PyFloat_AsDouble(result); + Py_DECREF(result); + if (value == -1.0 && PyErr_Occurred()) return 0; + } + *score = value; + return 1; +} + +static int +_call_insertion_score_function(Aligner* aligner, int i, int j, int n, double* score) +{ + double value; + PyObject* result; + PyObject* function = aligner->insertion_score_function; + if (!function) { + if (i == 0) { + value = aligner->open_left_insertion_score + + (j-1) * aligner->extend_left_insertion_score; + } + else if (i == n) { + value = aligner->open_right_insertion_score + + (j-1) * aligner->extend_right_insertion_score; + } + else { + value = aligner->open_internal_insertion_score + + (j-1) * aligner->extend_internal_insertion_score; + } + } + else { + result = PyObject_CallFunction(function, "ii", i, j); + if (result == NULL) return 0; + value = PyFloat_AsDouble(result); + Py_DECREF(result); + if (value == -1.0 && PyErr_Occurred()) return 0; + } + *score = value; + return 1; +} + +static PyObject* +Aligner_watermansmithbeyer_global_score_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + WATERMANSMITHBEYER_ENTER_SCORE; + switch (strand) { + case '+': { + WATERMANSMITHBEYER_GLOBAL_SCORE(COMPARE_SCORE, j); + break; + } + case '-': { + WATERMANSMITHBEYER_GLOBAL_SCORE(COMPARE_SCORE, nB-j); + break; + } + } + WATERMANSMITHBEYER_EXIT_SCORE; +} + +static PyObject* +Aligner_watermansmithbeyer_global_score_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + WATERMANSMITHBEYER_ENTER_SCORE; + switch (strand) { + case '+': + WATERMANSMITHBEYER_GLOBAL_SCORE(MATRIX_SCORE, j); + break; + case '-': + WATERMANSMITHBEYER_GLOBAL_SCORE(MATRIX_SCORE, nB-j); + break; + } + WATERMANSMITHBEYER_EXIT_SCORE; +} + +static PyObject* +Aligner_watermansmithbeyer_local_score_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + double maximum = 0.0; + WATERMANSMITHBEYER_ENTER_SCORE; + switch (strand) { + case '+': { + WATERMANSMITHBEYER_LOCAL_SCORE(COMPARE_SCORE, j); + break; + } + case '-': { + WATERMANSMITHBEYER_LOCAL_SCORE(COMPARE_SCORE, nB-j); + break; + } + } + WATERMANSMITHBEYER_EXIT_SCORE; +} + +static PyObject* +Aligner_watermansmithbeyer_local_score_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + double maximum = 0.0; + WATERMANSMITHBEYER_ENTER_SCORE; + switch (strand) { + case '+': { + WATERMANSMITHBEYER_LOCAL_SCORE(MATRIX_SCORE, j); + break; + } + case '-': { + WATERMANSMITHBEYER_LOCAL_SCORE(MATRIX_SCORE, nB-j); + break; + } + } + WATERMANSMITHBEYER_EXIT_SCORE; +} + +static PyObject* +Aligner_watermansmithbeyer_global_align_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + WATERMANSMITHBEYER_ENTER_ALIGN(Global); + switch (strand) { + case '+': { + WATERMANSMITHBEYER_GLOBAL_ALIGN(COMPARE_SCORE, j); + break; + } + case '-': { + WATERMANSMITHBEYER_GLOBAL_ALIGN(COMPARE_SCORE, nB-j); + break; + } + } + WATERMANSMITHBEYER_EXIT_ALIGN; +} + +static PyObject* +Aligner_watermansmithbeyer_global_align_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + WATERMANSMITHBEYER_ENTER_ALIGN(Global); + switch (strand) { + case '+': { + WATERMANSMITHBEYER_GLOBAL_ALIGN(MATRIX_SCORE, j); + break; + } + case '-': { + WATERMANSMITHBEYER_GLOBAL_ALIGN(MATRIX_SCORE, nB-j); + break; + } + } + WATERMANSMITHBEYER_EXIT_ALIGN; +} + +static PyObject* +Aligner_watermansmithbeyer_local_align_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + int im = nA; + int jm = nB; + double maximum = 0; + WATERMANSMITHBEYER_ENTER_ALIGN(Local); + switch (strand) { + case '+': { + WATERMANSMITHBEYER_LOCAL_ALIGN(COMPARE_SCORE, j); + break; + } + case '-': { + WATERMANSMITHBEYER_LOCAL_ALIGN(COMPARE_SCORE, nB-j); + break; + } + } + WATERMANSMITHBEYER_EXIT_ALIGN; +} + +static PyObject* +Aligner_watermansmithbeyer_local_align_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + int im = nA; + int jm = nB; + double maximum = 0; + WATERMANSMITHBEYER_ENTER_ALIGN(Local); + switch (strand) { + case '+': { + WATERMANSMITHBEYER_LOCAL_ALIGN(MATRIX_SCORE, j); + break; + } + case '-': { + WATERMANSMITHBEYER_LOCAL_ALIGN(MATRIX_SCORE, nB-j); + break; + } + } + WATERMANSMITHBEYER_EXIT_ALIGN; +} + +#define FOGSAA_CHECK_SCORES \ + if (mismatch >= match) { \ + PyObject *Bio_module = PyImport_ImportModule("Bio"); \ + PyObject *BiopythonWarning = PyObject_GetAttrString(Bio_module, "BiopythonWarning"); \ + Py_DECREF(Bio_module); \ + if (PyErr_WarnEx(BiopythonWarning, \ + "Match score is less than mismatch score. Algorithm may return incorrect results.", 1)) { \ + Py_DECREF(BiopythonWarning); \ + return NULL; \ + } \ + Py_DECREF(BiopythonWarning); \ + } \ + if ( self->open_left_deletion_score > mismatch || \ + self->open_internal_deletion_score > mismatch || \ + self->open_right_deletion_score > mismatch || \ + self->open_left_insertion_score > mismatch || \ + self->open_internal_insertion_score > mismatch || \ + self->open_right_insertion_score > mismatch || \ + self->extend_left_deletion_score > mismatch || \ + self->extend_internal_deletion_score > mismatch || \ + self->extend_right_deletion_score > mismatch || \ + self->extend_left_insertion_score > mismatch || \ + self->extend_internal_insertion_score > mismatch || \ + self->extend_right_insertion_score > mismatch) { \ + PyObject *Bio_module = PyImport_ImportModule("Bio"); \ + PyObject *BiopythonWarning = PyObject_GetAttrString(Bio_module, "BiopythonWarning"); \ + Py_DECREF(Bio_module); \ + if (PyErr_WarnEx(BiopythonWarning, \ + "One or more gap scores are greater than mismatch score. Algorithm may return incorrect results.", 1)) { \ + Py_DECREF(BiopythonWarning); \ + return NULL; \ + } \ + Py_DECREF(BiopythonWarning); \ + } + +static PyObject* +Aligner_fogsaa_score_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + FOGSAA_ENTER + + FOGSAA_CHECK_SCORES + + FOGSAA_DO(COMPARE_SCORE) + FOGSAA_EXIT_SCORE +} + +static PyObject* +Aligner_fogsaa_score_matrix(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + double match = substitution_matrix[0], mismatch = substitution_matrix[0]; + FOGSAA_ENTER + + // for prediction purposes, maximum score is match and minimum score is mismatch + for (i = 0; i < n*n; i++) { + if (substitution_matrix[i] > match) + match = substitution_matrix[i]; + else if (substitution_matrix[i] < mismatch) + mismatch = substitution_matrix[i]; + } + FOGSAA_CHECK_SCORES + + FOGSAA_DO(MATRIX_SCORE) + FOGSAA_EXIT_SCORE +} + +static PyObject* +Aligner_fogsaa_align_compare(Aligner* self, + const int* sA, int nA, + const int* sB, int nB, + unsigned char strand) +{ + const double match = self->match; + const double mismatch = self->mismatch; + const int wildcard = self->wildcard; + PathGenerator* paths; + Trace** M; + FOGSAA_ENTER + + FOGSAA_CHECK_SCORES + + FOGSAA_DO(COMPARE_SCORE) + FOGSAA_EXIT_ALIGN +} + +static PyObject* +Aligner_fogsaa_align_matrix(Aligner* self, + const int* sA, int nA, + + const int* sB, int nB, + unsigned char strand) +{ + const Py_ssize_t n = self->substitution_matrix.shape[0]; + const double* substitution_matrix = self->substitution_matrix.buf; + double match = substitution_matrix[0], mismatch = substitution_matrix[0]; + PathGenerator* paths; + Trace** M; + FOGSAA_ENTER + + // for prediction purposes, maximum score is match and minimum score is mismatch + for (i = 0; i < n*n; i++) { + if (substitution_matrix[i] > match) + match = substitution_matrix[i]; + else if (substitution_matrix[i] < mismatch) + mismatch = substitution_matrix[i]; + } + FOGSAA_CHECK_SCORES + + FOGSAA_DO(MATRIX_SCORE) + FOGSAA_EXIT_ALIGN +} + +static bool _check_indices(Py_buffer* view, Py_buffer* substitution_matrix) { + const Py_ssize_t m = substitution_matrix->shape[0]; + const int* indices = view->buf; + const Py_ssize_t n = view->len / view->itemsize; + Py_ssize_t i; + for (i = 0; i < n; i++) { + const int index = indices[i]; + if (index < 0) { + PyErr_Format(PyExc_ValueError, + "sequence item %zd is negative (%d)", + i, index); + return false; + } + if (index >= m) { + PyErr_Format(PyExc_ValueError, + "sequence item %zd is out of bound" + " (%d, should be < %zd)", i, index, m); + return false; + } + } + return true; +} + +static bool _map_indices(Py_buffer* view, const int* mapping, Py_ssize_t m) { + Py_ssize_t i; + const Py_ssize_t n = view->len / view->itemsize; + int* const indices = view->buf; + for (i = 0; i < n; i++) { + int index = indices[i]; + if (index < 0) { + PyErr_Format(PyExc_ValueError, + "sequence item %zd is negative (%d)", + i, index); + return false; + } + if (index >= m) { + PyErr_Format(PyExc_ValueError, + "sequence item %zd is out of bound" + " (%d, should be < %zd)", i, index, m); + return false; + } + index = mapping[index]; + if (index == MISSING_LETTER) { + PyErr_SetString(PyExc_ValueError, + "sequence contains letters not in the alphabet"); + return false; + } + indices[i] = index; + } + return true; +} + +static bool _prepare_indices(Py_buffer* substitution_matrix, Py_buffer* bA, Py_buffer* bB) +{ + if (PyObject_IsInstance(substitution_matrix->obj, + (PyObject*)Array_Type)) { + const PyTypeObject* basetype = Array_Type->tp_base; + const Py_ssize_t offset = basetype->tp_basicsize; + Fields* fields = (Fields*)((intptr_t)substitution_matrix->obj + offset); + Py_buffer* buffer = &fields->mapping; + const int* mapping = buffer->buf; + if (mapping) { + const Py_ssize_t m = buffer->len / buffer->itemsize; + if (!_map_indices(bA, mapping, m)) return false; + if (!_map_indices(bB, mapping, m)) return false; + return true; + } + } + if (!_check_indices(bA, substitution_matrix)) return false; + if (!_check_indices(bB, substitution_matrix)) return false; + return true; +} + +static int +sequence_converter(PyObject* argument, void* pointer) +{ + Py_buffer* view = pointer; + const int flag = PyBUF_FORMAT | PyBUF_C_CONTIGUOUS; + + if (argument == NULL) { + PyBuffer_Release(view); + return 1; + } + + if (PyObject_GetBuffer(argument, view, flag) != 0) { + PyErr_SetString(PyExc_TypeError, "argument is not a sequence"); + return 0; + } + if (view->ndim != 1) { + PyErr_Format(PyExc_ValueError, + "sequence has incorrect rank (%d expected 1)", view->ndim); + PyBuffer_Release(view); + return 0; + } + if (view->len == 0) { + PyErr_SetString(PyExc_ValueError, "sequence has zero length"); + PyBuffer_Release(view); + return 0; + } + if (strcmp(view->format, "i") != 0 && strcmp(view->format, "l") != 0) { + PyErr_Format(PyExc_ValueError, + "sequence has incorrect data type '%s'", view->format); + PyBuffer_Release(view); + return 0; + } + if (view->itemsize != sizeof(int)) { + PyErr_Format(PyExc_ValueError, + "sequence has unexpected item byte size " + "(%ld, expected %ld)", view->itemsize, sizeof(int)); + PyBuffer_Release(view); + return 0; + } + return Py_CLEANUP_SUPPORTED; +} + +static int +strand_converter(PyObject* argument, void* pointer) +{ + if (!PyUnicode_Check(argument)) goto error; + if (PyUnicode_READY(argument) == -1) return 0; + if (PyUnicode_GET_LENGTH(argument) == 1) { + const Py_UCS4 ch = PyUnicode_READ_CHAR(argument, 0); + if (ch < 128) { + const char c = ch; + if (ch == '+' || ch == '-') { + *((char*)pointer) = c; + return 1; + } + } + } +error: + PyErr_SetString(PyExc_ValueError, "strand must be '+' or '-'"); + return 0; +} + +static const char Aligner_score__doc__[] = "calculates the alignment score"; + +static PyObject* +Aligner_score(Aligner* self, PyObject* args, PyObject* keywords) +{ + const int* sA; + const int* sB; + int nA; + int nB; + Py_buffer bA = {0}; + Py_buffer bB = {0}; + const Mode mode = self->mode; + const Algorithm algorithm = _get_algorithm(self); + char strand = '+'; + PyObject* result = NULL; + PyObject* substitution_matrix = self->substitution_matrix.obj; + + static char *kwlist[] = {"sequenceA", "sequenceB", "strand", NULL}; + + if (!PyArg_ParseTupleAndKeywords(args, keywords, "O&O&O&", kwlist, + sequence_converter, &bA, + sequence_converter, &bB, + strand_converter, &strand)) + return NULL; + + if (substitution_matrix) { + if (!_prepare_indices(&self->substitution_matrix, &bA, &bB)) goto exit; + } + + nA = (int) (bA.len / bA.itemsize); + nB = (int) (bB.len / bB.itemsize); + if (nA != bA.len / bA.itemsize || nB != bB.len / bB.itemsize) { + PyErr_SetString(PyExc_ValueError, "sequences too long"); + goto exit; + } + sA = bA.buf; + sB = bB.buf; + + switch (algorithm) { + case NeedlemanWunschSmithWaterman: + switch (mode) { + case Global: + if (substitution_matrix) + result = Aligner_needlemanwunsch_score_matrix(self, sA, nA, sB, nB, strand); + else + result = Aligner_needlemanwunsch_score_compare(self, sA, nA, sB, nB, strand); + break; + case Local: + if (substitution_matrix) + result = Aligner_smithwaterman_score_matrix(self, sA, nA, sB, nB); + else + result = Aligner_smithwaterman_score_compare(self, sA, nA, sB, nB); + break; + default: + ERR_UNEXPECTED_MODE + goto exit; + } + break; + case Gotoh: + switch (mode) { + case Global: + if (substitution_matrix) + result = Aligner_gotoh_global_score_matrix(self, sA, nA, sB, nB, strand); + else + result = Aligner_gotoh_global_score_compare(self, sA, nA, sB, nB, strand); + break; + case Local: + if (substitution_matrix) + result = Aligner_gotoh_local_score_matrix(self, sA, nA, sB, nB); + else + result = Aligner_gotoh_local_score_compare(self, sA, nA, sB, nB); + break; + default: + ERR_UNEXPECTED_MODE + goto exit; + } + break; + case WatermanSmithBeyer: + switch (mode) { + case Global: + if (substitution_matrix) + result = Aligner_watermansmithbeyer_global_score_matrix(self, sA, nA, sB, nB, strand); + else + result = Aligner_watermansmithbeyer_global_score_compare(self, sA, nA, sB, nB, strand); + break; + case Local: + if (substitution_matrix) + result = Aligner_watermansmithbeyer_local_score_matrix(self, sA, nA, sB, nB, strand); + else + result = Aligner_watermansmithbeyer_local_score_compare(self, sA, nA, sB, nB, strand); + break; + default: + ERR_UNEXPECTED_MODE + goto exit; + } + break; + case FOGSAA: + if (mode != FOGSAA_Mode) { + ERR_UNEXPECTED_MODE + goto exit; + } + if (substitution_matrix) + result = Aligner_fogsaa_score_matrix(self, sA, nA, sB, nB, strand); + else + result = Aligner_fogsaa_score_compare(self, sA, nA, sB, nB, strand); + break; + case Unknown: + default: + ERR_UNEXPECTED_ALGORITHM + break; + } + +exit: + sequence_converter(NULL, &bA); + sequence_converter(NULL, &bB); + + return result; +} + +static const char Aligner_align__doc__[] = "align two sequences"; + +static PyObject* +Aligner_align(Aligner* self, PyObject* args, PyObject* keywords) +{ + const int* sA; + const int* sB; + int nA; + int nB; + Py_buffer bA = {0}; + Py_buffer bB = {0}; + const Mode mode = self->mode; + const Algorithm algorithm = _get_algorithm(self); + char strand = '+'; + PyObject* result = NULL; + PyObject* substitution_matrix = self->substitution_matrix.obj; + + static char *kwlist[] = {"sequenceA", "sequenceB", "strand", NULL}; + + if(!PyArg_ParseTupleAndKeywords(args, keywords, "O&O&O&", kwlist, + sequence_converter, &bA, + sequence_converter, &bB, + strand_converter, &strand)) + return NULL; + + if (substitution_matrix) { + if (!_prepare_indices(&self->substitution_matrix, &bA, &bB)) goto exit; + } + + nA = (int) (bA.len / bA.itemsize); + nB = (int) (bB.len / bB.itemsize); + if (nA != bA.len / bA.itemsize || nB != bB.len / bB.itemsize) { + PyErr_SetString(PyExc_ValueError, "sequences too long"); + goto exit; + } + sA = bA.buf; + sB = bB.buf; + + switch (algorithm) { + case NeedlemanWunschSmithWaterman: + switch (mode) { + case Global: + if (substitution_matrix) + result = Aligner_needlemanwunsch_align_matrix(self, sA, nA, sB, nB, strand); + else + result = Aligner_needlemanwunsch_align_compare(self, sA, nA, sB, nB, strand); + break; + case Local: + if (substitution_matrix) + result = Aligner_smithwaterman_align_matrix(self, sA, nA, sB, nB, strand); + else + result = Aligner_smithwaterman_align_compare(self, sA, nA, sB, nB, strand); + break; + default: + ERR_UNEXPECTED_MODE + goto exit; + } + break; + case Gotoh: + switch (mode) { + case Global: + if (substitution_matrix) + result = Aligner_gotoh_global_align_matrix(self, sA, nA, sB, nB, strand); + else + result = Aligner_gotoh_global_align_compare(self, sA, nA, sB, nB, strand); + break; + case Local: + if (substitution_matrix) + result = Aligner_gotoh_local_align_matrix(self, sA, nA, sB, nB, strand); + else + result = Aligner_gotoh_local_align_compare(self, sA, nA, sB, nB, strand); + break; + default: + ERR_UNEXPECTED_MODE + goto exit; + } + break; + case WatermanSmithBeyer: + switch (mode) { + case Global: + if (substitution_matrix) + result = Aligner_watermansmithbeyer_global_align_matrix(self, sA, nA, sB, nB, strand); + else + result = Aligner_watermansmithbeyer_global_align_compare(self, sA, nA, sB, nB, strand); + break; + case Local: + if (substitution_matrix) + result = Aligner_watermansmithbeyer_local_align_matrix(self, sA, nA, sB, nB, strand); + else + result = Aligner_watermansmithbeyer_local_align_compare(self, sA, nA, sB, nB, strand); + break; + default: + ERR_UNEXPECTED_MODE + goto exit; + } + break; + case FOGSAA: + if (mode != FOGSAA_Mode) { + ERR_UNEXPECTED_MODE + goto exit; + } + if (substitution_matrix) + result = Aligner_fogsaa_align_matrix(self, sA, nA, sB, nB, strand); + else + result = Aligner_fogsaa_align_compare(self, sA, nA, sB, nB, strand); + break; + case Unknown: + default: + ERR_UNEXPECTED_ALGORITHM + break; + } + +exit: + sequence_converter(NULL, &bA); + sequence_converter(NULL, &bB); + + return result; +} + +static char Aligner_doc[] = +"The PairwiseAligner class implements common algorithms to align two\n" +"sequences to each other.\n"; + +static PyObject* +Aligner_warn_defaults_changed(Aligner* self) +// FIXME remove this function once Biopython release 1.87 is out +{ + if (warned) + Py_RETURN_NONE; + if (self->open_internal_insertion_score_set + && self->extend_internal_insertion_score_set + && self->open_left_insertion_score_set + && self->extend_left_insertion_score_set + && self->open_right_insertion_score_set + && self->extend_right_insertion_score_set + && self->open_internal_deletion_score_set + && self->extend_internal_deletion_score_set + && self->open_left_deletion_score_set + && self->extend_left_deletion_score_set + && self->open_right_deletion_score_set + && self->extend_right_deletion_score_set) { + Py_RETURN_NONE; + } + warned = true; + PyErr_WarnEx(PyExc_UserWarning, +"\n" +"Note that the default value for the gap score parameter of a\n" +"PairwiseAligner object has changed.\n" +"\n" +"In older versions of Biopython, the pairwise aligner was initialized\n" +"by default with a match score of +1, a mismatch score of 0, and a gap\n" +"score of 0. This choice was made to be consistent with the pairwise\n" +"alignment code in Bio.pairwise2.\n" +"\n" +"However, this scoring scheme tends to produce a large number of alignments\n" +"with only trivial difference between them. In particular, a mismatch\n" +"between two letters, a single insertion followed by a deletion, and a\n" +"deletion followed by an insertion are all assigned the same score. For long\n" +"sequences, the number of alignments with such trivial differences can be\n" +"astronomical.\n" +"\n" +"In Biopython 1.86, the default gap score was therefore changed to -1,\n" +"while the default match score remained +1 and the default mismatch score\n" +"remained 0.\n", 1); + Py_RETURN_NONE; +} + +static PyMethodDef Aligner_methods[] = { + {"score", + (PyCFunction)Aligner_score, + METH_VARARGS | METH_KEYWORDS, + Aligner_score__doc__ + }, + {"align", + (PyCFunction)Aligner_align, + METH_VARARGS | METH_KEYWORDS, + Aligner_align__doc__ + }, + {"warn_defaults_changed", + (PyCFunction)Aligner_warn_defaults_changed, + METH_NOARGS, + "return False if all gap scores have been set explicitly, and True otherwise." + }, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +static PyTypeObject Aligner_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "_pairwisealigner.PairwiseAligner", + .tp_basicsize = sizeof(Aligner), + .tp_dealloc = (destructor)Aligner_dealloc, + .tp_repr = (reprfunc)Aligner_repr, + .tp_str = (reprfunc)Aligner_str, + .tp_flags =Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + .tp_doc = Aligner_doc, + .tp_methods = Aligner_methods, + .tp_getset = Aligner_getset, + .tp_init = (initproc)Aligner_init, +}; + + +/* Module definition */ + +static char _pairwisealigner__doc__[] = +"C extension module implementing pairwise alignment algorithms"; + +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + .m_name = "_pairwisealigner", + .m_doc = _pairwisealigner__doc__, + .m_size = -1, +}; + +PyObject * +PyInit__pairwisealigner(void) +{ + PyObject* module; + Aligner_Type.tp_new = PyType_GenericNew; + + if (PyType_Ready(&Aligner_Type) < 0 + || PyType_Ready(&PathGenerator_Type) < 0) + return NULL; + + module = PyModule_Create(&moduledef); + if (!module) return NULL; + + Py_INCREF(&Aligner_Type); + /* Reference to Aligner_Type will be stolen by PyModule_AddObject + * only if it is successful. */ + if (PyModule_AddObject(module, + "PairwiseAligner", (PyObject*) &Aligner_Type) < 0) { + Py_DECREF(&Aligner_Type); + Py_DECREF(module); + return NULL; + } + + PyObject *mod = PyImport_ImportModule("Bio.Align.substitution_matrices._arraycore"); + if (!mod) { + Py_DECREF(&Aligner_Type); + Py_DECREF(module); + return NULL; + } + + Array_Type = (PyTypeObject*) PyObject_GetAttrString(mod, "Array"); + Py_DECREF(mod); + + if (!Array_Type) { + Py_DECREF(&Aligner_Type); + Py_DECREF(module); + return NULL; + } + + return module; +} diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.h b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.h new file mode 100644 index 0000000000000000000000000000000000000000..e60833857e1cf3b967f4a9e14736307f06e825e0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.h @@ -0,0 +1,60 @@ +/* Copyright 2018-2019 by Michiel de Hoon. All rights reserved. + * This file is part of the Biopython distribution and governed by your + * choice of the "Biopython License Agreement" or the "BSD 3-Clause License". + * Please see the LICENSE file that should have been included as part of this + * package. + */ + + +#define PY_SSIZE_T_CLEAN +#include "Python.h" + +#define HORIZONTAL 0x1 +#define VERTICAL 0x2 +#define DIAGONAL 0x4 + +typedef enum {NeedlemanWunschSmithWaterman, + Gotoh, + WatermanSmithBeyer, + FOGSAA, + Unknown} Algorithm; + +typedef enum {Global, Local, FOGSAA_Mode} Mode; + +typedef struct { + PyObject_HEAD + Mode mode; + Algorithm algorithm; + double match; + double mismatch; + double epsilon; + double open_internal_insertion_score; + double extend_internal_insertion_score; + double open_left_insertion_score; + double extend_left_insertion_score; + double open_right_insertion_score; + double extend_right_insertion_score; + double open_internal_deletion_score; + double extend_internal_deletion_score; + double open_left_deletion_score; + double extend_left_deletion_score; + double open_right_deletion_score; + double extend_right_deletion_score; + bool open_internal_insertion_score_set; + bool extend_internal_insertion_score_set; + bool open_left_insertion_score_set; + bool extend_left_insertion_score_set; + bool open_right_insertion_score_set; + bool extend_right_insertion_score_set; + bool open_internal_deletion_score_set; + bool extend_internal_deletion_score_set; + bool open_left_deletion_score_set; + bool extend_left_deletion_score_set; + bool open_right_deletion_score_set; + bool extend_right_deletion_score_set; + PyObject* insertion_score_function; + PyObject* deletion_score_function; + Py_buffer substitution_matrix; + PyObject* alphabet; + int wildcard; +} Aligner; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/a2m.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/a2m.py new file mode 100644 index 0000000000000000000000000000000000000000..6da7be15802351fe168967914a46f0c63f40a744 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/a2m.py @@ -0,0 +1,121 @@ +# Copyright 2022 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for A2M files. + +A2M files are alignment files created by align2model or hmmscore in the SAM +Sequence Alignment and Modeling Software System. +""" + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Alignment file writer for the A2M file format.""" + + fmt = "A2M" + + def format_alignment(self, alignment): + """Return a string with the alignment in the A2M file format.""" + if not isinstance(alignment, Alignment): + raise TypeError("Expected an Alignment object") + lines = [] + state = alignment.column_annotations["state"] + for sequence, line in zip(alignment.sequences, alignment): + try: + name = sequence.id + except AttributeError: + name = "" + try: + description = sequence.description + except AttributeError: + description = "" + if description: + lines.append(f">{name} {description}") + else: + lines.append(f">{name}") + s = "" + for c, m in zip(line, state): + if m == "D": + s += c.upper() + elif m == "I": + if c == "-": + s += "." + else: + s += c.lower() + lines.append(s) + return "\n".join(lines) + "\n" + + write_alignments = interfaces.AlignmentWriter.write_single_alignment + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Alignment iterator for files in the A2M file format. + + An A2M file contains one multiple alignment. Matches are represented by + upper case letters and deletions by dashes in alignment columns containing + matches or deletions only. Insertions are represented by lower case letters, + with gaps aligned to the insertion shown as periods. Header lines start + with '>' followed by the name of the sequence, and optionally a description. + """ + + fmt = "A2M" + + def _read_next_alignment(self, stream): + names = [] + descriptions = [] + lines = [] + for line in stream: + if line.startswith(">"): + parts = line[1:].rstrip().split(None, 1) + try: + name = parts[0] + except IndexError: + name = "" + try: + description = parts[1] + except IndexError: + description = "" + names.append(name) + descriptions.append(description) + lines.append("") + else: + lines[-1] += line.strip() + if not lines: + if self._stream.tell() == 0: + raise ValueError("Empty file.") + return + state = "" + for c in lines[0]: + if c == "-" or c.isupper(): + state += "D" # Match/deletion state + elif c == "." or c.islower(): + state += "I" # Insertion state + else: + raise Exception("Unexpected letter '%s' in alignment" % c) + for line in lines[1:]: + for c, m in zip(line, state): + if m == "D": # Match/deletion state + assert c == "-" or c.isupper() + elif m == "I": # Insertion state + assert c == "." or c.islower() + else: + raise Exception("Unexpected letter '%s' in alignment" % c) + for i, line in enumerate(lines): + lines[i] = line.upper().replace(".", "-").encode() + seqdata, coordinates = Alignment.parse_printed_alignment(lines) + records = [] + for name, description, seqrow in zip(names, descriptions, seqdata): + sequence = Seq(seqrow) + record = SeqRecord(sequence, name, description=description) + records.append(record) + alignment = Alignment(records, coordinates) + alignment.column_annotations = {} + alignment.column_annotations["state"] = state + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/analysis.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..5c89f0a2adff7224b0667a7d3ed26094997a16f9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/analysis.py @@ -0,0 +1,1299 @@ +# Copyright 2013 by Zheng Ruan (zruan1991@gmail.com). All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Code for performing calculations on codon alignments.""" + +import sys +from collections import Counter +from collections import defaultdict +from heapq import heapify +from heapq import heappop +from heapq import heappush +from itertools import permutations +from math import erfc +from math import floor +from math import log +from math import sqrt + +import numpy as np + +from Bio.Align import Alignment +from Bio.Data import CodonTable + + +def calculate_dn_ds(alignment, method="NG86", codon_table=None, k=1, cfreq=None): + """Calculate dN and dS of the given two sequences. + + Available methods: + - NG86 - `Nei and Gojobori (1986)`_ (PMID 3444411). + - LWL85 - `Li et al. (1985)`_ (PMID 3916709). + - ML - `Goldman and Yang (1994)`_ (PMID 7968486). + - YN00 - `Yang and Nielsen (2000)`_ (PMID 10666704). + + .. _`Nei and Gojobori (1986)`: http://www.ncbi.nlm.nih.gov/pubmed/3444411 + .. _`Li et al. (1985)`: http://www.ncbi.nlm.nih.gov/pubmed/3916709 + .. _`Goldman and Yang (1994)`: http://mbe.oxfordjournals.org/content/11/5/725 + .. _`Yang and Nielsen (2000)`: https://doi.org/10.1093/oxfordjournals.molbev.a026236 + + Arguments: + - k - transition/transversion rate ratio + - cfreq - Current codon frequency vector can only be specified + when you are using ML method. Possible ways of + getting cfreq are: F1x4, F3x4 and F61. + + """ + if cfreq is None: + cfreq = "F3x4" + elif cfreq is not None and method != "ML": + raise ValueError("cfreq can only be specified when you are using ML method") + elif cfreq not in ("F1x4", "F3x4", "F61"): + raise ValueError("cfreq must be 'F1x4', 'F3x4', or 'F61'") + if codon_table is None: + codon_table = CodonTable.generic_by_id[1] + codons1 = [] + codons2 = [] + sequence1, sequence2 = alignment.sequences + try: + sequence1 = sequence1.seq # stupid SeqRecord + except AttributeError: + pass + sequence1 = str(sequence1) + try: + sequence2 = sequence2.seq # stupid SeqRecord + except AttributeError: + pass + sequence2 = str(sequence2) + aligned1, aligned2 = alignment.aligned + for block1, block2 in zip(aligned1, aligned2): + start1, end1 = block1 + start2, end2 = block2 + codons1.extend(sequence1[i : i + 3] for i in range(start1, end1, 3)) + codons2.extend(sequence2[i : i + 3] for i in range(start2, end2, 3)) + bases = {"A", "T", "C", "G"} + for codon1 in codons1: + if not all(nucleotide in bases for nucleotide in codon1): + raise ValueError( + f"Unrecognized character in {codon1} in the target sequence" + " (Codons consist of A, T, C or G)" + ) + for codon2 in codons2: + if not all(nucleotide in bases for nucleotide in codon2): + raise ValueError( + f"Unrecognized character in {codon2} in the query sequence" + " (Codons consist of A, T, C or G)" + ) + if method == "ML": + return _ml(codons1, codons2, cfreq, codon_table) + elif method == "NG86": + return _ng86(codons1, codons2, k, codon_table) + elif method == "LWL85": + return _lwl85(codons1, codons2, codon_table) + elif method == "YN00": + return _yn00(codons1, codons2, codon_table) + else: + raise ValueError(f"Unknown method '{method}'") + + +################################################################# +# private functions for NG86 method +################################################################# + + +def _ng86(codons1, codons2, k, codon_table): + """NG86 method main function (PRIVATE).""" + S_sites1, N_sites1 = _count_site_NG86(codons1, codon_table=codon_table, k=k) + S_sites2, N_sites2 = _count_site_NG86(codons2, codon_table=codon_table, k=k) + S_sites = (S_sites1 + S_sites2) / 2.0 + N_sites = (N_sites1 + N_sites2) / 2.0 + SN = [0, 0] + for codon1, codon2 in zip(codons1, codons2): + SN = [ + m + n + for m, n in zip( + SN, _count_diff_NG86(codon1, codon2, codon_table=codon_table) + ) + ] + + ps = SN[0] / S_sites + pn = SN[1] / N_sites + if ps < 3 / 4: + dS = abs(-3.0 / 4 * log(1 - 4.0 / 3 * ps)) + else: + dS = -1 + if pn < 3 / 4: + dN = abs(-3.0 / 4 * log(1 - 4.0 / 3 * pn)) + else: + dN = -1 + return dN, dS + + +def _count_site_NG86(codons, codon_table, k=1): + """Count synonymous and non-synonymous sites of a list of codons (PRIVATE). + + Arguments: + - codons - A list of three letter codons. + - k - transition/transversion rate ratio. + + """ + S_site = 0 # synonymous sites + N_site = 0 # non-synonymous sites + purine = ("A", "G") + pyrimidine = ("T", "C") + bases = ("A", "T", "C", "G") + for codon in codons: + neighbor_codon = {"transition": [], "transversion": []} + # classify neighbor codons + codon = codon.replace("U", "T") + for i, nucleotide in enumerate(codon): + for base in bases: + if nucleotide == base: + pass + elif nucleotide in purine and base in purine: + codon_chars = list(codon) + codon_chars[i] = base + this_codon = "".join(codon_chars) + neighbor_codon["transition"].append(this_codon) + elif nucleotide in pyrimidine and base in pyrimidine: + codon_chars = list(codon) + codon_chars[i] = base + this_codon = "".join(codon_chars) + neighbor_codon["transition"].append(this_codon) + else: + codon_chars = list(codon) + codon_chars[i] = base + this_codon = "".join(codon_chars) + neighbor_codon["transversion"].append(this_codon) + # count synonymous and non-synonymous sites + aa = codon_table.forward_table[codon] + this_codon_N_site = this_codon_S_site = 0 + for neighbor in neighbor_codon["transition"]: + if neighbor in codon_table.stop_codons: + this_codon_N_site += k + elif codon_table.forward_table[neighbor] == aa: + this_codon_S_site += k + else: + this_codon_N_site += k + for neighbor in neighbor_codon["transversion"]: + if neighbor in codon_table.stop_codons: + this_codon_N_site += 1 + elif codon_table.forward_table[neighbor] == aa: + this_codon_S_site += 1 + else: + this_codon_N_site += 1 + norm_const = (this_codon_N_site + this_codon_S_site) / 3 + S_site += this_codon_S_site / norm_const + N_site += this_codon_N_site / norm_const + return (S_site, N_site) + + +def _count_diff_NG86(codon1, codon2, codon_table): + """Count differences between two codons, three-letter string (PRIVATE). + + The function will take multiple pathways from codon1 to codon2 + into account. + """ + SN = [0, 0] # synonymous and nonsynonymous counts + if codon1 == codon2: + return SN + else: + diff_pos = [ + i + for i, (nucleotide1, nucleotide2) in enumerate(zip(codon1, codon2)) + if nucleotide1 != nucleotide2 + ] + + def compare_codon(codon1, codon2, codon_table, weight=1): + """Compare two codon accounting for different pathways.""" + sd = nd = 0 + if len(set(map(codon_table.forward_table.get, [codon1, codon2]))) == 1: + sd += weight + else: + nd += weight + return (sd, nd) + + if len(diff_pos) == 1: + SN = [ + i + j + for i, j in zip( + SN, compare_codon(codon1, codon2, codon_table=codon_table) + ) + ] + elif len(diff_pos) == 2: + for i in diff_pos: + temp_codon = codon1[:i] + codon2[i] + codon1[i + 1 :] + SN = [ + i + j + for i, j in zip( + SN, + compare_codon( + codon1, temp_codon, codon_table=codon_table, weight=0.5 + ), + ) + ] + SN = [ + i + j + for i, j in zip( + SN, + compare_codon( + temp_codon, codon2, codon_table=codon_table, weight=0.5 + ), + ) + ] + elif len(diff_pos) == 3: + paths = list(permutations([0, 1, 2], 3)) + tmp_codon = [] + for index1, index2, index3 in paths: + tmp1 = codon1[:index1] + codon2[index1] + codon1[index1 + 1 :] + tmp2 = tmp1[:index2] + codon2[index2] + tmp1[index2 + 1 :] + tmp_codon.append((tmp1, tmp2)) + SN = [ + i + j + for i, j in zip( + SN, compare_codon(codon1, tmp1, codon_table, weight=0.5 / 3) + ) + ] + SN = [ + i + j + for i, j in zip( + SN, compare_codon(tmp1, tmp2, codon_table, weight=0.5 / 3) + ) + ] + SN = [ + i + j + for i, j in zip( + SN, compare_codon(tmp2, codon2, codon_table, weight=0.5 / 3) + ) + ] + return SN + + +################################################################# +# private functions for LWL85 method +################################################################# + + +def _lwl85(codons1, codons2, codon_table): + """LWL85 method main function (PRIVATE). + + Nomenclature is according to Li et al. (1985), PMID 3916709. + """ + codon_fold_dict = _get_codon_fold(codon_table) + # count number of sites in different degenerate classes + fold0 = [0, 0] + fold2 = [0, 0] + fold4 = [0, 0] + for codon in codons1 + codons2: + fold_num = codon_fold_dict[codon] + for f in fold_num: + if f == "0": + fold0[0] += 1 + elif f == "2": + fold2[0] += 1 + elif f == "4": + fold4[0] += 1 + L = [sum(fold0) / 2.0, sum(fold2) / 2.0, sum(fold4) / 2.0] + # count number of differences in different degenerate classes + PQ = [0] * 6 # with P0, P2, P4, Q0, Q2, Q4 in each position + for codon1, codon2 in zip(codons1, codons2): + if codon1 == codon2: + continue + PQ = [ + i + j + for i, j in zip(PQ, _diff_codon(codon1, codon2, fold_dict=codon_fold_dict)) + ] + PQ = [i / j for i, j in zip(PQ, L * 2)] + P = PQ[:3] + Q = PQ[3:] + A = [ + (1.0 / 2) * log(1.0 / (1 - 2 * i - j)) - (1.0 / 4) * log(1.0 / (1 - 2 * j)) + for i, j in zip(P, Q) + ] + B = [(1.0 / 2) * log(1.0 / (1 - 2 * i)) for i in Q] + dS = 3 * (L[2] * A[1] + L[2] * (A[2] + B[2])) / (L[1] + 3 * L[2]) + dN = 3 * (L[2] * B[1] + L[0] * (A[0] + B[0])) / (2 * L[1] + 3 * L[0]) + return dN, dS + + +def _get_codon_fold(codon_table): + """Classify different position in a codon into different folds (PRIVATE).""" + fold_table = {} + forward_table = codon_table.forward_table + bases = {"A", "T", "C", "G"} + for codon in forward_table: + if "U" in codon: + continue + fold = "" + codon_base_lst = list(codon) + for i, base in enumerate(codon_base_lst): + other_bases = bases - set(base) + aa = [] + for other_base in other_bases: + codon_base_lst[i] = other_base + try: + aa.append(forward_table["".join(codon_base_lst)]) + except KeyError: + aa.append("stop") + if aa.count(forward_table[codon]) == 0: + fold += "0" + elif aa.count(forward_table[codon]) in (1, 2): + fold += "2" + elif aa.count(forward_table[codon]) == 3: + fold += "4" + else: + raise RuntimeError( + "Unknown Error, cannot assign the position to a fold" + ) + codon_base_lst[i] = base + fold_table[codon] = fold + return fold_table + + +def _diff_codon(codon1, codon2, fold_dict): + """Count number of different substitution types between two codons (PRIVATE). + + returns tuple (P0, P2, P4, Q0, Q2, Q4) + + Nomenclature is according to Li et al. (1958), PMID 3916709. + """ + P0 = P2 = P4 = Q0 = Q2 = Q4 = 0 + fold_num = fold_dict[codon1] + purine = ("A", "G") + pyrimidine = ("T", "C") + for n, (nucleotide1, nucleotide2) in enumerate(zip(codon1, codon2)): + if nucleotide1 == nucleotide2: + pass + elif nucleotide1 in purine and nucleotide2 in purine: + if fold_num[n] == "0": + P0 += 1 + elif fold_num[n] == "2": + P2 += 1 + elif fold_num[n] == "4": + P4 += 1 + else: + raise RuntimeError("Unexpected fold_num %d" % fold_num[n]) + elif nucleotide1 in pyrimidine and nucleotide2 in pyrimidine: + if fold_num[n] == "0": + P0 += 1 + elif fold_num[n] == "2": + P2 += 1 + elif fold_num[n] == "4": + P4 += 1 + else: + raise RuntimeError("Unexpected fold_num %d" % fold_num[n]) + else: + # nucleotide1 in purine and nucleotide2 in pyrimidine, or + # nucleotide1 in pyrimidine and nucleotide2 in purine + if fold_num[n] == "0": + Q0 += 1 + elif fold_num[n] == "2": + Q2 += 1 + elif fold_num[n] == "4": + Q4 += 1 + else: + raise RuntimeError("Unexpected fold_num %d" % fold_num[n]) + return (P0, P2, P4, Q0, Q2, Q4) + + +################################################################# +# private functions for YN00 method +################################################################# + + +def _yn00(codons1, codons2, codon_table): + """YN00 method main function (PRIVATE). + + Nomenclature is according to Yang and Nielsen (2000), PMID 10666704. + """ + from scipy.linalg import expm + + fcodon = [ + {"A": 0, "G": 0, "C": 0, "T": 0}, + {"A": 0, "G": 0, "C": 0, "T": 0}, + {"A": 0, "G": 0, "C": 0, "T": 0}, + ] + codon_fold_dict = _get_codon_fold(codon_table) + fold0_cnt = defaultdict(int) + fold4_cnt = defaultdict(int) + for codon in codons1 + codons2: + # count sites at different codon position + fcodon[0][codon[0]] += 1 + fcodon[1][codon[1]] += 1 + fcodon[2][codon[2]] += 1 + # count sites in different degenerate fold class + fold_num = codon_fold_dict[codon] + for i, f in enumerate(fold_num): + if f == "0": + fold0_cnt[codon[i]] += 1 + elif f == "4": + fold4_cnt[codon[i]] += 1 + f0_total = sum(fold0_cnt.values()) + f4_total = sum(fold4_cnt.values()) + for i, j in zip(fold0_cnt, fold4_cnt): + fold0_cnt[i] = fold0_cnt[i] / f0_total + fold4_cnt[i] = fold4_cnt[i] / f4_total + # TODO: + # the initial kappa is different from what yn00 gives, + # try to find the problem. + TV = _get_TV(codons1, codons2, codon_table=codon_table) + k04 = (_get_kappa_t(fold0_cnt, TV), _get_kappa_t(fold4_cnt, TV)) + kappa = (f0_total * k04[0] + f4_total * k04[1]) / (f0_total + f4_total) + # kappa = 2.4285 + # count synonymous sites and non-synonymous sites + for i in range(3): + tot = sum(fcodon[i].values()) + fcodon[i] = {j: k / tot for j, k in fcodon[i].items()} + pi = defaultdict(int) + for codon in list(codon_table.forward_table.keys()) + codon_table.stop_codons: + if "U" not in codon: + pi[codon] = 0 + for codon in codons1 + codons2: + pi[codon] += 1 + S_sites1, N_sites1, bfreqSN1 = _count_site_YN00( + codons1, codons2, pi, k=kappa, codon_table=codon_table + ) + S_sites2, N_sites2, bfreqSN2 = _count_site_YN00( + codons2, codons1, pi, k=kappa, codon_table=codon_table + ) + N_sites = (N_sites1 + N_sites2) / 2 + S_sites = (S_sites1 + S_sites2) / 2 + bfreqSN = [{"A": 0, "T": 0, "C": 0, "G": 0}, {"A": 0, "T": 0, "C": 0, "G": 0}] + for i in range(2): + for base in ("A", "T", "C", "G"): + bfreqSN[i][base] = (bfreqSN1[i][base] + bfreqSN2[i][base]) / 2 + # use NG86 method to get initial t and w + SN = [0, 0] + for codon1, codon2 in zip(codons1, codons2): + SN = [ + m + n + for m, n in zip( + SN, _count_diff_NG86(codon1, codon2, codon_table=codon_table) + ) + ] + ps = SN[0] / S_sites + pn = SN[1] / N_sites + p = sum(SN) / (S_sites + N_sites) + w = log(1 - 4.0 / 3 * pn) / log(1 - 4.0 / 3 * ps) + t = -3 / 4 * log(1 - 4 / 3 * p) + tolerance = 1e-5 + dSdN_pre = [0, 0] + for temp in range(20): + # count synonymous and nonsynonymous differences under kappa, w, t + codons = [ + codon + for codon in list(codon_table.forward_table.keys()) + + codon_table.stop_codons + if "U" not in codon + ] + Q = _get_Q(pi, kappa, w, codons, codon_table) + P = expm(Q * t) + TV = [0, 0, 0, 0] # synonymous/nonsynonymous transition/transversion + codon_npath = Counter(zip(codons1, codons2)) + for (nucleotide1, nucleotide2), count in codon_npath.items(): + tv = _count_diff_YN00(nucleotide1, nucleotide2, P, codons, codon_table) + TV = [m + n * count for m, n in zip(TV, tv)] + TV = (TV[0] / S_sites, TV[1] / S_sites), (TV[2] / N_sites, TV[3] / N_sites) + # according to the DistanceF84() function of yn00.c in paml, + # the t (e.q. 10) appears in PMID: 10666704 is dS and dN + dSdN = [] + for f, tv in zip(bfreqSN, TV): + dSdN.append(_get_kappa_t(f, tv, t=True)) + t = dSdN[0] * 3 * S_sites / (S_sites + N_sites) + dSdN[1] * 3 * N_sites / ( + S_sites + N_sites + ) + w = dSdN[1] / dSdN[0] + if all(abs(i - j) < tolerance for i, j in zip(dSdN, dSdN_pre)): + return dSdN[1], dSdN[0] # dN, dS + dSdN_pre = dSdN + + +def _get_TV(codons1, codons2, codon_table): + """Get TV (PRIVATE). + + Arguments: + - T - proportions of transitional differences + - V - proportions of transversional differences + + """ + purine = ("A", "G") + pyrimidine = ("C", "T") + TV = [0, 0] + sites = 0 + for codon1, codon2 in zip(codons1, codons2): + for nucleotide1, nucleotide2 in zip(codon1, codon2): + if nucleotide1 == nucleotide2: + pass + elif nucleotide1 in purine and nucleotide2 in purine: + TV[0] += 1 + elif nucleotide1 in pyrimidine and nucleotide2 in pyrimidine: + TV[0] += 1 + else: + TV[1] += 1 + sites += 1 + return (TV[0] / sites, TV[1] / sites) + # return (TV[0], TV[1]) + + +def _get_kappa_t(pi, TV, t=False): + """Calculate kappa (PRIVATE). + + The following formula and variable names are according to PMID: 10666704 + """ + pi["Y"] = pi["T"] + pi["C"] + pi["R"] = pi["A"] + pi["G"] + A = ( + 2 * (pi["T"] * pi["C"] + pi["A"] * pi["G"]) + + 2 + * ( + pi["T"] * pi["C"] * pi["R"] / pi["Y"] + + pi["A"] * pi["G"] * pi["Y"] / pi["R"] + ) + * (1 - TV[1] / (2 * pi["Y"] * pi["R"])) + - TV[0] + ) / (2 * (pi["T"] * pi["C"] / pi["Y"] + pi["A"] * pi["G"] / pi["R"])) + B = 1 - TV[1] / (2 * pi["Y"] * pi["R"]) + a = -0.5 * log(A) # this seems to be an error in YANG's original paper + b = -0.5 * log(B) + kappaF84 = a / b - 1 + if t is False: + kappaHKY85 = 1 + ( + pi["T"] * pi["C"] / pi["Y"] + pi["A"] * pi["G"] / pi["R"] + ) * kappaF84 / (pi["T"] * pi["C"] + pi["A"] * pi["G"]) + return kappaHKY85 + else: + t = ( + 4 * pi["T"] * pi["C"] * (1 + kappaF84 / pi["Y"]) + + 4 * pi["A"] * pi["G"] * (1 + kappaF84 / pi["R"]) + + 4 * pi["Y"] * pi["R"] + ) * b + return t + + +def _count_site_YN00(codons1, codons2, pi, k, codon_table): + """Site counting method from Ina / Yang and Nielsen (PRIVATE). + + Method from `Ina (1995)`_ as modified by `Yang and Nielsen (2000)`_. + This will return the total number of synonymous and nonsynonymous sites + and base frequencies in each category. The function is equivalent to + the ``CountSites()`` function in ``yn00.c`` of PAML. + + .. _`Ina (1995)`: https://doi.org/10.1007/BF00167113 + .. _`Yang and Nielsen (2000)`: https://doi.org/10.1093/oxfordjournals.molbev.a026236 + + """ + length = len(codons1) + assert length == len(codons2) + purine = ("A", "G") + pyrimidine = ("T", "C") + bases = ("A", "T", "C", "G") + codon_dict = codon_table.forward_table + stop = codon_table.stop_codons + codon_npath = Counter(zip(codons1, codons2)) + S_sites = N_sites = 0 + freqSN = [ + {"A": 0, "T": 0, "C": 0, "G": 0}, # synonymous + {"A": 0, "T": 0, "C": 0, "G": 0}, + ] # nonsynonymous + for codon_pair, npath in codon_npath.items(): + codon = codon_pair[0] + S = N = 0 + for pos in range(3): + for base in bases: + if codon[pos] == base: + continue + neighbor_codon = codon[:pos] + base + codon[pos + 1 :] + if neighbor_codon in stop: + continue + weight = pi[neighbor_codon] + if codon[pos] in pyrimidine and base in pyrimidine: + weight *= k + elif codon[pos] in purine and base in purine: + weight *= k + if codon_dict[codon] == codon_dict[neighbor_codon]: + S += weight + freqSN[0][base] += weight * npath + else: + N += weight + freqSN[1][base] += weight * npath + S_sites += S * npath + N_sites += N * npath + norm_const = 3 * length / (S_sites + N_sites) + S_sites *= norm_const + N_sites *= norm_const + for i in freqSN: + norm_const = sum(i.values()) + for b in i: + i[b] /= norm_const + return S_sites, N_sites, freqSN + + +def _count_diff_YN00(codon1, codon2, P, codons, codon_table): + """Count differences between two codons (three-letter string; PRIVATE). + + The function will weighted multiple pathways from codon1 to codon2 + according to P matrix of codon substitution. The proportion + of transition and transversion (TV) will also be calculated in + the function. + """ + TV = [ + 0, + 0, + 0, + 0, + ] # transition and transversion counts (synonymous and nonsynonymous) + if codon1 == codon2: + return TV + else: + diff_pos = [ + i + for i, (nucleotide1, nucleotide2) in enumerate(zip(codon1, codon2)) + if nucleotide1 != nucleotide2 + ] + + def count_TV(codon1, codon2, diff, codon_table, weight=1): + purine = ("A", "G") + pyrimidine = ("T", "C") + dic = codon_table.forward_table + stop = codon_table.stop_codons + if codon1 in stop or codon2 in stop: + # stop codon is always considered as nonsynonymous + if codon1[diff] in purine and codon2[diff] in purine: + return [0, 0, weight, 0] + elif codon1[diff] in pyrimidine and codon2[diff] in pyrimidine: + return [0, 0, weight, 0] + else: + return [0, 0, 0, weight] + elif dic[codon1] == dic[codon2]: + if codon1[diff] in purine and codon2[diff] in purine: + return [weight, 0, 0, 0] + elif codon1[diff] in pyrimidine and codon2[diff] in pyrimidine: + return [weight, 0, 0, 0] + else: + return [0, weight, 0, 0] + else: + if codon1[diff] in purine and codon2[diff] in purine: + return [0, 0, weight, 0] + elif codon1[diff] in pyrimidine and codon2[diff] in pyrimidine: + return [0, 0, weight, 0] + else: + return [0, 0, 0, weight] + + if len(diff_pos) == 1: + TV = [ + p + q + for p, q in zip(TV, count_TV(codon1, codon2, diff_pos[0], codon_table)) + ] + elif len(diff_pos) == 2: + tmp_codons = [codon1[:i] + codon2[i] + codon1[i + 1 :] for i in diff_pos] + path_prob = [] + for codon in tmp_codons: + codon_idx = list(map(codons.index, [codon1, codon, codon2])) + prob = (P[codon_idx[0], codon_idx[1]], P[codon_idx[1], codon_idx[2]]) + path_prob.append(prob[0] * prob[1]) + path_prob = [2 * i / sum(path_prob) for i in path_prob] + for n, i in enumerate(diff_pos): + codon = codon1[:i] + codon2[i] + codon1[i + 1 :] + TV = [ + p + q + for p, q in zip( + TV, + count_TV( + codon1, codon, i, codon_table, weight=path_prob[n] / 2 + ), + ) + ] + TV = [ + p + q + for p, q in zip( + TV, + count_TV( + codon1, codon, i, codon_table, weight=path_prob[n] / 2 + ), + ) + ] + elif len(diff_pos) == 3: + paths = list(permutations([0, 1, 2], 3)) + path_prob = [] + tmp_codons = [] + for index1, index2, index3 in paths: + tmp1 = codon1[:index1] + codon2[index1] + codon1[index1 + 1 :] + tmp2 = tmp1[:index2] + codon2[index2] + tmp1[index2 + 1 :] + tmp_codons.append((tmp1, tmp2)) + codon_idx = list(map(codons.index, [codon1, tmp1, tmp2, codon2])) + prob = ( + P[codon_idx[0], codon_idx[1]], + P[codon_idx[1], codon_idx[2]], + P[codon_idx[2], codon_idx[3]], + ) + path_prob.append(prob[0] * prob[1] * prob[2]) + path_prob = [3 * i / sum(path_prob) for i in path_prob] + for codon, j, k in zip(tmp_codons, path_prob, paths): + TV = [ + p + q + for p, q in zip( + TV, count_TV(codon1, codon[0], k[0], codon_table, weight=j / 3) + ) + ] + TV = [ + p + q + for p, q in zip( + TV, + count_TV(codon[0], codon[1], k[1], codon_table, weight=j / 3), + ) + ] + TV = [ + p + q + for p, q in zip( + TV, count_TV(codon[1], codon2, k[1], codon_table, weight=j / 3) + ) + ] + return TV + + +################################################################# +# private functions for Maximum Likelihood method +################################################################# + + +def _ml(codons1, codons2, cmethod, codon_table): + """ML method main function (PRIVATE).""" + from scipy.optimize import minimize + + pi = _get_pi(codons1, codons2, cmethod, codon_table=codon_table) + codon_cnt = Counter(zip(codons1, codons2)) + codons = [ + codon + for codon in list(codon_table.forward_table.keys()) + codon_table.stop_codons + if "U" not in codon + ] + + # apply optimization + def func( + params, pi=pi, codon_cnt=codon_cnt, codons=codons, codon_table=codon_table + ): + """Temporary function, params = [t, k, w].""" + return -_likelihood_func( + params[0], + params[1], + params[2], + pi, + codon_cnt, + codons=codons, + codon_table=codon_table, + ) + + # count sites + opt_res = minimize( + func, + [1, 0.1, 2], + method="L-BFGS-B", + bounds=((1e-10, 20), (1e-10, 20), (1e-10, 10)), + tol=1e-5, + ) + t, k, w = opt_res.x + Q = _get_Q(pi, k, w, codons, codon_table) + Sd = Nd = 0 + for i, codon1 in enumerate(codons): + for j, codon2 in enumerate(codons): + if i != j: + try: + if ( + codon_table.forward_table[codon1] + == codon_table.forward_table[codon2] + ): + # synonymous count + Sd += pi[codon1] * Q[i, j] + else: + # nonsynonymous count + Nd += pi[codon1] * Q[i, j] + except KeyError: + # This is probably due to stop codons + pass + Sd *= t + Nd *= t + + # count differences (with w fixed to 1) + def func_w1( + params, pi=pi, codon_cnt=codon_cnt, codons=codons, codon_table=codon_table + ): + """Temporary function, params = [t, k]. w is fixed to 1.""" + return -_likelihood_func( + params[0], + params[1], + 1.0, + pi, + codon_cnt, + codons=codons, + codon_table=codon_table, + ) + + opt_res = minimize( + func_w1, + [1, 0.1], + method="L-BFGS-B", + bounds=((1e-10, 20), (1e-10, 20)), + tol=1e-5, + ) + t, k = opt_res.x + w = 1.0 + Q = _get_Q(pi, k, w, codons, codon_table) + rhoS = rhoN = 0 + for i, codon1 in enumerate(codons): + for j, codon2 in enumerate(codons): + if i != j: + try: + if ( + codon_table.forward_table[codon1] + == codon_table.forward_table[codon2] + ): + # synonymous count + rhoS += pi[codon1] * Q[i, j] + else: + # nonsynonymous count + rhoN += pi[codon1] * Q[i, j] + except KeyError: + # This is probably due to stop codons + pass + rhoS *= 3 + rhoN *= 3 + dN = Nd / rhoN + dS = Sd / rhoS + return dN, dS + + +def _get_pi(codons1, codons2, cmethod, codon_table): + """Obtain codon frequency dict (pi) from two codon list (PRIVATE). + + This function is designed for ML method. Available counting methods + (cfreq) are F1x4, F3x4 and F64. + """ + # TODO: + # Stop codon should not be allowed according to Yang. + # Try to modify this! + pi = {} + if cmethod == "F1x4": + fcodon = Counter( + nucleotide for codon in codons1 + codons2 for nucleotide in codon + ) + tot = sum(fcodon.values()) + fcodon = {j: k / tot for j, k in fcodon.items()} + for codon in codon_table.forward_table.keys() + codon_table.stop_codons: + if "U" not in codon: + pi[codon] = fcodon[codon[0]] * fcodon[codon[1]] * fcodon[codon[2]] + elif cmethod == "F3x4": + # three codon position + fcodon = [ + {"A": 0, "G": 0, "C": 0, "T": 0}, + {"A": 0, "G": 0, "C": 0, "T": 0}, + {"A": 0, "G": 0, "C": 0, "T": 0}, + ] + for codon in codons1 + codons2: + fcodon[0][codon[0]] += 1 + fcodon[1][codon[1]] += 1 + fcodon[2][codon[2]] += 1 + for i in range(3): + tot = sum(fcodon[i].values()) + fcodon[i] = {j: k / tot for j, k in fcodon[i].items()} + for codon in list(codon_table.forward_table.keys()) + codon_table.stop_codons: + if "U" not in codon: + pi[codon] = ( + fcodon[0][codon[0]] * fcodon[1][codon[1]] * fcodon[2][codon[2]] + ) + elif cmethod == "F61": + for codon in codon_table.forward_table.keys() + codon_table.stop_codons: + if "U" not in codon: + pi[codon] = 0.1 + for codon in codons1 + codons2: + pi[codon] += 1 + tot = sum(pi.values()) + pi = {j: k / tot for j, k in pi.items()} + return pi + + +def _q(codon1, codon2, pi, k, w, codon_table): + """Q matrix for codon substitution (PRIVATE). + + Arguments: + - codon1, codon2 : three letter codon string + - pi : expected codon frequency + - k : transition/transversion ratio + - w : nonsynonymous/synonymous rate ratio + - codon_table : Bio.Data.CodonTable object + + """ + if codon1 == codon2: + # diagonal elements is the sum of all other elements + return 0 + if codon1 in codon_table.stop_codons or codon2 in codon_table.stop_codons: + return 0 + if (codon1 not in pi) or (codon2 not in pi): + return 0 + purine = ("A", "G") + pyrimidine = ("T", "C") + diff = [ + (i, nucleotide1, nucleotide2) + for i, (nucleotide1, nucleotide2) in enumerate(zip(codon1, codon2)) + if nucleotide1 != nucleotide2 + ] + if len(diff) >= 2: + return 0 + if codon_table.forward_table[codon1] == codon_table.forward_table[codon2]: + # synonymous substitution + if diff[0][1] in purine and diff[0][2] in purine: + # transition + return k * pi[codon2] + elif diff[0][1] in pyrimidine and diff[0][2] in pyrimidine: + # transition + return k * pi[codon2] + else: + # transversion + return pi[codon2] + else: + # nonsynonymous substitution + if diff[0][1] in purine and diff[0][2] in purine: + # transition + return w * k * pi[codon2] + elif diff[0][1] in pyrimidine and diff[0][2] in pyrimidine: + # transition + return w * k * pi[codon2] + else: + # transversion + return w * pi[codon2] + + +def _get_Q(pi, k, w, codons, codon_table): + """Q matrix for codon substitution (PRIVATE).""" + codon_num = len(codons) + Q = np.zeros((codon_num, codon_num)) + for i1, codon1 in enumerate(codons): + for i2, codon2 in enumerate(codons): + if i1 != i2: + Q[i1, i2] = _q(codon1, codon2, pi, k, w, codon_table=codon_table) + nucl_substitutions = 0 + for i, codon in enumerate(codons): + Q[i, i] = -sum(Q[i, :]) + try: + nucl_substitutions += pi[codon] * (-Q[i, i]) + except KeyError: + pass + Q /= nucl_substitutions + return Q + + +def _likelihood_func(t, k, w, pi, codon_cnt, codons, codon_table): + """Likelihood function for ML method (PRIVATE).""" + from scipy.linalg import expm + + Q = _get_Q(pi, k, w, codons, codon_table) + P = expm(Q * t) + likelihood = 0 + for i, codon1 in enumerate(codons): + for j, codon2 in enumerate(codons): + if (codon1, codon2) in codon_cnt: + if P[i, j] * pi[codon1] <= 0: + likelihood += codon_cnt[(codon1, codon2)] * 0 + else: + likelihood += codon_cnt[(codon1, codon2)] * log( + pi[codon1] * P[i, j] + ) + return likelihood + + +def calculate_dn_ds_matrix(alignment, method="NG86", codon_table=None): + """Calculate dN and dS pairwise for the multiple alignment, and return as matrices. + + Argument: + - method - Available methods include NG86, LWL85, YN00 and ML. + - codon_table - Codon table to use for forward translation. + + """ + from Bio.Phylo.TreeConstruction import DistanceMatrix + + if codon_table is None: + codon_table = CodonTable.generic_by_id[1] + sequences = alignment.sequences + coordinates = alignment.coordinates + names = [record.id for record in sequences] + size = len(names) + dn_matrix = [] + ds_matrix = [] + for i in range(size): + dn_matrix.append([]) + ds_matrix.append([]) + for j in range(i): + pairwise_sequences = [sequences[i], sequences[j]] + pairwise_coordinates = coordinates[(i, j), :] + pairwise_alignment = Alignment(pairwise_sequences, pairwise_coordinates) + dn, ds = calculate_dn_ds( + pairwise_alignment, method=method, codon_table=codon_table + ) + dn_matrix[i].append(dn) + ds_matrix[i].append(ds) + dn_matrix[i].append(0.0) + ds_matrix[i].append(0.0) + dn_dm = DistanceMatrix(names, matrix=dn_matrix) + ds_dm = DistanceMatrix(names, matrix=ds_matrix) + return dn_dm, ds_dm + + +def mktest(alignment, species=None, codon_table=None): + """McDonald-Kreitman test for neutrality. + + Implement the McDonald-Kreitman test for neutrality (PMID: 1904993) + This method counts changes rather than sites + (http://mkt.uab.es/mkt/help_mkt.asp). + + Arguments: + - alignment - Alignment of gene nucleotide sequences to compare. + - species - List of the species ID for each sequence in the alignment. + Typically, the species ID is the species name as a string, or an integer. + - codon_table - Codon table to use for forward translation. + + Return the p-value of test result. + """ + if codon_table is None: + codon_table = CodonTable.generic_by_id[1] + G, nonsyn_G = _get_codon2codon_matrix(codon_table=codon_table) + unique_species = set(species) + sequences = [] + for sequence in alignment.sequences: + try: + sequence = sequence.seq + except AttributeError: + pass + sequence = str(sequence) + sequences.append(sequence) + syn_fix, nonsyn_fix, syn_poly, nonsyn_poly = 0, 0, 0, 0 + starts = sys.maxsize + for ends in alignment.coordinates.transpose(): + step = min(ends - starts) + for j in range(0, step, 3): + codons = {key: [] for key in unique_species} + for key, sequence, start in zip(species, sequences, starts): + codon = sequence[start + j : start + j + 3] + codons[key].append(codon) + fixed = True + all_codons = set() + for value in codons.values(): + value = set(value) + if len(value) > 1: + fixed = False + all_codons.update(value) + if len(all_codons) == 1: + continue + nonsyn = _count_replacement(all_codons, nonsyn_G) + syn = _count_replacement(all_codons, G) - nonsyn + if fixed is True: + # fixed + nonsyn_fix += nonsyn + syn_fix += syn + else: + # not fixed + nonsyn_poly += nonsyn + syn_poly += syn + starts = ends + return _G_test([syn_fix, nonsyn_fix, syn_poly, nonsyn_poly]) + + +def _get_codon2codon_matrix(codon_table): + """Get codon codon substitution matrix (PRIVATE). + + Elements in the matrix are number of synonymous and nonsynonymous + substitutions required for the substitution. + """ + bases = ("A", "T", "C", "G") + codons = [ + codon + for codon in list(codon_table.forward_table.keys()) + codon_table.stop_codons + if "U" not in codon + ] + # set up codon_dict considering stop codons + codon_dict = codon_table.forward_table.copy() + for stop in codon_table.stop_codons: + codon_dict[stop] = "stop" + # count site + num = len(codons) + G = {} # graph for substitution + nonsyn_G = {} # graph for nonsynonymous substitution + graph = {} + graph_nonsyn = {} + for i, codon in enumerate(codons): + graph[codon] = {} + graph_nonsyn[codon] = {} + for p in range(3): + for base in bases: + tmp_codon = codon[0:p] + base + codon[p + 1 :] + if codon_dict[codon] != codon_dict[tmp_codon]: + graph_nonsyn[codon][tmp_codon] = 1 + graph[codon][tmp_codon] = 1 + else: + if codon != tmp_codon: + graph_nonsyn[codon][tmp_codon] = 0.1 + graph[codon][tmp_codon] = 1 + for codon1 in codons: + nonsyn_G[codon1] = {} + G[codon1] = {} + for codon2 in codons: + if codon1 == codon2: + nonsyn_G[codon1][codon2] = 0 + G[codon1][codon2] = 0 + else: + nonsyn_G[codon1][codon2] = _dijkstra(graph_nonsyn, codon1, codon2) + G[codon1][codon2] = _dijkstra(graph, codon1, codon2) + return G, nonsyn_G + + +def _dijkstra(graph, start, end): + """Dijkstra's algorithm Python implementation (PRIVATE). + + Algorithm adapted from + http://thomas.pelletier.im/2010/02/dijkstras-algorithm-python-implementation/. + However, an obvious bug in:: + + if D[child_node] >(<) D[node] + child_value: + + is fixed. + This function will return the distance between start and end. + + Arguments: + - graph: Dictionary of dictionary (keys are vertices). + - start: Start vertex. + - end: End vertex. + + Output: + List of vertices from the beginning to the end. + + """ + D = {} # Final distances dict + P = {} # Predecessor dict + # Fill the dicts with default values + for node in graph.keys(): + D[node] = 100 # Vertices are unreachable + P[node] = "" # Vertices have no predecessors + D[start] = 0 # The start vertex needs no move + unseen_nodes = list(graph.keys()) # All nodes are unseen + while len(unseen_nodes) > 0: + # Select the node with the lowest value in D (final distance) + shortest = None + node = "" + for temp_node in unseen_nodes: + if shortest is None: + shortest = D[temp_node] + node = temp_node + elif D[temp_node] < shortest: + shortest = D[temp_node] + node = temp_node + # Remove the selected node from unseen_nodes + unseen_nodes.remove(node) + # For each child (ie: connected vertex) of the current node + for child_node, child_value in graph[node].items(): + if D[child_node] > D[node] + child_value: + D[child_node] = D[node] + child_value + # To go to child_node, you have to go through node + P[child_node] = node + if node == end: + break + # Set a clean path + path = [] + # We begin from the end + node = end + distance = 0 + # While we are not arrived at the beginning + while not (node == start): + if path.count(node) == 0: + path.insert(0, node) # Insert the predecessor of the current node + node = P[node] # The current node becomes its predecessor + else: + break + path.insert(0, start) # Finally, insert the start vertex + for i in range(len(path) - 1): + distance += graph[path[i]][path[i + 1]] + return distance + + +def _count_replacement(codons, G): + """Count replacement needed for a given codon_set (PRIVATE).""" + if len(codons) == 1: + return 0, 0 + elif len(codons) == 2: + codons = list(codons) + return floor(G[codons[0]][codons[1]]) + else: + subgraph = { + codon1: {codon2: G[codon1][codon2] for codon2 in codons if codon1 != codon2} + for codon1 in codons + } + return _prim(subgraph) + + +def _prim(G): + """Prim's algorithm to find minimum spanning tree (PRIVATE). + + Code is adapted from + http://programmingpraxis.com/2010/04/09/minimum-spanning-tree-prims-algorithm/ + """ + nodes = [] + edges = [] + for i in G.keys(): + nodes.append(i) + for j in G[i]: + if (i, j, G[i][j]) not in edges and (j, i, G[i][j]) not in edges: + edges.append((i, j, G[i][j])) + conn = defaultdict(list) + for n1, n2, c in edges: + conn[n1].append((c, n1, n2)) + conn[n2].append((c, n2, n1)) + mst = [] # minimum spanning tree + used = set(nodes[0]) + usable_edges = conn[nodes[0]][:] + heapify(usable_edges) + while usable_edges: + cost, n1, n2 = heappop(usable_edges) + if n2 not in used: + used.add(n2) + mst.append((n1, n2, cost)) + for e in conn[n2]: + if e[2] not in used: + heappush(usable_edges, e) + length = 0 + for p in mst: + length += floor(p[2]) + return length + + +def _G_test(site_counts): + """G test for 2x2 contingency table (PRIVATE). + + Arguments: + - site_counts - [syn_fix, nonsyn_fix, syn_poly, nonsyn_poly] + + >>> print("%0.6f" % _G_test([17, 7, 42, 2])) + 0.004924 + """ + # TODO: + # Apply continuity correction for Chi-square test. + G = 0 + tot = sum(site_counts) + tot_syn = site_counts[0] + site_counts[2] + tot_non = site_counts[1] + site_counts[3] + tot_fix = sum(site_counts[:2]) + tot_poly = sum(site_counts[2:]) + exp = [ + tot_fix * tot_syn / tot, + tot_fix * tot_non / tot, + tot_poly * tot_syn / tot, + tot_poly * tot_non / tot, + ] + for obs, ex in zip(site_counts, exp): + G += obs * log(obs / ex) + # with only 1 degree of freedom for a 2x2 table, + # the cumulative chi-square distribution reduces to a simple form: + return erfc(sqrt(G)) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/bed.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/bed.py new file mode 100644 index 0000000000000000000000000000000000000000..d42a9cffe91f6b9362bf16d80f44ff0875e03a75 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/bed.py @@ -0,0 +1,259 @@ +# Copyright 2022 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for BED (Browser Extensible Data) files. + +The Browser Extensible Data (BED) format, stores a series of pairwise +alignments in a single file. Typically they are used for transcript to genome +alignments. BED files store the alignment positions and alignment scores, but +not the aligned sequences. + +See http://genome.ucsc.edu/FAQ/FAQformat.html#format1 + +You are expected to use this module via the Bio.Align functions. + +Coordinates in the BED format are defined in terms of zero-based start +positions (like Python) and aligning region sizes. + +A minimal aligned region of length one and starting at first position in the +source sequence would have ``start == 0`` and ``size == 1``. + +As we can see in this example, ``start + size`` will give one more than the +zero-based end position. We can therefore manipulate ``start`` and +``start + size`` as python list slice boundaries. +""" + +import sys + +import numpy as np + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Alignment file writer for the Browser Extensible Data (BED) file format.""" + + def __init__(self, target, bedN=12): + """Create an AlignmentWriter object. + + Arguments: + - target - output stream or file name + - bedN - number of columns in the BED file. + This must be between 3 and 12; default value is 12. + + """ + if bedN < 3 or bedN > 12: + raise ValueError("bedN must be between 3 and 12") + super().__init__(target) + self.bedN = bedN + + def format_alignment(self, alignment): + """Return a string with one alignment formatted as a BED line.""" + if not isinstance(alignment, Alignment): + raise TypeError("Expected an Alignment object") + coordinates = alignment.coordinates + if not coordinates.size: # alignment consists of gaps only + return "" + bedN = self.bedN + target, query = alignment.sequences + try: + chrom = target.id + except AttributeError: + chrom = "target" + else: + if chrom is None: + chrom = "target" + if coordinates[0, 0] > coordinates[0, -1]: + # read the alignment right-to-left to be consistent with BED + coordinates = coordinates[:, ::-1] + if coordinates[1, 0] > coordinates[1, -1]: + # DNA/RNA mapped to reverse strand of DNA/RNA + strand = "-" + else: + # mapped to forward strand + strand = "+" + # variable names follow those in the BED file format specification + blockSizes = [] + blockStarts = [] + tStart, qStart = coordinates[:, 0] + for tEnd, qEnd in coordinates[:, 1:].transpose(): + if tStart == tEnd: + qStart = qEnd + elif qStart == qEnd: + tStart = tEnd + else: + blockSize = tEnd - tStart + blockStarts.append(tStart) + blockSizes.append(blockSize) + tStart = tEnd + qStart = qEnd + try: + chromStart = blockStarts[0] # start of alignment in target + chromEnd = blockStarts[-1] + blockSize # end of alignment in target + except IndexError: # no aligned blocks + chromStart = chromEnd = tStart + fields = [chrom, str(chromStart), str(chromEnd)] + if bedN == 3: + return "\t".join(fields) + "\n" + try: + name = query.id + except AttributeError: + name = "query" + else: + if name is None: + name = "query" + fields.append(name) + if bedN == 4: + return "\t".join(fields) + "\n" + try: + score = alignment.score + except AttributeError: + score = 0 + fields.append(format(score, "g")) + if bedN == 5: + return "\t".join(fields) + "\n" + fields.append(strand) + if bedN == 6: + return "\t".join(fields) + "\n" + try: + thickStart = alignment.thickStart + except AttributeError: + thickStart = chromStart + fields.append(str(thickStart)) + if bedN == 7: + return "\t".join(fields) + "\n" + try: + thickEnd = alignment.thickEnd + except AttributeError: + thickEnd = chromEnd + fields.append(str(thickEnd)) + if bedN == 8: + return "\t".join(fields) + "\n" + try: + itemRgb = alignment.itemRgb + except AttributeError: + itemRgb = "0" + fields.append(str(itemRgb)) + if bedN == 9: + return "\t".join(fields) + "\n" + blockCount = len(blockSizes) + fields.append(str(blockCount)) + if bedN == 10: + return "\t".join(fields) + "\n" + fields.append(",".join(map(str, blockSizes)) + ",") + if bedN == 11: + return "\t".join(fields) + "\n" + blockStarts -= chromStart + fields.append(",".join(map(str, blockStarts)) + ",") + return "\t".join(fields) + "\n" + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Alignment iterator for Browser Extensible Data (BED) files. + + Each line in the file contains one pairwise alignment, which are loaded + and returned incrementally. Additional alignment information is stored as + attributes of each alignment. + """ + + fmt = "BED" + + def _read_next_alignment(self, stream): + for line in stream: + # note that we cannot extract one line by calling next, as stream + # may be iterable but not an iterator (for example, TemporaryFile + # or NamedTemporaryFile objects in tempfile). + words = line.split() + bedN = len(words) + if bedN < 3 or bedN > 12: + raise ValueError("expected between 3 and 12 columns, found %d" % bedN) + chrom = words[0] + chromStart = int(words[1]) + chromEnd = int(words[2]) + if bedN > 3: + name = words[3] + else: + name = None + if bedN > 5: + strand = words[5] + else: + strand = "+" + if bedN > 9: + blockCount = int(words[9]) + blockSizes = [ + int(blockSize) for blockSize in words[10].rstrip(",").split(",") + ] + blockStarts = [ + int(blockStart) for blockStart in words[11].rstrip(",").split(",") + ] + if len(blockSizes) != blockCount: + raise ValueError( + "Inconsistent number of block sizes (%d found, expected %d)" + % (len(blockSizes), blockCount) + ) + if len(blockStarts) != blockCount: + raise ValueError( + "Inconsistent number of block start positions (%d found, expected %d)" + % (len(blockStarts), blockCount) + ) + blockSizes = np.array(blockSizes) + blockStarts = np.array(blockStarts) + tPosition = 0 + qPosition = 0 + coordinates = [[tPosition, qPosition]] + for blockSize, blockStart in zip(blockSizes, blockStarts): + if blockStart != tPosition: + coordinates.append([blockStart, qPosition]) + tPosition = blockStart + tPosition += blockSize + qPosition += blockSize + coordinates.append([tPosition, qPosition]) + coordinates = np.array(coordinates, np.intp).transpose() + qSize = sum(blockSizes) + else: + blockSize = chromEnd - chromStart + coordinates = np.array([[0, blockSize], [0, blockSize]], np.intp) + qSize = blockSize + coordinates[0, :] += chromStart + query_sequence = Seq(None, length=qSize) + query_record = SeqRecord(query_sequence, id=name, description="") + target_sequence = Seq(None, length=sys.maxsize) + target_record = SeqRecord(target_sequence, id=chrom, description="") + records = [target_record, query_record] + if strand == "-": + coordinates[1, :] = qSize - coordinates[1, :] + if chromStart != coordinates[0, 0]: + raise ValueError( + "Inconsistent chromStart found (%d, expected %d)" + % (chromStart, coordinates[0, 0]) + ) + if chromEnd != coordinates[0, -1]: + raise ValueError( + "Inconsistent chromEnd found (%d, expected %d)" + % (chromEnd, coordinates[0, -1]) + ) + alignment = Alignment(records, coordinates) + if bedN <= 4: + return alignment + score = words[4] + try: + score = float(score) + except ValueError: + pass + alignment.score = score + if bedN <= 6: + return alignment + alignment.thickStart = int(words[6]) + if bedN <= 7: + return alignment + alignment.thickEnd = int(words[7]) + if bedN <= 8: + return alignment + alignment.itemRgb = words[8] + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/bigbed.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/bigbed.py new file mode 100644 index 0000000000000000000000000000000000000000..25f13f0e1fa984f9649317f2b16f7cdb225af10c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/bigbed.py @@ -0,0 +1,2243 @@ +# Copyright 2022 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for alignment files in the bigBed format. + +The bigBed format stores a series of pairwise alignments in a single indexed +binary file. Typically they are used for transcript to genome alignments. As +in the BED format, the alignment positions and alignment scores are stored, +but the aligned sequences are not. + +See http://genome.ucsc.edu/goldenPath/help/bigBed.html for more information. + +You are expected to use this module via the Bio.Align functions. +""" + +# This parser was written based on the description of the bigBed file format in +# W. J. Kent, A. S. Zweig, G. Barber, A. S. Hinrichs, and D. Karolchik: +# "BigWig and BigBed: enabling browsing of large distributed datasets." +# Bioinformatics 26(17): 2204–2207 (2010) +# in particular the tables in the supplemental materials listing the contents +# of a bigBed file byte-by-byte. + +# The writer is based on files in the src/lib and src/utils/bedToBigBed +# directories in Jim Kent's source code from UCSC. + +# These program files are provided by the University of California Santa Cruz +# under the following license: + +# ------------------------------------------------------------------------------ +# Copyright (C) 2001 UC Regents +# +# Permission is hereby granted, free of charge, to any person obtaining a copy of +# this software and associated documentation files (the "Software"), to deal in +# the Software without restriction, including without limitation the rights to +# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +# the Software, and to permit persons to whom the Software is furnished to do so, +# subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# ------------------------------------------------------------------------------ + +import copy +import io +import itertools +import struct +import sys +import zlib +from collections import namedtuple +from io import BytesIO + +import numpy as np + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +Field = namedtuple("Field", ("as_type", "name", "comment")) + + +class AutoSQLTable(list): + """AutoSQL table describing the columns of an (possibly extended) BED format.""" + + default: "AutoSQLTable" + + def __init__(self, name, comment, fields): + """Create an AutoSQL table describing the columns of an (extended) BED format.""" + self.name = name + self.comment = comment + self[:] = fields + + @classmethod + def from_bytes(cls, data): + """Return an AutoSQLTable initialized using the bytes object data.""" + assert data.endswith(b"\0") # NULL-terminated string + text = data[:-1].decode() + word, text = text.split(None, 1) + assert word == "table" + name, text = text.split(None, 1) + assert text.startswith('"') + i = text.find('"', 1) + comment = text[1:i] + text = text[i + 1 :].strip() + assert text.startswith("(") + assert text.endswith(")") + text = text[1:-1].strip() + fields = [] + while text: + i = text.index('"') + j = text.index('"', i + 1) + field_comment = text[i + 1 : j] + definition = text[:i].strip() + assert definition.endswith(";") + field_type, field_name = definition[:-1].rsplit(None, 1) + if field_type.endswith("]"): + i = field_type.index("[") + data_type = field_type[:i] + else: + data_type = field_type + assert data_type in ( + "int", + "uint", + "short", + "ushort", + "byte", + "ubyte", + "float", + "char", + "string", + "lstring", + ) + field = Field(field_type, field_name, field_comment) + fields.append(field) + text = text[j + 1 :].strip() + return AutoSQLTable(name, comment, fields) + + @classmethod + def from_string(cls, data): + """Return an AutoSQLTable initialized using the string object data.""" + return cls.from_bytes(data.encode() + b"\0") + + def __str__(self): + type_width = max(len(str(field.as_type)) for field in self) + name_width = max(len(field.name) for field in self) + 1 + lines = [] + lines.append("table %s\n" % self.name) + lines.append('"%s"\n' % self.comment) + lines.append("(\n") + for field in self: + name = field.name + ";" + lines.append( + f' %-{type_width}s %-{name_width}s "%s"\n' + % ( + field.as_type, + name, + field.comment, + ) + ) + lines.append(")\n") + return "".join(lines) + + def __bytes__(self): + return str(self).encode() + b"\0" + + def __getitem__(self, i): + if isinstance(i, slice): + fields = super().__getitem__(i) + return AutoSQLTable(self.name, self.comment, fields) + else: + return super().__getitem__(i) + + +AutoSQLTable.default = AutoSQLTable( + "bed", + "Browser Extensible Data", + [ + Field( + as_type="string", + name="chrom", + comment="Reference sequence chromosome or scaffold", + ), + Field( + as_type="uint", + name="chromStart", + comment="Start position in chromosome", + ), + Field( + as_type="uint", + name="chromEnd", + comment="End position in chromosome", + ), + Field(as_type="string", name="name", comment="Name of item."), + Field(as_type="uint", name="score", comment="Score (0-1000)"), + Field(as_type="char[1]", name="strand", comment="+ or - for strand"), + Field( + as_type="uint", + name="thickStart", + comment="Start of where display should be thick (start codon)", + ), + Field( + as_type="uint", + name="thickEnd", + comment="End of where display should be thick (stop codon)", + ), + Field( + as_type="uint", + name="reserved", + comment="Used as itemRgb as of 2004-11-22", + ), + Field(as_type="int", name="blockCount", comment="Number of blocks"), + Field( + as_type="int[blockCount]", + name="blockSizes", + comment="Comma separated list of block sizes", + ), + Field( + as_type="int[blockCount]", + name="chromStarts", + comment="Start positions relative to chromStart", + ), + ], +) + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Alignment file writer for the bigBed file format.""" + + fmt = "bigBed" + mode = "b" + + def __init__( + self, + target, + bedN=12, + declaration=None, + targets=None, + compress=True, + itemsPerSlot=512, + blockSize=256, + extraIndex=(), + ): + """Create an AlignmentWriter object. + + Arguments: + - target - output stream or file name. + - bedN - number of columns in the BED file. + This must be between 3 and 12; default value is 12. + - declaration - an AutoSQLTable object declaring the fields in the + BED file. + Required only if the BED file contains extra (custom) + fields. + Default value is None. + - targets - A list of SeqRecord objects with the chromosomes in + the order as they appear in the alignments. The + sequence contents in each SeqRecord may be undefined, + but the sequence length must be defined, as in this + example: + + SeqRecord(Seq(None, length=248956422), id="chr1") + + If targets is None (the default value), the alignments + must have an attribute .targets providing the list of + SeqRecord objects. + - compress - If True (default), compress data using zlib. + If False, do not compress data. + Use compress=False for faster searching. + - blockSize - Number of items to bundle in r-tree. + See UCSC's bedToBigBed program for more information. + Default value is 256. + - itemsPerSlot - Number of data points bundled at lowest level. + See UCSC's bedToBigBed program for more information. + Use itemsPerSlot=1 for faster searching. + Default value is 512. + - extraIndex - List of strings with the names of extra columns to be + indexed. + Default value is an empty list. + """ + if bedN < 3 or bedN > 12: + raise ValueError("bedN must be between 3 and 12") + super().__init__(target) + self.bedN = bedN + self.declaration = declaration + self.targets = targets + self.compress = compress + self.extraIndexNames = extraIndex + self.itemsPerSlot = itemsPerSlot + self.blockSize = blockSize + + def write_file(self, stream, alignments): + """Write the alignments to the file stream, and return the number of alignments. + + alignments - A list or iterator returning Alignment objects + stream - Output file stream. + """ + if self.targets is None: + targets = alignments.targets + else: + targets = self.targets + header = _Header() + header.definedFieldCount = self.bedN + if self.declaration is None: + try: + self.declaration = alignments.declaration[: self.bedN] + except AttributeError: + self.declaration = AutoSQLTable.default[: self.bedN] + declaration = self.declaration + header.fieldCount = len(declaration) + extra_indices = _ExtraIndices(self.extraIndexNames, declaration) + chromUsageList, aveSize = self._get_chrom_usage( + alignments, targets, extra_indices + ) + stream.write(bytes(header.size)) + stream.write(bytes(_ZoomLevels.size)) + header.autoSqlOffset = stream.tell() + stream.write(bytes(declaration)) + header.totalSummaryOffset = stream.tell() + stream.write(bytes(_Summary.size)) + header.extraIndicesOffset = stream.tell() + stream.write(bytes(extra_indices.size)) + header.chromosomeTreeOffset = stream.tell() + _BPlusTreeFormatter().write( + chromUsageList, min(self.blockSize, len(chromUsageList)), stream + ) + header.fullDataOffset = stream.tell() + reductions = _ZoomLevels.calculate_reductions(aveSize) + stream.write(len(alignments).to_bytes(8, sys.byteorder)) + extra_indices.initialize(len(alignments)) + maxBlockSize, regions = self.write_alignments( + alignments, + stream, + reductions, + extra_indices, + ) + if self.compress: + header.uncompressBufSize = max( + maxBlockSize, self.itemsPerSlot * _RegionSummary.size + ) + else: + header.uncompressBufSize = 0 + header.fullIndexOffset = stream.tell() + _RTreeFormatter().write( + regions, self.blockSize, 1, header.fullIndexOffset, stream + ) + zoomList, totalSum = self._write_zoom_levels( + alignments, + stream, + header.fullIndexOffset - header.fullDataOffset, + chromUsageList, + reductions, + ) + header.zoomLevels = len(zoomList) + for extra_index in extra_indices: + extra_index.fileOffset = stream.tell() + extra_index.chunks.sort() + _BPlusTreeFormatter().write(extra_index.chunks, self.blockSize, stream) + stream.seek(0) + stream.write(bytes(header)) + stream.write(bytes(zoomList)) + stream.seek(header.totalSummaryOffset) + stream.write(bytes(totalSum)) + assert header.extraIndicesOffset == stream.tell() + extra_indices.tofile(stream) + stream.seek(0, io.SEEK_END) + data = header.signature.to_bytes(4, sys.byteorder) + stream.write(data) + + def _get_chrom_usage(cls, alignments, targets, extra_indices): + aveSize = 0 + chromId = 0 + totalBases = 0 + bedCount = 0 + name = "" + chromUsageList = [] + keySize = 0 + chromSize = -1 + minDiff = sys.maxsize + for alignment in alignments: + chrom = alignment.sequences[0].id + # Note that for MAF files, this may be a multiple alignment, so + # alignment.target.id won't necessarily work. + start = alignment.coordinates[0, 0] + end = alignment.coordinates[0, -1] + for extra_index in extra_indices: + extra_index.updateMaxFieldSize(alignment) + if start > end: + raise ValueError( + f"end ({end}) before start ({start}) in alignment [{bedCount}]" + ) + bedCount += 1 + totalBases += end - start + if name != chrom: + if name > chrom: + raise ValueError( + f"alignments are not sorted by target name at alignment [{bedCount}]" + ) + if name: + chromUsageList.append((name, chromId, chromSize)) + chromId += 1 + for target in targets: + if target.id == chrom: + break + else: + raise ValueError( + f"failed to find target '{chrom}' in target list at alignment [{bedCount}]" + ) + name = chrom + keySize = max(keySize, len(chrom)) + chromSize = len(target) + lastStart = -1 + if end > chromSize: + raise ValueError( + f"end coordinate {end} bigger than {chrom} size of {chromSize} at alignment [{bedCount}]'" + ) + if lastStart >= 0: + diff = start - lastStart + if diff < minDiff: + if diff < 0: + raise ValueError( + f"alignments are not sorted at alignment [{bedCount}]" + ) + minDiff = diff + lastStart = start + if name: + chromUsageList.append((name, chromId, chromSize)) + chromUsageList = np.array( + chromUsageList, + dtype=[("name", f"S{keySize}"), ("id", "=i4"), ("size", "=i4")], + ) + if bedCount > 0: + aveSize = totalBases / bedCount + alignments._len = bedCount + return chromUsageList, aveSize + + def _write_zoom_levels( + self, alignments, output, dataSize, chromUsageList, reductions + ): + zoomList = _ZoomLevels() + totalSum = _Summary() + if len(alignments) == 0: + totalSum.minVal = 0.0 + totalSum.maxVal = 0.0 + else: + blockSize = self.blockSize + doCompress = self.compress + itemsPerSlot = self.itemsPerSlot + maxReducedSize = dataSize / 2 + zoomList[0].dataOffset = output.tell() + for initialReduction in reductions: + reducedSize = initialReduction["size"] * _RegionSummary.size + if doCompress: + reducedSize /= 2 + if reducedSize <= maxReducedSize: + break + else: + initialReduction = reductions[0] + initialReduction["size"].tofile(output) + size = itemsPerSlot * _RegionSummary.size + if doCompress: + buffer = _ZippedBufferedStream(output, size) + else: + buffer = _BufferedStream(output, size) + regions = [] + rezoomedList = [] + trees = _RangeTree.generate(chromUsageList, alignments) + scale = int(initialReduction["scale"]) + doubleReductionSize = scale * _ZoomLevels.bbiResIncrement + for tree in trees: + start = -sys.maxsize + summaries = tree.generate_summaries(scale, totalSum) + for summary in summaries: + buffer.write(summary) + regions.append(summary) + if start + doubleReductionSize < summary.end: + rezoomed = copy.copy(summary) + start = rezoomed.start + rezoomedList.append(rezoomed) + else: + rezoomed += summary + buffer.flush() + assert len(regions) == initialReduction["size"] + zoomList[0].reductionLevel = initialReduction["scale"] + indexOffset = output.tell() + zoomList[0].indexOffset = indexOffset + _RTreeFormatter().write( + regions, blockSize, itemsPerSlot, indexOffset, output + ) + if doCompress: + buffer = _ZippedBufferedStream(output, size) + else: + buffer = _BufferedStream(output, _RegionSummary.size) + zoomList.reduce( + rezoomedList, initialReduction, buffer, blockSize, itemsPerSlot + ) + return zoomList, totalSum + + def _extract_fields(self, alignment): + bedN = self.bedN + row = [] + chrom = alignment.target.id + if len(chrom) >= 255: + raise ValueError( + f"alignment target name '{chrom}' is too long (must not exceed 254 characters)" + ) + if len(chrom) < 1: + raise ValueError("alignment target name cannot be blank or empty") + chromStart = alignment.coordinates[0, 0] + chromEnd = alignment.coordinates[0, -1] + if chromEnd < chromStart: + raise ValueError(f"chromStart after chromEnd ({chromEnd} > {chromStart})") + if bedN > 3: + name = alignment.query.id + if name == "": + name = "." + elif len(name) > 255: + raise ValueError( + f"alignment query name '{name}' is too long (must not exceed 255 characters" + ) + row.append(name) + if bedN > 4: + try: + score = alignment.score + except AttributeError: + score = "." + else: + if score < 0 or score > 1000: + raise ValueError(f"score ({score}) must be between 0 and 1000") + score = str(score) + row.append(score) + if bedN > 5: + if alignment.coordinates[1, 0] <= alignment.coordinates[1, -1]: + strand = "+" + else: + strand = "-" + row.append(strand) + if bedN > 6: + try: + thickStart = alignment.thickStart + except AttributeError: + thickStart = chromStart + row.append(str(thickStart)) + if bedN > 7: + try: + thickEnd = alignment.thickEnd + except AttributeError: + thickEnd = chromEnd + else: + if thickEnd < thickStart: + raise ValueError( + f"thickStart ({thickStart}) after thickEnd ({thickEnd})" + ) + if thickStart != 0 and ( + thickStart < chromStart or thickStart > chromEnd + ): + raise ValueError( + f"thickStart out of range for {name}:{chromStart}-{chromEnd}, thick:{thickStart}-{thickEnd}" + ) + if thickEnd != 0 and (thickEnd < chromStart or thickEnd > chromEnd): + raise ValueError( + f"thickEnd out of range for {name}:{chromStart}-{chromEnd}, thick:{thickStart}-{thickEnd}" + ) + row.append(str(thickEnd)) + if bedN > 8: + try: + itemRgb = alignment.itemRgb + except AttributeError: + itemRgb = "." + else: + colors = itemRgb.rstrip(",").split(",") + if len(colors) == 3 and all(0 <= int(color) < 256 for color in colors): + pass + elif 0 <= int(itemRgb) < (2 << 32): + pass + else: + raise ValueError( + f"Expecting color to consist of r,g,b values from 0 to 255. Got '{itemRgb}'" + ) + row.append(itemRgb) + if bedN > 9: + steps = np.diff(alignment.coordinates) + aligned = sum(steps != 0, 0) == 2 + blockSizes = steps.max(0)[aligned] + blockCount = len(blockSizes) + row.append(str(blockCount)) + if bedN > 10: + row.append(",".join(str(blockSize) for blockSize in blockSizes) + ",") + if bedN > 11: + chromStarts = alignment.coordinates[0, :-1][aligned] - chromStart + row.append(",".join(str(chromStart) for chromStart in chromStarts) + ",") + if bedN > 12: + if bedN != 15: + raise ValueError(f"Unexpected value {bedN} for bedN in _extract_fields") + expIds = alignment.annotations["expIds"] + expScores = alignment.annotations["expScores"] + expCount = len(expIds) + assert expCount == len(expScores) + row.append(str(expCount)) + row.append(",".join(expIds)) + row.append(",".join(str(expScore) for expScore in expScores)) + for field in self.declaration[bedN:]: + value = alignment.annotations[field.name] + if isinstance(value, str): + row.append(value) + elif isinstance(value, (int, float)): + row.append(str(value)) + else: + row.append(",".join(map(str, value))) + rest = "\t".join(row).encode() + return chrom, chromStart, chromEnd, rest + + def write_alignments(self, alignments, output, reductions, extra_indices): + """Write alignments to the output file, and return the number of alignments. + + alignments - A list or iterator returning Alignment objects + stream - Output file stream. + """ + itemsPerSlot = self.itemsPerSlot + chromId = -1 + itemIx = 0 + sectionStartIx = 0 + sectionEndIx = 0 + currentChrom = None + + regions = [] + if self.compress is True: + buffer = _ZippedStream() + else: + buffer = BytesIO() + maxBlockSize = 0 + + # Supplemental Table 12: Binary BED-data format + # chromId 4 bytes, unsigned + # chromStart 4 bytes, unsigned + # chromEnd 4 bytes, unsigned + # rest zero-terminated string in tab-separated format + formatter = struct.Struct("=III") + + done = False + region = None + alignments = iter(alignments) + while True: + try: + alignment = next(alignments) + except StopIteration: + itemIx = itemsPerSlot + done = True + else: + chrom, start, end, rest = self._extract_fields(alignment) + if chrom != currentChrom: + if currentChrom is not None: + itemIx = itemsPerSlot + currentChrom = chrom + chromId += 1 + reductions["end"] = 0 + if itemIx == itemsPerSlot: + blockStartOffset = output.tell() + size = buffer.tell() + if size > maxBlockSize: + maxBlockSize = size + data = buffer.getvalue() + output.write(data) + buffer.seek(0) + buffer.truncate(0) + if extra_indices: + blockEndOffset = output.tell() + blockSize = blockEndOffset - blockStartOffset + for extra_index in extra_indices: + extra_index.addOffsetSize( + blockStartOffset, + blockSize, + sectionStartIx, + sectionEndIx, + ) + sectionStartIx = sectionEndIx + region.offset = blockStartOffset + if done is True: + break + itemIx = 0 + if itemIx == 0: + region = _Region(chromId, start, end) + regions.append(region) + elif end > region.end: + region.end = end + itemIx += 1 + for row in reductions: + if start >= row["end"]: + row["size"] += 1 + row["end"] = start + row["scale"] + while end > row["end"]: + row["size"] += 1 + row["end"] += row["scale"] + if extra_indices: + for extra_index in extra_indices: + extra_index.addKeysFromRow(alignment, sectionEndIx) + sectionEndIx += 1 + data = formatter.pack(chromId, start, end) + buffer.write(data + rest + b"\0") + return maxBlockSize, regions + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Alignment iterator for bigBed files. + + The pairwise alignments stored in the bigBed file are loaded and returned + incrementally. Additional alignment information is stored as attributes + of each alignment. + """ + + fmt = "bigBed" + mode = "b" + + def _read_header(self, stream): + header = _Header.fromfile(stream) + byteorder = header.byteorder + autoSqlOffset = header.autoSqlOffset + self.byteorder = byteorder + fieldCount = header.fieldCount + definedFieldCount = header.definedFieldCount + fullDataOffset = header.fullDataOffset + zoomList = _ZoomLevels(byteorder) + zoomList.read(stream) + formatter = _RTreeFormatter(byteorder).formatter_header + for zoomLevel in zoomList: + indexOffset = zoomLevel.indexOffset + stream.seek(indexOffset) + data = stream.read(formatter.size) + ( + signature, + blockSize, + nItems, + startChromId, + startBase, + endChromId, + endBase, + endFileOffset, + self.itemsPerSlot, + ) = formatter.unpack(data) + assert signature == _RTreeFormatter.signature + self.declaration = self._read_autosql(stream, header) + stream.seek(fullDataOffset) + (dataCount,) = struct.unpack(byteorder + "Q", stream.read(8)) + self._length = dataCount + + if header.uncompressBufSize > 0: + self._compressed = True + else: + self._compressed = False + + stream.seek(header.chromosomeTreeOffset) + self.targets = _BPlusTreeFormatter(byteorder).read(stream) + + stream.seek(header.fullIndexOffset) + self.tree = _RTreeFormatter(byteorder).read(stream) + self._data = self._iterate_index(stream) + + def _read_autosql(self, stream, header): + autoSqlSize = header.totalSummaryOffset - header.autoSqlOffset + fieldCount = header.fieldCount + self.bedN = header.definedFieldCount + stream.seek(header.autoSqlOffset) + data = stream.read(autoSqlSize) + declaration = AutoSQLTable.from_bytes(data) + self._analyze_fields(declaration, fieldCount, self.bedN) + return declaration + + def _analyze_fields(self, fields, fieldCount, definedFieldCount): + names = ( + "chrom", + "chromStart", + "chromEnd", + "name", + "score", + "strand", + "thickStart", + "thickEnd", + "reserved", + "blockCount", + "blockSizes", + "chromStarts", + ) + for i in range(self.bedN): + name = fields[i].name + if name != names[i]: + raise ValueError( + "Expected field name '%s'; found '%s'" % (names[i], name) + ) + if fieldCount > definedFieldCount: + self._custom_fields = [] + for i in range(definedFieldCount, fieldCount): + field_name = fields[i].name + field_type = fields[i].as_type + if "[" in field_type and "]" in field_type: + make_array = True + field_type, _ = field_type.split("[") + field_type = field_type.strip() + else: + make_array = False + if field_type in ("int", "uint", "short", "ushort"): + converter = int + elif field_type in ("byte", "ubyte"): + converter = bytes + elif field_type == "float": + converter = float + elif field_type in ("float", "char", "string", "lstring"): + converter = str + else: + raise Exception("Unknown field type %s" % field_type) + if make_array: + item_converter = converter + + def converter(data, item_converter=item_converter): + values = data.rstrip(",").split(",") + return [item_converter(value) for value in values] + + self._custom_fields.append([field_name, converter]) + + def _iterate_index(self, stream): + # Supplemental Table 12: Binary BED-data format + # chromId 4 bytes, unsigned + # chromStart 4 bytes, unsigned + # chromEnd 4 bytes, unsigned + # rest zero-terminated string in tab-separated format + formatter = struct.Struct(self.byteorder + "III") + size = formatter.size + node = self.tree + while True: + try: + children = node.children + except AttributeError: + stream.seek(node.dataOffset) + data = stream.read(node.dataSize) + if self._compressed > 0: + data = zlib.decompress(data) + while data: + chromId, chromStart, chromEnd = formatter.unpack(data[:size]) + i = data.index(0, size) + 1 + rest = data[size:i] + data = data[i:] + yield (chromId, chromStart, chromEnd, rest, 0, len(rest)) + while True: + parent = node.parent + if parent is None: + return + for index, child in enumerate(parent.children): + if id(node) == id(child): + break + else: + raise RuntimeError("Failed to find child node") + try: + node = parent.children[index + 1] + except IndexError: + node = parent + else: + break + else: + node = children[0] + + def _search_index(self, stream, chromIx, start, end): + # Supplemental Table 12: Binary BED-data format + # chromId 4 bytes, unsigned + # chromStart 4 bytes, unsigned + # chromEnd 4 bytes, unsigned + # rest zero-terminated string in tab-separated format + formatter = struct.Struct(self.byteorder + "III") + size = formatter.size + padded_start = start - 1 + padded_end = end + 1 + node = self.tree + while True: + try: + children = node.children + except AttributeError: + stream.seek(node.dataOffset) + data = stream.read(node.dataSize) + if self._compressed > 0: + data = zlib.decompress(data) + if self.itemsPerSlot == 1: + child_chromIx, child_chromStart, child_chromEnd = formatter.unpack( + data[:size] + ) + if child_chromIx == chromIx: + if (child_chromStart < end and start < child_chromEnd) or ( + child_chromStart == child_chromEnd + and (child_chromStart == end or start == child_chromEnd) + ): + yield ( + child_chromIx, + child_chromStart, + child_chromEnd, + data, + size, + len(data), + ) + else: + i = 0 + n = len(data) + while i < n: + j = i + size + child_chromIx, child_chromStart, child_chromEnd = ( + formatter.unpack(data[i:j]) + ) + i = j + j = data.index(b"\00", i) + 1 + rest = data[i:j] + i = j + if child_chromIx != chromIx: + continue + if end <= child_chromStart or child_chromEnd <= start: + if child_chromStart != child_chromEnd: + continue + if child_chromStart != end and child_chromEnd != start: + continue + yield ( + child_chromIx, + child_chromStart, + child_chromEnd, + rest, + 0, + len(rest), + ) + else: + visit_child = False + for child in children: + if (child.endChromIx, child.endBase) < (chromIx, padded_start): + continue + if (chromIx, padded_end) < (child.startChromIx, child.startBase): + continue + visit_child = True + break + if visit_child: + node = child + continue + while True: + parent = node.parent + if parent is None: + return + for index, child in enumerate(parent.children): + if id(node) == id(child): + break + else: + raise RuntimeError("Failed to find child node") + try: + node = parent.children[index + 1] + except IndexError: + node = parent + else: + break + + def _read_next_alignment(self, stream): + try: + row = next(self._data) + except StopIteration: + return + chromId, chromStart, chromEnd, rest, dataStart, dataEnd = row + return self._create_alignment( + chromId, chromStart, chromEnd, rest, dataStart, dataEnd + ) + + def _create_alignment( + self, chromId, chromStart, chromEnd, rest, dataStart, dataEnd + ): + assert rest[dataEnd - 1] == 0 + rest = rest[dataStart : dataEnd - 1] + if rest: + words = rest.decode().split("\t") + else: + words = [] + target_record = self.targets[chromId] + if self.bedN > 3: + name = words[0] + else: + name = None + if self.bedN > 5: + strand = words[2] + else: + strand = "+" + if self.bedN > 9: + blockCount = int(words[6]) + blockSizes = np.fromiter(words[7].rstrip(",").split(","), int) + blockStarts = np.fromiter(words[8].rstrip(",").split(","), int) + if len(blockSizes) != blockCount: + raise ValueError( + "Inconsistent number of block sizes (%d found, expected %d)" + % (len(blockSizes), blockCount) + ) + if len(blockStarts) != blockCount: + raise ValueError( + "Inconsistent number of block start positions (%d found, expected %d)" + % (len(blockStarts), blockCount) + ) + tPosition = 0 + qPosition = 0 + coordinates = [[tPosition, qPosition]] + for blockSize, blockStart in zip(blockSizes, blockStarts): + if blockStart != tPosition: + coordinates.append([blockStart, qPosition]) + tPosition = blockStart + tPosition += blockSize + qPosition += blockSize + coordinates.append([tPosition, qPosition]) + coordinates = np.array(coordinates, np.intp).transpose() + qSize = sum(blockSizes) + else: + blockSize = chromEnd - chromStart + coordinates = np.array([[0, blockSize], [0, blockSize]], np.intp) + qSize = blockSize + coordinates[0, :] += chromStart + query_sequence = Seq(None, length=qSize) + query_record = SeqRecord(query_sequence, id=name) + records = [target_record, query_record] + if strand == "-": + coordinates[1, :] = qSize - coordinates[1, :] + if chromStart != coordinates[0, 0]: + raise ValueError( + "Inconsistent chromStart found (%d, expected %d)" + % (chromStart, coordinates[0, 0]) + ) + if chromEnd != coordinates[0, -1]: + raise ValueError( + "Inconsistent chromEnd found (%d, expected %d)" + % (chromEnd, coordinates[0, -1]) + ) + alignment = Alignment(records, coordinates) + if len(words) > self.bedN - 3: + alignment.annotations = {} + for word, custom_field in zip(words[self.bedN - 3 :], self._custom_fields): + name, converter = custom_field + alignment.annotations[name] = converter(word) + if self.bedN <= 4: + return alignment + score = words[1] + try: + score = float(score) + except ValueError: + pass + else: + if score.is_integer(): + score = int(score) + alignment.score = score + if self.bedN <= 6: + return alignment + alignment.thickStart = int(words[3]) + if self.bedN <= 7: + return alignment + alignment.thickEnd = int(words[4]) + if self.bedN <= 8: + return alignment + alignment.itemRgb = words[5] + return alignment + + def __len__(self): + return self._length + + def search(self, chromosome=None, start=None, end=None): + """Iterate over alignments overlapping the specified chromosome region.. + + This method searches the index to find alignments to the specified + chromosome that fully or partially overlap the chromosome region + between start and end. + + Arguments: + - chromosome - chromosome name. If None (default value), include all + alignments. + - start - starting position on the chromosome. If None (default + value), use 0 as the starting position. + - end - end position on the chromosome. If None (default value), + use the length of the chromosome as the end position. + + """ + stream = self._stream + if chromosome is None: + if start is not None or end is not None: + raise ValueError( + "start and end must both be None if chromosome is None" + ) + else: + for chromIx, target in enumerate(self.targets): + if target.id == chromosome: + break + else: + raise ValueError("Failed to find %s in alignments" % chromosome) + if start is None: + if end is None: + start = 0 + end = len(target) + else: + raise ValueError("end must be None if start is None") + elif end is None: + end = start + 1 + data = self._search_index(stream, chromIx, start, end) + for row in data: + chromIx, chromStart, chromEnd, rest, dataStart, dataEnd = row + alignment = self._create_alignment( + chromIx, chromStart, chromEnd, rest, dataStart, dataEnd + ) + yield alignment + + +class _ZippedStream(io.BytesIO): + def getvalue(self): + data = super().getvalue() + return zlib.compress(data) + + +class _BufferedStream: + def __init__(self, output, size): + self.buffer = BytesIO() + self.output = output + self.size = size + + def write(self, item): + item.offset = self.output.tell() + data = bytes(item) + self.buffer.write(data) + if self.buffer.tell() == self.size: + self.output.write(self.buffer.getvalue()) + self.buffer.seek(0) + self.buffer.truncate(0) + + def flush(self): + self.output.write(self.buffer.getvalue()) + self.buffer.seek(0) + self.buffer.truncate(0) + + +class _ZippedBufferedStream(_BufferedStream): + def write(self, item): + item.offset = self.output.tell() + data = bytes(item) + self.buffer.write(data) + if self.buffer.tell() == self.size: + self.output.write(zlib.compress(self.buffer.getvalue())) + self.buffer.seek(0) + self.buffer.truncate(0) + + def flush(self): + self.output.write(zlib.compress(self.buffer.getvalue())) + self.buffer.seek(0) + self.buffer.truncate(0) + + +class _Header: + __slots__ = ( + "byteorder", + "zoomLevels", + "chromosomeTreeOffset", + "fullDataOffset", + "fullIndexOffset", + "fieldCount", + "definedFieldCount", + "autoSqlOffset", + "totalSummaryOffset", + "uncompressBufSize", + "extraIndicesOffset", + ) + + # Supplemental Table 5: Common header + # magic 4 bytes, unsigned + # version 2 bytes, unsigned + # zoomLevels 2 bytes, unsigned + # chromosomeTreeOffset 8 bytes, unsigned + # fullDataOffset 8 bytes, unsigned + # fullIndexOffset 8 bytes, unsigned + # fieldCount 2 bytes, unsigned + # definedFieldCount 2 bytes, unsigned + # autoSqlOffset 8 bytes, unsigned + # totalSummaryOffset 8 bytes, unsigned + # uncompressBufSize 4 bytes, unsigned + # reserved 8 bytes, unsigned + + formatter = struct.Struct("=IHHQQQHHQQIQ") + size = formatter.size + signature = 0x8789F2EB + bbiCurrentVersion = 4 + + @classmethod + def fromfile(cls, stream): + magic = stream.read(4) + if int.from_bytes(magic, byteorder="little") == _Header.signature: + byteorder = "<" + elif int.from_bytes(magic, byteorder="big") == _Header.signature: + byteorder = ">" + else: + raise ValueError("not a bigBed file") + formatter = struct.Struct(byteorder + "HHQQQHHQQIQ") + header = _Header() + header.byteorder = byteorder + size = formatter.size + data = stream.read(size) + ( + version, + header.zoomLevels, + header.chromosomeTreeOffset, + header.fullDataOffset, + header.fullIndexOffset, + header.fieldCount, + header.definedFieldCount, + header.autoSqlOffset, + header.totalSummaryOffset, + header.uncompressBufSize, + header.extraIndicesOffset, + ) = formatter.unpack(data) + assert version == _Header.bbiCurrentVersion + definedFieldCount = header.definedFieldCount + if definedFieldCount < 3 or definedFieldCount > 12: + raise ValueError( + "expected between 3 and 12 columns, found %d" % definedFieldCount + ) + return header + + def __bytes__(self): + return _Header.formatter.pack( + _Header.signature, + _Header.bbiCurrentVersion, + self.zoomLevels, + self.chromosomeTreeOffset, + self.fullDataOffset, + self.fullIndexOffset, + self.fieldCount, + self.definedFieldCount, + self.autoSqlOffset, + self.totalSummaryOffset, + self.uncompressBufSize, + self.extraIndicesOffset, + ) + + +class _ExtraIndex: + __slots__ = ("indexField", "maxFieldSize", "fileOffset", "chunks", "get_value") + + formatter = struct.Struct("=xxHQxxxxHxx") + + def __init__(self, name, declaration): + self.maxFieldSize = 0 + self.fileOffset = None + for index, field in enumerate(declaration): + if field.name == name: + break + else: + raise ValueError( + "extraIndex field %s not a standard bed field or found in 'as' file.", + name, + ) from None + if field.as_type != "string": + raise ValueError("Sorry for now can only index string fields.") + self.indexField = index + if name == "chrom": + self.get_value = lambda alignment: alignment.target.id + elif name == "name": + self.get_value = lambda alignment: alignment.query.id + else: + self.get_value = lambda alignment: alignment.annotations[name] + + def updateMaxFieldSize(self, alignment): + value = self.get_value(alignment) + size = len(value) + if size > self.maxFieldSize: + self.maxFieldSize = size + + def addKeysFromRow(self, alignment, recordIx): + value = self.get_value(alignment) + self.chunks[recordIx]["name"] = value.encode() + + def addOffsetSize(self, offset, size, startIx, endIx): + self.chunks[startIx:endIx]["offset"] = offset + self.chunks[startIx:endIx]["size"] = size + + def __bytes__(self): + indexFieldCount = 1 + return self.formatter.pack(indexFieldCount, self.fileOffset, self.indexField) + + +class _ExtraIndices(list): + formatter = struct.Struct("=HHQ52x") + + def __init__(self, names, declaration): + self[:] = [_ExtraIndex(name, declaration) for name in names] + + @property + def size(self): + return self.formatter.size + _ExtraIndex.formatter.size * len(self) + + def initialize(self, bedCount): + if bedCount == 0: + return + for extra_index in self: + keySize = extra_index.maxFieldSize + # bbiFile.h: bbNamedFileChunk + # name keySize bytes + # offset 8 bytes, unsigned + # size 8 bytes, unsigned + dtype = np.dtype( + [("name", f"=S{keySize}"), ("offset", "=u8"), ("size", "=u8")] + ) + extra_index.chunks = np.zeros(bedCount, dtype=dtype) + + def tofile(self, stream): + size = self.formatter.size + if len(self) > 0: + offset = stream.tell() + size + data = self.formatter.pack(size, len(self), offset) + stream.write(data) + for extra_index in self: + stream.write(bytes(extra_index)) + else: + data = self.formatter.pack(size, 0, 0) + stream.write(data) + + +class _ZoomLevel: + __slots__ = ["reductionLevel", "dataOffset", "indexOffset", "formatter"] + + def __init__(self, byteorder="="): + # Supplemental Table 6: The zoom header + # reductionLevel 4 bytes, unsigned + # reserved 4 bytes, unsigned + # dataOffset 8 bytes, unsigned + # indexOffset 8 bytes, unsigned + self.formatter = struct.Struct(byteorder + "IxxxxQQ") + + def __bytes__(self): + return self.formatter.pack( + self.reductionLevel, self.dataOffset, self.indexOffset + ) + + def read(self, stream): + data = stream.read(self.formatter.size) + reductionLevel, dataOffset, indexOffset = self.formatter.unpack(data) + if reductionLevel == 0: + raise StopIteration + self.reductionLevel = reductionLevel + self.dataOffset = dataOffset + self.indexOffset = indexOffset + + +class _ZoomLevels(list): + bbiResIncrement = 4 + bbiMaxZoomLevels = 10 + size = _ZoomLevel("=").formatter.size * bbiMaxZoomLevels + + def __init__(self, byteorder="="): + self[:] = [_ZoomLevel(byteorder) for i in range(_ZoomLevels.bbiMaxZoomLevels)] + + def __bytes__(self): + data = b"".join(bytes(item) for item in self) + data += bytes(_ZoomLevels.size - len(data)) + return data + + def read(self, stream): + for zoomLevels in range(_ZoomLevels.bbiMaxZoomLevels): + try: + self[zoomLevels].read(stream) + except StopIteration: + del self[zoomLevels:] + break + + @classmethod + def calculate_reductions(cls, aveSize): + bbiMaxZoomLevels = _ZoomLevels.bbiMaxZoomLevels + reductions = np.zeros( + bbiMaxZoomLevels, + dtype=[("scale", "=i4"), ("size", "=i4"), ("end", "=i4")], + ) + minZoom = 10 + res = max(int(aveSize), minZoom) + maxInt = np.iinfo(reductions.dtype["scale"]).max + for resTry in range(bbiMaxZoomLevels): + if res > maxInt: + break + reductions[resTry]["scale"] = res + res *= _ZoomLevels.bbiResIncrement + return reductions[:resTry] + + def reduce(self, summaries, initialReduction, buffer, blockSize, itemsPerSlot): + zoomCount = initialReduction["size"] + reduction = int(initialReduction["scale"]) * _ZoomLevels.bbiResIncrement + output = buffer.output + formatter = _RTreeFormatter() + for zoomLevels in range(1, _ZoomLevels.bbiMaxZoomLevels): + rezoomCount = len(summaries) + if rezoomCount >= zoomCount: + break + zoomCount = rezoomCount + self[zoomLevels].dataOffset = output.tell() + data = zoomCount.to_bytes(4, sys.byteorder) + output.write(data) + for summary in summaries: + buffer.write(summary) + buffer.flush() + indexOffset = output.tell() + formatter.write(summaries, blockSize, itemsPerSlot, indexOffset, output) + self[zoomLevels].indexOffset = indexOffset + self[zoomLevels].reductionLevel = reduction + reduction *= _ZoomLevels.bbiResIncrement + i = 0 + chromId = None + for summary in summaries: + if summary.chromId != chromId or summary.end > end: # noqa: F821 + end = summary.start + reduction + chromId = summary.chromId + currentSummary = summary + summaries[i] = currentSummary + i += 1 + else: + currentSummary += summary + del summaries[i:] + del self[zoomLevels:] + + +class _Summary: + __slots__ = ("validCount", "minVal", "maxVal", "sumData", "sumSquares") + + formatter = struct.Struct("=Qdddd") + size = formatter.size + + def __init__(self): + self.validCount = 0 + self.minVal = sys.maxsize + self.maxVal = -sys.maxsize + self.sumData = 0.0 + self.sumSquares = 0.0 + + def update(self, size, val): + self.validCount += size + if val < self.minVal: + self.minVal = val + if val > self.maxVal: + self.maxVal = val + self.sumData += val * size + self.sumSquares += val * val * size + + def __bytes__(self): + return self.formatter.pack( + self.validCount, + self.minVal, + self.maxVal, + self.sumData, + self.sumSquares, + ) + + +class _Region: + __slots__ = ("chromId", "start", "end", "offset") + + def __init__(self, chromId, start, end): + self.chromId = chromId + self.start = start + self.end = end + + +class _RegionSummary(_Summary): + __slots__ = _Region.__slots__ + _Summary.__slots__ + + formatter = struct.Struct("=IIIIffff") + size = formatter.size + + def __init__(self, chromId, start, end, value): + self.chromId = chromId + self.start = start + self.end = end + self.validCount = 0 + self.minVal = np.float32(value) + self.maxVal = np.float32(value) + self.sumData = np.float32(0.0) + self.sumSquares = np.float32(0.0) + self.offset = None + + def __iadd__(self, other): + self.end = other.end + self.validCount += other.validCount + self.minVal = min(self.minVal, other.minVal) + self.maxVal = max(self.maxVal, other.maxVal) + self.sumData = np.float32(self.sumData + other.sumData) + self.sumSquares = np.float32(self.sumSquares + other.sumSquares) + return self + + def update(self, overlap, val): + self.validCount += overlap + if self.minVal > val: + self.minVal = np.float32(val) + if self.maxVal < val: + self.maxVal = np.float32(val) + self.sumData = np.float32(self.sumData + val * overlap) + self.sumSquares = np.float32(self.sumSquares + val * val * overlap) + + def __bytes__(self): + return self.formatter.pack( + self.chromId, + self.start, + self.end, + self.validCount, + self.minVal, + self.maxVal, + self.sumData, + self.sumSquares, + ) + + +class _RTreeNode: + __slots__ = [ + "children", + "parent", + "startChromId", + "startBase", + "endChromId", + "endBase", + "startFileOffset", + "endFileOffset", + ] + + def __init__(self): + self.parent = None + self.children = [] + + def calcLevelSizes(self, levelSizes, level): + levelSizes[level] += 1 + level += 1 + if level == len(levelSizes): + return + for child in self.children: + child.calcLevelSizes(levelSizes, level) + + +class _RangeTree: + __slots__ = ("root", "n", "freeList", "stack", "chromId", "chromSize") + + def __init__(self, chromId, chromSize): + self.root = None + self.n = 0 + self.freeList = [] + self.chromId = chromId + self.chromSize = chromSize + + @classmethod + def generate(cls, chromUsageList, alignments): + alignments = iter(alignments) + alignment = None + for chromName, chromId, chromSize in chromUsageList: + chromName = chromName.decode() + tree = _RangeTree(chromId, chromSize) + if alignment is not None: + tree.addToCoverageDepth(alignment) + while True: + try: + alignment = next(alignments) + except StopIteration: + break + if alignment.target.id != chromName: + break + tree.addToCoverageDepth(alignment) + yield tree + + def generate_summaries(self, scale, totalSum): + ranges = self.root.traverse() + start, end, val = next(ranges) + chromId = self.chromId + chromSize = self.chromSize + summary = _RegionSummary( + chromId, + start, + min(start + scale, chromSize), + val, + ) + while True: + size = max(end - start, 1) + totalSum.update(size, val) + if summary.end <= start: + summary = _RegionSummary( + chromId, + start, + min(start + scale, chromSize), + val, + ) + while end > summary.end: + overlap = min(end, summary.end) - max(start, summary.start) + assert overlap > 0 + summary.update(overlap, val) + size -= overlap + start = summary.end + yield summary + summary = _RegionSummary( + chromId, + start, + min(start + scale, chromSize), + val, + ) + summary.update(size, val) + try: + start, end, val = next(ranges) + except StopIteration: + break + if summary.end <= start: + yield summary + yield summary + + def find(self, start, end): + p = self.root + while p is not None: + if end <= p.item.start: + p = p.left + elif p.item.end <= start: + p = p.right + else: + return p.item + + def restructure(self, x, y, z): + tos = len(self.stack) + if y is x.left: + if z is y.left: + midNode = y + y.left = z + x.left = y.right + y.right = x + else: + midNode = z + y.right = z.left + z.left = y + x.left = z.right + z.right = x + else: + if z is y.left: + midNode = z + x.right = z.left + z.left = x + y.left = z.right + z.right = y + else: + midNode = y + x.right = y.left + y.left = x + y.right = z + if tos != 0: + parent = self.stack[tos - 1] + if x is parent.left: + parent.left = midNode + else: + parent.right = midNode + else: + self.root = midNode + return midNode + + def add(self, item): + self.stack = [] + try: + x = self.freeList.pop() + except IndexError: + x = _RedBlackTreeNode() + else: + self.freeList = x.right + x.left = None + x.right = None + x.item = item + x.color = None + p = self.root + if p is not None: + while True: + self.stack.append(p) + if item.end <= p.item.start: + p = p.left + if p is None: + p = self.stack.pop() + p.left = x + break + elif p.item.end <= item.start: + p = p.right + if p is None: + p = self.stack.pop() + p.right = x + break + else: + return + col = True + else: + self.root = x + col = False + x.color = col + self.n += 1 + if len(self.stack) > 0: + while p.color is True: + m = self.stack.pop() + if p == m.left: + q = m.right + else: + q = m.left + if q is None or q.color is False: + m = self.restructure(m, p, x) + m.color = False + m.left.color = True + m.right.color = True + break + p.color = False + q.color = False + if len(self.stack) == 0: + break + m.color = True + x = m + p = self.stack.pop() + + def addToCoverageDepth(self, alignment): + start = alignment.coordinates[0, 0] + end = alignment.coordinates[0, -1] + if start > end: + start, end = end, start + existing = self.find(start, end) + if existing is None: + r = _Range(start, end, val=1) + self.add(r) + else: + if existing.start <= start and existing.end >= end: + if existing.start < start: + r = _Range(existing.start, start, existing.val) + existing.start = start + self.add(r) + if existing.end > end: + r = _Range(end, existing.end, existing.val) + existing.end = end + self.add(r) + existing.val += 1 + else: + items = list(self.root.traverse_range(start, end)) + s = start + e = end + for item in items: + if s < item.start: + r = _Range(s, item.start, 1) + s = item.start + self.add(r) + elif s > item.start: + r = _Range(item.start, s, item.val) + item.start = s + self.add(r) + if item.start < end and item.end > end: + r = _Range(end, item.end, item.val) + item.end = end + self.add(r) + item.val += 1 + s = item.end + if s < e: + r = _Range(s, e, 1) + self.add(r) + + +class _Range: + __slots__ = ("next", "start", "end", "val") + + def __init__(self, start, end, val): + self.start = start + self.end = end + self.val = val + + def __iter__(self): + return iter((self.start, self.end, self.val)) + + +class _RedBlackTreeNode: + __slots__ = ("left", "right", "color", "item") + + def traverse(self): + if self.left is not None: + yield from self.left.traverse() + yield self.item + if self.right is not None: + yield from self.right.traverse() + + def traverse_range(self, start, end): + if self.item.end <= start: + if self.right is not None: + yield from self.right.traverse_range(start, end) + elif end <= self.item.start: + if self.left is not None: + yield from self.left.traverse_range(start, end) + else: + if self.left is not None: + yield from self.left.traverse_range(start, end) + yield self.item + if self.right is not None: + yield from self.right.traverse_range(start, end) + + +class _RTreeFormatter: + signature = 0x2468ACE0 + + def __init__(self, byteorder="="): + # Supplemental Table 14: R tree index header + # magic 4 bytes, unsigned + # blockSize 4 bytes, unsigned + # itemCount 8 bytes, unsigned + # startChromIx 4 bytes, unsigned + # startBase 4 bytes, unsigned + # endChromIx 4 bytes, unsigned + # endBase 4 bytes, unsigned + # endFileOffset 8 bytes, unsigned + # itemsPerSlot 4 bytes, unsigned + # reserved 4 bytes, unsigned + self.formatter_header = struct.Struct(byteorder + "IIQIIIIQIxxxx") + + # Supplemental Table 15: R tree node format + # isLeaf 1 byte + # reserved 1 byte + # count 2 bytes, unsigned + self.formatter_node = struct.Struct(byteorder + "?xH") + + # Supplemental Table 17: R tree non-leaf format + # startChromIx 4 bytes, unsigned + # startBase 4 bytes, unsigned + # endChromIx 4 bytes, unsigned + # endBase 4 bytes, unsigned + # dataOffset 8 bytes, unsigned + self.formatter_nonleaf = struct.Struct(byteorder + "IIIIQ") + + # Supplemental Table 16: R tree leaf format + # startChromIx 4 bytes, unsigned + # startBase 4 bytes, unsigned + # endChromIx 4 bytes, unsigned + # endBase 4 bytes, unsigned + # dataOffset 8 bytes, unsigned + # dataSize 8 bytes, unsigned + self.formatter_leaf = struct.Struct(byteorder + "IIIIQQ") + + def read(self, stream): + NonLeaf = namedtuple( + "NonLeaf", + [ + "parent", + "children", + "startChromIx", + "startBase", + "endChromIx", + "endBase", + "dataOffset", + ], + ) + + Leaf = namedtuple( + "Leaf", + [ + "parent", + "startChromIx", + "startBase", + "endChromIx", + "endBase", + "dataOffset", + "dataSize", + ], + ) + + data = stream.read(self.formatter_header.size) + ( + magic, + blockSize, + itemCount, + startChromIx, + startBase, + endChromIx, + endBase, + endFileOffset, + itemsPerSlot, + ) = self.formatter_header.unpack(data) + assert magic == _RTreeFormatter.signature + + formatter_node = self.formatter_node + formatter_nonleaf = self.formatter_nonleaf + formatter_leaf = self.formatter_leaf + + root = NonLeaf(None, [], startChromIx, startBase, endChromIx, endBase, None) + node = root + itemsCounted = 0 + while True: + data = stream.read(formatter_node.size) + isLeaf, count = formatter_node.unpack(data) + if isLeaf: + children = node.children + for i in range(count): + data = stream.read(formatter_leaf.size) + ( + startChromIx, + startBase, + endChromIx, + endBase, + dataOffset, + dataSize, + ) = formatter_leaf.unpack(data) + child = Leaf( + node, + startChromIx, + startBase, + endChromIx, + endBase, + dataOffset, + dataSize, + ) + children.append(child) + itemsCounted += count + while True: + parent = node.parent + if parent is None: + assert itemsCounted == itemCount + return node + for index, child in enumerate(parent.children): + if id(node) == id(child): + break + else: + raise RuntimeError("Failed to find child node") + try: + node = parent.children[index + 1] + except IndexError: + node = parent + else: + break + else: + children = node.children + for i in range(count): + data = stream.read(formatter_nonleaf.size) + ( + startChromIx, + startBase, + endChromIx, + endBase, + dataOffset, + ) = formatter_nonleaf.unpack(data) + child = NonLeaf( + node, + [], + startChromIx, + startBase, + endChromIx, + endBase, + dataOffset, + ) + children.append(child) + parent = node + node = children[0] + stream.seek(node.dataOffset) + + def rTreeFromChromRangeArray(self, blockSize, items, endFileOffset): + itemCount = len(items) + if itemCount == 0: + return + children = [] + nextOffset = items[0].offset + oneSize = 0 + i = 0 + while i < itemCount: + child = _RTreeNode() + children.append(child) + startItem = items[i] + child.startChromId = child.endChromId = startItem.chromId + child.startBase = startItem.start + child.endBase = startItem.end + child.startFileOffset = nextOffset + oneSize = 1 + endItem = startItem + for j in range(i + 1, itemCount): + endItem = items[j] + nextOffset = endItem.offset + if nextOffset != child.startFileOffset: + break + oneSize += 1 + else: + nextOffset = endFileOffset + child.endFileOffset = nextOffset + for item in items[i + 1 : i + oneSize]: + if item.chromId < child.startChromId: + child.startChromId = item.chromId + child.startBase = item.start + elif ( + item.chromId == child.startChromId and item.start < child.startBase + ): + child.startBase = item.start + if item.chromId > child.endChromId: + child.endChromId = item.chromId + child.endBase = item.end + elif item.chromId == child.endChromId and item.end > child.endBase: + child.endBase = item.end + i += oneSize + levelCount = 1 + while True: + parents = [] + slotsUsed = blockSize + for child in children: + if slotsUsed >= blockSize: + slotsUsed = 1 + parent = _RTreeNode() + parent.parent = child.parent + parent.startChromId = child.startChromId + parent.startBase = child.startBase + parent.endChromId = child.endChromId + parent.endBase = child.endBase + parent.startFileOffset = child.startFileOffset + parent.endFileOffset = child.endFileOffset + parents.append(parent) + else: + slotsUsed += 1 + if child.startChromId < parent.startChromId: + parent.startChromId = child.startChromId + parent.startBase = child.startBase + elif ( + child.startChromId == parent.startChromId + and child.startBase < parent.startBase + ): + parent.startBase = child.startBase + if child.endChromId > parent.endChromId: + parent.endChromId = child.endChromId + parent.endBase = child.endBase + elif ( + child.endChromId == parent.endChromId + and child.endBase > parent.endBase + ): + parent.endBase = child.endBase + parent.children.append(child) + child.parent = parent + levelCount += 1 + if len(parents) == 1: + break + children = parents + return parent, levelCount + + def rWriteLeaves(self, itemsPerSlot, lNodeSize, tree, curLevel, leafLevel, output): + formatter_leaf = self.formatter_leaf + if curLevel == leafLevel: + isLeaf = True + data = self.formatter_node.pack(isLeaf, len(tree.children)) + output.write(data) + for child in tree.children: + data = formatter_leaf.pack( + child.startChromId, + child.startBase, + child.endChromId, + child.endBase, + child.startFileOffset, + child.endFileOffset - child.startFileOffset, + ) + output.write(data) + output.write( + bytes((itemsPerSlot - len(tree.children)) * self.formatter_nonleaf.size) + ) + # self.formatter_leaf.size seems more reasonable here, but this is + # what bedToBigBed has here. See also + # https://github.com/ucscGenomeBrowser/kent/issues/76. + else: + for child in tree.children: + self.rWriteLeaves( + itemsPerSlot, lNodeSize, child, curLevel + 1, leafLevel, output + ) + + def rWriteIndexLevel( + self, parent, blockSize, childNodeSize, curLevel, destLevel, offset, output + ): + previous_offset = offset + formatter_nonleaf = self.formatter_nonleaf + if curLevel == destLevel: + isLeaf = False + data = self.formatter_node.pack(isLeaf, len(parent.children)) + output.write(data) + for child in parent.children: + data = formatter_nonleaf.pack( + child.startChromId, + child.startBase, + child.endChromId, + child.endBase, + offset, + ) + output.write(data) + offset += childNodeSize + output.write( + bytes((blockSize - len(parent.children)) * self.formatter_nonleaf.size) + ) + else: + for child in parent.children: + offset = self.rWriteIndexLevel( + child, + blockSize, + childNodeSize, + curLevel + 1, + destLevel, + offset, + output, + ) + position = output.tell() + if position != previous_offset: + raise RuntimeError( + f"Internal error: offset mismatch ({position} vs {previous_offset})" + ) + return offset + + def write(self, items, blockSize, itemsPerSlot, endFileOffset, output): + root, levelCount = self.rTreeFromChromRangeArray( + blockSize, items, endFileOffset + ) + data = self.formatter_header.pack( + _RTreeFormatter.signature, + blockSize, + len(items), + root.startChromId, + root.startBase, + root.endChromId, + root.endBase, + endFileOffset, + itemsPerSlot, + ) + output.write(data) + + if root is None: + return + + levelSizes = np.zeros(levelCount, int) + root.calcLevelSizes(levelSizes, level=0) + size = self.formatter_node.size + self.formatter_nonleaf.size * blockSize + levelOffset = output.tell() + for i in range(levelCount - 2): + levelOffset += levelSizes[i] * size + if i == levelCount - 3: + size = self.formatter_node.size + self.formatter_leaf.size * blockSize + self.rWriteIndexLevel(root, blockSize, size, 0, i, levelOffset, output) + leafLevel = levelCount - 2 + self.rWriteLeaves(blockSize, size, root, 0, leafLevel, output) + + +class _BPlusTreeFormatter: + signature = 0x78CA8C91 + + def __init__(self, byteorder="="): + # Supplemental Table 8: Chromosome B+ tree header + # magic 4 bytes, unsigned + # blockSize 4 bytes, unsigned + # keySize 4 bytes, unsigned + # valSize 4 bytes, unsigned + # itemCount 8 bytes, unsigned + # reserved 8 bytes, unsigned + self.formatter_header = struct.Struct(byteorder + "IIIIQxxxxxxxx") + + # Supplemental Table 9: Chromosome B+ tree node + # isLeaf 1 byte + # reserved 1 byte + # count 2 bytes, unsigned + self.formatter_node = struct.Struct(byteorder + "?xH") + + # Supplemental Table 11: Chromosome B+ tree non-leaf item + # key keySize bytes + # childOffset 8 bytes, unsigned + self.fmt_nonleaf = byteorder + "{keySize}sQ" + + self.byteorder = byteorder + + def read(self, stream): + byteorder = self.byteorder + + formatter = self.formatter_header + data = stream.read(formatter.size) + magic, blockSize, keySize, valSize, itemCount = formatter.unpack(data) + assert magic == _BPlusTreeFormatter.signature + + formatter_node = self.formatter_node + formatter_nonleaf = struct.Struct(self.fmt_nonleaf.format(keySize=keySize)) + + # Supplemental Table 10: Chromosome B+ tree leaf item format + # key keySize bytes + # chromId 4 bytes, unsigned + # chromSize 4 bytes, unsigned + formatter_leaf = struct.Struct(f"{byteorder}{keySize}sII") + assert keySize == formatter_leaf.size - valSize + assert valSize == 8 + + Node = namedtuple("Node", ["parent", "children"]) + + targets = [] + node = None + while True: + data = stream.read(formatter_node.size) + isLeaf, count = formatter_node.unpack(data) + if isLeaf: + for i in range(count): + data = stream.read(formatter_leaf.size) + key, chromId, chromSize = formatter_leaf.unpack(data) + name = key.rstrip(b"\x00").decode() + assert chromId == len(targets) + sequence = Seq(None, length=chromSize) + record = SeqRecord(sequence, id=name) + targets.append(record) + else: + children = [] + for i in range(count): + data = stream.read(formatter_nonleaf.size) + key, pos = formatter_nonleaf.unpack(data) + children.append(pos) + parent = node + node = Node(parent, children) + while True: + if node is None: + assert len(targets) == itemCount + return targets + children = node.children + try: + pos = children.pop(0) + except IndexError: + node = node.parent + else: + break + stream.seek(pos) + + def write(self, items, blockSize, output): + signature = _BPlusTreeFormatter.signature + keySize = items.dtype["name"].itemsize + valSize = items.itemsize - keySize + itemCount = len(items) + formatter = self.formatter_header + data = formatter.pack(signature, blockSize, keySize, valSize, itemCount) + output.write(data) + + formatter_node = self.formatter_node + formatter_nonleaf = struct.Struct(self.fmt_nonleaf.format(keySize=keySize)) + + levels = 1 + while itemCount > blockSize: + itemCount = len(range(0, itemCount, blockSize)) + levels += 1 + itemCount = len(items) + bytesInIndexBlock = formatter_node.size + blockSize * formatter_nonleaf.size + bytesInLeafBlock = formatter_node.size + blockSize * items.itemsize + isLeaf = False + indexOffset = output.tell() + for level in range(levels - 1, 0, -1): + slotSizePer = blockSize**level + nodeSizePer = slotSizePer * blockSize + indices = range(0, itemCount, nodeSizePer) + if level == 1: + bytesInNextLevelBlock = bytesInLeafBlock + else: + bytesInNextLevelBlock = bytesInIndexBlock + levelSize = len(indices) * bytesInIndexBlock + endLevel = indexOffset + levelSize + nextChild = endLevel + for index in indices: + block = items[index : index + nodeSizePer : slotSizePer] + n = len(block) + output.write(formatter_node.pack(isLeaf, n)) + for item in block: + data = formatter_nonleaf.pack(item["name"], nextChild) + output.write(data) + nextChild += bytesInNextLevelBlock + data = bytes((blockSize - n) * formatter_nonleaf.size) + output.write(data) + indexOffset = endLevel + isLeaf = True + for index in itertools.count(0, blockSize): + block = items[index : index + blockSize] + n = len(block) + if n == 0: + break + output.write(formatter_node.pack(isLeaf, n)) + block.tofile(output) + data = bytes((blockSize - n) * items.itemsize) + output.write(data) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/bigmaf.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/bigmaf.py new file mode 100644 index 0000000000000000000000000000000000000000..b0afb5b97bdc941fc1708446c03e1bc2097d1e34 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/bigmaf.py @@ -0,0 +1,353 @@ +# Copyright 2022 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for the "bigmaf" multiple alignment format. + +The bigMaf format stores multiple alignments in a format compatible with +the MAF (Multiple Alignment Format) format. BigMaf files are binary and are +indexed as a bigBed file. + +See https://genome.ucsc.edu/goldenPath/help/bigMaf.html +""" + +import re +import struct +import zlib + +import numpy as np + +from Bio.Align import _aligncore # type: ignore +from Bio.Align import Alignment +from Bio.Align import Alignments +from Bio.Align import bigbed +from Bio.Align import maf +from Bio.Align.bigbed import AutoSQLTable +from Bio.Align.bigbed import Field +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +declaration = AutoSQLTable( + "bedMaf", + "Bed3 with MAF block", + [ + Field( + as_type="string", + name="chrom", + comment="Reference sequence chromosome or scaffold", + ), + Field( + as_type="uint", + name="chromStart", + comment="Start position in chromosome", + ), + Field( + as_type="uint", + name="chromEnd", + comment="End position in chromosome", + ), + Field( + as_type="lstring", + name="mafBlock", + comment="MAF block", + ), + ], +) + + +class AlignmentWriter(bigbed.AlignmentWriter): + """Alignment file writer for the bigMaf file format.""" + + fmt = "bigMaf" + + def __init__( + self, + target, + targets=None, + compress=True, + blockSize=256, + itemsPerSlot=512, + ): + """Create an AlignmentWriter object. + + Arguments: + - target - output stream or file name. + - targets - A list of SeqRecord objects with the chromosomes in + the order as they appear in the alignments. The + sequence contents in each SeqRecord may be undefined, + but the sequence length must be defined, as in this + example: + + SeqRecord(Seq(None, length=248956422), id="chr1") + + If targets is None (the default value), the alignments + must have an attribute .targets providing the list of + SeqRecord objects. + - compress - If True (default), compress data using zlib. + If False, do not compress data. + Use compress=False for faster searching. + - blockSize - Number of items to bundle in r-tree. + See UCSC's bedToBigBed program for more information. + Default value is 256. + - itemsPerSlot - Number of data points bundled at lowest level. + See UCSC's bedToBigBed program for more information. + Use itemsPerSlot=1 for faster searching. + Default value is 512. + + """ + super().__init__( + target, + bedN=3, + declaration=declaration, + targets=targets, + compress=compress, + blockSize=blockSize, + itemsPerSlot=itemsPerSlot, + ) + + def write_file(self, stream, alignments): + """Write the file.""" + fixed_alignments = Alignments() + for alignment in alignments: + if not isinstance(alignment, Alignment): + raise TypeError("Expected an Alignment object") + mafBlock = format(alignment, "maf")[:-1].replace("\n", ";") + coordinates = alignment.coordinates + if not coordinates.size: # alignment consists of gaps only + continue + alignment = alignment[:2] + reference, chromosome = alignment.target.id.split(".", 1) + alignment.target.id = chromosome + assert coordinates[0, 0] < coordinates[0, -1] + alignment.annotations = {} + alignment.annotations["mafBlock"] = mafBlock + fixed_alignments.append(alignment) + fixed_alignments.sort( + key=lambda alignment: (alignment.target.id, alignment.coordinates[0, 0]) + ) + record = alignments.targets[0] + reference, chromosome = record.id.split(".", 1) + targets = list(alignments.targets) + targets[0] = SeqRecord(record.seq, id=chromosome) + fixed_alignments.targets = targets + bigbed.AlignmentWriter( + stream, bedN=3, declaration=declaration, compress=self.compress + ).write(fixed_alignments) + + +class AlignmentIterator(bigbed.AlignmentIterator, maf.AlignmentIterator): + """Alignment iterator for bigMaf files. + + The file may contain multiple alignments, which are loaded and returned + incrementally. + + Alignment annotations are stored in the ``.annotations`` attribute of the + ``Alignment`` object, except for the alignment score, which is stored as an + attribute. Sequence information of empty parts in the alignment block + (sequences that connect the previous alignment block to the next alignment + block, but do not align to the current alignment block) is stored in the + alignment annotations under the ``"empty"`` key. Annotations specific to + each line in the alignment are stored in the ``.annotations`` attribute of + the corresponding sequence record. + """ + + fmt = "bigMaf" + mode = "b" + + def __init__(self, source): + """Create an AlignmentIterator object. + + Arguments: + - source - input file stream, or path to input file + """ + self.reference = None + super().__init__(source) + + def _read_reference(self, stream): + # Supplemental Table 12: Binary BED-data format + # chromId 4 bytes, unsigned + # chromStart 4 bytes, unsigned + # chromEnd 4 bytes, unsigned + # rest zero-terminated string in tab-separated format + formatter = struct.Struct(self.byteorder + "III") + size = formatter.size + node = self.tree + while True: + try: + children = node.children + except AttributeError: + break + else: + node = children[0] + filepos = stream.tell() + stream.seek(node.dataOffset) + dataSize = 256 + data = b"" + compressed_data = b"" + while True: + chunk = stream.read(dataSize) + if self._compressed: + compressed_data += chunk + decompressor = zlib.decompressobj() + data = decompressor.decompress(compressed_data) + else: + data += chunk + try: + i = data.index(b";s", size) + except ValueError: + continue + words = data[i + 1 :].split() + if len(words) > 2: + break + name = words[1] + stream.seek(filepos) + reference, chromosome = name.split(b".", 1) + return reference.decode() + + def _read_header(self, stream): + super()._read_header(stream) + if self.reference is None: + self.reference = self._read_reference(stream) + self._index = 0 + self.targets[0].id = "%s.%s" % (self.reference, self.targets[0].id) + + def _create_alignment( + self, chromId, chromStart, chromEnd, data, dataStart, dataEnd + ): + assert data[dataEnd - 1] == 0 + buffer = memoryview(data) + buffer = buffer[dataStart:dataEnd] + records = [] + strands = [] + annotations = {} + score = None + printed_alignment_parser = _aligncore.PrintedAlignmentParser(b";") + j = -1 + sequences = [] + while True: + i = j + 1 + prefix = buffer[i : i + 1] + if prefix == b"#": + m = re.match(b"^[^;]*", buffer[i:]) + j = i + m.span()[1] + elif prefix == b"a": + m = re.match(b"^[^;]*", buffer[i:]) + j = i + m.span()[1] + line = buffer[i:j].tobytes() + words = line[1:].split() + for word in words: + key, value = word.split(b"=") + if key == b"score": + score = float(value) + elif key == b"pass": + value = int(value) + if value <= 0: + raise ValueError( + "pass value must be positive (found %d)" % value + ) + annotations["pass"] = value + else: + raise ValueError( + "Unknown annotation variable '%s'" % key.decode() + ) + elif prefix == b"s": + m = re.match(rb"^s\s*\S*\s*\d*\s*\d*\s*[+-]\s*\d*\s*", buffer[i:]) + j = i + m.span()[1] + line = buffer[i:j].tobytes() + words = line.split(None, 5) + if len(words) != 6: + raise ValueError( + "Error parsing alignment - 's' line must have 7 fields" + ) + src = words[1].decode() + start = int(words[2]) + size = int(words[3]) + strand = words[4] + srcSize = int(words[5]) + i = j + n, sequence = printed_alignment_parser.feed(data, dataStart + i) + if len(sequence) != size: + raise ValueError( + "sequence size is incorrect (found %d, expected %d)" + % (len(sequence), size) + ) + seq = Seq({start: sequence}, length=srcSize) + record = SeqRecord(seq, id=src, name="", description="") + records.append(record) + j = i + n + i = j + 1 + strands.append(strand) + elif prefix == b"i": + m = re.match(b"^[^;]*", buffer[i:]) + j = i + m.span()[1] + line = buffer[i:j].tobytes() + words = line.split(None, 5) + assert len(words) == 6 + assert words[1].decode() == src # from the previous "s" line + leftStatus = words[2].decode() + leftCount = int(words[3]) + rightStatus = words[4].decode() + rightCount = int(words[5]) + assert leftStatus in AlignmentIterator.status_characters + assert rightStatus in AlignmentIterator.status_characters + record.annotations["leftStatus"] = leftStatus + record.annotations["leftCount"] = leftCount + record.annotations["rightStatus"] = rightStatus + record.annotations["rightCount"] = rightCount + elif prefix == b"e": + m = re.match(b"^[^;]*", buffer[i:]) + j = i + m.span()[1] + line = buffer[i:j].tobytes() + words = line.split(None, 6) + assert len(words) == 7 + src = words[1].decode() + start = int(words[2]) + size = int(words[3]) + strand = words[4] + srcSize = int(words[5]) + status = words[6].decode() + assert status in AlignmentIterator.empty_status_characters + sequence = Seq(None, length=srcSize) + record = SeqRecord(sequence, id=src, name="", description="") + end = start + size + if strand == b"+": + segment = (start, end) + else: + segment = (srcSize - start, srcSize - end) + empty = (record, segment, status) + annotation = annotations.get("empty") + if annotation is None: + annotation = [] + annotations["empty"] = annotation + annotation.append(empty) + elif prefix == b"q": + m = re.match(b"^[^;]*", buffer[i:]) + j = i + m.span()[1] + line = buffer[i:j].tobytes() + words = line.split(None, 2) + assert len(words) == 3 + assert words[1].decode() == src # from the previous "s" line + value = words[2].replace(b"-", b"") + record.annotations["quality"] = value.decode() + elif prefix == b"\00": + # reached the end of the alignment + break + else: + raise ValueError(f"Error parsing alignment - unexpected line:\n{line}") + shape = printed_alignment_parser.shape + coordinates = np.empty(shape, np.intp) + printed_alignment_parser.fill(coordinates) + for record, strand, row in zip(records, strands, coordinates): + if strand == b"+": + row += record.seq.defined_ranges[0][0] + else: # strand == b"-" + record.seq = record.seq.reverse_complement() + row[:] = record.seq.defined_ranges[0][1] - row + alignment = Alignment(records, coordinates) + if annotations is not None: + alignment.annotations = annotations + if score is not None: + alignment.score = score + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/bigpsl.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/bigpsl.py new file mode 100644 index 0000000000000000000000000000000000000000..e52d53fcde28f7aa130233ea955c928ca13660a3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/bigpsl.py @@ -0,0 +1,613 @@ +# Copyright 2022 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for alignment files in the bigPsl format. + +A bigPsl file is a bigBed file with a BED12+13 format consisting of the 12 +predefined BED fields and 13 custom fields defined in the autoSql file +bigPsl.as. This module uses the Bio.Align.bigbed module to parse the file, +but stores the data in a PSL-consistent manner as defined in bigPsl.as. As the +bigPsl format is a special case of the bigBed format, bigPsl files are binary +and are indexed as bigBed files. + +See http://genome.ucsc.edu/goldenPath/help/bigPsl.html for more information. + +You are expected to use this module via the Bio.Align functions. +""" + +import numpy as np + +from Bio.Align import Alignment +from Bio.Align import Alignments +from Bio.Align import bigbed +from Bio.Align.bigbed import AutoSQLTable +from Bio.Align.bigbed import Field +from Bio.Seq import reverse_complement +from Bio.Seq import Seq +from Bio.Seq import UndefinedSequenceError +from Bio.SeqFeature import Location +from Bio.SeqFeature import SeqFeature +from Bio.SeqIO.InsdcIO import _insdc_location_string +from Bio.SeqRecord import SeqRecord + +declaration = AutoSQLTable( + "bigPsl", + "bigPsl pairwise alignment", + [ + Field( + as_type="string", + name="chrom", + comment="Reference sequence chromosome or scaffold", + ), + Field( + as_type="uint", + name="chromStart", + comment="Start position in chromosome", + ), + Field( + as_type="uint", + name="chromEnd", + comment="End position in chromosome", + ), + Field( + as_type="string", + name="name", + comment="Name or ID of item, ideally both human readable and unique", + ), + Field( + as_type="uint", + name="score", + comment="Score (0-1000)", + ), + Field( + as_type="char[1]", + name="strand", + comment="+ or - indicates whether the query aligns to the + or - strand on the reference", + ), + Field( + as_type="uint", + name="thickStart", + comment="Start of where display should be thick (start codon)", + ), + Field( + as_type="uint", + name="thickEnd", + comment="End of where display should be thick (stop codon)", + ), + Field( + as_type="uint", + name="reserved", + comment="RGB value (use R,G,B string in input file)", + ), + Field( + as_type="int", + name="blockCount", + comment="Number of blocks", + ), + Field( + as_type="int[blockCount]", + name="blockSizes", + comment="Comma separated list of block sizes", + ), + Field( + as_type="int[blockCount]", + name="chromStarts", + comment="Start positions relative to chromStart", + ), + Field( + as_type="uint", + name="oChromStart", + comment="Start position in other chromosome", + ), + Field( + as_type="uint", + name="oChromEnd", + comment="End position in other chromosome", + ), + Field( + as_type="char[1]", + name="oStrand", + comment="+ or -, - means that psl was reversed into BED-compatible coordinates", + ), + Field( + as_type="uint", + name="oChromSize", + comment="Size of other chromosome.", + ), + Field( + as_type="int[blockCount]", + name="oChromStarts", + comment="Start positions relative to oChromStart or from oChromStart+oChromSize depending on strand", + ), + Field( + as_type="lstring", + name="oSequence", + comment="Sequence on other chrom (or edit list, or empty)", + ), + Field( + as_type="string", + name="oCDS", + comment="CDS in NCBI format", + ), + Field( + as_type="uint", + name="chromSize", + comment="Size of target chromosome", + ), + Field( + as_type="uint", + name="match", + comment="Number of bases matched.", + ), + Field( + as_type="uint", + name="misMatch", + comment="Number of bases that don't match", + ), + Field( + as_type="uint", + name="repMatch", + comment="Number of bases that match but are part of repeats", + ), + Field( + as_type="uint", + name="nCount", + comment="Number of 'N' bases", + ), + Field( + as_type="uint", + name="seqType", + comment="0=empty, 1=nucleotide, 2=amino_acid", + ), + ], +) + + +class AlignmentWriter(bigbed.AlignmentWriter): + """Alignment file writer for the bigPsl file format.""" + + fmt = "bigPsl" + + def __init__( + self, + target, + targets=None, + compress=True, + extraIndex=(), + cds=False, + fa=False, + mask=None, + wildcard="N", + ): + """Create an AlignmentWriter object. + + Arguments: + - target - output stream or file name. + - targets - A list of SeqRecord objects with the chromosomes in the + order as they appear in the alignments. The sequence + contents in each SeqRecord may be undefined, but the + sequence length must be defined, as in this example: + + SeqRecord(Seq(None, length=248956422), id="chr1") + + If targets is None (the default value), the alignments + must have an attribute .targets providing the list of + SeqRecord objects. + - compress - If True (default), compress data using zlib. + If False, do not compress data. + - extraIndex - List of strings with the names of extra columns to be + indexed. + Default value is an empty list. + - cds - If True, look for a query feature of type CDS and write + it in NCBI style in the PSL file (default: False). + - fa - If True, include the query sequence in the PSL file + (default: False). + - mask - Specify if repeat regions in the target sequence are + masked and should be reported in the `repMatches` field + instead of in the `matches` field. + Acceptable values are + None : no masking (default); + "lower": masking by lower-case characters; + "upper": masking by upper-case characters. + - wildcard - Report alignments to the wildcard character in the + target or query sequence in the `nCount` field instead + of in the `matches`, `misMatches`, or `repMatches` + fields. + Default value is 'N'. + """ + super().__init__( + target, + bedN=12, + declaration=declaration, + targets=targets, + compress=compress, + extraIndex=extraIndex, + ) + self.cds = cds + self.fa = fa + self.mask = mask + self.wildcard = wildcard + + def write_file(self, stream, alignments): + """Write the file.""" + fixed_alignments = Alignments() + cds = self.cds + fa = self.fa + for alignment in alignments: + if not isinstance(alignment, Alignment): + raise TypeError("Expected an Alignment object") + coordinates = alignment.coordinates + if not coordinates.size: # alignment consists of gaps only + continue + target, query = alignment.sequences + try: + query = query.seq + except AttributeError: + pass + try: + target = target.seq + except AttributeError: + pass + tSize = len(target) + qSize = len(query) + # fmt: off + dnax = None # set to True for translated DNA aligned to protein, + # and to False for DNA/RNA aligned to DNA/RNA # noqa: E114, E116 + # fmt: on + if coordinates[1, 0] > coordinates[1, -1]: + # DNA/RNA mapped to reverse strand of DNA/RNA + strand = "-" + query = reverse_complement(query) + coordinates = coordinates.copy() + coordinates[1, :] = qSize - coordinates[1, :] + elif coordinates[0, 0] > coordinates[0, -1]: + # protein mapped to reverse strand of DNA + strand = "-" + target = reverse_complement(target) + coordinates = coordinates.copy() + coordinates[0, :] = tSize - coordinates[0, :] + dnax = True + else: + # mapped to forward strand + strand = "+" + wildcard = self.wildcard + mask = self.mask + # variable names follow those in the PSL file format specification + matches = 0 + misMatches = 0 + repMatches = 0 + nCount = 0 + blockSizes = [] + qStarts = [] + tStarts = [] + tStart, qStart = coordinates[:, 0] + for tEnd, qEnd in coordinates[:, 1:].transpose(): + if tStart == tEnd: + qStart = qEnd + elif qStart == qEnd: + tStart = tEnd + else: + tCount = tEnd - tStart + qCount = qEnd - qStart + tStarts.append(tStart) + qStarts.append(qStart) + blockSizes.append(qCount) + if tCount == qCount: + assert dnax is not True + dnax = False + else: + # translated DNA aligned to protein, typically generated by + # blat -t=dnax -q=prot + assert tCount == 3 * qCount + assert dnax is not False + dnax = True + tSeq = target[tStart:tEnd] + qSeq = query[qStart:qEnd] + try: + tSeq = bytes(tSeq) + except TypeError: # string + tSeq = bytes(tSeq, "ASCII") + except UndefinedSequenceError: # sequence contents is unknown + tSeq = None + try: + qSeq = bytes(qSeq) + except TypeError: # string + qSeq = bytes(qSeq, "ASCII") + except UndefinedSequenceError: # sequence contents is unknown + qSeq = None + if tSeq is None or qSeq is None: + # contents of at least one sequence is unknown; + # count all aligned letters as matches: + matches += qCount + else: + if mask == "lower": + for u1, u2, c1 in zip(tSeq.upper(), qSeq.upper(), tSeq): + if u1 == wildcard or u2 == wildcard: + nCount += 1 + elif u1 == u2: + if u1 == c1: + matches += 1 + else: + repMatches += 1 + else: + misMatches += 1 + elif mask == "upper": + for u1, u2, c1 in zip(tSeq.lower(), qSeq.lower(), tSeq): + if u1 == wildcard or u2 == wildcard: + nCount += 1 + elif u1 == u2: + if u1 == c1: + matches += 1 + else: + repMatches += 1 + else: + misMatches += 1 + else: + for u1, u2 in zip(tSeq.upper(), qSeq.upper()): + if u1 == wildcard or u2 == wildcard: + nCount += 1 + elif u1 == u2: + matches += 1 + else: + misMatches += 1 + tStart = tEnd + qStart = qEnd + tStarts = np.array(tStarts) + qStarts = np.array(qStarts) + blockSizes = np.array(blockSizes) + try: + matches = alignment.matches + except AttributeError: + pass + try: + misMatches = alignment.misMatches + except AttributeError: + pass + try: + repMatches = alignment.repMatches + except AttributeError: + pass + try: + nCount = alignment.nCount + except AttributeError: + pass + qStart = qStarts[0] # start of alignment in query + qEnd = qStarts[-1] + qCount # end of alignment in query + oStrand = "+" + if strand == "-": + if dnax is True: + oStrand = "-" + qStarts = qSize - (qStarts + blockSizes) + qStarts = qStarts[::-1] + alignment.coordinates = alignment.coordinates[:, ::-1] + else: + qStart, qEnd = qSize - qEnd, qSize - qStart + if fa is True: + oSequence = str(alignment.query.seq) + else: + oSequence = "" + if cds is True: + for feature in alignment.query.features: + if feature.type == "CDS": + oCDS = _insdc_location_string( + feature.location, len(alignment.query) + ) + break + else: + oCDS = "n/a" + else: + oCDS = "" + seqType = 0 + molecule_type = alignment.query.annotations.get("molecule_type") + if molecule_type == "DNA": + seqType = "1" + elif molecule_type == "protein": + seqType = "2" + else: + seqType = "0" + alignment.annotations["oChromStart"] = str(qStart) + alignment.annotations["oChromEnd"] = str(qEnd) + alignment.annotations["oStrand"] = oStrand + alignment.annotations["oChromSize"] = str(qSize) + alignment.annotations["oChromStarts"] = ",".join(map(str, qStarts)) + alignment.annotations["oSequence"] = oSequence + alignment.annotations["oCDS"] = oCDS + alignment.annotations["chromSize"] = str(tSize) + alignment.annotations["match"] = str(matches) + alignment.annotations["misMatch"] = str(misMatches) + alignment.annotations["repMatch"] = str(repMatches) + alignment.annotations["nCount"] = str(nCount) + alignment.annotations["seqType"] = seqType + fixed_alignments.append(alignment) + fixed_alignments.sort( + key=lambda alignment: (alignment.target.id, alignment.coordinates[0, 0]) + ) + fixed_alignments.targets = alignments.targets + bigbed.AlignmentWriter( + stream, bedN=12, declaration=declaration, compress=self.compress + ).write(fixed_alignments) + + +class AlignmentIterator(bigbed.AlignmentIterator): + """Alignment iterator for bigPsl files. + + The pairwise alignments stored in the bigPsl file are loaded and returned + incrementally. Additional alignment information is stored as attributes + of each alignment. + """ + + fmt = "bigPsl" + + def _analyze_fields(self, fields, fieldCount, definedFieldCount): + names = ( + "chrom", + "chromStart", + "chromEnd", + "name", # 0 + "score", # 1 + "strand", # 2 + "thickStart", # 3 + "thickEnd", # 4 + "reserved", # 5 + "blockCount", # 6 + "blockSizes", # 7 + "chromStarts", # 8 + "oChromStart", # 9 + "oChromEnd", # 10 + "oStrand", # 11 + "oChromSize", # 12 + "oChromStarts", # 13 + "oSequence", # 14 + "oCDS", # 15 + "chromSize", # 16 + "match", # 17 + "misMatch", # 18 + "repMatch", # 19 + "nCount", # 20 + "seqType", # 21 + ) + for i, name in enumerate(names): + if name != fields[i].name: + raise ValueError( + "Expected field name '%s'; found '%s'" % (name, fields[i].name) + ) + + def _create_alignment(self, chromId, tStart, tEnd, rest, dataStart, dataEnd): + assert rest[dataEnd - 1] == 0 + words = rest[dataStart : dataEnd - 1].decode().split("\t") + if len(words) != 22: + raise ValueError( + "Unexpected number of fields (%d, expected 22)" % len(words) + ) + target_record = self.targets[chromId] + tSize = int(words[16]) + if len(target_record) != tSize: + raise ValueError( + "Unexpected chromosome size %d (expected %d)" + % (tSize, len(target_record)) + ) + strand = words[2] + qName = words[0] + qSize = int(words[12]) + blockCount = int(words[6]) + blockSizes = [int(blockSize) for blockSize in words[7].rstrip(",").split(",")] + tStarts = [int(start) for start in words[8].rstrip(",").split(",")] + qStarts = [int(start) for start in words[13].rstrip(",").split(",")] + if len(blockSizes) != blockCount: + raise ValueError( + "Inconsistent number of blocks (%d found, expected %d)" + % (len(blockSizes), blockCount) + ) + if len(qStarts) != blockCount: + raise ValueError( + "Inconsistent number of query start positions (%d found, expected %d)" + % (len(qStarts), blockCount) + ) + if len(tStarts) != blockCount: + raise ValueError( + "Inconsistent number of target start positions (%d found, expected %d)" + % (len(qStarts), blockCount) + ) + qStarts = np.array(qStarts) + tStarts = np.array(tStarts) + tBlockSizes = np.array(blockSizes) + query_sequence = words[14] + if query_sequence == "": + query_sequence = Seq(None, length=qSize) + else: + query_sequence = Seq(query_sequence) + if len(query_sequence) != qSize: + raise ValueError( + "Inconsistent query sequence length (%d, expected %d)" + % (len(query_sequence), qSize) + ) + query_record = SeqRecord(query_sequence, id=qName) + cds = words[15] + if cds and cds != "n/a": + location = Location.fromstring(cds) + feature = SeqFeature(location, type="CDS") + query_record.features.append(feature) + seqType = words[21] + if seqType == "0": + qBlockSizes = tBlockSizes + elif seqType == "1": + query_record.annotations["molecule_type"] = "DNA" + qBlockSizes = tBlockSizes + elif seqType == "2": + query_record.annotations["molecule_type"] = "protein" + qBlockSizes = tBlockSizes // 3 + else: + raise ValueError("Unexpected sequence type '%s'" % seqType) + tStarts += tStart + qStrand = words[11] + if qStrand == "-" and strand == "-": + tStart, tEnd = tEnd, tStart + qStarts = qSize - qStarts - qBlockSizes + tStarts = tSize - tStarts - tBlockSizes + qStarts = qStarts[::-1] + tStarts = tStarts[::-1] + qBlockSizes = qBlockSizes[::-1] + tBlockSizes = tBlockSizes[::-1] + qPosition = qStarts[0] + tPosition = tStarts[0] + coordinates = [[tPosition, qPosition]] + for tB, qB, tS, qS in zip(tBlockSizes, qBlockSizes, tStarts, qStarts): + if tS != tPosition: + coordinates.append([tS, qPosition]) + tPosition = tS + if qS != qPosition: + coordinates.append([tPosition, qS]) + qPosition = qS + tPosition += tB + qPosition += qB + coordinates.append([tPosition, qPosition]) + coordinates = np.array(coordinates, np.intp).transpose() + qStart = int(words[9]) + qEnd = int(words[10]) + if strand == "-": + if qStrand == "-": + coordinates[0, :] = tSize - coordinates[0, :] + else: + qStart, qEnd = qEnd, qStart + coordinates[1, :] = qSize - coordinates[1, :] + if tStart != coordinates[0, 0]: + raise ValueError( + "Inconsistent tStart found (%d, expected %d)" + % (tStart, coordinates[0, 0]) + ) + if tEnd != coordinates[0, -1]: + raise ValueError( + "Inconsistent tEnd found (%d, expected %d)" % (tEnd, coordinates[0, -1]) + ) + if qStart != coordinates[1, 0]: + raise ValueError( + "Inconsistent qStart found (%d, expected %d)" + % (qStart, coordinates[1, 0]) + ) + if qEnd != coordinates[1, -1]: + raise ValueError( + "Inconsistent qEnd found (%d, expected %d)" % (qEnd, coordinates[1, -1]) + ) + records = [target_record, query_record] + alignment = Alignment(records, coordinates) + alignment.annotations = {} + score = words[1] + try: + score = float(score) + except ValueError: + pass + else: + if score.is_integer(): + score = int(score) + alignment.score = score + alignment.thickStart = int(words[3]) + alignment.thickEnd = int(words[4]) + alignment.itemRgb = words[5] + alignment.matches = int(words[17]) + alignment.misMatches = int(words[18]) + alignment.repMatches = int(words[19]) + alignment.nCount = int(words[20]) + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/chain.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/chain.py new file mode 100644 index 0000000000000000000000000000000000000000..799fa072a6a9d787f1ec4358c816579218293f5c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/chain.py @@ -0,0 +1,267 @@ +# Copyright 2023 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for the "chain" pairwise alignment format. + +As described by UCSC, a chain file stores a series of pairwise alignments in a +single file. Typically they are used for genome to genome alignments. Chain +files store the lengths of the aligned segments, alignment gaps, and alignment +scores, but do not store the aligned sequences. + +See https://genome.ucsc.edu/goldenPath/help/chain.html. + +You are expected to use this module via the Bio.Align functions. + +Coordinates in the chain file format are defined in terms of zero-based start +positions (like Python) and aligning region sizes. +""" + +import numpy as np + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Alignment file writer for the UCSC chain file format.""" + + fmt = "chain" + + def format_alignment(self, alignment): + """Return a string with one alignment formatted as a chain block.""" + if not isinstance(alignment, Alignment): + raise TypeError("Expected an Alignment object") + coordinates = alignment.coordinates + if not coordinates.size: # alignment consists of gaps only + return "" + target, query = alignment.sequences + try: + qName = query.id + except AttributeError: + qName = "query" + try: + query = query.seq + except AttributeError: + pass + try: + tName = target.id + except AttributeError: + tName = "target" + try: + target = target.seq + except AttributeError: + pass + tSize = len(target) + qSize = len(query) + lines = [] + try: + score = alignment.score + except AttributeError: + score = 0 + if coordinates[0, 0] > coordinates[0, -1]: + tStrand = "-" + coordinates = coordinates.copy() + coordinates[0, :] = tSize - coordinates[0, :] + else: + tStrand = "+" + if coordinates[1, 0] > coordinates[1, -1]: + qStrand = "-" + coordinates = coordinates.copy() + coordinates[1, :] = qSize - coordinates[1, :] + else: + qStrand = "+" + tStart = coordinates[0, 0] + tEnd = coordinates[0, -1] + qStart = coordinates[1, 0] + qEnd = coordinates[1, -1] + try: + chainID = alignment.annotations["id"] + except (AttributeError, KeyError): + line = f"chain {score:g} {tName} {tSize} {tStrand} {tStart} {tEnd} {qName} {qSize} {qStrand} {qStart} {qEnd}" + else: + line = f"chain {score:g} {tName} {tSize} {tStrand} {tStart} {tEnd} {qName} {qSize} {qStrand} {qStart} {qEnd} {chainID}" + lines.append(line) + # variable names follow those in the UCSC chain file format description + tStart, qStart = coordinates[:, 0] + step = 0 + qGap = 0 + tGap = 0 + for tEnd, qEnd in coordinates[:, 1:].transpose(): + if tStart == tEnd: + if tGap > 0: + qGap = qEnd - qStart + line = f"{step}\t{tGap}\t{qGap}" + lines.append(line) + step = 0 + tGap = 0 + qGap = 0 + elif qGap > 0: + line = f"{step}\t{tGap}\t{qGap}" + lines.append(line) + step = 0 + qGap = qEnd - qStart + else: + qGap = qEnd - qStart + qStart = qEnd + elif qStart == qEnd: + if qGap > 0: + tGap = tEnd - tStart + line = f"{step}\t{tGap}\t{qGap}" + lines.append(line) + step = 0 + tGap = 0 + qGap = 0 + elif tGap > 0: + line = f"{step}\t{tGap}\t{qGap}" + lines.append(line) + step = 0 + tGap = tEnd - tStart + else: + tGap = tEnd - tStart + tStart = tEnd + else: + if step == 0: + tStep = tEnd - tStart + qStep = qEnd - qStart + if tGap == 0 and qGap == 0: + step = tStep + else: + line = f"{tStep}\t{tGap}\t{qGap}" + lines.append(line) + tGap = 0 + qGap = 0 + else: + line = f"{step}\t{tGap}\t{qGap}" + lines.append(line) + tStep = tEnd - tStart + qStep = qEnd - qStart + step = tStep + tGap = 0 + qGap = 0 + if tStep != qStep: + raise ValueError( + f"Expected equal step size in target and query (found {tStep} and {qStep})" + ) + tStart = tEnd + qStart = qEnd + if tGap > 0 or qGap > 0: + line = f"0\t{tGap}\t{qGap}" + lines.append(line) + line = f"{step}" + lines.append(line) + line = "" + lines.append(line) + block = "\n".join(lines) + "\n" + return block + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Alignment iterator for UCSC chain files. + + Each chain block in the file contains one pairwise alignment, which are + loaded and returned incrementally. The alignment score is scored as an + attribute of the alignment; the ID is stored under the key "id" in the + dictionary referred to by the annotations attribute of the alignment. + """ + + fmt = "chain" + + def _read_header(self, stream): + self._line = "" + for line in stream: + if not line.startswith("#"): + self._line = line + break + + def _read_next_alignment(self, stream): + if not self._line: + return + line = self._line + self._line = "" + words = line.split() + if len(words) == 12: + chainID = None + elif len(words) == 13: + chainID = words[12] + else: + raise ValueError( + "expected line with 12 or 13 columns at the beginning of a chain block" + ) + if words[0] != "chain": + raise ValueError( + "expected first line of chain block to start with 'chain '" + ) + score = float(words[1]) + tName = words[2] + tSize = int(words[3]) + tStrand = words[4] + tStart = int(words[5]) + tEnd = int(words[6]) + qName = words[7] + qSize = int(words[8]) + qStrand = words[9] + qStart = int(words[10]) + qEnd = int(words[11]) + qPosition = 0 + tPosition = 0 + qStarts = [qPosition] + tStarts = [tPosition] + for line in stream: + words = line.split() + if words[0] == "chain": + self._line = line + break + step = int(words[0]) + qPosition += step + tPosition += step + qStarts.append(qPosition) + tStarts.append(tPosition) + if len(words) == 1: + break + tGap = int(words[1]) + qGap = int(words[2]) + if tGap > 0: + tPosition += tGap + qStarts.append(qPosition) + tStarts.append(tPosition) + if qGap > 0: + qPosition += qGap + qStarts.append(qPosition) + tStarts.append(tPosition) + target_sequence = Seq(None, length=tSize) + query_sequence = Seq(None, length=qSize) + target_record = SeqRecord(target_sequence, id=tName, description="") + query_record = SeqRecord(query_sequence, id=qName, description="") + records = [target_record, query_record] + coordinates = np.array([tStarts, qStarts], np.intp) + coordinates[0, :] += tStart + coordinates[1, :] += qStart + if tStrand == "+": + pass + elif tStrand == "-": + coordinates[0, :] = tSize - coordinates[0, :] + else: + raise ValueError(f"tStrand should be '+' or '-' (found '{tStrand}')") + if qStrand == "+": + pass + elif qStrand == "-": + coordinates[1, :] = qSize - coordinates[1, :] + else: + raise ValueError(f"qStrand should be '+' or '-' (found '{qStrand}')") + alignment = Alignment(records, coordinates) + alignment.score = score + if chainID is not None: + alignment.annotations = {"id": chainID} + # There is supposed to be a blank line between chain blocks, but some + # tools (e.g. pslToChain) do not include such a blank line in their + # output. + line = stream.readline() + if not line.strip(): + line = stream.readline() + self._line = line + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/clustal.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/clustal.py new file mode 100644 index 0000000000000000000000000000000000000000..82e97d71b5c676e609351f7002dc01a88f526825 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/clustal.py @@ -0,0 +1,250 @@ +# Copyright 2006-2016 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for "clustal" output from CLUSTAL W and other tools. + +You are expected to use this module via the Bio.Align functions (or the +Bio.SeqIO functions if you are interested in the sequences only). +""" + +import Bio +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Clustalw alignment writer.""" + + fmt = "Clustal" + + def write_header(self, stream, alignments): + """Use this to write the file header.""" + try: + metadata = alignments.metadata + program = metadata["Program"] + except (AttributeError, KeyError): + program = "Biopython" + version = Bio.__version__ + else: + version = metadata.get("Version", "") + line = f"{program} {version} multiple sequence alignment\n" + stream.write(line) + stream.write("\n") + stream.write("\n") + + def format_alignment(self, alignment): + """Return a string with a single alignment in the Clustal format.""" + nseqs, length = alignment.shape + if nseqs == 0: + raise ValueError("Must have at least one sequence") + if length == 0: + raise ValueError("Non-empty sequences are required") + + try: + column_annotations = alignment.column_annotations + except AttributeError: + consensus = None + else: + consensus = column_annotations.get("clustal_consensus") + + gapped_sequences = list(alignment) + names = [] + for i, sequence in enumerate(alignment.sequences): + try: + name = sequence.id + except AttributeError: + name = "sequence_%d" % i # Clustal format doesn't allow an empty string + else: + # when we output, we do a nice 80 column output, although + # this may result in truncation of the ids. Also, make sure + # we don't get any spaces in the record identifier when output + # in the file by replacing them with underscores. + name = name[:30].replace(" ", "_") + name = name.ljust(36) + names.append(name) + + lines = [] + start = 0 + while start != length: + # calculate the number of letters to show, which will + # be less if we are at the end of the alignment. + stop = start + 50 + if stop > length: + stop = length + + for name, gapped_sequence in zip(names, gapped_sequences): + line = f"{name}{gapped_sequence[start:stop]}\n" + lines.append(line) + + # now we need to print out the star info, if we've got it + if consensus is not None: + line = " " * 36 + consensus[start:stop] + "\n" + lines.append(line) + + lines.append("\n") + start = stop + lines.append("\n") + return "".join(lines) + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Clustalw alignment iterator.""" + + fmt = "Clustal" + + def _read_header(self, stream): + line = stream.readline() + if not line: + raise ValueError("Empty file.") + + self.metadata = {} + # Whitelisted programs we know about + words = line.split() + known_programs = [ + "CLUSTAL", + "PROBCONS", + "MUSCLE", + "MSAPROBS", + "Kalign", + "Biopython", + ] + program = words[0] + if program not in known_programs: + raise ValueError( + "%s is not known to generate CLUSTAL files: %s" + % (program, ", ".join(known_programs)) + ) + self.metadata["Program"] = program + + # find the clustal version in the header line + for word in words: + if word[0] == "(" and word[-1] == ")": + word = word[1:-1] + if word[0].isdigit(): + self.metadata["Version"] = word + break + + def _read_next_alignment(self, stream): + # If the alignment contains entries with the same sequence + # identifier (not a good idea - but seems possible), then this + # dictionary based parser will merge their sequences. Fix this? + ids = [] + aligned_seqs = [] + consensus = "" + index = None # Used to extract the consensus + + # Use the first block to get the sequence identifiers + for line in stream: + if line.startswith(" "): + # Sequence consensus line... + assert len(ids) > 0 + assert index is not None + length = len(aligned_seq) # noqa: F821 + consensus = line[index : index + length] + break + elif line.strip(): + # Sequences identifier... + fields = line.split() + + # We expect there to be two fields, there can be an optional + # "sequence number" field containing the letter count. + if len(fields) < 2 or len(fields) > 3: + raise ValueError("Could not parse line:\n%s" % line) + + seqid, aligned_seq = fields[:2] + ids.append(seqid) + aligned_seqs.append(aligned_seq) + + # Record the sequence position to get the consensus + if index is None: + index = line.find(aligned_seq, len(seqid)) + + if len(fields) == 3: + # This MAY be an old style file with a letter count... + try: + count = int(fields[2]) + except ValueError: + raise ValueError( + "Could not parse line, bad sequence count:\n%s" % line + ) from None + if len(aligned_seq) - aligned_seq.count("-") != count: + raise ValueError( + "Could not parse line, incorrect sequence count:\n%s" % line + ) from None + else: + # no consensus line + if index: + break + else: + return + + assert index is not None + + # Confirm all same length + length = len(aligned_seqs[0]) + for aligned_seq in aligned_seqs: + assert len(aligned_seq) == length + if consensus: + assert len(consensus) == length + + n = len(aligned_seqs) + i = 0 + # Loop over any remaining blocks... + for line in stream: + if line.startswith(" "): # Sequence consensus line + assert index is not None + length = len(aligned_seq) + consensus += line[index : index + length] + elif not line.strip(): # Blank line + continue + else: + seqid = ids[i] + # Sequences identifier... + fields = line.split() + + # We expect there to be two fields, there can be an optional + # "sequence number" field containing the letter count. + if len(fields) < 2 or len(fields) > 3: + raise ValueError("Could not parse line:\n%s" % line) + + assert seqid == fields[0] + aligned_seq = fields[1] + aligned_seqs[i] += aligned_seq + + if len(fields) == 3: + # This MAY be an old style file with a letter count... + try: + count = int(fields[2]) + except ValueError: + raise ValueError( + "Could not parse line, bad sequence number:\n%s" % line + ) from None + if len(aligned_seqs[i]) - aligned_seqs[i].count("-") != count: + raise ValueError( + "Could not parse line, incorrect sequence count:\n%s" % line + ) from None + i += 1 + if i == n: + i = 0 + aligned_seqs = [s.encode() for s in aligned_seqs] + seqs, coordinates = Alignment.parse_printed_alignment(aligned_seqs) + records = [ + SeqRecord(Seq(seq), id=seqid, description="") + for (seqid, seq) in zip(ids, seqs) + ] + alignment = Alignment(records, coordinates) + if consensus: + columns = alignment.length + if len(consensus) != columns: + raise ValueError( + "Alignment has %i columns, consensus length is %i, '%s'" + % (columns, len(consensus), consensus) + ) + alignment.column_annotations = {} + alignment.column_annotations["clustal_consensus"] = consensus + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/emboss.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/emboss.py new file mode 100644 index 0000000000000000000000000000000000000000..97a7366b2acc715909c4a9bf7a503471e4332d74 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/emboss.py @@ -0,0 +1,246 @@ +# Copyright 2008-2016 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for "emboss" alignment output from EMBOSS tools. + +This module contains a parser for the EMBOSS srspair/pair/simple file format, +for example from the needle, water, and stretcher tools. +""" + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Emboss alignment iterator. + + For reading the (pairwise) alignments from EMBOSS tools in what they + call the "pairs" and "simple" formats. + """ + + fmt = "EMBOSS" + + def _read_header(self, stream): + line = stream.readline() + if not line: + raise ValueError("Empty file.") + if line.rstrip() != "########################################": + raise ValueError("Unexpected line: %s") % line + + # assume srspair format (default) if not specified explicitly in + # the output file + self.metadata = {} + self.metadata["Align_format"] = "srspair" + commandline = None + for line in stream: + if line.rstrip() == "########################################": + break + if not line.startswith("# "): + raise ValueError("Unexpected line: %s") % line + if commandline is not None: + if line.startswith("# "): + commandline += " " + line[1:].strip() + continue + self.metadata["Command line"] = commandline + commandline = None + key, value = line[2:].split(":", 1) + if key == "Program": + self.metadata["Program"] = value.strip() + elif key == "Rundate": + self.metadata["Rundate"] = value.strip() + elif key == "Report_file": + self.metadata["Report_file"] = value.strip() + elif key == "Align_format": + self.metadata["Align_format"] = value.strip() + elif key == "Commandline": + commandline = value.strip() + + def _read_next_alignment(self, stream): + number_of_sequences = None + annotations = {} + for line in stream: + line = line.rstrip("\r\n") + if not line: + continue + elif line.startswith("#---------------------------------------"): + # may appear between alignments + continue + elif line.startswith("#======================================="): + # found the alignment metadata start + identifiers = [] + ncols = None + sequences = None + break + else: + raise ValueError("Unexpected line: %s" % line) + for line in stream: + line = line.rstrip("\r\n") + if line == "#=======================================": + # reached the end of alignment metadata + break + elif line.strip() == "#": + continue + elif not line.startswith("# "): + raise ValueError("Unexpected line: %s") % line + try: + key, value = line[2:].split(":", 1) + except ValueError: + # An equal sign is used for Longest_Identity, + # Longest_Similarity, Shortest_Identity, and + # Shortest_Similarity, which are included if command line + # argument -nobrief was used. + key, value = line[2:].split(" = ", 1) + if key == "Aligned_sequences": + number_of_sequences = int(value.strip()) + assert len(identifiers) == 0 + # Should now expect the record identifiers... + for i, line in enumerate(stream): + if not line.startswith("# "): + raise ValueError("Unexpected line: %s") % line + number, identifier = line[2:].split(":") + assert i + 1 == int(number) + identifiers.append(identifier.strip()) + if len(identifiers) == number_of_sequences: + break + elif key == "Matrix": + annotations[key] = value.strip() + elif key == "Gap_penalty": + annotations[key] = float(value.strip()) + elif key == "Extend_penalty": + annotations[key] = float(value.strip()) + elif key == "Length": + ncols = int(value.strip()) + elif key == "Identity": + annotations[key] = int(value.strip().split("/")[0]) + elif key == "Similarity": + annotations[key] = int(value.strip().split("/")[0]) + elif key == "Gaps": + annotations[key] = int(value.strip().split("/")[0]) + elif key == "Score": + annotations[key] = float(value.strip()) + # TODO: + # The following are generated if the -nobrief command line + # argument used. We could simply calculate them from the + # alignment, but then we have to define what we mean by + # "similar". For now, simply store them as an annotation. + elif key == "Longest_Identity": + annotations[key] = value.strip() + elif key == "Longest_Similarity": + annotations[key] = value.strip() + elif key == "Shortest_Identity": + annotations[key] = value.strip() + elif key == "Shortest_Similarity": + annotations[key] = value.strip() + else: + raise ValueError("Failed to parse line '%s'" % line) + else: + return + if len(identifiers) == 0: + raise ValueError("Number of sequences missing!") + if ncols is None: + raise ValueError("Length of alignment missing!") + sequences = [""] * number_of_sequences + aligned_sequences = [""] * number_of_sequences + consensus = "" + starts = [0] * number_of_sequences + ends = [0] * number_of_sequences + column = 0 + index = 0 + for line in stream: + line = line.rstrip("\r\n") + # parse the sequences + if not line: + # empty line + if index == number_of_sequences: + # reached the end of an alignment block + if column == ncols: + # reached the end of the sequences + break + index = 0 + continue + prefix = line[:21].strip() + if prefix == "": + # match line + consensus += line[21:71] + else: + identifier, start = prefix.split(None, 1) + assert identifiers[index].startswith(identifier) + aligned_sequence, end = line[21:].split(None, 1) + start = int(start) + end = int(end) + length = len(sequences[index]) + sequence = aligned_sequence.replace("-", "") + if length == 0 and len(sequence) > 0: + if start < end: + start -= 1 # Python counting + assert end == start + len(sequence) + else: + end -= 1 # Python counting + assert end == start - len(sequence) + # Record the start + starts[index] = start + else: + if starts[index] <= ends[index]: + # forward strand + if ( + self.metadata["Align_format"] == "srspair" + and len(sequence) == 0 + ): + assert start == ends[index] + assert end == start + else: + start -= 1 + assert end == start + len(sequence) + else: + if ( + self.metadata["Align_format"] == "srspair" + and len(sequence) == 0 + ): + assert start - 1 == ends[index] + assert end == start + else: + end -= 1 + assert end == start - len(sequence) + # Record the end + ends[index] = end + sequences[index] += sequence + aligned_sequences[index] += aligned_sequence + if index == 0: + column += len(aligned_sequence) + else: + assert column == len(aligned_sequences[index]) + index += 1 + aligned_sequences = [ + aligned_sequence.encode() for aligned_sequence in aligned_sequences + ] + sequences, coordinates = Alignment.parse_printed_alignment(aligned_sequences) + records = [] + n = len(sequences) + for i in range(n): + start = starts[i] + end = ends[i] + data = sequences[i] + if start == 0: + sequence = Seq(data) + elif start < end: + coordinates[i, :] += start + # create a partially defined sequence + sequence = Seq({start: data}, length=end) + else: + start, end = end, start + coordinates[i, :] = end - coordinates[i, :] + # create a partially defined sequence + sequence = Seq({0: data}, length=end).reverse_complement() + record = SeqRecord(sequence, identifiers[i]) + records.append(record) + alignment = Alignment(records, coordinates) + if annotations: + alignment.annotations = annotations + if consensus: + alignment.column_annotations = {"emboss_consensus": consensus} + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/exonerate.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/exonerate.py new file mode 100644 index 0000000000000000000000000000000000000000..1df037d9f51df710f07e73c5902fd1bd19c6c84b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/exonerate.py @@ -0,0 +1,655 @@ +# Copyright 2022 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for Exonerate output format. + +This module provides support for Exonerate outputs. Exonerate is a generic +tool for pairwise sequence comparison that allows you to align sequences using +several different models. + +Bio.Align.exonerate was tested on the following Exonerate versions and models: + + - version: 2.2 + - models: + - affine:local - cdna2genome + - coding2coding - est2genome + - genome2genome - ner + - protein2dna - protein2genome + - ungapped - ungapped:translated + +Although model testing were not exhaustive, the parser should be able to cope +with all Exonerate models. Please file a bug report if you stumble upon an +unparsable file. + +You are expected to use this module via the Bio.Align functions. +""" + +import numpy as np + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Alignment file writer for the Exonerate cigar and vulgar file format.""" + + fmt = "Exonerate" + + def __init__(self, target, fmt="vulgar"): + """Create an AlignmentWriter object. + + Arguments: + - target - output stream or file name + - fmt - write alignments in the vulgar (Verbose Useful Labelled + Gapped Alignment Report) format (fmt="vulgar") or in + the cigar (Compact Idiosyncratic Gapped Alignment Report) + format (fmt="cigar"). + Default value is 'vulgar'. + + """ + super().__init__(target) + if fmt == "vulgar": + self.format_alignment = self._format_alignment_vulgar + elif fmt == "cigar": + self.format_alignment = self._format_alignment_cigar + else: + raise ValueError( + "argument fmt should be 'vulgar' or 'cigar' (received %s)" % fmt + ) + + def write_header(self, stream, alignments): + """Write the header.""" + try: + metadata = alignments.metadata + except AttributeError: + commandline = "" + hostname = "" + else: + commandline = metadata.get("Command line", "") + hostname = metadata.get("Hostname", "") + stream.write(f"Command line: [{commandline}]\n") + stream.write(f"Hostname: [{hostname}]\n") + + def write_footer(self, stream): + """Write the footer.""" + stream.write("-- completed exonerate analysis\n") + + def _format_alignment_cigar(self, alignment): + """Return a string with a single alignment formatted as a cigar line.""" + if not isinstance(alignment, Alignment): + raise TypeError("Expected an Alignment object") + coordinates = alignment.coordinates + target_start = coordinates[0, 0] + target_end = coordinates[0, -1] + query_start = coordinates[1, 0] + query_end = coordinates[1, -1] + steps = np.diff(coordinates) + query = alignment.query + target = alignment.target + try: + query_id = query.id + except AttributeError: + query_id = "query" + try: + target_id = target.id + except AttributeError: + target_id = "target" + try: + target_molecule_type = target.annotations["molecule_type"] + except (AttributeError, KeyError): + target_molecule_type = None + if target_molecule_type == "protein": + target_strand = "." + elif target_start <= target_end: + target_strand = "+" + elif target_start > target_end: + target_strand = "-" + steps[0, :] = -steps[0, :] + try: + query_molecule_type = query.annotations["molecule_type"] + except (AttributeError, KeyError): + query_molecule_type = None + if query_molecule_type == "protein": + query_strand = "." + elif query_start <= query_end: + query_strand = "+" + elif query_start > query_end: + query_strand = "-" + steps[1, :] = -steps[1, :] + score = format(alignment.score, "g") + words = [ + "cigar:", + query_id, + str(query_start), + str(query_end), + query_strand, + target_id, + str(target_start), + str(target_end), + target_strand, + score, + ] + try: + operations = alignment.operations + except AttributeError: + for step in steps.transpose(): + target_step, query_step = step + if target_step == query_step: + operation = "M" + step = target_step + elif query_step == 0: + operation = "D" # Deletion + step = target_step + elif target_step == 0: + operation = "I" # Insertion + step = query_step + elif ( + target_molecule_type != "protein" + and query_molecule_type == "protein" + ): + operation = "M" + step = target_step + elif ( + target_molecule_type == "protein" + and query_molecule_type != "protein" + ): + operation = "M" + step = query_step + else: + raise ValueError( + "Unexpected step target %d, query %d for molecule type %s, %s" + % ( + target_step, + query_step, + target_molecule_type, + query_molecule_type, + ) + ) + words.append(operation) + words.append(str(step)) + else: + for step, operation in zip(steps.transpose(), operations.decode()): + target_step, query_step = step + if operation == "M": + if target_step == query_step: + step = target_step + elif target_step == 3 * query_step: + step = target_step + assert query_molecule_type == "protein" + assert target_molecule_type != "protein" + elif query_step == 3 * target_step: + step = query_step + assert query_molecule_type != "protein" + assert target_molecule_type == "protein" + else: + raise ValueError( + "Unexpected steps target %d, query %s for operation 'M'" + ) + elif operation == "5": # 5' splice site + if query_step == 0: + step = target_step + operation = "D" + elif target_step == 0: + step = query_step + operation = "I" + else: + assert query_step == target_step + step = target_step + operation = "M" + elif operation == "N": # Intron + if query_step == 0: + step = target_step + operation = "D" + elif target_step == 0: + step = query_step + operation = "I" + else: + raise ValueError( + "Unexpected intron with steps target %d, query %d" + % (target_step, query_step) + ) + elif operation == "3": # 3' splice site + if query_step == 0: + step = target_step + operation = "D" + elif target_step == 0: + step = query_step + operation = "I" + else: + assert query_step == target_step + step = target_step + operation = "M" + elif operation == "C": # Codon + assert target_step == query_step + step = target_step + operation = "M" + elif operation == "D": # Deletion + assert query_step == 0 + step = target_step + operation = "D" + elif operation == "I": # Insertion + assert target_step == 0 + step = query_step + elif operation == "U": # Non-equivalenced (unaligned) region + if target_step > 0: + operation = "D" + words.append(operation) + words.append(str(target_step)) + if query_step > 0: + operation = "I" + words.append(operation) + words.append(str(query_step)) + continue + elif operation == "S": # Split codon + if target_step > 0: + operation = "D" + words.append(operation) + words.append(str(target_step)) + if query_step > 0: + operation = "I" + words.append(operation) + words.append(str(query_step)) + continue + elif operation == "F": # Frame shift + if target_step == 0: + step = query_step + operation = "I" + elif query_step == 0: + step = target_step + operation = "D" + else: + raise ValueError("Expected target step or query step to be 0") + else: + raise ValueError("Unknown operation %s" % operation) + words.append(operation) + words.append(str(step)) + line = " ".join(words) + "\n" + return line + + def _format_alignment_vulgar(self, alignment): + """Return a string with a single alignment formatted as one vulgar line.""" + if not isinstance(alignment, Alignment): + raise TypeError("Expected an Alignment object") + coordinates = alignment.coordinates + target_start = coordinates[0, 0] + target_end = coordinates[0, -1] + query_start = coordinates[1, 0] + query_end = coordinates[1, -1] + steps = np.diff(coordinates) + query = alignment.query + target = alignment.target + try: + query_id = query.id + except AttributeError: + query_id = "query" + try: + target_id = target.id + except AttributeError: + target_id = "target" + try: + target_molecule_type = target.annotations["molecule_type"] + except (AttributeError, KeyError): + target_molecule_type = None + if target_molecule_type == "protein": + target_strand = "." + elif target_start <= target_end: + target_strand = "+" + elif target_start > target_end: + target_strand = "-" + steps[0, :] = -steps[0, :] + try: + query_molecule_type = query.annotations["molecule_type"] + except (AttributeError, KeyError): + query_molecule_type = None + if query_molecule_type == "protein": + query_strand = "." + elif query_start <= query_end: + query_strand = "+" + elif query_start > query_end: + query_strand = "-" + steps[1, :] = -steps[1, :] + score = format(alignment.score, "g") + words = [ + "vulgar:", + query_id, + str(query_start), + str(query_end), + query_strand, + target_id, + str(target_start), + str(target_end), + target_strand, + str(score), + ] + try: + operations = alignment.operations + except AttributeError: + for step in steps.transpose(): + target_step, query_step = step + if target_step == query_step: + operation = "M" + elif query_step == 0: + operation = "G" # Gap; exonerate definition + elif target_step == 0: + operation = "G" # Gap; exonerate definition + elif ( + query_molecule_type == "protein" + and target_molecule_type != "protein" + ): + operation = "M" + elif ( + query_molecule_type != "protein" + and target_molecule_type == "protein" + ): + operation = "M" + else: + raise ValueError("Both target and query step are zero") + words.append(operation) + words.append(str(query_step)) + words.append(str(target_step)) + else: + steps = steps.transpose() + operations = operations.decode() + n = len(operations) + i = 0 + while i < n: + target_step, query_step = steps[i] + operation = operations[i] + if operation == "M": + if target_step == query_step: + pass + elif target_step == 3 * query_step: + assert query_molecule_type == "protein" + assert target_molecule_type != "protein" + elif query_step == 3 * target_step: + assert query_molecule_type != "protein" + assert target_molecule_type == "protein" + else: + raise ValueError( + "Unexpected steps target %d, query %d for operation 'M'" + % (target_step, query_step) + ) + elif operation == "5": # 5' splice site + assert target_step == 2 or query_step == 2 + elif operation == "N": # Intron + operation = "I" # Intron; exonerate definition + assert query_step == 0 or target_step == 0 + elif operation == "3": # 3' splice site + assert target_step == 2 or query_step == 2 + elif operation == "C": # Codon + assert target_step == query_step + elif operation == "D": # Deletion + assert query_step == 0 + operation = "G" # Gap; exonerate definition + elif operation == "I": # Insertion + assert target_step == 0 + operation = "G" # Gap; exonerate definition + elif operation == "U": # Non-equivalenced (unaligned) region + if target_step == 0: + assert query_step > 0 + i += 1 + target_step, dummy = steps[i] + assert dummy == 0 + if query_step == 0: + assert target_step > 0 + i += 1 + dummy, query_step = steps[i] + assert dummy == 0 + operation = operations[i] + assert operation == "U" + operation = "N" # Non-equivalenced region; exonerate definition + elif operation == "S": # Split codon + step = target_step + elif operation == "F": # Frame shift + step = target_step + else: + raise ValueError("Unknown operation %s" % operation) + words.append(operation) + words.append(str(query_step)) + words.append(str(target_step)) + i += 1 + line = " ".join(words) + "\n" + return line + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Alignment iterator for the Exonerate text, cigar, and vulgar formats. + + Each line in the file contains one pairwise alignment, which are loaded + and returned incrementally. Alignment score information such as the number + of matches and mismatches are stored as attributes of each alignment. + """ + + fmt = "Exonerate" + + def _read_header(self, stream): + self.metadata = {} + self.metadata["Program"] = "exonerate" + line = stream.readline() + prefix = "Command line: " + assert line.startswith(prefix) + commandline = line[len(prefix) :].strip() + assert commandline.startswith("[") + assert commandline.endswith("]") + self.metadata["Command line"] = commandline[1:-1] + line = stream.readline() + prefix = "Hostname: " + assert line.startswith(prefix) + hostname = line[len(prefix) :].strip() + assert hostname.startswith("[") + assert hostname.endswith("]") + self.metadata["Hostname"] = hostname[1:-1] + + @staticmethod + def _parse_cigar(words): + query_id = words[0] + query_start = int(words[1]) + query_end = int(words[2]) + query_strand = words[3] + target_id = words[4] + target_start = int(words[5]) + target_end = int(words[6]) + target_strand = words[7] + score = float(words[8]) + qs = 0 + ts = 0 + n = (len(words) - 8) // 2 + coordinates = np.empty((2, n + 1), np.intp) + coordinates[0, 0] = ts + coordinates[1, 0] = qs + for i, (operation, step) in enumerate(zip(words[9::2], words[10::2])): + step = int(step) + if operation == "M": # match or mismatch + ts += step + qs += step + elif operation == "I": # insertion + if query_strand == "." and target_strand != ".": + qs += step * 3 + else: + qs += step + elif operation == "D": # deletion + if target_strand == "." and query_strand != ".": + ts += step * 3 + else: + ts += step + else: + raise ValueError("Unknown operation %s in cigar string" % operation) + coordinates[0, i + 1] = ts + coordinates[1, i + 1] = qs + if target_strand == "+": + coordinates[0, :] += target_start + target_length = target_end + target_molecule_type = None + elif target_strand == "-": + coordinates[0, :] = target_start - coordinates[0, :] + target_length = target_start + target_molecule_type = None + elif target_strand == ".": # protein + if query_strand != ".": + # dna to protein alignment; integer division, but round up: + coordinates[0, :] = (coordinates[0, :] + 2) // 3 + coordinates[0, :] += target_start + target_molecule_type = "protein" + target_length = target_end + if query_strand == "+": + coordinates[1, :] += query_start + query_length = query_end + query_molecule_type = None + elif query_strand == "-": + coordinates[1, :] = query_start - coordinates[1, :] + query_length = query_start + query_molecule_type = None + elif query_strand == ".": # protein + if target_strand != ".": + # protein to dna alignment; integer division, but round up: + coordinates[1, :] = -(coordinates[1, :] // -3) + coordinates[1, :] += query_start + query_molecule_type = "protein" + query_length = query_end + target_seq = Seq(None, length=target_length) + query_seq = Seq(None, length=query_length) + target = SeqRecord(target_seq, id=target_id, description="") + query = SeqRecord(query_seq, id=query_id, description="") + if target_molecule_type is not None: + target.annotations["molecule_type"] = target_molecule_type + if query_molecule_type is not None: + query.annotations["molecule_type"] = query_molecule_type + alignment = Alignment([target, query], coordinates) + alignment.score = score + return alignment + + @staticmethod + def _parse_vulgar(words): + query_id = words[0] + query_start = int(words[1]) + query_end = int(words[2]) + query_strand = words[3] + target_id = words[4] + target_start = int(words[5]) + target_end = int(words[6]) + target_strand = words[7] + score = float(words[8]) + ops = words[9::3] + qs = 0 + ts = 0 + n = (len(words) - 8) // 3 + ops.count("N") + coordinates = np.empty((2, n + 1), np.intp) + coordinates[0, 0] = ts + coordinates[1, 0] = qs + operations = bytearray(n) + i = 0 + for operation, query_step, target_step in zip(ops, words[10::3], words[11::3]): + query_step = int(query_step) + target_step = int(target_step) + if operation == "M": # Match + pass + elif operation == "5": # 5' splice site + assert target_step == 2 or query_step == 2 + elif operation == "I": # Intron + # use SAM/BAM definitions of operations: + operation = "N" + elif operation == "3": # 3' splice site + assert target_step == 2 or query_step == 2 + elif operation == "C": # Codon + assert target_step % 3 == 0 + assert query_step % 3 == 0 + elif operation == "G": # Gap + # use SAM/BAM definitions of operations: + if query_step == 0: + operation = "D" # Deletion + elif target_step == 0: + operation = "I" # Insertion + else: + raise ValueError( + "Unexpected gap operation with steps %d, %d in vulgar line" + % (query_step, target_step) + ) + elif operation == "N": # Non-equivalenced (unaligned) region + operation = "U" # 'N' is already used for introns in SAM/BAM + if target_step > 0: + ts += target_step + coordinates[0, i + 1] = ts + coordinates[1, i + 1] = qs + operations[i] = ord(operation) + i += 1 + if query_step > 0: + qs += query_step + coordinates[0, i + 1] = ts + coordinates[1, i + 1] = qs + operations[i] = ord(operation) + i += 1 + continue + elif operation == "S": # Split codon + pass + elif operation == "F": # Frame shift + pass + else: + raise ValueError("Unknown operation %s in vulgar string" % operation) + ts += target_step + qs += query_step + coordinates[0, i + 1] = ts + coordinates[1, i + 1] = qs + operations[i] = ord(operation) + i += 1 + if target_strand == "+": + coordinates[0, :] += target_start + target_length = target_end + target_molecule_type = None + elif target_strand == "-": + coordinates[0, :] = target_start - coordinates[0, :] + target_length = target_start + target_molecule_type = None + elif target_strand == ".": # protein + coordinates[0, :] += target_start + target_molecule_type = "protein" + target_length = target_end + if query_strand == "+": + coordinates[1, :] += query_start + query_length = query_end + query_molecule_type = None + elif query_strand == "-": + coordinates[1, :] = query_start - coordinates[1, :] + query_length = query_start + query_molecule_type = None + elif query_strand == ".": # protein + coordinates[1, :] += query_start + query_molecule_type = "protein" + query_length = query_end + target_seq = Seq(None, length=target_length) + query_seq = Seq(None, length=query_length) + target = SeqRecord(target_seq, id=target_id, description="") + query = SeqRecord(query_seq, id=query_id, description="") + if target_molecule_type is not None: + target.annotations["molecule_type"] = target_molecule_type + if query_molecule_type is not None: + query.annotations["molecule_type"] = query_molecule_type + alignment = Alignment([target, query], coordinates) + alignment.operations = operations + alignment.score = score + return alignment + + def _read_next_alignment(self, stream): + for line in stream: + line = line.strip() + if line == "-- completed exonerate analysis": + line = stream.readline() + if line: + raise ValueError( + "Found additional data after 'completed exonerate analysis'; corrupt file?" + ) + return + if line.startswith("vulgar: "): + words = line[8:].split() + alignment = self._parse_vulgar(words) + elif line.startswith("cigar: "): + words = line[7:].split() + alignment = self._parse_cigar(words) + return alignment + raise ValueError( + "Failed to find 'completed exonerate analysis'; truncated file?" + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/fasta.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/fasta.py new file mode 100644 index 0000000000000000000000000000000000000000..fd573a71f4d508a298a35a14ec045062fcd312ce --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/fasta.py @@ -0,0 +1,86 @@ +# Copyright 2022 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for aligned FASTA files. + +Aligned FASTA files are FASTA files in which alignment gaps in a sequence are +represented by dashes. Each sequence line in an aligned FASTA should have the +same length. +""" + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Alignment file writer for the aligned FASTA file format.""" + + fmt = "FASTA" + + def format_alignment(self, alignment): + """Return a string with the alignment in aligned FASTA format.""" + if not isinstance(alignment, Alignment): + raise TypeError("Expected an Alignment object") + lines = [] + for sequence, line in zip(alignment.sequences, alignment): + try: + name = sequence.id + except AttributeError: # Seq or plain string + lines.append(">") + else: # SeqRecord + if sequence.description: + lines.append(f">{sequence.id} {sequence.description}") + else: + lines.append(f">{sequence.id}") + lines.append(line) + return "\n".join(lines) + "\n" + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Alignment iterator for aligned FASTA files. + + An aligned FASTA file contains one multiple alignment. Alignment gaps are + represented by dashes in the sequence lines. Header lines start with '>' + followed by the name of the sequence, and optionally a description. + """ + + fmt = "FASTA" + + def _read_next_alignment(self, stream): + names = [] + descriptions = [] + lines = [] + for line in stream: + if line.startswith(">"): + parts = line[1:].rstrip().split(None, 1) + if len(parts) == 2: + name, description = parts + else: + description = "" + if len(parts) == 1: + name = parts[0] + else: + name = "" + names.append(name) + descriptions.append(description) + lines.append("") + else: + lines[-1] += line.strip() + if not lines: + if self._stream.tell() == 0: + raise ValueError("Empty file.") + return + lines = [line.encode() for line in lines] + seqs, coordinates = Alignment.parse_printed_alignment(lines) + records = [] + for name, description, seq in zip(names, descriptions, seqs): + sequence = Seq(seq) + record = SeqRecord(sequence, id=name, description=description) + records.append(record) + alignment = Alignment(records, coordinates) + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/hhr.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/hhr.py new file mode 100644 index 0000000000000000000000000000000000000000..57d1cd99e939a15298c5d0869fa9245efdcdf2bf --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/hhr.py @@ -0,0 +1,236 @@ +# Copyright 2022 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for hhr files generated by HHsearch or HHblits in HH-suite. + +You are expected to use this module via the Bio.Align functions. +""" + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Alignment iterator for hhr output files generated by HHsearch or HHblits. + + HHsearch and HHblits are part of the HH-suite of programs for Hidden Markov + Models. An output files in the hhr format contains multiple pairwise + alignments for a single query sequence. + """ + + fmt = "hhr" + + def _read_header(self, stream): + metadata = {} + for line in stream: + line = line.strip() + if line == "": + break + key, value = line.split(None, 1) + if key == "Query": + self.query_name = value + elif key == "Match_columns": + metadata[key] = int(value) + elif key == "No_of_seqs": + value1, value2 = value.split(" out of ") + metadata[key] = (int(value1), int(value2)) + elif key in ("Neff", "Template_Neff"): + metadata[key] = float(value) + elif key == "Searched_HMMs": + metadata[key] = int(value) + elif key == "Date": + metadata["Rundate"] = value + elif key == "Command": + metadata["Command line"] = value + else: + raise ValueError("Unknown key '%s'" % key) + self.metadata = metadata + line = stream.readline() + if not line: + raise ValueError("Truncated file.") + assert line.split() == [ + "No", + "Hit", + "Prob", + "E-value", + "P-value", + "Score", + "SS", + "Cols", + "Query", + "HMM", + "Template", + "HMM", + ] + counter = 0 + for line in stream: + if line.strip() == "": + break + counter += 1 + word, _ = line.split(None, 1) + assert int(word) == counter + self._length = counter + self._counter = 0 + + def _read_next_alignment(self, stream): + def create_alignment(): + n = len(target_sequence) + assert len(query_sequence) == n + if n == 0: + return + lines = [target_sequence.encode(), query_sequence.encode()] + seq_data, coordinates = Alignment.parse_printed_alignment(lines) + target_seq_data, query_seq_data = seq_data + coordinates[0, :] += target_start + coordinates[1, :] += query_start + sequence = {query_start: query_seq_data} + query_seq = Seq(sequence, length=query_length) + query = SeqRecord(query_seq, id=self.query_name) + sequence = {target_start: target_seq_data} + target_seq = Seq(sequence, length=target_length) + target_annotations = { + "hmm_name": hmm_name, + "hmm_description": hmm_description, + } + target = SeqRecord( + target_seq, id=target_name, annotations=target_annotations + ) + fmt = f"{' ' * target_start}%-{target_length - target_start}s" + # fmt: off + target.letter_annotations["Consensus"] = fmt % target_consensus.replace("-", "") + target.letter_annotations["ss_pred"] = fmt % target_ss_pred.replace("-", "") + target.letter_annotations["ss_dssp"] = fmt % target_ss_dssp.replace("-", "") + alignment_confidence = fmt % "".join( + c for t, c in zip(target_sequence, confidence) if t != "-" + ) + fmt = f"{' ' * query_start}%-{query_length - query_start}s" + if query_consensus: + query.letter_annotations["Consensus"] = fmt % query_consensus.replace("-", "") + if query_ss_pred: + query.letter_annotations["ss_pred"] = fmt % query_ss_pred.replace("-", "") + records = [target, query] + # fmt: on + alignment = Alignment(records, coordinates=coordinates) + alignment.annotations = alignment_annotations + alignment.column_annotations = {} + alignment.column_annotations["column score"] = column_score + alignment.column_annotations["Confidence"] = alignment_confidence + return alignment + + query_start = None + query_sequence = "" + query_consensus = "" + query_ss_pred = "" + target_start = None + target_sequence = "" + target_consensus = "" + target_ss_pred = "" + target_ss_dssp = "" + column_score = "" + confidence = "" + consensus = "" + for line in stream: + line = line.rstrip() + if not line: + pass + elif line.startswith(">"): + hmm_name, hmm_description = line[1:].split(None, 1) + line = stream.readline() + words = line.split() + alignment_annotations = {} + for word in words: + key, value = word.split("=") + if key == "Aligned_cols": + continue # can be obtained from coordinates + if key == "Identities": + value = value.rstrip("%") + value = float(value) + alignment_annotations[key] = value + elif line == "Done!": + line = stream.readline() + if line: + raise ValueError( + "Found additional data after 'Done!'; corrupt file?" + ) + elif line.startswith(" "): + column_score += line.strip() + elif line.startswith("No "): + counter = self._counter + self._counter += 1 + key, value = line.split() + assert int(value) == self._counter + if self._counter > self._length: + raise ValueError( + "Expected %d alignments, found %d" + % (self._length, self._counter) + ) + if counter > 0: + return create_alignment() + elif line.startswith("Confidence"): + value = line[-len(consensus) :] + confidence += value + elif line.startswith("Q ss_pred "): + key, value = line.rsplit(None, 1) + query_ss_pred += value + elif line.startswith("Q Consensus "): + key1, key2, start, consensus, end, total = line.split() + start = int(start) - 1 + end = int(end) + assert total.startswith("(") + assert total.endswith(")") + total = int(total[1:-1]) + query_consensus += consensus + elif line.startswith("Q "): + key1, key2, start, sequence, end, total = line.split() + assert self.query_name.startswith(key2) + start = int(start) - 1 + end = int(end) + assert total.startswith("(") + assert total.endswith(")") + query_length = int(total[1:-1]) + assert query_length == self.metadata["Match_columns"] + if query_start is None: + query_start = start + query_sequence += sequence + elif line.startswith("T ss_pred "): + key, value = line.rsplit(None, 1) + target_ss_pred += value + elif line.startswith("T ss_dssp "): + key, value = line.rsplit(None, 1) + target_ss_dssp += value + elif line.startswith("T Consensus "): + key1, key2, start, consensus, end, total = line.split() + start = int(start) - 1 + end = int(end) + assert total.startswith("(") + assert total.endswith(")") + total = int(total[1:-1]) + target_consensus += consensus + elif line.startswith("T "): + key, name, start, sequence, end, total = line.split() + assert key == "T" + target_name = name + start = int(start) - 1 + end = int(end) + assert total.startswith("(") + assert total.endswith(")") + target_length = int(total[1:-1]) + if target_start is None: + target_start = start + target_sequence += sequence + else: + raise ValueError("Failed to parse line '%s...'" % line[:30]) + alignment = create_alignment() + length = self._length + counter = self._counter + if alignment is None and counter != length: + raise ValueError("Expected %d alignments, found %d" % (length, counter)) + return alignment + + def __len__(self): + return self._length diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/interfaces.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/interfaces.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee310fa0b4b5bf0f704206d3d1444cdaef04310 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/interfaces.py @@ -0,0 +1,349 @@ +# Copyright 2006-2021 by Peter Cock. +# Copyright 2022 by Michiel de Hoon. +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support module (not for general use). + +Unless you are writing a new parser or writer for Bio.Align, you should not +use this module. It provides base classes to try and simplify things. +""" + +from abc import ABC +from abc import abstractmethod +from typing import Optional + +from Bio import StreamModeError +from Bio.Align import Alignments +from Bio.Align import AlignmentsAbstractBaseClass + + +class AlignmentIterator(AlignmentsAbstractBaseClass): + """Base class for building Alignment iterators. + + You should write a parse method that returns an Alignment generator. You + may wish to redefine the __init__ method as well. + + Subclasses may define the following class attributes: + - mode - 't' or 'b' for text or binary files, respectively + - fmt - a human-readable name for the file format. + """ + + mode = "t" # assume text files by default + fmt: str | None = None # to be defined in the subclass + + def __init__(self, source): + """Create an AlignmentIterator object. + + Arguments: + - source - input file stream, or path to input file + + This method MAY be overridden by any subclass. + + Note when subclassing: + - there should be a single non-optional argument, the source. + - you can add additional optional arguments. + """ + self.source = source + try: + self._stream = open(source, "r" + self.mode) + except TypeError: # not a path, assume we received a stream + if self.mode == "t": + if source.read(0) != "": + raise StreamModeError( + f"{self.fmt} files must be opened in text mode." + ) from None + elif self.mode == "b": + if source.read(0) != b"": + raise StreamModeError( + f"{self.fmt} files must be opened in binary mode." + ) from None + else: + raise ValueError(f"Unknown mode '{self.mode}'") from None + self._stream = source + self._index = 0 + self._read_header(self._stream) + + def __next__(self): + """Return the next alignment.""" + try: + stream = self._stream + except AttributeError: + raise StopIteration from None + alignment = self._read_next_alignment(stream) + if alignment is None: + self._len = self._index + raise StopIteration + self._index += 1 + return alignment + + def __len__(self): + """Return the number of alignments. + + The number of alignments is cached. If not yet calculated, the iterator + is rewound to the beginning, and the number of alignments is calculated + by iterating over the alignments. The iterator is then returned to its + original position in the file. + """ + try: + length = self._len + except AttributeError: + index = self._index + self.rewind() + length = 0 + for alignment in self: + length += 1 + self.rewind() + while self._index < index: + next(self) + self._len = length + return length + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, exc_traceback): + try: + stream = self._stream + except AttributeError: + return + if stream is not self.source: + stream.close() + del self._stream + + def __getitem__(self, index): + """Return the alignments as an Alignments object (which inherits from list). + + Only an index of the form [:] (i.e., a full slice) is supported. + The file stream is returned to its zero position, and the file header + is read and stored in an Alignments object. Next, we iterate over the + alignments and store them in the Alignments object. The iterator + is then returned to its original position in the file, and the + Alignments object is returned. The Alignments object contains the exact + same information as the Alignment iterator self, but stores the + alignments in a list instead of as an iterator, allowing indexing. + + Typical usage is + + >>> from Bio import Align + >>> alignments = Align.parse("Blat/dna_rna.psl", "psl") + >>> alignments.metadata + {'psLayout version': '3'} + + As `alignments` is an iterator and not a list, we cannot retrieve an + alignment by its index: + + >>> alignment = alignments[2] # doctest:+ELLIPSIS + Traceback (most recent call last): + ... + KeyError: 'only [:] (a full slice) can be used as the index' + + So we use the iterator to create a list-like Alignments object: + + >>> alignments = alignments[:] + + While `alignments` is a list-like object, it has the same `metadata` + attribute representing the information stored in the file header: + + >>> alignments.metadata + {'psLayout version': '3'} + + Now we can index individual alignments: + + >>> len(alignments) + 4 + >>> alignment = alignments[2] + >>> alignment.target.id, alignment.query.id + ('chr3', 'NR_111921.1') + + """ + if index != slice(None, None, None): + raise KeyError("only [:] (a full slice) can be used as the index") + read_header = type(self)._read_header + index = self._index + alignments = Alignments() + stream = self._stream + stream.seek(0) + # Read the header information and store it on the new alignments object: + read_header(alignments, stream) + # Rewind the iterator to initialize it correctly for iteration: + self.rewind() + alignments.extend(self) + # May as well store the number of alignments while we are at it: + self._len = self._index + # Return the alignments iterator to its original position: + self.rewind() + while self._index < index: + next(self) + return alignments + + def _read_header(self, stream): + """Read the file header and store it in metadata.""" + return + + @abstractmethod + def _read_next_alignment(self, stream): + """Read one Alignment from the stream, and return it.""" + + def rewind(self): # noqa: D102 + self._stream.seek(0) + self._read_header(self._stream) + self._index = 0 + + +class AlignmentWriter(ABC): # noqa: B024 + """Base class for alignment writers. This class should be subclassed. + + It is intended for alignment file formats with an (optional) + header, one or more alignments, and an (optional) footer. + + The user may call the write_file() method to write a complete + file containing the alignments. + + Alternatively, users may call the write_header(), followed + by multiple calls to format_alignment() and/or write_alignments(), + followed finally by write_footer(). + + Subclasses may define the following class attributes: + - mode - 't' or 'b' for text or binary files, respectively + - fmt - a human-readable name for the file format. + """ + + mode = "t" # assume text files by default + fmt: str | None = None # to be defined in the subclass + + def __init__(self, target): + """Create the writer object. + + Arguments: + - target - output file stream, or path to output file + + This method MAY be overridden by any subclass. + + Note when subclassing: + - there should be a single non-optional argument, the target. + - you can add additional optional arguments. + """ + if target is not None: + # target is None if we only use the writer to format strings. + if self.mode == "t": + try: + target.write("") + except TypeError: + # target was opened in binary mode + raise StreamModeError("File must be opened in text mode.") from None + except AttributeError: + # target is a path + stream = open(target, "w" + self.mode) + else: + stream = target + elif self.mode == "b": + try: + target.write(b"") + except TypeError: + # target was opened in text mode + raise StreamModeError( + "File must be opened in binary mode." + ) from None + except AttributeError: + # target is a path + stream = open(target, "w" + self.mode) + else: + stream = target + else: + raise RuntimeError("Unknown mode '%s'" % self.mode) + self._stream = stream + self._target = target + + def write_header(self, stream, alignments): + """Write the file header to the output file.""" + return + ################################################## + # You MUST implement this method in the subclass # + # if the file format defines a file header. # + ################################################## + + def write_footer(self, stream): + """Write the file footer to the output file.""" + return + ################################################## + # You MUST implement this method in the subclass # + # if the file format defines a file footer. # + ################################################## + + def format_alignment(self, alignment): + """Format a single alignment as a string. + + alignment - an Alignment object + """ + if self.mode == "t": + raise NotImplementedError("This method should be implemented") + ################################################### + # You MUST implement this method in the subclass. # + # if the file mode is text. # + ################################################### + + def write_single_alignment(self, stream, alignments): + """Write a single alignment to the output file, and return 1. + + alignments - A list or iterator returning Alignment objects + stream - Output file stream. + """ + count = 0 + for alignment in alignments: + if count == 1: + raise ValueError( + f"Alignment files in the {self.fmt} format can contain a single alignment only." + ) + line = self.format_alignment(alignment) + stream.write(line) + count += 1 + return count + + def write_multiple_alignments(self, stream, alignments): + """Write alignments to the output file, and return the number of alignments. + + alignments - A list or iterator returning Alignment objects + stream - Output file stream. + """ + count = 0 + for alignment in alignments: + line = self.format_alignment(alignment) + stream.write(line) + count += 1 + return count + + write_alignments = write_multiple_alignments + + def write_file(self, stream, alignments): + """Write the alignments to the file stream, and return the number of alignments. + + alignments - A list or iterator returning Alignment objects + stream - Output file stream. + """ + self.write_header(stream, alignments) + count = self.write_alignments(stream, alignments) + self.write_footer(stream) + return count + + def write(self, alignments): + """Write a file with the alignments, and return the number of alignments. + + alignments - A list or iterator returning Alignment objects + """ + stream = self._stream + try: + count = self.write_file(stream, alignments) + finally: + if stream is not self._target: + stream.close() + return count + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/maf.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/maf.py new file mode 100644 index 0000000000000000000000000000000000000000..09b69ca45f7b29e477e58b40b82768595647010c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/maf.py @@ -0,0 +1,457 @@ +# Copyright 2011, 2012 by Andrew Sczesnak. All rights reserved. +# Revisions Copyright 2011, 2017 by Peter Cock. All rights reserved. +# Revisions Copyright 2014, 2015 by Adam Novak. All rights reserved. +# Revisions Copyright 2015, 2017 by Blaise Li. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for the "maf" multiple alignment format. + +The Multiple Alignment Format, described by UCSC, stores a series of +multiple alignments in a single file. It is suitable for whole-genome +to whole-genome alignments, metadata such as source chromosome, start +position, size, and strand can be stored. + +See http://genome.ucsc.edu/FAQ/FAQformat.html#format5 + +You are expected to use this module via the Bio.Align functions. + +Coordinates in the MAF format are defined in terms of zero-based start +positions (like Python) and aligning region sizes. + +A minimal aligned region of length one and starting at first position in the +source sequence would have ``start == 0`` and ``size == 1``. + +As we can see on this example, ``start + size`` will give one more than the +zero-based end position. We can therefore manipulate ``start`` and +``start + size`` as python list slice boundaries. +""" + +import shlex + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Accepts Alignment objects, writes a MAF file.""" + + fmt = "MAF" + + def _write_trackline(self, stream, metadata): + stream.write("track") + for key, value in metadata.items(): + if key in ("name", "description", "frames"): + pass + elif key == "mafDot": + if value not in ("on", "off"): + raise ValueError( + "mafDot value must be 'on' or 'off' (received '%s')" % value + ) + elif key == "visibility": + if value not in ("dense", "pack", "full"): + raise ValueError( + "visibility value must be 'dense', 'pack', or 'full' (received '%s')" + % value + ) + elif key == "speciesOrder": + value = " ".join(value) + else: + continue + if " " in value: + value = '"%s"' % value + stream.write(f" {key}={value}") + stream.write("\n") + + def write_header(self, stream, alignments): + """Write the MAF header.""" + try: + metadata = alignments.metadata + except AttributeError: + metadata = {"MAF Version": "1"} + track_keys = ( + "name", + "description", + "frames", + "mafDot", + "visibility", + "speciesOrder", + ) + for key in track_keys: + if key in metadata: + self._write_trackline(stream, metadata) + break + stream.write("##maf") + for key, value in metadata.items(): + if key in track_keys: + continue + if key == "Comments": + continue + if key == "MAF Version": + if value != "1": + raise ValueError("MAF version must be 1") + key = "version" + elif key == "Scoring": + key = "scoring" + elif key == "Program": + key = "program" + else: + raise ValueError("Unexpected key '%s' for header" % key) + stream.write(f" {key}={value}") + stream.write("\n") + comments = metadata.get("Comments") + if comments is not None: + for comment in comments: + stream.write(f"# {comment}\n") + stream.write("\n") + + def _format_score_line(self, alignment, annotations): + try: + score = alignment.score + except AttributeError: + line = "a" + else: + line = f"a score={score:.6f}" + value = annotations.get("pass") + if value is not None: + line += f" pass={value}" + return line + "\n" + + def format_alignment(self, alignment): + """Return a string with a single alignment formatted as a MAF block.""" + if not isinstance(alignment, Alignment): + raise TypeError("Expected an Alignment object") + try: + alignment_annotations = alignment.annotations + except AttributeError: + alignment_annotations = {} + lines = [] + line = self._format_score_line(alignment, alignment_annotations) + lines.append(line) + name_width = 0 + start_width = 0 + size_width = 0 + length_width = 0 + n = len(alignment.sequences) + for i in range(n): + record = alignment.sequences[i] + coordinates = alignment.coordinates[i] + try: + name = record.id + except AttributeError: + name = "sequence_%d" % i + start = coordinates[0] + end = coordinates[-1] + length = len(record) + if start < end: + size = end - start + else: + size = start - end + start = length - start + name_width = max(name_width, len(name)) + start_width = max(start_width, len(str(start))) + size_width = max(size_width, len(str(size))) + length_width = max(length_width, len(str(length))) + for i, empty in enumerate(alignment_annotations.get("empty", [])): + record, segment, status = empty + try: + name = record.id + except AttributeError: + name = "sequence_%d" % (i + n) + name_width = max(name_width, len(name)) + start, end = segment + length = len(record.seq) + if start <= end: + size = end - start + else: + size = start - end + start = length - start + start_width = max(start_width, len(str(start))) + size_width = max(size_width, len(str(size))) + length_width = max(length_width, len(str(length))) + quality_width = name_width + start_width + size_width + length_width + 5 + for i in range(n): + record = alignment.sequences[i] + coordinates = alignment.coordinates[i] + try: + record_id = record.id + except AttributeError: + record_id = "sequence_%d" % i + start = coordinates[0] + end = coordinates[-1] + length = len(record) + if start < end: + size = end - start + strand = "+" + else: + size = start - end + start = length - start + strand = "-" + text = alignment[i] + name = record_id.ljust(name_width) + start = str(start).rjust(start_width) + size = str(size).rjust(size_width) + length = str(length).rjust(length_width) + line = f"s {name} {start} {size} {strand} {length} {text}\n" + lines.append(line) + try: + annotations = record.annotations + except AttributeError: + annotations = None + if annotations is not None: + quality = annotations.get("quality") + if quality is not None: + gapped_quality = "" + j = 0 + for letter in text: + if letter == "-": + gapped_quality += "-" + else: + gapped_quality += quality[j] + j += 1 + name = record_id.ljust(quality_width) + line = f"q {name} {gapped_quality}\n" + lines.append(line) + try: + leftStatus = annotations["leftStatus"] + leftCount = annotations["leftCount"] + rightStatus = annotations["rightStatus"] + rightCount = annotations["rightCount"] + except KeyError: + pass + else: + name = record_id.ljust(name_width) + line = f"i {name} {leftStatus} {leftCount} {rightStatus} {rightCount}\n" + lines.append(line) + for i, empty in enumerate(alignment_annotations.get("empty", [])): + record, segment, status = empty + try: + name = record.id + except AttributeError: + name = "sequence_%d" % (i + n) + name = name.ljust(name_width) + start, end = segment + length = len(record.seq) + if start <= end: + size = end - start + strand = "+" + else: + size = start - end + start = length - start + strand = "-" + start = str(start).rjust(start_width) + size = str(size).rjust(size_width) + length = str(length).rjust(length_width) + line = f"e {name} {start} {size} {strand} {length} {status}\n" + lines.append(line) + lines.append("\n") + return "".join(lines) + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Alignment iterator for Multiple Alignment Format files. + + The file may contain multiple concatenated alignments, which are loaded + and returned incrementally. + + File meta-data are stored in the ``.metadata`` attribute of the returned + iterator. Alignment annotations are stored in the ``.annotations`` + attribute of the ``Alignment`` object, except for the alignment score, + which is stored as an attribute. Sequence information of empty parts in + the alignment block (sequences that connect the previous alignment block to + the next alignment block, but do not align to the current alignment block) + is stored in the alignment annotations under the ``"empty"`` key. + Annotations specific to each line in the alignment are stored in the + ``.annotations`` attribute of the corresponding sequence record. + """ + + fmt = "MAF" + + status_characters = ("C", "I", "N", "n", "M", "T") + empty_status_characters = ("C", "I", "M", "n") + + def _read_header(self, stream): + metadata = {} + line = stream.readline() + if line.startswith("track "): + words = shlex.split(line) + for word in words[1:]: + key, value = word.split("=") + if key in ("name", "description", "frames"): + pass + elif key == "mafDot": + if value not in ("on", "off"): + raise ValueError( + "Variable mafDot in track line has unexpected value '%s'" + % value + ) + elif key == "visibility": + if value not in ("dense", "pack", "full"): + raise ValueError( + "Variable visibility in track line has unexpected value '%s'" + % value + ) + elif key == "speciesOrder": + value = value.split() + else: + raise ValueError("Unexpected variable '%s' in track line" % key) + metadata[key] = value + line = stream.readline() + words = line.split() + if words[0] != "##maf": + raise ValueError("header line does not start with ##maf") + for word in words[1:]: + key, value = word.split("=") + if key == "version": + key = "MAF Version" + elif key == "scoring": + key = "Scoring" + elif key == "program": + key = "Program" + else: + raise ValueError("Unexpected variable '%s' in header line" % key) + metadata[key] = value + if metadata.get("MAF Version") != "1": + raise ValueError("MAF version must be 1") + comments = [] + for line in stream: + if line.strip(): + if not line.startswith("#"): + assert line.startswith("a") + self._aline = line + break + comment = line[1:].strip() + comments.append(comment) + else: + self._close() + if comments: + metadata["Comments"] = comments + self.metadata = metadata + + def _read_next_alignment(self, stream): + aline = self._aline + if aline is None: + return + records = [] + starts = [] + sizes = [] + strands = [] + score = None + aligned_sequences = [] + annotations = {} + words = aline[1:].split() + for word in words: + key, value = word.split("=") + if key == "score": + score = float(value) + elif key == "pass": + value = int(value) + if value <= 0: + raise ValueError("pass value must be positive (found %d)" % value) + annotations["pass"] = value + else: + raise ValueError("Unknown annotation variable '%s'" % key) + + for line in stream: + if line.startswith("#"): + continue + elif line.startswith("a"): + self._aline = line + break + elif line.startswith("s "): + words = line.strip().split() + if len(words) != 7: + raise ValueError( + "Error parsing alignment - 's' line must have 7 fields" + ) + src = words[1] + start = int(words[2]) + size = int(words[3]) + strand = words[4] + srcSize = int(words[5]) + text = words[6] + for gap_char in ".=_": + text = text.replace(gap_char, "-") + aligned_sequences.append(text.encode()) + seq = Seq(None, length=srcSize) + record = SeqRecord(seq, id=src, name="", description="") + records.append(record) + starts.append(start) + sizes.append(size) + strands.append(strand) + elif line.startswith("i "): + words = line.strip().split() + assert len(words) == 6 + assert words[1] == src # from the previous "s" line + leftStatus = words[2] + leftCount = int(words[3]) + rightStatus = words[4] + rightCount = int(words[5]) + assert leftStatus in AlignmentIterator.status_characters + assert rightStatus in AlignmentIterator.status_characters + record.annotations["leftStatus"] = leftStatus + record.annotations["leftCount"] = leftCount + record.annotations["rightStatus"] = rightStatus + record.annotations["rightCount"] = rightCount + elif line.startswith("e"): + words = line[1:].split() + assert len(words) == 6 + src = words[0] + start = int(words[1]) + size = int(words[2]) + strand = words[3] + srcSize = int(words[4]) + status = words[5] + assert status in AlignmentIterator.empty_status_characters + sequence = Seq(None, length=srcSize) + record = SeqRecord(sequence, id=src, name="", description="") + end = start + size + if strand == "+": + segment = (start, end) + else: + segment = (srcSize - start, srcSize - end) + empty = (record, segment, status) + annotation = annotations.get("empty") + if annotation is None: + annotation = [] + annotations["empty"] = annotation + annotation.append(empty) + elif line.startswith("q "): + words = line.strip().split() + assert len(words) == 3 + assert words[1] == src # from the previous "s" line + value = words[2].replace("-", "") + record.annotations["quality"] = value + elif not line.strip(): + # reached the end of the alignment, but keep reading until we + # find the next alignment + continue + else: + raise ValueError(f"Error parsing alignment - unexpected line:\n{line}") + else: + self._aline = None + sequences, coordinates = Alignment.parse_printed_alignment(aligned_sequences) + for start, size, sequence, record in zip(starts, sizes, sequences, records): + srcSize = len(record.seq) + if len(sequence) != size: + raise ValueError( + "sequence size is incorrect (found %d, expected %d)" + % (len(sequence), size) + ) + record.seq = Seq({start: sequence}, length=srcSize) + for record, strand, row in zip(records, strands, coordinates): + if strand == "-": + row[:] = row[-1] - row[0] - row + record.seq = record.seq.reverse_complement() + start = record.seq.defined_ranges[0][0] + row += start + alignment = Alignment(records, coordinates) + if annotations is not None: + alignment.annotations = annotations + if score is not None: + alignment.score = score + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/mauve.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/mauve.py new file mode 100644 index 0000000000000000000000000000000000000000..c328f3c3e2b802d32da4db437af96a0f338f0293 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/mauve.py @@ -0,0 +1,253 @@ +# Copyright 2015-2015 by Eric Rasche. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for "xmfa" output from Mauve/ProgressiveMauve. + +You are expected to use this module via the Bio.Align functions. +""" + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Mauve xmfa alignment writer.""" + + fmt = "Mauve" + + def __init__(self, target, metadata=None, identifiers=None): + """Create an AlignmentWriter object. + + Arguments: + - target - output stream or file name + - metadata - metadata to be included in the output. If metadata + is None, then the alignments object to be written + must have an attribute `metadata`. + - identifiers - list of the IDs of the sequences included in the + alignment. Sequences will be numbered according to + their index in this list. If identifiers is None, + then the alignments object to be written must have + an attribute `identifiers`. + """ + super().__init__(target) + self._metadata = metadata + self._identifiers = identifiers + + def write_header(self, stream, alignments): + """Write the file header to the output file.""" + metadata = self._metadata + format_version = metadata.get("FormatVersion", "Mauve1") + line = f"#FormatVersion {format_version}\n" + stream.write(line) + identifiers = self._identifiers + filename = metadata.get("File") + if filename is None: + # sequences came from separate files + for index, filename in enumerate(identifiers): + number = index + 1 + line = f"#Sequence{number}File\t{filename}\n" + stream.write(line) + line = f"#Sequence{number}Format\tFastA\n" + stream.write(line) + else: + # sequences came from one combined file + for number, identifier in enumerate(identifiers): + assert number == int(identifier) + number += 1 + line = f"#Sequence{number}File\t{filename}\n" + stream.write(line) + line = f"#Sequence{number}Entry\t{number}\n" + stream.write(line) + line = f"#Sequence{number}Format\tFastA\n" + stream.write(line) + backbone_file = metadata.get("BackboneFile") + if backbone_file is not None: + line = f"#BackboneFile\t{backbone_file}\n" + stream.write(line) + + def write_file(self, stream, alignments): + """Write a file with the alignments, and return the number of alignments. + + alignments - A Bio.Align.mauve.AlignmentIterator object. + """ + metadata = self._metadata + if metadata is None: + try: + metadata = alignments.metadata + except AttributeError: + raise ValueError("alignments do not have an attribute `metadata`") + else: + self._metadata = metadata + identifiers = self._identifiers + if identifiers is None: + try: + identifiers = alignments.identifiers + except AttributeError: + raise ValueError("alignments do not have an attribute `identifiers`") + else: + self._identifiers = identifiers + count = interfaces.AlignmentWriter.write_file(self, stream, alignments) + return count + + def format_alignment(self, alignment): + """Return a string with a single alignment in the Mauve format.""" + metadata = self._metadata + n, m = alignment.shape + + if n == 0: + raise ValueError("Must have at least one sequence") + if m == 0: + raise ValueError("Non-empty sequences are required") + + filename = metadata.get("File") + lines = [] + for i in range(n): + identifier = alignment.sequences[i].id + start = alignment.coordinates[i, 0] + end = alignment.coordinates[i, -1] + if start <= end: + strand = "+" + else: + strand = "-" + start, end = end, start + if start == end: + assert start == 0 + else: + start += 1 # switch to 1-based counting + sequence = alignment[i] + if filename is None: + number = ( + self._identifiers.index(identifier) + 1 + ) # Switch to 1-based counting + line = f"> {number}:{start}-{end} {strand} {identifier}\n" + else: + number = int(identifier) + 1 # Switch to 1-based counting + line = f"> {number}:{start}-{end} {strand} {filename}\n" + lines.append(line) + line = f"{sequence}\n" + lines.append(line) + lines.append("=\n") + return "".join(lines) + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Mauve xmfa alignment iterator.""" + + fmt = "Mauve" + + def _read_header(self, stream): + metadata = {} + prefix = "Sequence" + suffixes = ("File", "Entry", "Format") + id_info = {} + for suffix in suffixes: + id_info[suffix] = [] + for line in stream: + if not line.startswith("#"): + self._line = line.strip() + break + key, value = line[1:].split() + if key.startswith(prefix): + for suffix in suffixes: + if key.endswith(suffix): + break + else: + raise ValueError("Unexpected keyword '%s'" % key) + if suffix == "Entry": + value = int(value) - 1 # Switch to 0-based counting + seq_num = int(key[len(prefix) : -len(suffix)]) + id_info[suffix].append(value) + assert seq_num == len(id_info[suffix]) # Mauve uses 1-based counting + else: + metadata[key] = value.strip() + else: + if not metadata: + raise ValueError("Empty file.") from None + if len(set(id_info["File"])) == 1: + # A single file containing all sequences was provided as input; + # store the file name once, and use the entry number as ID + metadata["File"] = id_info["File"][0] + self.identifiers = [str(entry) for entry in id_info["Entry"]] + else: + assert len(set(id_info["File"])) == len(id_info["File"]) + # Separate files for each of the sequences were provided as input; + # use the sequence file as ID + self.identifiers = id_info["File"] + self.metadata = metadata + + def _parse_description(self, line): + assert line.startswith(">") + locus, strand, comments = line[1:].split(None, 2) + seq_num, start_end = locus.split(":") + seq_num = int(seq_num) - 1 # python counting + identifier = self.identifiers[seq_num] + assert strand in "+-" + start, end = start_end.split("-") + start = int(start) + end = int(end) + if start == 0: + assert end == 0 # unaligned sequence + else: + start -= 1 # python counting + return (identifier, start, end, strand, comments) + + def _read_next_alignment(self, stream): + descriptions = [] + seqs = [] + + try: + line = self._line + except AttributeError: + pass + else: + del self._line + description = self._parse_description(line) + identifier, start, end, strand, comments = description + descriptions.append(description) + seqs.append("") + + for line in stream: + line = line.strip() + if line.startswith("="): + # There may be more data, but we've reached the end of this + # alignment + seqs = [seq.encode() for seq in seqs] + seqs, coordinates = Alignment.parse_printed_alignment(seqs) + records = [] + for index, (description, seq) in enumerate(zip(descriptions, seqs)): + identifier, start, end, strand, comments = description + assert len(seq) == end - start + if strand == "+": + pass + elif strand == "-": + coordinates[index, :] = len(seq) - coordinates[index, :] + else: + raise ValueError("Unexpected strand '%s'" % strand) + coordinates[index] += start + if start == 0: + seq = Seq(seq) + if strand == "-": + seq = seq.reverse_complement() + else: + if strand == "+": + seq = Seq({start: seq}, length=end) + else: # strand == "-" + seq = Seq({0: seq}, length=end) + seq = seq.reverse_complement() + record = SeqRecord(seq, id=identifier, description=comments) + records.append(record) + + return Alignment(records, coordinates) + + elif line.startswith(">"): + description = self._parse_description(line) + identifier, start, end, strand, comments = description + descriptions.append(description) + seqs.append("") + else: + seqs[-1] += line diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/msf.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/msf.py new file mode 100644 index 0000000000000000000000000000000000000000..075d455df26e692af8b4c72db9eb83c729a90f78 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/msf.py @@ -0,0 +1,244 @@ +# Copyright 2019, National Marrow Donor Program (NMPD). All rights reserved. +# Written by Peter Cock, The James Hutton Institute, under contract to NMDP. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for GCG MSF format. + +The file format was produced by the GCG PileUp and LocalPileUp tools, and later +tools such as T-COFFEE and MUSCLE support it as an optional output format. + +You are expected to use this module via the Bio.Align functions. +""" + +import warnings + +from Bio import BiopythonParserWarning +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentIterator(interfaces.AlignmentIterator): + """GCG MSF alignment iterator.""" + + fmt = "MSF" + + def _read_next_alignment(self, stream): + line = stream.readline() + if not line: + if stream.tell() == 0: + raise ValueError("Empty file.") from None + return + # Whitelisted headers we know about. + known_headers = ["!!NA_MULTIPLE_ALIGNMENT", "!!AA_MULTIPLE_ALIGNMENT", "PileUp"] + # Examples in "Molecular Biology Software Training Manual GCG version 10" + # by BBSRC Bioscuences IT Services (BITS), Harpenden, UK, Copyright 1996-2001 + # would often start as follows: + # + # !!AA_MUTIPLE_ALIGNMENT 1.0 + # PileUp of: @/usr/users2/culhane/... + # + # etc with other seemingly free format text before getting to the + # MSF/Type/Check line and the following Name: lines block and // line. + # + # MUSCLE just has a line "PileUp", while other sources just use the line + # "!!AA_MULTIPLE_ALIGNMENT" (amino acid) or "!!NA_MULTIPLE_ALIGNMENT" + # (nucleotide). + if line.strip().split()[0] not in known_headers: + raise ValueError( + "%s is not a known GCG MSF header: %s" + % (line.strip().split()[0], ", ".join(known_headers)) + ) + + for line in stream: + line = line.rstrip("\n") + if "MSF: " in line and line.endswith(".."): + break + else: + raise ValueError("Reached end of file without MSF/Type/Check header line") + + # Quoting from "Molecular Biology Software Training Manual GCG version 10" + # by BBSRC Bioscuences IT Services (BITS), Harpenden, UK. Copyright 1996-2001. + # Page 31: + # + # "Header information is before a .. (double dot) in a GCG format file. + # The file will also have a checksum specific for that file." + # + # This was followed by a single non-aligned sequence, but this convention + # appears to also be used in the GCG MSF files. Quoting other examples in + # this reference, page 31: + # + # localpileup_17.msf MSF: 195 Type: P January 6, 2000 15:41 Check: 4365 .. + # + # Except from page 148: + # + # localpileup_106.msf MSF: 457 Type: P November 28, 2000 16:09 Check: 2396 .. + # + # Quoting output from MUSCLE v3.8, have two leading spaces and a zero checksum: + # + # MSF: 689 Type: N Check: 0000 .. + # + # By observation, the MSF value is the column count, type is N (nucleotide) + # or P (protein / amino acid). + # + # In a possible bug, EMBOSS v6.6.0.0 uses CompCheck: rather than Check: as shown, + # + # $ seqret -sequence Tests/Fasta/f002 -auto -stdout -osformat msf + # !!NA_MULTIPLE_ALIGNMENT 1.0 + # + # stdout MSF: 633 Type: N 01/08/19 CompCheck: 8543 .. + # + # Name: G26680 Len: 633 Check: 4334 Weight: 1.00 + # Name: G26685 Len: 633 Check: 3818 Weight: 1.00 + # Name: G29385 Len: 633 Check: 391 Weight: 1.00 + # + # // + # + parts = line.split() + offset = parts.index("MSF:") + if parts[offset + 2] != "Type:" or parts[-3] not in ("Check:", "CompCheck:"): + raise ValueError( + "GCG MSF header line should be " + "' MSF: Type: Check: ..', " + " not: %r" % line + ) + try: + aln_length = int(parts[offset + 1]) + except ValueError: + raise ValueError( + "GCG MSF header line should have MSF: for column count, not %r" + % parts[offset + 1] + ) from None + seq_type = parts[offset + 3] + if seq_type not in ["P", "N"]: + raise ValueError( + "GCG MSF header line should have 'Type: P' (protein) " + "or 'Type: N' (nucleotide), not 'Type: %s'" % seq_type + ) + + # There should be a blank line after that header line, then the Name: lines + # + # The Name may be followed by 'oo', as shown here: + # + # PileUp + # + # + # + # MSF: 628 Type: P Check: 147 .. + # + # Name: AK1H_ECOLI/1-378 oo Len: 628 Check: 3643 Weight: 1.000 + # Name: AKH_HAEIN/1-382 oo Len: 628 Check: 6504 Weight: 1.000 + # + # // + names = [] + remaining = [] + checks = [] + weights = [] + for line in stream: + line = line.strip() + if line == "//": + break + if line.startswith("Name: "): + words = line.split() + try: + index_name = words.index("Name:") + index_len = words.index("Len:") + index_weight = words.index("Weight:") + index_check = words.index("Check:") + except ValueError: + raise ValueError(f"Malformed GCG MSF name line: {line!r}") from None + name = words[index_name + 1] + length = int(words[index_len + 1]) + weight = float(words[index_weight + 1]) + check = words[index_check + 1] + if name in names: + raise ValueError(f"Duplicated ID of {name!r}") + names.append(name) + remaining.append(length) + checks.append(check) + weights.append(weight) + else: + raise ValueError("End of file while looking for end of header // line.") + + line = stream.readline() + if not line: + raise ValueError("End of file after // line, expected sequences.") from None + if line.strip(): + raise ValueError("After // line, expected blank line before sequences.") + + # Now load the sequences + seqs = [""] * len(names) + for line in stream: + words = line.split() + if not words: + continue + name = words[0] + try: + index = names.index(name) + except ValueError: + # This may be a coordinate line + for word in words: + if not word.isdigit(): + break + else: + # all words are integers; assume this is a coordinate line + continue + raise ValueError(f"Unexpected line '{line}' in input") from None + seq = "".join(words[1:]) + length = remaining[index] - (len(seq) - seq.count("-")) + if length < 0: + raise ValueError("Received longer sequence than expected for %s" % name) + seqs[index] += seq + remaining[index] = length + if all(length == 0 for length in remaining): + break + else: + raise ValueError("End of file where expecting sequence data.") + + # skip any remaining empty lines + for line in stream: + assert line.strip() == "" + + length = max(len(seq) for seq in seqs) + if length != aln_length: + warnings.warn( + "GCG MSF headers said alignment length %i, but found %i" + % (aln_length, length), + BiopythonParserWarning, + stacklevel=2, + ) + aln_length = length + + # Combine list of strings into single string, remap gaps + for index, seq in enumerate(seqs): + seq = "".join(seq).replace("~", "-").replace(".", "-") + if len(seq) < aln_length: + seq += "-" * (aln_length - len(seq)) + seqs[index] = seq + + seqs = [seq.encode() for seq in seqs] + seqs, coordinates = Alignment.parse_printed_alignment(seqs) + records = [ + SeqRecord( + Seq(seq), + id=name, + name=name, + description=name, + annotations={"weight": weight}, + ) + for (name, seq, weight) in zip(names, seqs, weights) + ] + + alignment = Alignment(records, coordinates) + # This will check alignment lengths are self-consistent: + columns = alignment.length + if columns != aln_length: + raise ValueError( + "GCG MSF headers said alignment length %i, but found %i" + % (aln_length, columns) + ) + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/nexus.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/nexus.py new file mode 100644 index 0000000000000000000000000000000000000000..fafe6cbb7e9cfd4eb320b44341787f29b5f55cfe --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/nexus.py @@ -0,0 +1,194 @@ +# Copyright 2006-2016 by Peter Cock. All rights reserved. +# Revisions copyright 2021 by Michiel de Hoon. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for the "nexus" file format. + +You are expected to use this module via the Bio.Align functions. + +See also the Bio.Nexus module (which this code calls internally), +as this offers more than just accessing the alignment or its +sequences as SeqRecord objects. +""" + +from io import StringIO + +import numpy as np + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Nexus import Nexus +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Nexus alignment writer. + + Note that Nexus files are only expected to hold ONE alignment + matrix. + + You are expected to call this class via Bio.Align.write(). + """ + + fmt = "Nexus" + + def __init__(self, target, interleave=None): + """Create an AlignmentWriter object. + + Arguments: + - target - output stream or file name + - interleave - if None (default): interleave if columns > 1000 + if True: use interleaved format + if False: do not use interleaved format + + """ + super().__init__(target) + self.interleave = interleave + + def write_file(self, stream, alignments): + """Write a file with the alignments, and return the number of alignments. + + alignments - A list or iterator returning Alignment objects + """ + count = super().write_file(stream, alignments) + if count != 1: + raise ValueError("Expected to write 1 alignment; wrote %d" % count) + return count + + def format_alignment(self, alignment, interleave=None): + """Return a string with a single alignment in the Nexus format. + + Creates an empty Nexus object, adds the sequences + and then gets Nexus to prepare the output. + + - alignment - An Alignment object + - interleave - if None (default): interleave if columns > 1000 + if True: use interleaved format + if False: do not use interleaved format + """ + stream = StringIO() + self.write_alignment(alignment, stream, interleave) + stream.seek(0) + return stream.read() + + def write_alignment(self, alignment, stream, interleave=None): + """Write a single alignment to the output file. + + - alignment - An Alignment object + - stream - output stream + - interleave - if None (default): interleave if columns > 1000 + if True: use interleaved format + if False: do not use interleaved format + """ + nseqs, length = alignment.shape + if nseqs == 0: + raise ValueError("Must have at least one sequence") + if length == 0: + raise ValueError("Non-empty sequences are required") + + rows, columns = alignment.shape + if rows == 0: + raise ValueError("Must have at least one sequence") + if columns == 0: + raise ValueError("Non-empty sequences are required") + datatype = self._classify_mol_type_for_nexus(alignment) + minimal_record = ( + "begin data; dimensions ntax=0 nchar=0; format datatype=%s; end;" % datatype + ) + n = Nexus.Nexus(minimal_record) + for record, aligned_sequence in zip(alignment.sequences, alignment): + # Sanity test sequences (should this be even stricter?) + if datatype == "dna" and "U" in record.seq: + raise ValueError(f"{record.id} contains U, but DNA alignment") + elif datatype == "rna" and "T" in record.seq: + raise ValueError(f"{record.id} contains T, but RNA alignment") + n.add_sequence(record.id, aligned_sequence) + + # Note: MrBayes may choke on large alignments if not interleaved + if interleave is None: + interleave = columns > 1000 + n.write_nexus_data(stream, interleave=interleave) + + def write_alignments(self, stream, alignments): + """Write alignments to the output file, and return the number of alignments. + + alignments - A list or iterator returning Alignment objects + """ + count = 0 + interleave = self.interleave + for alignment in alignments: + self.write_alignment(alignment, stream, interleave=interleave) + count += 1 + return count + + def _classify_mol_type_for_nexus(self, alignment): + """Return 'protein', 'dna', or 'rna' based on records' molecule type (PRIVATE). + + All the records must have a molecule_type annotation, and they must + agree. + + Raises an exception if this is not possible. + """ + values = { + sequence.annotations.get("molecule_type", None) + for sequence in alignment.sequences + } + if all(_ and "DNA" in _ for _ in values): + return "dna" # could have been a mix of "DNA" and "gDNA" + elif all(_ and "RNA" in _ for _ in values): + return "rna" # could have been a mix of "RNA" and "mRNA" + elif all(_ and "protein" in _ for _ in values): + return "protein" + else: + raise ValueError("Need the molecule type to be defined") + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Nexus alignment iterator.""" + + fmt = "Nexus" + + def _read_header(self, stream): + line = stream.readline() + if not line: + raise ValueError("Empty file.") from None + + if line.strip() != "#NEXUS": + raise ValueError("File does not start with NEXUS header.") + + def _read_next_alignment(self, stream): + # NOTE - We only expect ONE alignment matrix per Nexus file. + n = Nexus.Nexus(stream) + if not n.matrix: + # No alignment found + return + + # Bio.Nexus deals with duplicated names by adding a '.copy' suffix. + # The original names and the modified names are kept in these two lists: + assert len(n.unaltered_taxlabels) == len(n.taxlabels) + + # TODO - Can we extract any annotation too? + if n.datatype in ("dna", "nucleotide"): + annotations = {"molecule_type": "DNA"} + elif n.datatype == "rna": + annotations = {"molecule_type": "RNA"} + elif n.datatype == "protein": + annotations = {"molecule_type": "protein"} + else: + annotations = None + aligned_seqs = [bytes(n.matrix[name]) for name in n.taxlabels] + seqs, coordinates = Alignment.parse_printed_alignment(aligned_seqs) + records = [ + SeqRecord(Seq(seq), id=name, annotations=annotations) + for seq, name in zip(seqs, n.unaltered_taxlabels) + ] + # Remove columns consisting of gaps only + steps = np.diff(coordinates, 1).max(0) + indices = np.nonzero(steps == 0)[0] + 1 + coordinates = np.delete(coordinates, indices, 1) + alignment = Alignment(records, coordinates) + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/phylip.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/phylip.py new file mode 100644 index 0000000000000000000000000000000000000000..13a1598af4f7b7f41830cf576b97f40ccdf40cee --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/phylip.py @@ -0,0 +1,181 @@ +# Copyright 2006-2016 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for the alignment format for input files for PHYLIP tools. + +You are expected to use this module via the Bio.Align functions. +""" + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +_PHYLIP_ID_WIDTH = 10 + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Clustalw alignment writer.""" + + fmt = "PHYLIP" + + def format_alignment(self, alignment): + """Return a string with a single alignment in the Phylip format.""" + names = [] + for record in alignment.sequences: + try: + name = record.id + except AttributeError: + name = "" + else: + name = name.strip() + for char in "[](),": + name = name.replace(char, "") + for char in ":;": + name = name.replace(char, "|") + name = name[:_PHYLIP_ID_WIDTH] + names.append(name) + + lines = [] + nseqs, length = alignment.shape + if nseqs == 0: + raise ValueError("Must have at least one sequence") + if length == 0: + raise ValueError("Non-empty sequences are required") + line = "%d %d\n" % (nseqs, length) + lines.append(line) + + # From experimentation, the use of tabs is not understood by the + # EMBOSS suite. The nature of the expected white space is not + # defined in the PHYLIP documentation, simply "These are in free + # format, separated by blanks". We'll use spaces to keep EMBOSS + # happy. + for name, sequence in zip(names, alignment): + # Write the entire sequence to one line + line = name[:_PHYLIP_ID_WIDTH].ljust(_PHYLIP_ID_WIDTH) + sequence + "\n" + lines.append(line) + return "".join(lines) + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Reads a Phylip alignment file and returns an Alignment iterator. + + Record names are limited to at most 10 characters. + + The parser determines from the file contents if the file format is + sequential or interleaved, and parses the file accordingly. + + For more information on the file format, please see: + http://evolution.genetics.washington.edu/phylip/doc/sequence.html + http://evolution.genetics.washington.edu/phylip/doc/main.html#inputfiles + """ + + fmt = "PHYLIP" + + def _read_header(self, stream): + line = stream.readline() + if not line: + raise ValueError("Empty file.") from None + + words = line.split() + if len(words) == 2: + try: + self._number_of_seqs = int(words[0]) + self._length_of_seqs = int(words[1]) + return + except ValueError: + pass + raise ValueError( + "Expected two integers in the first line, received '%s'" % line + ) + + def _parse_interleaved_first_block(self, lines, seqs, names): + for line in lines: + line = line.rstrip() + name = line[:_PHYLIP_ID_WIDTH].strip() + seq = line[_PHYLIP_ID_WIDTH:].strip().replace(" ", "") + names.append(name) + seqs.append([seq]) + + def _parse_interleaved_other_blocks(self, stream, seqs): + i = 0 + for line in stream: + line = line.rstrip() + if not line: + assert i == self._number_of_seqs + i = 0 + else: + seq = line.replace(" ", "") + seqs[i].append(seq) + i += 1 + if i != 0 and i != self._number_of_seqs: + raise ValueError("Unexpected file format") + + def _parse_sequential(self, lines, seqs, names, length): + for line in lines: + if length == 0: + line = line.rstrip() + name = line[:_PHYLIP_ID_WIDTH].strip() + seq = line[_PHYLIP_ID_WIDTH:].strip() + names.append(name) + seqs.append([]) + else: + seq = line.strip() + seq = seq.replace(" ", "") + seqs[-1].append(seq) + length += len(seq) + if length == self._length_of_seqs: + length = 0 + return length + + def _read_file(self, stream): + names = [] + seqs = [] + lines = [stream.readline() for i in range(self._number_of_seqs)] + line = stream.readline() + if line.rstrip(): + # sequential file format + lines.append(line) + length = self._parse_sequential(lines, seqs, names, 0) + self._parse_sequential(stream, seqs, names, length) + else: + # interleaved file format + self._parse_interleaved_first_block(lines, seqs, names) + self._parse_interleaved_other_blocks(stream, seqs) + return names, seqs + + def _read_next_alignment(self, stream): + try: + self._number_of_seqs + except AttributeError: + return + names, seqs = self._read_file(stream) + + seqs = ["".join(seq) for seq in seqs] + if len(seqs) != self._number_of_seqs: + raise ValueError( + "Found %i records in this alignment, told to expect %i" + % (len(seqs), self._number_of_seqs) + ) + for seq in seqs: + if len(seq) != self._length_of_seqs: + raise ValueError( + "Expected all sequences to have length %d; found %d" + % (self._length_of_seqs, len(seq)) + ) + if "." in seq: + raise ValueError("PHYLIP format no longer allows dots in sequence") + + seqs = [seq.encode() for seq in seqs] + seqs, coordinates = Alignment.parse_printed_alignment(seqs) + records = [ + SeqRecord(Seq(seq), id=name, description="") + for (name, seq) in zip(names, seqs) + ] + alignment = Alignment(records, coordinates) + del self._number_of_seqs + del self._length_of_seqs + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/psl.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/psl.py new file mode 100644 index 0000000000000000000000000000000000000000..c714ca83118aa4e3f318c2bcadfdc9807d22305b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/psl.py @@ -0,0 +1,541 @@ +# Copyright 2022 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for the "psl" pairwise alignment format. + +The Pattern Space Layout (PSL) format, described by UCSC, stores a series +of pairwise alignments in a single file. Typically they are used for +transcript to genome alignments. PSL files store the alignment positions +and alignment scores, but do not store the aligned sequences. + +See http://genome.ucsc.edu/FAQ/FAQformat.html#format2 + +You are expected to use this module via the Bio.Align functions. + +Coordinates in the PSL format are defined in terms of zero-based start +positions (like Python) and aligning region sizes. + +A minimal aligned region of length one and starting at first position in the +source sequence would have ``start == 0`` and ``size == 1``. + +As we can see in this example, ``start + size`` will give one more than the +zero-based end position. We can therefore manipulate ``start`` and +``start + size`` as python list slice boundaries. +""" + +from itertools import chain + +import numpy as np + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import reverse_complement +from Bio.Seq import Seq +from Bio.Seq import UndefinedSequenceError +from Bio.SeqFeature import CompoundLocation +from Bio.SeqFeature import ExactPosition +from Bio.SeqFeature import SeqFeature +from Bio.SeqFeature import SimpleLocation +from Bio.SeqRecord import SeqRecord + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Alignment file writer for the Pattern Space Layout (PSL) file format.""" + + fmt = "PSL" + + def __init__(self, target, header=True, mask=None, wildcard="N"): + """Create an AlignmentWriter object. + + Arguments: + - target - output stream or file name + - header - If True (default), write the PSL header consisting of + five lines containing the PSL format version and a + header for each column. + If False, suppress the PSL header, resulting in a simple + tab-delimited file. + - mask - Specify if repeat regions in the target sequence are + masked and should be reported in the `repMatches` field + of the PSL file instead of in the `matches` field. + Acceptable values are + None : no masking (default); + "lower": masking by lower-case characters; + "upper": masking by upper-case characters. + - wildcard - Report alignments to the wildcard character in the + target or query sequence in the `nCount` field of the + PSL file instead of in the `matches`, `misMatches`, or + `repMatches` fields. + Default value is 'N'. + + """ + super().__init__(target) + self.header = header + if wildcard is not None: + if mask == "upper": + wildcard = ord(wildcard.lower()) + else: + wildcard = ord(wildcard.upper()) + self.wildcard = wildcard + self.mask = mask + + def write_header(self, stream, alignments): + """Write the PSL header.""" + if not self.header: + return + try: + metadata = alignments.metadata + except AttributeError: + version = "3" + else: + version = metadata.get("psLayout version", "3") + # fmt: off + stream.write( + f"""\ +psLayout version {version} + +match mis- rep. N's Q gap Q gap T gap T gap strand Q Q Q Q T T T T block blockSizes qStarts tStarts + match match count bases count bases name size start end name size start end count +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +""" # noqa: W191, E101 + ) + # fmt: on + + def format_alignment(self, alignment): + """Return a string with a single alignment formatted as one PSL line.""" + if not isinstance(alignment, Alignment): + raise TypeError("Expected an Alignment object") + coordinates = alignment.coordinates + if not coordinates.size: # alignment consists of gaps only + return "" + target, query = alignment.sequences + try: + qName = query.id + except AttributeError: + qName = "query" + try: + query = query.seq + except AttributeError: + pass + try: + tName = target.id + except AttributeError: + tName = "target" + try: + target = target.seq + except AttributeError: + pass + tSize = len(target) + qSize = len(query) + steps = abs(np.diff(coordinates, 1)) + aligned = steps.min(0) > 0 + tCount, qCount = steps[:, aligned].sum(1) + if tCount == qCount: + dnax = False + if coordinates[0, 0] > coordinates[0, -1]: + coordinates = coordinates[:, ::-1] + if coordinates[1, 0] > coordinates[1, -1]: + # DNA/RNA mapped to reverse strand of DNA/RNA + strand = "-" + query = reverse_complement(query) + coordinates = coordinates.copy() + coordinates[1, :] = qSize - coordinates[1, :] + else: + # mapped to forward strand + strand = "+" + elif tCount == 3 * qCount: + dnax = True + if coordinates[0, 0] > coordinates[0, -1]: + # protein mapped to reverse strand of DNA + strand = "-" + target = reverse_complement(target) + coordinates = coordinates.copy() + coordinates[0, :] = tSize - coordinates[0, :] + else: + # mapped to forward strand + strand = "+" + else: + raise ValueError("inconsistent step sizes %d, %d" % (tCount, qCount)) + # fmt: on + wildcard = self.wildcard + mask = self.mask + # variable names follow those in the PSL file format specification + matches = 0 + misMatches = 0 + repMatches = 0 + nCount = 0 + qNumInsert = 0 + qBaseInsert = 0 + tNumInsert = 0 + tBaseInsert = 0 + blockSizes = [] + qStarts = [] + tStarts = [] + tStart, qStart = coordinates[:, 0] + for tEnd, qEnd in coordinates[:, 1:].transpose(): + if tStart == tEnd: + if qStart > 0 and qEnd < qSize: + qNumInsert += 1 + qBaseInsert += qEnd - qStart + qStart = qEnd + elif qStart == qEnd: + if tStart > 0 and tEnd < tSize: + tNumInsert += 1 + tBaseInsert += tEnd - tStart + tStart = tEnd + else: + tCount = tEnd - tStart + qCount = qEnd - qStart + tStarts.append(tStart) + qStarts.append(qStart) + blockSizes.append(qCount) + if tCount == qCount: + assert dnax is False + else: + # translated DNA aligned to protein, typically generated by + # blat -t=dnax -q=prot + assert tCount == 3 * qCount + assert dnax is True + tSeq = target[tStart:tEnd] + qSeq = query[qStart:qEnd] + try: + tSeq = bytes(tSeq) + except TypeError: # string + tSeq = bytes(tSeq, "ASCII") + except UndefinedSequenceError: # sequence contents is unknown + tSeq = None + try: + qSeq = bytes(qSeq) + except TypeError: # string + qSeq = bytes(qSeq, "ASCII") + except UndefinedSequenceError: # sequence contents is unknown + qSeq = None + if tSeq is None or qSeq is None: + # contents of at least one sequence is unknown; + # count all aligned letters as matches: + matches += qCount + else: + if mask == "lower": + for u1, u2, c1 in zip(tSeq.upper(), qSeq.upper(), tSeq): + if u1 == wildcard or u2 == wildcard: + nCount += 1 + elif u1 == u2: + if u1 == c1: + matches += 1 + else: + repMatches += 1 + else: + misMatches += 1 + elif mask == "upper": + for u1, u2, c1 in zip(tSeq.lower(), qSeq.lower(), tSeq): + if u1 == wildcard or u2 == wildcard: + nCount += 1 + elif u1 == u2: + if u1 == c1: + matches += 1 + else: + repMatches += 1 + else: + misMatches += 1 + else: + for u1, u2 in zip(tSeq.upper(), qSeq.upper()): + if u1 == wildcard or u2 == wildcard: + nCount += 1 + elif u1 == u2: + matches += 1 + else: + misMatches += 1 + tStart = tEnd + qStart = qEnd + try: + matches = alignment.matches + except AttributeError: + pass + try: + misMatches = alignment.misMatches + except AttributeError: + pass + try: + repMatches = alignment.repMatches + except AttributeError: + pass + try: + nCount = alignment.nCount + except AttributeError: + pass + tStart = tStarts[0] # start of alignment in target + qStart = qStarts[0] # start of alignment in query + tEnd = tStarts[-1] + tCount # end of alignment in target + qEnd = qStarts[-1] + qCount # end of alignment in query + if strand == "-": + if dnax is True: + tStart, tEnd = tSize - tEnd, tSize - tStart + else: + qStart, qEnd = qSize - qEnd, qSize - qStart + blockCount = len(blockSizes) + blockSizes = ",".join(map(str, blockSizes)) + "," + qStarts = ",".join(map(str, qStarts)) + "," + tStarts = ",".join(map(str, tStarts)) + "," + if dnax: + strand = "+" + strand + words = [ + str(matches), + str(misMatches), + str(repMatches), + str(nCount), + str(qNumInsert), + str(qBaseInsert), + str(tNumInsert), + str(tBaseInsert), + strand, + qName, + str(qSize), + str(qStart), + str(qEnd), + tName, + str(tSize), + str(tStart), + str(tEnd), + str(blockCount), + blockSizes, + qStarts, + tStarts, + ] + line = "\t".join(words) + "\n" + return line + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Alignment iterator for Pattern Space Layout (PSL) files. + + Each line in the file contains one pairwise alignment, which are loaded + and returned incrementally. Alignment score information such as the number + of matches and mismatches are stored as attributes of each alignment. + """ + + fmt = "PSL" + + def _read_header(self, stream): + line = stream.readline() + if line.startswith("psLayout "): + words = line.split() + if words[1] != "version": + raise ValueError("Unexpected word '%s' in header line" % words[1]) + self.metadata = {"psLayout version": words[2]} + line = stream.readline() + line = stream.readline() + line = stream.readline() + line = stream.readline() + if line.lstrip("-").strip() != "": + raise ValueError("End of header not found") + else: + self._line = line + + def _read_next_alignment(self, stream): + try: + line = self._line + except AttributeError: + lines = stream + else: + del self._line + lines = chain([line], stream) + for line in lines: + words = line.split() + if len(words) == 23: + pslx = True + elif len(words) == 21: + pslx = False + else: + raise ValueError("line has %d columns; expected 21 or 23" % len(words)) + strand = words[8] + qName = words[9] + qSize = int(words[10]) + tName = words[13] + tSize = int(words[14]) + blockCount = int(words[17]) + blockSizes = [ + int(blockSize) for blockSize in words[18].rstrip(",").split(",") + ] + qStarts = [int(start) for start in words[19].rstrip(",").split(",")] + tStarts = [int(start) for start in words[20].rstrip(",").split(",")] + if len(blockSizes) != blockCount: + raise ValueError( + "Inconsistent number of blocks (%d found, expected %d)" + % (len(blockSizes), blockCount) + ) + if len(qStarts) != blockCount: + raise ValueError( + "Inconsistent number of query start positions (%d found, expected %d)" + % (len(qStarts), blockCount) + ) + if len(tStarts) != blockCount: + raise ValueError( + "Inconsistent number of target start positions (%d found, expected %d)" + % (len(tStarts), blockCount) + ) + qStarts = np.array(qStarts) + tStarts = np.array(tStarts) + qBlockSizes = np.array(blockSizes) + if strand in ("++", "+-"): + # protein sequence aligned against translated DNA sequence + tBlockSizes = 3 * qBlockSizes + else: + tBlockSizes = qBlockSizes + qPosition = qStarts[0] + tPosition = tStarts[0] + coordinates = [[tPosition, qPosition]] + for tBlockSize, qBlockSize, tStart, qStart in zip( + tBlockSizes, qBlockSizes, tStarts, qStarts + ): + if tStart != tPosition: + coordinates.append([tStart, qPosition]) + tPosition = tStart + if qStart != qPosition: + coordinates.append([tPosition, qStart]) + qPosition = qStart + tPosition += tBlockSize + qPosition += qBlockSize + coordinates.append([tPosition, qPosition]) + coordinates = np.array(coordinates, np.intp).transpose() + qNumInsert = 0 + qBaseInsert = 0 + tNumInsert = 0 + tBaseInsert = 0 + tStart, qStart = coordinates[:, 0] + for tEnd, qEnd in coordinates[:, 1:].transpose(): + tCount = tEnd - tStart + qCount = qEnd - qStart + if tCount == 0: + if qStart > 0 and qEnd < qSize: + qNumInsert += 1 + qBaseInsert += qCount + qStart = qEnd + elif qCount == 0: + if tStart > 0 and tEnd < tSize: + tNumInsert += 1 + tBaseInsert += tCount + tStart = tEnd + else: + tStart = tEnd + qStart = qEnd + if qNumInsert != int(words[4]): + raise ValueError( + "Inconsistent qNumInsert found (%s, expected %d)" + % (words[4], qNumInsert) + ) + if qBaseInsert != int(words[5]): + raise ValueError( + "Inconsistent qBaseInsert found (%s, expected %d)" + % (words[5], qBaseInsert) + ) + if tNumInsert != int(words[6]): + raise ValueError( + "Inconsistent tNumInsert found (%s, expected %d)" + % (words[6], tNumInsert) + ) + if tBaseInsert != int(words[7]): + raise ValueError( + "Inconsistent tBaseInsert found (%s, expected %d)" + % (words[7], tBaseInsert) + ) + qStart = int(words[11]) + qEnd = int(words[12]) + tStart = int(words[15]) + tEnd = int(words[16]) + if strand == "-": + qStart, qEnd = qEnd, qStart + coordinates[1, :] = qSize - coordinates[1, :] + elif strand == "+-": + tStart, tEnd = tEnd, tStart + coordinates[0, :] = tSize - coordinates[0, :] + if tStart != coordinates[0, 0]: + raise ValueError( + "Inconsistent tStart found (%d, expected %d)" + % (tStart, coordinates[0, 0]) + ) + if tEnd != coordinates[0, -1]: + raise ValueError( + "Inconsistent tEnd found (%d, expected %d)" + % (tEnd, coordinates[0, -1]) + ) + if qStart != coordinates[1, 0]: + raise ValueError( + "Inconsistent qStart found (%d, expected %d)" + % (qStart, coordinates[1, 0]) + ) + if qEnd != coordinates[1, -1]: + raise ValueError( + "Inconsistent qEnd found (%d, expected %d)" + % (qEnd, coordinates[1, -1]) + ) + feature = None + if pslx is True: + qSeqs = words[21].rstrip(",").split(",") + tSeqs = words[22].rstrip(",").split(",") + qSeq = dict(zip(qStarts, qSeqs)) + if strand in ("++", "+-"): + # protein sequence aligned against translated DNA sequence + target_sequence = Seq(None, length=tSize) + query_sequence = Seq(qSeq, length=qSize) + if strand == "++": + tStart, qStart = coordinates[:, 0] + locations = [] + for tEnd, qEnd in coordinates[:, 1:].transpose(): + if qStart < qEnd and tStart < tEnd: + location = SimpleLocation( + ExactPosition(tStart), + ExactPosition(tEnd), + strand=+1, + ) + locations.append(location) + qStart = qEnd + tStart = tEnd + if len(locations) > 1: + location = CompoundLocation(locations, "join") + tSeq = "".join(tSeqs) + qualifiers = {"translation": [tSeq]} + feature = SeqFeature( + location, type="CDS", qualifiers=qualifiers + ) + elif strand == "+-": + tEnd, qStart = coordinates[:, 0] + locations = [] + for tStart, qEnd in coordinates[:, 1:].transpose(): + if qStart < qEnd and tStart < tEnd: + location = SimpleLocation( + ExactPosition(tStart), + ExactPosition(tEnd), + strand=-1, + ) + locations.append(location) + tEnd = tStart + qStart = qEnd + if len(locations) > 1: + location = CompoundLocation(locations, "join") + tSeq = "".join(tSeqs) + qualifiers = {"translation": [tSeq]} + feature = SeqFeature( + location, type="CDS", qualifiers=qualifiers + ) + else: + tSeq = dict(zip(tStarts, tSeqs)) + target_sequence = Seq(tSeq, length=tSize) + query_sequence = Seq(qSeq, length=qSize) + if strand == "-": + query_sequence = query_sequence.reverse_complement() + else: + target_sequence = Seq(None, length=tSize) + query_sequence = Seq(None, length=qSize) + target_record = SeqRecord(target_sequence, id=tName, description="") + query_record = SeqRecord(query_sequence, id=qName, description="") + if feature is not None: + target_record.features.append(feature) + records = [target_record, query_record] + alignment = Alignment(records, coordinates) + alignment.matches = int(words[0]) + alignment.misMatches = int(words[1]) + alignment.repMatches = int(words[2]) + alignment.nCount = int(words[3]) + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/sam.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/sam.py new file mode 100644 index 0000000000000000000000000000000000000000..3ccf84e930ea81d8125dd504c696d2aa64056cde --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/sam.py @@ -0,0 +1,765 @@ +# Copyright 2022 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for the "sam" pairwise alignment format. + +The Sequence Alignment/Map (SAM) format, created by Heng Li and Richard Durbin +at the Wellcome Trust Sanger Institute, stores a series of alignments to the +genome in a single file. Typically they are used for next-generation sequencing +data. SAM files store the alignment positions for mapped sequences, and may +also store the aligned sequences and other information associated with the +sequence. + +See http://www.htslib.org/ for more information. + +You are expected to use this module via the Bio.Align functions. + +Coordinates in the SAM format are defined in terms of one-based start +positions; the parser converts these to zero-based coordinates to be consistent +with Python and other alignment formats. +""" + +import copy +from itertools import chain + +import numpy as np + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import reverse_complement +from Bio.Seq import Seq +from Bio.Seq import UndefinedSequenceError +from Bio.SeqRecord import SeqRecord + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Alignment file writer for the Sequence Alignment/Map (SAM) file format.""" + + fmt = "SAM" + + def __init__(self, target, md=False): + """Create an AlignmentWriter object. + + Arguments: + - md - If True, calculate the MD tag from the alignment and include it + in the output. + If False (default), do not include the MD tag in the output. + + """ + super().__init__(target) + self.md = md + + def write_header(self, stream, alignments): + """Write the SAM header.""" + try: + metadata = alignments.metadata + except AttributeError: + metadata = {} + try: + targets = alignments.targets + except AttributeError: + targets = {} + values = metadata.get("HD") + if values is not None: + # if HD is present, then VN is required and must come first + fields = ["@HD", "VN:%s" % values["VN"]] + for key, value in values.items(): + if key == "VN": + continue + fields.append("%s:%s" % (key, value)) + line = "\t".join(fields) + "\n" + stream.write(line) + for record in targets: + fields = ["@SQ"] + fields.append("SN:%s" % record.id) + length = len(record.seq) + fields.append("LN:%d" % length) + for key, value in record.annotations.items(): + if key == "alternate_locus": + fields.append("AH:%s" % value) + elif key == "names": + fields.append("AN:%s" % ",".join(value)) + elif key == "assembly": + fields.append("AS:%s" % value) + elif key == "MD5": + fields.append("M5:%s" % value) + elif key == "species": + fields.append("SP:%s" % value) + elif key == "topology": + assert value in ("linear", "circular") + fields.append("PP:%s" % value) + elif key == "URI": + fields.append("UR:%s" % value) + else: + fields.append("%s:%s" % (key[:2], value)) + try: + description = record.description + except AttributeError: + pass + else: + if description != "": + fields.append("DS:%s" % description) + line = "\t".join(fields) + "\n" + stream.write(line) + for tag, rows in metadata.items(): + if tag == "HD": # already written + continue + for row in rows: + fields = ["@" + tag] + for key, value in row.items(): + fields.append("%s:%s" % (key, value)) + line = "\t".join(fields) + "\n" + stream.write(line) + + def format_alignment(self, alignment, md=None): + """Return a string with a single alignment formatted as one SAM line.""" + if not isinstance(alignment, Alignment): + raise TypeError("Expected an Alignment object") + coordinates = alignment.coordinates.transpose() + target, query = alignment.sequences + hard_clip_left = None + hard_clip_right = None + try: + qName = query.id + except AttributeError: + qName = "query" + qual = "*" + else: + try: + hard_clip_left = query.annotations["hard_clip_left"] + except (AttributeError, KeyError): + pass + try: + hard_clip_right = query.annotations["hard_clip_right"] + except (AttributeError, KeyError): + pass + try: + phred = query.letter_annotations["phred_quality"] + except (AttributeError, KeyError): + qual = "*" + else: + qual = "".join(chr(value + 33) for value in phred) + query = query.seq + qSize = len(query) + try: + rname = target.id + except AttributeError: + rname = "target" + else: + target = target.seq + if coordinates[0, 0] > coordinates[-1, 0]: + coordinates = coordinates[::-1, :] + if coordinates[0, 1] < coordinates[-1, 1]: # mapped to forward strand + flag = 0 + else: # mapped to reverse strand + flag = 16 + query = reverse_complement(query) + coordinates = np.array(coordinates, np.intp) + coordinates[:, 1] = qSize - coordinates[:, 1] + hard_clip_left, hard_clip_right = hard_clip_right, hard_clip_left + try: + flag |= alignment.flag + except AttributeError: + pass + try: + query = bytes(query) + except TypeError: # string + pass + except UndefinedSequenceError: + query = "*" + else: + query = str(query, "ASCII") + tStart, qStart = coordinates[0, :] + pos = tStart + 1 # 1-based coordinate + cigar = "" + if hard_clip_left is not None: + cigar += "%dH" % hard_clip_left + if qStart > 0: + cigar += "%dS" % qStart + try: + operations = alignment.operations + except AttributeError: + operations = None + for tEnd, qEnd in coordinates[1:, :]: + tCount = tEnd - tStart + qCount = qEnd - qStart + if tCount == 0: + cigar += "%dI" % qCount # insertion to the reference + qStart = qEnd + elif qCount == 0: + cigar += "%dD" % tCount # deletion from the reference + tStart = tEnd + else: + if tCount != qCount: + raise ValueError("Unequal step sizes in alignment") + cigar += "%dM" % tCount + tStart = tEnd + qStart = qEnd + else: + for operation, (tEnd, qEnd) in zip(operations, coordinates[1:, :]): + tCount = tEnd - tStart + qCount = qEnd - qStart + if tCount == 0: + assert operation == ord("I") + cigar += "%dI" % qCount # insertion to the reference + qStart = qEnd + elif qCount == 0: + if operation == ord("N"): + cigar += "%dN" % tCount # skipped region from the reference + elif operation == ord("D"): + cigar += "%dD" % tCount # deletion from the reference + else: + raise ValueError(f"Unexpected operation {operation}") + tStart = tEnd + else: + if tCount != qCount: + raise ValueError("Unequal step sizes in alignment") + assert operation == ord("M") + cigar += "%dM" % tCount + tStart = tEnd + qStart = qEnd + if qEnd < qSize: + cigar += "%dS" % (qSize - qEnd) + if hard_clip_right is not None: + cigar += "%dH" % hard_clip_right + try: + mapq = alignment.mapq + except AttributeError: + mapq = 255 # not available + try: + rnext = alignment.rnext + except AttributeError: + rnext = "*" + else: + if rnext == rname: + rnext = "=" + try: + pnext = alignment.pnext + except AttributeError: + pnext = 0 + else: + pnext += 1 # 1-based coordinates + tLen = 0 + fields = [ + qName, + str(flag), + rname, + str(pos), + str(mapq), + cigar, + rnext, + str(pnext), + str(tLen), + query, + qual, + ] + if md is None: + md = self.md + if md is True: + if query == "*": + raise ValueError("requested MD tag with undefined sequence") + # calculate the MD tag from the alignment coordinates and sequences + tStart, qStart = coordinates[0, :] + number = 0 + md = "" + if operations is None: + for tEnd, qEnd in coordinates[1:, :]: + tCount = tEnd - tStart + qCount = qEnd - qStart + if tCount == 0: + # insertion to the reference + qStart = qEnd + elif qCount == 0: + if True: + # deletion from the reference + if number: + md += str(number) + number = 0 + md += "^" + target[tStart:tEnd] + tStart = tEnd + else: + # alignment match + if tCount != qCount: + raise ValueError("Unequal step sizes in alignment") + for tc, qc in zip(target[tStart:tEnd], query[qStart:qEnd]): + if tc == qc: + number += 1 + else: + md += str(number) + tc + number = 0 + tStart = tEnd + qStart = qEnd + if number: + md += str(number) + else: + for operation, (tEnd, qEnd) in zip(operations, coordinates[1:, :]): + tCount = tEnd - tStart + qCount = qEnd - qStart + if tCount == 0: + # insertion to the reference + qStart = qEnd + elif qCount == 0: + if operation != ord("N"): + # deletion from the reference + if number: + md += str(number) + number = 0 + md += "^" + target[tStart:tEnd] + tStart = tEnd + else: + # alignment match + if tCount != qCount: + raise ValueError("Unequal step sizes in alignment") + for tc, qc in zip(target[tStart:tEnd], query[qStart:qEnd]): + if tc == qc: + number += 1 + else: + md += str(number) + tc + number = 0 + tStart = tEnd + qStart = qEnd + if number: + md += str(number) + field = "MD:Z:%s" % md + fields.append(field) + try: + score = alignment.score + except AttributeError: + pass + else: + field = "AS:i:%.0f" % score + fields.append(field) + try: + annotations = alignment.annotations + except AttributeError: + pass + else: + for key, value in annotations.items(): + if isinstance(value, int): + datatype = "i" + value = str(value) + elif isinstance(value, float): + datatype = "f" + value = str(value) + elif isinstance(value, str): + if len(value) == 1: + datatype = "A" + else: + datatype = "Z" + elif isinstance(value, bytes): + datatype = "H" + value = "".join(map(str, value)) + elif isinstance(value, np.array): + datatype = "B" + if np.issubdtype(value.dtype, np.integer): + pass + elif np.issubdtype(value.dtype, float): + pass + else: + raise ValueError( + f"Array of incompatible data type {value.dtype} in annotation '{key}'" + ) + value = "".join(map(str, value)) + field = f"{key}:{datatype}:{value}" + fields.append(field) + line = "\t".join(fields) + "\n" + return line + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Alignment iterator for Sequence Alignment/Map (SAM) files. + + Each line in the file contains one genomic alignment, which are loaded + and returned incrementally. The following columns are stored as attributes + of the alignment: + + - flag: The FLAG combination of bitwise flags; + - mapq: Mapping Quality (only stored if available) + - rnext: Reference sequence name of the primary alignment of the next read + in the alignment (only stored if available) + - pnext: Zero-based position of the primary alignment of the next read in + the template (only stored if available) + - tlen: signed observed template length (only stored if available) + + Other information associated with the alignment by its tags are stored in + the annotations attribute of each alignment. + + Any hard clipping (clipped sequences not present in the query sequence) + are stored as 'hard_clip_left' and 'hard_clip_right' in the annotations + dictionary attribute of the query sequence record. + + The sequence quality, if available, is stored as 'phred_quality' in the + letter_annotations dictionary attribute of the query sequence record. + """ + + fmt = "SAM" + + def _read_header(self, stream): + self.metadata = {} + self.targets = [] + for line in stream: + if not line.startswith("@"): + self._line = line + break + fields = line[1:].strip().split("\t") + tag = fields[0] + values = {} + if tag == "SQ": + annotations = {} + description = None + for field in fields[1:]: + key, value = field.split(":", 1) + assert len(key) == 2 + if key == "SN": + rname = value + elif key == "LN": + length = int(value) + elif key == "AH": + annotations["alternate_locus"] = value + elif key == "AN": + annotations["names"] = value.split(",") + elif key == "AS": + annotations["assembly"] = value + elif key == "DS": + description = value + elif key == "M5": + annotations["MD5"] = value + elif key == "SP": + annotations["species"] = value + elif key == "TP": + assert value in ("linear", "circular") + annotations["topology"] = value + elif key == "UR": + annotations["URI"] = value + else: + annotations[key] = value + sequence = Seq(None, length=length) + record = SeqRecord( + sequence, id=rname, description="", annotations=annotations + ) + if description is not None: + record.description = description + self.targets.append(record) + else: + for field in fields[1:]: + key, value = field.split(":", 1) + assert len(key) == 2 + values[key] = value + if tag == "HD": + self.metadata[tag] = values + else: + if tag not in self.metadata: + self.metadata[tag] = [] + self.metadata[tag].append(values) + self._target_indices = { + record.id: index for index, record in enumerate(self.targets) + } + + def _read_next_alignment(self, stream): + try: + line = self._line + except AttributeError: + lines = stream + else: + lines = chain([line], stream) + del self._line + for line in lines: + fields = line.split() + if len(fields) < 11: + raise ValueError( + "line has %d columns; expected at least 11" % len(fields) + ) + qname = fields[0] + flag = int(fields[1]) + rname = fields[2] + target_pos = int(fields[3]) - 1 + mapq = int(fields[4]) + cigar = fields[5] + rnext = fields[6] + pnext = int(fields[7]) - 1 + tlen = int(fields[8]) + query = fields[9] + qual = fields[10] + md = None + score = None + annotations = {} + for field in fields[11:]: + tag, datatype, value = field.split(":", 2) + if tag == "AS": + assert datatype == "i" + score = int(value) + elif tag == "MD": + assert datatype == "Z" + md = value + else: + if datatype == "i": + value = int(value) + elif datatype == "f": + value = float(value) + elif datatype in ("A", "Z"): # string + pass + elif datatype == "H": + n = len(value) + value = bytes(int(value[i : i + 2]) for i in range(0, n, 2)) + elif datatype == "B": + letter = value[0] + value = value[1:].split(",") + if letter in "cCsSiI": + dtype = int + elif letter == "f": + dtype = float + else: + raise ValueError( + f"Unknown number type '{letter}' in tag '{field}'" + ) + value = np.array(value, dtype) + annotations[tag] = value + if flag & 0x10: + strand = "-" + else: + strand = "+" + hard_clip_left = None + hard_clip_right = None + store_operations = False + if flag & 0x4: # unmapped + target = None + coordinates = None + elif md is None: + query_pos = 0 + coordinates = [[target_pos, query_pos]] + number = "" + operations = bytearray() + for letter in cigar: + if letter == "M": + # M: alignment match + length = int(number) + target_pos += length + query_pos += length + elif letter in "=X": + # =: sequence match + # X: sequence mismatch + length = int(number) + target_pos += length + query_pos += length + store_operations = True + elif letter == "I": + # I: insertion to the reference + length = int(number) + query_pos += length + elif letter == "S": + # S: soft clipping + length = int(number) + if query_pos == 0: + coordinates[0][1] += length + query_pos += length + number = "" + continue + elif letter == "D": + # D: deletion from the reference + length = int(number) + target_pos += length + elif letter == "N": + # N: skipped region from the reference + length = int(number) + target_pos += length + store_operations = True + elif letter == "H": # hard clipping + if query_pos == 0: + hard_clip_left = int(number) + else: + hard_clip_right = int(number) + number = "" + continue + elif letter == "P": # padding + raise NotImplementedError( + "padding operator is not yet implemented" + ) + else: + number += letter + continue + coordinates.append([target_pos, query_pos]) + operations.append(ord(letter)) + number = "" + index = self._target_indices.get(rname) + if index is None: + if self.targets: + raise ValueError(f"Found target {rname} missing from header") + target = SeqRecord(None, id=rname, description="") + else: + target = self.targets[index] + else: + query_pos = 0 + coordinates = [[target_pos, query_pos]] + seq = query + target = "" + starts = [target_pos] + size = 0 + sizes = [] + number = "" + operations = bytearray() + for letter in cigar: + if letter in "M": + # M: alignment match + length = int(number) + target_pos += length + query_pos += length + target += seq[:length] + seq = seq[length:] + size += length + elif letter in "=X": + # =: sequence match + # X: sequence mismatch + length = int(number) + target_pos += length + query_pos += length + target += seq[:length] + seq = seq[length:] + size += length + store_operations = True + elif letter == "I": + # I: insertion to the reference + length = int(number) + query_pos += length + seq = seq[length:] + elif letter == "S": + # S: soft clipping + length = int(number) + if query_pos == 0: + coordinates[0][1] += length + query_pos += length + seq = seq[length:] + number = "" + continue + elif letter == "D": # deletion from the reference + length = int(number) + target_pos += length + size += length + starts.append(target_pos) + sizes.append(size) + size = 0 + elif letter == "N": # skipped region from the reference + length = int(number) + target_pos += length + starts.append(target_pos) + sizes.append(size) + size = 0 + store_operations = True + elif letter == "H": + # hard clipping (clipped sequences not present in sequence) + if query_pos == 0: + hard_clip_left = int(number) + else: + hard_clip_right = int(number) + number = "" + continue + elif letter == "P": # padding + raise NotImplementedError( + "padding operator is not yet implemented" + ) + else: + number += letter + continue + coordinates.append([target_pos, query_pos]) + operations.append(ord(letter)) + number = "" + sizes.append(size) + seq = target + target = "" + number = "" + letters = iter(md) + for letter in letters: + if letter in "ACGTNacgtn": + if number: + number = int(number) + target += seq[:number] + seq = seq[number:] + number = "" + target += letter + seq = seq[1:] + elif letter == "^": + if number: + number = int(number) + target += seq[:number] + seq = seq[number:] + number = "" + for letter in letters: + if letter not in "ACGTNacgtn": + break + target += letter + else: + break + number = letter + else: + number += letter + if number: + number = int(number) + target += seq[:number] + seq = target + rname_target = self.targets[self._target_indices[rname]] + length = len(rname_target.seq) + data = {} + index = 0 + for start, size in zip(starts, sizes): + data[start] = seq[index : index + size] + index += size + + target = SeqRecord._from_validated( + Seq(data, length=length), + rname_target.id, + rname_target.name, + rname_target.description, + annotations={ + key: copy.copy(val) + for key, val in rname_target.annotations.items() + }, + ) + if coordinates is not None: + coordinates = np.array(coordinates, np.intp).transpose() + if strand == "-": + coordinates[1, :] = query_pos - coordinates[1, :] + if query == "*": + length = query_pos + sequence = Seq(None, length=length) + else: + sequence = Seq(query) + if not (flag & 0x4): # not unmapped + assert len(query) == query_pos + if strand == "-": + sequence = sequence.reverse_complement() + query = SeqRecord(sequence, id=qname, description="") + if strand == "-": + hard_clip_left, hard_clip_right = hard_clip_right, hard_clip_left + if hard_clip_left is not None: + query.annotations["hard_clip_left"] = hard_clip_left + if hard_clip_right is not None: + query.annotations["hard_clip_right"] = hard_clip_right + if qual != "*": + phred = [ord(c) - 33 for c in qual] + query.letter_annotations["phred_quality"] = phred + records = [target, query] + alignment = Alignment(records, coordinates) + alignment.flag = flag + if mapq != 255: + alignment.mapq = mapq + if rnext == "=": + alignment.rnext = rname + elif rnext != "*": + alignment.rnext = rnext + if pnext >= 0: + alignment.pnext = pnext + if tlen != 0: + alignment.tlen = tlen + if score is not None: + alignment.score = score + if annotations: + alignment.annotations = annotations + if hard_clip_left is not None: + alignment.hard_clip_left = hard_clip_left + if hard_clip_right is not None: + alignment.hard_clip_right = hard_clip_right + if store_operations: + alignment.operations = operations + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/stockholm.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/stockholm.py new file mode 100644 index 0000000000000000000000000000000000000000..9667a554b5759f9cfafab6273aa91c05af3ddddc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/stockholm.py @@ -0,0 +1,624 @@ +# Copyright 2006-2016 by Peter Cock. All rights reserved. +# Copyright 2021 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for alignment files in the Stockholm file format. + +You are expected to use this module via the Bio.Align functions. + +For example, consider this alignment from PFAM for the HAT helix motif:: + + # STOCKHOLM 1.0 + #=GF ID HAT + #=GF AC PF02184.18 + #=GF DE HAT (Half-A-TPR) repeat + #=GF AU SMART; + #=GF SE Alignment kindly provided by SMART + #=GF GA 21.00 21.00; + #=GF TC 21.00 21.00; + #=GF NC 20.90 20.90; + #=GF BM hmmbuild HMM.ann SEED.ann + #=GF SM hmmsearch -Z 57096847 -E 1000 --cpu 4 HMM pfamseq + #=GF TP Repeat + #=GF CL CL0020 + #=GF RN [1] + #=GF RM 9478129 + #=GF RT The HAT helix, a repetitive motif implicated in RNA processing. + #=GF RA Preker PJ, Keller W; + #=GF RL Trends Biochem Sci 1998;23:15-16. + #=GF DR INTERPRO; IPR003107; + #=GF DR SMART; HAT; + #=GF DR SO; 0001068; polypeptide_repeat; + #=GF CC The HAT (Half A TPR) repeat is found in several RNA processing + #=GF CC proteins [1]. + #=GF SQ 3 + #=GS CRN_DROME/191-222 AC P17886.2 + #=GS CLF1_SCHPO/185-216 AC P87312.1 + #=GS CLF1_SCHPO/185-216 DR PDB; 3JB9 R; 185-216; + #=GS O16376_CAEEL/201-233 AC O16376.2 + CRN_DROME/191-222 KEIDRAREIYERFVYVH.PDVKNWIKFARFEES + CLF1_SCHPO/185-216 HENERARGIYERFVVVH.PEVTNWLRWARFEEE + #=GR CLF1_SCHPO/185-216 SS --HHHHHHHHHHHHHHS.--HHHHHHHHHHHHH + O16376_CAEEL/201-233 KEIDRARSVYQRFLHVHGINVQNWIKYAKFEER + #=GC SS_cons --HHHHHHHHHHHHHHS.--HHHHHHHHHHHHH + #=GC seq_cons KEIDRARuIYERFVaVH.P-VpNWIKaARFEEc + // + +Parsing this file using Bio.Align stores the alignment, its annotations, as +well as the sequences and their annotations:: + + >>> from Bio.Align import stockholm + >>> alignments = stockholm.AlignmentIterator("Stockholm/example.sth") + >>> alignment = next(alignments) + >>> alignment.shape + (3, 33) + >>> alignment[0] + 'KEIDRAREIYERFVYVH-PDVKNWIKFARFEES' + +Alignment meta-data are stored in alignment.annotations:: + + >>> alignment.annotations["accession"] + 'PF02184.18' + >>> alignment.annotations["references"][0]["title"] + 'The HAT helix, a repetitive motif implicated in RNA processing.' + +Annotations of alignment columns are stored in alignment.column_annotations:: + + >>> alignment.column_annotations["consensus secondary structure"] + '--HHHHHHHHHHHHHHS.--HHHHHHHHHHHHH' + +Sequences and their annotations are stored in alignment.sequences:: + + >>> alignment.sequences[0].id + 'CRN_DROME/191-222' + >>> alignment.sequences[0].seq + Seq('KEIDRAREIYERFVYVHPDVKNWIKFARFEES') + >>> alignment.sequences[1].letter_annotations["secondary structure"] + '--HHHHHHHHHHHHHHS--HHHHHHHHHHHHH' + +Slicing specific columns of an alignment will slice any per-column-annotations: + + >>> alignment.column_annotations["consensus secondary structure"] + '--HHHHHHHHHHHHHHS.--HHHHHHHHHHHHH' + >>> part_alignment = alignment[:,10:20] + >>> part_alignment.column_annotations["consensus secondary structure"] + 'HHHHHHS.--' +""" + +import textwrap +from collections import defaultdict + +import numpy as np + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Alignment iterator for alignment files in the Stockholm format. + + The file may contain multiple concatenated alignments, which are loaded + and returned incrementally. + + Alignment meta-data (lines starting with #=GF) are stored in the dictionary + alignment.annotations. Column annotations (lines starting with #=GC) are + stored in the dictionary alignment.column_annotations. Sequence names are + stored in record.id. Sequence record meta-data (lines starting with #=GS) + are stored in the dictionary record.annotations. Sequence letter + annotations (lines starting with #=GR) are stored in the dictionary + record.letter_annotations. + + Wrap-around alignments are not supported - each sequence must be on + a single line. + + For more information on the file format, please see: + http://sonnhammer.sbc.su.se/Stockholm.html + https://en.wikipedia.org/wiki/Stockholm_format + """ + + fmt = "Stockholm" + + gf_mapping = { + "ID": "identifier", + "AC": "accession", + "DE": "definition", + "AU": "author", + "SE": "source of seed", + "SS": "source of structure", + "GA": "gathering method", + "TC": "trusted cutoff", + "NC": "noise cutoff", + "BM": "build method", + "SM": "search method", + "TP": "type", + "PI": "previous identifier", + "CC": "comment", + "CL": "clan", + "WK": "wikipedia", + "CB": "calibration method", + "**": "**", # Found in Rfam + } + + gr_mapping = { + "SS": "secondary structure", + "PP": "posterior probability", + "CSA": "Catalytic Site Atlas", # used in CATH + # These features are included in the Stockholm file format + # documentation, but currently not used in the PFAM, RFAM, and CATH + # databases: + "SA": "surface accessibility", + "TM": "transmembrane", + "LI": "ligand binding", + "AS": "active site", + "pAS": "active site - Pfam predicted", + "sAS": "active site - from SwissProt", + "IN": "intron", + } + + gc_mapping = { + "RF": "reference coordinate annotation", + "seq_cons": "consensus sequence", + "scorecons": "consensus score", # used in CATH + "scorecons_70": "consensus score 70", # used in CATH + "scorecons_80": "consensus score 80", # used in CATH + "scorecons_90": "consensus score 90", # used in CATH + # This feature is included in the Stockholm file format + # documentation, but currently not used in the PFAM, RFAM, + # and CATH databases: + "MM": "model mask", + } + # Add *_cons from GR mapping: + for key, value in gr_mapping.items(): + gc_mapping[key + "_cons"] = "consensus " + value + + # These GC keywords are used in Rfam: + for keyword in ( + "RNA_elements", + "RNA_structural_element", + "RNA_structural_elements", + "RNA_ligand_AdoCbl", + "RNA_ligand_AqCbl", + "RNA_ligand_FMN", + "RNA_ligand_Guanidinium", + "RNA_ligand_SAM", + "RNA_ligand_THF_1", + "RNA_ligand_THF_2", + "RNA_ligand_TPP", + "RNA_ligand_preQ1", + "RNA_motif_k_turn", + "Repeat_unit", + "2L3J_B_SS", + "CORE", + "PK", + "PK_SS", + "cons", + ): + gc_mapping[keyword] = keyword.replace("_", " ") + gs_mapping = { + "AC": "accession", + # "DE": description, # handled separately + # "DR": "database_references", # handled separately + "OS": "organism", + # These two features are included in the Stockholm file + # format documentation, but currently not used in the PFAM, + # RFAM, and CATH databases: + "OC": "organism classification", + "LO": "look", + } + + @staticmethod + def _store_per_file_annotations(alignment, gf, rows): + for key, value in gf.items(): + if key == "WK": + lines = iter(value) + references = [] + for line in lines: + reference = "" + while line.endswith("/"): + reference += line[:-1] + line = next(lines) + reference += line + references.append(reference) + value = references + elif key in ("SM", "CC", "**"): + value = " ".join(value) + elif key == "SQ": + assert len(value) == 1 + if int(value.pop()) != rows: + raise ValueError("Inconsistent number of sequences in alignment") + continue + elif key == "AU": + pass + else: + assert len(value) == 1, (key, value) + value = value.pop() + try: + alignment.annotations[AlignmentIterator.gf_mapping[key]] = value + except KeyError: + pass + + @staticmethod + def _store_per_column_annotations(alignment, gc, columns, skipped_columns): + if gc: + alignment.column_annotations = {} + for key, value in gc.items(): + if skipped_columns.size > 0: + value = "".join( + letter + for index, letter in enumerate(value) + if index not in skipped_columns + ) + if len(value) != columns: + raise ValueError( + f"{key} length is {len(value)}, expected {columns}" + ) + alignment.column_annotations[ + AlignmentIterator.gc_mapping.get(key, key) + ] = value + + @staticmethod + def _store_per_sequence_annotations(alignment, gs): + for seqname, annotations in gs.items(): + for record in alignment.sequences: + if record.id == seqname: + break + else: + raise ValueError(f"Failed to find seqname {seqname}") + for key, value in annotations.items(): + if key == "DE": + record.description = value + elif key == "DR": + record.dbxrefs = value + else: + record.annotations[AlignmentIterator.gs_mapping.get(key, key)] = ( + value + ) + + @staticmethod + def _store_per_sequence_and_per_column_annotations(alignment, gr): + for seqname, letter_annotations in gr.items(): + for record in alignment.sequences: + if record.id == seqname: + break + else: + raise ValueError(f"Failed to find seqname {seqname}") + for key, letter_annotation in letter_annotations.items(): + feature = AlignmentIterator.gr_mapping.get(key, key) + if key == "CSA": + letter_annotation = letter_annotation.replace("-", "") + else: + letter_annotation = letter_annotation.replace(".", "") + record.letter_annotations[feature] = letter_annotation + + def _read_next_alignment(self, stream): + for line in stream: + line = line.strip() + if not line: + continue + elif line == "# STOCKHOLM 1.0": + # Starting a new alignment + records = [] + aligned_sequences = [] + references = [] + reference_comments = [] + database_references = [] + nested_domains = [] + gf = defaultdict(list) + gc = {} + gs = defaultdict(lambda: {"DR": []}) + gr = defaultdict(dict) + length = None + elif line == "//": + # Reached the end of the alignment. + aligned_sequences = np.array( + [np.frombuffer(row.encode(), np.int8) for row in aligned_sequences] + ) + skipped_columns = np.nonzero((aligned_sequences == ord("-")).all(0))[0] + aligned_sequences = np.delete(aligned_sequences, skipped_columns, 1) + aligned_sequences = [row.tobytes() for row in aligned_sequences] + sequences, coordinates = Alignment.parse_printed_alignment( + aligned_sequences + ) + for sequence, record in zip(sequences, records): + record.seq = Seq(sequence) + alignment = Alignment(records, coordinates) + for index in sorted(skipped_columns, reverse=True): + del operations[index] # noqa: F821 + alignment.operations = operations # noqa: F821 + alignment.annotations = {} + if references: + alignment.annotations["references"] = [] + for reference in references: + reference = dict(reference) + reference["title"] = " ".join(reference["title"]) + reference["author"] = " ".join(reference["author"]) + reference["location"] = " ".join(reference["location"]) + alignment.annotations["references"].append(reference) + if database_references: + alignment.annotations["database references"] = database_references + if nested_domains: + alignment.annotations["nested domains"] = nested_domains + rows, columns = alignment.shape + AlignmentIterator._store_per_file_annotations(alignment, gf, rows) + AlignmentIterator._store_per_column_annotations( + alignment, gc, columns, skipped_columns + ) + AlignmentIterator._store_per_sequence_annotations(alignment, gs) + AlignmentIterator._store_per_sequence_and_per_column_annotations( + alignment, gr + ) + return alignment + elif not line.startswith("#"): + # Sequence + # Format: " " + try: + seqname, aligned_sequence = line.split(None, 1) + except ValueError: + # This might be someone attempting to store a zero length sequence? + raise ValueError( + "Could not split line into sequence name and aligned sequence:\n" + + line + ) from None + if length is None: + length = len(aligned_sequence) + operations = bytearray(b"M" * length) + elif length != len(aligned_sequence): + raise ValueError( + f"Aligned sequence {seqname} consists of {len(aligned_sequence)} letters, expected {length} letters)" + ) + for i, letter in enumerate(aligned_sequence): + if letter == "-": + assert operations[i] != ord("I") + operations[i] = ord("D") # deletion + elif letter == ".": + assert operations[i] != ord("D") + operations[i] = ord("I") # insertion + aligned_sequence = aligned_sequence.replace(".", "-") + aligned_sequences.append(aligned_sequence) + record = SeqRecord(None, id=seqname, description="") + records.append(record) + elif line.startswith("#=GF "): + # Generic per-File annotation, free text + # Format: #=GF + feature, text = line[5:].strip().split(None, 1) + if feature == "RN": + assert text.startswith("[") + assert text.endswith("]") + number = int(text[1:-1]) + reference = defaultdict(list) + reference["number"] = number + if reference_comments: + reference["comment"] = " ".join(reference_comments) + reference_comments = [] + references.append(reference) + elif feature == "RM": + assert not reference["medline"] + reference["medline"] = text + elif feature == "RT": + reference["title"].append(text) + elif feature == "RA": + reference["author"].append(text) + elif feature == "RL": + reference["location"].append(text) + elif feature == "RC": + reference_comments.append(text) + elif feature == "DR": + database_reference = {"reference": text} + database_references.append(database_reference) + elif feature == "DC": + assert "comment" not in database_reference + database_reference["comment"] = text + elif feature == "NE": + nested_domain = {"accession": text} + nested_domains.append(nested_domain) + elif feature == "NL": + assert "location" not in nested_domain + nested_domain["location"] = text + else: + # Each feature key could be used more than once, + # so store the entries as a list of strings. + gf[feature].append(text) + elif line.startswith("#=GC "): + # Generic per-Column annotation, exactly 1 char per column + # Format: "#=GC " + feature, text = line[5:].strip().split(None, 2) + if feature not in gc: + gc[feature] = "" + gc[feature] += text.strip() # append to any previous entry + # Might be interleaved blocks, so can't check length yet + elif line.startswith("#=GS "): + # Generic per-Sequence annotation, free text + # Format: "#=GS " + try: + seqname, feature, text = line[5:].strip().split(None, 2) + except ValueError: + # Free text can sometimes be empty, which a one line split throws an error for. + # See https://github.com/biopython/biopython/issues/2982 for more details + seqname, feature = line[5:].strip().split(None, 1) + text = "" + if feature == "DR": + gs[seqname][feature].append(text) + else: + assert feature not in gs[seqname] + gs[seqname][feature] = text + elif line[:5] == "#=GR ": + # Generic per-Sequence AND per-Column markup + # Format: "#=GR " + terms = line[5:].split(None, 2) + assert terms[0] == seqname + feature = terms[1] + gr[seqname][feature] = terms[2].strip() + + +class AlignmentWriter(interfaces.AlignmentWriter): + """Alignment file writer for the Stockholm file format.""" + + gf_mapping = {value: key for key, value in AlignmentIterator.gf_mapping.items()} + gs_mapping = {value: key for key, value in AlignmentIterator.gs_mapping.items()} + gr_mapping = {value: key for key, value in AlignmentIterator.gr_mapping.items()} + gc_mapping = {value: key for key, value in AlignmentIterator.gc_mapping.items()} + + fmt = "Stockholm" + + def format_alignment(self, alignment): + """Return a string with a single alignment in the Stockholm format.""" + rows, columns = alignment.shape + + if rows == 0: + raise ValueError("Must have at least one sequence") + if columns == 0: + raise ValueError("Non-empty sequences are required") + + try: + alignment_annotations = alignment.annotations + except AttributeError: + alignment_annotations = {} + lines = [] + lines.append("# STOCKHOLM 1.0\n") + # #=GF Above the alignment; alignment.annotations + for key, feature in self.gf_mapping.items(): + if key == "comment": + # write this last + continue + value = alignment_annotations.get(key) + if value is not None: + feature = self.gf_mapping[key] + if key in ("author", "wikipedia"): + for item in value: + lines.append(f"#=GF {feature} {item}\n") + else: + lines.append(f"#=GF {feature} {value}\n") + nested_domains = alignment_annotations.get("nested domains") + if nested_domains is not None: + for nested_domain in nested_domains: + accession = nested_domain.get("accession") + if accession is not None: + lines.append(f"#=GF NE {accession}\n") + location = nested_domain.get("location") + if location is not None: + lines.append(f"#=GF NL {location}\n") + references = alignment_annotations.get("references") + if references is not None: + for reference in references: + comment = reference.get("comment") + lines.append(AlignmentWriter._format_long_text("#=GF RC ", comment)) + lines.append(f"#=GF RN [{reference['number']}]\n") + lines.append(f"#=GF RM {reference['medline']}\n") + title = reference["title"] + lines.append(AlignmentWriter._format_long_text("#=GF RT ", title)) + lines.append(f"#=GF RA {reference['author']}\n") + lines.append(f"#=GF RL {reference['location']}\n") + database_references = alignment_annotations.get("database references") + if database_references is not None: + for database_reference in database_references: + lines.append(f"#=GF DR {database_reference['reference']}\n") + comment = database_reference.get("comment") + if comment is not None: + lines.append(f"#=GF DC {comment}\n") + key = "comment" + value = alignment_annotations.get(key) + if value is not None: + prefix = "#=GF %s " % self.gf_mapping[key] + lines.append(AlignmentWriter._format_long_text(prefix, value)) + for key in alignment_annotations: + if key in self.gf_mapping: + continue + if key == "nested domains": + continue + if key == "references": + continue + if key == "database references": + continue + raise ValueError( + "Unknown annotation %s found in alignment.annotations" % key + ) + lines.append("#=GF SQ %i\n" % rows) + # #=GS Above the alignment or just below the corresponding sequence; + # record.annotations + # #=GR Just below the corresponding sequence; + # record.letter_annotations + width = max(len(record.id) for record in alignment.sequences) + start = max(width, 20) + 12 + for record in alignment.sequences: + name = record.id.ljust(width) + for key, value in record.annotations.items(): + feature = self.gs_mapping.get(key, key) + lines.append(f"#=GS {name} {feature} {value}\n") + if record.description: + lines.append(f"#=GS {name} DE {record.description}\n") + for value in record.dbxrefs: + lines.append(f"#=GS {name} DR {value}\n") + + try: + operations = alignment.operations + except AttributeError: + operations = bytes(b"M" * columns) + else: + assert len(operations) == columns + for aligned_sequence, record in zip(alignment, alignment.sequences): + aligned_sequence = "".join( + "." if letter == "-" and operation == ord("I") else letter + for operation, letter in zip(operations, aligned_sequence) + ) + lines.extend( + AlignmentWriter._format_record(width, start, aligned_sequence, record) + ) + # #=GC Below the alignment; + # alignment.column_annotations + if alignment.column_annotations: + for key, value in alignment.column_annotations.items(): + feature = self.gc_mapping.get(key, key) + line = f"#=GC {feature} ".ljust(start) + value + "\n" + lines.append(line) + lines.append("//\n") + return "".join(lines) + + @staticmethod + def _format_long_text(prefix, text): + """Format the text as wrapped lines (PRIVATE).""" + if text is None: + return "" + return ( + textwrap.fill( + text, + width=79, + break_long_words=False, + initial_indent=prefix, + subsequent_indent=prefix, + ) + + "\n" + ) + + @staticmethod + def _format_record(width, start, aligned_sequence, record): + """Format lines for a single SeqRecord (PRIVATE).""" + name = record.id.ljust(start) + line = name + aligned_sequence + "\n" + yield line + indices = [ + index for index, letter in enumerate(aligned_sequence) if letter in ".-" + ] + indices.reverse() + name = record.id.ljust(width) + for key, value in record.letter_annotations.items(): + feature = AlignmentWriter.gr_mapping.get(key, key) + j = 0 + values = bytearray(b"." * len(aligned_sequence)) + for i, letter in enumerate(aligned_sequence): + if letter not in ".-": + values[i] = ord(value[j]) + j += 1 + value = values.decode() + line = f"#=GR {name} {feature} ".ljust(start) + value + "\n" + yield line + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9704c2ccda0ad6af9bb31f661caf97f671903383 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/__init__.py @@ -0,0 +1,508 @@ +# Copyright 2019 by Michiel de Hoon. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Substitution matrices.""" + +import os +import string + +import numpy as np + +from Bio.File import as_handle +from Bio.Align.substitution_matrices import _arraycore # type: ignore + + +class Array(_arraycore.Array): + """numpy array subclass indexed by integers and by letters.""" + + def __new__(cls, alphabet=None, dims=None, data=None, dtype=float): + """Create a new Array instance.""" + if isinstance(data, dict): + if alphabet is not None: + raise ValueError("alphabet must be None if data is a dict") + if dims is not None: + raise ValueError("dims must be None if data is a dict") + alphabet = [] + single_letters = True + for key in data: + if isinstance(key, str): + if dims is None: + dims = 1 + elif dims != 1: + raise ValueError("inconsistent dimensions in data") + alphabet.append(key) + elif isinstance(key, tuple): + if dims is None: + dims = len(key) + elif dims != len(key): + raise ValueError("inconsistent dimensions in data") + if dims == 1: + if not isinstance(key, str): + raise ValueError("expected string") + if len(key) > 1: + single_letters = False + alphabet.append(key) + elif dims == 2: + for letter in key: + if not isinstance(letter, str): + raise ValueError("expected string") + if len(letter) > 1: + single_letters = False + alphabet.append(letter) + else: + raise ValueError( + "data array should be 1- or 2- dimensional " + "(found %d dimensions) in key" % dims + ) + alphabet = sorted(set(alphabet)) + if single_letters: + alphabet = "".join(alphabet) + else: + alphabet = tuple(alphabet) + n = len(alphabet) + if dims == 1: + shape = (n,) + elif dims == 2: + shape = (n, n) + else: # dims is None + raise ValueError("data is an empty dictionary") + obj = super().__new__(cls, shape, dtype) + if dims == 1: + for i, key in enumerate(alphabet): + obj[i] = data.get(letter, 0.0) + elif dims == 2: + for i1, letter1 in enumerate(alphabet): + for i2, letter2 in enumerate(alphabet): + key = (letter1, letter2) + value = data.get(key, 0.0) + obj[i1, i2] = value + else: + if alphabet is None: + alphabet = string.ascii_uppercase + elif not (isinstance(alphabet, (str, tuple))): + raise ValueError("alphabet should be a string or a tuple") + n = len(alphabet) + if data is None: + if dims is None: + dims = 1 + elif dims not in (1, 2): + raise ValueError("dims should be 1 or 2 (found %s)" % dims) + shape = (n,) * dims + else: + if dims is None: + shape = data.shape + dims = len(shape) + if dims == 1: + pass + elif dims == 2: + if shape[0] != shape[1]: + raise ValueError("data array is not square") + else: + raise ValueError( + "data array should be 1- or 2- dimensional " + "(found %d dimensions) " % dims + ) + else: + shape = (n,) * dims + if data.shape != shape: + raise ValueError( + "data shape has inconsistent shape (expected (%s), found (%s))" + % (shape, data.shape) + ) + obj = super().__new__(cls, shape, dtype) + if data is None: + obj[:] = 0.0 + else: + obj[:] = data + obj.alphabet = alphabet + return obj + + def __array_finalize__(self, obj): + try: + alphabet = obj.alphabet + except AttributeError: + # None, or plain numpy array + pass + else: + if alphabet is not None: + self.alphabet = alphabet + + def _convert_key(self, key): + if isinstance(key, tuple): + indices = [] + for index in key: + if isinstance(index, str): + try: + index = self.alphabet.index(index) + except ValueError: + raise IndexError("'%s'" % index) from None + indices.append(index) + key = tuple(indices) + elif isinstance(key, str): + try: + key = self.alphabet.index(key) + except ValueError: + raise IndexError("'%s'" % key) from None + return key + + def __getitem__(self, key): + key = self._convert_key(key) + value = np.ndarray.__getitem__(self, key) + if value.ndim == 2: + if self.ndim == 2: + if value.shape != self.shape: + raise IndexError("Requesting truncated array") + elif self.ndim == 1: + length = self.shape[0] + if value.shape[0] == length and value.shape[1] == 1: + pass + elif value.shape[0] == 1 and value.shape[1] == length: + pass + else: + raise IndexError("Requesting truncated array") + elif value.ndim == 1: + if value.shape[0] != self.shape[0]: + raise IndexError("Requesting truncated array") + elif value.ndim == 0: + return value.item() + return value.view(Array) + + def __setitem__(self, key, value): + key = self._convert_key(key) + np.ndarray.__setitem__(self, key, value) + + def __contains__(self, key): + # Follow dict definition of __contains__ + return key in self.keys() + + def __array_prepare__(self, out_arr, context=None): + # needed for numpy older than 1.13.0 + ufunc, inputs, i = context + alphabet = self.alphabet + for arg in inputs: + if isinstance(arg, Array): + if arg.alphabet != alphabet: + raise ValueError("alphabets are inconsistent") + return np.ndarray.__array_prepare__(self, out_arr, context) + + def __array_wrap__(self, out_arr, context=None): + if len(out_arr) == 1: + return out_arr[0] + return np.ndarray.__array_wrap__(self, out_arr, context) + + def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): + args = [] + alphabet = self.alphabet + for arg in inputs: + if isinstance(arg, Array): + if arg.alphabet != alphabet: + raise ValueError("alphabets are inconsistent") + args.append(arg.view(np.ndarray)) + else: + args.append(arg) + + outputs = kwargs.pop("out", None) + if outputs: + out_args = [] + for arg in outputs: + if isinstance(arg, Array): + if arg.alphabet != alphabet: + raise ValueError("alphabets are inconsistent") + out_args.append(arg.view(np.ndarray)) + else: + out_args.append(arg) + kwargs["out"] = tuple(out_args) + else: + outputs = (None,) * ufunc.nout + + raw_results = super().__array_ufunc__(ufunc, method, *args, **kwargs) + if raw_results is NotImplemented: + return NotImplemented + + if method == "at": + return + + if ufunc.nout == 1: + raw_results = (raw_results,) + + results = [] + for raw_result, output in zip(raw_results, outputs): + if raw_result.ndim == 0: + result = raw_result + elif output is None: + result = np.asarray(raw_result).view(Array) + result.alphabet = self.alphabet + else: + result = output + results.append(result) + + return results[0] if len(results) == 1 else results + + def __reduce__(self): + import pickle + + values = np.array(self) + state = pickle.dumps(values) + alphabet = self.alphabet + dims = len(self.shape) + dtype = self.dtype + arguments = (Array, alphabet, dims, None, dtype) + return (Array.__new__, arguments, state) + + def __setstate__(self, state): + import pickle + + self[:, :] = pickle.loads(state) + + def get(self, key, value=None): + """Return the value of the key if found; return value otherwise.""" + try: + return self[key] + except IndexError: + return value + + def items(self): + """Return an iterator of (key, value) pairs in the array.""" + dims = len(self.shape) + if dims == 1: + for index, key in enumerate(self.alphabet): + value = np.ndarray.__getitem__(self, index) + yield key, value + elif dims == 2: + for i1, c1 in enumerate(self.alphabet): + for i2, c2 in enumerate(self.alphabet): + key = (c1, c2) + value = np.ndarray.__getitem__(self, (i1, i2)) + yield key, value + else: + raise RuntimeError("array has unexpected shape %s" % self.shape) + + def keys(self): + """Return a tuple with the keys associated with the array.""" + dims = len(self.shape) + alphabet = self.alphabet + if dims == 1: + return tuple(alphabet) + elif dims == 2: + return tuple((c1, c2) for c2 in alphabet for c1 in alphabet) + else: + raise RuntimeError("array has unexpected shape %s" % self.shape) + + def values(self): + """Return a tuple with the values stored in the array.""" + dims = len(self.shape) + alphabet = self.alphabet + if dims == 1: + return tuple(self) + elif dims == 2: + n1, n2 = self.shape + return tuple( + np.ndarray.__getitem__(self, (i1, i2)) + for i2 in range(n2) + for i1 in range(n1) + ) + else: + raise RuntimeError("array has unexpected shape %s" % self.shape) + + def update(self, E=None, **F): + """Update the array from dict/iterable E and F.""" + if E is not None: + try: + alphabet = E.keys() + except AttributeError: + for key, value in E: + self[key] = value + else: + for key in E: + self[key] = E[key] + for key in F: + self[key] = F[key] + + def select(self, alphabet): + """Subset the array by selecting the letters from the specified alphabet.""" + ii = [] + jj = [] + for i, key in enumerate(alphabet): + try: + j = self.alphabet.index(key) + except ValueError: + continue + ii.append(i) + jj.append(j) + dims = len(self.shape) + a = Array(alphabet, dims=dims) + ii = np.ix_(*[ii] * dims) + jj = np.ix_(*[jj] * dims) + a[ii] = self.view(np.ndarray)[jj] + return a + + def _format_1D(self, fmt): + alphabet = self.alphabet + n = len(alphabet) + words = [None] * n + lines = [] + try: + header = self.header + except AttributeError: + pass + else: + for line in header: + line = "# %s\n" % line + lines.append(line) + maxwidth = 0 + for i, key in enumerate(alphabet): + value = self[key] + word = fmt % value + width = len(word) + if width > maxwidth: + maxwidth = width + words[i] = word + fmt2 = " %" + str(maxwidth) + "s" + for letter, word in zip(alphabet, words): + word = fmt2 % word + line = letter + word + "\n" + lines.append(line) + text = "".join(lines) + return text + + def _format_2D(self, fmt): + alphabet = self.alphabet + n = len(alphabet) + words = [[None] * n for _ in range(n)] + lines = [] + try: + header = self.header + except AttributeError: + pass + else: + for line in header: + line = "# %s\n" % line + lines.append(line) + keywidth = max(len(c) for c in alphabet) + keyfmt = "%" + str(keywidth) + "s" + line = " " * keywidth + for j, c2 in enumerate(alphabet): + maxwidth = 0 + for i, c1 in enumerate(alphabet): + key = (c1, c2) + value = self[key] + word = fmt % value + width = len(word) + if width > maxwidth: + maxwidth = width + words[i][j] = word + fmt2 = " %" + str(maxwidth) + "s" + word = fmt2 % c2 + line += word + for i, c1 in enumerate(alphabet): + word = words[i][j] + words[i][j] = fmt2 % word + line = line.rstrip() + "\n" + lines.append(line) + for letter, row in zip(alphabet, words): + key = keyfmt % letter + line = key + "".join(row) + "\n" + lines.append(line) + text = "".join(lines) + return text + + def __format__(self, fmt): + return self.format(fmt) + + def format(self, fmt=""): + """Return a string representation of the array. + + The argument ``fmt`` specifies the number format to be used. + By default, the number format is "%i" if the array contains integer + numbers, and "%.1f" otherwise. + + """ + if fmt == "": + if np.issubdtype(self.dtype, np.integer): + fmt = "%i" + else: + fmt = "%.1f" + n = len(self.shape) + if n == 1: + return self._format_1D(fmt) + elif n == 2: + return self._format_2D(fmt) + else: + raise RuntimeError("Array has unexpected rank %d" % n) + + def __str__(self): + return self.format() + + def __repr__(self): + text = np.ndarray.__repr__(self) + alphabet = self.alphabet + if isinstance(alphabet, str): + assert text.endswith(")") + text = text[:-1] + ",\n alphabet='%s')" % self.alphabet + return text + + +def read(handle, dtype=float): + """Parse the file and return an Array object.""" + with as_handle(handle) as fp: + lines = fp.readlines() + + header = [] + for i, line in enumerate(lines): + if not line.startswith("#"): + break + header.append(line[1:].strip()) + rows = [line.split() for line in lines[i:]] + if len(rows[0]) == len(rows[1]) == 2: + alphabet = [key for key, value in rows] + for key in alphabet: + if len(key) > 1: + alphabet = tuple(alphabet) + break + else: + alphabet = "".join(alphabet) + matrix = Array(alphabet=alphabet, dims=1, dtype=dtype) + matrix.update(rows) + else: + alphabet = rows.pop(0) + for key in alphabet: + if len(key) > 1: + alphabet = tuple(alphabet) + break + else: + alphabet = "".join(alphabet) + matrix = Array(alphabet=alphabet, dims=2, dtype=dtype) + for letter1, row in zip(alphabet, rows): + letter = row.pop(0) + assert letter1 == letter + for letter2, word in zip(alphabet, row): + matrix[letter1, letter2] = float(word) + matrix.header = header + return matrix + + +def load(name=None): + """Load and return a precalculated substitution matrix. + + >>> from Bio.Align import substitution_matrices + >>> names = substitution_matrices.load() + """ + path = os.path.realpath(__file__) + directory = os.path.dirname(path) + subdirectory = os.path.join(directory, "data") + if name is None: + filenames = os.listdir(subdirectory) + try: + filenames.remove("README.txt") + # The README.txt file is not present in usual Biopython + # installations, but is included in a development install. + except ValueError: + pass + return sorted(filenames) + path = os.path.join(subdirectory, name) + matrix = read(path) + return matrix diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30f85a2878d0de7bd3de2786d07e13d7fe60763e Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/_arraycore.c b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/_arraycore.c new file mode 100644 index 0000000000000000000000000000000000000000..081151f375025abc729c79ca9983363de4111a56 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/_arraycore.c @@ -0,0 +1,236 @@ +#define PY_SSIZE_T_CLEAN +#include +#include "_arraycore.h" + + +static PyTypeObject Array_Type; + + +static void +Array_dealloc(PyObject *self) +{ + PyTypeObject* basetype = Array_Type.tp_base; + Fields* fields = (Fields*)((intptr_t)self + basetype->tp_basicsize); + /* fields->alphabet may be NULL if this instance was created by numpy + * and __array_finalize__ somehow failed. + */ + Py_XDECREF(fields->alphabet); + /* PyBuffer_Release won't do anything if fields->mapping.obj is NULL. */ + PyMem_Free(fields->mapping.buf); + basetype->tp_dealloc(self); +} + +static PyObject * +Array_finalize(PyObject *self, PyObject *obj) +{ + if (obj == Py_None) Py_RETURN_NONE; + if (Py_TYPE(self) != Py_TYPE(obj)) { + PyErr_SetString(PyExc_RuntimeError, + "__array_finalize__ argument is not an Array object"); + return NULL; + } + PyTypeObject* basetype = Array_Type.tp_base; + Fields* self_fields = (Fields*)((intptr_t)self + basetype->tp_basicsize); + const Fields* obj_fields = (Fields*)((intptr_t)obj + basetype->tp_basicsize); + PyObject* alphabet = obj_fields->alphabet; + if (alphabet) { + Py_INCREF(alphabet); + self_fields->alphabet = obj_fields->alphabet; + } + Py_RETURN_NONE; +} + +static PyMethodDef Array_methods[] = { + {"__array_finalize__", (PyCFunction)Array_finalize, METH_O, + "Called by NumPy to finalize new views or copies"}, + {NULL} /* Sentinel */ +}; + +static PyObject *Array_get_alphabet(PyObject *self, void *closure) { + PyTypeObject* basetype = Array_Type.tp_base; + Fields* fields = (Fields*)((intptr_t)self + basetype->tp_basicsize); + PyObject* alphabet = fields->alphabet; + if (!alphabet) Py_RETURN_NONE; + Py_INCREF(alphabet); + return alphabet; +} + +static int Array_set_alphabet(PyObject *self, PyObject *arg, void *closure) { + Py_buffer view; + const Py_ssize_t length = PySequence_Size(arg); + PyTypeObject* basetype = Array_Type.tp_base; + Fields* fields = (Fields*)((intptr_t)self + basetype->tp_basicsize); + if (fields->alphabet) { + PyErr_SetString(PyExc_ValueError, "the alphabet has already been set."); + return -1; + } + if (!PySequence_Check(arg)) { + PyErr_SetString(PyExc_TypeError, + "alphabet must support the sequence protocol (e.g.,\n" + "strings, lists, and tuples can be valid alphabets)."); + return -1; + } + if (PyObject_GetBuffer(self, &view, PyBUF_STRIDES) != 0) { + PyErr_SetString(PyExc_RuntimeError, "failed to access matrix buffer"); + return -1; + } + switch (view.ndim) { + case 1: + if (view.shape[0] == length) break; + PyErr_Format(PyExc_ValueError, + "alphabet length %zd is inconsistent with array size " + "%zd", length, view.shape[0]); + PyBuffer_Release(&view); + return -1; + case 2: + if ((view.shape[0] == length && view.shape[1] == length) + || (view.shape[0] == length && view.shape[1] == 1) + || (view.shape[0] == 1 && view.shape[1] == length)) break; + PyErr_Format(PyExc_ValueError, + "alphabet length %zd is inconsistent with array size " + "(%zd, %zd)", length, view.shape[0], view.shape[1]); + PyBuffer_Release(&view); + return -1; + default: + PyErr_Format(PyExc_ValueError, + "substitution matrix has incorrect rank %d " + "(expected 1 or 2)", view.ndim); + PyBuffer_Release(&view); + return -1; + } + PyBuffer_Release(&view); + if (PyUnicode_Check(arg)) { + /* initialize mapping if alphabet is a string: */ + Py_ssize_t mapping_size; + void* characters = PyUnicode_DATA(arg); + int kind = PyUnicode_KIND(arg); + int* mapping; + Py_ssize_t i; + switch (kind) { + case PyUnicode_1BYTE_KIND: { + mapping_size = 1 << 8 * sizeof(Py_UCS1); + break; + } + case PyUnicode_2BYTE_KIND: { + mapping_size = 1 << 8 * sizeof(Py_UCS2); + break; + } + case PyUnicode_4BYTE_KIND: { + mapping_size = 0x110000; /* Maximum code point in Unicode 6.0 + * is 0x10ffff = 1114111 */ + break; + } + default: + PyErr_SetString(PyExc_ValueError, "could not interpret alphabet"); + return -1; + } + mapping = PyMem_Malloc(mapping_size*sizeof(int)); + if (!mapping) return -1; + for (i = 0; i < mapping_size; i++) mapping[i] = MISSING_LETTER; + for (i = 0; i < length; i++) { + Py_UCS4 character = PyUnicode_READ(kind, characters, i); + if (mapping[character] != MISSING_LETTER) { + PyObject* c = PyUnicode_FromKindAndData(kind, &character, 1); + PyErr_Format(PyExc_ValueError, + "alphabet contains '%S' more than once", c); + Py_XDECREF(c); + PyMem_Free(mapping); + return -1; + } + mapping[character] = i; + } + if (PyBuffer_FillInfo(&fields->mapping, + NULL, + mapping, + mapping_size * sizeof(int), + 0, + PyBUF_SIMPLE) == -1) { + PyMem_Free(mapping); + return -1; + } + fields->mapping.itemsize = sizeof(int); + } + Py_INCREF(arg); + fields->alphabet = arg; + return 0; +} + +static PyGetSetDef Array_getset[] = { + {"alphabet", (getter)Array_get_alphabet, (setter)Array_set_alphabet, "alphabet", NULL}, + {NULL} +}; + +static PyTypeObject Array_Type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "_arraycore.Array", + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + .tp_dealloc = (destructor)Array_dealloc, + .tp_methods = Array_methods, + .tp_getset = Array_getset, +}; + +static struct PyModuleDef module = { + PyModuleDef_HEAD_INIT, + .m_name = "_arraycore", + .m_doc = "Base module defining the Array base class", + .m_size = -1, +}; + +PyMODINIT_FUNC +PyInit__arraycore(void) +{ + int result; + PyObject *basemodule; + PyObject *baseclass; + PyTypeObject* basetype; + + PyObject *mod = PyModule_Create(&module); + if (!mod) return NULL; + + // Import the module containing the base class + basemodule = PyImport_ImportModule("numpy"); + if (!basemodule) + return NULL; + + // Get the base class + baseclass = PyObject_GetAttrString(basemodule, "ndarray"); + Py_DECREF(basemodule); + if (!baseclass || !PyType_Check(baseclass)) { + Py_XDECREF(basemodule); + PyErr_SetString(PyExc_RuntimeError, "Failed to get numpy.ndarray"); + return NULL; + } + + basetype = (PyTypeObject *)baseclass; + if (!(basetype->tp_flags & Py_TPFLAGS_BASETYPE)) { + PyErr_SetString(PyExc_RuntimeError, + "numpy ndarray class is not subclassable"); + return NULL; + } + if (basetype->tp_itemsize != 0) { + PyErr_Format(PyExc_RuntimeError, + "expected numpy arrays to have tp_itemsize 0 (found %zd)", + basetype->tp_itemsize); + return NULL; + } + if (!basetype->tp_new) { + PyErr_SetString(PyExc_RuntimeError, + "numpy ndarray class does not have tp_new"); + return NULL; + } + + Array_Type.tp_basicsize = basetype->tp_basicsize + sizeof(Fields); + Array_Type.tp_base = (PyTypeObject *)baseclass; + + if (PyType_Ready(&Array_Type) < 0) + return NULL; + + result = PyModule_AddObjectRef(mod, "Array", (PyObject*)&Array_Type); + Py_DECREF(&Array_Type); + if (result == -1) { + Py_DECREF(mod); + return NULL; + } + + return mod; +} diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/_arraycore.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/_arraycore.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..b3e28f033b25fea9879fdd1eba1b4ec2bd6a0998 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/_arraycore.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/_arraycore.h b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/_arraycore.h new file mode 100644 index 0000000000000000000000000000000000000000..b37eb063bfe5d70fc8dc4df1f8650aae614329c9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/_arraycore.h @@ -0,0 +1,7 @@ +typedef struct { + PyObject* alphabet; + Py_buffer mapping; +} Fields; + + +#define MISSING_LETTER -1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BENNER22 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BENNER22 new file mode 100644 index 0000000000000000000000000000000000000000..49ba457096283edbc10418f49b5730a8ae011ad0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BENNER22 @@ -0,0 +1,27 @@ +# S.A. Benner, M.A. Cohen, G.H. Gonnet: +# "Amino acid substitution during functionally constrained divergent evolution +# of protein sequences". +# Protein Engineering 7(11): 1323-1332 (1994). +# Figure 3B. +# PMID 7700864 + A C D E F G H I K L M N P Q R S T V W Y +A 2.5 -1.2 -0.2 -0.3 -3.1 0.8 -1.6 -0.4 -1.0 -1.7 -0.8 0.0 0.8 -0.9 -1.2 1.3 1.4 0.4 -5.5 -3.5 +C -1.2 12.6 -3.7 -4.3 -0.1 -1.7 -1.5 -2.4 -3.3 -2.6 -2.5 -1.9 -3.1 -3.3 -1.6 0.3 -1.1 -1.7 0.5 0.6 +D -0.2 -3.7 4.8 3.9 -5.4 0.7 0.3 -4.0 0.2 -4.9 -3.9 2.4 -1.8 0.6 -1.0 0.1 -0.7 -3.0 -6.4 -3.0 +E -0.3 -4.3 3.9 4.6 -5.7 0.5 -0.2 -3.6 1.0 -4.4 -3.4 1.2 -1.7 1.7 -0.1 -0.5 -0.9 -2.7 -6.3 -4.0 +F -3.1 -0.1 -5.4 -5.7 7.7 -5.8 0.3 0.5 -5.1 2.2 0.7 -3.5 -3.4 -3.6 -4.3 -2.2 -2.6 -0.1 0.5 5.9 +G 0.8 -1.7 0.7 0.5 -5.8 6.2 -2.0 -3.8 -1.0 -4.9 -3.8 0.4 -1.8 -1.4 -0.7 0.6 -0.7 -2.5 -4.5 -4.8 +H -1.6 -1.5 0.3 -0.2 0.3 -2.0 6.1 -3.2 0.8 -2.1 -2.4 1.4 -0.4 2.4 1.5 -0.5 -1.1 -3.0 -2.7 3.7 +I -0.4 -2.4 -4.0 -3.6 0.5 -3.8 -3.2 4.2 -3.0 2.7 3.1 -2.7 -2.3 -2.7 -3.2 -1.4 0.3 3.6 -4.4 -2.2 +K -1.0 -3.3 0.2 1.0 -5.1 -1.0 0.8 -3.0 4.4 -3.3 -2.0 1.0 -1.6 2.2 3.9 -0.4 -0.4 -2.7 -3.7 -3.6 +L -1.7 -2.6 -4.9 -4.4 2.2 -4.9 -2.1 2.7 -3.3 4.6 3.2 -3.5 -1.3 -2.0 -2.9 -2.1 -1.0 2.0 -1.8 -0.7 +M -0.8 -2.5 -3.9 -3.4 0.7 -3.8 -2.4 3.1 -2.0 3.2 4.9 -2.6 -2.0 -1.7 -2.1 -1.5 0.1 2.5 -2.8 -1.8 +N 0.0 -1.9 2.4 1.2 -3.5 0.4 1.4 -2.7 1.0 -3.5 -2.6 3.3 -1.1 0.5 0.4 1.1 0.5 -2.3 -5.2 -1.2 +P 0.8 -3.1 -1.8 -1.7 -3.4 -1.8 -0.4 -2.3 -1.6 -1.3 -2.0 -1.1 7.0 -0.1 -1.2 1.1 0.4 -1.7 -5.8 -3.5 +Q -0.9 -3.3 0.6 1.7 -3.6 -1.4 2.4 -2.7 2.2 -2.0 -1.7 0.5 -0.1 4.2 2.2 -0.6 -0.7 -2.4 -3.3 -1.9 +R -1.2 -1.6 -1.0 -0.1 -4.3 -0.7 1.5 -3.2 3.9 -2.9 -2.1 0.4 -1.2 2.2 5.0 -0.5 -0.7 -2.9 -1.1 -2.7 +S 1.3 0.3 0.1 -0.5 -2.2 0.6 -0.5 -1.4 -0.4 -2.1 -1.5 1.1 1.1 -0.6 -0.5 2.0 1.5 -0.9 -3.9 -1.9 +T 1.4 -1.1 -0.7 -0.9 -2.6 -0.7 -1.1 0.3 -0.4 -1.0 0.1 0.5 0.4 -0.7 -0.7 1.5 2.5 0.4 -4.5 -3.0 +V 0.4 -1.7 -3.0 -2.7 -0.1 -2.5 -3.0 3.6 -2.7 2.0 2.5 -2.3 -1.7 -2.4 -2.9 -0.9 0.4 3.7 -4.5 -2.6 +W -5.5 0.5 -6.4 -6.3 0.5 -4.5 -2.7 -4.4 -3.7 -1.8 -2.8 -5.2 -5.8 -3.3 -1.1 -3.9 -4.5 -4.5 15.7 1.5 +Y -3.5 0.6 -3.0 -4.0 5.9 -4.8 3.7 -2.2 -3.6 -0.7 -1.8 -1.2 -3.5 -1.9 -2.7 -1.9 -3.0 -2.6 1.5 9.0 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BENNER6 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BENNER6 new file mode 100644 index 0000000000000000000000000000000000000000..4849b30a75bc275097d79ef12e2591eec04c2ba1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BENNER6 @@ -0,0 +1,27 @@ +# S.A. Benner, M.A. Cohen, G.H. Gonnet: +# "Amino acid substitution during functionally constrained divergent evolution +# of protein sequences". +# Protein Engineering 7(11): 1323-1332 (1994). +# Figure 3A. +# PMID 7700864 + A C D E F G H I K L M N P Q R S T V W Y +A 2.5 -1.7 -0.6 -0.7 -3.2 0.8 -2.1 0.1 -1.9 -1.3 -0.2 0.0 1.1 -1.7 -1.7 1.4 1.7 0.7 -4.3 -4.0 +C -1.7 12.1 -3.7 -4.7 -0.1 -1.3 -1.2 -3.6 -2.8 -3.8 -3.7 -1.6 -2.7 -3.2 -0.4 0.9 -1.5 -3.1 1.6 2.6 +D -0.6 -3.7 5.2 4.4 -5.7 0.8 0.1 -4.2 -0.2 -5.3 -4.3 2.5 -2.8 0.6 -1.5 -0.4 -1.2 -3.3 -6.3 -2.3 +E -0.7 -4.7 4.4 5.2 -6.7 0.5 -0.2 -4.1 0.9 -5.0 -4.1 1.1 -2.6 2.1 -0.4 -1.2 -1.6 -3.0 -5.6 -4.1 +F -3.2 -0.1 -5.7 -6.7 8.3 -5.7 0.1 0.0 -6.3 2.4 -0.1 -3.5 -3.2 -4.4 -4.9 -1.8 -2.4 -0.5 -1.6 5.6 +G 0.8 -1.3 0.8 0.5 -5.7 5.8 -2.1 -3.4 -1.4 -4.6 -3.7 -0.1 -1.7 -1.6 -0.1 0.8 -0.5 -2.3 -1.7 -4.9 +H -2.1 -1.2 0.1 -0.2 0.1 -2.1 6.1 -3.7 0.9 -2.2 -3.4 1.4 -0.4 3.2 1.8 -0.9 -1.7 -3.8 -2.8 4.4 +I 0.1 -3.6 -4.2 -4.1 0.0 -3.4 -3.7 4.4 -3.8 2.4 4.0 -2.5 -2.0 -3.8 -3.8 -1.2 0.7 3.9 -5.0 -3.3 +K -1.9 -2.8 -0.2 0.9 -6.3 -1.4 0.9 -3.8 5.6 -4.1 -2.9 1.0 -2.3 2.5 4.3 -1.2 -1.1 -3.8 -1.4 -4.0 +L -1.3 -3.8 -5.3 -5.0 2.4 -4.6 -2.2 2.4 -4.1 4.8 -2.9 -3.4 -0.2 -2.4 -3.2 -1.5 -0.4 1.9 -3.0 -1.6 +M -0.2 -3.7 -4.3 -4.1 -0.1 -3.7 -3.4 4.0 -2.9 -2.9 4.8 -2.5 -1.8 -3.1 -3.0 -1.3 0.6 3.3 -4.4 -3.6 +N 0.0 -1.6 2.5 1.1 -3.5 -0.1 1.4 -2.5 1.0 -3.4 -2.5 3.6 -1.1 0.1 -0.1 1.2 0.5 -2.4 -4.4 -0.9 +P 1.1 -2.7 -2.8 -2.6 -3.2 -1.7 -0.4 -2.0 -2.3 -0.2 -1.8 -1.1 6.5 0.1 -1.3 1.4 0.6 -1.6 -4.8 -3.8 +Q -1.7 -3.2 0.6 2.1 -4.4 -1.6 3.2 -3.8 2.5 -2.4 -3.1 0.1 0.1 5.3 2.5 -1.4 -1.7 -3.5 -2.6 -1.4 +R -1.7 -0.4 -1.5 -0.4 -4.9 -0.1 1.8 -3.8 4.3 -3.2 -3.0 -0.1 -1.3 2.5 5.1 -0.9 -1.3 -3.7 2.0 -2.6 +S 1.4 0.9 -0.4 -1.2 -1.8 0.8 -0.9 -1.2 -1.2 -1.5 -1.3 1.2 1.4 -1.4 -0.9 2.1 1.5 -0.9 -2.9 -1.8 +T 1.7 -1.5 -1.2 -1.6 -2.4 -0.5 -1.7 0.7 -1.1 -0.4 0.6 0.5 0.6 -1.7 -1.3 1.5 2.4 0.6 -2.6 -3.4 +V 0.7 -3.1 -3.3 -3.0 -0.5 -2.3 -3.8 3.9 -3.8 1.9 3.3 -2.4 -1.6 -3.5 -3.7 -0.9 0.6 4.0 -4.8 -3.8 +W -4.3 1.6 -6.3 -5.6 -1.6 -1.7 -2.8 -5.0 -1.4 -3.0 -4.4 -4.4 -4.8 -2.6 2.0 -2.9 -2.6 -4.8 14.7 -0.3 +Y -4.0 2.6 -2.3 -4.1 5.6 -4.9 4.4 -3.3 -4.0 -1.6 -3.6 -0.9 -3.8 -1.4 -2.6 -1.8 -3.4 -3.8 -0.3 9.5 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BENNER74 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BENNER74 new file mode 100644 index 0000000000000000000000000000000000000000..62000b1c1db01c0da9eb8ee93c89ff4e859222e5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BENNER74 @@ -0,0 +1,27 @@ +# S.A. Benner, M.A. Cohen, G.H. Gonnet: +# "Amino acid substitution during functionally constrained divergent evolution +# of protein sequences". +# Protein Engineering 7(11): 1323-1332 (1994). +# Figure 3C. +# PMID 7700864 + A C D E F G H I K L M N P Q R S T V W Y +A 2.4 0.3 -0.3 -0.1 -2.6 0.6 -1.0 -0.8 -0.4 -1.4 -0.8 -0.2 0.4 -0.3 -0.8 1.1 0.7 0.1 -4.1 -2.6 +C 0.3 11.8 -3.2 -3.2 -0.7 -2.0 -1.3 -1.2 -2.9 -1.6 -1.2 -1.8 -3.1 -2.6 -2.2 0.1 -0.6 -0.2 -0.9 -0.4 +D -0.3 -3.2 4.8 2.9 -4.7 0.2 0.4 -3.9 0.4 -4.2 -3.2 2.2 -1.0 0.8 -0.5 0.4 -0.2 -2.9 -5.5 -2.8 +E -0.1 -3.2 2.9 3.7 -4.3 -0.5 0.2 -2.9 1.2 -3.1 -2.2 1.0 -0.7 1.7 0.3 0.1 -0.2 -2.1 -4.7 -3.0 +F -2.6 -0.7 -4.7 -4.3 7.2 -5.4 0.0 0.9 -3.6 2.1 1.3 -3.2 -3.8 -2.8 -3.5 -2.6 -2.2 0.1 3.0 5.3 +G 0.6 -2.0 0.2 -0.5 -5.4 6.6 -1.6 -4.3 -1.1 -4.6 -3.5 0.4 -1.7 -1.1 -1.0 0.4 -1.0 -3.1 -4.1 -4.3 +H -1.0 -1.3 0.4 0.2 0.0 -1.6 6.1 -2.3 0.6 -1.9 -1.5 1.2 -1.0 1.4 1.0 -0.3 -0.5 -2.1 -1.0 2.5 +I -0.8 -1.2 -3.9 -2.9 0.9 -4.3 -2.3 4.0 -2.3 2.8 2.6 -2.8 -2.6 -2.0 -2.6 -1.8 -0.3 3.2 -2.3 -1.0 +K -0.4 -2.9 0.4 1.2 -3.6 -1.1 0.6 -2.3 3.4 -2.4 -1.5 0.9 -0.8 1.7 2.9 0.0 0.1 -1.9 -3.6 -2.4 +L -1.4 -1.6 -4.2 -3.1 2.1 -4.6 -1.9 2.8 -2.4 4.2 2.9 -3.1 -2.2 -1.7 -2.4 -2.2 -1.1 1.9 -0.9 -0.1 +M -0.8 -1.2 -3.2 -2.2 1.3 -3.5 -1.5 2.6 -1.5 2.9 4.5 -2.2 -2.4 -1.0 -1.8 -1.4 -0.4 1.8 -1.3 -0.5 +N -0.2 -1.8 2.2 1.0 -3.2 0.4 1.2 -2.8 0.9 -3.1 -2.2 3.6 -1.0 0.7 0.3 0.9 0.4 -2.2 -4.0 -1.4 +P 0.4 -3.1 -1.0 -0.7 -3.8 -1.7 -1.0 -2.6 -0.8 -2.2 -2.4 -1.0 7.5 -0.2 -0.1 0.5 0.1 -1.9 -5.2 -3.4 +Q -0.3 -2.6 0.8 1.7 -2.8 -1.1 1.4 -2.0 1.7 -1.7 -1.0 0.7 -0.2 3.0 1.6 0.1 -0.1 -1.7 -2.8 -1.8 +R -0.8 -2.2 -0.5 0.3 -3.5 -1.0 1.0 -2.6 2.9 -2.4 -1.8 0.3 -0.1 1.6 4.8 -0.2 -0.3 -2.2 -1.6 -2.0 +S 1.1 0.1 0.4 0.1 -2.6 0.4 -0.3 -1.8 0.0 -2.2 -1.4 0.9 0.5 0.1 -0.2 2.1 1.4 -1.0 -3.4 -1.9 +T 0.7 -0.6 -0.2 -0.2 -2.2 -1.0 -0.5 -0.3 0.1 -1.1 -0.4 0.4 0.1 -0.1 -0.3 1.4 2.5 0.2 -3.7 -2.1 +V 0.1 -0.2 -2.9 -2.1 0.1 -3.1 -2.1 3.2 -1.9 1.9 1.8 -2.2 -1.9 -1.7 -2.2 -1.0 0.2 3.4 -2.9 -1.4 +W -4.1 -0.9 -5.5 -4.7 3.0 -4.1 -1.0 -2.3 -3.6 -0.9 -1.3 -4.0 -5.2 -2.8 -1.6 -3.4 -3.7 -2.9 14.7 3.6 +Y -2.6 -0.4 -2.8 -3.0 5.3 -4.3 2.5 -1.0 -2.4 -0.1 -0.5 -1.4 -3.4 -1.8 -2.0 -1.9 -2.1 -1.4 3.6 8.1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLASTN b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLASTN new file mode 100644 index 0000000000000000000000000000000000000000..9244a8efcf8866dfd758ef05b55c793d13bf9272 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLASTN @@ -0,0 +1,29 @@ +# BLASTN default substitution scores. +# For the default gap scores, as used for BLASTN on NCBI Web +# BLAST, the BLAST documentation shows gap costs a = 5 for opening +# a gap, and b = 2 for each letter in the gap, and defines the +# total score of a gap of k residues as -(a + b*k). In contrast, +# Biopython follows the definition given in "Biological Sequence +# Analysis" (Durbin et al., 1998), for which the total score of a +# gap of k residues is -d - e * (k - 1), where d is the gap-open +# penalty and e is the gap-extend penalty. Biopython uses -d as +# the gap open score and -e as the gap extend penalty: +# gap open score: -7 +# gap extend score: -2 +# with the substitution matrix below, as the BLASTN score parameters. + A T G C S W R Y K M B V H D N +A 2 -3 -3 -3 -3 -1 -1 -3 -3 -1 -3 -1 -1 -1 -2 +T -3 2 -3 -3 -3 -1 -3 -1 -1 -3 -1 -3 -1 -1 -2 +G -3 -3 2 -3 -1 -3 -1 -3 -1 -3 -1 -1 -3 -1 -2 +C -3 -3 -3 2 -1 -3 -3 -1 -3 -1 -1 -1 -1 -3 -2 +S -3 -3 -1 -1 -1 -3 -1 -1 -1 -1 -1 -1 -1 -1 -2 +W -1 -1 -3 -3 -3 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 +R -1 -3 -1 -3 -1 -1 -1 -3 -1 -1 -1 -1 -1 -1 -2 +Y -3 -1 -3 -1 -1 -1 -3 -1 -1 -1 -1 -1 -1 -1 -2 +K -3 -1 -1 -3 -1 -1 -1 -1 -1 -3 -1 -1 -1 -1 -2 +M -1 -3 -3 -1 -1 -1 -1 -1 -3 -1 -1 -1 -1 -1 -2 +B -3 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 +V -1 -3 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 +H -1 -1 -3 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 +D -1 -1 -1 -3 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 +N -2 -2 -2 -2 -2 -2 -2 -2 -2 -2 -2 -2 -2 -2 -2 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLASTP b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLASTP new file mode 100644 index 0000000000000000000000000000000000000000..0b4a61185d199571a46815f07bb708005aa26284 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLASTP @@ -0,0 +1,44 @@ +# BLASTP default substitution scores. +# For the default gap scores, as used for BLASTP on NCBI Web +# BLAST, the BLAST documentation shows gap costs a = 11 for opening +# a gap, and b = 1 for each letter in the gap, and defines the +# total score of a gap of k residues as -(a + b*k). In contrast, +# Biopython follows the definition given in "Biological Sequence +# Analysis" (Durbin et al., 1998), for which the total score of a +# gap of k residues is -d - e * (k - 1), where d is the gap-open +# penalty and e is the gap-extend penalty. Biopython uses -d as +# the gap open score and -e as the gap extend penalty: +# gap open score: -12 +# gap extend score: -1 +# with the substitution matrix below, as the BLASTP score parameters. +# The substitution matrix is identical to BLOSUM62, except for some +# values of the ambiguous amino acids B, Z, and X; the values for +# the ambiguous amino acids U, O, and J are not included in BLOSUM62. + A B C D E F G H I J K L M N O P Q R S T U V W X Y Z * +A 4 -2 0 -2 -1 -2 0 -2 -1 -1 -1 -1 -1 -2 -1 -1 -1 -1 1 0 0 0 -3 -1 -2 -1 -4 +B -2 4 -3 4 1 -3 -1 0 -3 -3 0 -4 -3 4 -1 -2 0 -1 0 -1 -3 -3 -4 -1 -3 0 -4 +C 0 -3 9 -3 -4 -2 -3 -3 -1 -1 -3 -1 -1 -3 -1 -3 -3 -3 -1 -1 9 -1 -2 -1 -2 -3 -4 +D -2 4 -3 6 2 -3 -1 -1 -3 -3 -1 -4 -3 1 -1 -1 0 -2 0 -1 -3 -3 -4 -1 -3 1 -4 +E -1 1 -4 2 5 -3 -2 0 -3 -3 1 -3 -2 0 -1 -1 2 0 0 -1 -4 -2 -3 -1 -2 4 -4 +F -2 -3 -2 -3 -3 6 -3 -1 0 0 -3 0 0 -3 -1 -4 -3 -3 -2 -2 -2 -1 1 -1 3 -3 -4 +G 0 -1 -3 -1 -2 -3 6 -2 -4 -4 -2 -4 -3 0 -1 -2 -2 -2 0 -2 -3 -3 -2 -1 -3 -2 -4 +H -2 0 -3 -1 0 -1 -2 8 -3 -3 -1 -3 -2 1 -1 -2 0 0 -1 -2 -3 -3 -2 -1 2 0 -4 +I -1 -3 -1 -3 -3 0 -4 -3 4 3 -3 2 1 -3 -1 -3 -3 -3 -2 -1 -1 3 -3 -1 -1 -3 -4 +J -1 -3 -1 -3 -3 0 -4 -3 3 3 -3 3 2 -3 -1 -3 -2 -2 -2 -1 -1 2 -2 -1 -1 -3 -4 +K -1 0 -3 -1 1 -3 -2 -1 -3 -3 5 -2 -1 0 -1 -1 1 2 0 -1 -3 -2 -3 -1 -2 1 -4 +L -1 -4 -1 -4 -3 0 -4 -3 2 3 -2 4 2 -3 -1 -3 -2 -2 -2 -1 -1 1 -2 -1 -1 -3 -4 +M -1 -3 -1 -3 -2 0 -3 -2 1 2 -1 2 5 -2 -1 -2 0 -1 -1 -1 -1 1 -1 -1 -1 -1 -4 +N -2 4 -3 1 0 -3 0 1 -3 -3 0 -3 -2 6 -1 -2 0 0 1 0 -3 -3 -4 -1 -2 0 -4 +O -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -4 +P -1 -2 -3 -1 -1 -4 -2 -2 -3 -3 -1 -3 -2 -2 -1 7 -1 -2 -1 -1 -3 -2 -4 -1 -3 -1 -4 +Q -1 0 -3 0 2 -3 -2 0 -3 -2 1 -2 0 0 -1 -1 5 1 0 -1 -3 -2 -2 -1 -1 4 -4 +R -1 -1 -3 -2 0 -3 -2 0 -3 -2 2 -2 -1 0 -1 -2 1 5 -1 -1 -3 -3 -3 -1 -2 0 -4 +S 1 0 -1 0 0 -2 0 -1 -2 -2 0 -2 -1 1 -1 -1 0 -1 4 1 -1 -2 -3 -1 -2 0 -4 +T 0 -1 -1 -1 -1 -2 -2 -2 -1 -1 -1 -1 -1 0 -1 -1 -1 -1 1 5 -1 0 -2 -1 -2 -1 -4 +U 0 -3 9 -3 -4 -2 -3 -3 -1 -1 -3 -1 -1 -3 -1 -3 -3 -3 -1 -1 9 -1 -2 -1 -2 -3 -4 +V 0 -3 -1 -3 -2 -1 -3 -3 3 2 -2 1 1 -3 -1 -2 -2 -3 -2 0 -1 4 -3 -1 -1 -2 -4 +W -3 -4 -2 -4 -3 1 -2 -2 -3 -2 -3 -2 -1 -4 -1 -4 -2 -3 -3 -2 -2 -3 11 -1 2 -2 -4 +X -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -4 +Y -2 -3 -2 -3 -2 3 -3 2 -1 -1 -2 -1 -1 -2 -1 -3 -1 -2 -2 -2 -2 -1 2 -1 7 -2 -4 +Z -1 0 -3 1 4 -3 -2 0 -3 -3 1 -3 -1 0 -1 -1 4 0 0 -1 -3 -2 -2 -1 -2 4 -4 +* -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM45 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM45 new file mode 100644 index 0000000000000000000000000000000000000000..18c3323896f4f802558e6eda688f467a582a3d5e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM45 @@ -0,0 +1,31 @@ +# Matrix made by matblas from blosum45.iij +# * column uses minimum score +# BLOSUM Clustered Scoring Matrix in 1/3 Bit Units +# Blocks Database = /data/blocks_5.0/blocks.dat +# Cluster Percentage: >= 45 +# Entropy = 0.3795, Expected = -0.2789 + A R N D C Q E G H I L K M F P S T W Y V B Z X * +A 5 -2 -1 -2 -1 -1 -1 0 -2 -1 -1 -1 -1 -2 -1 1 0 -2 -2 0 -1 -1 0 -5 +R -2 7 0 -1 -3 1 0 -2 0 -3 -2 3 -1 -2 -2 -1 -1 -2 -1 -2 -1 0 -1 -5 +N -1 0 6 2 -2 0 0 0 1 -2 -3 0 -2 -2 -2 1 0 -4 -2 -3 4 0 -1 -5 +D -2 -1 2 7 -3 0 2 -1 0 -4 -3 0 -3 -4 -1 0 -1 -4 -2 -3 5 1 -1 -5 +C -1 -3 -2 -3 12 -3 -3 -3 -3 -3 -2 -3 -2 -2 -4 -1 -1 -5 -3 -1 -2 -3 -2 -5 +Q -1 1 0 0 -3 6 2 -2 1 -2 -2 1 0 -4 -1 0 -1 -2 -1 -3 0 4 -1 -5 +E -1 0 0 2 -3 2 6 -2 0 -3 -2 1 -2 -3 0 0 -1 -3 -2 -3 1 4 -1 -5 +G 0 -2 0 -1 -3 -2 -2 7 -2 -4 -3 -2 -2 -3 -2 0 -2 -2 -3 -3 -1 -2 -1 -5 +H -2 0 1 0 -3 1 0 -2 10 -3 -2 -1 0 -2 -2 -1 -2 -3 2 -3 0 0 -1 -5 +I -1 -3 -2 -4 -3 -2 -3 -4 -3 5 2 -3 2 0 -2 -2 -1 -2 0 3 -3 -3 -1 -5 +L -1 -2 -3 -3 -2 -2 -2 -3 -2 2 5 -3 2 1 -3 -3 -1 -2 0 1 -3 -2 -1 -5 +K -1 3 0 0 -3 1 1 -2 -1 -3 -3 5 -1 -3 -1 -1 -1 -2 -1 -2 0 1 -1 -5 +M -1 -1 -2 -3 -2 0 -2 -2 0 2 2 -1 6 0 -2 -2 -1 -2 0 1 -2 -1 -1 -5 +F -2 -2 -2 -4 -2 -4 -3 -3 -2 0 1 -3 0 8 -3 -2 -1 1 3 0 -3 -3 -1 -5 +P -1 -2 -2 -1 -4 -1 0 -2 -2 -2 -3 -1 -2 -3 9 -1 -1 -3 -3 -3 -2 -1 -1 -5 +S 1 -1 1 0 -1 0 0 0 -1 -2 -3 -1 -2 -2 -1 4 2 -4 -2 -1 0 0 0 -5 +T 0 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -1 -1 2 5 -3 -1 0 0 -1 0 -5 +W -2 -2 -4 -4 -5 -2 -3 -2 -3 -2 -2 -2 -2 1 -3 -4 -3 15 3 -3 -4 -2 -2 -5 +Y -2 -1 -2 -2 -3 -1 -2 -3 2 0 0 -1 0 3 -3 -2 -1 3 8 -1 -2 -2 -1 -5 +V 0 -2 -3 -3 -1 -3 -3 -3 -3 3 1 -2 1 0 -3 -1 0 -3 -1 5 -3 -3 -1 -5 +B -1 -1 4 5 -2 0 1 -1 0 -3 -3 0 -2 -3 -2 0 0 -4 -2 -3 4 2 -1 -5 +Z -1 0 0 1 -3 4 4 -2 0 -3 -2 1 -1 -3 -1 0 -1 -2 -2 -3 2 4 -1 -5 +X 0 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 0 0 -2 -1 -1 -1 -1 -1 -5 +* -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM50 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM50 new file mode 100644 index 0000000000000000000000000000000000000000..3f62e3cf94390c8f58aafa467d7277011b6b20af --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM50 @@ -0,0 +1,31 @@ +# Matrix made by matblas from blosum50.iij +# * column uses minimum score +# BLOSUM Clustered Scoring Matrix in 1/3 Bit Units +# Blocks Database = /data/blocks_5.0/blocks.dat +# Cluster Percentage: >= 50 +# Entropy = 0.4808, Expected = -0.3573 + A R N D C Q E G H I L K M F P S T W Y V B Z X * +A 5 -2 -1 -2 -1 -1 -1 0 -2 -1 -2 -1 -1 -3 -1 1 0 -3 -2 0 -2 -1 -1 -5 +R -2 7 -1 -2 -4 1 0 -3 0 -4 -3 3 -2 -3 -3 -1 -1 -3 -1 -3 -1 0 -1 -5 +N -1 -1 7 2 -2 0 0 0 1 -3 -4 0 -2 -4 -2 1 0 -4 -2 -3 4 0 -1 -5 +D -2 -2 2 8 -4 0 2 -1 -1 -4 -4 -1 -4 -5 -1 0 -1 -5 -3 -4 5 1 -1 -5 +C -1 -4 -2 -4 13 -3 -3 -3 -3 -2 -2 -3 -2 -2 -4 -1 -1 -5 -3 -1 -3 -3 -2 -5 +Q -1 1 0 0 -3 7 2 -2 1 -3 -2 2 0 -4 -1 0 -1 -1 -1 -3 0 4 -1 -5 +E -1 0 0 2 -3 2 6 -3 0 -4 -3 1 -2 -3 -1 -1 -1 -3 -2 -3 1 5 -1 -5 +G 0 -3 0 -1 -3 -2 -3 8 -2 -4 -4 -2 -3 -4 -2 0 -2 -3 -3 -4 -1 -2 -2 -5 +H -2 0 1 -1 -3 1 0 -2 10 -4 -3 0 -1 -1 -2 -1 -2 -3 2 -4 0 0 -1 -5 +I -1 -4 -3 -4 -2 -3 -4 -4 -4 5 2 -3 2 0 -3 -3 -1 -3 -1 4 -4 -3 -1 -5 +L -2 -3 -4 -4 -2 -2 -3 -4 -3 2 5 -3 3 1 -4 -3 -1 -2 -1 1 -4 -3 -1 -5 +K -1 3 0 -1 -3 2 1 -2 0 -3 -3 6 -2 -4 -1 0 -1 -3 -2 -3 0 1 -1 -5 +M -1 -2 -2 -4 -2 0 -2 -3 -1 2 3 -2 7 0 -3 -2 -1 -1 0 1 -3 -1 -1 -5 +F -3 -3 -4 -5 -2 -4 -3 -4 -1 0 1 -4 0 8 -4 -3 -2 1 4 -1 -4 -4 -2 -5 +P -1 -3 -2 -1 -4 -1 -1 -2 -2 -3 -4 -1 -3 -4 10 -1 -1 -4 -3 -3 -2 -1 -2 -5 +S 1 -1 1 0 -1 0 -1 0 -1 -3 -3 0 -2 -3 -1 5 2 -4 -2 -2 0 0 -1 -5 +T 0 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1 2 5 -3 -2 0 0 -1 0 -5 +W -3 -3 -4 -5 -5 -1 -3 -3 -3 -3 -2 -3 -1 1 -4 -4 -3 15 2 -3 -5 -2 -3 -5 +Y -2 -1 -2 -3 -3 -1 -2 -3 2 -1 -1 -2 0 4 -3 -2 -2 2 8 -1 -3 -2 -1 -5 +V 0 -3 -3 -4 -1 -3 -3 -4 -4 4 1 -3 1 -1 -3 -2 0 -3 -1 5 -4 -3 -1 -5 +B -2 -1 4 5 -3 0 1 -1 0 -4 -4 0 -3 -4 -2 0 0 -5 -3 -4 5 2 -1 -5 +Z -1 0 0 1 -3 4 5 -2 0 -3 -3 1 -1 -4 -1 0 -1 -2 -2 -3 2 5 -1 -5 +X -1 -1 -1 -1 -2 -1 -1 -2 -1 -1 -1 -1 -1 -2 -2 -1 0 -3 -1 -1 -1 -1 -1 -5 +* -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 -5 1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM62 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM62 new file mode 100644 index 0000000000000000000000000000000000000000..205f139aa2f8c879f6426708fe316be8bf55f771 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM62 @@ -0,0 +1,31 @@ +# Matrix made by matblas from blosum62.iij +# * column uses minimum score +# BLOSUM Clustered Scoring Matrix in 1/2 Bit Units +# Blocks Database = /data/blocks_5.0/blocks.dat +# Cluster Percentage: >= 62 +# Entropy = 0.6979, Expected = -0.5209 + A R N D C Q E G H I L K M F P S T W Y V B Z X * +A 4 -1 -2 -2 0 -1 -1 0 -2 -1 -1 -1 -1 -2 -1 1 0 -3 -2 0 -2 -1 0 -4 +R -1 5 0 -2 -3 1 0 -2 0 -3 -2 2 -1 -3 -2 -1 -1 -3 -2 -3 -1 0 -1 -4 +N -2 0 6 1 -3 0 0 0 1 -3 -3 0 -2 -3 -2 1 0 -4 -2 -3 3 0 -1 -4 +D -2 -2 1 6 -3 0 2 -1 -1 -3 -4 -1 -3 -3 -1 0 -1 -4 -3 -3 4 1 -1 -4 +C 0 -3 -3 -3 9 -3 -4 -3 -3 -1 -1 -3 -1 -2 -3 -1 -1 -2 -2 -1 -3 -3 -2 -4 +Q -1 1 0 0 -3 5 2 -2 0 -3 -2 1 0 -3 -1 0 -1 -2 -1 -2 0 3 -1 -4 +E -1 0 0 2 -4 2 5 -2 0 -3 -3 1 -2 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4 +G 0 -2 0 -1 -3 -2 -2 6 -2 -4 -4 -2 -3 -3 -2 0 -2 -2 -3 -3 -1 -2 -1 -4 +H -2 0 1 -1 -3 0 0 -2 8 -3 -3 -1 -2 -1 -2 -1 -2 -2 2 -3 0 0 -1 -4 +I -1 -3 -3 -3 -1 -3 -3 -4 -3 4 2 -3 1 0 -3 -2 -1 -3 -1 3 -3 -3 -1 -4 +L -1 -2 -3 -4 -1 -2 -3 -4 -3 2 4 -2 2 0 -3 -2 -1 -2 -1 1 -4 -3 -1 -4 +K -1 2 0 -1 -3 1 1 -2 -1 -3 -2 5 -1 -3 -1 0 -1 -3 -2 -2 0 1 -1 -4 +M -1 -1 -2 -3 -1 0 -2 -3 -2 1 2 -1 5 0 -2 -1 -1 -1 -1 1 -3 -1 -1 -4 +F -2 -3 -3 -3 -2 -3 -3 -3 -1 0 0 -3 0 6 -4 -2 -2 1 3 -1 -3 -3 -1 -4 +P -1 -2 -2 -1 -3 -1 -1 -2 -2 -3 -3 -1 -2 -4 7 -1 -1 -4 -3 -2 -2 -1 -2 -4 +S 1 -1 1 0 -1 0 0 0 -1 -2 -2 0 -1 -2 -1 4 1 -3 -2 -2 0 0 0 -4 +T 0 -1 0 -1 -1 -1 -1 -2 -2 -1 -1 -1 -1 -2 -1 1 5 -2 -2 0 -1 -1 0 -4 +W -3 -3 -4 -4 -2 -2 -3 -2 -2 -3 -2 -3 -1 1 -4 -3 -2 11 2 -3 -4 -3 -2 -4 +Y -2 -2 -2 -3 -2 -1 -2 -3 2 -1 -1 -2 -1 3 -3 -2 -2 2 7 -1 -3 -2 -1 -4 +V 0 -3 -3 -3 -1 -2 -2 -3 -3 3 1 -2 1 -1 -2 -2 0 -3 -1 4 -3 -2 -1 -4 +B -2 -1 3 4 -3 0 1 -1 0 -3 -4 0 -3 -3 -2 0 -1 -4 -3 -3 4 1 -1 -4 +Z -1 0 0 1 -3 3 4 -2 0 -3 -3 1 -1 -3 -1 0 -1 -3 -2 -2 1 4 -1 -4 +X 0 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -2 0 0 -2 -1 -1 -1 -1 -1 -4 +* -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 -4 1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM80 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM80 new file mode 100644 index 0000000000000000000000000000000000000000..78172a3592b5322c5e9429e2e4661dc5c374d9eb --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM80 @@ -0,0 +1,31 @@ +# Matrix made by matblas from blosum80_3.iij +# * column uses minimum score +# BLOSUM Clustered Scoring Matrix in 1/3 Bit Units +# Blocks Database = /data/blocks_5.0/blocks.dat +# Cluster Percentage: >= 80 +# Entropy = 0.9868, Expected = -0.7442 + A R N D C Q E G H I L K M F P S T W Y V B Z X * +A 7 -3 -3 -3 -1 -2 -2 0 -3 -3 -3 -1 -2 -4 -1 2 0 -5 -4 -1 -3 -2 -1 -8 +R -3 9 -1 -3 -6 1 -1 -4 0 -5 -4 3 -3 -5 -3 -2 -2 -5 -4 -4 -2 0 -2 -8 +N -3 -1 9 2 -5 0 -1 -1 1 -6 -6 0 -4 -6 -4 1 0 -7 -4 -5 5 -1 -2 -8 +D -3 -3 2 10 -7 -1 2 -3 -2 -7 -7 -2 -6 -6 -3 -1 -2 -8 -6 -6 6 1 -3 -8 +C -1 -6 -5 -7 13 -5 -7 -6 -7 -2 -3 -6 -3 -4 -6 -2 -2 -5 -5 -2 -6 -7 -4 -8 +Q -2 1 0 -1 -5 9 3 -4 1 -5 -4 2 -1 -5 -3 -1 -1 -4 -3 -4 -1 5 -2 -8 +E -2 -1 -1 2 -7 3 8 -4 0 -6 -6 1 -4 -6 -2 -1 -2 -6 -5 -4 1 6 -2 -8 +G 0 -4 -1 -3 -6 -4 -4 9 -4 -7 -7 -3 -5 -6 -5 -1 -3 -6 -6 -6 -2 -4 -3 -8 +H -3 0 1 -2 -7 1 0 -4 12 -6 -5 -1 -4 -2 -4 -2 -3 -4 3 -5 -1 0 -2 -8 +I -3 -5 -6 -7 -2 -5 -6 -7 -6 7 2 -5 2 -1 -5 -4 -2 -5 -3 4 -6 -6 -2 -8 +L -3 -4 -6 -7 -3 -4 -6 -7 -5 2 6 -4 3 0 -5 -4 -3 -4 -2 1 -7 -5 -2 -8 +K -1 3 0 -2 -6 2 1 -3 -1 -5 -4 8 -3 -5 -2 -1 -1 -6 -4 -4 -1 1 -2 -8 +M -2 -3 -4 -6 -3 -1 -4 -5 -4 2 3 -3 9 0 -4 -3 -1 -3 -3 1 -5 -3 -2 -8 +F -4 -5 -6 -6 -4 -5 -6 -6 -2 -1 0 -5 0 10 -6 -4 -4 0 4 -2 -6 -6 -3 -8 +P -1 -3 -4 -3 -6 -3 -2 -5 -4 -5 -5 -2 -4 -6 12 -2 -3 -7 -6 -4 -4 -2 -3 -8 +S 2 -2 1 -1 -2 -1 -1 -1 -2 -4 -4 -1 -3 -4 -2 7 2 -6 -3 -3 0 -1 -1 -8 +T 0 -2 0 -2 -2 -1 -2 -3 -3 -2 -3 -1 -1 -4 -3 2 8 -5 -3 0 -1 -2 -1 -8 +W -5 -5 -7 -8 -5 -4 -6 -6 -4 -5 -4 -6 -3 0 -7 -6 -5 16 3 -5 -8 -5 -5 -8 +Y -4 -4 -4 -6 -5 -3 -5 -6 3 -3 -2 -4 -3 4 -6 -3 -3 3 11 -3 -5 -4 -3 -8 +V -1 -4 -5 -6 -2 -4 -4 -6 -5 4 1 -4 1 -2 -4 -3 0 -5 -3 7 -6 -4 -2 -8 +B -3 -2 5 6 -6 -1 1 -2 -1 -6 -7 -1 -5 -6 -4 0 -1 -8 -5 -6 6 0 -3 -8 +Z -2 0 -1 1 -7 5 6 -4 0 -6 -5 1 -3 -6 -2 -1 -2 -5 -4 -4 0 6 -1 -8 +X -1 -2 -2 -3 -4 -2 -2 -3 -2 -2 -2 -2 -2 -3 -3 -1 -1 -5 -3 -2 -3 -1 -2 -8 +* -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM90 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM90 new file mode 100644 index 0000000000000000000000000000000000000000..71441b54b015e3a95d414803c1b20c5c88d12a2c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/BLOSUM90 @@ -0,0 +1,31 @@ +# Matrix made by matblas from blosum90.iij +# * column uses minimum score +# BLOSUM Clustered Scoring Matrix in 1/2 Bit Units +# Blocks Database = /data/blocks_5.0/blocks.dat +# Cluster Percentage: >= 90 +# Entropy = 1.1806, Expected = -0.8887 + A R N D C Q E G H I L K M F P S T W Y V B Z X * +A 5 -2 -2 -3 -1 -1 -1 0 -2 -2 -2 -1 -2 -3 -1 1 0 -4 -3 -1 -2 -1 -1 -6 +R -2 6 -1 -3 -5 1 -1 -3 0 -4 -3 2 -2 -4 -3 -1 -2 -4 -3 -3 -2 0 -2 -6 +N -2 -1 7 1 -4 0 -1 -1 0 -4 -4 0 -3 -4 -3 0 0 -5 -3 -4 4 -1 -2 -6 +D -3 -3 1 7 -5 -1 1 -2 -2 -5 -5 -1 -4 -5 -3 -1 -2 -6 -4 -5 4 0 -2 -6 +C -1 -5 -4 -5 9 -4 -6 -4 -5 -2 -2 -4 -2 -3 -4 -2 -2 -4 -4 -2 -4 -5 -3 -6 +Q -1 1 0 -1 -4 7 2 -3 1 -4 -3 1 0 -4 -2 -1 -1 -3 -3 -3 -1 4 -1 -6 +E -1 -1 -1 1 -6 2 6 -3 -1 -4 -4 0 -3 -5 -2 -1 -1 -5 -4 -3 0 4 -2 -6 +G 0 -3 -1 -2 -4 -3 -3 6 -3 -5 -5 -2 -4 -5 -3 -1 -3 -4 -5 -5 -2 -3 -2 -6 +H -2 0 0 -2 -5 1 -1 -3 8 -4 -4 -1 -3 -2 -3 -2 -2 -3 1 -4 -1 0 -2 -6 +I -2 -4 -4 -5 -2 -4 -4 -5 -4 5 1 -4 1 -1 -4 -3 -1 -4 -2 3 -5 -4 -2 -6 +L -2 -3 -4 -5 -2 -3 -4 -5 -4 1 5 -3 2 0 -4 -3 -2 -3 -2 0 -5 -4 -2 -6 +K -1 2 0 -1 -4 1 0 -2 -1 -4 -3 6 -2 -4 -2 -1 -1 -5 -3 -3 -1 1 -1 -6 +M -2 -2 -3 -4 -2 0 -3 -4 -3 1 2 -2 7 -1 -3 -2 -1 -2 -2 0 -4 -2 -1 -6 +F -3 -4 -4 -5 -3 -4 -5 -5 -2 -1 0 -4 -1 7 -4 -3 -3 0 3 -2 -4 -4 -2 -6 +P -1 -3 -3 -3 -4 -2 -2 -3 -3 -4 -4 -2 -3 -4 8 -2 -2 -5 -4 -3 -3 -2 -2 -6 +S 1 -1 0 -1 -2 -1 -1 -1 -2 -3 -3 -1 -2 -3 -2 5 1 -4 -3 -2 0 -1 -1 -6 +T 0 -2 0 -2 -2 -1 -1 -3 -2 -1 -2 -1 -1 -3 -2 1 6 -4 -2 -1 -1 -1 -1 -6 +W -4 -4 -5 -6 -4 -3 -5 -4 -3 -4 -3 -5 -2 0 -5 -4 -4 11 2 -3 -6 -4 -3 -6 +Y -3 -3 -3 -4 -4 -3 -4 -5 1 -2 -2 -3 -2 3 -4 -3 -2 2 8 -3 -4 -3 -2 -6 +V -1 -3 -4 -5 -2 -3 -3 -5 -4 3 0 -3 0 -2 -3 -2 -1 -3 -3 5 -4 -3 -2 -6 +B -2 -2 4 4 -4 -1 0 -2 -1 -5 -5 -1 -4 -4 -3 0 -1 -6 -4 -4 4 0 -2 -6 +Z -1 0 -1 0 -5 4 4 -3 0 -4 -4 1 -2 -4 -2 -1 -1 -4 -3 -3 0 4 -1 -6 +X -1 -2 -2 -2 -3 -1 -2 -2 -2 -2 -2 -1 -1 -2 -2 -1 -1 -3 -2 -2 -2 -1 -2 -6 +* -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 -6 1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/DAYHOFF b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/DAYHOFF new file mode 100644 index 0000000000000000000000000000000000000000..e8aecac6442d1cf9108534efccb8cd98af8bc373 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/DAYHOFF @@ -0,0 +1,27 @@ +# M.O. Dayhoff, R.M. Schwartz, and B.C. Orcutt: +# "A Model of Evolutionary Change in Proteins." +# Margaret O. Dayhoff: Atlas of Protein Sequence and Structure, +# Volume 5, Supplement 3, 1978, pages 345-352. +# The National Biomedical Research Foundation, 1979. +# Figure 84, page 352. + A C D E F G H I K L M N P Q R S T V W Y +A 0.2 -0.2 0.0 0.0 -0.4 0.1 -0.1 -0.1 -0.1 -0.2 -0.1 0.0 0.1 0.0 -0.2 0.1 0.1 0.0 -0.6 -0.3 +C -0.2 1.2 -0.5 -0.5 -0.4 -0.3 -0.3 -0.2 -0.5 -0.6 -0.5 -0.4 -0.3 -0.5 -0.4 0.0 -0.2 -0.2 -0.8 0.0 +D 0.0 -0.5 0.4 0.3 -0.6 0.1 0.1 -0.2 0.0 -0.4 -0.3 0.2 -0.1 0.2 -0.1 0.0 0.0 -0.2 -0.7 -0.4 +E 0.0 -0.5 0.3 0.4 -0.5 0.0 0.1 -0.2 0.0 -0.3 -0.2 0.1 -0.1 0.2 -0.1 0.0 0.0 -0.2 -0.7 -0.4 +F -0.4 -0.4 -0.6 -0.5 0.9 -0.5 -0.2 0.1 -0.5 0.2 0.0 -0.4 -0.5 -0.5 -0.4 -0.3 -0.3 -0.1 0.0 0.7 +G 0.1 -0.3 0.1 0.0 -0.5 0.5 -0.2 -0.3 -0.2 -0.4 -0.3 0.0 -0.1 -0.1 -0.3 0.1 0.0 -0.1 -0.7 -0.5 +H -0.1 -0.3 0.1 0.1 -0.2 -0.2 0.6 -0.2 0.0 -0.2 -0.2 0.2 0.0 0.3 0.2 -0.1 -0.1 -0.2 -0.3 0.0 +I -0.1 -0.2 -0.2 -0.2 0.1 -0.3 -0.2 0.5 -0.2 0.2 0.2 -0.2 -0.2 -0.2 -0.2 -0.1 0.0 0.4 -0.5 -0.1 +K -0.1 -0.5 0.0 0.0 -0.5 -0.2 0.0 -0.2 0.5 -0.3 0.0 0.1 -0.1 0.1 0.3 0.0 0.0 -0.2 -0.3 -0.4 +L -0.2 -0.6 -0.4 -0.3 0.2 -0.4 -0.2 0.2 -0.3 0.6 0.4 -0.3 -0.3 -0.2 -0.3 -0.3 -0.2 0.2 -0.2 -0.1 +M -0.1 -0.5 -0.3 -0.2 0.0 -0.3 -0.2 0.2 0.0 0.4 0.6 -0.2 -0.2 -0.1 0.0 -0.2 -0.1 0.2 -0.4 -0.2 +N 0.0 -0.4 0.2 0.1 -0.4 0.0 0.2 -0.2 0.1 -0.3 -0.2 0.2 -0.1 0.1 0.0 0.1 0.0 -0.2 -0.4 -0.2 +P 0.1 -0.3 -0.1 -0.1 -0.5 -0.1 0.0 -0.2 -0.1 -0.3 -0.2 -0.1 0.6 0.0 0.0 0.1 0.0 -0.1 -0.6 -0.5 +Q 0.0 -0.5 0.2 0.2 -0.5 -0.1 0.3 -0.2 0.1 -0.2 -0.1 0.1 0.0 0.4 0.1 -0.1 -0.1 -0.2 -0.5 -0.4 +R -0.2 -0.4 -0.1 -0.1 -0.4 -0.3 0.2 -0.2 0.3 -0.3 0.0 0.0 0.0 0.1 0.6 0.0 -0.1 -0.2 0.2 -0.4 +S 0.1 0.0 0.0 0.0 -0.3 0.1 -0.1 -0.1 0.0 -0.3 -0.2 0.1 0.1 -0.1 0.0 0.2 0.1 -0.1 -0.2 -0.3 +T 0.1 -0.2 0.0 0.0 -0.3 0.0 -0.1 0.0 0.0 -0.2 -0.1 0.0 0.0 -0.1 -0.1 0.1 0.3 0.0 -0.5 -0.3 +V 0.0 -0.2 -0.2 -0.2 -0.1 -0.1 -0.2 0.4 -0.2 0.2 0.2 -0.2 -0.1 -0.2 -0.2 -0.1 0.0 0.4 -0.6 -0.2 +W -0.6 -0.8 -0.7 -0.7 0.0 -0.7 -0.3 -0.5 -0.3 -0.2 -0.4 -0.4 -0.6 -0.5 0.2 -0.2 -0.5 -0.6 1.7 0.0 +Y -0.3 0.0 -0.4 -0.4 0.7 -0.5 0.0 -0.1 -0.4 -0.1 -0.2 -0.2 -0.5 -0.4 -0.4 -0.3 -0.3 -0.2 0.0 1.0 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/FENG b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/FENG new file mode 100644 index 0000000000000000000000000000000000000000..ebd5c2d19a2c9ee6be8da820564e20be464f6e4f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/FENG @@ -0,0 +1,26 @@ +# D.F. Feng, M.S. Johnson, R.F. Doolittle: +# "Aligning amino acid sequences: Comparison of commonly used methods." +# Journal of Molecular Evolution 21(2): 112-125 (1985). +# Table 1, upper triangle. +# PMID 6100188 + A C D E F G H I K L M N P Q R S T V W Y +A 6 2 4 4 2 5 2 2 3 2 2 3 5 3 2 5 5 5 2 2 +C 2 6 1 0 3 3 2 2 0 2 2 2 2 1 2 4 2 2 3 3 +D 4 1 6 5 1 4 3 1 3 1 0 5 2 4 2 3 2 3 0 2 +E 4 0 5 6 0 4 2 1 4 1 1 3 3 4 2 3 3 4 1 1 +F 2 3 1 0 6 1 2 4 0 4 2 1 2 1 1 3 1 4 3 5 +G 5 3 4 4 1 6 1 2 2 2 1 3 3 2 3 5 2 4 3 2 +H 2 2 3 2 2 1 6 1 3 3 1 4 3 4 4 3 2 1 1 3 +I 2 2 1 1 4 2 1 6 2 5 4 2 2 1 2 2 3 5 2 3 +K 3 0 3 4 0 2 3 2 6 2 2 4 2 4 5 3 4 3 1 1 +L 2 2 1 1 4 2 3 5 2 6 5 1 3 2 2 2 2 5 4 3 +M 2 2 0 1 2 1 1 4 2 5 6 1 2 2 2 1 3 4 3 2 +N 3 2 5 3 1 3 4 2 4 1 1 6 2 3 2 5 4 2 0 3 +P 5 2 2 3 2 3 3 2 2 3 2 2 6 3 3 4 4 3 2 2 +Q 3 1 4 4 1 2 4 1 4 2 2 3 3 6 3 3 3 2 1 2 +R 2 2 2 2 1 3 4 2 5 2 2 2 3 3 6 3 3 2 2 1 +S 5 4 3 3 3 5 3 2 3 2 1 5 4 3 3 6 5 2 2 3 +T 5 2 2 3 1 2 2 3 4 2 3 4 4 3 3 5 6 3 1 2 +V 5 2 3 4 4 4 1 5 3 5 4 2 3 2 2 2 3 6 3 3 +W 2 3 0 1 3 3 1 2 1 4 3 0 2 1 2 2 1 3 6 3 +Y 2 3 2 1 5 2 3 3 1 3 2 3 2 2 1 3 2 3 3 6 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/GENETIC b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/GENETIC new file mode 100644 index 0000000000000000000000000000000000000000..79fc69b14b99874c700dca8da2ca1e278b7b993e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/GENETIC @@ -0,0 +1,27 @@ +# S.A. Benner, M.A. Cohen, G.H. Gonnet: +# "Amino acid substitution during functionally constrained divergent evolution +# of protein sequences." +# Figure 5. +# Protein Engineering 7(11): 1323-1332 (1994). +# PMID 7700864 + A C D E F G H I K L M N P Q R S T V W Y +A 4.0 -1.9 1.0 1.3 -2.4 1.2 -2.1 -1.8 -1.9 -2.3 -2.0 -1.7 0.8 -2.1 -1.6 0.1 0.9 1.0 -2.2 -2.4 +C -1.9 5.5 -1.6 -3.0 1.8 1.0 -1.6 -1.9 -3.2 -1.3 -2.7 -1.5 -1.9 -3.1 0.7 1.5 -1.9 -2.2 4.1 2.6 +D 1.0 -1.6 4.8 3.8 -1.7 1.1 1.7 -2.1 0.3 -2.4 -2.5 1.7 -2.2 0.3 -2.3 -2.1 -2.1 1.0 -2.9 2.3 +E 1.3 -3.0 3.8 5.7 -2.9 1.4 0.3 -2.3 2.0 -2.5 -1.8 0.3 -2.1 2.0 -2.0 -2.8 -2.1 1.3 -3.2 -0.9 +F -2.4 1.8 -1.7 -2.9 4.5 -1.9 -1.1 1.3 -2.8 2.2 0.5 -1.3 -1.8 -2.1 -1.5 0.0 -2.1 1.0 0.0 2.0 +G 1.2 1.0 1.1 1.4 -1.9 4.2 -2.2 -2.5 -2.2 -2.2 -2.3 -2.6 -1.8 -2.1 0.8 -0.6 -2.1 1.1 1.4 -1.8 +H -2.1 -1.6 1.7 0.3 -1.1 -2.2 4.7 -1.8 0.6 -0.1 -1.8 1.8 0.7 3.6 3.6 -1.6 -1.8 -2.1 -2.1 2.3 +I -1.8 -1.9 -2.1 -2.3 1.3 -2.5 -1.8 4.1 0.7 1.2 3.3 0.9 -1.6 -1.9 -1.2 -0.5 0.8 1.0 -2.2 -1.6 +K -1.9 -3.2 0.3 2.0 -2.8 -2.2 0.6 0.7 5.6 -2.0 1.6 3.5 -1.5 2.2 -0.2 -1.5 1.0 -2.1 -3.0 -0.8 +L -2.3 -1.3 -2.4 -2.5 2.2 -2.2 -0.1 1.2 -2.0 3.4 1.5 -2.2 0.0 0.1 -0.4 -1.2 -1.9 1.1 -0.3 -1.6 +M -2.0 -2.7 -2.5 -1.8 0.5 -2.3 -1.8 3.3 1.6 1.5 5.4 0.1 -1.4 -1.2 -0.4 -1.3 0.7 1.0 -2.0 -2.9 +N -1.7 -1.5 1.7 0.3 -1.3 -2.6 1.8 0.9 3.5 -2.2 0.1 4.7 -1.6 0.4 -1.5 -0.3 0.9 -2.2 -3.0 2.5 +P 0.8 -1.9 -2.2 -2.1 -1.8 -1.8 0.7 -1.6 -1.5 0.0 -1.4 -1.6 3.8 1.0 0.3 0.4 1.1 -2.1 -1.6 -2.3 +Q -2.1 -3.1 0.3 2.0 -2.1 -2.1 3.6 -1.9 2.2 0.1 -1.2 0.4 1.0 5.5 0.3 -2.3 -1.7 -2.0 -2.3 -0.8 +R -1.6 0.7 -2.3 -2.0 -1.5 0.8 3.6 -1.2 -0.2 -0.4 -0.4 -1.5 0.3 0.3 2.9 0.3 -0.6 -2.1 1.8 -1.9 +S 0.1 1.5 -2.1 -2.8 0.0 -0.6 -1.6 -0.5 -1.5 -1.2 -1.3 -0.3 0.4 -2.3 0.3 2.6 1.0 -2.2 0.8 0.3 +T 0.9 -1.9 -2.1 -2.1 -2.1 -2.1 -1.8 0.8 1.0 -1.9 0.7 0.9 1.1 -1.7 -0.6 1.0 4.0 -2.2 -2.2 -2.1 +V 1.0 -2.2 1.0 1.3 1.0 1.1 -2.1 1.0 -2.1 1.1 1.0 -2.2 -2.1 -2.0 -2.1 -2.2 -2.2 4.1 -2.1 -2.2 +W -2.2 4.1 -2.9 -3.2 0.0 1.4 -2.1 -2.2 -3.0 -0.3 -2.0 -3.0 -1.6 -2.3 1.8 0.8 -2.2 -2.1 7.5 -0.5 +Y -2.4 2.6 2.3 -0.9 2.0 -1.8 2.3 -1.6 -0.8 -1.6 -2.9 2.5 -2.3 -0.8 -1.9 0.3 -2.1 -2.2 -0.5 6.5 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/GONNET1992 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/GONNET1992 new file mode 100644 index 0000000000000000000000000000000000000000..ac4e8218bc45d38c85aa1ce246b62178628db0de --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/GONNET1992 @@ -0,0 +1,26 @@ +# Gaston H. Gonnet, Mark A. Cohen, Steven A. Benner: +# "Exhaustive matching of the entire protein sequence database." +# Science 256(5062): 1443-1445 (1992). +# Figure 2. +# PMID 1604319 + A C D E F G H I K L M N P Q R S T V W Y +A 2.4 0.5 -0.3 0.0 -2.3 0.5 -0.8 -0.8 -0.4 -1.2 -0.7 -0.3 0.3 -0.2 -0.6 1.1 0.6 0.1 -3.6 -2.2 +C 0.5 11.5 -3.2 -3.0 -0.8 -2.0 -1.3 -1.1 -2.8 -1.5 -0.9 -1.8 -3.1 -2.4 -2.2 0.1 -0.5 0.0 -1.0 -0.5 +D -0.3 -3.2 4.7 2.7 -4.5 0.1 0.4 -3.8 0.5 -4.0 -3.0 2.2 -0.7 0.9 -0.3 0.5 0.0 -2.9 -5.2 -2.8 +E 0.0 -3.0 2.7 3.6 -3.9 -0.8 0.4 -2.7 1.2 -2.8 -2.0 0.9 -0.5 1.7 0.4 0.2 -0.1 -1.9 -4.3 -2.7 +F -2.3 -0.8 -4.5 -3.9 7.0 -5.2 -0.1 1.0 -3.3 2.0 1.6 -3.1 -3.8 -2.6 -3.2 -2.8 -2.2 0.1 3.6 5.1 +G 0.5 -2.0 0.1 -0.8 -5.2 6.6 -1.4 -4.5 -1.1 -4.4 -3.5 0.4 -1.6 -1.0 -1.0 0.4 -1.1 -3.3 -4.0 -4.0 +H -0.8 -1.3 0.4 0.4 -0.1 -1.4 6.0 -2.2 0.6 -1.9 -1.3 1.2 -1.1 1.2 0.6 -0.2 -0.3 -2.0 -0.8 2.2 +I -0.8 -1.1 -3.8 -2.7 1.0 -4.5 -2.2 4.0 -2.1 2.8 2.5 -2.8 -2.6 -1.9 -2.4 -1.8 -0.6 3.1 -1.8 -0.7 +K -0.4 -2.8 0.5 1.2 -3.3 -1.1 0.6 -2.1 3.2 -2.1 -1.4 0.8 -0.6 1.5 2.7 0.1 0.1 -1.7 -3.5 -2.1 +L -1.2 -1.5 -4.0 -2.8 2.0 -4.4 -1.9 2.8 -2.1 4.0 2.8 -3.0 -2.3 -1.6 -2.2 -2.1 -1.3 1.8 -0.7 0.0 +M -0.7 -0.9 -3.0 -2.0 1.6 -3.5 -1.3 2.5 -1.4 2.8 4.3 -2.2 -2.4 -1.0 -1.7 -1.4 -0.6 1.6 -1.0 -0.2 +N -0.3 -1.8 2.2 0.9 -3.1 0.4 1.2 -2.8 0.8 -3.0 -2.2 3.8 -0.9 0.7 0.3 0.9 0.5 -2.2 -3.6 -1.4 +P 0.3 -3.1 -0.7 -0.5 -3.8 -1.6 -1.1 -2.6 -0.6 -2.3 -2.4 -0.9 7.6 -0.2 -0.9 0.4 0.1 -1.8 -5.0 -3.1 +Q -0.2 -2.4 0.9 1.7 -2.6 -1.0 1.2 -1.9 1.5 -1.6 -1.0 0.7 -0.2 2.7 1.5 0.2 0.0 -1.5 -2.7 -1.7 +R -0.6 -2.2 -0.3 0.4 -3.2 -1.0 0.6 -2.4 2.7 -2.2 -1.7 0.3 -0.9 1.5 4.7 -0.2 -0.2 -2.0 -1.6 -1.8 +S 1.1 0.1 0.5 0.2 -2.8 0.4 -0.2 -1.8 0.1 -2.1 -1.4 0.9 0.4 0.2 -0.2 2.2 1.5 -1.0 -3.3 -1.9 +T 0.6 -0.5 0.0 -0.1 -2.2 -1.1 -0.3 -0.6 0.1 -1.3 -0.6 0.5 0.1 0.0 -0.2 1.5 2.5 0.0 -3.5 -1.9 +V 0.1 0.0 -2.9 -1.9 0.1 -3.3 -2.0 3.1 -1.7 1.8 1.6 -2.2 -1.8 -1.5 -2.0 -1.0 0.0 3.4 -2.6 -1.1 +W -3.6 -1.0 -5.2 -4.3 3.6 -4.0 -0.8 -1.8 -3.5 -0.7 -1.0 -3.6 -5.0 -2.7 -1.6 -3.3 -3.5 -2.6 14.2 4.1 +Y -2.2 -0.5 -2.8 -2.7 5.1 -4.0 2.2 -0.7 -2.1 0.0 -0.2 -1.4 -3.1 -1.7 -1.8 -1.9 -1.9 -1.1 4.1 7.8 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/HOXD70 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/HOXD70 new file mode 100644 index 0000000000000000000000000000000000000000..4cbd0f658475ca9bc36d0119ec0f8892676e2cc2 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/HOXD70 @@ -0,0 +1,9 @@ +# F. Chiaromonte, V.B. Yap, W. Miller: +# "Scoring pairwise genomic sequence alignments" +# Pacific Symposium on Biocomputing 2002: 115-26 (2002). +# PMID 11928468 + A C G T +A 91 -114 -31 -123 +C -114 100 -125 -31 +G -31 -125 100 -114 +T -123 -31 -114 91 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/JOHNSON b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/JOHNSON new file mode 100644 index 0000000000000000000000000000000000000000..7d3096466c5e483b0af023b022a2cbef6858cd0b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/JOHNSON @@ -0,0 +1,27 @@ +# Mark S. Johnson and John P. Overington: +# "A structural basis for sequence comparisons. An evaluation of scoring +# methodologies." +# Journal of Molecular Biology 233(4): 716-738 (1993). +# Table 3, upper triangle. +# PMID 8411177 + A C D E F G H I K L M N P Q R S T V W Y +A 0.60 -0.34 -0.16 -0.07 -0.32 -0.05 -0.31 -0.22 -0.09 -0.33 -0.15 -0.14 -0.10 -0.06 -0.16 0.00 -0.08 -0.05 -0.58 -0.40 +C -0.34 1.61 -0.97 -0.69 -0.44 -0.82 -0.82 -0.77 -0.87 -0.87 -0.44 -0.76 -0.89 -0.69 -0.56 -0.77 -0.60 -0.48 -0.91 -0.77 +D -0.16 -0.97 0.85 0.24 -0.70 -0.21 -0.07 -0.48 -0.15 -0.80 -0.59 0.26 -0.10 -0.11 -0.34 -0.02 -0.18 -0.52 -0.60 -0.38 +E -0.07 -0.69 0.24 0.86 -0.64 -0.25 -0.23 -0.48 0.11 -0.56 -0.28 -0.07 -0.15 0.24 -0.02 -0.22 -0.05 -0.42 -0.76 -0.37 +F -0.32 -0.44 -0.70 -0.64 1.04 -0.86 -0.17 0.05 -0.56 0.18 -0.06 -0.38 -0.50 -0.64 -0.60 -0.48 -0.50 -0.13 0.34 0.34 +G -0.05 -0.82 -0.21 -0.25 -0.86 0.80 -0.32 -0.55 -0.35 -0.72 -0.52 -0.14 -0.25 -0.28 -0.28 -0.13 -0.38 -0.56 -0.63 -0.54 +H -0.31 -0.82 -0.07 -0.23 -0.17 -0.32 1.27 -0.51 0.01 -0.42 -0.23 0.17 -0.43 0.14 0.01 -0.26 -0.30 -0.39 -0.40 -0.04 +I -0.22 -0.77 -0.48 -0.48 0.05 -0.55 -0.51 0.81 -0.47 0.26 0.26 -0.47 -0.57 -0.70 -0.54 -0.47 -0.32 0.39 -0.33 -0.25 +K -0.09 -0.87 -0.15 0.11 -0.56 -0.35 0.01 -0.47 0.76 -0.34 -0.19 0.01 -0.06 0.11 0.32 -0.15 -0.02 -0.37 -0.54 -0.37 +L -0.33 -0.87 -0.80 -0.56 0.18 -0.72 -0.42 0.26 -0.34 0.73 0.44 -0.48 -0.28 -0.44 -0.37 -0.52 -0.46 0.18 -0.10 -0.24 +M -0.15 -0.44 -0.59 -0.28 -0.06 -0.52 -0.23 0.26 -0.19 0.44 1.12 -0.37 -0.98 -0.06 -0.42 -0.48 -0.32 0.07 -0.09 -0.13 +N -0.14 -0.76 0.26 -0.07 -0.38 -0.14 0.17 -0.47 0.01 -0.48 -0.37 0.80 -0.24 -0.08 -0.15 0.10 0.01 -0.57 -0.61 -0.13 +P -0.10 -0.89 -0.10 -0.15 -0.50 -0.25 -0.43 -0.57 -0.06 -0.28 -0.98 -0.24 1.03 -0.36 -0.36 -0.10 -0.20 -0.52 -0.74 -0.70 +Q -0.06 -0.69 -0.11 0.24 -0.64 -0.28 0.14 -0.70 0.11 -0.44 -0.06 -0.08 -0.36 0.90 0.21 -0.12 -0.04 -0.36 -0.82 -0.51 +R -0.16 -0.56 -0.34 -0.02 -0.60 -0.28 0.01 -0.54 0.32 -0.37 -0.42 -0.15 -0.36 0.21 1.00 -0.06 -0.14 -0.49 -0.38 -0.21 +S 0.00 -0.77 -0.02 -0.22 -0.48 -0.13 -0.26 -0.47 -0.15 -0.52 -0.48 0.10 -0.10 -0.12 -0.06 0.58 0.20 -0.43 -0.62 -0.34 +T -0.08 -0.60 -0.18 -0.05 -0.50 -0.38 -0.30 -0.32 -0.02 -0.46 -0.32 0.01 -0.20 -0.04 -0.14 0.20 0.68 -0.19 -0.93 -0.27 +V -0.05 -0.48 -0.52 -0.42 -0.13 -0.56 -0.39 0.39 -0.37 0.18 0.07 -0.57 -0.52 -0.36 -0.49 -0.43 -0.19 0.70 -0.49 -0.18 +W -0.58 -0.91 -0.60 -0.76 0.34 -0.63 -0.40 -0.33 -0.54 -0.10 -0.09 -0.61 -0.74 -0.82 -0.38 -0.62 -0.93 -0.49 1.52 0.23 +Y -0.40 -0.77 -0.38 -0.37 0.34 -0.54 -0.04 -0.25 -0.37 -0.24 -0.13 -0.13 -0.70 -0.51 -0.21 -0.34 -0.27 -0.18 0.23 1.05 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/JONES b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/JONES new file mode 100644 index 0000000000000000000000000000000000000000..daed99521846c8a59d6c5c872bb5e822f8d274b6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/JONES @@ -0,0 +1,26 @@ +# David T. Jones, William R. Taylor, Janet M. Thornton: +# "The rapid generation of mutation data matrices from protein sequences." +# Computer Applications in the Biosciences: CABIOS 8(3): 275-282 (1992). +# Table I, lower triangle. +# PMID 1633570 + A R N D C Q E G H I L K M F P S T W Y V +A 0.2 -0.1 0.0 0.0 -0.1 -0.1 -0.1 0.1 -0.2 0.0 -0.1 -0.1 -0.1 -0.3 0.1 0.1 0.2 -0.4 -0.3 0.1 +R -0.1 0.5 0.0 -0.1 -0.1 0.2 0.0 0.0 0.2 -0.3 -0.3 0.4 -0.2 -0.4 -0.1 -0.1 -0.1 0.0 -0.2 -0.3 +N 0.0 0.0 0.3 0.2 -0.1 0.0 0.1 0.0 0.1 -0.2 -0.3 0.1 -0.2 -0.3 -0.1 0.1 0.1 -0.5 -0.1 -0.2 +D 0.0 -0.1 0.2 0.5 -0.3 0.1 0.4 0.1 0.0 -0.3 -0.4 0.0 -0.3 -0.5 -0.2 0.0 -0.1 -0.5 -0.2 -0.2 +C -0.1 -0.1 -0.1 -0.3 1.1 -0.3 -0.4 -0.1 0.0 -0.2 -0.3 -0.3 -0.2 0.0 -0.2 0.1 -0.1 0.1 0.2 -0.2 +Q -0.1 0.2 0.0 0.1 -0.3 0.5 0.2 -0.1 0.2 -0.3 -0.2 0.2 -0.2 -0.4 0.0 -0.1 -0.1 -0.3 -0.2 -0.3 +E -0.1 0.0 0.1 0.4 -0.4 0.2 0.5 0.0 0.0 -0.3 -0.4 0.1 -0.3 -0.5 -0.2 -0.1 -0.1 -0.5 -0.4 -0.2 +G 0.1 0.0 0.0 0.1 -0.1 -0.1 0.0 0.5 -0.2 -0.3 -0.4 -0.1 -0.3 -0.5 -0.1 0.1 -0.1 -0.2 -0.4 -0.2 +H -0.2 0.2 0.1 0.0 0.0 0.2 0.0 -0.2 0.6 -0.3 -0.2 0.1 -0.2 0.0 0.0 -0.1 -0.1 -0.3 0.4 -0.3 +I 0.0 -0.3 -0.2 -0.3 -0.2 -0.3 -0.3 -0.3 -0.3 0.4 0.2 -0.3 0.3 0.0 -0.2 -0.1 0.1 -0.4 -0.2 0.4 +L -0.1 -0.3 -0.3 -0.4 -0.3 -0.2 -0.4 -0.4 -0.2 0.2 0.5 -0.3 0.3 0.2 0.0 -0.2 -0.1 -0.2 -0.1 0.2 +K -0.1 0.4 0.1 0.0 -0.3 0.2 0.1 -0.1 0.1 -0.3 -0.3 0.5 -0.2 -0.5 -0.2 -0.1 -0.1 -0.3 -0.3 -0.3 +M -0.1 -0.2 -0.2 -0.3 -0.2 -0.2 -0.3 -0.3 -0.2 0.3 0.3 -0.2 0.6 0.0 -0.2 -0.1 0.0 -0.3 -0.2 0.2 +F -0.3 -0.4 -0.3 -0.5 0.0 -0.4 -0.5 -0.5 0.0 0.0 0.2 -0.5 0.0 0.8 -0.3 -0.2 -0.2 -0.1 0.5 0.0 +P 0.1 -0.1 -0.1 -0.2 -0.2 0.0 -0.2 -0.1 0.0 -0.2 0.0 -0.2 -0.2 -0.3 0.6 0.1 0.1 -0.4 -0.3 -0.1 +S 0.1 -0.1 0.1 0.0 0.1 -0.1 -0.1 0.1 -0.1 -0.1 -0.2 -0.1 -0.1 -0.2 0.1 0.2 0.1 -0.3 -0.1 -0.1 +T 0.2 -0.1 0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 0.1 -0.1 -0.1 0.0 -0.2 0.1 0.1 0.2 -0.4 -0.3 0.0 +W -0.4 0.0 -0.5 -0.5 0.1 -0.3 -0.5 -0.2 -0.3 -0.4 -0.2 -0.3 -0.3 -0.1 -0.4 -0.3 -0.4 1.5 0.0 -0.3 +Y -0.3 -0.2 -0.1 -0.2 0.2 -0.2 -0.4 -0.4 0.4 -0.2 -0.1 -0.3 -0.2 0.5 -0.3 -0.1 -0.3 0.0 0.9 -0.3 +V 0.1 -0.3 -0.2 -0.2 -0.2 -0.3 -0.2 -0.2 -0.3 0.4 0.2 -0.3 0.2 0.0 -0.1 -0.1 0.0 -0.3 -0.3 0.4 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/LEVIN b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/LEVIN new file mode 100644 index 0000000000000000000000000000000000000000..2f9c8c45bbd81c1e0693abc412ae05a61eb28793 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/LEVIN @@ -0,0 +1,27 @@ +# Jonathan M. Levin, Barry Robson, Jean Garnier: +# "An algorithm for secondary structure determination in proteins based on +# sequence similarity." +# FEBS Letters 205(2): 303-308 (1986). +# Figure 1. +# PMID 3743779 + A C D E F G H I K L M N P Q R S T V W Y +A 2 0 0 1 -1 0 0 0 0 0 0 0 -1 0 0 1 0 0 -1 -1 +C 0 2 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 -1 -1 +D 0 0 2 1 -1 0 0 -1 0 -1 -1 1 0 0 0 0 0 -1 -1 -1 +E 1 0 1 2 -1 0 0 -1 0 -1 -1 0 -1 1 0 0 0 -1 -1 -1 +F -1 -1 -1 -1 2 -1 -1 1 -1 0 0 -1 -1 -1 -1 -1 -1 0 0 1 +G 0 0 0 0 -1 2 0 -1 0 -1 -1 0 0 0 0 0 0 -1 -1 -1 +H 0 0 0 0 -1 0 2 -1 0 -1 -1 0 0 0 0 0 0 -1 -1 0 +I 0 0 -1 -1 1 -1 -1 2 -1 0 0 -1 -1 -1 -1 -1 0 1 0 0 +K 0 0 0 0 -1 0 0 -1 2 -1 -1 1 0 0 1 0 0 -1 -1 -1 +L 0 0 -1 -1 0 -1 -1 0 -1 2 2 -1 -1 -1 -1 -1 0 1 0 0 +M 0 0 -1 -1 0 -1 -1 0 -1 2 2 -1 -1 -1 -1 -1 0 0 0 0 +N 0 0 1 0 -1 0 0 -1 1 -1 -1 3 0 1 0 0 0 -1 -1 -1 +P -1 0 0 -1 -1 0 0 -1 0 -1 -1 0 3 0 0 0 0 -1 -1 -1 +Q 0 0 0 1 -1 0 0 -1 0 -1 -1 1 0 2 0 0 0 -1 -1 -1 +R 0 0 0 0 -1 0 0 -1 1 -1 -1 0 0 0 2 0 0 -1 0 -1 +S 1 0 0 0 -1 0 0 -1 0 -1 -1 0 0 0 0 2 0 -1 -1 -1 +T 0 0 0 0 -1 0 0 0 0 0 0 0 0 0 0 0 2 0 -1 -1 +V 0 0 -1 -1 0 -1 -1 1 -1 1 0 -1 -1 -1 -1 -1 0 2 0 0 +W -1 -1 -1 -1 0 -1 -1 0 -1 0 0 -1 -1 -1 0 -1 -1 0 2 0 +Y -1 -1 -1 -1 1 -1 0 0 -1 0 0 -1 -1 -1 -1 -1 -1 0 0 2 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/MCLACHLAN b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/MCLACHLAN new file mode 100644 index 0000000000000000000000000000000000000000..adf81ce7ac38218eadd68683547763fcd9ec0f29 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/MCLACHLAN @@ -0,0 +1,27 @@ +# A.D. McLachlan: +# "Tests for comparing related amino-acid sequences. Cytochrome c and +# cytochrome c 551." +# Journal of Molecular Biology 61(2): 409-424 (1971). +# Figure 1. +# PMID 5167087 + A C D E F G H I K L M N P Q R S T V W Y +A 8 1 3 4 1 3 3 2 3 2 3 3 4 3 2 4 3 3 1 1 +C 1 9 1 0 0 1 3 1 0 0 3 1 0 0 1 2 2 1 2 1 +D 3 1 8 5 1 3 4 1 3 1 2 5 3 4 1 3 3 1 0 1 +E 4 0 5 8 0 3 2 1 4 1 1 4 4 5 3 4 4 2 1 2 +F 1 0 1 0 9 0 4 3 0 5 5 0 1 0 1 2 1 3 6 6 +G 3 1 3 3 0 8 2 1 3 1 1 3 3 2 3 3 2 2 1 0 +H 3 3 4 2 4 2 8 2 4 2 3 4 3 4 5 3 4 2 3 4 +I 2 1 1 1 3 1 2 8 1 5 5 1 1 0 1 2 3 5 3 3 +K 3 0 3 4 0 3 4 1 8 2 1 4 3 4 5 3 3 2 1 1 +L 2 0 1 1 5 1 2 5 2 8 6 1 1 3 2 2 3 5 3 3 +M 3 3 2 1 5 1 3 5 1 6 8 2 1 3 1 2 3 4 1 2 +N 3 1 5 4 0 3 4 1 4 1 2 8 1 4 3 5 3 1 0 2 +P 4 0 3 4 1 3 3 1 3 1 1 1 8 3 3 3 3 2 0 0 +Q 3 0 4 5 0 2 4 0 4 3 3 4 3 8 5 4 3 2 2 1 +R 2 1 1 3 1 3 5 1 5 2 1 3 3 5 8 4 3 2 3 2 +S 4 2 3 4 2 3 3 2 3 2 2 5 3 4 4 8 5 2 3 3 +T 3 2 3 4 1 2 4 3 3 3 3 3 3 3 3 5 8 3 2 1 +V 3 1 1 2 3 2 2 5 2 5 4 1 2 2 2 2 3 8 2 3 +W 1 2 0 1 6 1 3 3 1 3 1 0 0 2 3 3 2 2 9 6 +Y 1 1 1 2 6 0 4 3 1 3 2 2 0 1 2 3 1 3 6 9 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/MDM78 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/MDM78 new file mode 100644 index 0000000000000000000000000000000000000000..5d0b2ef7d9a8c45e75eeee14d1111805f883b3a5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/MDM78 @@ -0,0 +1,27 @@ +# R.M. Schwartz and M.O. Dayhoff: +# "Matrices for Detecting Distant Relationships." +# Margaret O. Dayhoff: Atlas of Protein Sequence and Structure, +# Volume 5, Supplement 3, 1978, pages 353-358. +# The National Biomedical Research Foundation, 1979. +# Figure 85, page 354. + A R N D C Q E G H I L K M F P S T W Y V +A 0.18 -0.15 0.02 0.03 -0.20 -0.04 0.03 0.13 -0.14 -0.05 -0.19 -0.12 -0.11 -0.35 0.11 0.11 0.12 -0.58 -0.35 0.02 +R -0.15 0.61 0.00 -0.13 -0.36 0.13 -0.11 -0.26 0.16 -0.20 -0.30 0.34 -0.04 -0.45 -0.02 -0.03 -0.09 0.22 -0.42 -0.25 +N 0.02 0.00 0.20 0.21 -0.36 0.08 0.14 0.03 0.16 -0.18 -0.29 0.10 -0.17 -0.35 -0.05 0.07 0.04 -0.42 -0.21 -0.17 +D 0.03 -0.13 0.21 0.39 -0.51 0.16 0.34 0.06 0.07 -0.24 -0.40 0.01 -0.26 -0.56 -0.10 0.03 -0.01 -0.68 -0.43 -0.21 +C -0.20 -0.36 -0.36 -0.51 1.19 -0.54 -0.53 -0.34 -0.34 -0.23 -0.60 -0.54 -0.52 -0.43 -0.28 0.00 -0.22 -0.78 0.03 -0.19 +Q -0.04 0.13 0.08 0.16 -0.54 0.40 0.25 -0.12 0.29 -0.20 -0.18 0.07 -0.10 -0.47 0.02 -0.05 -0.08 -0.48 -0.40 -0.19 +E 0.03 -0.11 0.14 0.34 -0.53 0.25 0.38 0.02 0.07 -0.20 -0.34 -0.01 -0.21 -0.54 -0.06 0.00 -0.04 -0.70 -0.43 -0.18 +G 0.13 -0.26 0.03 0.06 -0.34 -0.12 0.02 0.48 -0.21 -0.26 -0.41 -0.17 -0.28 -0.48 -0.05 0.11 0.00 -0.70 -0.52 -0.14 +H -0.14 0.16 0.16 0.07 -0.34 0.29 0.07 -0.21 0.65 -0.24 -0.21 0.00 -0.21 -0.18 -0.02 -0.08 -0.13 -0.28 -0.01 -0.22 +I -0.05 -0.20 -0.18 -0.24 -0.23 -0.20 -0.20 -0.26 -0.24 0.45 0.24 -0.19 0.22 0.10 -0.20 -0.14 0.01 -0.51 -0.09 0.37 +L -0.19 -0.30 -0.29 -0.40 -0.60 -0.18 -0.34 -0.41 -0.21 0.24 0.59 -0.29 0.37 0.18 -0.25 -0.28 -0.17 -0.18 -0.09 0.19 +K -0.12 0.34 0.10 0.01 -0.54 0.07 -0.01 -0.17 0.00 -0.19 -0.29 0.47 0.04 -0.53 -0.11 -0.02 0.00 -0.35 -0.44 -0.24 +M -0.11 -0.04 -0.17 -0.26 -0.52 -0.10 -0.21 -0.28 -0.21 0.22 0.37 0.04 0.64 0.02 -0.21 -0.16 -0.06 -0.42 -0.24 0.18 +F -0.35 -0.45 -0.35 -0.56 -0.43 -0.47 -0.54 -0.48 -0.18 0.10 0.18 -0.53 0.02 0.91 -0.46 -0.32 -0.31 0.04 0.70 -0.12 +P 0.11 -0.02 -0.05 -0.10 -0.28 0.02 -0.06 -0.05 -0.02 -0.20 -0.25 -0.11 -0.21 -0.46 0.59 0.09 0.03 -0.56 -0.49 -0.12 +S 0.11 -0.03 0.07 0.03 0.00 -0.05 0.00 0.11 -0.08 -0.14 -0.28 -0.02 -0.16 -0.32 0.09 0.16 0.13 -0.25 -0.28 -0.10 +T 0.12 -0.09 0.04 -0.01 -0.22 -0.08 -0.04 0.00 -0.13 0.01 -0.17 0.00 -0.06 -0.31 0.03 0.13 0.26 -0.52 -0.27 0.03 +W -0.58 0.22 -0.42 -0.68 -0.78 -0.48 -0.70 -0.70 -0.28 -0.51 -0.18 -0.35 -0.42 0.04 -0.56 -0.25 -0.52 1.73 -0.02 -0.62 +Y -0.35 -0.42 -0.21 -0.43 0.03 -0.40 -0.43 -0.52 -0.01 -0.09 -0.09 -0.44 -0.24 0.70 -0.49 -0.28 -0.27 -0.02 1.01 -0.25 +V 0.02 -0.25 -0.17 -0.21 -0.19 -0.19 -0.18 -0.14 -0.22 0.37 0.19 -0.24 0.18 -0.12 -0.12 -0.10 0.03 -0.62 -0.25 0.43 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/MEGABLAST b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/MEGABLAST new file mode 100644 index 0000000000000000000000000000000000000000..de114626b914d28b3b868c986eb657abca63baa0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/MEGABLAST @@ -0,0 +1,29 @@ +# MEGABLAST default substitution scores. +# For the default gap scores, as used for MEGABLAST on NCBI Web +# BLAST, The BLAST documentation shows gap costs a = 0 for opening +# a gap, and b = 2.5 for each letter in the gap, and defines the +# total score of a gap of k residues as -(a + b*k). In contrast, +# Biopython follows the definition given in "Biological Sequence +# Analysis" (Durbin et al., 1998), for which the total score of a +# gap of k residues is -d - e * (k - 1), where d is the gap-open +# penalty and e is the gap-extend penalty. Biopython uses -d as +# the gap open score and -e as the gap extend penalty: +# gap open score: -2.5 +# gap extend score: -2.5 +# with the substitution matrix below, as the MEGABLAST score parameters. + A T G C S W R Y K M B V H D N +A 1 -2 -2 -2 -2 -1 -1 -2 -2 -1 -2 -1 -1 -1 -1 +T -2 1 -2 -2 -2 -1 -2 -1 -1 -2 -1 -2 -1 -1 -1 +G -2 -2 1 -2 -1 -2 -1 -2 -1 -2 -1 -1 -2 -1 -1 +C -2 -2 -2 1 -1 -2 -2 -1 -2 -1 -1 -1 -1 -2 -1 +S -2 -2 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 +W -1 -1 -2 -2 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 +R -1 -2 -1 -2 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 +Y -2 -1 -2 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 +K -2 -1 -1 -2 -1 -1 -1 -1 -1 -2 -1 -1 -1 -1 -1 +M -1 -2 -2 -1 -1 -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 +B -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 +V -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 +H -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 +D -1 -1 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 +N -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/NUC.4.4 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/NUC.4.4 new file mode 100644 index 0000000000000000000000000000000000000000..6fb12d25434616859d1f322b09f45cdce948a052 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/NUC.4.4 @@ -0,0 +1,25 @@ +# +# This matrix was created by Todd Lowe 12/10/92 +# +# Uses ambiguous nucleotide codes, probabilities rounded to +# nearest integer +# +# Lowest score = -4, Highest score = 5 +# + A T G C S W R Y K M B V H D N +A 5 -4 -4 -4 -4 1 1 -4 -4 1 -4 -1 -1 -1 -2 +T -4 5 -4 -4 -4 1 -4 1 1 -4 -1 -4 -1 -1 -2 +G -4 -4 5 -4 1 -4 1 -4 1 -4 -1 -1 -4 -1 -2 +C -4 -4 -4 5 1 -4 -4 1 -4 1 -1 -1 -1 -4 -2 +S -4 -4 1 1 -1 -4 -2 -2 -2 -2 -1 -1 -3 -3 -1 +W 1 1 -4 -4 -4 -1 -2 -2 -2 -2 -3 -3 -1 -1 -1 +R 1 -4 1 -4 -2 -2 -1 -4 -2 -2 -3 -1 -3 -1 -1 +Y -4 1 -4 1 -2 -2 -4 -1 -2 -2 -1 -3 -1 -3 -1 +K -4 1 1 -4 -2 -2 -2 -2 -1 -4 -1 -3 -3 -1 -1 +M 1 -4 -4 1 -2 -2 -2 -2 -4 -1 -3 -1 -1 -3 -1 +B -4 -1 -1 -1 -1 -3 -3 -1 -1 -3 -1 -2 -2 -2 -1 +V -1 -4 -1 -1 -1 -3 -1 -3 -3 -1 -2 -1 -2 -2 -1 +H -1 -1 -4 -1 -3 -1 -3 -1 -3 -1 -2 -2 -1 -2 -1 +D -1 -1 -1 -4 -3 -1 -1 -3 -1 -3 -2 -2 -2 -1 -1 +N -2 -2 -2 -2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM250 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM250 new file mode 100644 index 0000000000000000000000000000000000000000..17e9e604f20fb5d508b72a0390d8d1a172d5c1a0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM250 @@ -0,0 +1,34 @@ +# +# This matrix was produced by "pam" Version 1.0.6 [28-Jul-93] +# +# PAM 250 substitution matrix, scale = ln(2)/3 = 0.231049 +# +# Expected score = -0.844, Entropy = 0.354 bits +# +# Lowest score = -8, Highest score = 17 +# + A R N D C Q E G H I L K M F P S T W Y V B Z X * +A 2 -2 0 0 -2 0 0 1 -1 -1 -2 -1 -1 -3 1 1 1 -6 -3 0 0 0 0 -8 +R -2 6 0 -1 -4 1 -1 -3 2 -2 -3 3 0 -4 0 0 -1 2 -4 -2 -1 0 -1 -8 +N 0 0 2 2 -4 1 1 0 2 -2 -3 1 -2 -3 0 1 0 -4 -2 -2 2 1 0 -8 +D 0 -1 2 4 -5 2 3 1 1 -2 -4 0 -3 -6 -1 0 0 -7 -4 -2 3 3 -1 -8 +C -2 -4 -4 -5 12 -5 -5 -3 -3 -2 -6 -5 -5 -4 -3 0 -2 -8 0 -2 -4 -5 -3 -8 +Q 0 1 1 2 -5 4 2 -1 3 -2 -2 1 -1 -5 0 -1 -1 -5 -4 -2 1 3 -1 -8 +E 0 -1 1 3 -5 2 4 0 1 -2 -3 0 -2 -5 -1 0 0 -7 -4 -2 3 3 -1 -8 +G 1 -3 0 1 -3 -1 0 5 -2 -3 -4 -2 -3 -5 0 1 0 -7 -5 -1 0 0 -1 -8 +H -1 2 2 1 -3 3 1 -2 6 -2 -2 0 -2 -2 0 -1 -1 -3 0 -2 1 2 -1 -8 +I -1 -2 -2 -2 -2 -2 -2 -3 -2 5 2 -2 2 1 -2 -1 0 -5 -1 4 -2 -2 -1 -8 +L -2 -3 -3 -4 -6 -2 -3 -4 -2 2 6 -3 4 2 -3 -3 -2 -2 -1 2 -3 -3 -1 -8 +K -1 3 1 0 -5 1 0 -2 0 -2 -3 5 0 -5 -1 0 0 -3 -4 -2 1 0 -1 -8 +M -1 0 -2 -3 -5 -1 -2 -3 -2 2 4 0 6 0 -2 -2 -1 -4 -2 2 -2 -2 -1 -8 +F -3 -4 -3 -6 -4 -5 -5 -5 -2 1 2 -5 0 9 -5 -3 -3 0 7 -1 -4 -5 -2 -8 +P 1 0 0 -1 -3 0 -1 0 0 -2 -3 -1 -2 -5 6 1 0 -6 -5 -1 -1 0 -1 -8 +S 1 0 1 0 0 -1 0 1 -1 -1 -3 0 -2 -3 1 2 1 -2 -3 -1 0 0 0 -8 +T 1 -1 0 0 -2 -1 0 0 -1 0 -2 0 -1 -3 0 1 3 -5 -3 0 0 -1 0 -8 +W -6 2 -4 -7 -8 -5 -7 -7 -3 -5 -2 -3 -4 0 -6 -2 -5 17 0 -6 -5 -6 -4 -8 +Y -3 -4 -2 -4 0 -4 -4 -5 0 -1 -1 -4 -2 7 -5 -3 -3 0 10 -2 -3 -4 -2 -8 +V 0 -2 -2 -2 -2 -2 -2 -1 -2 4 2 -2 2 -1 -1 -1 0 -6 -2 4 -2 -2 -1 -8 +B 0 -1 2 3 -4 1 3 0 1 -2 -3 1 -2 -4 -1 0 0 -5 -3 -2 3 2 -1 -8 +Z 0 0 1 3 -5 3 3 0 2 -2 -3 0 -2 -5 0 0 -1 -6 -4 -2 2 3 -1 -8 +X 0 -1 0 -1 -3 -1 -1 -1 -1 -1 -1 -1 -1 -2 -1 0 0 -4 -2 -1 -1 -1 -1 -8 +* -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 -8 1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM30 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM30 new file mode 100644 index 0000000000000000000000000000000000000000..8a01c88667f2ddeb4acaa3bad90572d39877bad3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM30 @@ -0,0 +1,34 @@ +# +# This matrix was produced by "pam" Version 1.0.6 [28-Jul-93] +# +# PAM 30 substitution matrix, scale = ln(2)/2 = 0.346574 +# +# Expected score = -5.06, Entropy = 2.57 bits +# +# Lowest score = -17, Highest score = 13 +# + A R N D C Q E G H I L K M F P S T W Y V B Z X * +A 6 -7 -4 -3 -6 -4 -2 -2 -7 -5 -6 -7 -5 -8 -2 0 -1 -13 -8 -2 -3 -3 -3 -17 +R -7 8 -6 -10 -8 -2 -9 -9 -2 -5 -8 0 -4 -9 -4 -3 -6 -2 -10 -8 -7 -4 -6 -17 +N -4 -6 8 2 -11 -3 -2 -3 0 -5 -7 -1 -9 -9 -6 0 -2 -8 -4 -8 6 -3 -3 -17 +D -3 -10 2 8 -14 -2 2 -3 -4 -7 -12 -4 -11 -15 -8 -4 -5 -15 -11 -8 6 1 -5 -17 +C -6 -8 -11 -14 10 -14 -14 -9 -7 -6 -15 -14 -13 -13 -8 -3 -8 -15 -4 -6 -12 -14 -9 -17 +Q -4 -2 -3 -2 -14 8 1 -7 1 -8 -5 -3 -4 -13 -3 -5 -5 -13 -12 -7 -3 6 -5 -17 +E -2 -9 -2 2 -14 1 8 -4 -5 -5 -9 -4 -7 -14 -5 -4 -6 -17 -8 -6 1 6 -5 -17 +G -2 -9 -3 -3 -9 -7 -4 6 -9 -11 -10 -7 -8 -9 -6 -2 -6 -15 -14 -5 -3 -5 -5 -17 +H -7 -2 0 -4 -7 1 -5 -9 9 -9 -6 -6 -10 -6 -4 -6 -7 -7 -3 -6 -1 -1 -5 -17 +I -5 -5 -5 -7 -6 -8 -5 -11 -9 8 -1 -6 -1 -2 -8 -7 -2 -14 -6 2 -6 -6 -5 -17 +L -6 -8 -7 -12 -15 -5 -9 -10 -6 -1 7 -8 1 -3 -7 -8 -7 -6 -7 -2 -9 -7 -6 -17 +K -7 0 -1 -4 -14 -3 -4 -7 -6 -6 -8 7 -2 -14 -6 -4 -3 -12 -9 -9 -2 -4 -5 -17 +M -5 -4 -9 -11 -13 -4 -7 -8 -10 -1 1 -2 11 -4 -8 -5 -4 -13 -11 -1 -10 -5 -5 -17 +F -8 -9 -9 -15 -13 -13 -14 -9 -6 -2 -3 -14 -4 9 -10 -6 -9 -4 2 -8 -10 -13 -8 -17 +P -2 -4 -6 -8 -8 -3 -5 -6 -4 -8 -7 -6 -8 -10 8 -2 -4 -14 -13 -6 -7 -4 -5 -17 +S 0 -3 0 -4 -3 -5 -4 -2 -6 -7 -8 -4 -5 -6 -2 6 0 -5 -7 -6 -1 -5 -3 -17 +T -1 -6 -2 -5 -8 -5 -6 -6 -7 -2 -7 -3 -4 -9 -4 0 7 -13 -6 -3 -3 -6 -4 -17 +W -13 -2 -8 -15 -15 -13 -17 -15 -7 -14 -6 -12 -13 -4 -14 -5 -13 13 -5 -15 -10 -14 -11 -17 +Y -8 -10 -4 -11 -4 -12 -8 -14 -3 -6 -7 -9 -11 2 -13 -7 -6 -5 10 -7 -6 -9 -7 -17 +V -2 -8 -8 -8 -6 -7 -6 -5 -6 2 -2 -9 -1 -8 -6 -6 -3 -15 -7 7 -8 -6 -5 -17 +B -3 -7 6 6 -12 -3 1 -3 -1 -6 -9 -2 -10 -10 -7 -1 -3 -10 -6 -8 6 0 -5 -17 +Z -3 -4 -3 1 -14 6 6 -5 -1 -6 -7 -4 -5 -13 -4 -5 -6 -14 -9 -6 0 6 -5 -17 +X -3 -6 -3 -5 -9 -5 -5 -5 -5 -5 -6 -5 -5 -8 -5 -3 -4 -11 -7 -5 -5 -5 -5 -17 +* -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 -17 1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM70 b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM70 new file mode 100644 index 0000000000000000000000000000000000000000..b20cdf082e485532af9d4c605dfdf8af3e8effc1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/PAM70 @@ -0,0 +1,34 @@ +# +# This matrix was produced by "pam" Version 1.0.6 [28-Jul-93] +# +# PAM 70 substitution matrix, scale = ln(2)/2 = 0.346574 +# +# Expected score = -2.77, Entropy = 1.60 bits +# +# Lowest score = -11, Highest score = 13 +# + A R N D C Q E G H I L K M F P S T W Y V B Z X * +A 5 -4 -2 -1 -4 -2 -1 0 -4 -2 -4 -4 -3 -6 0 1 1 -9 -5 -1 -1 -1 -2 -11 +R -4 8 -3 -6 -5 0 -5 -6 0 -3 -6 2 -2 -7 -2 -1 -4 0 -7 -5 -4 -2 -3 -11 +N -2 -3 6 3 -7 -1 0 -1 1 -3 -5 0 -5 -6 -3 1 0 -6 -3 -5 5 -1 -2 -11 +D -1 -6 3 6 -9 0 3 -1 -1 -5 -8 -2 -7 -10 -4 -1 -2 -10 -7 -5 5 2 -3 -11 +C -4 -5 -7 -9 9 -9 -9 -6 -5 -4 -10 -9 -9 -8 -5 -1 -5 -11 -2 -4 -8 -9 -6 -11 +Q -2 0 -1 0 -9 7 2 -4 2 -5 -3 -1 -2 -9 -1 -3 -3 -8 -8 -4 -1 5 -2 -11 +E -1 -5 0 3 -9 2 6 -2 -2 -4 -6 -2 -4 -9 -3 -2 -3 -11 -6 -4 2 5 -3 -11 +G 0 -6 -1 -1 -6 -4 -2 6 -6 -6 -7 -5 -6 -7 -3 0 -3 -10 -9 -3 -1 -3 -3 -11 +H -4 0 1 -1 -5 2 -2 -6 8 -6 -4 -3 -6 -4 -2 -3 -4 -5 -1 -4 0 1 -3 -11 +I -2 -3 -3 -5 -4 -5 -4 -6 -6 7 1 -4 1 0 -5 -4 -1 -9 -4 3 -4 -4 -3 -11 +L -4 -6 -5 -8 -10 -3 -6 -7 -4 1 6 -5 2 -1 -5 -6 -4 -4 -4 0 -6 -4 -4 -11 +K -4 2 0 -2 -9 -1 -2 -5 -3 -4 -5 6 0 -9 -4 -2 -1 -7 -7 -6 -1 -2 -3 -11 +M -3 -2 -5 -7 -9 -2 -4 -6 -6 1 2 0 10 -2 -5 -3 -2 -8 -7 0 -6 -3 -3 -11 +F -6 -7 -6 -10 -8 -9 -9 -7 -4 0 -1 -9 -2 8 -7 -4 -6 -2 4 -5 -7 -9 -5 -11 +P 0 -2 -3 -4 -5 -1 -3 -3 -2 -5 -5 -4 -5 -7 7 0 -2 -9 -9 -3 -4 -2 -3 -11 +S 1 -1 1 -1 -1 -3 -2 0 -3 -4 -6 -2 -3 -4 0 5 2 -3 -5 -3 0 -2 -1 -11 +T 1 -4 0 -2 -5 -3 -3 -3 -4 -1 -4 -1 -2 -6 -2 2 6 -8 -4 -1 -1 -3 -2 -11 +W -9 0 -6 -10 -11 -8 -11 -10 -5 -9 -4 -7 -8 -2 -9 -3 -8 13 -3 -10 -7 -10 -7 -11 +Y -5 -7 -3 -7 -2 -8 -6 -9 -1 -4 -4 -7 -7 4 -9 -5 -4 -3 9 -5 -4 -7 -5 -11 +V -1 -5 -5 -5 -4 -4 -4 -3 -4 3 0 -6 0 -5 -3 -3 -1 -10 -5 6 -5 -4 -2 -11 +B -1 -4 5 5 -8 -1 2 -1 0 -4 -6 -1 -6 -7 -4 0 -1 -7 -4 -5 5 1 -2 -11 +Z -1 -2 -1 2 -9 5 5 -3 1 -4 -4 -2 -3 -9 -2 -2 -3 -10 -7 -4 1 5 -3 -11 +X -2 -3 -2 -3 -6 -2 -3 -3 -3 -3 -4 -3 -3 -5 -3 -1 -2 -7 -5 -2 -2 -3 -3 -11 +* -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 -11 1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/RAO b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/RAO new file mode 100644 index 0000000000000000000000000000000000000000..f3ef1c00b39340ef4291b6266d6935d10fb2f24f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/RAO @@ -0,0 +1,27 @@ +# J.K. Mohana Rao: +# "New scoring matrix for amino acid residue exchanges based on residue +# characteristic physical parameters." +# International Journal of Peptide and Protein Research: 29(2): 276-281 (1987). +# Figure 1, lower triangle. +# PMID 3570667 + A C D E F G H I K L M N P Q R S T V W Y +A 16 11 9 10 10 8 11 9 10 11 11 9 6 11 8 10 10 9 11 9 +C 11 16 8 9 10 8 10 8 9 11 10 9 7 10 8 10 10 8 11 10 +D 9 8 16 11 4 9 9 3 11 6 5 11 8 11 10 10 9 3 6 7 +E 10 9 11 16 6 6 11 4 11 7 8 10 5 11 9 9 8 4 7 6 +F 10 10 4 6 16 7 9 12 6 11 10 6 4 7 5 8 10 11 11 10 +G 8 8 9 6 7 16 7 6 7 6 4 10 11 8 7 11 10 6 8 10 +H 11 10 9 11 9 7 16 8 11 10 10 10 5 11 10 10 10 9 10 9 +I 9 8 3 4 12 6 8 16 4 10 9 5 3 6 4 8 10 12 11 10 +K 10 9 11 11 6 7 11 4 16 7 8 11 6 12 11 10 9 5 7 7 +L 11 11 6 7 11 6 10 10 7 16 11 7 4 9 6 8 9 10 11 9 +M 11 10 5 8 10 4 10 9 8 11 16 6 2 9 6 7 8 9 10 8 +N 9 9 11 10 6 10 10 5 11 7 6 16 9 11 10 11 10 5 8 8 +P 6 7 8 5 4 11 5 3 6 4 2 9 16 7 6 10 8 3 6 8 +Q 11 10 11 11 7 8 11 6 12 9 9 11 7 16 10 10 10 6 9 8 +R 8 8 10 9 5 7 10 4 11 6 6 10 6 10 16 9 9 5 7 7 +S 10 10 10 9 8 11 10 8 10 8 7 11 10 10 9 16 11 8 10 11 +T 10 10 9 8 10 10 10 10 9 9 8 10 8 10 9 11 16 10 11 11 +V 9 8 3 4 11 6 9 12 5 10 9 5 3 6 5 8 10 16 11 10 +W 11 11 6 7 11 8 10 11 7 11 10 8 6 9 7 10 11 11 16 11 +Y 9 10 7 6 10 10 9 10 7 9 8 8 8 8 7 11 11 10 11 16 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/RISLER b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/RISLER new file mode 100644 index 0000000000000000000000000000000000000000..438b601bfd0ff8a6eb41a29b00bcdd1259735dcd --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/RISLER @@ -0,0 +1,27 @@ +# J.L. Risler, M.O. Delorme, H. Delacroix, A. Henaut: +# "Amino acid substitutions in structurally related proteins. A pattern +# recognition approach. Determination of a new and efficient scoring matrix." +# Journal of Molecular Biology 204(4): 1019-1029 (1988). +# Figure 5. +# PMID 3221397 + A C D E F G H I K L M N P Q R S T V W Y +A 2.2 -1.5 0.2 1.7 0.6 0.6 -0.6 1.7 1.4 1.3 1.0 1.3 -0.2 1.8 1.5 2.0 1.9 2.0 -0.9 0.2 +C -1.5 2.2 -1.7 -1.5 -1.6 -1.7 -1.8 -1.6 -1.6 -1.5 -1.6 -1.6 -1.8 -1.4 -1.5 -1.3 -1.4 -1.4 -1.8 -1.1 +D 0.2 -1.7 2.2 1.0 -0.3 -0.4 -1.3 0.0 0.1 -0.2 -0.5 0.8 -1.2 0.6 -0.1 0.7 0.0 0.0 -1.4 -0.4 +E 1.7 -1.5 1.0 2.2 0.6 0.3 -0.6 1.5 1.4 0.9 0.6 1.4 -0.1 2.1 1.9 1.8 1.6 1.6 -1.0 0.2 +F 0.6 -1.6 -0.3 0.6 2.2 -0.4 -1.1 1.0 0.1 1.0 -0.2 0.4 -1.1 0.7 0.4 0.5 0.3 0.8 -0.9 2.0 +G 0.6 -1.7 -0.4 0.3 -0.4 2.2 -1.2 0.0 -0.1 -0.2 -0.4 0.2 -1.2 0.2 0.1 0.7 0.2 0.1 -1.3 -0.2 +H -0.6 -1.8 -1.3 -0.6 -1.1 -1.2 2.2 -0.8 -1.0 -0.9 -1.2 -0.3 -1.6 -0.5 -0.4 -0.4 -0.9 -0.7 -1.7 -0.8 +I 1.7 -1.6 0.0 1.5 1.0 0.0 -0.8 2.2 1.0 2.1 0.9 0.9 -0.6 1.4 1.4 1.6 1.6 2.2 -0.7 0.4 +K 1.4 -1.6 0.1 1.4 0.1 -0.1 -1.0 1.0 2.2 0.7 0.4 1.0 -0.7 1.7 2.1 1.4 1.2 1.2 -1.1 0.5 +L 1.3 -1.5 -0.2 0.9 1.0 -0.2 -0.9 2.1 0.7 2.2 1.8 0.8 -0.8 1.1 1.2 1.3 1.2 2.0 -0.8 0.5 +M 1.0 -1.6 -0.5 0.6 -0.2 -0.4 -1.2 0.9 0.4 1.8 2.2 0.0 -1.2 1.2 1.1 0.6 0.8 0.8 -1.3 -0.2 +N 1.3 -1.6 0.8 1.4 0.4 0.2 -0.3 0.9 1.0 0.8 0.0 2.2 -1.0 1.6 1.2 1.9 1.1 1.1 -1.1 -0.1 +P -0.2 -1.8 -1.2 -0.1 -1.1 -1.2 -1.6 -0.6 -0.7 -0.8 -1.2 -1.0 2.2 -0.6 -0.3 -0.3 -0.5 -0.6 -1.6 -1.2 +Q 1.8 -1.4 0.6 2.1 0.7 0.2 -0.5 1.4 1.7 1.1 1.2 1.6 -0.6 2.2 2.0 1.8 1.7 1.5 -1.0 0.5 +R 1.5 -1.5 -0.1 1.9 0.4 0.1 -0.4 1.4 2.1 1.2 1.1 1.2 -0.3 2.0 2.2 2.0 1.9 1.5 -0.8 0.8 +S 2.0 -1.3 0.7 1.8 0.5 0.7 -0.4 1.6 1.4 1.3 0.6 1.9 -0.3 1.8 2.0 2.2 2.1 1.8 -0.8 0.4 +T 1.9 -1.4 0.0 1.6 0.3 0.2 -0.9 1.6 1.2 1.2 0.8 1.1 -0.5 1.7 1.9 2.1 2.2 1.6 -1.0 0.3 +V 2.0 -1.4 0.0 1.6 0.8 0.1 -0.7 2.2 1.2 2.0 0.8 1.1 -0.6 1.5 1.5 1.8 1.6 2.2 -0.7 0.3 +W -0.9 -1.8 -1.4 -1.0 -0.9 -1.3 -1.7 -0.7 -1.1 -0.8 -1.3 -1.1 -1.6 -1.0 -0.8 -0.8 -1.0 -0.7 2.2 -0.6 +Y 0.2 -1.1 -0.4 0.2 2.0 -0.2 -0.8 0.4 0.5 0.5 -0.2 -0.1 -1.2 0.5 0.8 0.4 0.3 0.3 -0.6 2.2 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/SCHNEIDER b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/SCHNEIDER new file mode 100644 index 0000000000000000000000000000000000000000..0384fa9ba53b682c28c66688b6b64b1853e9bdf9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/SCHNEIDER @@ -0,0 +1,70 @@ +# Adrian Schneider, Gina M. Cannarozzi, and Gaston H. Gonnet: +# "Empirical codon substitution matrix." +# BMC Bioinformatics 6:134 (2005). +# Additional File 3. +# PMID 15927081 + AAA AAC AAG AAT ACA ACC ACG ACT AGA AGC AGG AGT ATA ATC ATG ATT CAA CAC CAG CAT CCA CCC CCG CCT CGA CGC CGG CGT CTA CTC CTG CTT GAA GAC GAG GAT GCA GCC GCG GCT GGA GGC GGG GGT GTA GTC GTG GTT TAA TAC TAG TAT TCA TCC TCG TCT TGA TGC TGG TGT TTA TTC TTG TTT +AAA 11.6 -2.7 9.7 -1.7 -2.7 -6.4 -3.9 -5.6 5.1 -5.0 3.6 -4.2 -6.3 -13.0 -7.1 -11.5 0.4 -6.0 -1.9 -5.3 -8.5 -11.2 -8.9 -10.8 2.1 0.0 1.4 0.2 -10.2 -13.5 -13.0 -12.5 -2.6 -8.5 -5.0 -8.1 -6.3 -9.9 -7.5 -9.0 -7.1 -10.2 -8.2 -9.2 -8.2 -12.5 -11.1 -11.4 -50.0 -14.8 -50.0 -13.8 -7.3 -10.1 -8.4 -9.1 -50.0 -13.0 -13.5 -12.4 -10.7 -18.1 -11.8 -17.2 +AAC -2.7 13.0 -3.3 10.9 -3.5 -0.4 -3.3 -1.8 -5.4 4.6 -5.5 3.0 -10.2 -7.9 -9.9 -9.6 -5.0 0.5 -5.5 -1.0 -10.3 -8.1 -9.4 -9.6 -8.1 -5.0 -7.3 -6.3 -13.4 -11.3 -14.4 -12.9 -6.3 0.8 -6.4 -1.1 -7.4 -5.0 -6.2 -6.5 -5.6 -1.6 -4.7 -3.0 -10.8 -8.7 -11.9 -10.0 -50.0 -6.2 -50.0 -7.5 -6.3 -4.3 -6.2 -5.4 -50.0 -7.0 -16.3 -8.2 -13.2 -12.3 -13.1 -13.3 +AAG 9.7 -3.3 11.6 -2.8 -4.5 -6.7 -3.1 -6.9 3.3 -5.5 4.8 -5.1 -8.9 -13.2 -5.7 -12.6 -1.5 -6.1 -0.6 -6.1 -10.0 -11.8 -8.6 -11.9 1.2 0.5 2.2 0.1 -11.8 -14.0 -11.9 -13.4 -4.9 -9.1 -3.4 -8.9 -8.0 -10.0 -7.2 -10.0 -9.1 -10.2 -7.1 -9.9 -10.1 -13.0 -10.6 -12.7 -50.0 -14.9 -50.0 -14.4 -8.9 -10.8 -8.9 -10.4 -50.0 -13.1 -11.8 -13.0 -12.4 -19.4 -11.5 -17.8 +AAT -1.7 10.9 -2.8 12.9 -2.7 -2.2 -2.8 0.2 -4.8 2.9 -5.2 5.2 -9.1 -9.5 -9.0 -7.0 -4.0 -1.0 -5.0 1.0 -9.0 -8.8 -8.9 -7.7 -7.0 -6.8 -7.1 -4.3 -12.4 -12.9 -13.9 -10.0 -4.9 -0.7 -5.6 1.4 -6.0 -6.5 -6.2 -4.8 -5.1 -3.2 -5.0 -1.2 -9.8 -9.9 -11.3 -8.2 -50.0 -7.6 -50.0 -5.1 -5.5 -5.8 -5.9 -4.2 -50.0 -8.3 -15.5 -5.9 -11.6 -14.2 -12.0 -11.6 +ACA -2.7 -3.5 -4.5 -2.7 11.7 9.0 10.6 9.6 -3.2 -0.7 -5.1 -0.4 0.7 -4.6 -0.4 -3.6 -4.8 -8.9 -6.5 -7.8 -1.4 -4.1 -2.9 -3.3 -8.0 -9.1 -8.0 -8.2 -6.0 -9.3 -7.7 -8.5 -6.4 -10.1 -7.5 -8.6 2.8 -0.7 0.9 0.1 -5.9 -7.3 -6.5 -6.5 -0.4 -3.9 -2.6 -3.1 -50.0 -14.6 -50.0 -12.6 2.9 0.1 1.8 1.0 -50.0 -9.2 -13.6 -7.7 -4.8 -12.2 -6.2 -11.0 +ACC -6.4 -0.4 -6.7 -2.2 9.0 12.3 9.8 9.6 -7.1 2.4 -7.2 0.3 -2.9 -1.2 -3.0 -3.3 -7.6 -6.7 -8.1 -7.9 -4.9 -1.9 -4.5 -3.8 -9.5 -7.8 -9.3 -8.9 -9.4 -7.1 -9.0 -9.0 -9.4 -7.5 -9.3 -9.2 -0.7 2.6 0.2 -0.1 -8.0 -4.6 -7.7 -6.1 -3.6 -1.0 -4.1 -3.1 -50.0 -11.6 -50.0 -11.6 0.2 2.3 0.4 0.5 -50.0 -6.5 -15.3 -7.8 -8.4 -9.5 -8.3 -11.1 +ACG -3.9 -3.3 -3.1 -2.8 10.6 9.8 12.2 9.8 -4.9 0.1 -3.6 -0.2 -1.7 -4.1 0.9 -3.5 -5.9 -8.9 -5.6 -8.5 -3.9 -3.9 -2.2 -4.5 -7.3 -7.5 -6.4 -8.5 -7.1 -8.2 -6.7 -7.8 -7.9 -9.1 -7.1 -9.4 0.9 -0.2 2.5 -0.3 -6.9 -6.5 -5.5 -6.8 -1.7 -3.4 -1.7 -2.8 -50.0 -13.0 -50.0 -11.5 1.5 0.7 2.7 0.6 -50.0 -8.9 -12.1 -7.4 -6.1 -11.5 -5.4 -10.4 +ACT -5.6 -1.8 -6.9 0.2 9.6 9.6 9.8 11.6 -6.6 0.9 -7.2 2.5 -2.3 -3.4 -2.3 -0.6 -6.5 -8.2 -8.0 -6.3 -3.7 -3.5 -3.9 -1.6 -9.9 -8.9 -9.6 -7.0 -8.6 -8.9 -8.8 -6.8 -8.6 -8.2 -8.8 -6.8 0.3 0.1 0.2 2.4 -7.4 -6.2 -6.9 -4.4 -2.9 -2.9 -3.5 -0.9 -50.0 -12.2 -50.0 -10.1 1.2 0.6 1.2 2.4 -50.0 -7.6 -16.1 -5.8 -7.2 -10.8 -7.4 -9.0 +AGA 5.1 -5.4 3.3 -4.8 -3.2 -7.1 -4.9 -6.6 13.3 -2.8 11.2 -1.9 -5.7 -12.5 -7.2 -11.6 -0.7 -4.8 -3.1 -4.3 -10.0 -11.6 -8.8 -11.7 10.5 7.7 9.1 8.5 -9.8 -12.7 -11.7 -11.8 -6.3 -11.4 -8.8 -11.0 -7.5 -10.3 -8.3 -9.9 -1.9 -6.7 -4.1 -6.4 -7.9 -12.5 -11.4 -11.7 -50.0 -14.0 -50.0 -13.2 -8.5 -10.4 -9.1 -9.6 -50.0 -9.8 -7.7 -8.8 -10.3 -17.9 -11.8 -16.0 +AGC -5.0 4.6 -5.5 2.9 -0.7 2.4 0.1 0.9 -2.8 12.8 -2.6 11.0 -8.4 -6.3 -8.3 -7.7 -6.1 -2.9 -6.5 -4.2 -8.5 -5.9 -7.5 -7.7 -5.5 -2.4 -5.5 -4.1 -12.9 -10.3 -12.7 -11.3 -7.4 -3.1 -7.4 -4.9 -4.4 -1.8 -3.5 -3.5 -1.6 3.0 -0.8 0.9 -8.4 -6.3 -9.6 -7.3 -50.0 -9.0 -50.0 -9.7 -2.3 -0.2 -1.2 -1.5 -50.0 -0.7 -13.3 -2.0 -11.8 -11.9 -12.3 -12.7 +AGG 3.6 -5.5 4.8 -5.2 -5.1 -7.2 -3.6 -7.2 11.2 -2.6 13.4 -2.1 -7.7 -12.5 -5.3 -11.9 -2.2 -4.4 -1.9 -4.8 -10.2 -11.5 -8.1 -12.0 9.3 8.2 10.0 8.0 -10.8 -11.9 -10.7 -12.4 -8.2 -11.8 -6.9 -11.5 -8.4 -9.9 -7.1 -10.6 -4.7 -6.8 -1.2 -7.0 -9.8 -11.6 -9.6 -12.1 -50.0 -14.1 -50.0 -12.7 -10.0 -10.8 -8.8 -10.5 -50.0 -9.2 -4.2 -9.3 -11.0 -18.2 -11.1 -16.1 +AGT -4.2 3.0 -5.1 5.2 -0.4 0.3 -0.2 2.5 -1.9 11.0 -2.1 13.2 -7.6 -8.5 -8.0 -5.3 -5.6 -4.5 -6.8 -2.4 -7.8 -7.9 -7.9 -6.2 -5.7 -5.1 -5.4 -2.1 -12.4 -12.3 -13.1 -10.1 -6.6 -4.4 -6.9 -2.6 -3.6 -3.8 -3.7 -2.0 -1.4 0.8 -0.9 3.0 -8.2 -8.1 -9.2 -5.8 -50.0 -10.1 -50.0 -7.4 -1.7 -2.0 -1.5 -0.5 -50.0 -2.1 -12.6 -0.4 -11.6 -13.9 -11.4 -11.1 +ATA -6.3 -10.2 -8.9 -9.1 0.7 -2.9 -1.7 -2.3 -5.7 -8.4 -7.7 -7.6 13.2 9.6 3.5 9.7 -8.7 -12.4 -10.7 -10.7 -7.8 -10.2 -8.8 -9.6 -9.5 -11.9 -10.9 -10.5 2.3 -0.4 -0.2 -0.3 -9.7 -15.5 -11.4 -13.7 -3.0 -6.4 -4.1 -5.4 -9.6 -11.9 -10.5 -11.8 6.2 3.3 3.7 3.6 -50.0 -13.6 -50.0 -11.9 -5.6 -8.8 -7.2 -8.9 -50.0 -12.4 -14.1 -11.6 2.8 -6.4 0.5 -5.2 +ATC -13.0 -7.9 -13.2 -9.5 -4.6 -1.2 -4.1 -3.4 -12.5 -6.3 -12.5 -8.5 9.6 12.7 0.2 10.5 -12.4 -11.6 -13.2 -12.0 -12.4 -10.1 -11.6 -12.0 -15.1 -13.1 -14.3 -13.4 -1.4 1.4 -1.6 -0.5 -14.9 -14.3 -15.2 -16.8 -7.7 -4.7 -6.3 -6.6 -14.6 -10.8 -12.8 -13.0 2.3 6.0 2.5 3.6 -50.0 -11.2 -50.0 -11.9 -10.5 -9.2 -10.5 -10.5 -50.0 -10.3 -16.2 -11.3 -1.7 -3.7 -2.5 -5.4 +ATG -7.1 -9.9 -5.7 -9.0 -0.4 -3.0 0.9 -2.3 -7.2 -8.3 -5.3 -8.0 3.5 0.2 14.3 1.0 -7.3 -11.2 -6.9 -9.7 -8.5 -10.2 -7.7 -9.8 -10.0 -10.4 -8.4 -10.2 1.0 -0.6 1.7 -0.5 -11.1 -14.8 -9.7 -14.5 -3.7 -5.8 -3.1 -5.6 -10.4 -11.5 -8.2 -11.1 0.6 -1.6 1.6 -1.1 -50.0 -12.4 -50.0 -11.5 -5.5 -8.0 -4.9 -7.2 -50.0 -12.4 -10.3 -11.6 0.7 -6.8 2.4 -6.0 +ATT -11.5 -9.6 -12.6 -7.0 -3.6 -3.3 -3.5 -0.6 -11.6 -7.7 -11.9 -5.3 9.7 10.5 1.0 12.6 -12.0 -12.2 -12.5 -9.7 -11.1 -11.2 -11.9 -9.4 -12.9 -14.3 -14.0 -11.9 -1.0 -0.4 -1.6 1.2 -13.9 -15.4 -13.7 -12.6 -6.2 -6.7 -6.3 -4.4 -13.0 -12.2 -13.0 -10.4 2.9 3.8 2.5 5.8 -50.0 -12.5 -50.0 -10.2 -9.6 -9.7 -9.6 -8.3 -50.0 -11.6 -15.4 -9.4 -1.1 -5.4 -1.6 -3.3 +CAA 0.4 -5.0 -1.5 -4.0 -4.8 -7.6 -5.9 -6.5 -0.7 -6.1 -2.2 -5.6 -8.7 -12.4 -7.3 -12.0 12.8 2.3 10.2 3.0 0.0 -3.4 -0.7 -3.2 2.5 -0.8 0.9 0.2 -3.0 -7.2 -5.7 -6.1 -0.2 -6.6 -1.8 -6.0 -5.3 -8.2 -5.7 -7.6 -6.7 -9.6 -7.5 -9.3 -7.1 -10.5 -9.6 -9.4 -50.0 -8.1 -50.0 -7.2 -4.3 -6.8 -5.7 -6.3 -50.0 -9.5 -9.6 -8.9 -6.2 -12.8 -6.8 -11.8 +CAC -6.0 0.5 -6.1 -1.0 -8.9 -6.7 -8.9 -8.2 -4.8 -2.9 -4.4 -4.5 -12.4 -11.6 -11.2 -12.2 2.3 14.6 1.9 12.9 -5.5 -2.6 -4.1 -4.7 -1.2 3.0 -1.1 1.6 -8.0 -4.7 -8.7 -6.0 -8.2 -4.7 -7.8 -6.7 -10.0 -8.3 -8.9 -9.9 -10.8 -7.1 -10.0 -9.2 -11.6 -10.1 -12.3 -11.9 -50.0 2.2 -50.0 0.9 -7.9 -5.9 -7.4 -6.9 -50.0 -4.6 -11.6 -5.6 -9.7 -5.9 -9.9 -7.3 +CAG -1.9 -5.5 -0.6 -5.0 -6.5 -8.1 -5.6 -8.0 -3.1 -6.5 -1.9 -6.8 -10.7 -13.2 -6.9 -12.5 10.2 1.9 11.9 2.1 -2.3 -4.1 -0.5 -4.6 -0.1 -0.9 2.4 -0.8 -5.1 -6.9 -4.8 -6.7 -2.3 -7.1 -0.8 -7.2 -7.2 -8.0 -5.6 -8.5 -9.4 -9.7 -7.2 -9.8 -9.2 -11.1 -9.5 -10.7 -50.0 -8.7 -50.0 -8.6 -6.1 -7.5 -5.5 -7.7 -50.0 -10.4 -7.7 -10.0 -7.3 -13.6 -6.4 -13.3 +CAT -5.3 -1.0 -6.1 1.0 -7.8 -7.9 -8.5 -6.3 -4.3 -4.2 -4.8 -2.4 -10.7 -12.0 -9.7 -9.7 3.0 12.9 2.1 14.7 -4.9 -3.8 -4.0 -2.4 -1.0 0.8 -1.3 3.4 -7.6 -5.7 -8.1 -3.5 -6.8 -5.8 -7.2 -4.2 -8.9 -10.2 -8.4 -8.2 -9.9 -8.4 -9.7 -6.4 -11.1 -11.1 -11.8 -10.0 -50.0 0.4 -50.0 2.6 -7.2 -7.0 -7.4 -5.1 -50.0 -5.7 -9.8 -3.2 -8.4 -7.4 -8.9 -5.9 +CCA -8.5 -10.3 -10.0 -9.0 -1.4 -4.9 -3.9 -3.7 -10.0 -8.5 -10.2 -7.8 -7.8 -12.4 -8.5 -11.1 0.0 -5.5 -2.3 -4.9 12.6 10.0 11.1 10.5 -6.0 -8.3 -6.9 -7.5 -2.2 -7.4 -5.3 -5.9 -8.9 -12.5 -9.4 -11.6 -0.7 -3.9 -2.3 -3.0 -9.1 -9.8 -9.2 -9.5 -5.6 -9.0 -8.0 -8.5 -50.0 -15.3 -50.0 -14.1 2.3 -1.4 0.3 -0.5 -50.0 -13.6 -14.3 -11.5 -5.3 -13.7 -6.1 -12.7 +CCC -11.2 -8.1 -11.8 -8.8 -4.1 -1.9 -3.9 -3.5 -11.6 -5.9 -11.5 -7.9 -10.2 -10.1 -10.2 -11.2 -3.4 -2.6 -4.1 -3.8 10.0 13.1 10.7 10.6 -8.1 -5.2 -8.0 -6.7 -6.1 -3.7 -7.5 -5.6 -11.1 -10.3 -10.6 -11.9 -3.2 -1.0 -2.2 -2.8 -10.5 -8.1 -9.4 -9.5 -8.3 -6.9 -9.4 -8.8 -50.0 -11.3 -50.0 -12.8 -0.6 2.2 -0.3 0.1 -50.0 -10.1 -17.5 -11.1 -8.6 -9.9 -8.6 -11.9 +CCG -8.9 -9.4 -8.6 -8.9 -2.9 -4.5 -2.2 -3.9 -8.8 -7.5 -8.1 -7.9 -8.8 -11.6 -7.7 -11.9 -0.7 -4.1 -0.5 -4.0 11.1 10.7 13.2 10.4 -5.7 -5.8 -3.5 -6.1 -3.6 -6.5 -3.3 -5.5 -9.4 -11.0 -8.7 -11.2 -1.8 -2.7 0.7 -3.0 -9.1 -8.2 -7.3 -9.4 -7.2 -8.2 -7.2 -8.2 -50.0 -13.2 -50.0 -13.3 0.5 -0.9 1.8 -0.6 -50.0 -11.4 -11.1 -10.5 -6.1 -12.9 -5.0 -11.9 +CCT -10.8 -9.6 -11.9 -7.7 -3.3 -3.8 -4.5 -1.6 -11.7 -7.7 -12.0 -6.2 -9.6 -12.0 -9.8 -9.4 -3.2 -4.7 -4.6 -2.4 10.5 10.6 10.4 12.6 -8.2 -7.9 -9.0 -4.7 -6.1 -6.0 -7.5 -2.9 -10.9 -12.2 -11.2 -10.9 -2.4 -2.9 -2.7 -0.9 -10.4 -9.7 -10.2 -8.0 -8.4 -9.1 -9.3 -6.5 -50.0 -13.3 -50.0 -11.0 -0.0 -0.4 -0.4 2.3 -50.0 -10.9 -17.2 -8.3 -8.3 -12.7 -7.8 -9.3 +CGA 2.1 -8.1 1.2 -7.0 -8.0 -9.5 -7.3 -9.9 10.5 -5.5 9.3 -5.7 -9.5 -15.1 -10.0 -12.9 2.5 -1.2 -0.1 -1.0 -6.0 -8.1 -5.7 -8.2 13.8 11.3 11.8 12.1 -6.0 -9.1 -9.0 -9.5 -8.9 -13.4 -10.0 -13.1 -9.9 -11.7 -9.8 -12.8 -5.9 -9.4 -6.5 -8.1 -10.7 -14.0 -13.3 -13.9 -50.0 -11.9 -50.0 -9.7 -8.9 -10.8 -9.0 -11.1 -50.0 -6.5 -5.3 -6.3 -10.5 -16.2 -10.4 -15.2 +CGC 0.0 -5.0 0.5 -6.8 -9.1 -7.8 -7.5 -8.9 7.7 -2.4 8.2 -5.1 -11.9 -13.1 -10.4 -14.3 -0.8 3.0 -0.9 0.8 -8.3 -5.2 -5.8 -7.9 11.3 15.0 11.2 12.8 -9.7 -5.3 -9.2 -7.8 -11.7 -10.6 -10.1 -12.2 -11.7 -8.8 -8.9 -11.8 -9.3 -5.0 -8.0 -8.2 -13.6 -11.4 -12.8 -13.0 -50.0 -7.2 -50.0 -8.4 -11.0 -7.7 -8.7 -10.2 -50.0 -1.5 -7.1 -4.9 -11.2 -11.6 -11.6 -15.0 +CGG 1.4 -7.3 2.2 -7.1 -8.0 -9.3 -6.4 -9.6 9.1 -5.5 10.0 -5.4 -10.9 -14.3 -8.4 -14.0 0.9 -1.1 2.4 -1.3 -6.9 -8.0 -3.5 -9.0 11.8 11.2 13.4 11.4 -7.3 -8.8 -6.5 -8.5 -10.0 -12.5 -7.8 -12.5 -9.6 -11.0 -7.1 -10.7 -7.9 -8.0 -4.3 -9.4 -11.4 -12.3 -10.9 -12.9 -50.0 -11.8 -50.0 -11.2 -9.4 -9.8 -7.3 -10.5 -50.0 -6.2 -2.2 -6.7 -9.8 -15.2 -8.5 -14.9 +CGT 0.2 -6.3 0.1 -4.3 -8.2 -8.9 -8.5 -7.0 8.5 -4.1 8.0 -2.1 -10.5 -13.4 -10.2 -11.9 0.2 1.6 -0.8 3.4 -7.5 -6.7 -6.1 -4.7 12.1 12.8 11.4 14.7 -8.7 -7.4 -9.4 -5.3 -9.9 -11.8 -10.5 -10.3 -9.9 -10.1 -9.3 -9.3 -8.1 -7.2 -8.0 -5.2 -12.0 -12.1 -12.6 -10.9 -50.0 -7.9 -50.0 -5.3 -9.3 -8.8 -8.9 -7.0 -50.0 -3.6 -7.1 -1.2 -10.2 -12.7 -9.9 -11.0 +CTA -10.2 -13.4 -11.8 -12.4 -6.0 -9.4 -7.1 -8.6 -9.8 -12.9 -10.8 -12.4 2.3 -1.4 1.0 -1.0 -3.0 -8.0 -5.1 -7.6 -2.2 -6.1 -3.6 -6.1 -6.0 -9.7 -7.3 -8.7 11.2 7.9 8.9 8.1 -12.1 -17.4 -13.2 -16.8 -6.3 -9.5 -7.5 -8.8 -12.7 -15.2 -13.1 -14.2 0.0 -3.1 -1.8 -3.1 -50.0 -10.7 -50.0 -9.3 -4.6 -8.9 -5.9 -8.3 -50.0 -12.8 -9.6 -10.6 9.5 -3.2 8.2 -2.8 +CTC -13.5 -11.3 -14.0 -12.9 -9.3 -7.1 -8.2 -8.9 -12.7 -10.3 -11.9 -12.3 -0.4 1.4 -0.6 -0.4 -7.2 -4.7 -6.9 -5.7 -7.4 -3.7 -6.5 -6.0 -9.1 -5.3 -8.8 -7.4 7.9 11.9 7.8 9.3 -15.2 -15.1 -14.6 -17.2 -9.7 -7.3 -8.2 -9.2 -15.0 -12.8 -14.1 -14.9 -2.8 0.2 -2.9 -2.3 -50.0 -7.4 -50.0 -8.7 -9.4 -7.3 -9.4 -9.4 -50.0 -8.0 -11.9 -9.7 6.5 0.5 6.4 -1.8 +CTG -13.0 -14.4 -11.9 -13.9 -7.7 -9.0 -6.7 -8.8 -11.7 -12.7 -10.7 -13.1 -0.2 -1.6 1.7 -1.6 -5.7 -8.7 -4.8 -8.1 -5.3 -7.5 -3.3 -7.5 -9.0 -9.2 -6.5 -9.4 8.9 7.8 10.1 7.8 -14.3 -17.7 -13.0 -17.8 -8.0 -9.4 -6.2 -9.2 -15.1 -14.9 -12.2 -14.9 -1.8 -3.2 -0.8 -3.2 -50.0 -10.8 -50.0 -9.9 -7.3 -9.6 -6.4 -9.4 -50.0 -12.3 -8.7 -11.3 7.6 -3.3 8.7 -2.9 +CTT -12.5 -12.9 -13.4 -10.0 -8.5 -9.0 -7.8 -6.8 -11.8 -11.3 -12.4 -10.1 -0.3 -0.5 -0.5 1.2 -6.1 -6.0 -6.7 -3.5 -5.9 -5.6 -5.5 -2.9 -9.5 -7.8 -8.5 -5.3 8.1 9.3 7.8 11.8 -14.4 -15.7 -14.5 -14.6 -8.4 -8.7 -7.9 -7.1 -14.3 -13.8 -13.8 -12.3 -2.4 -2.2 -2.9 -0.2 -50.0 -8.9 -50.0 -7.1 -8.1 -9.1 -8.7 -6.6 -50.0 -9.7 -11.4 -8.0 6.8 -1.8 6.9 0.4 +GAA -2.6 -6.3 -4.9 -4.9 -6.4 -9.4 -7.9 -8.6 -6.3 -7.4 -8.2 -6.6 -9.7 -14.9 -11.1 -13.9 -0.2 -8.2 -2.3 -6.8 -8.9 -11.1 -9.4 -10.9 -8.9 -11.7 -10.0 -9.9 -12.1 -15.2 -14.3 -14.4 11.1 2.9 9.2 3.5 -3.0 -7.0 -4.3 -6.2 -2.2 -6.6 -3.7 -5.7 -6.0 -10.4 -8.6 -9.5 -50.0 -15.5 -50.0 -13.9 -7.8 -10.5 -8.7 -9.6 -50.0 -16.5 -17.1 -14.8 -12.1 -18.9 -12.4 -17.4 +GAC -8.5 0.8 -9.1 -0.7 -10.1 -7.5 -9.1 -8.2 -11.4 -3.1 -11.8 -4.4 -15.5 -14.3 -14.8 -15.4 -6.6 -4.7 -7.1 -5.8 -12.5 -10.3 -11.0 -12.2 -13.4 -10.6 -12.5 -11.8 -17.4 -15.1 -17.7 -15.7 2.9 12.5 3.1 10.3 -7.7 -5.2 -6.2 -7.3 -5.4 -1.7 -5.4 -3.7 -11.6 -9.1 -13.0 -10.8 -50.0 -10.3 -50.0 -11.2 -9.8 -8.3 -9.1 -9.7 -50.0 -12.7 -20.6 -13.1 -16.0 -16.6 -17.0 -18.4 +GAG -5.0 -6.4 -3.4 -5.6 -7.5 -9.3 -7.1 -8.8 -8.8 -7.4 -6.9 -6.9 -11.4 -15.2 -9.7 -13.7 -1.8 -7.8 -0.8 -7.2 -9.4 -10.6 -8.7 -11.2 -10.0 -10.1 -7.8 -10.5 -13.2 -14.6 -13.0 -14.5 9.2 3.1 10.8 3.0 -4.5 -6.7 -2.7 -6.7 -5.0 -6.8 -2.5 -6.7 -7.5 -10.4 -7.4 -10.2 -50.0 -15.5 -50.0 -14.2 -8.9 -10.2 -8.5 -10.0 -50.0 -15.6 -15.3 -15.5 -13.0 -18.8 -12.6 -18.3 +GAT -8.1 -1.1 -8.9 1.4 -8.6 -9.2 -9.4 -6.8 -11.0 -4.9 -11.5 -2.6 -13.7 -16.8 -14.5 -12.6 -6.0 -6.7 -7.2 -4.2 -11.6 -11.9 -11.2 -10.9 -13.1 -12.2 -12.5 -10.3 -16.8 -17.2 -17.8 -14.6 3.5 10.3 3.0 12.4 -6.9 -7.5 -6.8 -4.9 -5.4 -4.2 -5.4 -1.3 -10.8 -11.5 -12.4 -8.2 -50.0 -12.5 -50.0 -8.9 -9.2 -10.0 -9.4 -7.9 -50.0 -14.3 -19.9 -11.4 -16.2 -19.2 -15.8 -15.9 +GCA -6.3 -7.4 -8.0 -6.0 2.8 -0.7 0.9 0.3 -7.5 -4.4 -8.4 -3.6 -3.0 -7.7 -3.7 -6.2 -5.3 -10.0 -7.2 -8.9 -0.7 -3.2 -1.8 -2.4 -9.9 -11.7 -9.6 -9.9 -6.3 -9.7 -8.0 -8.4 -3.0 -7.7 -4.5 -6.9 11.3 8.2 9.4 9.1 -1.0 -3.3 -1.8 -2.4 1.5 -2.1 -0.4 -1.1 -50.0 -14.5 -50.0 -12.9 2.8 -0.0 1.4 0.7 -50.0 -8.7 -14.1 -7.5 -5.2 -12.5 -6.5 -10.7 +GCC -9.9 -5.0 -10.0 -6.5 -0.7 2.6 -0.2 0.1 -10.3 -1.8 -9.9 -3.8 -6.4 -4.7 -5.8 -6.7 -8.2 -8.3 -8.0 -10.2 -3.9 -1.0 -2.7 -2.9 -11.7 -8.8 -11.0 -10.1 -9.5 -7.3 -9.4 -8.7 -7.0 -5.2 -6.7 -7.5 8.2 11.6 8.8 9.1 -3.7 -0.9 -3.1 -3.0 -2.0 1.2 -2.3 -1.3 -50.0 -12.1 -50.0 -12.6 0.1 2.5 0.7 0.6 -50.0 -6.0 -14.8 -7.5 -8.6 -9.4 -8.5 -11.2 +GCG -7.5 -6.2 -7.2 -6.2 0.9 0.2 2.5 0.2 -8.3 -3.5 -7.1 -3.7 -4.1 -6.3 -3.1 -6.3 -5.7 -8.9 -5.6 -8.4 -2.3 -2.2 0.7 -2.7 -9.8 -8.9 -7.1 -9.3 -7.5 -8.2 -6.2 -7.9 -4.3 -6.2 -2.7 -6.8 9.4 8.8 12.1 8.8 -2.1 -2.0 0.1 -2.4 0.0 -1.1 1.3 -0.8 -50.0 -11.9 -50.0 -12.6 1.2 0.7 3.5 0.8 -50.0 -7.1 -12.4 -7.1 -7.1 -10.6 -5.0 -10.6 +GCT -9.0 -6.5 -10.0 -4.8 0.1 -0.1 -0.3 2.4 -9.9 -3.5 -10.6 -2.0 -5.4 -6.6 -5.6 -4.4 -7.6 -9.9 -8.5 -8.2 -3.0 -2.8 -3.0 -0.9 -12.8 -11.8 -10.7 -9.3 -8.8 -9.2 -9.2 -7.1 -6.2 -7.3 -6.7 -4.9 9.1 9.1 8.8 11.2 -3.1 -3.0 -3.3 -1.0 -1.1 -1.4 -2.0 1.2 -50.0 -12.8 -50.0 -10.9 0.8 0.5 0.7 2.3 -50.0 -7.5 -16.5 -5.9 -7.8 -11.1 -7.8 -9.0 +GGA -7.1 -5.6 -9.1 -5.1 -5.9 -8.0 -6.9 -7.4 -1.9 -1.6 -4.7 -1.4 -9.6 -14.6 -10.4 -13.0 -6.7 -10.8 -9.4 -9.9 -9.1 -10.5 -9.1 -10.4 -5.9 -9.3 -7.9 -8.1 -12.7 -15.0 -15.1 -14.3 -2.2 -5.4 -5.0 -5.4 -1.0 -3.7 -2.1 -3.1 12.8 9.6 11.1 10.1 -4.8 -9.4 -8.1 -8.6 -50.0 -18.3 -50.0 -15.4 -5.9 -7.5 -6.6 -7.1 -50.0 -9.5 -11.7 -8.4 -12.5 -17.3 -13.2 -15.4 +GGC -10.2 -1.6 -10.2 -3.2 -7.3 -4.6 -6.5 -6.2 -6.7 3.0 -6.8 0.8 -11.9 -10.8 -11.5 -12.2 -9.6 -7.1 -9.7 -8.4 -9.8 -8.1 -8.2 -9.7 -9.4 -5.0 -8.0 -7.2 -15.2 -12.8 -14.9 -13.8 -6.6 -1.7 -6.8 -4.2 -3.3 -0.9 -2.0 -3.0 9.6 12.8 9.7 10.5 -8.5 -5.6 -9.3 -7.8 -50.0 -12.7 -50.0 -13.8 -6.8 -5.1 -5.3 -6.5 -50.0 -4.1 -12.8 -5.8 -14.4 -14.1 -13.6 -14.8 +GGG -8.2 -4.7 -7.1 -5.0 -6.5 -7.7 -5.5 -6.9 -4.1 -0.8 -1.2 -0.9 -10.5 -12.8 -8.2 -13.0 -7.5 -10.0 -7.2 -9.7 -9.2 -9.4 -7.3 -10.2 -6.5 -8.0 -4.3 -8.0 -13.1 -14.1 -12.2 -13.8 -3.7 -5.4 -2.5 -5.4 -1.8 -3.1 0.1 -3.3 11.1 9.7 12.9 9.8 -5.5 -8.1 -5.4 -7.8 -50.0 -16.4 -50.0 -14.8 -5.9 -7.1 -4.7 -7.2 -50.0 -8.4 -6.4 -8.1 -12.1 -16.2 -10.3 -15.8 +GGT -9.2 -3.0 -9.9 -1.2 -6.5 -6.1 -6.8 -4.4 -6.4 0.9 -7.0 3.0 -11.8 -13.0 -11.1 -10.4 -9.3 -9.2 -9.8 -6.4 -9.5 -9.5 -9.4 -8.0 -8.1 -8.2 -9.4 -5.2 -14.2 -14.9 -14.9 -12.3 -5.7 -3.7 -6.7 -1.3 -2.4 -3.0 -2.4 -1.0 10.1 10.5 9.8 13.1 -7.2 -8.0 -8.4 -5.0 -50.0 -14.7 -50.0 -11.4 -6.3 -6.7 -5.8 -5.0 -50.0 -6.1 -13.4 -3.6 -13.0 -16.0 -13.7 -13.3 +GTA -8.2 -10.8 -10.1 -9.8 -0.4 -3.6 -1.7 -2.9 -7.9 -8.4 -9.8 -8.2 6.2 2.3 0.6 2.9 -7.1 -11.6 -9.2 -11.1 -5.6 -8.3 -7.2 -8.4 -10.7 -13.6 -11.4 -12.0 0.0 -2.8 -1.8 -2.4 -6.0 -11.6 -7.5 -10.8 1.5 -2.0 0.0 -1.1 -4.8 -8.5 -5.5 -7.2 11.9 8.6 10.0 9.0 -50.0 -14.2 -50.0 -12.8 -4.1 -7.4 -5.7 -6.5 -50.0 -11.0 -14.3 -9.9 1.4 -7.9 -0.7 -6.8 +GTC -12.5 -8.7 -13.0 -9.9 -3.9 -1.0 -3.4 -2.9 -12.5 -6.3 -11.6 -8.1 3.3 6.0 -1.6 3.8 -10.5 -10.1 -11.1 -11.1 -9.0 -6.9 -8.2 -9.1 -14.0 -11.4 -12.3 -12.1 -3.1 0.2 -3.2 -2.2 -10.4 -9.1 -10.4 -11.5 -2.1 1.2 -1.1 -1.4 -9.4 -5.6 -8.1 -8.0 8.6 12.4 8.6 9.5 -50.0 -10.4 -50.0 -11.6 -7.2 -5.7 -7.5 -7.4 -50.0 -8.6 -15.7 -9.7 -3.0 -3.7 -3.2 -5.9 +GTG -11.1 -11.9 -10.6 -11.3 -2.6 -4.1 -1.7 -3.5 -11.4 -9.6 -9.6 -9.2 3.7 2.5 1.6 2.5 -9.6 -12.3 -9.5 -11.8 -8.0 -9.4 -7.2 -9.3 -13.3 -12.8 -10.9 -12.6 -1.8 -2.9 -0.8 -2.9 -8.6 -13.0 -7.4 -12.4 -0.4 -2.3 1.3 -2.0 -8.1 -9.3 -5.4 -8.4 10.0 8.6 11.4 8.9 -50.0 -13.7 -50.0 -13.2 -6.1 -8.1 -5.5 -7.5 -50.0 -11.3 -12.7 -10.1 -1.6 -7.8 -0.3 -7.2 +GTT -11.4 -10.0 -12.7 -8.2 -3.1 -3.1 -2.8 -0.9 -11.7 -7.3 -12.1 -5.8 3.6 3.6 -1.1 5.8 -9.4 -11.9 -10.7 -10.0 -8.5 -8.8 -8.2 -6.5 -13.9 -13.0 -12.9 -10.9 -3.1 -2.3 -3.2 -0.2 -9.5 -10.8 -10.2 -8.2 -1.1 -1.3 -0.8 1.2 -8.6 -7.8 -7.8 -5.0 9.0 9.5 8.9 12.0 -50.0 -13.0 -50.0 -10.3 -6.2 -7.0 -7.1 -5.4 -50.0 -9.3 -14.0 -8.2 -2.4 -6.3 -2.4 -3.9 +TAA -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 33.3 -50.0 30.6 -50.0 -50.0 -50.0 -50.0 -50.0 29.2 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 +TAC -14.8 -6.2 -14.9 -7.6 -14.6 -11.6 -13.0 -12.2 -14.0 -9.0 -14.1 -10.1 -13.6 -11.2 -12.4 -12.5 -8.1 2.2 -8.7 0.4 -15.3 -11.3 -13.2 -13.3 -11.9 -7.2 -11.8 -7.9 -10.7 -7.4 -10.8 -8.9 -15.5 -10.3 -15.5 -12.5 -14.5 -12.1 -11.9 -12.8 -18.3 -12.7 -16.4 -14.7 -14.2 -10.4 -13.7 -13.0 -50.0 15.1 -50.0 13.3 -9.9 -5.8 -8.9 -7.6 -50.0 -1.5 -7.8 -3.0 -8.1 3.6 -9.4 2.0 +TAG -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 30.6 -50.0 35.2 -50.0 -50.0 -50.0 -50.0 -50.0 28.5 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 +TAT -13.8 -7.5 -14.4 -5.1 -12.6 -11.6 -11.5 -10.1 -13.2 -9.7 -12.7 -7.4 -11.9 -11.9 -11.5 -10.2 -7.2 0.9 -8.6 2.6 -14.1 -12.8 -13.3 -11.0 -9.7 -8.4 -11.2 -5.3 -9.3 -8.7 -9.9 -7.1 -13.9 -11.2 -14.2 -8.9 -12.9 -12.6 -12.6 -10.9 -15.4 -13.8 -14.8 -11.4 -12.8 -11.6 -13.2 -10.3 -50.0 13.3 -50.0 15.2 -8.6 -7.0 -8.4 -4.8 -50.0 -3.0 -7.1 -0.1 -7.3 2.3 -8.7 3.9 +TCA -7.3 -6.3 -8.9 -5.5 2.9 0.2 1.5 1.2 -8.5 -2.3 -10.0 -1.7 -5.6 -10.5 -5.5 -9.6 -4.3 -7.9 -6.1 -7.2 2.3 -0.6 0.5 -0.0 -8.9 -11.0 -9.4 -9.3 -4.6 -9.4 -7.3 -8.1 -7.8 -9.8 -8.9 -9.2 2.8 0.1 1.2 0.8 -5.9 -6.8 -5.9 -6.3 -4.1 -7.2 -6.1 -6.2 -50.0 -9.9 -50.0 -8.6 12.5 9.4 11.0 9.8 -50.0 -4.8 -8.7 -3.5 -0.0 -8.6 -2.1 -7.0 +TCC -10.1 -4.3 -10.8 -5.8 0.1 2.3 0.7 0.6 -10.4 -0.2 -10.8 -2.0 -8.8 -9.2 -8.0 -9.7 -6.8 -5.9 -7.5 -7.0 -1.4 2.2 -0.9 -0.4 -10.8 -7.7 -9.8 -8.8 -8.9 -7.3 -9.6 -9.1 -10.5 -8.3 -10.2 -10.0 -0.0 2.5 0.7 0.5 -7.5 -5.1 -7.1 -6.7 -7.4 -5.7 -8.1 -7.0 -50.0 -5.8 -50.0 -7.0 9.4 12.7 10.1 10.0 -50.0 -1.5 -11.3 -3.3 -5.4 -4.2 -5.6 -6.8 +TCG -8.4 -6.2 -8.9 -5.9 1.8 0.4 2.7 1.2 -9.1 -1.2 -8.8 -1.5 -7.2 -10.5 -4.9 -9.6 -5.7 -7.4 -5.5 -7.4 0.3 -0.3 1.8 -0.4 -9.0 -8.7 -7.3 -8.9 -5.9 -9.4 -6.4 -8.7 -8.7 -9.1 -8.5 -9.4 1.4 0.7 3.5 0.7 -6.6 -5.3 -4.7 -5.8 -5.7 -7.5 -5.5 -7.1 -50.0 -8.9 -50.0 -8.4 11.0 10.1 13.2 10.2 -50.0 -4.2 -6.1 -3.6 -3.5 -8.4 -1.2 -6.8 +TCT -9.1 -5.4 -10.4 -4.2 1.0 0.5 0.6 2.4 -9.6 -1.5 -10.5 -0.5 -8.9 -10.5 -7.2 -8.3 -6.3 -6.9 -7.7 -5.1 -0.5 0.1 -0.6 2.3 -11.1 -10.2 -10.5 -7.0 -8.3 -9.4 -9.4 -6.6 -9.6 -9.7 -10.0 -7.9 0.7 0.6 0.8 2.3 -7.1 -6.5 -7.2 -5.0 -6.5 -7.4 -7.5 -5.4 -50.0 -7.6 -50.0 -4.8 9.8 10.0 10.2 12.1 -50.0 -3.1 -11.4 -0.7 -4.6 -6.6 -4.9 -3.9 +TGA -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 29.2 -50.0 28.5 -50.0 -50.0 -50.0 -50.0 -50.0 33.3 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 -50.0 +TGC -13.0 -7.0 -13.1 -8.3 -9.2 -6.5 -8.9 -7.6 -9.8 -0.7 -9.2 -2.1 -12.4 -10.3 -12.4 -11.6 -9.5 -4.6 -10.4 -5.7 -13.6 -10.1 -11.4 -10.9 -6.5 -1.5 -6.2 -3.6 -12.8 -8.0 -12.3 -9.7 -16.5 -12.7 -15.6 -14.3 -8.7 -6.0 -7.1 -7.5 -9.5 -4.1 -8.4 -6.1 -11.0 -8.6 -11.3 -9.3 -50.0 -1.5 -50.0 -3.0 -4.8 -1.5 -4.2 -3.1 -50.0 16.4 -5.1 14.2 -10.1 -4.3 -10.0 -5.4 +TGG -13.5 -16.3 -11.8 -15.5 -13.6 -15.3 -12.1 -16.1 -7.7 -13.3 -4.2 -12.6 -14.1 -16.2 -10.3 -15.4 -9.6 -11.6 -7.7 -9.8 -14.3 -17.5 -11.1 -17.2 -5.3 -7.1 -2.2 -7.1 -9.6 -11.9 -8.7 -11.4 -17.1 -20.6 -15.3 -19.9 -14.1 -14.8 -12.4 -16.5 -11.7 -12.8 -6.4 -13.4 -14.3 -15.7 -12.7 -14.0 -50.0 -7.8 -50.0 -7.1 -8.7 -11.3 -6.1 -11.4 -50.0 -5.1 18.6 -4.8 -8.6 -8.1 -4.5 -7.3 +TGT -12.4 -8.2 -13.0 -5.9 -7.7 -7.8 -7.4 -5.8 -8.8 -2.0 -9.3 -0.4 -11.6 -11.3 -11.6 -9.4 -8.9 -5.6 -10.0 -3.2 -11.5 -11.1 -10.5 -8.3 -6.3 -4.9 -6.7 -1.2 -10.6 -9.7 -11.3 -8.0 -14.8 -13.1 -15.5 -11.4 -7.5 -7.5 -7.1 -5.9 -8.4 -5.8 -8.1 -3.6 -9.9 -9.7 -10.1 -8.2 -50.0 -3.0 -50.0 -0.1 -3.5 -3.3 -3.6 -0.7 -50.0 14.2 -4.8 16.4 -8.9 -5.8 -8.9 -3.4 +TTA -10.7 -13.2 -12.4 -11.6 -4.8 -8.4 -6.1 -7.2 -10.3 -11.8 -11.0 -11.6 2.8 -1.7 0.7 -1.1 -6.2 -9.7 -7.3 -8.4 -5.3 -8.6 -6.1 -8.3 -10.5 -11.2 -9.8 -10.2 9.5 6.5 7.6 6.8 -12.1 -16.0 -13.0 -16.2 -5.2 -8.6 -7.1 -7.8 -12.5 -14.4 -12.1 -13.0 1.4 -3.0 -1.6 -2.4 -50.0 -8.1 -50.0 -7.3 -0.0 -5.4 -3.5 -4.6 -50.0 -10.1 -8.6 -8.9 13.2 -0.9 9.7 -0.3 +TTC -18.1 -12.3 -19.4 -14.2 -12.2 -9.5 -11.5 -10.8 -17.9 -11.9 -18.2 -13.9 -6.4 -3.7 -6.8 -5.4 -12.8 -5.9 -13.6 -7.4 -13.7 -9.9 -12.9 -12.7 -16.2 -11.6 -15.2 -12.7 -3.2 0.5 -3.3 -1.8 -18.9 -16.6 -18.8 -19.2 -12.5 -9.4 -10.6 -11.1 -17.3 -14.1 -16.2 -16.0 -7.9 -3.7 -7.8 -6.3 -50.0 3.6 -50.0 2.3 -8.6 -4.2 -8.4 -6.6 -50.0 -4.3 -8.1 -5.8 -0.9 14.2 -1.8 11.6 +TTG -11.8 -13.1 -11.5 -12.0 -6.2 -8.3 -5.4 -7.4 -11.8 -12.3 -11.1 -11.4 0.5 -2.5 2.4 -1.6 -6.8 -9.9 -6.4 -8.9 -6.1 -8.6 -5.0 -7.8 -10.4 -11.6 -8.5 -9.9 8.2 6.4 8.7 6.9 -12.4 -17.0 -12.6 -15.8 -6.5 -8.5 -5.0 -7.8 -13.2 -13.6 -10.3 -13.7 -0.7 -3.2 -0.3 -2.4 -50.0 -9.4 -50.0 -8.7 -2.1 -5.6 -1.2 -4.9 -50.0 -10.0 -4.5 -8.9 9.7 -1.8 11.3 -0.9 +TTT -17.2 -13.3 -17.8 -11.6 -11.0 -11.1 -10.4 -9.0 -16.0 -12.7 -16.1 -11.1 -5.2 -5.4 -6.0 -3.3 -11.8 -7.3 -13.3 -5.9 -12.7 -11.9 -11.9 -9.3 -15.2 -15.0 -14.9 -11.0 -2.8 -1.8 -2.9 0.4 -17.4 -18.4 -18.3 -15.9 -10.7 -11.2 -10.6 -9.0 -15.4 -14.8 -15.8 -13.3 -6.8 -5.9 -7.2 -3.9 -50.0 2.0 -50.0 3.9 -7.0 -6.8 -6.8 -3.9 -50.0 -5.4 -7.3 -3.4 -0.3 11.6 -0.9 14.1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/STR b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/STR new file mode 100644 index 0000000000000000000000000000000000000000..23189c34ab4b42d23ad223a2b056a8d37a9604d9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/STR @@ -0,0 +1,26 @@ +# Steven Henikoff and Jorja G. Henikoff: +# "Performance evaluation of amino acid substitution matrices." +# Proteins: Structure, Function, and Genetics: 17(1): 49-61 (1993). +# Figure 1, lower triangle. +# PMID 8234244 + A C D E F G H I K L M N P Q R S T V W Y +A 4 -2 -1 0 -3 0 -2 -2 -1 -2 0 -1 -1 0 -1 0 -1 0 -3 -3 +C -2 11 -7 -3 -2 -6 -6 -4 -4 -6 -5 -6 -8 -3 -2 -4 -5 -4 -6 -6 +D -1 -7 6 2 -5 -1 0 -3 -1 -6 -4 2 -1 0 -2 0 -1 -4 -6 -3 +E 0 -3 2 5 -4 -2 -2 -3 1 -4 -2 0 -1 2 0 -1 0 -2 -6 -2 +F -3 -2 -5 -4 7 -6 -2 1 -3 2 0 -3 -5 -4 -4 -3 -3 -1 2 3 +G 0 -6 -1 -2 -6 5 -3 -5 -3 -5 -4 -1 -2 -2 -2 -1 -3 -4 -4 -3 +H -2 -6 0 -2 -2 -3 8 -5 0 -3 -2 2 -3 0 0 -2 -2 -2 -3 0 +I -2 -4 -3 -3 1 -5 -5 6 -3 2 1 -3 -4 -5 -3 -3 -2 2 -2 -1 +K -1 -4 -1 1 -3 -3 0 -3 5 -2 -1 0 -1 1 2 -1 0 -3 -3 -2 +L -2 -6 -6 -4 2 -5 -3 2 -2 5 3 -3 -3 -3 -3 -4 -3 1 -1 -2 +M 0 -5 -4 -2 0 -4 -2 1 -1 3 8 -2 -6 1 -4 -4 -2 0 -2 -1 +N -1 -6 2 0 -3 -1 2 -3 0 -3 -2 5 -2 0 -1 0 0 -4 -5 -1 +P -1 -8 -1 -1 -5 -2 -3 -4 -1 -3 -6 -2 7 -2 -2 -1 -1 -4 -4 -6 +Q 0 -3 0 2 -4 -2 0 -5 1 -3 1 0 -2 6 1 -1 0 -2 -5 -3 +R -1 -2 -2 0 -4 -2 0 -3 2 -3 -4 -1 -2 1 7 0 -1 -3 -2 -1 +S 0 -4 0 -1 -3 -1 -2 -3 -1 -4 -4 0 -1 -1 0 4 1 -3 -5 -2 +T -1 -5 -1 0 -3 -3 -2 -2 0 -3 -2 0 -1 0 -1 1 5 -1 -5 -2 +V 0 -4 -4 -2 -1 -4 -2 2 -3 1 0 -4 -4 -2 -3 -3 -1 5 -4 -1 +W -3 -6 -6 -6 2 -4 -3 -2 -3 -1 -2 -5 -4 -5 -2 -5 -5 -4 10 2 +Y -3 -6 -3 -2 3 -3 0 -1 -2 -2 -1 -1 -6 -3 -1 -2 -2 -1 2 7 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/TRANS b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/TRANS new file mode 100644 index 0000000000000000000000000000000000000000..611e6b982b6b235523f65703d26f999e88dd2c23 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/TRANS @@ -0,0 +1,12 @@ +# David Wheeler, +# Department of Cell Biology, Baylor College of Medicine, Houston, Texas: +# "Weight matrices for sequence similarity scoring." +# Version 2.0, May 1996. +# David Wheeler defined the Transition/Transversion Matrix as a penalty +# matrix; the matrix below is a similarity matrix where +# similarity = 5 - penalty. + A T C G +A 5 0 0 4 +T 0 5 4 0 +C 0 4 5 0 +G 4 0 0 5 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/tabular.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/tabular.py new file mode 100644 index 0000000000000000000000000000000000000000..75401b61727c4ec958d7732ab47fa8d756aa44fa --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/tabular.py @@ -0,0 +1,408 @@ +# Copyright 2021 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Align support for tabular output from BLAST or FASTA. + +This module contains a parser for tabular output from BLAST run with the +'-outfmt 7' argument, as well as tabular output from William Pearson's +FASTA alignment tools using the '-m 8CB' or '-m 8CC' arguments. +""" + +import enum +import re + +import numpy as np + +from Bio.Align import Alignment +from Bio.Align import interfaces +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class State(enum.Enum): + """Enumerate alignment states needed when parsing a BTOP string.""" + + MATCH = enum.auto() + QUERY_GAP = enum.auto() + TARGET_GAP = enum.auto() + NONE = enum.auto() + + +class AlignmentIterator(interfaces.AlignmentIterator): + """Alignment iterator for tabular output from BLAST or FASTA. + + For reading (pairwise) alignments from tabular output generated by BLAST + run with the '-outfmt 7' argument, as well as tabular output generated by + William Pearson's FASTA alignment programs with the '-m 8CB' or '-m 8CC' + output formats. + """ + + fmt = "Tabular" + + def _read_header(self, stream): + line = stream.readline() + if not line: + raise ValueError("Empty file.") + if not line.startswith("# "): + raise ValueError("Missing header.") + line = line.rstrip() + self._parse_header(stream, line) + + def _parse_header(self, stream, line): + metadata = {} + blast_programs = ( + "BLASTN", + "BLASTP", + "BLASTX", + "TBLASTN", + "TBLASTX", + "DELTABLAST", + "PSIBLAST", + "RPSBLAST", + "RPSTBLASTN", + ) + try: + program, version = line[2:].split(None, 1) + if program not in blast_programs: + raise ValueError("Not a BLAST program") + except ValueError: + # FASTA + metadata["Command line"] = line[2:] + line = stream.readline() + assert line.startswith("# ") + metadata["Program"], metadata["Version"] = line[2:].rstrip().split(None, 1) + self._final_prefix = "# FASTA processed " + else: + # BLAST + metadata["Program"], metadata["Version"] = program, version + self._final_prefix = "# BLAST processed " + for line in stream: + line = line.strip() + assert line.startswith("# ") + try: + prefix, value = line[2:].split(": ") + except ValueError: + suffix = " hits found" + assert line.endswith(suffix) + hits = int(line[2 : -len(suffix)]) + break + if prefix == "Query": + if metadata["Program"] == "FASTA": + query_line, query_size = value.rsplit(" - ", 1) + query_size, unit = query_size.split() + self._query_size = int(query_size) + assert unit in ("nt", "aa") + else: + query_line = value + self._query_size = None + try: + self._query_id, self._query_description = query_line.split(None, 1) + except ValueError: + self._query_id = query_line.strip() + self._query_description = None + elif prefix == "Database": + metadata["Database"] = value + elif prefix == "Fields": + self._fields = value.split(", ") + elif prefix == "RID": + metadata["RID"] = value + self.metadata = metadata + + def _read_next_alignment(self, stream): + for line in stream: + line = line.rstrip() + if line.startswith("# "): + if line.startswith(self._final_prefix) and line.endswith(" queries"): + del self._fields + del self._query_id + del self._query_description + del self._query_size + del self._final_prefix + return + self._parse_header(stream, line) + else: + break + alignment_length = None + identical = None + btop = None + cigar = None + score = None + query_id = None + target_id = None + query_start = None + query_end = None + target_start = None + target_end = None + query_sequence = None + target_sequence = None + target_length = None + coordinates = None + query_size = self._query_size + columns = line.split("\t") + assert len(columns) == len(self._fields) + annotations = {} + query_annotations = {} + target_annotations = {} + for column, field in zip(columns, self._fields): + if field == "query id": + query_id = column + if self._query_id is not None: + assert query_id == self._query_id + elif field == "subject id": + target_id = column + elif field == "% identity": + annotations[field] = float(column) + elif field == "alignment length": + alignment_length = int(column) + elif field == "mismatches": + annotations[field] = int(column) + elif field == "gap opens": + annotations[field] = int(column) + elif field == "q. start": + query_start = int(column) + elif field == "q. end": + query_end = int(column) + elif field == "s. start": + target_start = int(column) + elif field == "s. end": + target_end = int(column) + elif field == "evalue": + annotations["evalue"] = float(column) + elif field == "bit score": + annotations["bit score"] = float(column) + elif field == "BTOP": + coordinates = self.parse_btop(column) + elif field == "aln_code": + coordinates = self.parse_cigar(column) + elif field == "query gi": + query_annotations["gi"] = column + elif field == "query acc.": + query_annotations["acc."] = column + elif field == "query acc.ver": + query_annotations["acc.ver"] = column + if query_id is None: + query_id = column + elif field == "query length": + if query_size is None: + query_size = int(column) + else: + assert query_size == int(column) + elif field == "subject ids": + target_annotations["ids"] = column + elif field == "subject gi": + target_annotations["gi"] = column + elif field == "subject gis": + target_annotations["gis"] = column + elif field == "subject acc.": + target_annotations["acc."] = column + elif field == "subject accs.": + target_annotations["accs."] = column + elif field == "subject tax ids": + target_annotations["tax ids"] = column + elif field == "subject sci names": + target_annotations["sci names"] = column + elif field == "subject com names": + target_annotations["com names"] = column + elif field == "subject blast names": + target_annotations["blast names"] = column + elif field == "subject super kingdoms": + target_annotations["super kingdoms"] = column + elif field == "subject title": + target_annotations["title"] = column + elif field == "subject titles": + target_annotations["titles"] = column + elif field == "subject strand": + target_annotations["strand"] = column + elif field == "% subject coverage": + target_annotations["% coverage"] = float(column) + elif field == "subject acc.ver": + target_annotations["acc.ver"] = column + if target_id is None: + target_id = column + elif field == "subject length": + target_length = int(column) + elif field == "query seq": + query_sequence = column + elif field == "subject seq": + target_sequence = column + elif field == "score": + score = int(column) + elif field == "identical": + identical = int(column) + annotations[field] = identical + elif field == "positives": + annotations[field] = int(column) + elif field == "gaps": + annotations[field] = int(column) + elif field == "% positives": + annotations[field] = float(column) + elif field == "% hsp coverage": + annotations[field] = float(column) + elif field == "query/sbjct frames": + annotations[field] = column + elif field == "query frame": + query_annotations["frame"] = column + elif field == "sbjct frame": + target_annotations["frame"] = column + else: + raise ValueError("Unexpected field '%s'" % field) + program = self.metadata["Program"] + if coordinates is None: + if alignment_length is not None: + annotations["alignment length"] = alignment_length + # otherwise, get it from alignment.shape + if query_start is not None and query_end is not None: + if query_start < query_end: + query_start -= 1 + else: + query_end -= 1 + if target_start is not None and target_end is not None: + if target_start < target_end: + target_start -= 1 + else: + target_end -= 1 + if coordinates is None or program in ("BLASTX", "TBLASTX"): + if query_start is not None: + query_annotations["start"] = query_start + if query_end is not None: + query_annotations["end"] = query_end + elif coordinates is not None: + if query_start < query_end: + coordinates[1, :] += query_start + else: + # mapped to reverse strand + coordinates[1, :] = query_start - coordinates[1, :] + if coordinates is None or program in ("TBLASTN", "TBLASTX"): + if target_start is not None: + target_annotations["start"] = target_start + if target_end is not None: + target_annotations["end"] = target_end + elif coordinates is not None: + coordinates[0, :] += target_start + if query_sequence is None: + if query_size is None: + query_seq = None + else: + query_seq = Seq(None, length=query_size) + else: + query_sequence = query_sequence.replace("-", "") + if program == "TBLASTN": + assert len(query_sequence) == query_end - query_start + query_seq = Seq({query_start: query_sequence}, length=query_size) + elif program == "TBLASTX": + query_annotations["start"] = query_start + query_annotations["end"] = query_end + query_seq = Seq(query_sequence) + else: + raise Exception("Unknown program %s" % program) + query = SeqRecord(query_seq, id=query_id) + if self._query_description is not None: + query.description = self._query_description + if query_annotations: + query.annotations = query_annotations + if self.metadata["Program"] in ("TBLASTN", "TBLASTX"): + target_annotations["length"] = target_length + if target_sequence is None: + target_seq = None + else: + target_sequence = target_sequence.replace("-", "") + target_seq = Seq(target_sequence) + else: + if target_sequence is None: + if target_end is None: + target_seq = None + else: + target_seq = Seq(None, length=target_end) + else: + target_sequence = target_sequence.replace("-", "") + if target_start is not None and target_end is not None: + assert len(target_sequence) == target_end - target_start + target_seq = Seq({target_start: target_sequence}, length=target_end) + target = SeqRecord(target_seq, id=target_id) + if target_annotations: + target.annotations = target_annotations + records = [target, query] + alignment = Alignment(records, coordinates) + alignment.annotations = annotations + if score is not None: + alignment.score = score + return alignment + + def parse_btop(self, btop): + """Parse a BTOP string and return alignment coordinates. + + A BTOP (Blast trace-back operations) string is used by BLAST to + describe a sequence alignment. + """ + target_coordinates = [] + query_coordinates = [] + target_coordinates.append(0) + query_coordinates.append(0) + state = State.NONE + tokens = re.findall("([A-Z-*]{2}|\\d+)", btop) + # each token is now + # - an integer + # - a pair of characters, which may include dashes + for token in tokens: + if token.startswith("-"): + if state != State.QUERY_GAP: + target_coordinates.append(target_coordinates[-1]) + query_coordinates.append(query_coordinates[-1]) + state = State.QUERY_GAP + target_coordinates[-1] += 1 + elif token.endswith("-"): + if state != State.TARGET_GAP: + target_coordinates.append(target_coordinates[-1]) + query_coordinates.append(query_coordinates[-1]) + state = State.TARGET_GAP + query_coordinates[-1] += 1 + else: + try: + length = int(token) + except ValueError: + # pair of mismatched letters + length = 1 + if state == State.MATCH: + target_coordinates[-1] += length + query_coordinates[-1] += length + else: + target_coordinates.append(target_coordinates[-1] + length) + query_coordinates.append(query_coordinates[-1] + length) + state = State.MATCH + coordinates = np.array([target_coordinates, query_coordinates], np.intp) + return coordinates + + def parse_cigar(self, cigar): + """Parse a CIGAR string and return alignment coordinates. + + A CIGAR string, as defined by the SAM Sequence Alignment/Map format, + describes a sequence alignment as a series of lengths and operation + (alignment/insertion/deletion) codes. + """ + target_coordinates = [] + query_coordinates = [] + target_coordinate = 0 + query_coordinate = 0 + target_coordinates.append(target_coordinate) + query_coordinates.append(query_coordinate) + state = State.NONE + tokens = re.findall("(M|D|I|\\d+)", cigar) + # each token is now + # - the length of the operation + # - the operation + for length, operation in zip(tokens[::2], tokens[1::2]): + length = int(length) + if operation == "M": + target_coordinate += length + query_coordinate += length + elif operation == "I": + target_coordinate += length + elif operation == "D": + query_coordinate += length + target_coordinates.append(target_coordinate) + query_coordinates.append(query_coordinate) + coordinates = np.array([target_coordinates, query_coordinates], np.intp) + return coordinates diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/ClustalIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/ClustalIO.py new file mode 100644 index 0000000000000000000000000000000000000000..69499c7b10e0ee7b4e155cee6413d33a07e7ce7d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/ClustalIO.py @@ -0,0 +1,313 @@ +# Copyright 2006-2016 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.AlignIO support for "clustal" output from CLUSTAL W and other tools. + +You are expected to use this module via the Bio.AlignIO functions (or the +Bio.SeqIO functions if you want to work directly with the gapped sequences). +""" + +from Bio.Align import MultipleSeqAlignment +from Bio.AlignIO.Interfaces import AlignmentIterator +from Bio.AlignIO.Interfaces import SequentialAlignmentWriter +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class ClustalWriter(SequentialAlignmentWriter): + """Clustalw alignment writer.""" + + def write_alignment(self, alignment): + """Use this to write (another) single alignment to an open file.""" + if len(alignment) == 0: + raise ValueError("Must have at least one sequence") + if alignment.get_alignment_length() == 0: + # This doubles as a check for an alignment object + raise ValueError("Non-empty sequences are required") + + # Old versions of the parser in Bio.Clustalw used a ._version property + try: + version = str(alignment._version) + except AttributeError: + version = "" + if not version: + version = "1.81" + if version.startswith("2."): + # e.g. 2.0.x + output = f"CLUSTAL {version} multiple sequence alignment\n\n\n" + else: + # e.g. 1.81 or 1.83 + output = f"CLUSTAL X ({version}) multiple sequence alignment\n\n\n" + + cur_char = 0 + max_length = len(alignment[0]) + + if max_length <= 0: + raise ValueError("Non-empty sequences are required") + + if "clustal_consensus" in alignment.column_annotations: + star_info = alignment.column_annotations["clustal_consensus"] + else: + try: + # This was originally stored by Bio.Clustalw as ._star_info + star_info = alignment._star_info + except AttributeError: + star_info = None + + # keep displaying sequences until we reach the end + while cur_char != max_length: + # calculate the number of sequences to show, which will + # be less if we are at the end of the sequence + if (cur_char + 50) > max_length: + show_num = max_length - cur_char + else: + show_num = 50 + + # go through all of the records and print out the sequences + # when we output, we do a nice 80 column output, although this + # may result in truncation of the ids. + for record in alignment: + # Make sure we don't get any spaces in the record + # identifier when output in the file by replacing + # them with underscores: + line = record.id[0:30].replace(" ", "_").ljust(36) + line += str(record.seq[cur_char : (cur_char + show_num)]) + output += line + "\n" + + # now we need to print out the star info, if we've got it + if star_info: + output += ( + (" " * 36) + star_info[cur_char : (cur_char + show_num)] + "\n" + ) + + output += "\n" + cur_char += show_num + + # Want a trailing blank new line in case the output is concatenated + self.handle.write(output + "\n") + + +class ClustalIterator(AlignmentIterator): + """Clustalw alignment iterator.""" + + _header = None # for caching lines between __next__ calls + + def __next__(self): + """Parse the next alignment from the handle.""" + handle = self.handle + + if self._header is None: + line = handle.readline() + else: + # Header we saved from when we were parsing + # the previous alignment. + line = self._header + self._header = None + + if not line: + raise StopIteration + + # Whitelisted headers we know about + known_headers = [ + "CLUSTAL", + "PROBCONS", + "MUSCLE", + "MSAPROBS", + "Kalign", + "Biopython", + ] + if line.strip().split()[0] not in known_headers: + raise ValueError( + "%s is not a known CLUSTAL header: %s" + % (line.strip().split()[0], ", ".join(known_headers)) + ) + + # find the clustal version in the header line + version = None + for word in line.split(): + if word[0] == "(" and word[-1] == ")": + word = word[1:-1] + if word[0] in "0123456789": + version = word + break + + # There should be two blank lines after the header line + line = handle.readline() + while line.strip() == "": + line = handle.readline() + + # If the alignment contains entries with the same sequence + # identifier (not a good idea - but seems possible), then this + # dictionary based parser will merge their sequences. Fix this? + ids = [] + seqs = [] + consensus = "" + seq_cols = None # Used to extract the consensus + + # Use the first block to get the sequence identifiers + while True: + if line[0] != " " and line.strip() != "": + # Sequences identifier... + fields = line.rstrip().split() + + # We expect there to be two fields, there can be an optional + # "sequence number" field containing the letter count. + if len(fields) < 2 or len(fields) > 3: + raise ValueError(f"Could not parse line:\n{line}") + + ids.append(fields[0]) + seqs.append(fields[1]) + + # Record the sequence position to get the consensus + if seq_cols is None: + start = len(fields[0]) + line[len(fields[0]) :].find(fields[1]) + end = start + len(fields[1]) + seq_cols = slice(start, end) + del start, end + assert fields[1] == line[seq_cols] + + if len(fields) == 3: + # This MAY be an old style file with a letter count... + try: + letters = int(fields[2]) + except ValueError: + raise ValueError( + f"Could not parse line, bad sequence number:\n{line}" + ) from None + if len(fields[1].replace("-", "")) != letters: + raise ValueError( + f"Could not parse line, invalid sequence number:\n{line}" + ) + elif line[0] == " ": + # Sequence consensus line... + assert len(ids) == len(seqs) + assert len(ids) > 0 + assert seq_cols is not None + consensus = line[seq_cols] + assert not line[: seq_cols.start].strip() + assert not line[seq_cols.stop :].strip() + # Check for blank line (or end of file) + line = handle.readline() + assert line.strip() == "" + break + else: + # No consensus + break + line = handle.readline() + if not line: + break # end of file + + assert line.strip() == "" + assert seq_cols is not None + + # Confirm all same length + for s in seqs: + assert len(s) == len(seqs[0]) + if consensus: + assert len(consensus) == len(seqs[0]) + + # Loop over any remaining blocks... + done = False + while not done: + # There should be a blank line between each block. + # Also want to ignore any consensus line from the + # previous block. + while (not line) or line.strip() == "": + line = handle.readline() + if not line: + break # end of file + if not line: + break # end of file + + if line.split(None, 1)[0] in known_headers: + # Found concatenated alignment. + self._header = line + break + + for i in range(len(ids)): + if line[0] == " ": + raise ValueError(f"Unexpected line:\n{line!r}") + fields = line.rstrip().split() + + # We expect there to be two fields, there can be an optional + # "sequence number" field containing the letter count. + if len(fields) < 2 or len(fields) > 3: + raise ValueError(f"Could not parse line:\n{line!r}") + + if fields[0] != ids[i]: + raise ValueError( + "Identifiers out of order? Got '%s' but expected '%s'" + % (fields[0], ids[i]) + ) + + if fields[1] != line[seq_cols]: + start = len(fields[0]) + line[len(fields[0]) :].find(fields[1]) + if start != seq_cols.start: + raise ValueError("Old location %s -> %i:XX" % (seq_cols, start)) + end = start + len(fields[1]) + seq_cols = slice(start, end) + del start, end + + # Append the sequence + seqs[i] += fields[1] + assert len(seqs[i]) == len(seqs[0]) + + if len(fields) == 3: + # This MAY be an old style file with a letter count... + try: + letters = int(fields[2]) + except ValueError: + raise ValueError( + f"Could not parse line, bad sequence number:\n{line}" + ) from None + if len(seqs[i].replace("-", "")) != letters: + raise ValueError( + f"Could not parse line, invalid sequence number:\n{line}" + ) + + # Read in the next line + line = handle.readline() + # There should now be a consensus line + if consensus: + assert line[0] == " " + assert seq_cols is not None + consensus += line[seq_cols] + assert len(consensus) == len(seqs[0]) + assert not line[: seq_cols.start].strip() + assert not line[seq_cols.stop :].strip() + # Read in the next line + line = handle.readline() + + assert len(ids) == len(seqs) + if len(seqs) == 0 or len(seqs[0]) == 0: + raise StopIteration + + if ( + self.records_per_alignment is not None + and self.records_per_alignment != len(ids) + ): + raise ValueError( + "Found %i records in this alignment, told to expect %i" + % (len(ids), self.records_per_alignment) + ) + + records = (SeqRecord(Seq(s), id=i, description=i) for (i, s) in zip(ids, seqs)) + alignment = MultipleSeqAlignment(records) + # TODO - Handle alignment annotation better, for now + # mimic the old parser in Bio.Clustalw + if version: + alignment._version = version + if consensus: + alignment_length = len(seqs[0]) + if len(consensus) != alignment_length: + raise ValueError( + "Alignment length is %i, consensus length is %i, '%s'" + % (alignment_length, len(consensus), consensus) + ) + alignment.column_annotations["clustal_consensus"] = consensus + # For backward compatibility prior to .column_annotations: + alignment._star_info = consensus + return alignment diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/EmbossIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/EmbossIO.py new file mode 100644 index 0000000000000000000000000000000000000000..39babdc68261b35b6e18c608e8bb6d5ce591abf3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/EmbossIO.py @@ -0,0 +1,220 @@ +# Copyright 2008-2016 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.AlignIO support for "emboss" alignment output from EMBOSS tools. + +You are expected to use this module via the Bio.AlignIO functions (or the +Bio.SeqIO functions if you want to work directly with the gapped sequences). + +This module contains a parser for the EMBOSS pairs/simple file format, for +example from the alignret, water and needle tools. +""" + +from Bio.Align import MultipleSeqAlignment +from Bio.AlignIO.Interfaces import AlignmentIterator +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class EmbossIterator(AlignmentIterator): + """Emboss alignment iterator. + + For reading the (pairwise) alignments from EMBOSS tools in what they + call the "pairs" and "simple" formats. + """ + + _header = None # for caching lines between __next__ calls + + def __next__(self): + """Parse the next alignment from the handle.""" + handle = self.handle + + if self._header is None: + line = handle.readline() + else: + # Header we saved from when we were parsing + # the previous alignment. + line = self._header + self._header = None + + if not line: + raise StopIteration + + while line.rstrip() != "#=======================================": + line = handle.readline() + if not line: + raise StopIteration + + length_of_seqs = None + number_of_seqs = None + ids = [] + header_dict = {} + + while line[0] == "#": + # Read in the rest of this alignment header, + # try and discover the number of records expected + # and their length + parts = line[1:].split(":", 1) + key = parts[0].lower().strip() + if key == "aligned_sequences": + number_of_seqs = int(parts[1].strip()) + assert len(ids) == 0 + # Should now expect the record identifiers... + for i in range(number_of_seqs): + line = handle.readline() + parts = line[1:].strip().split(":", 1) + assert i + 1 == int(parts[0].strip()) + ids.append(parts[1].strip()) + assert len(ids) == number_of_seqs + if key == "length": + length_of_seqs = int(parts[1].strip()) + + # Parse the rest of the header + if key == "identity": + header_dict["identity"] = int(parts[1].strip().split("/")[0]) + if key == "similarity": + header_dict["similarity"] = int(parts[1].strip().split("/")[0]) + if key == "gaps": + header_dict["gaps"] = int(parts[1].strip().split("/")[0]) + if key == "score": + header_dict["score"] = float(parts[1].strip()) + + # And read in another line... + line = handle.readline() + + if number_of_seqs is None: + raise ValueError("Number of sequences missing!") + if length_of_seqs is None: + raise ValueError("Length of sequences missing!") + + if ( + self.records_per_alignment is not None + and self.records_per_alignment != number_of_seqs + ): + raise ValueError( + "Found %i records in this alignment, told to expect %i" + % (number_of_seqs, self.records_per_alignment) + ) + + seqs = [""] * len(ids) + seq_starts = [] + index = 0 + + # Parse the seqs + while line: + if len(line) > 21: + id_start = line[:21].strip().split(None, 1) + seq_end = line[21:].strip().split(None, 1) + if len(id_start) == 2 and len(seq_end) == 2: + # identifier, seq start position, seq, seq end position + # (an aligned seq is broken up into multiple lines) + id, start = id_start + seq, end = seq_end + if start >= end: + # Special case, either a single letter is present, + # or no letters at all. + if seq.replace("-", "") == "": + start = int(start) + end = int(end) + else: + start = int(start) - 1 + end = int(end) + else: + assert seq.replace("-", "") != "", repr(line) + start = int(start) - 1 # python counting + end = int(end) + + if index < 0 or index >= number_of_seqs: + raise ValueError( + "Expected index %i in range [0,%i)" + % (index, number_of_seqs) + ) + # The identifier is truncated... + assert id == ids[index] or id == ids[index][: len(id)] + + if len(seq_starts) == index: + # Record the start + seq_starts.append(start) + + # Check the start... + if start >= end: + assert seq.replace("-", "") == "", line + elif start - seq_starts[index] != len(seqs[index].replace("-", "")): + raise ValueError( + "Found %i chars so far for sequence %i (%s, %r), line says start %i:\n%s" + % ( + len(seqs[index].replace("-", "")), + index, + id, + seqs[index], + start, + line, + ) + ) + seqs[index] += seq + + # Check the end ... + if end != seq_starts[index] + len(seqs[index].replace("-", "")): + raise ValueError( + "Found %i chars so far for sequence %i (%s, %r, start=%i), file says end %i:\n%s" + % ( + len(seqs[index].replace("-", "")), + index, + id, + seqs[index], + seq_starts[index], + end, + line, + ) + ) + + index += 1 + if index >= number_of_seqs: + index = 0 + else: + # just a start value, this is just alignment annotation (?) + # print("Skipping: " + line.rstrip()) + pass + elif line.strip() == "": + # Just a spacer? + pass + else: + raise ValueError(f"Unrecognised EMBOSS pairwise line: {line!r}\n") + + line = handle.readline() + if ( + line.rstrip() == "#---------------------------------------" + or line.rstrip() == "#=======================================" + ): + # End of alignment + self._header = line + break + + assert index == 0 + + if ( + self.records_per_alignment is not None + and self.records_per_alignment != len(ids) + ): + raise ValueError( + "Found %i records in this alignment, told to expect %i" + % (len(ids), self.records_per_alignment) + ) + + records = [] + for id, seq in zip(ids, seqs): + if len(seq) != length_of_seqs: + # EMBOSS 2.9.0 is known to use spaces instead of minus signs + # for leading gaps, and thus fails to parse. This old version + # is still used as of Dec 2008 behind the EBI SOAP webservice: + # http://www.ebi.ac.uk/Tools/webservices/wsdl/WSEmboss.wsdl + raise ValueError( + "Error parsing alignment - sequences of " + "different length? You could be using an " + "old version of EMBOSS." + ) + records.append(SeqRecord(Seq(seq), id=id, description=id)) + return MultipleSeqAlignment(records, annotations=header_dict) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/FastaIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/FastaIO.py new file mode 100644 index 0000000000000000000000000000000000000000..012106838d45e730856c3e4994a5f90d3a0ef213 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/FastaIO.py @@ -0,0 +1,346 @@ +# Copyright 2008-2016 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.AlignIO support for "fasta-m10" output from Bill Pearson's FASTA tools. + +You are expected to use this module via the Bio.AlignIO functions (or the +Bio.SeqIO functions if you want to work directly with the gapped sequences). + +This module contains a parser for the pairwise alignments produced by Bill +Pearson's FASTA tools, for use from the Bio.AlignIO interface where it is +referred to as the "fasta-m10" file format (as we only support the machine +readable output format selected with the -m 10 command line option). + +This module does NOT cover the generic "fasta" file format originally +developed as an input format to the FASTA tools. The Bio.AlignIO and +Bio.SeqIO both use the Bio.SeqIO.FastaIO module to deal with these files, +which can also be used to store a multiple sequence alignments. +""" + +from Bio.Align import MultipleSeqAlignment +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +def _extract_alignment_region(alignment_seq_with_flanking, annotation): + """Extract alignment region (PRIVATE). + + Helper function for the main parsing code. + + To get the actual pairwise alignment sequences, we must first + translate the un-gapped sequence based coordinates into positions + in the gapped sequence (which may have a flanking region shown + using leading - characters). To date, I have never seen any + trailing flanking region shown in the m10 file, but the + following code should also cope with that. + + Note that this code seems to work fine even when the "sq_offset" + entries are present as a result of using the -X command line option. + """ + align_stripped = alignment_seq_with_flanking.strip("-") + display_start = int(annotation["al_display_start"]) + if int(annotation["al_start"]) <= int(annotation["al_stop"]): + start = int(annotation["al_start"]) - display_start + end = int(annotation["al_stop"]) - display_start + 1 + else: + # FASTA has flipped this sequence... + start = display_start - int(annotation["al_start"]) + end = display_start - int(annotation["al_stop"]) + 1 + + end += align_stripped.count("-") + if start < 0 or start >= end or end > len(align_stripped): + raise ValueError( + "Problem with sequence start/stop,\n%s[%i:%i]\n%s" + % (alignment_seq_with_flanking, start, end, annotation) + ) + return align_stripped[start:end] + + +def FastaM10Iterator(handle, seq_count=None): + """Alignment iterator for the FASTA tool's pairwise alignment output. + + This is for reading the pairwise alignments output by Bill Pearson's + FASTA program when called with the -m 10 command line option for machine + readable output. For more details about the FASTA tools, see the website + http://fasta.bioch.virginia.edu/ and the paper: + + W.R. Pearson & D.J. Lipman PNAS (1988) 85:2444-2448 + + This class is intended to be used via the Bio.AlignIO.parse() function + by specifying the format as "fasta-m10" as shown in the following code:: + + from Bio import AlignIO + handle = ... + for a in AlignIO.parse(handle, "fasta-m10"): + assert len(a) == 2, "Should be pairwise!" + print("Alignment length %i" % a.get_alignment_length()) + for record in a: + print("%s %s %s" % (record.seq, record.name, record.id)) + + Note that this is not a full blown parser for all the information + in the FASTA output - for example, most of the header and all of the + footer is ignored. Also, the alignments are not batched according to + the input queries. + + Also note that there can be up to about 30 letters of flanking region + included in the raw FASTA output as contextual information. This is NOT + part of the alignment itself, and is not included in the resulting + MultipleSeqAlignment objects returned. + """ + state_PREAMBLE = -1 + state_NONE = 0 + state_QUERY_HEADER = 1 + state_ALIGN_HEADER = 2 + state_ALIGN_QUERY = 3 + state_ALIGN_MATCH = 4 + state_ALIGN_CONS = 5 + + def build_hsp(): + if not query_tags and not match_tags: + raise ValueError(f"No data for query {query_id!r}, match {match_id!r}") + assert query_tags, query_tags + assert match_tags, match_tags + evalue = align_tags.get("fa_expect") + tool = global_tags.get("tool", "").upper() + + q = _extract_alignment_region(query_seq, query_tags) + if tool in ["TFASTX"] and len(match_seq) == len(q): + m = match_seq + # Quick hack until I can work out how -, * and / characters + # and the apparent mix of aa and bp coordinates works. + else: + m = _extract_alignment_region(match_seq, match_tags) + if len(q) != len(m): + raise ValueError( + f"""\ +Darn... amino acids vs nucleotide coordinates? +tool: {tool} +query_seq: {query_seq} +query_tags: {query_tags} +{q} length: {len(q)} +match_seq: {match_seq} +match_tags: {match_tags} +{m} length: {len(m)} +handle.name: {handle.name} +""" + ) + + annotations = {} + records = [] + + # Want to record both the query header tags, and the alignment tags. + annotations.update(header_tags) + annotations.update(align_tags) + + # Query + # ===== + record = SeqRecord( + Seq(q), + id=query_id, + name="query", + description=query_descr, + annotations={"original_length": int(query_tags["sq_len"])}, + ) + # TODO - handle start/end coordinates properly. Short term hack for now: + record._al_start = int(query_tags["al_start"]) + record._al_stop = int(query_tags["al_stop"]) + + # TODO - Can FASTA output RNA? + if "sq_type" in query_tags: + if query_tags["sq_type"] == "D": + record.annotations["molecule_type"] = "DNA" + elif query_tags["sq_type"] == "p": + record.annotations["molecule_type"] = "protein" + + records.append(record) + + # Match + # ===== + record = SeqRecord( + Seq(m), + id=match_id, + name="match", + description=match_descr, + annotations={"original_length": int(match_tags["sq_len"])}, + ) + # TODO - handle start/end coordinates properly. Short term hack for now: + record._al_start = int(match_tags["al_start"]) + record._al_stop = int(match_tags["al_stop"]) + + if "sq_type" in match_tags: + if match_tags["sq_type"] == "D": + record.annotations["molecule_type"] = "DNA" + elif match_tags["sq_type"] == "p": + record.annotations["molecule_type"] = "protein" + + records.append(record) + + return MultipleSeqAlignment(records, annotations=annotations) + + state = state_PREAMBLE + query_id = None + match_id = None + query_descr = "" + match_descr = "" + global_tags = {} + header_tags = {} + align_tags = {} + query_tags = {} + match_tags = {} + query_seq = "" + match_seq = "" + cons_seq = "" + for line in handle: + if ">>>" in line and not line.startswith(">>>"): + if query_id and match_id: + # This happens on old FASTA output which lacked an end of + # query >>><<< marker line. + yield build_hsp() + state = state_NONE + query_descr = line[line.find(">>>") + 3 :].strip() + query_id = query_descr.split(None, 1)[0] + match_id = None + header_tags = {} + align_tags = {} + query_tags = {} + match_tags = {} + query_seq = "" + match_seq = "" + cons_seq = "" + elif line.startswith("!! No "): + # e.g. + # !! No library sequences with E() < 0.5 + # or on more recent versions, + # No sequences with E() < 0.05 + assert state == state_NONE + assert not header_tags + assert not align_tags + assert not match_tags + assert not query_tags + assert match_id is None + assert not query_seq + assert not match_seq + assert not cons_seq + query_id = None + elif line.strip() in [">>><<<", ">>>///"]: + # End of query, possible end of all queries + if query_id and match_id: + yield build_hsp() + state = state_NONE + query_id = None + match_id = None + header_tags = {} + align_tags = {} + query_tags = {} + match_tags = {} + query_seq = "" + match_seq = "" + cons_seq = "" + elif line.startswith(">>>"): + # Should be start of a match! + assert query_id is not None + assert line[3:].split(", ", 1)[0] == query_id, line + assert match_id is None + assert not header_tags + assert not align_tags + assert not query_tags + assert not match_tags + assert not match_seq + assert not query_seq + assert not cons_seq + state = state_QUERY_HEADER + elif line.startswith(">>"): + # Should now be at start of a match alignment! + if query_id and match_id: + yield build_hsp() + align_tags = {} + query_tags = {} + match_tags = {} + query_seq = "" + match_seq = "" + cons_seq = "" + match_descr = line[2:].strip() + match_id = match_descr.split(None, 1)[0] + state = state_ALIGN_HEADER + elif line.startswith(">--"): + # End of one HSP + assert query_id and match_id, line + yield build_hsp() + # Clean up read for next HSP + # but reuse header_tags + align_tags = {} + query_tags = {} + match_tags = {} + query_seq = "" + match_seq = "" + cons_seq = "" + state = state_ALIGN_HEADER + elif line.startswith(">"): + if state == state_ALIGN_HEADER: + # Should be start of query alignment seq... + assert query_id is not None, line + assert match_id is not None, line + assert query_id.startswith(line[1:].split(None, 1)[0]), line + state = state_ALIGN_QUERY + elif state == state_ALIGN_QUERY: + # Should be start of match alignment seq + assert query_id is not None, line + assert match_id is not None, line + assert match_id.startswith(line[1:].split(None, 1)[0]), line + state = state_ALIGN_MATCH + elif state == state_NONE: + # Can get > as the last line of a histogram + pass + else: + raise RuntimeError("state %i got %r" % (state, line)) + elif line.startswith("; al_cons"): + assert state == state_ALIGN_MATCH, line + state = state_ALIGN_CONS + # Next line(s) should be consensus seq... + elif line.startswith("; "): + if ": " in line: + key, value = (s.strip() for s in line[2:].split(": ", 1)) + else: + import warnings + + from Bio import BiopythonParserWarning + + # Seen in lalign36, specifically version 36.3.4 Apr, 2011 + # Fixed in version 36.3.5b Oct, 2011(preload8) + warnings.warn( + f"Missing colon in line: {line!r}", BiopythonParserWarning + ) + try: + key, value = (s.strip() for s in line[2:].split(" ", 1)) + except ValueError: + raise ValueError(f"Bad line: {line!r}") from None + if state == state_QUERY_HEADER: + header_tags[key] = value + elif state == state_ALIGN_HEADER: + align_tags[key] = value + elif state == state_ALIGN_QUERY: + query_tags[key] = value + elif state == state_ALIGN_MATCH: + match_tags[key] = value + else: + raise RuntimeError(f"Unexpected state {state!r}, {line!r}") + elif state == state_ALIGN_QUERY: + query_seq += line.strip() + elif state == state_ALIGN_MATCH: + match_seq += line.strip() + elif state == state_ALIGN_CONS: + cons_seq += line.strip("\n") + elif state == state_PREAMBLE: + if line.startswith("#"): + global_tags["command"] = line[1:].strip() + elif line.startswith(" version "): + global_tags["version"] = line[9:].strip() + elif " compares a " in line: + global_tags["tool"] = line[: line.find(" compares a ")].strip() + elif " searches a " in line: + global_tags["tool"] = line[: line.find(" searches a ")].strip() + else: + pass diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/Interfaces.py b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/Interfaces.py new file mode 100644 index 0000000000000000000000000000000000000000..12852405f981d6a42715b2fcc7b8872c5dcd67ff --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/Interfaces.py @@ -0,0 +1,158 @@ +# Copyright 2008-2018 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""AlignIO support module (not for general use). + +Unless you are writing a new parser or writer for Bio.AlignIO, you should not +use this module. It provides base classes to try and simplify things. +""" + + +class AlignmentIterator: + """Base class for building MultipleSeqAlignment iterators. + + You should write a next() method to return Alignment + objects. You may wish to redefine the __init__ + method as well. + """ + + def __init__(self, handle, seq_count=None): + """Create an AlignmentIterator object. + + Arguments: + - handle - input file + - count - optional, expected number of records per alignment + Recommend for fasta file format. + + Note when subclassing: + - there should be a single non-optional argument, the handle, + and optional count IN THAT ORDER. + - you can add additional optional arguments. + + """ + self.handle = handle + self.records_per_alignment = seq_count + ##################################################### + # You may want to subclass this, for example # + # to read through the file to find the first record,# + # or if additional arguments are required. # + ##################################################### + + def __next__(self): + """Return the next alignment in the file. + + This method should be replaced by any derived class to do something + useful. + """ + raise NotImplementedError("This object should be subclassed") + ##################################################### + # You SHOULD subclass this, to split the file up # + # into your individual alignments and convert these # + # into MultipleSeqAlignment objects. # + ##################################################### + + def __iter__(self): + """Iterate over the entries as MultipleSeqAlignment objects. + + Example usage for (concatenated) PHYLIP files:: + + with open("many.phy","r") as myFile: + for alignment in PhylipIterator(myFile): + print("New alignment:") + for record in alignment: + print(record.id) + print(record.seq) + + """ + return iter(self.__next__, None) + + +class AlignmentWriter: + """Base class for building MultipleSeqAlignment writers. + + You should write a write_alignment() method. + You may wish to redefine the __init__ method as well. + """ + + def __init__(self, handle): + """Initialize the class.""" + self.handle = handle + + def write_file(self, alignments): + """Use this to write an entire file containing the given alignments. + + Arguments: + - alignments - A list or iterator returning MultipleSeqAlignment objects + + In general, this method can only be called once per file. + + This method should be replaced by any derived class to do something + useful. It should return the number of alignments.. + """ + raise NotImplementedError("This object should be subclassed") + ##################################################### + # You SHOULD subclass this, to write the alignment # + # objects to the file handle # + ##################################################### + + def clean(self, text): + """Use this to avoid getting newlines in the output.""" + return text.replace("\n", " ").replace("\r", " ") + + +class SequentialAlignmentWriter(AlignmentWriter): + """Base class for building MultipleSeqAlignment writers. + + This assumes each alignment can be simply appended to the file. + You should write a write_alignment() method. + You may wish to redefine the __init__ method as well. + """ + + def __init__(self, handle): + """Initialize the class.""" + self.handle = handle + + def write_file(self, alignments): + """Use this to write an entire file containing the given alignments. + + Arguments: + - alignments - A list or iterator returning MultipleSeqAlignment objects + + In general, this method can only be called once per file. + """ + self.write_header() + count = 0 + for alignment in alignments: + self.write_alignment(alignment) + count += 1 + self.write_footer() + return count + + def write_header(self): + """Use this to write any header. + + This method should be replaced by any derived class to do something + useful. + """ + + def write_footer(self): + """Use this to write any footer. + + This method should be replaced by any derived class to do something + useful. + """ + + def write_alignment(self, alignment): + """Use this to write a single alignment. + + This method should be replaced by any derived class to do something + useful. + """ + raise NotImplementedError("This object should be subclassed") + ##################################################### + # You SHOULD subclass this, to write the alignment # + # objects to the file handle # + ##################################################### diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MafIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MafIO.py new file mode 100644 index 0000000000000000000000000000000000000000..aa2128857feaebfa262916d3c9c20f9f1106cf5b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MafIO.py @@ -0,0 +1,869 @@ +# Copyright 2011, 2012 by Andrew Sczesnak. All rights reserved. +# Revisions Copyright 2011, 2017 by Peter Cock. All rights reserved. +# Revisions Copyright 2014, 2015 by Adam Novak. All rights reserved. +# Revisions Copyright 2015, 2017 by Blaise Li. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.AlignIO support for the "maf" multiple alignment format. + +The Multiple Alignment Format, described by UCSC, stores a series of +multiple alignments in a single file. It is suitable for whole-genome +to whole-genome alignments, metadata such as source chromosome, start +position, size, and strand can be stored. + +See http://genome.ucsc.edu/FAQ/FAQformat.html#format5 + +You are expected to use this module via the Bio.AlignIO functions(or the +Bio.SeqIO functions if you want to work directly with the gapped sequences). + +Coordinates in the MAF format are defined in terms of zero-based start +positions (like Python) and aligning region sizes. + +A minimal aligned region of length one and starting at first position in the +source sequence would have ``start == 0`` and ``size == 1``. + +As we can see on this example, ``start + size`` will give one more than the +zero-based end position. We can therefore manipulate ``start`` and +``start + size`` as python list slice boundaries. + +For an inclusive end coordinate, we need to use ``end = start + size - 1``. +A 1-column wide alignment would have ``start == end``. +""" + +import os +from itertools import islice + +try: + from sqlite3 import dbapi2 +except ImportError: + dbapi2 = None # type: ignore + +from Bio.Align import MultipleSeqAlignment +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import SequentialAlignmentWriter + +MAFINDEX_VERSION = 2 + + +class MafWriter(SequentialAlignmentWriter): + """Accepts a MultipleSeqAlignment object, writes a MAF file.""" + + def write_header(self): + """Write the MAF header.""" + self.handle.write("##maf version=1 scoring=none\n") + self.handle.write("# generated by Biopython\n\n") + + def _write_record(self, record): + """Write a single SeqRecord object to an 's' line in a MAF block (PRIVATE).""" + # convert biopython-style 1/-1 strand to MAF-style +/- strand + if record.annotations.get("strand") == 1: + strand = "+" + elif record.annotations.get("strand") == -1: + strand = "-" + else: + # TODO: issue warning? + strand = "+" + + fields = [ + "s", + # In the MAF file format, spaces are not allowed in the id + "%-40s" % record.id.replace(" ", "_"), + "%15s" % record.annotations.get("start", 0), + "%5s" + % record.annotations.get("size", len(str(record.seq).replace("-", ""))), + strand, + "%15s" % record.annotations.get("srcSize", 0), + str(record.seq), + ] + self.handle.write(f"{' '.join(fields)}\n") + + def write_alignment(self, alignment): + """Write a complete alignment to a MAF block. + + Writes every SeqRecord in a MultipleSeqAlignment object to its own + MAF block (beginning with an 'a' line, containing 's' lines). + """ + if not isinstance(alignment, MultipleSeqAlignment): + raise TypeError("Expected an alignment object") + + if len({len(x) for x in alignment}) > 1: + raise ValueError("Sequences must all be the same length") + + # We allow multiple sequences with the same IDs; for example, there may + # be a MAF aligning the + and - strands of the same sequence together. + + # for now, use ._annotations private property, but restrict keys to those + # specifically supported by the MAF format, according to spec + try: + anno = " ".join( + [ + f"{x}={y}" + for x, y in alignment._annotations.items() + if x in ("score", "pass") + ] + ) + except AttributeError: + anno = "score=0.00" + + self.handle.write(f"a {anno}\n") + + recs_out = 0 + + for record in alignment: + self._write_record(record) + + recs_out += 1 + + self.handle.write("\n") + + return recs_out + + +# Invalid function name according to pylint, but kept for compatibility +# with Bio* conventions. +def MafIterator(handle, seq_count=None): + """Iterate over a MAF file handle as MultipleSeqAlignment objects. + + Iterates over lines in a MAF file-like object (handle), yielding + MultipleSeqAlignment objects. SeqRecord IDs generally correspond to + species names. + """ + in_a_bundle = False + + annotations = [] + records = [] + + while True: + # allows parsing of the last bundle without duplicating code + line = handle.readline() + + try: + # Will be in binary mode if called via the indexing code + # (which needs the raw offsets for cross platform indexing) + line = line.decode("ASCII") + except AttributeError: + pass + + if in_a_bundle: + if line.startswith("s"): + # add a SeqRecord to the bundle + line_split = line.strip().split() + + if len(line_split) != 7: + raise ValueError( + "Error parsing alignment - 's' line must have 7 fields" + ) + + # convert MAF-style +/- strand to biopython-type 1/-1 + if line_split[4] == "+": + strand = 1 + elif line_split[4] == "-": + strand = -1 + else: + # TODO: issue warning, set to 0? + strand = 1 + + # s (literal), src (ID), start, size, strand, srcSize, text (sequence) + anno = { + "start": int(line_split[2]), + "size": int(line_split[3]), + "strand": strand, + "srcSize": int(line_split[5]), + } + + sequence = line_split[6] + + # interpret a dot/period to mean the same as the first sequence + if "." in sequence: + if not records: + raise ValueError( + "Found dot/period in first sequence of alignment" + ) + + ref = records[0].seq + new = [] + + for letter, ref_letter in zip(sequence, ref): + new.append(ref_letter if letter == "." else letter) + + sequence = "".join(new) + + records.append( + SeqRecord( + Seq(sequence), + id=line_split[1], + name=line_split[1], + description="", + annotations=anno, + ) + ) + elif line.startswith("i"): + # TODO: information about what is in the aligned species DNA before + # and after the immediately preceding "s" line + pass + elif line.startswith("e"): + # TODO: information about the size of the gap between the alignments + # that span the current block + pass + elif line.startswith("q"): + # TODO: quality of each aligned base for the species. + # Need to find documentation on this, looks like ASCII 0-9 or gap? + # Can then store in each SeqRecord's .letter_annotations dictionary, + # perhaps as the raw string or turned into integers / None for gap? + pass + elif line.startswith("#"): + # ignore comments + # (not sure whether comments + # are in the maf specification, though) + pass + elif not line.strip(): + # end a bundle of records + if seq_count is not None: + assert len(records) == seq_count + + alignment = MultipleSeqAlignment(records) + # TODO - Introduce an annotated alignment class? + # See also Bio/AlignIO/FastaIO.py for same requirement. + # For now, store the annotation a new private property: + alignment._annotations = annotations + + yield alignment + + in_a_bundle = False + + annotations = [] + records = [] + else: + raise ValueError(f"Error parsing alignment - unexpected line:\n{line}") + elif line.startswith("a"): + # start a bundle of records + in_a_bundle = True + annot_strings = line.strip().split()[1:] + if len(annot_strings) != line.count("="): + raise ValueError("Error parsing alignment - invalid key in 'a' line") + annotations = dict(a_string.split("=") for a_string in annot_strings) + elif line.startswith("#"): + # ignore comments + pass + elif not line: + break + + +class MafIndex: + """Index for a MAF file. + + The index is a sqlite3 database that is built upon creation of the object + if necessary, and queried when methods *search* or *get_spliced* are + used. + """ + + def __init__(self, sqlite_file, maf_file, target_seqname): + """Indexes or loads the index of a MAF file.""" + if dbapi2 is None: + # Python was compiled without sqlite3 support + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Python was compiled without the sqlite3 module" + ) + + self._target_seqname = target_seqname + # example: Tests/MAF/ucsc_mm9_chr10.mafindex + self._index_filename = sqlite_file + # example: /home/bli/src/biopython/Tests/MAF + self._relative_path = os.path.abspath(os.path.dirname(sqlite_file)) + # example: Tests/MAF/ucsc_mm9_chr10.maf + self._maf_file = maf_file + + # Opening in bytes mode as want real offsets, not where + # Python attempts to hide cross-platform newline differences etc + self._maf_fp = open(self._maf_file, "rb") + + # if sqlite_file exists, use the existing db, otherwise index the file + if os.path.isfile(sqlite_file): + self._con = dbapi2.connect(sqlite_file) + try: + self._record_count = self.__check_existing_db() + except ValueError as err: + self._maf_fp.close() + self._con.close() + raise err from None + else: + self._con = dbapi2.connect(sqlite_file) + try: + self._record_count = self.__make_new_index() + except ValueError as err: + self._maf_fp.close() + self._con.close() + raise err from None + + # lastly, setup a MafIterator pointing at the open maf_file + self._mafiter = MafIterator(self._maf_fp) + + def close(self): + """Close the file handle being used to read the data. + + Once called, further use of the index won't work. The sole + purpose of this method is to allow explicit handle closure + - for example if you wish to delete the file, on Windows + you must first close all open handles to that file. + """ + self._con.close() + self._record_count = 0 + + def __check_existing_db(self): + """Perform basic sanity checks upon loading an existing index (PRIVATE).""" + try: + idx_version = int( + self._con.execute( + "SELECT value FROM meta_data WHERE key = 'version'" + ).fetchone()[0] + ) + if idx_version != MAFINDEX_VERSION: + msg = "\n".join( + [ + "Index version (%s) incompatible with this version " + "of MafIndex" % idx_version, + "You might erase the existing index %s " + "for it to be rebuilt." % self._index_filename, + ] + ) + raise ValueError(msg) + + filename = self._con.execute( + "SELECT value FROM meta_data WHERE key = 'filename'" + ).fetchone()[0] + # Compute absolute path of the original maf file + if os.path.isabs(filename): + # It was already stored as absolute + tmp_mafpath = filename + else: + # It should otherwise have been stored as relative to the index + # Would be stored with Unix / path separator, so convert + # it to the local OS path separator here: + tmp_mafpath = os.path.join( + self._relative_path, filename.replace("/", os.path.sep) + ) + if tmp_mafpath != os.path.abspath(self._maf_file): + # Original and given absolute paths differ. + raise ValueError( + f"Index uses a different file ({filename} != {self._maf_file})" + ) + + db_target = self._con.execute( + "SELECT value FROM meta_data WHERE key = 'target_seqname'" + ).fetchone()[0] + if db_target != self._target_seqname: + raise ValueError( + "Provided database indexed for %s, expected %s" + % (db_target, self._target_seqname) + ) + + record_count = int( + self._con.execute( + "SELECT value FROM meta_data WHERE key = 'record_count'" + ).fetchone()[0] + ) + if record_count == -1: + raise ValueError("Unfinished/partial database provided") + + records_found = int( + self._con.execute("SELECT COUNT(*) FROM offset_data").fetchone()[0] + ) + if records_found != record_count: + raise ValueError( + "Expected %s records, found %s. Corrupt index?" + % (record_count, records_found) + ) + + return records_found + + except (dbapi2.OperationalError, dbapi2.DatabaseError) as err: + raise ValueError(f"Problem with SQLite database: {err}") from None + + def __make_new_index(self): + """Read MAF file and generate SQLite index (PRIVATE).""" + # make the tables + self._con.execute("CREATE TABLE meta_data (key TEXT, value TEXT);") + self._con.execute( + "INSERT INTO meta_data (key, value) VALUES (?, ?);", + ("version", MAFINDEX_VERSION), + ) + self._con.execute( + "INSERT INTO meta_data (key, value) VALUES ('record_count', -1);" + ) + self._con.execute( + "INSERT INTO meta_data (key, value) VALUES (?, ?);", + ("target_seqname", self._target_seqname), + ) + # Determine whether to store maf file as relative to the index or absolute + # See https://github.com/biopython/biopython/pull/381 + if not os.path.isabs(self._maf_file) and not os.path.isabs( + self._index_filename + ): + # Since the user gave both maf file and index as relative paths, + # we will store the maf file relative to the index. + # Note for cross platform use (e.g. shared drive over SAMBA), + # convert any Windows slash into Unix style for rel paths. + # example: ucsc_mm9_chr10.maf + mafpath = os.path.relpath(self._maf_file, self._relative_path).replace( + os.path.sep, "/" + ) + elif ( + os.path.dirname(os.path.abspath(self._maf_file)) + os.path.sep + ).startswith(self._relative_path + os.path.sep): + # Since maf file is in same directory or sub directory, + # might as well make this into a relative path: + mafpath = os.path.relpath(self._maf_file, self._relative_path).replace( + os.path.sep, "/" + ) + else: + # Default to storing as an absolute path + # example: /home/bli/src/biopython/Tests/MAF/ucsc_mm9_chr10.maf + mafpath = os.path.abspath(self._maf_file) + self._con.execute( + "INSERT INTO meta_data (key, value) VALUES (?, ?);", + ("filename", mafpath), + ) + self._con.execute( + "CREATE TABLE offset_data (bin INTEGER, start INTEGER, end INTEGER, offset INTEGER);" + ) + + insert_count = 0 + + # iterate over the entire file and insert in batches + mafindex_func = self.__maf_indexer() + + while True: + batch = list(islice(mafindex_func, 100)) + if not batch: + break + + # batch is made from self.__maf_indexer(), + # which yields zero-based "inclusive" start and end coordinates + self._con.executemany( + "INSERT INTO offset_data (bin, start, end, offset) VALUES (?,?,?,?);", + batch, + ) + self._con.commit() + insert_count += len(batch) + + # then make indexes on the relevant fields + self._con.execute("CREATE INDEX IF NOT EXISTS bin_index ON offset_data(bin);") + self._con.execute( + "CREATE INDEX IF NOT EXISTS start_index ON offset_data(start);" + ) + self._con.execute("CREATE INDEX IF NOT EXISTS end_index ON offset_data(end);") + + self._con.execute( + f"UPDATE meta_data SET value = '{insert_count}' WHERE key = 'record_count'" + ) + + self._con.commit() + + return insert_count + + def __maf_indexer(self): + """Return index information for each bundle (PRIVATE). + + Yields index information for each bundle in the form of + (bin, start, end, offset) tuples where start and end are + 0-based inclusive coordinates. + """ + line = self._maf_fp.readline() + + while line: + if line.startswith(b"a"): + # note the offset + offset = self._maf_fp.tell() - len(line) + + # search the following lines for a match to target_seqname + while True: + line = self._maf_fp.readline() + + if not line.strip() or line.startswith(b"a"): + # Empty line or new alignment record + raise ValueError( + "Target for indexing (%s) not found in this bundle" + % (self._target_seqname,) + ) + elif line.startswith(b"s"): + # s (literal), src (ID), start, size, strand, srcSize, text (sequence) + line_split = line.decode("ASCII").strip().split() + + if line_split[1] == self._target_seqname: + start = int(line_split[2]) + size = int(line_split[3]) + if size != len(line_split[6].replace("-", "")): + raise ValueError( + "Invalid length for target coordinates " + "(expected %s, found %s)" + % (size, len(line_split[6].replace("-", ""))) + ) + + # "inclusive" end position is start + length - 1 + end = start + size - 1 + + # _ucscbin takes end-exclusive coordinates + yield (self._ucscbin(start, end + 1), start, end, offset) + + break + + line = self._maf_fp.readline() + + # TODO: check coordinate correctness for the two bin-related static methods + @staticmethod + def _region2bin(start, end): + """Find bins that a region may belong to (PRIVATE). + + Converts a region to a list of bins that it may belong to, including largest + and smallest bins. + """ + bins = [0, 1] + + bins.extend(range(1 + (start >> 26), 2 + ((end - 1) >> 26))) + bins.extend(range(9 + (start >> 23), 10 + ((end - 1) >> 23))) + bins.extend(range(73 + (start >> 20), 74 + ((end - 1) >> 20))) + bins.extend(range(585 + (start >> 17), 586 + ((end - 1) >> 17))) + + return set(bins) + + @staticmethod + def _ucscbin(start, end): + """Return the smallest bin a given region will fit into (PRIVATE). + + Adapted from http://genomewiki.ucsc.edu/index.php/Bin_indexing_system + """ + bin_offsets = [512 + 64 + 8 + 1, 64 + 8 + 1, 8 + 1, 1, 0] + + _bin_first_shift = 17 + _bin_next_shift = 3 + + start_bin = start + end_bin = end - 1 + + start_bin >>= _bin_first_shift + end_bin >>= _bin_first_shift + + for bin_offset in bin_offsets: + if start_bin == end_bin: + return bin_offset + start_bin + start_bin >>= _bin_next_shift + end_bin >>= _bin_next_shift + + return 0 + + def _get_record(self, offset): + """Retrieve a single MAF record located at the offset provided (PRIVATE).""" + self._maf_fp.seek(offset) + return next(self._mafiter) + + def search(self, starts, ends): + """Search index database for MAF records overlapping ranges provided. + + Returns *MultipleSeqAlignment* results in order by start, then end, then + internal offset field. + + *starts* should be a list of 0-based start coordinates of segments in the reference. + *ends* should be the list of the corresponding segment ends + (in the half-open UCSC convention: + http://genome.ucsc.edu/blog/the-ucsc-genome-browser-coordinate-counting-systems/). + """ + # verify the provided exon coordinates + if len(starts) != len(ends): + raise ValueError("Every position in starts must have a match in ends") + + # Could it be safer to sort the (exonstart, exonend) pairs? + for exonstart, exonend in zip(starts, ends): + exonlen = exonend - exonstart + if exonlen < 1: + raise ValueError( + "Exon coordinates (%d, %d) invalid: exon length (%d) < 1" + % (exonstart, exonend, exonlen) + ) + con = self._con + + # Keep track of what blocks have already been yielded + # in order to avoid duplicating them + # (see https://github.com/biopython/biopython/issues/1083) + yielded_rec_coords = set() + # search for every exon + for exonstart, exonend in zip(starts, ends): + try: + possible_bins = ", ".join( + map(str, self._region2bin(exonstart, exonend)) + ) + except TypeError: + raise TypeError( + "Exon coordinates must be integers " + "(start=%d, end=%d)" % (exonstart, exonend) + ) from None + + # https://www.sqlite.org/lang_expr.html + # ----- + # The BETWEEN operator + # + # The BETWEEN operator is logically equivalent to a pair of + # comparisons. "x BETWEEN y AND z" is equivalent to "x>=y AND x<=z" + # except that with BETWEEN, the x expression is only evaluated + # once. The precedence of the BETWEEN operator is the same as the + # precedence as operators == and != and LIKE and groups left to + # right. + # ----- + + # We are testing overlap between the query segment and records in + # the index, using non-strict coordinates comparisons. + # The query segment end must be passed as end-inclusive + # The index should also have been build with end-inclusive + # end coordinates. + # See https://github.com/biopython/biopython/pull/1086#issuecomment-285069073 + + result = con.execute( + "SELECT DISTINCT start, end, offset FROM offset_data " + "WHERE bin IN (%s) " + "AND (end BETWEEN %s AND %s OR %s BETWEEN start AND end) " + "ORDER BY start, end, offset ASC;" + % (possible_bins, exonstart, exonend - 1, exonend - 1) + ) + + rows = result.fetchall() + + # rows come from the sqlite index, + # which should have been written using __make_new_index, + # so rec_start and rec_end should be zero-based "inclusive" coordinates + for rec_start, rec_end, offset in rows: + # Avoid yielding multiple time the same block + if (rec_start, rec_end) in yielded_rec_coords: + continue + else: + yielded_rec_coords.add((rec_start, rec_end)) + # Iterate through hits, fetching alignments from the MAF file + # and checking to be sure we've retrieved the expected record. + + fetched = self._get_record(int(offset)) + + for record in fetched: + if record.id == self._target_seqname: + # start and size come from the maf lines + start = record.annotations["start"] + # "inclusive" end is start + length - 1 + end = start + record.annotations["size"] - 1 + + if not (start == rec_start and end == rec_end): + raise ValueError( + "Expected %s-%s @ offset %s, found %s-%s" + % (rec_start, rec_end, offset, start, end) + ) + + yield fetched + + def get_spliced(self, starts, ends, strand=1): + """Return a multiple alignment of the exact sequence range provided. + + Accepts two lists of start and end positions on target_seqname, representing + exons to be spliced in silico. Returns a *MultipleSeqAlignment* of the + desired sequences spliced together. + + *starts* should be a list of 0-based start coordinates of segments in the reference. + *ends* should be the list of the corresponding segment ends + (in the half-open UCSC convention: + http://genome.ucsc.edu/blog/the-ucsc-genome-browser-coordinate-counting-systems/). + + To ask for the alignment portion corresponding to the first 100 + nucleotides of the reference sequence, you would use + ``search([0], [100])`` + """ + # validate strand + if strand not in (1, -1): + raise ValueError(f"Strand must be 1 or -1, got {strand}") + + # pull all alignments that span the desired intervals + fetched = list(self.search(starts, ends)) + + # keep track of the expected letter count + # (sum of lengths of [start, end) segments, + # where [start, end) half-open) + expected_letters = sum(end - start for start, end in zip(starts, ends)) + + # if there's no alignment, return filler for the assembly of the length given + if len(fetched) == 0: + return MultipleSeqAlignment( + [SeqRecord(Seq("N" * expected_letters), id=self._target_seqname)] + ) + + # find the union of all IDs in these alignments + all_seqnames = {sequence.id for multiseq in fetched for sequence in multiseq} + + # split every record by base position + # key: sequence name + # value: dictionary + # key: position in the reference sequence + # value: letter(s) (including letters + # aligned to the "-" preceding the letter + # at the position in the reference, if any) + split_by_position = {seq_name: {} for seq_name in all_seqnames} + + # keep track of what the total number of (unspliced) letters should be + total_rec_length = 0 + + # track first strand encountered on the target seqname + ref_first_strand = None + + for multiseq in fetched: + # find the target_seqname in this MultipleSeqAlignment and use it to + # set the parameters for the rest of this iteration + for seqrec in multiseq: + if seqrec.id == self._target_seqname: + try: + if ref_first_strand is None: + ref_first_strand = seqrec.annotations["strand"] + + if ref_first_strand not in (1, -1): + raise ValueError("Strand must be 1 or -1") + elif ref_first_strand != seqrec.annotations["strand"]: + raise ValueError( + "Encountered strand='%s' on target seqname, " + "expected '%s'" + % (seqrec.annotations["strand"], ref_first_strand) + ) + except KeyError: + raise ValueError( + "No strand information for target seqname (%s)" + % self._target_seqname + ) from None + # length including gaps (i.e. alignment length) + rec_length = len(seqrec) + rec_start = seqrec.annotations["start"] + ungapped_length = seqrec.annotations["size"] + # inclusive end in zero-based coordinates of the reference + rec_end = rec_start + ungapped_length - 1 + # This is length in terms of actual letters in the reference + total_rec_length += ungapped_length + + # blank out these positions for every seqname + for seqrec in multiseq: + for pos in range(rec_start, rec_end + 1): + split_by_position[seqrec.id][pos] = "" + + break + # http://psung.blogspot.fr/2007/12/for-else-in-python.html + # https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops + else: + raise ValueError( + f"Did not find {self._target_seqname} in alignment bundle" + ) + + # the true, chromosome/contig/etc position in the target seqname + real_pos = rec_start + + # loop over the alignment to fill split_by_position + for gapped_pos in range(rec_length): + for seqrec in multiseq: + # keep track of this position's value for the target seqname + if seqrec.id == self._target_seqname: + track_val = seqrec.seq[gapped_pos] + + # Here, a real_pos that corresponds to just after a series of "-" + # in the reference will "accumulate" the letters found in other sequences + # in front of the "-"s + split_by_position[seqrec.id][real_pos] += seqrec.seq[gapped_pos] + + # increment the real_pos counter only when non-gaps are found in + # the target_seqname, and we haven't reached the end of the record + if track_val != "-" and real_pos < rec_end: + real_pos += 1 + + # make sure the number of bp entries equals the sum of the record lengths + if len(split_by_position[self._target_seqname]) != total_rec_length: + raise ValueError( + "Target seqname (%s) has %s records, expected %s" + % ( + self._target_seqname, + len(split_by_position[self._target_seqname]), + total_rec_length, + ) + ) + + # translates a position in the target_seqname sequence to its gapped length + realpos_to_len = { + pos: len(gapped_fragment) + for pos, gapped_fragment in split_by_position[self._target_seqname].items() + if len(gapped_fragment) > 1 + } + + # splice together the exons + subseq = {} + + for seqid in all_seqnames: + seq_split = split_by_position[seqid] + seq_splice = [] + + filler_char = "N" if seqid == self._target_seqname else "-" + + # iterate from start to end, taking bases from split_by_position when + # they exist, using N or - for gaps when there is no alignment. + append = seq_splice.append + + for exonstart, exonend in zip(starts, ends): + # exonend is exclusive + for real_pos in range(exonstart, exonend): + # if this seqname has this position, add it + if real_pos in seq_split: + append(seq_split[real_pos]) + # if not, but it's in the target_seqname, add length-matched filler + elif real_pos in realpos_to_len: + append(filler_char * realpos_to_len[real_pos]) + # it's not in either, so add a single filler character + else: + append(filler_char) + + subseq[seqid] = "".join(seq_splice) + + # make sure we're returning the right number of letters + if len(subseq[self._target_seqname].replace("-", "")) != expected_letters: + raise ValueError( + "Returning %s letters for target seqname (%s), expected %s" + % ( + len(subseq[self._target_seqname].replace("-", "")), + self._target_seqname, + expected_letters, + ) + ) + + # check to make sure all sequences are the same length as the target seqname + ref_subseq_len = len(subseq[self._target_seqname]) + + for seqid, seq in subseq.items(): + if len(seq) != ref_subseq_len: + raise ValueError( + "Returning length %s for %s, expected %s" + % (len(seq), seqid, ref_subseq_len) + ) + + # finally, build a MultipleSeqAlignment object for our final sequences + result_multiseq = [] + + for seqid, seq in subseq.items(): + seq = Seq(seq) + + seq = seq if strand == ref_first_strand else seq.reverse_complement() + + result_multiseq.append(SeqRecord(seq, id=seqid, name=seqid, description="")) + + return MultipleSeqAlignment(result_multiseq) + + def __repr__(self): + """Return a string representation of the index.""" + return "MafIO.MafIndex(%r, target_seqname=%r)" % ( + self._maf_fp.name, + self._target_seqname, + ) + + def __len__(self): + """Return the number of records in the index.""" + return self._record_count diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MauveIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MauveIO.py new file mode 100644 index 0000000000000000000000000000000000000000..478a268effbfc249b6df48e6dc641a5c862046d4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MauveIO.py @@ -0,0 +1,343 @@ +# Copyright 2015-2015 by Eric Rasche. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.AlignIO support for "xmfa" output from Mauve/ProgressiveMauve. + +You are expected to use this module via the Bio.AlignIO functions (or the +Bio.SeqIO functions if you want to work directly with the gapped sequences). + +For example, consider a progressiveMauve alignment file containing the following:: + + #FormatVersion Mauve1 + #Sequence1File a.fa + #Sequence1Entry 1 + #Sequence1Format FastA + #Sequence2File b.fa + #Sequence2Entry 2 + #Sequence2Format FastA + #Sequence3File c.fa + #Sequence3Entry 3 + #Sequence3Format FastA + #BackboneFile three.xmfa.bbcols + > 1:0-0 + a.fa + -------------------------------------------------------------------------------- + -------------------------------------------------------------------------------- + -------------------------------------------------------------------------------- + > 2:5417-5968 + b.fa + TTTAAACATCCCTCGGCCCGTCGCCCTTTTATAATAGCAGTACGTGAGAGGAGCGCCCTAAGCTTTGGGAAATTCAAGC- + -------------------------------------------------------------------------------- + CTGGAACGTACTTGCTGGTTTCGCTACTATTTCAAACAAGTTAGAGGCCGTTACCTCGGGCGAACGTATAAACCATTCTG + > 3:9476-10076 - c.fa + TTTAAACACCTTTTTGGATG--GCCCAGTTCGTTCAGTTGTG-GGGAGGAGATCGCCCCAAACGTATGGTGAGTCGGGCG + TTTCCTATAGCTATAGGACCAATCCACTTACCATACGCCCGGCGTCGCCCAGTCCGGTTCGGTACCCTCCATGACCCACG + ---------------------------------------------------------AAATGAGGGCCCAGGGTATGCTT + = + > 2:5969-6015 + b.fa + ----------------------- + GGGCGAACGTATAAACCATTCTG + > 3:9429-9476 - c.fa + TTCGGTACCCTCCATGACCCACG + AAATGAGGGCCCAGGGTATGCTT + +This is a multiple sequence alignment with multiple aligned sections, so you +would probably load this using the Bio.AlignIO.parse() function: + + >>> from Bio import AlignIO + >>> align = AlignIO.parse("Mauve/simple_short.xmfa", "mauve") + >>> alignments = list(align) + >>> for aln in alignments: + ... print(aln) + ... + Alignment with 3 rows and 240 columns + --------------------------------------------...--- a.fa + TTTAAACATCCCTCGGCCCGTCGCCCTTTTATAATAGCAGTACG...CTG b.fa/5416-5968 + TTTAAACACCTTTTTGGATG--GCCCAGTTCGTTCAGTTGTG-G...CTT c.fa/9475-10076 + Alignment with 2 rows and 46 columns + -----------------------GGGCGAACGTATAAACCATTCTG b.fa/5968-6015 + TTCGGTACCCTCCATGACCCACGAAATGAGGGCCCAGGGTATGCTT c.fa/9428-9476 + +Additional information is extracted from the XMFA file and available through +the annotation attribute of each record:: + + >>> for record in alignments[0]: + ... print(record.id, len(record)) + ... print(" start: %d, end: %d, strand: %d" %( + ... record.annotations['start'], record.annotations['end'], + ... record.annotations['strand'])) + ... + a.fa 240 + start: 0, end: 0, strand: 1 + b.fa/5416-5968 240 + start: 5416, end: 5968, strand: 1 + c.fa/9475-10076 240 + start: 9475, end: 10076, strand: -1 + +""" + +import re + +from Bio.Align import MultipleSeqAlignment +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import AlignmentIterator +from .Interfaces import SequentialAlignmentWriter + +XMFA_HEADER_REGEX = re.compile( + r"> (?P\d+):(?P\d+)-(?P\d+) (?P[+-]) (?P.*)" +) +XMFA_HEADER_REGEX_BIOPYTHON = re.compile( + r"> (?P\d+):(?P\d+)-(?P\d+) (?P[+-]) (?P[^#]*) # (?P.*)" +) +ID_LINE_FMT = "> {seq_name}:{start}-{end} {strand} {filename} # {ugly_hack}" + + +def _identifier_split(identifier): + """Return (name, start, end) string tuple from an identifier (PRIVATE).""" + id, loc, strand = identifier.split(":") + start, end = map(int, loc.split("-")) + start -= 1 + return id, start, end, strand + + +class MauveWriter(SequentialAlignmentWriter): + """Mauve/XMFA alignment writer.""" + + def __init__(self, *args, **kwargs): + """Initialize the class.""" + super().__init__(*args, **kwargs) + self._wrote_header = False + self._wrote_first = False + + def write_alignment(self, alignment): + """Use this to write (another) single alignment to an open file. + + Note that sequences and their annotation are recorded + together (rather than having a block of annotation followed + by a block of aligned sequences). + """ + count = len(alignment) + + self._length_of_sequences = alignment.get_alignment_length() + + # NOTE - For now, the alignment object does not hold any per column + # or per alignment annotation - only per sequence. + + if count == 0: + raise ValueError("Must have at least one sequence") + if self._length_of_sequences == 0: + raise ValueError("Non-empty sequences are required") + + if not self._wrote_header: + self._wrote_header = True + self.handle.write("#FormatVersion Mauve1\n") + # There are some more headers, but we ignore those for now. + # Sequence1File unknown.fa + # Sequence1Entry 1 + # Sequence1Format FastA + for i in range(1, count + 1): + self.handle.write(f"#Sequence{i}Entry\t{i}\n") + + for idx, record in enumerate(alignment): + self._write_record(record, record_idx=idx) + self.handle.write("=\n") + + def _write_record(self, record, record_idx=0): + """Write a single SeqRecord to the file (PRIVATE).""" + if self._length_of_sequences != len(record.seq): + raise ValueError("Sequences must all be the same length") + + seq_name = record.name + try: + seq_name = str(int(record.name)) + except ValueError: + seq_name = str(record_idx + 1) + + # We remove the "/{start}-{end}" before writing, as it cannot be part + # of the produced XMFA file. + if "start" in record.annotations and "end" in record.annotations: + suffix0 = f"/{record.annotations['start']}-{record.annotations['end']}" + suffix1 = f"/{record.annotations['start'] + 1}-{record.annotations['end']}" + if seq_name[-len(suffix0) :] == suffix0: + seq_name = seq_name[: -len(suffix0)] + if seq_name[-len(suffix1) :] == suffix1: + seq_name = seq_name[: -len(suffix1)] + + if ( + "start" in record.annotations + and "end" in record.annotations + and "strand" in record.annotations + ): + id_line = ID_LINE_FMT.format( + seq_name=seq_name, + start=record.annotations["start"] + 1, + end=record.annotations["end"], + strand=("+" if record.annotations["strand"] == 1 else "-"), + filename=record.name + ".fa", + ugly_hack=record.id, + ) + lacking_annotations = False + else: + id_line = ID_LINE_FMT.format( + seq_name=seq_name, + start=0, + end=0, + strand="+", + filename=record.name + ".fa", + ugly_hack=record.id, + ) + lacking_annotations = True + + # If the sequence is an empty one, skip writing it out + if (":0-0 " in id_line or ":1-0 " in id_line) and not lacking_annotations: + # Except in the first LCB + if not self._wrote_first: + self._wrote_first = True + # The first LCB we write out is special, and must list ALL + # sequences, for the Mauve GUI + # http://darlinglab.org/mauve/user-guide/files.html#non-standard-xmfa-formatting-used-by-the-mauve-gui + id_line = ID_LINE_FMT.format( + seq_name=seq_name, + start=0, + end=0, + strand="+", + filename=record.name + ".fa", + ugly_hack=record.id, + ) + id_line = id_line.replace("\n", " ").replace("\r", " ") + self.handle.write(id_line + "\n\n") + # Alignments lacking a start/stop/strand were generated by + # Biopython on load, and shouldn't exist according to XMFA + else: + # In other blocks, we only write sequences if they exist in a given + # alignment. + id_line = id_line.replace("\n", " ").replace("\r", " ") + self.handle.write(id_line + "\n") + for i in range(0, len(record.seq), 80): + self.handle.write(f"{record.seq[i : i + 80]}\n") + + +class MauveIterator(AlignmentIterator): + """Mauve xmfa alignment iterator.""" + + _ids: list[str] = [] # for caching IDs between __next__ calls + + def __next__(self): + """Parse the next alignment from the handle.""" + handle = self.handle + line = handle.readline() + + if not line: + raise StopIteration + + # Strip out header comments + while line and line.strip().startswith("#"): + line = handle.readline() + + seqs = {} + seq_regions = {} + passed_end_alignment = False + + latest_id = None + while True: + if not line: + break # end of file + line = line.strip() + + if line.startswith("="): + # There may be more data, but we've reached the end of this + # alignment + break + elif line.startswith(">"): + m = XMFA_HEADER_REGEX_BIOPYTHON.match(line) + if not m: + m = XMFA_HEADER_REGEX.match(line) + if not m: + raise ValueError("Malformed header line: %s", line) + + parsed_id = m.group("id") + parsed_data = {} + for key in ("start", "end", "id", "strand", "name", "realname"): + try: + value = m.group(key) + if key == "start": + value = int(value) + # Convert to zero based counting + if value > 0: + value -= 1 + + if key == "end": + value = int(value) + parsed_data[key] = value + except IndexError: + # This will occur if we're asking for a group that + # doesn't exist. It's fine. + pass + seq_regions[parsed_id] = parsed_data + + if parsed_id not in self._ids: + self._ids.append(parsed_id) + + seqs.setdefault(parsed_id, "") + latest_id = parsed_id + else: + assert not passed_end_alignment + if latest_id is None: + raise ValueError("Saw sequence before definition line") + seqs[latest_id] += line + line = handle.readline() + + assert len(seqs) <= len(self._ids) + + self.ids = self._ids + self.sequences = seqs + + if self._ids and seqs: + alignment_length = max(map(len, list(seqs.values()))) + records = [] + for id in self._ids: + if id not in seqs or len(seqs[id]) == 0 or len(seqs[id]) == 0: + seq = "-" * alignment_length + else: + seq = seqs[id] + + if alignment_length != len(seq): + raise ValueError( + "Sequences have different lengths, or repeated identifier" + ) + + # Sometimes we don't see a particular sequence in the + # alignment, so we skip that record since it isn't present in + # that LCB/alignment + if id not in seq_regions: + continue + + if seq_regions[id]["start"] != 0 or seq_regions[id]["end"] != 0: + suffix = "/{start}-{end}".format(**seq_regions[id]) + if "realname" in seq_regions[id]: + corrected_id = seq_regions[id]["realname"] + else: + corrected_id = seq_regions[id]["name"] + if corrected_id.count(suffix) == 0: + corrected_id += suffix + else: + if "realname" in seq_regions[id]: + corrected_id = seq_regions[id]["realname"] + else: + corrected_id = seq_regions[id]["name"] + + record = SeqRecord(Seq(seq), id=corrected_id, name=id) + + record.annotations["start"] = seq_regions[id]["start"] + record.annotations["end"] = seq_regions[id]["end"] + record.annotations["strand"] = ( + 1 if seq_regions[id]["strand"] == "+" else -1 + ) + + records.append(record) + return MultipleSeqAlignment(records) + else: + raise StopIteration diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MsfIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MsfIO.py new file mode 100644 index 0000000000000000000000000000000000000000..a171d5da8cc90a6599e5c7a0f6a17c79fdd143bd --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/MsfIO.py @@ -0,0 +1,333 @@ +# Copyright 2019, National Marrow Donor Program (NMPD). All rights reserved. +# Written by Peter Cock, The James Hutton Institute, under contract to NMDP. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.AlignIO support for GCG MSF format. + +The file format was produced by the GCG PileUp and and LocalPileUp tools, +and later tools such as T-COFFEE and MUSCLE support it as an optional +output format. + +The original GCG tool would write gaps at ends of each sequence which could +be missing data as tildes (``~``), whereas internal gaps were periods (``.``) +instead. This parser replaces both with minus signs (``-``) for consistency +with the rest of ``Bio.AlignIO``. + +You are expected to use this module via the Bio.AlignIO functions (or the +Bio.SeqIO functions if you want to work directly with the gapped sequences). +""" + +from Bio.Align import MultipleSeqAlignment +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import AlignmentIterator + + +class MsfIterator(AlignmentIterator): + """GCG MSF alignment iterator.""" + + _header = None # for caching lines between __next__ calls + + def __next__(self): + """Parse the next alignment from the handle.""" + handle = self.handle + + if self._header is None: + line = handle.readline() + else: + # Header we saved from when we were parsing + # the previous alignment. + line = self._header + self._header = None + + if not line: + raise StopIteration + + # Whitelisted headers we know about. + known_headers = ["!!NA_MULTIPLE_ALIGNMENT", "!!AA_MULTIPLE_ALIGNMENT", "PileUp"] + # Examples in "Molecular Biology Software Training Manual GCG version 10" + # by BBSRC Bioscuences IT Services (BITS), Harpenden, UK, Copyright 1996-2001 + # would often start as follows: + # + # !!AA_MUTIPLE_ALIGNMENT 1.0 + # PileUp of: @/usr/users2/culhane/... + # + # etc with other seemingly free format text before getting to the + # MSF/Type/Check line and the following Name: lines block and // line. + # + # MUSCLE just has a line "PileUp", while other sources just use the line + # "!!AA_MULTIPLE_ALIGNMENT" (amino acid) or "!!NA_MULTIPLE_ALIGNMENT" + # (nucleotide). + if line.strip().split()[0] not in known_headers: + raise ValueError( + "%s is not a known GCG MSF header: %s" + % (line.strip().split()[0], ", ".join(known_headers)) + ) + + while line and " MSF: " not in line: + line = handle.readline() + + if not line: + raise ValueError("Reached end of file without MSF/Type/Check header line") + + # Quoting from "Molecular Biology Software Training Manual GCG version 10" + # by BBSRC Bioscuences IT Services (BITS), Harpenden, UK. Copyright 1996-2001. + # Page 31: + # + # "Header information is before a .. (double dot) in a GCG format file. + # The file will also have a checksum specific for that file." + # + # This was followed by a single non-aligned sequence, but this convention + # appears to also be used in the GCG MSF files. Quoting other examples in + # this reference, page 31: + # + # localpileup_17.msf MSF: 195 Type: P January 6, 2000 15:41 Check: 4365 .. + # + # Except from page 148: + # + # localpileup_106.msf MSF: 457 Type: P November 28, 2000 16:09 Check: 2396 .. + # + # Quoting output from MUSCLE v3.8, have two leading spaces and a zero checksum: + # + # MSF: 689 Type: N Check: 0000 .. + # + # By observation, the MSF value is the column count, type is N (nucleotide) + # or P (protein / amino acid). + # + # In a possible bug, EMBOSS v6.6.0.0 uses CompCheck: rather than Check: as shown, + # + # $ seqret -sequence Tests/Fasta/f002 -auto -stdout -osformat msf + # !!NA_MULTIPLE_ALIGNMENT 1.0 + # + # stdout MSF: 633 Type: N 01/08/19 CompCheck: 8543 .. + # + # Name: G26680 Len: 633 Check: 4334 Weight: 1.00 + # Name: G26685 Len: 633 Check: 3818 Weight: 1.00 + # Name: G29385 Len: 633 Check: 391 Weight: 1.00 + # + # // + # + parts = line.strip("\n").split() + offset = parts.index("MSF:") + if ( + parts[offset + 2] != "Type:" + or parts[-3] not in ("Check:", "CompCheck:") + or parts[-1] != ".." + ): + raise ValueError( + "GCG MSF header line should be " + "' MSF: Type: Check: ..', " + " not: %r" % line + ) + try: + aln_length = int(parts[offset + 1]) + except ValueError: + aln_length = -1 + if aln_length < 0: + raise ValueError( + "GCG MSF header line should have MDF: for column count, not %r" + % parts[offset + 1] + ) + seq_type = parts[offset + 3] + if seq_type not in ["P", "N"]: + raise ValueError( + "GCG MSF header line should have 'Type: P' (protein) " + "or 'Type: N' (nucleotide), not 'Type: %s'" % seq_type + ) + + # There should be a blank line after that header line, then the Name: lines + # + # In a possible bug, T-COFFEE v12.00 adds 'oo' after the names, as shown here, + # + # PileUp + # + # + # + # MSF: 628 Type: P Check: 147 .. + # + # Name: AK1H_ECOLI/1-378 oo Len: 628 Check: 3643 Weight: 1.000 + # Name: AKH_HAEIN/1-382 oo Len: 628 Check: 6504 Weight: 1.000 + # + # // + ids = [] + lengths = [] + checks = [] + weights = [] + line = handle.readline() + while line and line.strip() != "//": + line = handle.readline() + if line.strip().startswith("Name: "): + if " Len: " in line and " Check: " in line and " Weight: " in line: + rest = line[line.index("Name: ") + 6 :].strip() + name, rest = rest.split(" Len: ") + length, rest = rest.split(" Check: ") + check, weight = rest.split(" Weight: ") + name = name.strip() + if name.endswith(" oo"): + # T-COFFEE oddity, ignore this + name = name[:-3] + if name in ids: + raise ValueError(f"Duplicated ID of {name!r}") + if " " in name: + raise NotImplementedError(f"Space in ID {name!r}") + ids.append(name) + # Expect aln_length <= int(length.strip()), see below + lengths.append(int(length.strip())) + checks.append(int(check.strip())) + weights.append(float(weight.strip())) + else: + raise ValueError(f"Malformed GCG MSF name line: {line!r}") + if not line: + raise ValueError("End of file while looking for end of header // line.") + + if aln_length != max(lengths): + # In broken examples from IMGTHLA was possible to continue + # https://github.com/ANHIG/IMGTHLA/issues/201 + max_length = max(lengths) + max_count = sum(1 for _ in lengths if _ == max_length) + raise ValueError( + "GCG MSF header said alignment length %i, but %s of %i sequences said Len: %s" + % (aln_length, max_count, len(ids), max_length) + ) + + line = handle.readline() + if not line: + raise ValueError("End of file after // line, expected sequences.") + if line.strip(): + raise ValueError("After // line, expected blank line before sequences.") + + # Now load the sequences + seqs = [[] for _ in ids] # list of empty lists + completed_length = 0 + while completed_length < aln_length: + # Note might have a coordinate header line (seems to be optional) + for idx, name in enumerate(ids): + line = handle.readline() + if idx == 0 and not line.strip(): + # T-COFFEE uses two blank lines between blocks, rather than one + while line and not line.strip(): + line = handle.readline() + if not line: + raise ValueError("End of file where expecting sequence data.") + # print("Looking for seq for %s in line: %r" % (name, line)) + words = line.strip().split() + # Should we use column numbers, rather than assuming no spaces in names? + if idx == 0 and words and words[0] != name: + # print("Actually have a coord line") + # Hopefully this is a coordinate header before the first seq + try: + i = int(words[0]) + except ValueError: + i = -1 + if i != completed_length + 1: + raise ValueError( + "Expected GCG MSF coordinate line starting %i, got: %r" + % (completed_length + 1, line) + ) + if len(words) > 1: + # Final block usually not full 50 chars, so expect start only. + if len(words) != 2: + i = -1 + else: + try: + i = int(words[1]) + except ValueError: + i = -1 + if i != ( + completed_length + 50 + if completed_length + 50 < aln_length + else aln_length + ): + raise ValueError( + "Expected GCG MSF coordinate line %i to %i, got: %r" + % ( + completed_length + 1, + ( + completed_length + 50 + if completed_length + 50 < aln_length + else aln_length + ), + line, + ) + ) + line = handle.readline() + words = line.strip().split() + # print("Still looking for seq for %s in line: %r" % (name, line)) + # Dealt with any coordinate header line, should now be sequence + if not words: + # Should be sequence here, but perhaps its a short one? + if ( + lengths[idx] < aln_length + and len("".join(seqs[idx])) == lengths[idx] + ): + # Is this actually allowed in the format? Personally I would + # expect a line with name and a block of trailing ~ here. + pass + else: + raise ValueError(f"Expected sequence for {name}, got: {line!r}") + elif words[0] == name: + assert len(words) > 1, line + # print(i, name, repr(words)) + seqs[idx].extend(words[1:]) + else: + raise ValueError(f"Expected sequence for {name!r}, got: {line!r}") + # TODO - check the sequence lengths thus far are consistent + # with blocks of 50? + completed_length += 50 + line = handle.readline() + if line.strip(): + raise ValueError(f"Expected blank line, got: {line!r}") + + # Skip over any whitespace at the end... + while True: + line = handle.readline() + if not line: + # End of file, no more alignments + break + elif not line.strip(): + # Blank line, ignore + pass + elif line.strip().split()[0] in known_headers: + # Looks like the start of another alignment: + self._header = line + break + else: + raise ValueError(f"Unexpected line after GCG MSF alignment: {line!r}") + + # Combine list of strings into single string, remap gaps + seqs = ["".join(s).replace("~", "-").replace(".", "-") for s in seqs] + + # Apply any trailing padding for short sequences + padded = False + for idx, (length, s) in enumerate(zip(lengths, seqs)): + if len(s) < aln_length and len(s) == length: + padded = True + seqs[idx] = s + "-" * (aln_length - len(s)) + if padded: + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + "One of more alignment sequences were truncated and have been gap padded", + BiopythonParserWarning, + ) + + records = ( + SeqRecord(Seq(s), id=i, name=i, description=i, annotations={"weight": w}) + for (i, s, w) in zip(ids, seqs, weights) + ) + + # This will check alignment lengths are self-consistent: + align = MultipleSeqAlignment(records) + # Check matches the header: + if align.get_alignment_length() != aln_length: + raise ValueError( + "GCG MSF headers said alignment length %i, but have %i" + % (aln_length, align.get_alignment_length()) + ) + return align diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/NexusIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/NexusIO.py new file mode 100644 index 0000000000000000000000000000000000000000..f108bbdd78272bf917551ca6fa684edb65bcb093 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/NexusIO.py @@ -0,0 +1,173 @@ +# Copyright 2008-2010, 2012-2014, 2016-2017 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.AlignIO support for the "nexus" file format. + +You are expected to use this module via the Bio.AlignIO functions (or the +Bio.SeqIO functions if you want to work directly with the gapped sequences). + +See also the Bio.Nexus module (which this code calls internally), +as this offers more than just accessing the alignment or its +sequences as SeqRecord objects. +""" + +from typing import IO +from collections.abc import Iterator +from typing import Optional + +from Bio.Align import MultipleSeqAlignment +from Bio.AlignIO.Interfaces import AlignmentWriter +from Bio.Nexus import Nexus +from Bio.SeqRecord import SeqRecord + +# You can get a couple of example files here: +# http://www.molecularevolution.org/resources/fileformats/ + + +# This is a generator function! +def NexusIterator( + handle: IO[str], seq_count: int | None = None +) -> Iterator[MultipleSeqAlignment]: + """Return SeqRecord objects from a Nexus file. + + Thus uses the Bio.Nexus module to do the hard work. + + You are expected to call this function via Bio.SeqIO or Bio.AlignIO + (and not use it directly). + + NOTE - We only expect ONE alignment matrix per Nexus file, + meaning this iterator will only yield one MultipleSeqAlignment. + """ + n = Nexus.Nexus(handle) + if not n.matrix: + # No alignment found + return + + # Bio.Nexus deals with duplicated names by adding a '.copy' suffix. + # The original names and the modified names are kept in these two lists: + assert len(n.unaltered_taxlabels) == len(n.taxlabels) + + if seq_count and seq_count != len(n.unaltered_taxlabels): + raise ValueError( + "Found %i sequences, but seq_count=%i" + % (len(n.unaltered_taxlabels), seq_count) + ) + + # TODO - Can we extract any annotation too? + annotations: SeqRecord._AnnotationsDict | None + if n.datatype in ("dna", "nucleotide"): + annotations = {"molecule_type": "DNA"} + elif n.datatype == "rna": + annotations = {"molecule_type": "RNA"} + elif n.datatype == "protein": + annotations = {"molecule_type": "protein"} + else: + annotations = None + records = ( + SeqRecord( + n.matrix[new_name], + id=new_name, + name=old_name, + description="", + annotations=annotations, + ) + for old_name, new_name in zip(n.unaltered_taxlabels, n.taxlabels) + ) + # All done + yield MultipleSeqAlignment(records) + + +class NexusWriter(AlignmentWriter): + """Nexus alignment writer. + + Note that Nexus files are only expected to hold ONE alignment + matrix. + + You are expected to call this class via the Bio.AlignIO.write() or + Bio.SeqIO.write() functions. + """ + + def write_file(self, alignments): + """Use this to write an entire file containing the given alignments. + + Arguments: + - alignments - A list or iterator returning MultipleSeqAlignment objects. + This should hold ONE and only one alignment. + + """ + align_iter = iter(alignments) # Could have been a list + try: + alignment = next(align_iter) + except StopIteration: + # Nothing to write! + return 0 + + # Check there is only one alignment... + try: + next(align_iter) + raise ValueError("We can only write one Alignment to a Nexus file.") + except StopIteration: + pass + + # Good. Actually write the single alignment, + self.write_alignment(alignment) + return 1 # we only support writing one alignment! + + def write_alignment(self, alignment, interleave=None): + """Write an alignment to file. + + Creates an empty Nexus object, adds the sequences + and then gets Nexus to prepare the output. + Default interleave behaviour: Interleave if columns > 1000 + --> Override with interleave=[True/False] + """ + if len(alignment) == 0: + raise ValueError("Must have at least one sequence") + columns = alignment.get_alignment_length() + if columns == 0: + raise ValueError("Non-empty sequences are required") + datatype = self._classify_mol_type_for_nexus(alignment) + minimal_record = ( + "#NEXUS\nbegin data; dimensions ntax=0 nchar=0; format datatype=%s; end;" + % datatype + ) + n = Nexus.Nexus(minimal_record) + for record in alignment: + # Sanity test sequences (should this be even stricter?) + if datatype == "dna" and "U" in record.seq: + raise ValueError(f"{record.id} contains U, but DNA alignment") + elif datatype == "rna" and "T" in record.seq: + raise ValueError(f"{record.id} contains T, but RNA alignment") + n.add_sequence(record.id, str(record.seq)) + + # Note: MrBayes may choke on large alignments if not interleaved + if interleave is None: + interleave = columns > 1000 + n.write_nexus_data(self.handle, interleave=interleave) + + def _classify_mol_type_for_nexus(self, alignment): + """Return 'protein', 'dna', or 'rna' based on records' molecule type (PRIVATE). + + All the records must have a molecule_type annotation, and they must + agree. + + Raises an exception if this is not possible. + """ + values = {_.annotations.get("molecule_type", None) for _ in alignment} + if all(_ and "DNA" in _ for _ in values): + return "dna" # could have been a mix of "DNA" and "gDNA" + elif all(_ and "RNA" in _ for _ in values): + return "rna" # could have been a mix of "RNA" and "mRNA" + elif all(_ and "protein" in _ for _ in values): + return "protein" + else: + raise ValueError("Need the molecule type to be defined") + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/PhylipIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/PhylipIO.py new file mode 100644 index 0000000000000000000000000000000000000000..f8c4e5162d61d3f301348c9bd44a8f1665c9fb78 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/PhylipIO.py @@ -0,0 +1,454 @@ +# Copyright 2006-2016 by Peter Cock. All rights reserved. +# Revisions copyright 2011 Brandon Invergo. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""AlignIO support for "phylip" format from Joe Felsenstein's PHYLIP tools. + +You are expected to use this module via the Bio.AlignIO functions (or the +Bio.SeqIO functions if you want to work directly with the gapped sequences). + +Support for "relaxed phylip" format is also provided. Relaxed phylip differs +from standard phylip format in the following ways: + + - No whitespace is allowed in the sequence ID. + - No truncation is performed. Instead, sequence IDs are padded to the longest + ID length, rather than 10 characters. A space separates the sequence + identifier from the sequence. + +Relaxed phylip is supported by RAxML and PHYML. + +Note +==== + +In TREE_PUZZLE (Schmidt et al. 2003) and PHYML (Guindon and Gascuel 2003) +a dot/period (".") in a sequence is interpreted as meaning the same +character as in the first sequence. The PHYLIP documentation from 3.3 to 3.69 +http://evolution.genetics.washington.edu/phylip/doc/sequence.html says: + +"a period was also previously allowed but it is no longer allowed, +because it sometimes is used in different senses in other programs" + +Biopython 1.58 or later treats dots/periods in the sequence as invalid, both +for reading and writing. Older versions did nothing special with a dot/period. +""" + +import string + +from Bio.Align import MultipleSeqAlignment +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import AlignmentIterator +from .Interfaces import SequentialAlignmentWriter + +_PHYLIP_ID_WIDTH = 10 +_NO_DOTS = "PHYLIP format no longer allows dots in sequence" + + +class PhylipWriter(SequentialAlignmentWriter): + """Phylip alignment writer.""" + + def write_alignment(self, alignment, id_width=_PHYLIP_ID_WIDTH): + """Use this to write (another) single alignment to an open file. + + This code will write interlaced alignments (when the sequences are + longer than 50 characters). + + Note that record identifiers are strictly truncated to id_width, + defaulting to the value required to comply with the PHYLIP standard. + + For more information on the file format, please see: + http://evolution.genetics.washington.edu/phylip/doc/sequence.html + http://evolution.genetics.washington.edu/phylip/doc/main.html#inputfiles + """ + handle = self.handle + + if len(alignment) == 0: + raise ValueError("Must have at least one sequence") + length_of_seqs = alignment.get_alignment_length() + for record in alignment: + if length_of_seqs != len(record.seq): + raise ValueError("Sequences must all be the same length") + if length_of_seqs <= 0: + raise ValueError("Non-empty sequences are required") + + # Check for repeated identifiers... + # Apply this test *after* cleaning the identifiers + names = [] + seqs = [] + for record in alignment: + """ + Quoting the PHYLIP version 3.6 documentation: + + The name should be ten characters in length, filled out to + the full ten characters by blanks if shorter. Any printable + ASCII/ISO character is allowed in the name, except for + parentheses ("(" and ")"), square brackets ("[" and "]"), + colon (":"), semicolon (";") and comma (","). If you forget + to extend the names to ten characters in length by blanks, + the program [i.e. PHYLIP] will get out of synchronization + with the contents of the data file, and an error message will + result. + + Note that Tab characters count as only one character in the + species names. Their inclusion can cause trouble. + """ + name = sanitize_name(record.id, id_width) + if name in names: + raise ValueError( + "Repeated name %r (originally %r), possibly due to truncation" + % (name, record.id) + ) + names.append(name) + sequence = str(record.seq) + if "." in sequence: + # Do this check here (once per record, not once per block) + raise ValueError(_NO_DOTS) + seqs.append(sequence) + + # From experimentation, the use of tabs is not understood by the + # EMBOSS suite. The nature of the expected white space is not + # defined in the PHYLIP documentation, simply "These are in free + # format, separated by blanks". We'll use spaces to keep EMBOSS + # happy. + handle.write(" %i %s\n" % (len(alignment), length_of_seqs)) + block = 0 + while True: + for name, sequence in zip(names, seqs): + if block == 0: + # Write name (truncated/padded to id_width characters) + # Now truncate and right pad to expected length. + handle.write(name[:id_width].ljust(id_width)) + else: + # write indent + handle.write(" " * id_width) + # Write five chunks of ten letters per line... + for chunk in range(5): + i = block * 50 + chunk * 10 + seq_segment = sequence[i : i + 10] + # TODO - Force any gaps to be '-' character? + # TODO - How to cope with '?' or '.' in the sequence? + handle.write(f" {seq_segment}") + if i + 10 > length_of_seqs: + break + handle.write("\n") + block += 1 + if block * 50 >= length_of_seqs: + break + handle.write("\n") + + +class PhylipIterator(AlignmentIterator): + """Reads a Phylip alignment file returning a MultipleSeqAlignment iterator. + + Record identifiers are limited to at most 10 characters. + + It only copes with interlaced phylip files! Sequential files won't work + where the sequences are split over multiple lines. + + For more information on the file format, please see: + http://evolution.genetics.washington.edu/phylip/doc/sequence.html + http://evolution.genetics.washington.edu/phylip/doc/main.html#inputfiles + """ + + # Default truncation length + id_width = _PHYLIP_ID_WIDTH + + _header = None # for caching lines between __next__ calls + + def _is_header(self, line): + line = line.strip() + parts = [x for x in line.split() if x] + if len(parts) != 2: + return False # First line should have two integers + try: + number_of_seqs = int(parts[0]) + length_of_seqs = int(parts[1]) + return True + except ValueError: + return False # First line should have two integers + + def _split_id(self, line): + """Extract the sequence ID from a Phylip line (PRIVATE). + + Returning a tuple containing: (sequence_id, sequence_residues) + + The first 10 characters in the line are are the sequence id, the + remainder are sequence data. + """ + seq_id = line[: self.id_width].strip() + seq = line[self.id_width :].strip().replace(" ", "") + return seq_id, seq + + def __next__(self): + """Parse the next alignment from the handle.""" + handle = self.handle + + if self._header is None: + line = handle.readline() + else: + # Header we saved from when we were parsing + # the previous alignment. + line = self._header + self._header = None + + if not line: + raise StopIteration + line = line.strip() + parts = [x for x in line.split() if x] + if len(parts) != 2: + raise ValueError("First line should have two integers") + try: + number_of_seqs = int(parts[0]) + length_of_seqs = int(parts[1]) + except ValueError: + raise ValueError("First line should have two integers") from None + + assert self._is_header(line) + + if ( + self.records_per_alignment is not None + and self.records_per_alignment != number_of_seqs + ): + raise ValueError( + "Found %i records in this alignment, told to expect %i" + % (number_of_seqs, self.records_per_alignment) + ) + + ids = [] + seqs = [] + + # By default, expects STRICT truncation / padding to 10 characters. + # Does not require any whitespace between name and seq. + for i in range(number_of_seqs): + line = handle.readline().rstrip() + sequence_id, s = self._split_id(line) + ids.append(sequence_id) + if "." in s: + raise ValueError(_NO_DOTS) + seqs.append([s]) + + # Look for further blocks + line = "" + while True: + # Skip any blank lines between blocks... + while "" == line.strip(): + line = handle.readline() + if not line: + break # end of file + if not line: + break # end of file + + if self._is_header(line): + # Looks like the start of a concatenated alignment + self._header = line + break + + # print("New block...") + for i in range(number_of_seqs): + s = line.strip().replace(" ", "") + if "." in s: + raise ValueError(_NO_DOTS) + seqs[i].append(s) + line = handle.readline() + if (not line) and i + 1 < number_of_seqs: + raise ValueError("End of file mid-block") + if not line: + break # end of file + + records = ( + SeqRecord(Seq("".join(s)), id=i, name=i, description=i) + for (i, s) in zip(ids, seqs) + ) + return MultipleSeqAlignment(records) + + +# Relaxed Phylip +class RelaxedPhylipWriter(PhylipWriter): + """Relaxed Phylip format writer.""" + + def write_alignment(self, alignment): + """Write a relaxed phylip alignment.""" + # Check inputs + for name in (s.id.strip() for s in alignment): + if any(c in name for c in string.whitespace): + raise ValueError(f"Whitespace not allowed in identifier: {name}") + + # Calculate a truncation length - maximum length of sequence ID plus a + # single character for padding + # If no sequences, set id_width to 1. super(...) call will raise a + # ValueError + if len(alignment) == 0: + id_width = 1 + else: + id_width = max(len(s.id.strip()) for s in alignment) + 1 + super().write_alignment(alignment, id_width) + + +class RelaxedPhylipIterator(PhylipIterator): + """Relaxed Phylip format Iterator.""" + + def _split_id(self, line): + """Extract the sequence ID from a Phylip line (PRIVATE). + + Returns a tuple containing: (sequence_id, sequence_residues) + + For relaxed format split at the first whitespace character. + """ + seq_id, sequence = line.split(None, 1) + sequence = sequence.strip().replace(" ", "") + return seq_id, sequence + + +class SequentialPhylipWriter(SequentialAlignmentWriter): + """Sequential Phylip format Writer.""" + + def write_alignment(self, alignment, id_width=_PHYLIP_ID_WIDTH): + """Write a Phylip alignment to the handle.""" + handle = self.handle + + if len(alignment) == 0: + raise ValueError("Must have at least one sequence") + length_of_seqs = alignment.get_alignment_length() + for record in alignment: + if length_of_seqs != len(record.seq): + raise ValueError("Sequences must all be the same length") + if length_of_seqs <= 0: + raise ValueError("Non-empty sequences are required") + + # Check for repeated identifiers... + # Apply this test *after* cleaning the identifiers + names = [] + for record in alignment: + # Either remove the banned characters, or map them to something + # else like an underscore "_" or pipe "|" character... + name = sanitize_name(record.id, id_width) + if name in names: + raise ValueError( + "Repeated name %r (originally %r), possibly due to truncation" + % (name, record.id) + ) + names.append(name) + + # From experimentation, the use of tabs is not understood by the + # EMBOSS suite. The nature of the expected white space is not + # defined in the PHYLIP documentation, simply "These are in free + # format, separated by blanks". We'll use spaces to keep EMBOSS + # happy. + handle.write(" %i %s\n" % (len(alignment), length_of_seqs)) + for name, record in zip(names, alignment): + sequence = str(record.seq) + if "." in sequence: + raise ValueError(_NO_DOTS) + handle.write(name[:id_width].ljust(id_width)) + # Write the entire sequence to one line (see sequential format + # notes in the SequentialPhylipIterator docstring + handle.write(sequence) + handle.write("\n") + + +class SequentialPhylipIterator(PhylipIterator): + """Sequential Phylip format Iterator. + + The sequential format carries the same restrictions as the normal + interleaved one, with the difference being that the sequences are listed + sequentially, each sequence written in its entirety before the start of + the next. According to the PHYLIP documentation for input file + formatting, newlines and spaces may optionally be entered at any point + in the sequences. + """ + + _header = None # for caching lines between __next__ calls + + def __next__(self): + """Parse the next alignment from the handle.""" + handle = self.handle + + if self._header is None: + line = handle.readline() + else: + # Header we saved from when we were parsing + # the previous alignment. + line = self._header + self._header = None + + if not line: + raise StopIteration + line = line.strip() + parts = [x for x in line.split() if x] + if len(parts) != 2: + raise ValueError("First line should have two integers") + try: + number_of_seqs = int(parts[0]) + length_of_seqs = int(parts[1]) + except ValueError: + raise ValueError("First line should have two integers") from None + + assert self._is_header(line) + + if ( + self.records_per_alignment is not None + and self.records_per_alignment != number_of_seqs + ): + raise ValueError( + "Found %i records in this alignment, told to expect %i" + % (number_of_seqs, self.records_per_alignment) + ) + + ids = [] + seqs = [] + + # By default, expects STRICT truncation / padding to 10 characters. + # Does not require any whitespace between name and seq. + for i in range(number_of_seqs): + line = handle.readline().rstrip() + sequence_id, s = self._split_id(line) + ids.append(sequence_id) + while len(s) < length_of_seqs: + # The sequence may be split into multiple lines + line = handle.readline().strip() + if not line: + break + if line == "": + continue + s = "".join([s, line.strip().replace(" ", "")]) + if len(s) > length_of_seqs: + raise ValueError( + "Found a record of length %i, " + "should be %i" % (len(s), length_of_seqs) + ) + if "." in s: + raise ValueError(_NO_DOTS) + seqs.append(s) + while True: + # Find other alignments in the file + line = handle.readline() + if not line: + break + if self._is_header(line): + self._header = line + break + + records = ( + SeqRecord(Seq(s), id=i, name=i, description=i) for (i, s) in zip(ids, seqs) + ) + return MultipleSeqAlignment(records) + + +def sanitize_name(name, width=None): + """Sanitise sequence identifier for output. + + Removes the banned characters "[]()" and replaces the characters ":;" + with "|". The name is truncated to "width" characters if specified. + """ + name = name.strip() + for char in "[](),": + name = name.replace(char, "") + for char in ":;": + name = name.replace(char, "|") + if width is not None: + name = name[:width] + return name diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/StockholmIO.py b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/StockholmIO.py new file mode 100644 index 0000000000000000000000000000000000000000..721a7f3979a5c3b6abb214e3a27a79b6da75edac --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/StockholmIO.py @@ -0,0 +1,620 @@ +# Copyright 2006-2016 by Peter Cock. All rights reserved. +# Revisions copyright 2015 by Ben Woodcroft. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.AlignIO support for "stockholm" format (used in the PFAM database). + +You are expected to use this module via the Bio.AlignIO functions (or the +Bio.SeqIO functions if you want to work directly with the gapped sequences). + +For example, consider a Stockholm alignment file containing the following:: + + # STOCKHOLM 1.0 + #=GC SS_cons .................<<<<<<<<...<<<<<<<........>>>>>>>.. + AP001509.1 UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGU + #=GR AP001509.1 SS -----------------<<<<<<<<---..<<-<<-------->>->>..-- + AE007476.1 AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGU + #=GR AE007476.1 SS -----------------<<<<<<<<-----<<.<<-------->>.>>---- + + #=GC SS_cons ......<<<<<<<.......>>>>>>>..>>>>>>>>............... + AP001509.1 CUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU + #=GR AP001509.1 SS -------<<<<<--------->>>>>--->>>>>>>>--------------- + AE007476.1 UUCUACAAGGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU + #=GR AE007476.1 SS ------.<<<<<--------->>>>>.-->>>>>>>>--------------- + // + +This is a single multiple sequence alignment, so you would probably load this +using the Bio.AlignIO.read() function: + + >>> from Bio import AlignIO + >>> align = AlignIO.read("Stockholm/simple.sth", "stockholm") + >>> print(align) + Alignment with 2 rows and 104 columns + UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-G...UGU AP001509.1 + AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-C...GAU AE007476.1 + >>> for record in align: + ... print("%s %i" % (record.id, len(record))) + AP001509.1 104 + AE007476.1 104 + +In addition to the sequences themselves, this example alignment also includes +some GR lines for the secondary structure of the sequences. These are +strings, with one character for each letter in the associated sequence: + + >>> for record in align: + ... print(record.id) + ... print(record.seq) + ... print(record.letter_annotations['secondary_structure']) + AP001509.1 + UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU + -----------------<<<<<<<<---..<<-<<-------->>->>..---------<<<<<--------->>>>>--->>>>>>>>--------------- + AE007476.1 + AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGUUUCUACAAGGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU + -----------------<<<<<<<<-----<<.<<-------->>.>>----------.<<<<<--------->>>>>.-->>>>>>>>--------------- + +Any general annotation for each row is recorded in the SeqRecord's annotations +dictionary. Any per-column annotation for the entire alignment in in the +alignment's column annotations dictionary, such as the secondary structure +consensus in this example: + + >>> sorted(align.column_annotations.keys()) + ['secondary_structure'] + >>> align.column_annotations["secondary_structure"] + '.................<<<<<<<<...<<<<<<<........>>>>>>>........<<<<<<<.......>>>>>>>..>>>>>>>>...............' + +You can output this alignment in many different file formats +using Bio.AlignIO.write(), or the MultipleSeqAlignment object's format method: + + >>> print(format(align, "fasta")) + >AP001509.1 + UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-A + GGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU + >AE007476.1 + AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGUUUCUACAA + GGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU + + +Most output formats won't be able to hold the annotation possible in a +Stockholm file: + + >>> print(format(align, "stockholm")) + # STOCKHOLM 1.0 + #=GF SQ 2 + AP001509.1 UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU + #=GS AP001509.1 AC AP001509.1 + #=GS AP001509.1 DE AP001509.1 + #=GR AP001509.1 SS -----------------<<<<<<<<---..<<-<<-------->>->>..---------<<<<<--------->>>>>--->>>>>>>>--------------- + AE007476.1 AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGUUUCUACAAGGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU + #=GS AE007476.1 AC AE007476.1 + #=GS AE007476.1 DE AE007476.1 + #=GR AE007476.1 SS -----------------<<<<<<<<-----<<.<<-------->>.>>----------.<<<<<--------->>>>>.-->>>>>>>>--------------- + #=GC SS_cons .................<<<<<<<<...<<<<<<<........>>>>>>>........<<<<<<<.......>>>>>>>..>>>>>>>>............... + // + + +Note that when writing Stockholm files, AlignIO does not break long sequences +up and interleave them (as in the input file shown above). The standard +allows this simpler layout, and it is more likely to be understood by other +tools. + +Finally, as an aside, it can sometimes be useful to use Bio.SeqIO.parse() to +iterate over the alignment rows as SeqRecord objects - rather than working +with Alignnment objects. + + >>> from Bio import SeqIO + >>> for record in SeqIO.parse("Stockholm/simple.sth", "stockholm"): + ... print(record.id) + ... print(record.seq) + ... print(record.letter_annotations['secondary_structure']) + AP001509.1 + UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU + -----------------<<<<<<<<---..<<-<<-------->>->>..---------<<<<<--------->>>>>--->>>>>>>>--------------- + AE007476.1 + AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGUUUCUACAAGGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU + -----------------<<<<<<<<-----<<.<<-------->>.>>----------.<<<<<--------->>>>>.-->>>>>>>>--------------- + +Remember that if you slice a SeqRecord, the per-letter-annotations like the +secondary structure string here, are also sliced: + + >>> sub_record = record[10:20] + >>> print(sub_record.seq) + AUCGUUUUAC + >>> print(sub_record.letter_annotations['secondary_structure']) + -------<<< + +Likewise with the alignment object, as long as you are not dropping any rows, +slicing specific columns of an alignment will slice any per-column-annotations: + + >>> align.column_annotations["secondary_structure"] + '.................<<<<<<<<...<<<<<<<........>>>>>>>........<<<<<<<.......>>>>>>>..>>>>>>>>...............' + >>> part_align = align[:,10:20] + >>> part_align.column_annotations["secondary_structure"] + '.......<<<' + +You can also see this in the Stockholm output of this partial-alignment: + + >>> print(format(part_align, "stockholm")) + # STOCKHOLM 1.0 + #=GF SQ 2 + AP001509.1 UCAACACUCU + #=GS AP001509.1 AC AP001509.1 + #=GS AP001509.1 DE AP001509.1 + #=GR AP001509.1 SS -------<<< + AE007476.1 AUCGUUUUAC + #=GS AE007476.1 AC AE007476.1 + #=GS AE007476.1 DE AE007476.1 + #=GR AE007476.1 SS -------<<< + #=GC SS_cons .......<<< + // + + +""" + +from Bio.Align import MultipleSeqAlignment +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + +from .Interfaces import AlignmentIterator +from .Interfaces import SequentialAlignmentWriter + + +class StockholmWriter(SequentialAlignmentWriter): + """Stockholm/PFAM alignment writer.""" + + # These dictionaries should be kept in sync with those + # defined in the StockholmIterator class. + pfam_gr_mapping = { + "secondary_structure": "SS", + "surface_accessibility": "SA", + "transmembrane": "TM", + "posterior_probability": "PP", + "ligand_binding": "LI", + "active_site": "AS", + "intron": "IN", + } + # These GC mappings are in addition to *_cons in GR mapping: + pfam_gc_mapping = {"reference_annotation": "RF", "model_mask": "MM"} + # Following dictionary deliberately does not cover AC, DE or DR + pfam_gs_mapping = {"organism": "OS", "organism_classification": "OC", "look": "LO"} + + def write_alignment(self, alignment): + """Use this to write (another) single alignment to an open file. + + Note that sequences and their annotation are recorded + together (rather than having a block of annotation followed + by a block of aligned sequences). + """ + count = len(alignment) + + self._length_of_sequences = alignment.get_alignment_length() + self._ids_written = [] + + if count == 0: + raise ValueError("Must have at least one sequence") + if self._length_of_sequences == 0: + raise ValueError("Non-empty sequences are required") + + self.handle.write("# STOCKHOLM 1.0\n") + self.handle.write("#=GF SQ %i\n" % count) + for record in alignment: + self._write_record(record) + # This shouldn't be None... but just in case, + if alignment.column_annotations: + for k, v in sorted(alignment.column_annotations.items()): + if k in self.pfam_gc_mapping: + self.handle.write(f"#=GC {self.pfam_gc_mapping[k]} {v}\n") + elif k in self.pfam_gr_mapping: + self.handle.write(f"#=GC {self.pfam_gr_mapping[k]}_cons {v}\n") + else: + # It doesn't follow the PFAM standards, but should we record + # this data anyway? + pass + self.handle.write("//\n") + + def _write_record(self, record): + """Write a single SeqRecord to the file (PRIVATE).""" + if self._length_of_sequences != len(record.seq): + raise ValueError("Sequences must all be the same length") + + # For the case for stockholm to stockholm, try and use record.name + seq_name = record.id + if record.name is not None: + if "accession" in record.annotations: + if record.id == record.annotations["accession"]: + seq_name = record.name + + # In the Stockholm file format, spaces are not allowed in the id + seq_name = seq_name.replace(" ", "_") + + if "start" in record.annotations and "end" in record.annotations: + suffix = f"/{record.annotations['start']}-{record.annotations['end']}" + if seq_name[-len(suffix) :] != suffix: + seq_name = "%s/%s-%s" % ( + seq_name, + record.annotations["start"], + record.annotations["end"], + ) + + if seq_name in self._ids_written: + raise ValueError(f"Duplicate record identifier: {seq_name}") + self._ids_written.append(seq_name) + self.handle.write(f"{seq_name} {record.seq}\n") + + # The recommended placement for GS lines (per sequence annotation) + # is above the alignment (as a header block) or just below the + # corresponding sequence. + # + # The recommended placement for GR lines (per sequence per column + # annotation such as secondary structure) is just below the + # corresponding sequence. + # + # We put both just below the corresponding sequence as this allows + # us to write the file using a single pass through the records. + + # AC = Accession + if "accession" in record.annotations: + self.handle.write( + f"#=GS {seq_name} AC {self.clean(record.annotations['accession'])}\n" + ) + elif record.id: + self.handle.write(f"#=GS {seq_name} AC {self.clean(record.id)}\n") + + # DE = description + if record.description: + self.handle.write(f"#=GS {seq_name} DE {self.clean(record.description)}\n") + + # DE = database links + for xref in record.dbxrefs: + self.handle.write(f"#=GS {seq_name} DR {self.clean(xref)}\n") + + # GS = other per sequence annotation + for key, value in record.annotations.items(): + if key in self.pfam_gs_mapping: + data = self.clean(str(value)) + if data: + self.handle.write( + "#=GS %s %s %s\n" + % (seq_name, self.clean(self.pfam_gs_mapping[key]), data) + ) + else: + # It doesn't follow the PFAM standards, but should we record + # this data anyway? + pass + + # GR = per row per column sequence annotation + for key, value in record.letter_annotations.items(): + if key in self.pfam_gr_mapping and len(str(value)) == len(record.seq): + data = self.clean(str(value)) + if data: + self.handle.write( + "#=GR %s %s %s\n" + % (seq_name, self.clean(self.pfam_gr_mapping[key]), data) + ) + else: + # It doesn't follow the PFAM standards, but should we record + # this data anyway? + pass + + +class StockholmIterator(AlignmentIterator): + """Loads a Stockholm file from PFAM into MultipleSeqAlignment objects. + + The file may contain multiple concatenated alignments, which are loaded + and returned incrementally. + + This parser will detect if the Stockholm file follows the PFAM + conventions for sequence specific meta-data (lines starting #=GS + and #=GR) and populates the SeqRecord fields accordingly. + + Any annotation which does not follow the PFAM conventions is currently + ignored. + + If an accession is provided for an entry in the meta data, IT WILL NOT + be used as the record.id (it will be recorded in the record's + annotations). This is because some files have (sub) sequences from + different parts of the same accession (differentiated by different + start-end positions). + + Wrap-around alignments are not supported - each sequences must be on + a single line. However, interlaced sequences should work. + + For more information on the file format, please see: + http://sonnhammer.sbc.su.se/Stockholm.html + https://en.wikipedia.org/wiki/Stockholm_format + http://bioperl.org/formats/alignment_formats/Stockholm_multiple_alignment_format.html + + For consistency with BioPerl and EMBOSS we call this the "stockholm" + format. + """ + + # These dictionaries should be kept in sync with those + # defined in the PfamStockholmWriter class. + pfam_gr_mapping = { + "SS": "secondary_structure", + "SA": "surface_accessibility", + "TM": "transmembrane", + "PP": "posterior_probability", + "LI": "ligand_binding", + "AS": "active_site", + "IN": "intron", + } + # These GC mappings are in addition to *_cons in GR mapping: + pfam_gc_mapping = {"RF": "reference_annotation", "MM": "model_mask"} + # Following dictionary deliberately does not cover AC, DE or DR + pfam_gs_mapping = {"OS": "organism", "OC": "organism_classification", "LO": "look"} + + _header = None # for caching lines between __next__ calls + + def __next__(self): + """Parse the next alignment from the handle.""" + handle = self.handle + + if self._header is None: + line = handle.readline() + else: + # Header we saved from when we were parsing + # the previous alignment. + line = self._header + self._header = None + + if not line: + # Empty file - just give up. + raise StopIteration + if line.strip() != "# STOCKHOLM 1.0": + raise ValueError("Did not find STOCKHOLM header") + + # Note: If this file follows the PFAM conventions, there should be + # a line containing the number of sequences, e.g. "#=GF SQ 67" + # We do not check for this - perhaps we should, and verify that + # if present it agrees with our parsing. + + seqs = {} + ids = {} # Really only need an OrderedSet, but python lacks this + gs = {} + gr = {} + gf = {} + gc = {} + passed_end_alignment = False + while True: + line = handle.readline() + if not line: + break # end of file + line = line.strip() # remove trailing \n + if line == "# STOCKHOLM 1.0": + self._header = line + break + elif line == "//": + # The "//" line indicates the end of the alignment. + # There may still be more meta-data + passed_end_alignment = True + elif line == "": + # blank line, ignore + pass + elif line[0] != "#": + # Sequence + # Format: " " + assert not passed_end_alignment + parts = [x.strip() for x in line.split(" ", 1)] + if len(parts) != 2: + # This might be someone attempting to store a zero length sequence? + raise ValueError( + "Could not split line into identifier and sequence:\n" + line + ) + seq_id, seq = parts + if seq_id not in ids: + ids[seq_id] = True + seqs.setdefault(seq_id, "") + seqs[seq_id] += seq.replace(".", "-") + elif len(line) >= 5: + # Comment line or meta-data + if line[:5] == "#=GF ": + # Generic per-File annotation, free text + # Format: #=GF + feature, text = line[5:].strip().split(None, 1) + # Each feature key could be used more than once, + # so store the entries as a list of strings. + if feature not in gf: + gf[feature] = [text] + else: + gf[feature].append(text) + elif line[:5] == "#=GC ": + # Generic per-Column annotation, exactly 1 char per column + # Format: "#=GC " + feature, text = line[5:].strip().split(None, 2) + if feature not in gc: + gc[feature] = "" + gc[feature] += text.strip() # append to any previous entry + # Might be interleaved blocks, so can't check length yet + elif line[:5] == "#=GS ": + # Generic per-Sequence annotation, free text + # Format: "#=GS " + try: + seq_id, feature, text = line[5:].strip().split(None, 2) + except ValueError: + # Free text can sometimes be empty, which a one line split throws an error for. + # See https://github.com/biopython/biopython/issues/2982 for more details + seq_id, feature = line[5:].strip().split(None, 1) + text = "" + # if seq_id not in ids: + # ids.append(seq_id) + if seq_id not in gs: + gs[seq_id] = {} + if feature not in gs[seq_id]: + gs[seq_id][feature] = [text] + else: + gs[seq_id][feature].append(text) + elif line[:5] == "#=GR ": + # Generic per-Sequence AND per-Column markup + # Format: "#=GR " + seq_id, feature, text = line[5:].strip().split(None, 2) + # if seq_id not in ids: + # ids.append(seq_id) + if seq_id not in gr: + gr[seq_id] = {} + if feature not in gr[seq_id]: + gr[seq_id][feature] = "" + gr[seq_id][feature] += text.strip() # append to any previous entry + # Might be interleaved blocks, so can't check length yet + # Next line... + + assert len(seqs) <= len(ids) + # assert len(gs) <= len(ids) + # assert len(gr) <= len(ids) + + self.ids = ids.keys() + self.sequences = seqs + self.seq_annotation = gs + self.seq_col_annotation = gr + + if ids and seqs: + if ( + self.records_per_alignment is not None + and self.records_per_alignment != len(ids) + ): + raise ValueError( + "Found %i records in this alignment, told to expect %i" + % (len(ids), self.records_per_alignment) + ) + + alignment_length = len(list(seqs.values())[0]) + records = [] # Alignment obj will put them all in a list anyway + for seq_id in ids: + seq = seqs[seq_id] + if alignment_length != len(seq): + raise ValueError( + "Sequences have different lengths, or repeated identifier" + ) + name, start, end = self._identifier_split(seq_id) + record = SeqRecord( + Seq(seq), + id=seq_id, + name=name, + description=seq_id, + annotations={"accession": name}, + ) + # Accession will be overridden by _populate_meta_data if an explicit + # accession is provided: + record.annotations["accession"] = name + + if start is not None: + record.annotations["start"] = start + if end is not None: + record.annotations["end"] = end + + self._populate_meta_data(seq_id, record) + records.append(record) + for k, v in gc.items(): + if len(v) != alignment_length: + raise ValueError( + "%s length %i, expected %i" % (k, len(v), alignment_length) + ) + alignment = MultipleSeqAlignment(records) + + for k, v in sorted(gc.items()): + if k in self.pfam_gc_mapping: + alignment.column_annotations[self.pfam_gc_mapping[k]] = v + elif k.endswith("_cons") and k[:-5] in self.pfam_gr_mapping: + alignment.column_annotations[self.pfam_gr_mapping[k[:-5]]] = v + else: + # Ignore it? + alignment.column_annotations["GC:" + k] = v + + # TODO - Introduce an annotated alignment class? + # For now, store the annotation a new private property: + alignment._annotations = gr + + return alignment + else: + raise StopIteration + + def _identifier_split(self, identifier): + """Return (name, start, end) string tuple from an identifier (PRIVATE).""" + if "/" in identifier: + name, start_end = identifier.rsplit("/", 1) + if start_end.count("-") == 1: + try: + start, end = start_end.split("-") + return name, int(start), int(end) + except ValueError: + # Non-integers after final '/' - fall through + pass + return identifier, None, None + + def _get_meta_data(self, identifier, meta_dict): + """Take an identifier and returns dict of all meta-data matching it (PRIVATE). + + For example, given "Q9PN73_CAMJE/149-220" will return all matches to + this or "Q9PN73_CAMJE" which the identifier without its /start-end + suffix. + + In the example below, the suffix is required to match the AC, but must + be removed to match the OS and OC meta-data:: + + # STOCKHOLM 1.0 + #=GS Q9PN73_CAMJE/149-220 AC Q9PN73 + ... + Q9PN73_CAMJE/149-220 NKA... + ... + #=GS Q9PN73_CAMJE OS Campylobacter jejuni + #=GS Q9PN73_CAMJE OC Bacteria + + This function will return an empty dictionary if no data is found. + """ + name, start, end = self._identifier_split(identifier) + if name == identifier: + identifier_keys = [identifier] + else: + identifier_keys = [identifier, name] + answer = {} + for identifier_key in identifier_keys: + try: + for feature_key in meta_dict[identifier_key]: + answer[feature_key] = meta_dict[identifier_key][feature_key] + except KeyError: + pass + return answer + + def _populate_meta_data(self, identifier, record): + """Add meta-date to a SecRecord's annotations dictionary (PRIVATE). + + This function applies the PFAM conventions. + """ + seq_data = self._get_meta_data(identifier, self.seq_annotation) + for feature in seq_data: + # Note this dictionary contains lists! + if feature == "AC": # ACcession number + assert len(seq_data[feature]) == 1 + record.annotations["accession"] = seq_data[feature][0] + elif feature == "DE": # DEscription + record.description = "\n".join(seq_data[feature]) + elif feature == "DR": # Database Reference + # Should we try and parse the strings? + record.dbxrefs = seq_data[feature] + elif feature in self.pfam_gs_mapping: + record.annotations[self.pfam_gs_mapping[feature]] = ", ".join( + seq_data[feature] + ) + else: + # Ignore it? + record.annotations["GS:" + feature] = ", ".join(seq_data[feature]) + + # Now record the per-letter-annotations + seq_col_data = self._get_meta_data(identifier, self.seq_col_annotation) + for feature in seq_col_data: + # Note this dictionary contains strings! + if feature in self.pfam_gr_mapping: + record.letter_annotations[self.pfam_gr_mapping[feature]] = seq_col_data[ + feature + ] + else: + # Ignore it? + record.letter_annotations["GR:" + feature] = seq_col_data[feature] + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..883e7be3e24691d92eb313fd3fa86aa1e5fc99fb --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__init__.py @@ -0,0 +1,474 @@ +# Copyright 2008-2018 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Multiple sequence alignment input/output as alignment objects. + +The Bio.AlignIO interface is deliberately very similar to Bio.SeqIO, and in +fact the two are connected internally. Both modules use the same set of file +format names (lower case strings). From the user's perspective, you can read +in a PHYLIP file containing one or more alignments using Bio.AlignIO, or you +can read in the sequences within these alignments using Bio.SeqIO. + +Bio.AlignIO is also documented at http://biopython.org/wiki/AlignIO and by +a whole chapter in our Tutorial_: + +.. _Tutorial: https://biopython.org/docs/latest/Tutorial/index.html + +Input +----- +For the typical special case when your file or handle contains one and only +one alignment, use the function Bio.AlignIO.read(). This takes an input file +handle (or in recent versions of Biopython a filename as a string), format +string and optional number of sequences per alignment. It will return a single +MultipleSeqAlignment object (or raise an exception if there isn't just one +alignment): + +>>> from Bio import AlignIO +>>> align = AlignIO.read("Phylip/interlaced.phy", "phylip") +>>> print(align) +Alignment with 3 rows and 384 columns +-----MKVILLFVLAVFTVFVSS---------------RGIPPE...I-- CYS1_DICDI +MAHARVLLLALAVLATAAVAVASSSSFADSNPIRPVTDRAASTL...VAA ALEU_HORVU +------MWATLPLLCAGAWLLGV--------PVCGAAELSVNSL...PLV CATH_HUMAN + +For the general case, when the handle could contain any number of alignments, +use the function Bio.AlignIO.parse(...) which takes the same arguments, but +returns an iterator giving MultipleSeqAlignment objects (typically used in a +for loop). If you want random access to the alignments by number, turn this +into a list: + +>>> from Bio import AlignIO +>>> alignments = list(AlignIO.parse("Emboss/needle.txt", "emboss")) +>>> print(alignments[2]) +Alignment with 2 rows and 120 columns +-KILIVDDQYGIRILLNEVFNKEGYQTFQAANGLQALDIVTKER...--- ref_rec +LHIVVVDDDPGTCVYIESVFAELGHTCKSFVRPEAAEEYILTHP...HKE gi|94967506|receiver + +Most alignment file formats can be concatenated so as to hold as many +different multiple sequence alignments as possible. One common example +is the output of the tool seqboot in the PHLYIP suite. Sometimes there +can be a file header and footer, as seen in the EMBOSS alignment output. + +Output +------ +Use the function Bio.AlignIO.write(...), which takes a complete set of +Alignment objects (either as a list, or an iterator), an output file handle +(or filename in recent versions of Biopython) and of course the file format:: + + from Bio import AlignIO + alignments = ... + count = SeqIO.write(alignments, "example.faa", "fasta") + +If using a handle make sure to close it to flush the data to the disk:: + + from Bio import AlignIO + alignments = ... + with open("example.faa", "w") as handle: + count = SeqIO.write(alignments, handle, "fasta") + +In general, you are expected to call this function once (with all your +alignments) and then close the file handle. However, for file formats +like PHYLIP where multiple alignments are stored sequentially (with no file +header and footer), then multiple calls to the write function should work as +expected when using handles. + +If you are using a filename, the repeated calls to the write functions will +overwrite the existing file each time. + +Conversion +---------- +The Bio.AlignIO.convert(...) function allows an easy interface for simple +alignment file format conversions. Additionally, it may use file format +specific optimisations so this should be the fastest way too. + +In general however, you can combine the Bio.AlignIO.parse(...) function with +the Bio.AlignIO.write(...) function for sequence file conversion. Using +generator expressions provides a memory efficient way to perform filtering or +other extra operations as part of the process. + +File Formats +------------ +When specifying the file format, use lowercase strings. The same format +names are also used in Bio.SeqIO and include the following: + + - clustal - Output from Clustal W or X. + - emboss - EMBOSS tools' "pairs" and "simple" alignment formats. + - fasta - The generic sequence file format where each record starts with + an identifier line starting with a ">" character, followed by + lines of sequence. + - fasta-m10 - For the pairwise alignments output by Bill Pearson's FASTA + tools when used with the -m 10 command line option for machine + readable output. + - ig - The IntelliGenetics file format, apparently the same as the + MASE alignment format. + - msf - The GCG MSF alignment format, originally from PileUp tool. + - nexus - Output from NEXUS, see also the module Bio.Nexus which can also + read any phylogenetic trees in these files. + - phylip - Interlaced PHYLIP, as used by the PHYLIP tools. + - phylip-sequential - Sequential PHYLIP. + - phylip-relaxed - PHYLIP like format allowing longer names. + - stockholm - A richly annotated alignment file format used by PFAM. + - mauve - Output from progressiveMauve/Mauve + +Note that while Bio.AlignIO can read all the above file formats, it cannot +write to all of them. + +You can also use any file format supported by Bio.SeqIO, such as "fasta" or +"ig" (which are listed above), PROVIDED the sequences in your file are all the +same length. +""" + +# TODO +# - define policy on reading aligned sequences with gaps in +# (e.g. - and . characters) +# +# - Can we build the to_alignment(...) functionality +# into the generic Alignment class instead? +# +# - How best to handle unique/non unique record.id when writing. +# For most file formats reading such files is fine; The stockholm +# parser would fail. +# +# - MSF multiple alignment format, aka GCG, aka PileUp format (*.msf) +# http://www.bioperl.org/wiki/MSF_multiple_alignment_format +from Bio.Align import MultipleSeqAlignment +from Bio.File import as_handle + +from . import ClustalIO +from . import EmbossIO +from . import FastaIO +from . import MafIO +from . import MauveIO +from . import MsfIO +from . import NexusIO +from . import PhylipIO +from . import StockholmIO + +# Convention for format names is "mainname-subtype" in lower case. +# Please use the same names as BioPerl and EMBOSS where possible. + +_FormatToIterator = { # "fasta" is done via Bio.SeqIO + "clustal": ClustalIO.ClustalIterator, + "emboss": EmbossIO.EmbossIterator, + "fasta-m10": FastaIO.FastaM10Iterator, + "maf": MafIO.MafIterator, + "mauve": MauveIO.MauveIterator, + "msf": MsfIO.MsfIterator, + "nexus": NexusIO.NexusIterator, + "phylip": PhylipIO.PhylipIterator, + "phylip-sequential": PhylipIO.SequentialPhylipIterator, + "phylip-relaxed": PhylipIO.RelaxedPhylipIterator, + "stockholm": StockholmIO.StockholmIterator, +} + +_FormatToWriter = { # "fasta" is done via Bio.SeqIO + "clustal": ClustalIO.ClustalWriter, + "maf": MafIO.MafWriter, + "mauve": MauveIO.MauveWriter, + "nexus": NexusIO.NexusWriter, + "phylip": PhylipIO.PhylipWriter, + "phylip-sequential": PhylipIO.SequentialPhylipWriter, + "phylip-relaxed": PhylipIO.RelaxedPhylipWriter, + "stockholm": StockholmIO.StockholmWriter, +} + + +def write(alignments, handle, format): + """Write complete set of alignments to a file. + + Arguments: + - alignments - A list (or iterator) of MultipleSeqAlignment objects, + or a single alignment object. + - handle - File handle object to write to, or filename as string + (note older versions of Biopython only took a handle). + - format - lower case string describing the file format to write. + + You should close the handle after calling this function. + + Returns the number of alignments written (as an integer). + """ + from Bio import SeqIO + + # Try and give helpful error messages: + if not isinstance(format, str): + raise TypeError("Need a string for the file format (lower case)") + if not format: + raise ValueError("Format required (lower case string)") + if format != format.lower(): + raise ValueError(f"Format string '{format}' should be lower case") + + if isinstance(alignments, MultipleSeqAlignment): + # This raised an exception in older versions of Biopython + alignments = [alignments] + + with as_handle(handle, "w") as fp: + # Map the file format to a writer class + if format in _FormatToWriter: + writer_class = _FormatToWriter[format] + count = writer_class(fp).write_file(alignments) + elif format in SeqIO._FormatToWriter: + # Exploit the existing SeqIO parser to do the dirty work! + # TODO - Can we make one call to SeqIO.write() and count the alignments? + count = 0 + for alignment in alignments: + if not isinstance(alignment, MultipleSeqAlignment): + raise TypeError( + "Expect a list or iterator of MultipleSeqAlignment " + "objects, got: %r" % alignment + ) + SeqIO.write(alignment, fp, format) + count += 1 + elif format in _FormatToIterator or format in SeqIO._FormatToIterator: + raise ValueError(f"Reading format '{format}' is supported, but not writing") + else: + raise ValueError(f"Unknown format '{format}'") + + if not isinstance(count, int): + raise RuntimeError( + "Internal error - the underlying %s " + "writer should have returned the alignment count, not %r" % (format, count) + ) + + return count + + +# This is a generator function! +def _SeqIO_to_alignment_iterator(handle, format, seq_count=None): + """Use Bio.SeqIO to create an MultipleSeqAlignment iterator (PRIVATE). + + Arguments: + - handle - handle to the file. + - format - string describing the file format. + - seq_count - Optional integer, number of sequences expected in each + alignment. Recommended for fasta format files. + + If count is omitted (default) then all the sequences in the file are + combined into a single MultipleSeqAlignment. + """ + from Bio import SeqIO + + if format not in SeqIO._FormatToIterator: + raise ValueError(f"Unknown format '{format}'") + + if seq_count: + # Use the count to split the records into batches. + seq_record_iterator = SeqIO.parse(handle, format) + + records = [] + for record in seq_record_iterator: + records.append(record) + if len(records) == seq_count: + yield MultipleSeqAlignment(records) + records = [] + if records: + raise ValueError("Check seq_count argument, not enough sequences?") + else: + # Must assume that there is a single alignment using all + # the SeqRecord objects: + records = list(SeqIO.parse(handle, format)) + if records: + yield MultipleSeqAlignment(records) + + +def parse(handle, format, seq_count=None): + """Iterate over an alignment file as MultipleSeqAlignment objects. + + Arguments: + - handle - handle to the file, or the filename as a string + (note older versions of Biopython only took a handle). + - format - string describing the file format. + - seq_count - Optional integer, number of sequences expected in each + alignment. Recommended for fasta format files. + + If you have the file name in a string 'filename', use: + + >>> from Bio import AlignIO + >>> filename = "Emboss/needle.txt" + >>> format = "emboss" + >>> for alignment in AlignIO.parse(filename, format): + ... print("Alignment of length %i" % alignment.get_alignment_length()) + Alignment of length 124 + Alignment of length 119 + Alignment of length 120 + Alignment of length 118 + Alignment of length 125 + + If you have a string 'data' containing the file contents, use:: + + from Bio import AlignIO + from io import StringIO + my_iterator = AlignIO.parse(StringIO(data), format) + + Use the Bio.AlignIO.read() function when you expect a single record only. + """ + from Bio import SeqIO + + # Try and give helpful error messages: + if not isinstance(format, str): + raise TypeError("Need a string for the file format (lower case)") + if not format: + raise ValueError("Format required (lower case string)") + if format != format.lower(): + raise ValueError(f"Format string '{format}' should be lower case") + if seq_count is not None and not isinstance(seq_count, int): + raise TypeError("Need integer for seq_count (sequences per alignment)") + + with as_handle(handle) as fp: + # Map the file format to a sequence iterator: + if format in _FormatToIterator: + iterator_generator = _FormatToIterator[format] + i = iterator_generator(fp, seq_count) + + elif format in SeqIO._FormatToIterator: + # Exploit the existing SeqIO parser to the dirty work! + i = _SeqIO_to_alignment_iterator(fp, format, seq_count=seq_count) + else: + raise ValueError(f"Unknown format '{format}'") + + yield from i + + +def read(handle, format, seq_count=None): + """Turn an alignment file into a single MultipleSeqAlignment object. + + Arguments: + - handle - handle to the file, or the filename as a string + (note older versions of Biopython only took a handle). + - format - string describing the file format. + - seq_count - Optional integer, number of sequences expected in each + alignment. Recommended for fasta format files. + + If the handle contains no alignments, or more than one alignment, + an exception is raised. For example, using a PFAM/Stockholm file + containing one alignment: + + >>> from Bio import AlignIO + >>> filename = "Clustalw/protein.aln" + >>> format = "clustal" + >>> alignment = AlignIO.read(filename, format) + >>> print("Alignment of length %i" % alignment.get_alignment_length()) + Alignment of length 411 + + If however you want the first alignment from a file containing + multiple alignments this function would raise an exception. + + >>> from Bio import AlignIO + >>> filename = "Emboss/needle.txt" + >>> format = "emboss" + >>> alignment = AlignIO.read(filename, format) + Traceback (most recent call last): + ... + ValueError: More than one record found in handle + + Instead use: + + >>> from Bio import AlignIO + >>> filename = "Emboss/needle.txt" + >>> format = "emboss" + >>> alignment = next(AlignIO.parse(filename, format)) + >>> print("First alignment has length %i" % alignment.get_alignment_length()) + First alignment has length 124 + + You must use the Bio.AlignIO.parse() function if you want to read multiple + records from the handle. + """ + iterator = parse(handle, format, seq_count) + try: + alignment = next(iterator) + except StopIteration: + raise ValueError("No records found in handle") from None + try: + next(iterator) + raise ValueError("More than one record found in handle") + except StopIteration: + pass + if seq_count: + if len(alignment) != seq_count: + raise RuntimeError( + "More sequences found in alignment than specified in seq_count: %s." + % seq_count + ) + return alignment + + +def convert(in_file, in_format, out_file, out_format, molecule_type=None): + """Convert between two alignment files, returns number of alignments. + + Arguments: + - in_file - an input handle or filename + - in_format - input file format, lower case string + - output - an output handle or filename + - out_file - output file format, lower case string + - molecule_type - optional molecule type to apply, string containing + "DNA", "RNA" or "protein". + + **NOTE** - If you provide an output filename, it will be opened which will + overwrite any existing file without warning. This may happen if even the + conversion is aborted (e.g. an invalid out_format name is given). + + Some output formats require the molecule type be specified where this + cannot be determined by the parser. For example, converting to FASTA, + Clustal, or PHYLIP format to NEXUS: + + >>> from io import StringIO + >>> from Bio import AlignIO + >>> handle = StringIO() + >>> AlignIO.convert("Phylip/horses.phy", "phylip", handle, "nexus", "DNA") + 1 + >>> print(handle.getvalue()) + #NEXUS + begin data; + dimensions ntax=10 nchar=40; + format datatype=dna missing=? gap=-; + matrix + Mesohippus AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + Hypohippus AAACCCCCCCAAAAAAAAACAAAAAAAAAAAAAAAAAAAA + Archaeohip CAAAAAAAAAAAAAAAACACAAAAAAAAAAAAAAAAAAAA + Parahippus CAAACAACAACAAAAAAAACAAAAAAAAAAAAAAAAAAAA + Merychippu CCAACCACCACCCCACACCCAAAAAAAAAAAAAAAAAAAA + 'M. secundu' CCAACCACCACCCACACCCCAAAAAAAAAAAAAAAAAAAA + Nannipus CCAACCACAACCCCACACCCAAAAAAAAAAAAAAAAAAAA + Neohippari CCAACCCCCCCCCCACACCCAAAAAAAAAAAAAAAAAAAA + Calippus CCAACCACAACCCACACCCCAAAAAAAAAAAAAAAAAAAA + Pliohippus CCCACCCCCCCCCACACCCCAAAAAAAAAAAAAAAAAAAA + ; + end; + + """ + if molecule_type: + if not isinstance(molecule_type, str): + raise TypeError(f"Molecule type should be a string, not {molecule_type!r}") + elif ( + "DNA" in molecule_type + or "RNA" in molecule_type + or "protein" in molecule_type + ): + pass + else: + raise ValueError(f"Unexpected molecule type, {molecule_type!r}") + + # TODO - Add optimised versions of important conversions + # For now just off load the work to SeqIO parse/write + # Don't open the output file until we've checked the input is OK: + alignments = parse(in_file, in_format, None) + + if molecule_type: + # Edit the records on the fly to set molecule type + + def over_ride(alignment): + """Over-ride molecule in-place.""" + for record in alignment: + record.annotations["molecule_type"] = molecule_type + return alignment + + alignments = (over_ride(_) for _ in alignments) + return write(alignments, out_file, out_format) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/ClustalIO.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/ClustalIO.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06b8800fdfc5b39468fcf39a18fbe2c6539c5475 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/ClustalIO.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/EmbossIO.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/EmbossIO.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ed1453d5b40af9ab9ebb3437d28fcacda62f8f2 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/EmbossIO.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/FastaIO.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/FastaIO.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8289b17efeb219d273220a67594c5088ae9925f Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/FastaIO.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/Interfaces.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/Interfaces.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19761122d770c0ac844a0e6d4517a3764dc87329 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/Interfaces.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/MafIO.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/MafIO.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc98ed2bf3e9b0df9f8809ca249300d75ac15473 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/MafIO.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/MauveIO.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/MauveIO.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ba060baa1b3b5a97bd345c20caa19d34ef2aa0a Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/MauveIO.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/MsfIO.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/MsfIO.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bf89a42c04e42420814ea05edf328f270a588b4 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/MsfIO.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/NexusIO.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/NexusIO.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90c37d57927548084865a1811d024c92b08fed1b Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/NexusIO.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/PhylipIO.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/PhylipIO.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..012491bfbdce33ea3c3aa424977b6262cfb92358 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/PhylipIO.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/StockholmIO.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/StockholmIO.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2ca9831e84ecb25afe97c55573ee117be95b2bd Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/StockholmIO.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..129b8613d6bd42c749df696d14bc258e23092a6b Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/AlignIO/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Alphabet/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Alphabet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5940d68bd73cd99da89cd72013c0d683d3dfa35f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Alphabet/__init__.py @@ -0,0 +1,22 @@ +# Copyright 2000-2002 by Andrew Dalke. +# Revisions copyright 2007-2010 by Peter Cock. +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Alphabets were previously used to declare sequence type and letters (OBSOLETE). + +The design of Bio.Alphabet included a number of historic design choices +which, with the benefit of hindsight, were regretable. Bio.Alphabet was +therefore removed from Biopython in release 1.78. Instead, the molecule type is +included as an annotation on SeqRecords where appropriate. + +Please see https://biopython.org/wiki/Alphabet for examples showing how to +transition from Bio.Alphabet to molecule type annotations. +""" + +raise ImportError( + "Bio.Alphabet has been removed from Biopython. In many cases, the alphabet can simply be ignored and removed from scripts. In a few cases, you may need to specify the ``molecule_type`` as an annotation on a SeqRecord for your script to work correctly. Please see https://biopython.org/wiki/Alphabet for more information." +) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Alphabet/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Alphabet/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..257e7b037ae523be521800f155fcd29e0d02a44a Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Alphabet/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Blast/NCBIWWW.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Blast/NCBIWWW.py new file mode 100644 index 0000000000000000000000000000000000000000..ce233ae061d4c14ded78e7f83e4a01683e48830a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Blast/NCBIWWW.py @@ -0,0 +1,373 @@ +# Copyright 1999 by Jeffrey Chang. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Patched by Brad Chapman. +# Chris Wroe added modifications for work in myGrid + +"""Code to invoke the NCBI BLAST server over the internet. + +This module provides code to work with the WWW version of BLAST +provided by the NCBI. https://blast.ncbi.nlm.nih.gov/ + +Variables: + + - email Set the Blast email parameter (default is None). + - tool Set the Blast tool parameter (default is ``biopython``). + +""" + +import time +import warnings +from io import StringIO +from urllib.parse import urlencode +from urllib.request import build_opener +from urllib.request import HTTPBasicAuthHandler +from urllib.request import HTTPPasswordMgrWithDefaultRealm +from urllib.request import install_opener +from urllib.request import Request +from urllib.request import urlopen + +from Bio import BiopythonWarning +from Bio._utils import function_with_previous + +email = None +tool = "biopython" + + +NCBI_BLAST_URL = "https://blast.ncbi.nlm.nih.gov/Blast.cgi" + + +@function_with_previous +def qblast( + program, + database, + sequence, + url_base=NCBI_BLAST_URL, + auto_format=None, + composition_based_statistics=None, + db_genetic_code=None, + endpoints=None, + entrez_query="(none)", + expect=10.0, + filter=None, + gapcosts=None, + genetic_code=None, + hitlist_size=50, + i_thresh=None, + layout=None, + lcase_mask=None, + matrix_name=None, + nucl_penalty=None, + nucl_reward=None, + other_advanced=None, + perc_ident=None, + phi_pattern=None, + query_file=None, + query_believe_defline=None, + query_from=None, + query_to=None, + searchsp_eff=None, + service=None, + threshold=None, + ungapped_alignment=None, + word_size=None, + short_query=None, + alignments=500, + alignment_view=None, + descriptions=500, + entrez_links_new_window=None, + expect_low=None, + expect_high=None, + format_entrez_query=None, + format_object=None, + format_type="XML", + ncbi_gi=None, + results_file=None, + show_overview=None, + megablast=None, + template_type=None, + template_length=None, + username="blast", + password=None, +): + """BLAST search using NCBI's QBLAST server. + + Supports all parameters of the old qblast API for Put and Get. + + Please note that NCBI uses the new Common URL API for BLAST searches + on the internet (https://blast.ncbi.nlm.nih.gov/doc/blast-help/urlapi.html). + Thus, some of the parameters used by this function are not (or are no longer) + officially supported by NCBI. Although they are still functioning, this + may change in the future. + + Some useful parameters: + + - program blastn, blastp, blastx, tblastn, or tblastx (lower case) + - database Which database to search against (e.g. "nr"). + - sequence The sequence to search. + - ncbi_gi TRUE/FALSE whether to give 'gi' identifier. + - descriptions Number of descriptions to show. Def 500. + - alignments Number of alignments to show. Def 500. + - expect An expect value cutoff. Def 10.0. + - matrix_name Specify an alt. matrix (PAM30, PAM70, BLOSUM80, BLOSUM45). + - filter "none" turns off filtering. Default no filtering + - format_type "HTML", "Text", "ASN.1", or "XML". Def. "XML". + - entrez_query Entrez query to limit Blast search - only applies when searching nucleotide BLASTDBs + - hitlist_size Number of hits to return. Default 50 + - megablast TRUE/FALSE whether to use MEga BLAST algorithm (blastn only) + - short_query TRUE/FALSE whether to adjust the search parameters for a + short query sequence. Note that this will override + manually set parameters like word size and e value. Turns + off when sequence length is > 30 residues. Default: None. + - service plain, psi, phi, rpsblast, megablast (lower case) + + This function does no checking of the validity of the parameters + and passes the values to the server as is. More help is available at: + https://blast.ncbi.nlm.nih.gov/doc/blast-help/urlapi.html + + """ + programs = ["blastn", "blastp", "blastx", "tblastn", "tblastx"] + if program not in programs: + raise ValueError( + f"Program specified is {program}. Expected one of {', '.join(programs)}" + ) + + # SHORT_QUERY_ADJUST throws an error when using blastn (wrong parameter + # assignment from NCBIs side). + # Thus we set the (known) parameters directly: + if short_query and program == "blastn": + short_query = None + # We only use the 'short-query' parameters for short sequences: + if len(sequence) < 31: + expect = 1000 + word_size = 7 + nucl_reward = 1 + filter = None + lcase_mask = None + warnings.warn( + '"SHORT_QUERY_ADJUST" is incorrectly implemented (by NCBI) for blastn.' + " We bypass the problem by manually adjusting the search parameters." + " Thus, results may slightly differ from web page searches.", + BiopythonWarning, + ) + + # Format the "Put" command, which sends search requests to qblast. + # Parameters taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node5.html on 9 July 2007 + # Additional parameters are taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node9.html on 8 Oct 2010 + # To perform a PSI-BLAST or PHI-BLAST search the service ("Put" and "Get" commands) must be specified + # (e.g. psi_blast = NCBIWWW.qblast("blastp", "refseq_protein", input_sequence, service="psi")) + parameters = { + "AUTO_FORMAT": auto_format, + "COMPOSITION_BASED_STATISTICS": composition_based_statistics, + "DATABASE": database, + "DB_GENETIC_CODE": db_genetic_code, + "ENDPOINTS": endpoints, + "ENTREZ_QUERY": entrez_query, + "EXPECT": expect, + "FILTER": filter, + "GAPCOSTS": gapcosts, + "GENETIC_CODE": genetic_code, + "HITLIST_SIZE": hitlist_size, + "I_THRESH": i_thresh, + "LAYOUT": layout, + "LCASE_MASK": lcase_mask, + "MEGABLAST": megablast, + "MATRIX_NAME": matrix_name, + "NUCL_PENALTY": nucl_penalty, + "NUCL_REWARD": nucl_reward, + "OTHER_ADVANCED": other_advanced, + "PERC_IDENT": perc_ident, + "PHI_PATTERN": phi_pattern, + "PROGRAM": program, + # ('PSSM': pssm: - It is possible to use PSI-BLAST via this API? + "QUERY": sequence, + "QUERY_FILE": query_file, + "QUERY_BELIEVE_DEFLINE": query_believe_defline, + "QUERY_FROM": query_from, + "QUERY_TO": query_to, + # 'RESULTS_FILE': ...: - Can we use this parameter? + "SEARCHSP_EFF": searchsp_eff, + "SERVICE": service, + "SHORT_QUERY_ADJUST": short_query, + "TEMPLATE_TYPE": template_type, + "TEMPLATE_LENGTH": template_length, + "THRESHOLD": threshold, + "UNGAPPED_ALIGNMENT": ungapped_alignment, + "WORD_SIZE": word_size, + "CMD": "Put", + } + + if password is not None: + # handle authentication for BLAST cloud + password_mgr = HTTPPasswordMgrWithDefaultRealm() + password_mgr.add_password(None, url_base, username, password) + handler = HTTPBasicAuthHandler(password_mgr) + opener = build_opener(handler) + install_opener(opener) + + if url_base == NCBI_BLAST_URL: + parameters.update({"email": email, "tool": tool}) + parameters = {key: value for key, value in parameters.items() if value is not None} + message = urlencode(parameters).encode() + request = Request(url_base, message, {"User-Agent": "BiopythonClient"}) + # Send off the initial query to qblast. + # Note the NCBI do not currently impose a rate limit here, other + # than the request not to make say 50 queries at once using multiple + # threads. + handle = urlopen(request) + + # Format the "Get" command, which gets the formatted results from qblast + # Parameters taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node6.html on 9 July 2007 + rid, rtoe = _parse_qblast_ref_page(handle) + parameters = { + "ALIGNMENTS": alignments, + "ALIGNMENT_VIEW": alignment_view, + "DESCRIPTIONS": descriptions, + "ENTREZ_LINKS_NEW_WINDOW": entrez_links_new_window, + "EXPECT_LOW": expect_low, + "EXPECT_HIGH": expect_high, + "FORMAT_ENTREZ_QUERY": format_entrez_query, + "FORMAT_OBJECT": format_object, + "FORMAT_TYPE": format_type, + "NCBI_GI": ncbi_gi, + "RID": rid, + "RESULTS_FILE": results_file, + "SERVICE": service, + "SHOW_OVERVIEW": show_overview, + "CMD": "Get", + } + parameters = {key: value for key, value in parameters.items() if value is not None} + message = urlencode(parameters).encode() + + # Poll NCBI until the results are ready. + # https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=DeveloperInfo + # 1. Do not contact the server more often than once every 10 seconds. + # 2. Do not poll for any single RID more often than once a minute. + # 3. Use the URL parameter email and tool, so that the NCBI + # can contact you if there is a problem. + # 4. Run scripts weekends or between 9 pm and 5 am Eastern time + # on weekdays if more than 50 searches will be submitted. + # -- + # Could start with a 10s delay, but expect most short queries + # will take longer thus at least 70s with delay. Therefore, + # start with 20s delay, thereafter once a minute. + delay = 20 # seconds + start_time = time.time() + while True: + current = time.time() + wait = qblast.previous + delay - current + if wait > 0: + time.sleep(wait) + qblast.previous = current + wait + else: + qblast.previous = current + # delay by at least 60 seconds only if running the request against the public NCBI API + if delay < 60 and url_base == NCBI_BLAST_URL: + # Wasn't a quick return, must wait at least a minute + delay = 60 + elapsed = time.time() - start_time + # Throw a warning if search takes longer than ten minutes + if elapsed >= 600: + warnings.warn( + f"BLAST request {rid} is taking longer than 10 minutes, consider re-issuing it", + BiopythonWarning, + ) + + request = Request(url_base, message, {"User-Agent": "BiopythonClient"}) + handle = urlopen(request) + results = handle.read().decode() + + # Can see an "\n\n" page while results are in progress, + # if so just wait a bit longer... + if results == "\n\n": + continue + # XML results don't have the Status tag when finished + if "Status=" not in results: + break + i = results.index("Status=") + j = results.index("\n", i) + status = results[i + len("Status=") : j].strip() + if status.upper() == "READY": + break + return StringIO(results) + + +qblast.previous = 0 + + +def _parse_qblast_ref_page(handle): + """Extract a tuple of RID, RTOE from the 'please wait' page (PRIVATE). + + The NCBI FAQ pages use TOE for 'Time of Execution', so RTOE is probably + 'Request Time of Execution' and RID would be 'Request Identifier'. + """ + s = handle.read().decode() + i = s.find("RID =") + if i == -1: + rid = None + else: + j = s.find("\n", i) + rid = s[i + len("RID =") : j].strip() + + i = s.find("RTOE =") + if i == -1: + rtoe = None + else: + j = s.find("\n", i) + rtoe = s[i + len("RTOE =") : j].strip() + + if not rid and not rtoe: + # Can we reliably extract the error message from the HTML page? + # e.g. "Message ID#24 Error: Failed to read the Blast query: + # Nucleotide FASTA provided for protein sequence" + # or "Message ID#32 Error: Query contains no data: Query + # contains no sequence data" + # + # This used to occur inside a
entry: + i = s.find('
') + if i != -1: + msg = s[i + len('
') :].strip() + msg = msg.split("
", 1)[0].split("\n", 1)[0].strip() + if msg: + raise ValueError(f"Error message from NCBI: {msg}") + # In spring 2010 the markup was like this: + i = s.find('

') + if i != -1: + msg = s[i + len('

') :].strip() + msg = msg.split("

", 1)[0].split("\n", 1)[0].strip() + if msg: + raise ValueError(f"Error message from NCBI: {msg}") + # Generic search based on the way the error messages start: + i = s.find("Message ID#") + if i != -1: + # Break the message at the first HTML tag + msg = s[i:].split("<", 1)[0].split("\n", 1)[0].strip() + raise ValueError(f"Error message from NCBI: {msg}") + # We didn't recognise the error layout :( + # print(s) + raise ValueError( + "No RID and no RTOE found in the 'please wait' page, " + "there was probably an error in your request but we " + "could not extract a helpful error message." + ) + elif not rid: + # Can this happen? + raise ValueError( + f"No RID found in the 'please wait' page. (although RTOE = {rtoe!r})" + ) + elif not rtoe: + # Can this happen? + raise ValueError( + f"No RTOE found in the 'please wait' page. (although RID = {rid!r})" + ) + + try: + return rid, int(rtoe) + except ValueError: + raise ValueError( + f"A non-integer RTOE found in the 'please wait' page, {rtoe!r}" + ) from None diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Blast/NCBIXML.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Blast/NCBIXML.py new file mode 100644 index 0000000000000000000000000000000000000000..094d2b428921de87a6f92165b373ae1eaf646621 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Blast/NCBIXML.py @@ -0,0 +1,1331 @@ +# Copyright 1999-2000 by Jeffrey Chang. All rights reserved. +# Copyright 2000 by Bertrand Frottier. All rights reserved. +# Revisions 2005-2006 copyright Michiel de Hoon +# Revisions 2006-2009 copyright Peter Cock +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Code to work with the BLAST XML output. + +The BLAST XML DTD file is available on the NCBI site at: +https://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd + +Record classes to hold BLAST output are: + +Classes: +Blast Holds all the information from a blast search. +PSIBlast Holds all the information from a psi-blast search. + +Header Holds information from the header. +Description Holds information about one hit description. +Alignment Holds information about one alignment hit. +HSP Holds information about one HSP. +MultipleAlignment Holds information about a multiple alignment. +DatabaseReport Holds information from the database report. +Parameters Holds information from the parameters. + +""" +# XXX finish printable BLAST output + +import sys +import warnings +import xml.sax +from xml.sax.handler import ContentHandler + +from Bio import BiopythonParserWarning + +from Bio.Align import MultipleSeqAlignment +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +def fmt_(value, format_spec="%s", default_str=""): + """Ensure the given value formats to a string correctly.""" + if value is None: + return default_str + return format_spec % value + + +class Header: + """Saves information from a blast header. + + Members: + application The name of the BLAST flavor that generated this data. + version Version of blast used. + date Date this data was generated. + reference Reference for blast. + + query Name of query sequence. + query_letters Number of letters in the query sequence. (int) + + database Name of the database. + database_sequences Number of sequences in the database. (int) + database_letters Number of letters in the database. (int) + + """ + + def __init__(self): + """Initialize the class.""" + self.application = "" + self.version = "" + self.date = "" + self.reference = "" + + self.query = "" + self.query_letters = None + + self.database = "" + self.database_sequences = None + self.database_letters = None + + +class Description: + """Stores information about one hit in the descriptions section. + + Members: + title Title of the hit. + score Number of bits. (int) + bits Bit score. (float) + e E value. (float) + num_alignments Number of alignments for the same subject. (int) + """ + + def __init__(self): + """Initialize the class.""" + self.title = "" + self.score = None + self.bits = None + self.e = None + self.num_alignments = None + + def __str__(self): + """Return the description as a string.""" + return f"{self.title:<66} {self.score:>5} {self.e}" + + +class DescriptionExt(Description): + """Extended description record for BLASTXML version 2. + + Members: + items List of DescriptionExtItem + """ + + def __init__(self): + """Initialize the class.""" + super().__init__() + + self.items = [] + + def append_item(self, item): + """Add a description extended record.""" + if len(self.items) == 0: + self.title = str(item) + self.items.append(item) + + +class DescriptionExtItem: + """Stores information about one record in hit description for BLASTXML version 2. + + Members: + id Database identifier + title Title of the hit. + """ + + def __init__(self): + """Initialize the class.""" + self.id = None + self.title = None + self.accession = None + self.taxid = None + self.sciname = None + + def __str__(self): + """Return the description identifier and title as a string.""" + return f"{self.id} {self.title}" + + +class Alignment: + """Stores information about one hit in the alignments section. + + Members: + title Name. + hit_id Hit identifier. (str) + hit_def Hit definition. (str) + length Length. (int) + hsps A list of HSP objects. + + """ + + def __init__(self): + """Initialize the class.""" + self.title = "" + self.hit_id = "" + self.hit_def = "" + self.length = None + self.hsps = [] + + def __str__(self): + """Return the BLAST alignment as a formatted string.""" + lines = self.title.split("\n") + lines.append(f"Length = {self.length}\n") + return "\n ".join(lines) + + +class HSP: + """Stores information about one hsp in an alignment hit. + + Members: + - score BLAST score of hit. (float) + - bits Number of bits for that score. (float) + - expect Expect value. (float) + - num_alignments Number of alignments for same subject. (int) + - identities Number of identities (int) if using the XML parser. + Tuple of number of identities/total aligned (int, int) + if using the (obsolete) plain text parser. + - positives Number of positives (int) if using the XML parser. + Tuple of number of positives/total aligned (int, int) + if using the (obsolete) plain text parser. + - gaps Number of gaps (int) if using the XML parser. + Tuple of number of gaps/total aligned (int, int) if + using the (obsolete) plain text parser. + - align_length Length of the alignment. (int) + - strand Tuple of (query, target) strand. + - frame Tuple of 1 or 2 frame shifts, depending on the flavor. + + - query The query sequence. + - query_start The start residue for the query sequence. (1-based) + - query_end The end residue for the query sequence. (1-based) + - match The match sequence. + - sbjct The sbjct sequence. + - sbjct_start The start residue for the sbjct sequence. (1-based) + - sbjct_end The end residue for the sbjct sequence. (1-based) + + Not all flavors of BLAST return values for every attribute:: + + score expect identities positives strand frame + BLASTP X X X X + BLASTN X X X X X + BLASTX X X X X X + TBLASTN X X X X X + TBLASTX X X X X X/X + + Note: for BLASTX, the query sequence is shown as a protein sequence, + but the numbering is based on the nucleotides. Thus, the numbering + is 3x larger than the number of amino acid residues. A similar effect + can be seen for the sbjct sequence in TBLASTN, and for both sequences + in TBLASTX. + + Also, for negative frames, the sequence numbering starts from + query_start and counts down. + + """ + + def __init__(self): + """Initialize the class.""" + self.score = None + self.bits = None + self.expect = None + self.num_alignments = None + self.identities = (None, None) + self.positives = (None, None) + self.gaps = (None, None) + self.align_length = None + self.strand = (None, None) + self.frame = () + + self.query = "" + self.query_start = None + self.query_end = None + self.match = "" + self.sbjct = "" + self.sbjct_start = None + self.sbjct_end = None + + def __str__(self): + """Return the BLAST HSP as a formatted string.""" + lines = [ + "Score %s (%s bits), expectation %s, alignment length %s" + % ( + fmt_(self.score, "%i"), + fmt_(self.bits, "%i"), + fmt_(self.expect, "%0.1e"), + fmt_(self.align_length, "%i"), + ) + ] + if self.align_length is None: + return "\n".join(lines) + if self.align_length < 50: + lines.append( + "Query:%8s %s %s" % (self.query_start, self.query, self.query_end) + ) + lines.append(f" {self.match}") + lines.append( + "Sbjct:%8s %s %s" % (self.sbjct_start, self.sbjct, self.sbjct_end) + ) + else: + lines.append( + "Query:%8s %s...%s %s" + % (self.query_start, self.query[:45], self.query[-3:], self.query_end) + ) + lines.append(f" {self.match[:45]}...{self.match[-3:]}") + lines.append( + "Sbjct:%8s %s...%s %s" + % (self.sbjct_start, self.sbjct[:45], self.sbjct[-3:], self.sbjct_end) + ) + return "\n".join(lines) + + +class MultipleAlignment: + """Holds information about a multiple alignment. + + Members: + alignment A list of tuples (name, start residue, sequence, end residue). + + The start residue is 1-based. It may be blank, if that sequence is + not aligned in the multiple alignment. + + """ + + def __init__(self): + """Initialize the class.""" + self.alignment = [] + + def to_generic(self): + """Retrieve generic alignment object for the given alignment. + + Instead of the tuples, this returns a MultipleSeqAlignment object + from Bio.Align, through which you can manipulate and query + the object. + + Thanks to James Casbon for the code. + """ + seq_parts = [] + seq_names = [] + parse_number = 0 + n = 0 + for name, start, seq, end in self.alignment: + if name == "QUERY": # QUERY is the first in each alignment block + parse_number += 1 + n = 0 + + if parse_number == 1: # create on first_parse, append on all others + seq_parts.append(seq) + seq_names.append(name) + else: + seq_parts[n] += seq + n += 1 + + records = ( + SeqRecord(Seq(seq), name) for (name, seq) in zip(seq_names, seq_parts) + ) + return MultipleSeqAlignment(records) + + +class Round: + """Holds information from a PSI-BLAST round. + + Members: + number Round number. (int) + reused_seqs Sequences in model, found again. List of Description objects. + new_seqs Sequences not found, or below threshold. List of Description. + alignments A list of Alignment objects. + multiple_alignment A MultipleAlignment object. + """ + + def __init__(self): + """Initialize the class.""" + self.number = None + self.reused_seqs = [] + self.new_seqs = [] + self.alignments = [] + self.multiple_alignment = None + + +class DatabaseReport: + """Holds information about a database report. + + Members: + database_name List of database names. (can have multiple dbs) + num_letters_in_database Number of letters in the database. (int) + num_sequences_in_database List of number of sequences in the database. + posted_date List of the dates the databases were posted. + ka_params A tuple of (lambda, k, h) values. (floats) + gapped # XXX this isn't set right! + ka_params_gap A tuple of (lambda, k, h) values. (floats) + + """ + + def __init__(self): + """Initialize the class.""" + self.database_name = [] + self.posted_date = [] + self.num_letters_in_database = [] + self.num_sequences_in_database = [] + self.ka_params = (None, None, None) + self.gapped = 0 + self.ka_params_gap = (None, None, None) + + +class Parameters: + """Holds information about the parameters. + + Members: + matrix Name of the matrix. + gap_penalties Tuple of (open, extend) penalties. (floats) + sc_match Match score for nucleotide-nucleotide comparison + sc_mismatch Mismatch penalty for nucleotide-nucleotide comparison + num_hits Number of hits to the database. (int) + num_sequences Number of sequences. (int) + num_good_extends Number of extensions. (int) + num_seqs_better_e Number of sequences better than e-value. (int) + hsps_no_gap Number of HSP's better, without gapping. (int) + hsps_prelim_gapped Number of HSP's gapped in prelim test. (int) + hsps_prelim_gapped_attemped Number of HSP's attempted in prelim. (int) + hsps_gapped Total number of HSP's gapped. (int) + query_length Length of the query. (int) + query_id Identifier of the query sequence. (str) + database_length Number of letters in the database. (int) + effective_hsp_length Effective HSP length. (int) + effective_query_length Effective length of query. (int) + effective_database_length Effective length of database. (int) + effective_search_space Effective search space. (int) + effective_search_space_used Effective search space used. (int) + frameshift Frameshift window. Tuple of (int, float) + threshold Threshold. (int) + window_size Window size. (int) + dropoff_1st_pass Tuple of (score, bits). (int, float) + gap_x_dropoff Tuple of (score, bits). (int, float) + gap_x_dropoff_final Tuple of (score, bits). (int, float) + gap_trigger Tuple of (score, bits). (int, float) + blast_cutoff Tuple of (score, bits). (int, float) + """ + + def __init__(self): + """Initialize the class.""" + self.matrix = "" + self.gap_penalties = (None, None) + self.sc_match = None + self.sc_mismatch = None + self.num_hits = None + self.num_sequences = None + self.num_good_extends = None + self.num_seqs_better_e = None + self.hsps_no_gap = None + self.hsps_prelim_gapped = None + self.hsps_prelim_gapped_attemped = None + self.hsps_gapped = None + self.query_id = None + self.query_length = None + self.database_length = None + self.effective_hsp_length = None + self.effective_query_length = None + self.effective_database_length = None + self.effective_search_space = None + self.effective_search_space_used = None + self.frameshift = (None, None) + self.threshold = None + self.window_size = None + self.dropoff_1st_pass = (None, None) + self.gap_x_dropoff = (None, None) + self.gap_x_dropoff_final = (None, None) + self.gap_trigger = (None, None) + self.blast_cutoff = (None, None) + + +# TODO - Add a friendly __str__ method to BLAST results +class Blast(Header, DatabaseReport, Parameters): + """Saves the results from a blast search. + + Members: + descriptions A list of Description objects. + alignments A list of Alignment objects. + multiple_alignment A MultipleAlignment object. + + members inherited from base classes + + """ + + def __init__(self): + """Initialize the class.""" + Header.__init__(self) + DatabaseReport.__init__(self) + Parameters.__init__(self) + self.descriptions = [] + self.alignments = [] + self.multiple_alignment = None + + +class PSIBlast(Header, DatabaseReport, Parameters): + """Saves the results from a blastpgp search. + + Members: + rounds A list of Round objects. + converged Whether the search converged. + + members inherited from base classes + + """ + + def __init__(self): + """Initialize the class.""" + Header.__init__(self) + DatabaseReport.__init__(self) + Parameters.__init__(self) + self.rounds = [] + self.converged = 0 + + +class _XMLparser(ContentHandler): + """Generic SAX Parser (PRIVATE). + + Just a very basic SAX parser. + + Redefine the methods startElement, characters and endElement. + """ + + def __init__(self, debug=0): + """Initialize the parser. + + Arguments: + - debug - integer, amount of debug information to print + + """ + self._tag = [] + self._value = "" + self._debug = debug + self._debug_ignore_list = [] + self._method_name_level = 1 + self._method_map = None + + def startElement(self, name, attr): + """Found XML start tag. + + No real need of attr, BLAST DTD doesn't use them + + Arguments: + - name -- name of the tag + - attr -- tag attributes + + """ + self._tag.append(name) + + if len(self._tag) == 1: + # root node + self._on_root_node(name) + return + + # Try to call a method (defined in subclasses) + method = "start_" + self._node_method_name(name) + + # Note could use try / except AttributeError + # BUT I found often triggered by nested errors... + if method in self._method_map: + self._method_map[method]() + if self._debug > 4: + sys.stderr.write("NCBIXML: Parsed: " + method + "\n") + elif self._debug > 3: + # Doesn't exist (yet) and may want to warn about it + if method not in self._debug_ignore_list: + sys.stderr.write("NCBIXML: Ignored: " + method + "\n") + self._debug_ignore_list.append(method) + + # We don't care about white space in parent tags like Hsp, + # but that white space doesn't belong to child tags like Hsp_midline + if self._value.strip(): + raise ValueError( + f"What should we do with {self._value} before the {name!r} tag?" + ) + self._value = "" + + def characters(self, ch): + """Found some text. + + Arguments: + - ch -- characters read + + """ + self._value += ch # You don't ever get the whole string + + def endElement(self, name): + """Found XML end tag. + + Arguments: + - name -- tag name + + """ + # DON'T strip any white space, we may need it e.g. the hsp-midline + + # Try to call a method (defined in subclasses) + method = "end_" + self._node_method_name(name) + + # Note could use try / except AttributeError + # BUT I found often triggered by nested errors... + if method in self._method_map: + self._method_map[method]() + if self._debug > 2: + sys.stderr.write(f"NCBIXML: Parsed: {method} {self._value}\n") + elif self._debug > 1: + # Doesn't exist (yet) and may want to warn about it + if method not in self._debug_ignore_list: + sys.stderr.write(f"NCBIXML: Ignored: {method} {self._value}\n") + self._debug_ignore_list.append(method) + + # Reset character buffer + self._value = "" + + self._tag.pop() + + def _node_method_name(self, name): + if self._method_name_level == 1: + return name + return "/".join(self._tag[-self._method_name_level :]) + + +class BlastParser(_XMLparser): + """Parse XML BLAST data into a Blast object. + + Parses XML output from BLAST (direct use discouraged). + This (now) returns a list of Blast records. + Historically it returned a single Blast record. + You are expected to use this via the parse or read functions. + + All XML 'action' methods are private methods and may be: + + - ``_start_TAG`` called when the start tag is found + - ``_end_TAG`` called when the end tag is found + + """ + + def __init__(self, debug=0): + """Initialize the parser. + + Arguments: + - debug - integer, amount of debug information to print + + """ + # Calling superclass method + _XMLparser.__init__(self, debug) + + self._parser = xml.sax.make_parser() + self._parser.setContentHandler(self) + + # To avoid ValueError: unknown url type: NCBI_BlastOutput.dtd + self._parser.setFeature(xml.sax.handler.feature_validation, 0) + self._parser.setFeature(xml.sax.handler.feature_namespaces, 0) + self._parser.setFeature(xml.sax.handler.feature_external_pes, 0) + self._parser.setFeature(xml.sax.handler.feature_external_ges, 0) + + self._xml_version = 1 + + self.reset() + + def reset(self): + """Reset all the data allowing reuse of the BlastParser() object.""" + self._records = [] + self._header = Header() + self._parameters = Parameters() + self._parameters.filter = None # Maybe I should update the class? + + def _on_root_node(self, name): + if name == "BlastOutput": + self._setup_blast_v1() + elif name == "BlastXML2": + self._setup_blast_v2() + else: + raise ValueError( + "Invalid root node name: %s. Root node should be either" + " BlastOutput or BlastXML2" % name + ) + + def _setup_blast_v1(self): + self._method_map = { + "start_Iteration": self._start_blast_record, + "end_Iteration": self._end_blast_record, + "end_BlastOutput_program": self._set_header_application, + "end_BlastOutput_version": self._set_header_version, + "end_BlastOutput_reference": self._set_header_reference, + "end_BlastOutput_db": self._set_header_database, + "end_BlastOutput_query-ID": self._set_header_query_id, + "end_BlastOutput_query-def": self._set_header_query, + "end_BlastOutput_query-len": self._set_header_query_letters, + "end_Iteration_query-ID": self._set_record_query_id, + "end_Iteration_query-def": self._set_record_query_def, + "end_Iteration_query-len": self._set_record_query_letters, + "end_BlastOutput_hits": self._set_record_hits, + "end_Parameters_matrix": self._set_parameters_matrix, + "end_Parameters_expect": self._set_parameters_expect, + "end_Parameters_sc-match": self._set_parameters_sc_match, + "end_Parameters_sc-mismatch": self._set_parameters_sc_mismatch, + "end_Parameters_gap-open": self._set_parameters_gap_penalties, + "end_Parameters_gap-extend": self._set_parameters_gap_extend, + "end_Parameters_filter": self._set_parameters_filter, + "start_Hit": self._start_hit, + "end_Hit": self._end_hit, + "end_Hit_id": self.set_hit_id, + "end_Hit_def": self.set_hit_def, + "end_Hit_accession": self.set_hit_accession, + "end_Hit_len": self.set_hit_len, + "start_Hsp": self._start_hsp, + "end_Hsp_score": self._set_hsp_score, + "end_Hsp_bit-score": self._set_hsp_bit_score, + "end_Hsp_evalue": self._set_hsp_e_value, + "end_Hsp_query-from": self._set_hsp_query_start, + "end_Hsp_query-to": self._set_hsp_query_end, + "end_Hsp_hit-from": self._set_hsp_hit_from, + "end_Hsp_hit-to": self._set_hsp_hit_to, + "end_Hsp_query-frame": self._set_hsp_query_frame, + "end_Hsp_hit-frame": self._set_hsp_hit_frame, + "end_Hsp_identity": self._set_hsp_identity, + "end_Hsp_positive": self._set_hsp_positive, + "end_Hsp_gaps": self._set_hsp_gaps, + "end_Hsp_align-len": self._set_hsp_align_len, + "end_Hsp_qseq": self._set_hsp_query_seq, + "end_Hsp_hseq": self._set_hsp_subject_seq, + "end_Hsp_midline": self._set_hsp_midline, + "end_Statistics_db-num": self._set_statistics_db_num, + "end_Statistics_db-len": self._set_statistics_db_len, + "end_Statistics_hsp-len": self._set_statistics_hsp_len, + "end_Statistics_eff-space": self._set_statistics_eff_space, + "end_Statistics_kappa": self._set_statistics_kappa, + "end_Statistics_lambda": self._set_statistics_lambda, + "end_Statistics_entropy": self._set_statistics_entropy, + } + + def _setup_blast_v2(self): + self._method_name_level = 2 + self._xml_version = 2 + self._method_map = { + "start_report/Report": self._start_blast_record, + "end_report/Report": self._end_blast_record, + "end_Report/program": self._set_header_application, + "end_Report/version": self._set_header_version, + "end_Report/reference": self._set_header_reference, + "end_Target/db": self._set_header_database, + "end_Search/query-id": self._set_record_query_id, + "end_Search/query-title": self._set_record_query_def, + "end_Search/query-len": self._set_record_query_letters, + "end_BlastOutput_hits": self._set_record_hits, + "end_Parameters/matrix": self._set_parameters_matrix, + "end_Parameters/expect": self._set_parameters_expect, + "end_Parameters/sc-match": self._set_parameters_sc_match, + "end_Parameters/sc-mismatch": self._set_parameters_sc_mismatch, + "end_Parameters/gap-open": self._set_parameters_gap_penalties, + "end_Parameters/gap-extend": self._set_parameters_gap_extend, + "end_Parameters/filter": self._set_parameters_filter, + "start_hits/Hit": self._start_hit, + "end_hits/Hit": self._end_hit, + "start_description/HitDescr": self._start_hit_descr_item, + "end_description/HitDescr": self._end_hit_descr_item, + "end_HitDescr/id": self._end_description_id, + "end_HitDescr/accession": self._end_description_accession, + "end_HitDescr/title": self._end_description_title, + "end_HitDescr/taxid": self._end_description_taxid, + "end_HitDescr/sciname": self._end_description_sciname, + "end_Hit/len": self.set_hit_len, + "start_hsps/Hsp": self._start_hsp, + "end_hsps/Hsp": self._end_hsp, + "end_Hsp/score": self._set_hsp_score, + "end_Hsp/bit-score": self._set_hsp_bit_score, + "end_Hsp/evalue": self._set_hsp_e_value, + "end_Hsp/query-from": self._set_hsp_query_start, + "end_Hsp/query-to": self._set_hsp_query_end, + "end_Hsp/hit-from": self._set_hsp_hit_from, + "end_Hsp/hit-to": self._set_hsp_hit_to, + "end_Hsp/query-frame": self._set_hsp_query_frame, + "end_Hsp/hit-frame": self._set_hsp_hit_frame, + "end_Hsp/query-strand": self._set_hsp_query_strand, + "end_Hsp/hit-strand": self._set_hsp_hit_strand, + "end_Hsp/identity": self._set_hsp_identity, + "end_Hsp/positive": self._set_hsp_positive, + "end_Hsp/gaps": self._set_hsp_gaps, + "end_Hsp/align-len": self._set_hsp_align_len, + "end_Hsp/qseq": self._set_hsp_query_seq, + "end_Hsp/hseq": self._set_hsp_subject_seq, + "end_Hsp/midline": self._set_hsp_midline, + "end_Statistics/db-num": self._set_statistics_db_num, + "end_Statistics/db-len": self._set_statistics_db_len, + "end_Statistics/hsp-len": self._set_statistics_hsp_len, + "end_Statistics/eff-space": self._set_statistics_eff_space, + "end_Statistics/kappa": self._set_statistics_kappa, + "end_Statistics/lambda": self._set_statistics_lambda, + "end_Statistics/entropy": self._set_statistics_entropy, + } + + def _start_blast_record(self): + """Start interaction (PRIVATE).""" + self._blast = Blast() + + def _end_blast_record(self): + """End interaction (PRIVATE).""" + # We stored a lot of generic "top level" information + # in self._header (an object of type Header) + self._blast.reference = self._header.reference + self._blast.date = self._header.date + self._blast.version = self._header.version + self._blast.database = self._header.database + self._blast.application = self._header.application + + # These are required for "old" pre 2.2.14 files + # where only , + # and were used. Now they + # are supplemented/replaced by , + # and + if not hasattr(self._blast, "query") or not self._blast.query: + self._blast.query = self._header.query + if not hasattr(self._blast, "query_id") or not self._blast.query_id: + self._blast.query_id = self._header.query_id + if not hasattr(self._blast, "query_letters") or not self._blast.query_letters: + self._blast.query_letters = self._header.query_letters + + # Hack to record the query length as both the query_letters and + # query_length properties (as in the plain text parser, see + # Bug 2176 comment 12): + self._blast.query_length = self._blast.query_letters + # Perhaps in the long term we should deprecate one, but I would + # prefer to drop query_letters - so we need a transition period + # with both. + + # Hack to record the claimed database size as database_length + # (as well as in num_letters_in_database, see Bug 2176 comment 13): + self._blast.database_length = self._blast.num_letters_in_database + # TODO? Deprecate database_letters next? + + # Hack to record the claimed database sequence count as database_sequences + self._blast.database_sequences = self._blast.num_sequences_in_database + + # Apply the "top level" parameter information + self._blast.matrix = self._parameters.matrix + self._blast.num_seqs_better_e = self._parameters.num_seqs_better_e + self._blast.gap_penalties = self._parameters.gap_penalties + self._blast.filter = self._parameters.filter + self._blast.expect = self._parameters.expect + self._blast.sc_match = self._parameters.sc_match + self._blast.sc_mismatch = self._parameters.sc_mismatch + + # Add to the list + self._records.append(self._blast) + # Clear the object (a new empty one is create in _start_Iteration) + self._blast = None + + if self._debug: + sys.stderr.write("NCBIXML: Added Blast record to results\n") + + # Header + def _set_header_application(self): + """BLAST program, e.g., blastp, blastn, etc. (PRIVATE). + + Save this to put on each blast record object + """ + self._header.application = self._value.upper() + + def _set_header_version(self): + """Version number and date of the BLAST engine (PRIVATE). + + e.g. "BLASTX 2.2.12 [Aug-07-2005]" but there can also be + variants like "BLASTP 2.2.18+" without the date. + + Save this to put on each blast record object + """ + parts = self._value.split() + # TODO - Check the first word starts with BLAST? + + # The version is the second word (field one) + self._header.version = parts[1] + + # Check there is a third word (the date) + if len(parts) >= 3: + if parts[2][0] == "[" and parts[2][-1] == "]": + self._header.date = parts[2][1:-1] + else: + # Assume this is still a date, but without the + # square brackets + self._header.date = parts[2] + + def _set_header_reference(self): + """Record any article reference describing the algorithm (PRIVATE). + + Save this to put on each blast record object + """ + self._header.reference = self._value + + def _set_header_database(self): + """Record the database(s) searched (PRIVATE). + + Save this to put on each blast record object + """ + self._header.database = self._value + + def _set_header_query_id(self): + """Record the identifier of the query (PRIVATE). + + Important in old pre 2.2.14 BLAST, for recent versions + is enough + """ + self._header.query_id = self._value + + def _set_header_query(self): + """Record the definition line of the query (PRIVATE). + + Important in old pre 2.2.14 BLAST, for recent versions + is enough + """ + self._header.query = self._value + + def _set_header_query_letters(self): + """Record the length of the query (PRIVATE). + + Important in old pre 2.2.14 BLAST, for recent versions + is enough + """ + self._header.query_letters = int(self._value) + + def _set_record_query_id(self): + """Record the identifier of the query (PRIVATE).""" + self._blast.query_id = self._value + + def _set_record_query_def(self): + """Record the definition line of the query (PRIVATE).""" + self._blast.query = self._value + + def _set_record_query_letters(self): + """Record the length of the query (PRIVATE).""" + self._blast.query_letters = int(self._value) + + # def _end_BlastOutput_query_seq(self): + # """The query sequence (PRIVATE).""" + # pass # XXX Missing in Blast ? + + # def _end_BlastOutput_iter_num(self): + # """The psi-blast iteration number (PRIVATE).""" + # pass # XXX TODO PSI + + def _set_record_hits(self): + """Hits to the database sequences, one for every sequence (PRIVATE).""" + self._blast.num_hits = int(self._value) + + # def _end_BlastOutput_message(self): + # """error messages (PRIVATE).""" + # pass # XXX What to do ? + + # Parameters + def _set_parameters_matrix(self): + """Matrix used (-M on legacy BLAST) (PRIVATE).""" + self._parameters.matrix = self._value + + def _set_parameters_expect(self): + """Expect values cutoff (PRIVATE).""" + # NOTE: In old text output there was a line: + # Number of sequences better than 1.0e-004: 1 + # As far as I can see, parameters.num_seqs_better_e + # would take the value of 1, and the expectation + # value was not recorded. + # + # Anyway we should NOT record this against num_seqs_better_e + self._parameters.expect = self._value + + # def _end_Parameters_include(self): + # """Inclusion threshold for a psi-blast iteration (-h) (PRIVATE).""" + # pass # XXX TODO PSI + + def _set_parameters_sc_match(self): + """Match score for nucleotide-nucleotide comparison (-r) (PRIVATE).""" + self._parameters.sc_match = int(self._value) + + def _set_parameters_sc_mismatch(self): + """Mismatch penalty for nucleotide-nucleotide comparison (-r) (PRIVATE).""" + self._parameters.sc_mismatch = int(self._value) + + def _set_parameters_gap_penalties(self): + """Gap existence cost (-G) (PRIVATE).""" + self._parameters.gap_penalties = int(self._value) + + def _set_parameters_gap_extend(self): + """Gap extension cose (-E) (PRIVATE).""" + self._parameters.gap_penalties = ( + self._parameters.gap_penalties, + int(self._value), + ) + + def _set_parameters_filter(self): + """Record filtering options (-F) (PRIVATE).""" + self._parameters.filter = self._value + + # def _end_Parameters_pattern(self): + # """Pattern used for phi-blast search (PRIVATE). + # """ + # pass # XXX TODO PSI + + # def _end_Parameters_entrez_query(self): + # """Entrez query used to limit search (PRIVATE). + # """ + # pass # XXX TODO PSI + + # Hits + def _start_hit(self): + """Start filling records (PRIVATE).""" + self._blast.alignments.append(Alignment()) + self._descr = Description() if self._xml_version == 1 else DescriptionExt() + self._blast.descriptions.append(self._descr) + self._blast.multiple_alignment = [] + self._hit = self._blast.alignments[-1] + + self._descr.num_alignments = 0 + # Specifically ignore CREATE_VIEW statements that sometimes + # exist between tags, as a result of very large remote + # BLAST searches. + if self._value.strip() == "CREATE_VIEW": + warnings.warn( + f"NCBIXML: Ignored: {self._value!r}", + BiopythonParserWarning, + ) + self._value = "" + + def _end_hit(self): + """Clear variables (PRIVATE).""" + # Cleanup + self._blast.multiple_alignment = None + self._hit = None + self._descr = None + + def set_hit_id(self): + """Record the identifier of the database sequence (PRIVATE).""" + self._hit.hit_id = self._value + self._hit.title = self._value + " " + + def set_hit_def(self): + """Record the definition line of the database sequence (PRIVATE).""" + self._hit.hit_def = self._value + self._hit.title += self._value + self._descr.title = self._hit.title + + def set_hit_accession(self): + """Record the accession value of the database sequence (PRIVATE).""" + self._hit.accession = self._value + self._descr.accession = self._value + + def set_hit_len(self): + """Record the length of the hit.""" + self._hit.length = int(self._value) + + # HSPs + def _start_hsp(self): + # Note that self._start_Hit() should have been called + # to setup things like self._blast.multiple_alignment + self._hsp = HSP() + self._hsp.positives = None + self._hit.hsps.append(self._hsp) + self._descr.num_alignments += 1 + self._blast.multiple_alignment.append(MultipleAlignment()) + self._mult_al = self._blast.multiple_alignment[-1] + + def _end_hsp(self): + if self._hsp.frame and len(self._hsp.frame) == 1: + self._hsp.frame += (0,) + + # Hsp_num is useless + def _set_hsp_score(self): + """Record the raw score of HSP (PRIVATE).""" + self._hsp.score = float(self._value) + if self._descr.score is None: + self._descr.score = float(self._value) + + def _set_hsp_bit_score(self): + """Record the Bit score of HSP (PRIVATE).""" + self._hsp.bits = float(self._value) + if self._descr.bits is None: + self._descr.bits = float(self._value) + + def _set_hsp_e_value(self): + """Record the expect value of the HSP (PRIVATE).""" + self._hsp.expect = float(self._value) + if self._descr.e is None: + self._descr.e = float(self._value) + + def _set_hsp_query_start(self): + """Offset of query at the start of the alignment (one-offset) (PRIVATE).""" + self._hsp.query_start = int(self._value) + + def _set_hsp_query_end(self): + """Offset of query at the end of the alignment (one-offset) (PRIVATE).""" + self._hsp.query_end = int(self._value) + + def _set_hsp_hit_from(self): + """Offset of the database at the start of the alignment (one-offset) (PRIVATE).""" + self._hsp.sbjct_start = int(self._value) + + def _set_hsp_hit_to(self): + """Offset of the database at the end of the alignment (one-offset) (PRIVATE).""" + self._hsp.sbjct_end = int(self._value) + + # def _end_Hsp_pattern_from(self): + # """Start of phi-blast pattern on the query (one-offset) (PRIVATE).""" + # pass # XXX TODO PSI + + # def _end_Hsp_pattern_to(self): + # """End of phi-blast pattern on the query (one-offset) (PRIVATE).""" + # pass # XXX TODO PSI + + def _set_hsp_query_frame(self): + """Frame of the query if applicable (PRIVATE).""" + v = int(self._value) + self._hsp.frame = (v,) + if self._header.application == "BLASTN": + self._hsp.strand = ("Plus" if v > 0 else "Minus",) + + def _set_hsp_hit_frame(self): + """Frame of the database sequence if applicable (PRIVATE).""" + v = int(self._value) + if len(self._hsp.frame) == 0: + self._hsp.frame = (0, v) + else: + self._hsp.frame += (v,) + if self._header.application == "BLASTN": + self._hsp.strand += ("Plus" if v > 0 else "Minus",) + + def _set_hsp_query_strand(self): + """Frame of the query if applicable (PRIVATE).""" + self._hsp.strand = (self._value,) + if self._header.application == "BLASTN": + self._hsp.frame = (1 if self._value == "Plus" else -1,) + + def _set_hsp_hit_strand(self): + """Frame of the database sequence if applicable (PRIVATE).""" + self._hsp.strand += (self._value,) + if self._header.application == "BLASTN": + self._hsp.frame += (1 if self._value == "Plus" else -1,) + + def _set_hsp_identity(self): + """Record the number of identities in the alignment (PRIVATE).""" + v = int(self._value) + self._hsp.identities = v + if self._hsp.positives is None: + self._hsp.positives = v + + def _set_hsp_positive(self): + """Record the number of positive (conservative) substitutions in the alignment (PRIVATE).""" + self._hsp.positives = int(self._value) + + def _set_hsp_gaps(self): + """Record the number of gaps in the alignment (PRIVATE).""" + self._hsp.gaps = int(self._value) + + def _set_hsp_align_len(self): + """Record the length of the alignment (PRIVATE).""" + self._hsp.align_length = int(self._value) + + # def _en_Hsp_density(self): + # """Score density (PRIVATE).""" + # pass # XXX ??? + + def _set_hsp_query_seq(self): + """Record the alignment string for the query (PRIVATE).""" + self._hsp.query = self._value + + def _set_hsp_subject_seq(self): + """Record the alignment string for the database (PRIVATE).""" + self._hsp.sbjct = self._value + + def _set_hsp_midline(self): + """Record the middle line as normally seen in BLAST report (PRIVATE).""" + self._hsp.match = self._value # do NOT strip spaces! + assert len(self._hsp.match) == len(self._hsp.query) + assert len(self._hsp.match) == len(self._hsp.sbjct) + + # Statistics + def _set_statistics_db_num(self): + """Record the number of sequences in the database (PRIVATE).""" + self._blast.num_sequences_in_database = int(self._value) + + def _set_statistics_db_len(self): + """Record the number of letters in the database (PRIVATE).""" + self._blast.num_letters_in_database = int(self._value) + + def _set_statistics_hsp_len(self): + """Record the effective HSP length (PRIVATE).""" + self._blast.effective_hsp_length = int(self._value) + + def _set_statistics_eff_space(self): + """Record the effective search space (PRIVATE).""" + self._blast.effective_search_space = float(self._value) + + def _set_statistics_kappa(self): + """Karlin-Altschul parameter K (PRIVATE).""" + self._blast.ka_params = float(self._value) + + def _set_statistics_lambda(self): + """Karlin-Altschul parameter Lambda (PRIVATE).""" + self._blast.ka_params = (float(self._value), self._blast.ka_params) + + def _set_statistics_entropy(self): + """Karlin-Altschul parameter H (PRIVATE).""" + self._blast.ka_params = self._blast.ka_params + (float(self._value),) + + def _start_hit_descr_item(self): + """XML v2. Start hit description item.""" + self._hit_descr_item = DescriptionExtItem() + + def _end_hit_descr_item(self): + """XML v2. Start hit description item.""" + self._descr.append_item(self._hit_descr_item) + if not self._hit.title: + self._hit.title = str(self._hit_descr_item) + self._hit_descr_item = None + + def _end_description_id(self): + """XML v2. The identifier of the database sequence(PRIVATE).""" + self._hit_descr_item.id = self._value + if not self._hit.hit_id: + self._hit.hit_id = self._value + + def _end_description_accession(self): + """XML v2. The accession value of the database sequence (PRIVATE).""" + self._hit_descr_item.accession = self._value + if not getattr(self._hit, "accession", None): + self._hit.accession = self._value + + def _end_description_title(self): + """XML v2. The hit description title (PRIVATE).""" + self._hit_descr_item.title = self._value + + def _end_description_taxid(self): + try: + self._hit_descr_item.taxid = int(self._value) + except ValueError: + pass + + def _end_description_sciname(self): + self._hit_descr_item.sciname = self._value + + +def read(handle, debug=0): + """Return a single Blast record (assumes just one query). + + Uses the BlastParser internally. + + This function is for use when there is one and only one BLAST + result in your XML file. + + Use the Bio.Blast.NCBIXML.parse() function if you expect more than + one BLAST record (i.e. if you have more than one query sequence). + """ + iterator = parse(handle, debug) + try: + record = next(iterator) + except StopIteration: + raise ValueError("No records found in handle") from None + try: + next(iterator) + raise ValueError("More than one record found in handle") + except StopIteration: + pass + return record + + +def parse(handle, debug=0): + """Return an iterator a Blast record for each query. + + Incremental parser, this is an iterator that returns + Blast records. It uses the BlastParser internally. + + handle - file handle to and XML file to parse + debug - integer, amount of debug information to print + + This is a generator function that returns multiple Blast records + objects - one for each query sequence given to blast. The file + is read incrementally, returning complete records as they are read + in. + + Should cope with new BLAST 2.2.14+ which gives a single XML file + for multiple query records. + + Should also cope with XML output from older versions BLAST which + gave multiple XML files concatenated together (giving a single file + which strictly speaking wasn't valid XML). + """ + from xml.parsers import expat + + BLOCK = 1024 + MARGIN = 10 # must be at least length of newline + XML start + XML_START = "" + + def __str__(self): + alignment_text = super().__str__() + query = self.query + target = self.target + query_strand = ( + "Plus" if self.coordinates[1, 0] <= self.coordinates[1, -1] else "Minus" + ) + target_strand = ( + "Plus" if self.coordinates[0, 0] <= self.coordinates[0, -1] else "Minus" + ) + indent = " " * 8 + query_description = textwrap.fill( + query.description, + width=80, + initial_indent=indent, + subsequent_indent=indent, + ) + target_description = textwrap.fill( + target.description, + width=80, + initial_indent=indent, + subsequent_indent=indent, + ) + evalue = self.annotations["evalue"] + bitscore = self.annotations["bit score"] + score = self.score + steps = np.diff(self.coordinates, 1) + aln_span = sum(abs(steps).max(0)) + terms = [] + identity = self.annotations["identity"] + identity_percentage = round(100.0 * identity / aln_span) + identity_text = "Identities:%d/%d(%d%%)" % ( + identity, + aln_span, + identity_percentage, + ) + terms.append(identity_text) + positive = self.annotations.get("positive") + if positive is not None: + positive_percentage = round(100.0 * positive / aln_span) + positive_text = "Positives:%d/%d(%d%%)" % ( + positive, + aln_span, + positive_percentage, + ) + terms.append(positive_text) + try: + gaps = self.annotations["gaps"] + except KeyError: + pass + else: + gaps_percentage = round(100.0 * gaps / aln_span) + gaps_text = "Gaps:%d.%d(%d%%)" % (gaps, aln_span, gaps_percentage) + terms.append(gaps_text) + counts_line = ", ".join(terms) + return """\ +Query : %s Length: %d Strand: %s +%s +Target: %s Length: %d Strand: %s +%s + +Score:%d bits(%d), Expect:%.1g, +%s + +%s +""" % ( + query.id, + len(query), + query_strand, + query_description, + target.id, + len(target), + target_strand, + target_description, + bitscore, + score, + evalue, + counts_line, + alignment_text, + ) + + +class Hit(Alignments): + """Stores a single BLAST hit of one single query against one target. + + The ``Bio.Blast.Hit`` class inherits from the ``Bio.Align.Alignments`` + class, which is a subclass of a Python list. The ``Bio.Blast.Hit`` class + stores ``Bio.Blast.HSP`` objwcts, which inherit from + ``Bio.Align.Alignment``. A ``Bio.Blast.Hit`` object is therefore + effectively a list of ``Bio.Align.Alignment`` objects. Most hits consist of + only 1 or a few Alignment objects. + + Each ``Bio.Blast.Hit`` object has a ``target`` attribute containing the + following information: + + - target.id: seqId of subject; + - target.description: definition line of subject; + - target.name: accession of subject; + - len(target.seq): sequence length of subject. + + See the documentation of ``Bio.Blast.Record`` for a more detailed + explanation of the information stored in the alignments contained in the + ``Bio.Blast.Hit`` object. + """ + + def __getitem__(self, key): + try: + value = super().__getitem__(key) + except IndexError: + raise IndexError("index out of range") from None + if isinstance(key, slice): + hit = Hit(value) + hit.target = self.target + return hit + else: + return value + + def __repr__(self): + target = self.target + try: + alignment = self[0] + except IndexError: + return f"" + query = alignment.query + nhsps = len(self) + if nhsps == 1: + unit = "HSP" + else: # nhsps > 1 + unit = "HSPs" + return f"" + + def __str__(self): + """Return a human readable summary of the Hit object.""" + lines = [] + + # set query id line + query = self[0].query + qid_line = "Query: %s" % query.id + lines.append(qid_line) + indent = " " * 7 + description_lines = textwrap.wrap( + query.description, + width=80, + initial_indent=indent, + subsequent_indent=indent, + ) + lines.extend(description_lines) + + # set hit id line + target = self.target + hid_line = " Hit: %s (length=%i)" % (target.id, len(target)) + lines.append(hid_line) + description_lines = textwrap.wrap( + target.description, + width=80, + initial_indent=indent, + subsequent_indent=indent, + ) + lines.extend(description_lines) + + # set hsp line and table + lines.append( + " HSPs: %s %s %s %s %s %s" + % ("-" * 4, "-" * 8, "-" * 9, "-" * 6, "-" * 15, "-" * 21) + ) + pattern = "%11s %8s %9s %6s %15s %21s" + lines.append( + pattern % ("#", "E-value", "Bit score", "Span", "Query range", "Hit range") + ) + lines.append(pattern % ("-" * 4, "-" * 8, "-" * 9, "-" * 6, "-" * 15, "-" * 21)) + for idx, hsp in enumerate(self): + # evalue + evalue = format(hsp.annotations["evalue"], ".2g") + # bit score + bitscore = format(hsp.annotations["bit score"], ".2f") + # alignment length + steps = np.diff(hsp.coordinates, 1) + aln_span = sum(abs(steps).max(0)) + # query region + query_start = hsp.coordinates[1, 0] + query_end = hsp.coordinates[1, -1] + query_range = f"[{query_start}:{query_end}]" + # max column length is 18 + query_range = ( + query_range[:13] + "~]" if len(query_range) > 15 else query_range + ) + # hit region + hit_start = hsp.coordinates[0, 0] + hit_end = hsp.coordinates[0, -1] + hit_range = f"[{hit_start}:{hit_end}]" + hit_range = hit_range[:19] + "~]" if len(hit_range) > 21 else hit_range + # append the hsp row + lines.append( + pattern % (idx, evalue, bitscore, aln_span, query_range, hit_range) + ) + + return "\n".join(lines) + + +class Record(list): + """Stores the BLAST results for a single query. + + A ``Bio.Blast.Record`` object is a list of ``Bio.Blast.Hit`` objects, each + corresponding to one hit for the query in the BLAST output. + + The ``Bio.Blast.Record`` object may have the following attributes: + - query: A ``SeqRecord`` object which may contain some or all of the + following information: + - query.id: SeqId of query; + - query.description: Definition line of query; + - len(query.seq): Length of the query sequence. + - stat: A dictionary with summary statistics of the BLAST run. It may + contain the following keys: + - 'db-num': number of sequences in BLAST db (integer); + - 'db-len': length of BLAST db (integer); + - 'hsp-len': effective HSP length (integer); + - 'eff-space': effective search space (float); + - 'kappa': Karlin-Altschul parameter K (float); + - 'lambda': Karlin-Altschul parameter Lambda (float); + - 'entropy': Karlin-Altschul parameter H (float). + - message: Some (error?) information. + + Each ``Bio.Blast.Hit`` object has a ``target`` attribute containing the + following information: + + - target.id: seqId of subject; + - target.description: definition line of subject; + - target.name: accession of subject; + - len(target.seq): sequence length of subject. + + The ``Bio.Blast.Hit`` class inherits from the ``Bio.Align.Alignments`` + class, which inherits from a Python list. In this list, the + ``Bio.Blast.Hit`` object stores ``Bio.Blast.HSP`` objects, which inherit + from the ``Bio.Align.Alignment`` class. A ``Bio.Blast.Hit`` object is + therefore effectively a list of alignment objects. + + Each HSP in a ``Bio.Blast.Hit`` object has the attributes ``target`` and + ``query`` attributes, as usual for of a ``Bio.Align.Alignment`` object + storing a pairwise alignment, pointing to a ``SeqRecord`` object + representing the target and query, respectively. For translated BLAST + searches, the ``features`` attribute of the target or query may contain a + ``SeqFeature`` of type CDS that stores the amino acid sequence region. The + ``qualifiers`` attribute of such a feature is a dictionary with a single + key 'coded_by'; the corresponding value specifies the nucleotide sequence + region, in a GenBank-style string with 1-based coordinates, that encodes + the amino acid sequence. + + Each ``Bio.Blast.HSP`` object has the following additional attributes: + + - score: score of HSP; + - annotations: a dictionary that may contain the following keys: + - 'bit score': score (in bits) of HSP (float); + - 'evalue': e-value of HSP (float); + - 'identity': number of identities in HSP (integer); + - 'positive': number of positives in HSP (integer); + - 'gaps': number of gaps in HSP (integer); + - 'midline': formatting middle line. + + >>> from Bio import Blast + >>> record = Blast.read("Blast/xml_2212L_blastx_001.xml") + >>> record.query + SeqRecord(seq=Seq(None, length=556), id='gi|1347369|gb|G25137.1|G25137', name='', description='human STS EST48004, sequence tagged site', dbxrefs=[]) + >>> record.stat + {'db-num': 2934173, 'db-len': 1011751523, 'hsp-len': 0, 'eff-space': 0, 'kappa': 0.041, 'lambda': 0.267, 'entropy': 0.14} + >>> len(record) + 78 + >>> hit = record[0] + >>> type(hit) + + >>> from Bio.Align import Alignments + >>> isinstance(hit, Alignments) + True + >>> hit.target + SeqRecord(seq=Seq(None, length=319), id='gi|12654095|gb|AAH00859.1|', name='AAH00859', description='Unknown (protein for IMAGE:3459481) [Homo sapiens]', dbxrefs=[]) + + Most hits consist of only 1 or a few Alignment objects: + + >>> len(hit) + 1 + >>> alignment = hit[0] + >>> type(alignment) + + >>> alignment.score + 630.0 + >>> alignment.annotations + {'bit score': 247.284, 'evalue': 1.69599e-64, 'identity': 122, 'positive': 123, 'gaps': 0, 'midline': 'DLQLLIKAVNLFPAGTNSRWEVIANYMNIHSSSGVKRTAKDVIGKAKSLQKLDPHQKDDINKKAFDKFKKEHGVVPQADNATPSERF GPYTDFTP TTE QKL EQAL TYPVNT ERW IA AVPGR K+'} + + Target and query information are stored in the respective attributes of the + alignment: + + >>> alignment.target + SeqRecord(seq=Seq({155: 'DLQLLIKAVNLFPAGTNSRWEVIANYMNIHSSSGVKRTAKDVIGKAKSLQKLDP...TKK'}, length=319), id='gi|12654095|gb|AAH00859.1|', name='AAH00859', description='Unknown (protein for IMAGE:3459481) [Homo sapiens]', dbxrefs=[]) + >>> alignment.query + SeqRecord(seq=Seq('DLQLLIKAVNLFPAGTNSRWEVIANYMNIHSSSGVKRTAKDVIGKAKSLQKLDP...XKE'), id='gi|1347369|gb|G25137.1|G25137', name='', description='human STS EST48004, sequence tagged site', dbxrefs=[]) + + This was a BLASTX run, so the query sequence was translated: + + >>> len(alignment.target.features) + 0 + >>> len(alignment.query.features) + 1 + >>> feature = alignment.query.features[0] + >>> feature + SeqFeature(SimpleLocation(ExactPosition(0), ExactPosition(133)), type='CDS', qualifiers=...) + >>> feature.qualifiers + {'coded_by': 'gi|1347369|gb|G25137.1|G25137:1..399'} + + i.e., nucleotides 0:399 (in zero-based coordinates) encode the amino acids + of the query in the alignment. + + For an alignment against the reverse strand, the location in the qualifier + is shown as in this example: + + >>> record[72][0].query.features[0].qualifiers + {'coded_by': 'complement(gi|1347369|gb|G25137.1|G25137:345..530)'} + + """ + + def __init__(self): + """Initialize the Record object.""" + self.query = None + + def __repr__(self): + query = self.query + try: + query_id = query.id + except AttributeError: + query_id = "unknown" + nhits = len(self) + if nhits == 0: + return f"" + elif nhits == 1: + return f"" + else: + return f"" + + def __str__(self): + lines = [] + try: + version = self.version + except AttributeError: + pass + else: + lines.append(f"Program: {version}") + try: + db = self.db + except AttributeError: + pass + else: + lines.append(f" db: {db}") + if self.query is not None: + # self.query may be None with legacy Blast if there are no hits + lines.append(" Query: %s (length=%d)" % (self.query.id, len(self.query))) + indent = " " * 9 + description_lines = textwrap.wrap( + self.query.description, + width=80, + initial_indent=indent, + subsequent_indent=indent, + ) + lines.extend(description_lines) + if len(self) == 0: + lines.append(" Hits: No hits found") + else: + lines.append(" Hits: %s %s %s" % ("-" * 4, "-" * 5, "-" * 58)) + pattern = "%13s %5s %s" + lines.append(pattern % ("#", "# HSP", "ID + description")) + lines.append(pattern % ("-" * 4, "-" * 5, "-" * 58)) + for idx, hit in enumerate(self): + n = len(hit) # Number of HSPs + if idx < 30: + hid_line = "%s %s" % (hit.target.id, hit.target.description) + if len(hid_line) > 58: + hid_line = hid_line[:55] + "..." + lines.append(pattern % (idx, len(hit), hid_line)) + elif idx > len(self) - 4: + hid_line = "%s %s" % (hit.target.id, hit.target.description) + if len(hid_line) > 58: + hid_line = hid_line[:55] + "..." + lines.append(pattern % (idx, len(hit), hid_line)) + elif idx == 30: + lines.append("%14s" % "~~~") + return "\n".join(lines) + + def __getitem__(self, key): + try: + value = super().__getitem__(key) + except IndexError: + raise IndexError("index out of range") from None + except TypeError: + if not isinstance(key, str): + raise TypeError("key must be an integer, slice, or str") from None + for hit in self: + if hit.target.id == key: + return hit + raise KeyError(key) + else: + if isinstance(key, slice): + record = Record() + record.extend(value) + # Only store the query attribute, as the other attributes + # pertain to the complete Blast record: + try: + query = self.query + except AttributeError: + pass + else: + record.query = query + # The following keys may be present if the record was created + # by Blast.read: + keys = ( + "source", + "program", + "version", + "reference", + "db", + "param", + "mbstat", + ) + for key in keys: + try: + value = getattr(self, key) + except AttributeError: + pass + else: + setattr(record, key, value) + return record + return value + + def keys(self): + """Return a list of the target.id of each hit.""" + return [hit.target.id for hit in self] + + def __contains__(self, key): + for hit in self: + if hit.target.id == key: + return True + return False + + def index(self, key): + """Return the index of the hit for which the target.id is equal to the key.""" + for i, hit in enumerate(self): + if hit.target.id == key: + return i + raise ValueError(f"'{key}' not found") + + +class Records(UserList): + """Stores the BLAST results of a single BLAST run. + + A ``Bio.Blast.Records`` object is an iterator. Iterating over it returns + returns ``Bio.Blast.Record`` objects, each of which corresponds to one + BLAST query. + + Common attributes of a ``Bio.Blast.Records`` object are + + - source: The input data from which the ``Bio.Blast.Records`` object + was constructed. + - program: The specific BLAST program that was used (e.g., 'blastn'). + - version: The version of the BLAST program (e.g., 'BLASTN 2.2.27+'). + - reference: The literature reference to the BLAST publication. + - db: The BLAST database against which the query was run + (e.g., 'nr'). + - query: A ``SeqRecord`` object which may contain some or all of the + following information: + - query.id: SeqId of the query; + - query.description: Definition line of the query; + - query.seq: The query sequence. The query sequence. + The query sequence. + - param: A dictionary with the parameters used for the BLAST run. + You may find the following keys in this dictionary: + - 'matrix': the scoring matrix used in the BLAST run + (e.g., 'BLOSUM62') (string); + - 'expect': threshold on the expected number of chance + matches (float); + - 'include': e-value threshold for inclusion in + multipass model in psiblast (float); + - 'sc-match': score for matching nucleotides (integer); + - 'sc-mismatch': score for mismatched nucleotides + (integer); + - 'gap-open': gap opening cost (integer); + - 'gap-extend': gap extension cost (integer); + - 'filter': filtering options applied in the BLAST + run (string); + - 'pattern': PHI-BLAST pattern (string); + - 'entrez-query': Limit of request to Entrez query (string). + - mbstat: A dictionary with Mega BLAST search statistics. As this + information is stored near the end of the XML file, this + attribute can only be accessed after the file has been read + completely (by iterating over the records until a + ``StopIteration`` is issued. This dictionary can contain the + same keys as the dictionary stored under the ``stat`` + attribute of a ``Record`` object. + + >>> from Bio import Blast + >>> path = "Blast/xml_2218_blastp_002.xml" + + In a script, you would use a ``with`` block, as in + + >>> with Blast.parse(path) as records: + ... print(records.source) + ... + Blast/xml_2218_blastp_002.xml + + to ensure that the file is closed at the end of the block. + Here, we will simply do + + >>> records = Blast.parse("Blast/xml_2218_blastp_002.xml") + + so we can see the output of each command right away. + + >>> type(records) + + >>> records.source + 'Blast/xml_2218_blastp_002.xml' + >>> records.program + 'blastp' + >>> records.version + 'BLASTP 2.2.18+' + >>> records.reference + 'Altschul, Stephen F., Thomas L. Madden, Alejandro A. Schäffer, Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), "Gapped BLAST and PSI-BLAST: a new generation of protein database search programs", Nucleic Acids Res. 25:3389-3402.' + >>> records.db + 'gpipe/9606/Previous/protein' + >>> records.param + {'matrix': 'BLOSUM62', 'expect': 0.01, 'gap-open': 11, 'gap-extend': 1, 'filter': 'm L; R -d repeat/repeat_9606;'} + + Iterating over the records returns Bio.Blast.Record objects: + + >>> record = next(records) + >>> type(record) + + >>> record.query.id + 'gi|585505|sp|Q08386|MOPB_RHOCA' + >>> record = next(records) + >>> type(record) + + >>> record.query.id + 'gi|129628|sp|P07175.1|PARA_AGRTU' + >>> record = next(records) # doctest:+ELLIPSIS + Traceback (most recent call last): + ... + StopIteration + + You can also use the records as a list, for example by extracting a record + by index, or by calling ``len`` or ``print`` on the records. The parser + will then automatically iterate over the records and store them: + + >>> records = Blast.parse("Blast/wnts.xml") + >>> record = records[3] # this causes all records to be read in and stored + >>> record.query.id + 'Query_4' + >>> len(records) + 5 + + After the records have been read in, you can still iterate over them: + + >>> for i, record in enumerate(records): + ... print(i, record.query.id) + ... + 0 Query_1 + 1 Query_2 + 2 Query_3 + 3 Query_4 + 4 Query_5 + + """ # noqa: RST201, RST203, RST301 + + def __init__(self, source): + """Initialize the Records object.""" + if isinstance(source, list): # UserList API requirement + self._records = source + self._loaded = True + self._index = 0 + return + + self.source = source + try: + stream = open(source, "rb") + except TypeError: # not a path, assume we received a stream + if source.read(0) != b"": + raise StreamModeError( + "BLAST output files must be opened in binary mode." + ) from None + stream = source + self._stream = stream + self._read_header() + self._records = [] # for when we want to use Records as a list + self._loaded = False + + def _read_header(self): + from Bio.Blast._parser import XMLHandler + + stream = self._stream + source = self.source + try: # context manager won't kick in until after parse returns + parser = expat.ParserCreate(namespace_separator=" ") + self._parser = parser + + handler = XMLHandler(parser) + handler._records = self + + while True: + data = stream.read(BLOCK) + if data == b"": + try: + handler._parser + except AttributeError: + break + else: + try: + parser.Parse(b"", True) + except expat.ExpatError as e: + if parser.StartElementHandler is not None: + raise ValueError( + f"premature end of XML file: line {e.lineno}, column {e.offset}" + ) + raise e + try: + parser.Parse(data, False) + except expat.ExpatError as e: + try: + parser.Parse(b"", True) + except expat.ExpatError: + pass + if parser.StartElementHandler: + # We saw the initial 0: + try: + self._stream.seek(0) + except io.UnsupportedOperation: + raise ValueError( + "list-like access after iterating is supported only if the input data is seekable." + ) + self._read_header() + self._index = 0 + for record in self: + self._records.append(record) + stream = self._stream + if stream is not self.source: + stream.close() + del self._stream + self._loaded = True + self._index = index + return self._records + + def __repr__(self): + return f"" + + def __str__(self): + text = """\ +Program: %s + db: %s""" % ( + self.version, + self.db, + ) + records = self[:] # to ensure that the records are read in + for record in self._records: + text += "\n\n" + str(record) + return text + + +def parse(source): + """Parse an XML file containing BLAST output and return a Bio.Blast.Records object. + + This returns an iterator object; iterating over it returns Bio.Blast.Record + objects one by one. + + The source can be a file stream or the path to an XML file containing the + BLAST output. If a file stream, source must be in binary mode. This allows + the parser to detect the encoding from the XML file,and to use it to convert + any text in the XML to the correct Unicode string. The qblast function in + Bio.Blast returns a file stream in binary mode. For files, please use mode + "rb" when opening the file, as in + + >>> from Bio import Blast + >>> stream = open("Blast/wnts.xml", "rb") # opened in binary mode + >>> records = Blast.parse(stream) + >>> for record in records: + ... print(record.query.id, record.query.description) + ... + Query_1 gi|195230749:301-1383 Homo sapiens wingless-type MMTV integration site family member 2 (WNT2), transcript variant 1, mRNA + Query_2 gi|325053704:108-1166 Homo sapiens wingless-type MMTV integration site family, member 3A (WNT3A), mRNA + Query_3 gi|156630997:105-1160 Homo sapiens wingless-type MMTV integration site family, member 4 (WNT4), mRNA + Query_4 gi|371502086:108-1205 Homo sapiens wingless-type MMTV integration site family, member 5A (WNT5A), transcript variant 2, mRNA + Query_5 gi|53729353:216-1313 Homo sapiens wingless-type MMTV integration site family, member 6 (WNT6), mRNA + >>> stream.close() + + """ + return Records(source) + + +def read(source): + """Parse an XML file containing BLAST output for a single query and return it. + + Internally, this function uses Bio.Blast.parse to obtain an iterator over + BLAST records. The function then reads one record from the iterator, + ensures that there are no further records, and returns the record it found + as a Bio.Blast.Record object. An exception is raised if no records are + found, or more than one record is found. + + The source can be a file stream or the path to an XML file containing the + BLAST output. If a file stream, source must be in binary mode. This allows + the parser to detect the encoding from the XML file,and to use it to convert + any text in the XML to the correct Unicode string. The qblast function in + Bio.Blast returns a file stream in binary mode. For files, please use mode + "rb" when opening the file, as in + + >>> from Bio import Blast + >>> stream = open("Blast/xml_21500_blastn_001.xml", "rb") # opened in binary mode + >>> record = Blast.read(stream) + >>> record.query.id + 'Query_78041' + >>> record.query.description + 'G26684.1 human STS STS_D11570, sequence tagged site' + >>> len(record) + 11 + >>> stream.close() + + Use the Bio.Blast.parse function if you want to read a file containing + BLAST output for more than one query. + """ + with parse(source) as records: + try: + record = next(records) + except StopIteration: + raise ValueError("No BLAST output found.") from None + try: + next(records) + raise ValueError("BLAST output for more than one query found.") + except StopIteration: + pass + for key in ("source", "program", "version", "reference", "db", "param", "mbstat"): + try: + value = getattr(records, key) + except AttributeError: + pass + else: + setattr(record, key, value) + return record + + +def write(records, destination, fmt="XML"): + """Write BLAST records as an XML file, and return the number of records. + + Arguments: + - records - A ``Bio.Blast.Records`` object. + - destination - File or file-like object to write to, or filename as + string. + The File object must have been opened for writing in + binary mode, and must be closed (or flushed) by the caller + after this function returns to ensure that all records are + written. + - fmt - string describing the file format to write + (case-insensitive). + Currently, only "XML" and "XML2" are accepted. + + Returns the number of records written (as an integer). + """ + fmt = fmt.upper() + if fmt == "XML": + Writer = _writers.XMLWriter + elif fmt == "XML2": + Writer = _writers.XML2Writer + else: + raise ValueError(f"Unknown format {fmt}; expected 'XML' or 'XML2'") + try: + stream = open(destination, "wb") + except TypeError: # not a path, assume we received a stream + try: + destination.write(b"") + except TypeError: + # destination was opened in text mode + raise StreamModeError( + "File must be opened in binary mode for writing." + ) from None + stream = destination + writer = Writer(stream) + try: + count = writer.write(records) + finally: + if stream is not destination: + stream.close() + return count + + +@function_with_previous +def qblast( + program, + database, + sequence, + url_base=NCBI_BLAST_URL, + auto_format=None, + composition_based_statistics=None, + db_genetic_code=None, + endpoints=None, + entrez_query="(none)", + expect=10.0, + filter=None, + gapcosts=None, + genetic_code=None, + hitlist_size=50, + i_thresh=None, + layout=None, + lcase_mask=None, + matrix_name=None, + nucl_penalty=None, + nucl_reward=None, + other_advanced=None, + perc_ident=None, + phi_pattern=None, + query_file=None, + query_believe_defline=None, + query_from=None, + query_to=None, + searchsp_eff=None, + service=None, + threshold=None, + ungapped_alignment=None, + word_size=None, + short_query=None, + alignments=500, + alignment_view=None, + descriptions=500, + entrez_links_new_window=None, + expect_low=None, + expect_high=None, + format_entrez_query=None, + format_object=None, + format_type="XML", + ncbi_gi=None, + results_file=None, + show_overview=None, + megablast=None, + template_type=None, + template_length=None, + username="blast", + password=None, +): + """BLAST search using NCBI's QBLAST server. + + Supports all parameters of the old qblast API for Put and Get. + + Please note that NCBI uses the new Common URL API for BLAST searches on + the internet (https://blast.ncbi.nlm.nih.gov/doc/blast-help/urlapi.html). + Thus, some of the parameters used by this function are not (or are no + longer) officially supported by NCBI. Although they are still functioning, + this may change in the future. + + Some useful parameters: + + - program blastn, blastp, blastx, tblastn, or tblastx (lower case) + - database Which database to search against (e.g. "nr"). + - sequence The sequence to search. + - ncbi_gi TRUE/FALSE whether to give 'gi' identifier. + - descriptions Number of descriptions to show. Def 500. + - alignments Number of alignments to show. Def 500. + - expect An expect value cutoff. Def 10.0. + - matrix_name Specify an alt. matrix (PAM30, PAM70, BLOSUM80, BLOSUM45). + - filter "none" turns off filtering. Default no filtering + - format_type "XML" (default), "HTML", "Text", "XML2", "JSON2", + or "Tabular". + - entrez_query Entrez query to limit Blast search - only applies when searching nucleotide BLASTDBs + - hitlist_size Number of hits to return. Default 50 + - megablast TRUE/FALSE whether to use MEga BLAST algorithm (blastn only) + - short_query TRUE/FALSE whether to adjust the search parameters for a + short query sequence. Note that this will override + manually set parameters like word size and e value. Turns + off when sequence length is > 30 residues. Default: None. + - service plain, psi, phi, rpsblast, megablast (lower case) + + This function does no checking of the validity of the parameters + and passes the values to the server as is. More help is available at: + https://blast.ncbi.nlm.nih.gov/doc/blast-help/urlapi.html + + The http.client.HTTPResponse object returned by this function has the + additional attributes rid and rtoe with the Request ID and Request Time Of + Execution for this BLAST search. + + """ + programs = ["blastn", "blastp", "blastx", "tblastn", "tblastx"] + if program not in programs: + raise ValueError( + f"Program specified is {program}. Expected one of {', '.join(programs)}" + ) + + # SHORT_QUERY_ADJUST throws an error when using blastn (wrong parameter + # assignment from NCBIs side). + # Thus we set the (known) parameters directly: + if short_query and program == "blastn": + short_query = None + # We only use the 'short-query' parameters for short sequences: + if len(sequence) < 31: + expect = 1000 + word_size = 7 + nucl_reward = 1 + filter = None + lcase_mask = None + warnings.warn( + '"SHORT_QUERY_ADJUST" is incorrectly implemented (by NCBI) for blastn.' + " We bypass the problem by manually adjusting the search parameters." + " Thus, results may slightly differ from web page searches.", + BiopythonWarning, + ) + + # Format the "Put" command, which sends search requests to qblast. + # Parameters taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node5.html on 9 July 2007 + # Additional parameters are taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node9.html on 8 Oct 2010 + # To perform a PSI-BLAST or PHI-BLAST search the service ("Put" and "Get" commands) must be specified + # (e.g. psi_blast = NCBIWWW.qblast("blastp", "refseq_protein", input_sequence, service="psi")) + parameters = { + "AUTO_FORMAT": auto_format, + "COMPOSITION_BASED_STATISTICS": composition_based_statistics, + "DATABASE": database, + "DB_GENETIC_CODE": db_genetic_code, + "ENDPOINTS": endpoints, + "ENTREZ_QUERY": entrez_query, + "EXPECT": expect, + "FILTER": filter, + "GAPCOSTS": gapcosts, + "GENETIC_CODE": genetic_code, + "HITLIST_SIZE": hitlist_size, + "I_THRESH": i_thresh, + "LAYOUT": layout, + "LCASE_MASK": lcase_mask, + "MEGABLAST": megablast, + "MATRIX_NAME": matrix_name, + "NUCL_PENALTY": nucl_penalty, + "NUCL_REWARD": nucl_reward, + "OTHER_ADVANCED": other_advanced, + "PERC_IDENT": perc_ident, + "PHI_PATTERN": phi_pattern, + "PROGRAM": program, + # ('PSSM': pssm: - It is possible to use PSI-BLAST via this API? + "QUERY": sequence, + "QUERY_FILE": query_file, + "QUERY_BELIEVE_DEFLINE": query_believe_defline, + "QUERY_FROM": query_from, + "QUERY_TO": query_to, + # 'RESULTS_FILE': ...: - Can we use this parameter? + "SEARCHSP_EFF": searchsp_eff, + "SERVICE": service, + "SHORT_QUERY_ADJUST": short_query, + "TEMPLATE_TYPE": template_type, + "TEMPLATE_LENGTH": template_length, + "THRESHOLD": threshold, + "UNGAPPED_ALIGNMENT": ungapped_alignment, + "WORD_SIZE": word_size, + "CMD": "Put", + } + + if password is not None: + # handle authentication for BLAST cloud + password_mgr = HTTPPasswordMgrWithDefaultRealm() + password_mgr.add_password(None, url_base, username, password) + handler = HTTPBasicAuthHandler(password_mgr) + opener = build_opener(handler) + install_opener(opener) + + if url_base == NCBI_BLAST_URL: + parameters.update({"email": email, "tool": tool}) + parameters = {key: value for key, value in parameters.items() if value is not None} + message = urlencode(parameters).encode() + request = Request(url_base, message, {"User-Agent": "BiopythonClient"}) + # Send off the initial query to qblast. + # Note the NCBI do not currently impose a rate limit here, other + # than the request not to make say 50 queries at once using multiple + # threads. + stream = urlopen(request) + + # Format the "Get" command, which gets the formatted results from qblast + # Parameters taken from http://www.ncbi.nlm.nih.gov/BLAST/Doc/node6.html on 9 July 2007 + rid, rtoe = _parse_qblast_ref_page(stream) + parameters = { + "ALIGNMENTS": alignments, + "ALIGNMENT_VIEW": alignment_view, + "DESCRIPTIONS": descriptions, + "ENTREZ_LINKS_NEW_WINDOW": entrez_links_new_window, + "EXPECT_LOW": expect_low, + "EXPECT_HIGH": expect_high, + "FORMAT_ENTREZ_QUERY": format_entrez_query, + "FORMAT_OBJECT": format_object, + "FORMAT_TYPE": format_type, + "NCBI_GI": ncbi_gi, + "RID": rid, + "RESULTS_FILE": results_file, + "SERVICE": service, + "SHOW_OVERVIEW": show_overview, + "CMD": "Get", + } + parameters = {key: value for key, value in parameters.items() if value is not None} + message = urlencode(parameters).encode() + + # Poll NCBI until the results are ready. + # https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Web&PAGE_TYPE=BlastDocs&DOC_TYPE=DeveloperInfo + # 1. Do not contact the server more often than once every 10 seconds. + # 2. Do not poll for any single RID more often than once a minute. + # 3. Use the URL parameter email and tool, so that the NCBI + # can contact you if there is a problem. + # 4. Run scripts weekends or between 9 pm and 5 am Eastern time + # on weekdays if more than 50 searches will be submitted. + # -- + # Could start with a 10s delay, but expect most short queries + # will take longer thus at least 70s with delay. Therefore, + # start with 20s delay, thereafter once a minute. + delay = 20 # seconds + start_time = time.time() + while True: + current = time.time() + wait = qblast.previous + delay - current + if wait > 0: + time.sleep(wait) + qblast.previous = current + wait + else: + qblast.previous = current + # delay by at least 60 seconds only if running the request against the public NCBI API + if delay < 60 and url_base == NCBI_BLAST_URL: + # Wasn't a quick return, must wait at least a minute + delay = 60 + elapsed = time.time() - start_time + if elapsed >= 600: + warnings.warn( + f"BLAST request {rid} is taking longer than 10 minutes, consider re-issuing it", + BiopythonWarning, + ) + request = Request(url_base, message, {"User-Agent": "BiopythonClient"}) + stream = urlopen(request) + data = stream.peek() + if format_type == "HTML" and b"NCBI Blast:" in data: + continue + elif data.startswith(b" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/BITS-question-answer2.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/BITS-question-answer2.ent new file mode 100644 index 0000000000000000000000000000000000000000..b92a958988dabdb6c12988d26d61e97e2d27c038 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/BITS-question-answer2.ent @@ -0,0 +1,531 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/Docsum_3_3.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/Docsum_3_3.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..c1c1169c19b808ce9d73e77d4f2ef33bed7717b1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/Docsum_3_3.mod.dtd @@ -0,0 +1,1585 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/Docsum_3_4.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/Docsum_3_4.dtd new file mode 100644 index 0000000000000000000000000000000000000000..89ba0bc54c2d83a2ece283d3fbc9f57b6ac00bc1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/Docsum_3_4.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%Docsum_3_4_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/Docsum_3_4.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/Docsum_3_4.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..51899a8743e6f906b52595fd4a33d43d6d269380 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/Docsum_3_4.mod.dtd @@ -0,0 +1,1594 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/EMBL_General.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/EMBL_General.dtd new file mode 100644 index 0000000000000000000000000000000000000000..267f9e146f3559452a8a493afa1f6c2e9d1d8e8b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/EMBL_General.dtd @@ -0,0 +1,20 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%NCBI_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/EMBL_General.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/EMBL_General.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..1f6f6fa07e1bd382f1f3f9dcd2c7251a33fb29f9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/EMBL_General.mod.dtd @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/GenBank_General.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/GenBank_General.dtd new file mode 100644 index 0000000000000000000000000000000000000000..c8707a94deaf21215929e45a7a6ed5a323283b4f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/GenBank_General.dtd @@ -0,0 +1,20 @@ + + + + + +%NCBI_Entity_module; + + +%GenBank_General_module; + + +%NCBI_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/GenBank_General.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/GenBank_General.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..0cba4545f4eb7c8bae6b575b27ef922d8b75a284 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/GenBank_General.mod.dtd @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/HomoloGene.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/HomoloGene.dtd new file mode 100644 index 0000000000000000000000000000000000000000..82262e4fffccaac5f8a7c7fa86f5b2cb2664def5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/HomoloGene.dtd @@ -0,0 +1,89 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%HomoloGene_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/HomoloGene.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/HomoloGene.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..c88a5cd0054dff18924cd4b7b3bce24cf35ced9a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/HomoloGene.mod.dtd @@ -0,0 +1,293 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/INSD_INSDSeq.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/INSD_INSDSeq.dtd new file mode 100644 index 0000000000000000000000000000000000000000..fdf3b96a21b359a9fc28fe60312036c9fc4a8c9c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/INSD_INSDSeq.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%INSD_INSDSeq_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/INSD_INSDSeq.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/INSD_INSDSeq.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..308423d1f02b3bf4d74af38f9c14afc9d1b160bc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/INSD_INSDSeq.mod.dtd @@ -0,0 +1,491 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-ali-namespace1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-ali-namespace1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..64390689dd60b2d4acb03dc0e340dc21f9d7c575 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-ali-namespace1-3.ent @@ -0,0 +1,293 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-archivecustom-classes1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-archivecustom-classes1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..676de4d931f84357ab124446faf28cf999583b29 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-archivecustom-classes1-3.ent @@ -0,0 +1,409 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-archivecustom-mixes1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-archivecustom-mixes1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..aca1d4221529179a308ab9ee0b920d36f8bf856a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-archivecustom-mixes1-3.ent @@ -0,0 +1,601 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-articlemeta1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-articlemeta1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..a1c58370848d83031f8dac0cb2a328cafe965eb2 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-articlemeta1-3.ent @@ -0,0 +1,2552 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-backmatter1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-backmatter1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..9c73878f72e690ae6601628365314e776ca6ec23 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-backmatter1-3.ent @@ -0,0 +1,540 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-chars1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-chars1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..ceca2700c964d2b5316af88987ea54fbda26349b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-chars1-3.ent @@ -0,0 +1,664 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-common-atts1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-common-atts1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..5233f73ab188860be609d7c43d0f851ee1083b81 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-common-atts1-3.ent @@ -0,0 +1,360 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-common1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-common1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..93f918945ecdb2f35db291906ebde75be093cb5c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-common1-3.ent @@ -0,0 +1,4659 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-default-classes1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-default-classes1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..2833311dd3b211b793d45dd0dbc455cc013d3af8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-default-classes1-3.ent @@ -0,0 +1,1595 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-default-mixes1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-default-mixes1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..e4d14bcf18cd646573b56e7022ec6afa17603885 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-default-mixes1-3.ent @@ -0,0 +1,630 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-display1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-display1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..0c5bd178dc520b43acba1db3ab21fee95c039c7b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-display1-3.ent @@ -0,0 +1,1299 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-format1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-format1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..f771aefd2a40d3db815e4b4bd23bba6e74962900 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-format1-3.ent @@ -0,0 +1,997 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-funding1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-funding1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..8e2bb533a1d10d30eb66df094423276ec1278c2d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-funding1-3.ent @@ -0,0 +1,1100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-journalmeta1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-journalmeta1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..a3dbcfe4c1edd1c08ec60e72e818f47c5032dc09 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-journalmeta1-3.ent @@ -0,0 +1,593 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-list1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-list1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..4fe56161f3528f8717259e179f27815611429b72 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-list1-3.ent @@ -0,0 +1,663 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-math1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-math1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..3111c26b8bfa6e7429c3959feb0d084c20846abf --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-math1-3.ent @@ -0,0 +1,563 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-mathml3-mathmlsetup1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-mathml3-mathmlsetup1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..631ba9e9e6d1e5fb944bd06fc8d82aa4c29956f3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-mathml3-mathmlsetup1-3.ent @@ -0,0 +1,493 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]> + + + + + + + + + + + + + + + + + + + + + +%ent-mmlextra; + + + +%ent-mmlalias; + + + + + + + + + + + + + + + +%mathml.dtd; + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-mathml3-modules1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-mathml3-modules1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..2ded91d44771493ea3c460a0d1164822c4ccbd4a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-mathml3-modules1-3.ent @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-modules1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-modules1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..190edbf4c966b2ceb4feea58af388f9c05eaa3c9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-modules1-3.ent @@ -0,0 +1,769 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-phrase1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-phrase1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..2420ae871a380c8a10f88cae2c9e2e9d8476963e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-phrase1-3.ent @@ -0,0 +1,664 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-section1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-section1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..620df23804aa6a19b9d7bf710de8367c5f5d2256 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-section1-3.ent @@ -0,0 +1,463 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-xmlspecchars1-3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-xmlspecchars1-3.ent new file mode 100644 index 0000000000000000000000000000000000000000..4657a47aa32690f35fe28fd00d4619e0e46090d9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/JATS-xmlspecchars1-3.ent @@ -0,0 +1,528 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%ISOlat1; +%ISOlat2; +%ISObox; +%ISOdia; +%ISOnum; +%ISOpub; +%ISOcyr1; +%ISOcyr2; + +%ISOgrk1; +%ISOgrk2; +%ISOgrk4; + +%ISOtech; +%ISOgrk3; +%ISOamsa; +%ISOamsb; +%ISOamsc; +%ISOamsn; +%ISOamso; +%ISOamsr; +%ISOmscr; +%ISOmfrk; +%ISOmopf; + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB.dtd new file mode 100644 index 0000000000000000000000000000000000000000..738efa95c9aaffd49f32258d63ee3281bb36a131 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB.dtd @@ -0,0 +1,98 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%MMDB_module; + + +%MMDB_Chemical_graph_module; + + +%MMDB_Features_module; + + +%MMDB_Structural_model_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..84245331459811731592951a7543d2ee55d696b7 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB.mod.dtd @@ -0,0 +1,259 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB_Chemical_graph.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB_Chemical_graph.dtd new file mode 100644 index 0000000000000000000000000000000000000000..fd56bf75e62766fc881f16c3cb2e87e1cc4898f4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB_Chemical_graph.dtd @@ -0,0 +1,98 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%MMDB_module; + + +%MMDB_Chemical_graph_module; + + +%MMDB_Features_module; + + +%MMDB_Structural_model_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB_Features.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB_Features.dtd new file mode 100644 index 0000000000000000000000000000000000000000..b8eb2957c92fcd73a2f6cd7693d5def6d96b66aa --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB_Features.dtd @@ -0,0 +1,98 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%MMDB_module; + + +%MMDB_Chemical_graph_module; + + +%MMDB_Features_module; + + +%MMDB_Structural_model_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB_Structural_model.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB_Structural_model.dtd new file mode 100644 index 0000000000000000000000000000000000000000..a5a075e60b029ce6cf14ce37f5d4ebd346d7926c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/MMDB_Structural_model.dtd @@ -0,0 +1,98 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%MMDB_module; + + +%MMDB_Chemical_graph_module; + + +%MMDB_Features_module; + + +%MMDB_Structural_model_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Access.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Access.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..e83ad2aa97567b80713c545a05d6062de3cff034 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Access.mod.dtd @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Biblio.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Biblio.dtd new file mode 100644 index 0000000000000000000000000000000000000000..17edc09196cce683aa8fb73b65dff677b881af56 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Biblio.dtd @@ -0,0 +1,20 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_Biblio_module; + + +%NCBI_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BioSource.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BioSource.dtd new file mode 100644 index 0000000000000000000000000000000000000000..2bfea5c29ff4e9c4e72f25cc443c42d76e7c3179 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BioSource.dtd @@ -0,0 +1,23 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_BioSource_module; + + +%NCBI_General_module; + + +%NCBI_Organism_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BioSource.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BioSource.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..6b5c5da113b42305a66fd8fdd05759cfb98c3981 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BioSource.mod.dtd @@ -0,0 +1,200 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BioTree.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BioTree.dtd new file mode 100644 index 0000000000000000000000000000000000000000..26ba5d90e96fee41f5aa11a1f137190e7ac26c13 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BioTree.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_BioTree_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Blast4.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Blast4.dtd new file mode 100644 index 0000000000000000000000000000000000000000..24437c512f1ac6c3322506a39c24f4d8ee20768f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Blast4.dtd @@ -0,0 +1,95 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Blast4_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_ScoreMat_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Seqset_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BlastOutput.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BlastOutput.dtd new file mode 100644 index 0000000000000000000000000000000000000000..307176aaf01328f0e8789f75e87118bc7549cd97 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BlastOutput.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_BlastOutput_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BlastOutput.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BlastOutput.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..7b0f47ffe80f3521ff47cea5dcf531290f82e9b9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_BlastOutput.mod.dtd @@ -0,0 +1,273 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Cdd.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Cdd.dtd new file mode 100644 index 0000000000000000000000000000000000000000..b2d06ad60b64a640f5d4aa691c1bfabac11f6953 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Cdd.dtd @@ -0,0 +1,110 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%MMDB_module; + + +%MMDB_Chemical_graph_module; + + +%MMDB_Features_module; + + +%MMDB_Structural_model_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Cdd_module; + + +%NCBI_Cn3d_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_ScoreMat_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Seqset_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Cn3d.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Cn3d.dtd new file mode 100644 index 0000000000000000000000000000000000000000..95580456eb78a2f1a1e91e2f2ce32e60c784c4d0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Cn3d.dtd @@ -0,0 +1,101 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%MMDB_module; + + +%MMDB_Chemical_graph_module; + + +%MMDB_Features_module; + + +%MMDB_Structural_model_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Cn3d_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Cn3d.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Cn3d.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..16a815f9e2f79aa8b900c3b67e089e1a2f908305 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Cn3d.mod.dtd @@ -0,0 +1,534 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Entity.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Entity.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..3919c3e8ae2609ec707c2f29b37e743ff73de730 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Entity.mod.dtd @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Entrez2.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Entrez2.dtd new file mode 100644 index 0000000000000000000000000000000000000000..a08a9072524ede0577c1121d27f93bad11d1d042 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Entrez2.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_Entrez2_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Entrezgene.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Entrezgene.dtd new file mode 100644 index 0000000000000000000000000000000000000000..36e206f6c70d34e5ff543f4ae28995b05fef121b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Entrezgene.dtd @@ -0,0 +1,89 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Entrezgene_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Entrezgene.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Entrezgene.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..c75d32f25a9fb9d9bcb7f00d0c9e2c7b9ce5b9b9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Entrezgene.mod.dtd @@ -0,0 +1,394 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_FeatDef.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_FeatDef.dtd new file mode 100644 index 0000000000000000000000000000000000000000..a3ce559da877c9cf61ba0979b981fc568ad439fc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_FeatDef.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_FeatDef_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_FeatDef.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_FeatDef.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..65fbf9008b541d9807205b220e0a0a35cbd4291f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_FeatDef.mod.dtd @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_GBSeq.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_GBSeq.dtd new file mode 100644 index 0000000000000000000000000000000000000000..d317e9663396fa4ed036d39af9702383e8d4aa39 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_GBSeq.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_GBSeq_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_GBSeq.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_GBSeq.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..95be4f3c67a6df0ac2054c20115a70cf084f4ab7 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_GBSeq.mod.dtd @@ -0,0 +1,407 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Gene.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Gene.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..be703afdd0f16966408ca8b744bdeae6daad4af3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Gene.mod.dtd @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_General.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_General.dtd new file mode 100644 index 0000000000000000000000000000000000000000..a8bb6c1adb7c0d03f470e0b00498a4d8ec9da95f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_General.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_General.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_General.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..c573ca5786894322c93e7a2744389fd80eca09eb --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_General.mod.dtd @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ID1Access.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ID1Access.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..b489907402d3b68d9bc5be9183a76db9831ecb29 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ID1Access.mod.dtd @@ -0,0 +1,218 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ID2Access.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ID2Access.dtd new file mode 100644 index 0000000000000000000000000000000000000000..4adbfa5c9b5103085d2f91b62106547c53138a3e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ID2Access.dtd @@ -0,0 +1,95 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_ID2Access_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_Seq_split_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Seqset_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ID2Access.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ID2Access.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..5d5ecf750a6ecf499060cec596a8c3d510cd0413 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ID2Access.mod.dtd @@ -0,0 +1,759 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_MedArchive.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_MedArchive.dtd new file mode 100644 index 0000000000000000000000000000000000000000..1082302d8a223c576ca6b274b7c5a52ccb92012f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_MedArchive.dtd @@ -0,0 +1,35 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_Biblio_module; + + +%NCBI_General_module; + + +%NCBI_MedArchive_module; + + +%NCBI_Medlars_module; + + +%NCBI_Medline_module; + + +%NCBI_Pub_module; + + +%NCBI_PubMed_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Medlars.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Medlars.dtd new file mode 100644 index 0000000000000000000000000000000000000000..6d1410c355654f1650ea22794dcea5ddae72c3ea --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Medlars.dtd @@ -0,0 +1,23 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_Biblio_module; + + +%NCBI_General_module; + + +%NCBI_Medlars_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Medlars.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Medlars.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..cb8d48a48d3eafcfd7ea63d0e14545c3163c3b64 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Medlars.mod.dtd @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Medline.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Medline.dtd new file mode 100644 index 0000000000000000000000000000000000000000..9495345842431740e5779240fd2dcaf6ec26832b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Medline.dtd @@ -0,0 +1,23 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_Biblio_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Mim.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Mim.dtd new file mode 100644 index 0000000000000000000000000000000000000000..7dc862be74939cd861f2d2082d966e8e42ec5cf3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Mim.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_Mim_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Mim.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Mim.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..664a8514581259764aeefe3b994463ccc5ea5098 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Mim.mod.dtd @@ -0,0 +1,354 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Mime.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Mime.dtd new file mode 100644 index 0000000000000000000000000000000000000000..a7be9297b03dbc7bca00ea1bf34da59b15e84eb4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Mime.dtd @@ -0,0 +1,113 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%MMDB_module; + + +%MMDB_Chemical_graph_module; + + +%MMDB_Features_module; + + +%MMDB_Structural_model_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Cdd_module; + + +%NCBI_Cn3d_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Mime_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_ScoreMat_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Seqset_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ObjPrt.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ObjPrt.dtd new file mode 100644 index 0000000000000000000000000000000000000000..ae5196af075cb2d001fe103b2d6ee2565e38396f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ObjPrt.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_ObjPrt_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Organism.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Organism.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..9c36c43619d0fe8dbc107b4e9e55d026d08d7d25 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Organism.mod.dtd @@ -0,0 +1,226 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_PCSubstance.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_PCSubstance.dtd new file mode 100644 index 0000000000000000000000000000000000000000..0efe6fdf4b8af8180b2cee511946fc39e03071d9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_PCSubstance.dtd @@ -0,0 +1,29 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_Biblio_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_PCSubstance_module; + + +%NCBI_Pub_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Project.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Project.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..e2215fe28953bbd0b37b4e0eda393c8670f7f2bf --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Project.mod.dtd @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Protein.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Protein.dtd new file mode 100644 index 0000000000000000000000000000000000000000..e8279eae261ec9bdaf6aa116dfec442f5adc9e50 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Protein.dtd @@ -0,0 +1,20 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_General_module; + + +%NCBI_Protein_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Pub.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Pub.dtd new file mode 100644 index 0000000000000000000000000000000000000000..6a52954489e310215de576f9f499fa8afc3eb35b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Pub.dtd @@ -0,0 +1,26 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_Biblio_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Pub_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_RNA.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_RNA.dtd new file mode 100644 index 0000000000000000000000000000000000000000..c64fad9e72dadd499c258811718b6d0eea5d7b14 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_RNA.dtd @@ -0,0 +1,86 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_RNA.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_RNA.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..b1c7991dca708c2aba2d57e289cfb867f02e66f9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_RNA.mod.dtd @@ -0,0 +1,144 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Remap.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Remap.dtd new file mode 100644 index 0000000000000000000000000000000000000000..4696a507c8c61828acbffbb657a98a71e415179f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Remap.dtd @@ -0,0 +1,89 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Remap_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Remap.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Remap.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..9f14d3559f5b895dad9818b056aea900cca37bff --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Remap.mod.dtd @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Rsite.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Rsite.dtd new file mode 100644 index 0000000000000000000000000000000000000000..7bcf4ded594f5c18a824947e6632355ac32b6aa7 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Rsite.dtd @@ -0,0 +1,20 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_General_module; + + +%NCBI_Rsite_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Rsite.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Rsite.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..1758ab1533ed3b338e79d78c317300976faea0d9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Rsite.mod.dtd @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ScoreMat.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ScoreMat.dtd new file mode 100644 index 0000000000000000000000000000000000000000..64a676bc011e4fcfa609bc8022099c3e7f93f45c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_ScoreMat.dtd @@ -0,0 +1,92 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_ScoreMat_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Seqset_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_SeqCode.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_SeqCode.dtd new file mode 100644 index 0000000000000000000000000000000000000000..3e754ace6235d44918610bc9cdba2a6a00d17125 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_SeqCode.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_SeqCode_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_SeqCode.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_SeqCode.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..1e6096615ce4fee0b49f195d685df6052bc3af73 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_SeqCode.mod.dtd @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_SeqTable.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_SeqTable.dtd new file mode 100644 index 0000000000000000000000000000000000000000..f47d9bad4d4e7e35f71d9b643a5d7fb1b800ffcf --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_SeqTable.dtd @@ -0,0 +1,86 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seq_split.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seq_split.dtd new file mode 100644 index 0000000000000000000000000000000000000000..d705b7cf94b28320fed9f7a9f4db6b35832961e3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seq_split.dtd @@ -0,0 +1,92 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_Seq_split_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Seqset_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seq_split.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seq_split.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..4ab94ad4d4ce20d9956e9fd8eb5ecd713b3ebfa2 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seq_split.mod.dtd @@ -0,0 +1,559 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqfeat.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqfeat.dtd new file mode 100644 index 0000000000000000000000000000000000000000..48af83fb004ffca1091791bb6a0eba9b32e18a64 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqfeat.dtd @@ -0,0 +1,86 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqfeat.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqfeat.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..fb7dc7571e550bbddbe92c7d9c5cabe5b4579e48 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqfeat.mod.dtd @@ -0,0 +1,772 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqloc.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqloc.dtd new file mode 100644 index 0000000000000000000000000000000000000000..a0464a4df27e93066dfd1e69641cd5359c0db050 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqloc.dtd @@ -0,0 +1,86 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqres.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqres.dtd new file mode 100644 index 0000000000000000000000000000000000000000..353ff75aeee76fea2d820db7e0d35f3e939a4db9 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqres.dtd @@ -0,0 +1,86 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqres.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqres.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..27dba623009f06bc390677d4b19b7be728d5d669 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqres.mod.dtd @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqset.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqset.dtd new file mode 100644 index 0000000000000000000000000000000000000000..69de4db4f741263619b4780cc065bfbef7e432a1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Seqset.dtd @@ -0,0 +1,89 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Seqset_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Sequence.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Sequence.dtd new file mode 100644 index 0000000000000000000000000000000000000000..78673f6d015cbcc7a9d35c561112cd660b469443 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Sequence.dtd @@ -0,0 +1,86 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Sequence.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Sequence.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..d09ae02802590a964b7095950107aac08b6bd850 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Sequence.mod.dtd @@ -0,0 +1,1112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Submit.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Submit.dtd new file mode 100644 index 0000000000000000000000000000000000000000..b81b188dbb849ad0a82a48a2422a236aae0bd470 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Submit.dtd @@ -0,0 +1,92 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Seqset_module; + + +%NCBI_Sequence_module; + + +%NCBI_Submit_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_TxInit.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_TxInit.dtd new file mode 100644 index 0000000000000000000000000000000000000000..fe9a6c1084b1e528f1d5244c19f684269edd949e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_TxInit.dtd @@ -0,0 +1,29 @@ + + + + + +%NCBI_Entity_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_TxInit_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_TxInit.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_TxInit.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..d5d97c1e4c66ce5b724285599f6e62632aed1279 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_TxInit.mod.dtd @@ -0,0 +1,184 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Variation.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Variation.dtd new file mode 100644 index 0000000000000000000000000000000000000000..7a992b1814356be9813c0ce208a26433ab51fc1f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_Variation.dtd @@ -0,0 +1,86 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_all.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_all.dtd new file mode 100644 index 0000000000000000000000000000000000000000..3ed101df35fec9f395a4fc601983ec4b2335ce89 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NCBI_all.dtd @@ -0,0 +1,202 @@ + + +%NCBI_Entity_module; + + +%Docsum_3_0_module; + + +%Docsum_3_1_module; + + +%Docsum_3_2_module; + + +%Docsum_3_3_module; + + +%Docsum_3_4_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%HomoloGene_module; + + +%INSD_INSDSeq_module; + + +%MMDB_module; + + +%MMDB_Chemical_graph_module; + + +%MMDB_Features_module; + + +%MMDB_Structural_model_module; + + +%NCBI_Access_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_BioTree_module; + + +%NCBI_Blast4_module; + + +%NCBI_BlastDL_module; + + +%NCBI_BlastOutput_module; + + +%NCBI_Cdd_module; + + +%NCBI_Cn3d_module; + + +%NCBI_Entrez2_module; + + +%NCBI_Entrezgene_module; + + +%NCBI_FeatDef_module; + + +%NCBI_GBSeq_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_ID1Access_module; + + +%NCBI_ID2Access_module; + + +%NCBI_MedArchive_module; + + +%NCBI_Medlars_module; + + +%NCBI_Medline_module; + + +%NCBI_Mim_module; + + +%NCBI_Mime_module; + + +%NCBI_ObjPrt_module; + + +%NCBI_Organism_module; + + +%NCBI_PCAssay_module; + + +%NCBI_PCSubstance_module; + + +%NCBI_Project_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_PubMed_module; + + +%NCBI_RNA_module; + + +%NCBI_Remap_module; + + +%NCBI_Rsite_module; + + +%NCBI_ScoreMat_module; + + +%NCBI_SeqCode_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seq_split_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Seqset_module; + + +%NCBI_Sequence_module; + + +%NCBI_Submit_module; + + +%NCBI_TSeq_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%NSE_module; + + +%OMSSA_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NSE.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NSE.dtd new file mode 100644 index 0000000000000000000000000000000000000000..74f0075d8676ef074a8da200bbf8416974cd2e46 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NSE.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%NSE_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NSE.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NSE.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..4327f4855924d463b36064cb5e9456769203ac05 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/NSE.mod.dtd @@ -0,0 +1,895 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/OMSSA.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/OMSSA.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..26f050e6164655d0b125bd8859cd373511f08754 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/OMSSA.mod.dtd @@ -0,0 +1,1361 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PDB_General.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PDB_General.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..1e5aae9b76a82454b7d15c1852701f87a8809456 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PDB_General.mod.dtd @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PIR_General.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PIR_General.dtd new file mode 100644 index 0000000000000000000000000000000000000000..15f7879a7f29d1a999b098e4903207274226adfc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PIR_General.dtd @@ -0,0 +1,86 @@ + + + + + +%NCBI_Entity_module; + + +%EMBL_General_module; + + +%GenBank_General_module; + + +%NCBI_Biblio_module; + + +%NCBI_BioSource_module; + + +%NCBI_Gene_module; + + +%NCBI_General_module; + + +%NCBI_Medline_module; + + +%NCBI_Organism_module; + + +%NCBI_Protein_module; + + +%NCBI_Pub_module; + + +%NCBI_RNA_module; + + +%NCBI_Rsite_module; + + +%NCBI_SeqTable_module; + + +%NCBI_Seqalign_module; + + +%NCBI_Seqfeat_module; + + +%NCBI_Seqloc_module; + + +%NCBI_Seqres_module; + + +%NCBI_Sequence_module; + + +%NCBI_TxInit_module; + + +%NCBI_Variation_module; + + +%PDB_General_module; + + +%PIR_General_module; + + +%PRF_General_module; + + +%SP_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PIR_General.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PIR_General.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..bedc2edf6f7b28ba7f1ef7b34bdec5f3848d6ac6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PIR_General.mod.dtd @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PRF_General.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PRF_General.dtd new file mode 100644 index 0000000000000000000000000000000000000000..b6cf457849893886f9415ca281a58983df055d62 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PRF_General.dtd @@ -0,0 +1,17 @@ + + + + + +%NCBI_Entity_module; + + +%PRF_General_module; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PRF_General.mod.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PRF_General.mod.dtd new file mode 100644 index 0000000000000000000000000000000000000000..e09cc6054de03676dee75a0b5ead228fbe3d0c53 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/PRF_General.mod.dtd @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/XHTMLtablesetup.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/XHTMLtablesetup.ent new file mode 100644 index 0000000000000000000000000000000000000000..423df664e00d2b498b5178d94c04ed25ed81e0b5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/XHTMLtablesetup.ent @@ -0,0 +1,309 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%htmltable.dtd; + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/archivearticle.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/archivearticle.dtd new file mode 100644 index 0000000000000000000000000000000000000000..9505c2d7ec0f8ea4ef2f7c1a2375107c818597a1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/archivearticle.dtd @@ -0,0 +1,952 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%archivecustom-modules.ent; + + + + + +%modules.ent; + + + + + + + + + + + + + +%archivecustom-classes.ent; + + + + +%default-classes.ent; + + + + +%archivecustom-mixes.ent; + + + + +%default-mixes.ent; + + + + +%archivecustom-models.ent; + + + + + + + + + + +%common.ent; + + + + + + + +%articlemeta.ent; + + + +%backmatter.ent; + + + +%display.ent; + + + + +%format.ent; + + + +%journalmeta.ent; + + + +%link.ent; + + + +%list.ent; + + + +%math.ent; + + + +%para.ent; + + + +%phrase.ent; + + + +%references.ent; + + + +%section.ent; + + + + + + + + + +%mathmlsetup.ent; + + + + + +%XHTMLtablesetup.ent; + + + + +%xmlspecchars.ent; + + + + +%chars.ent; + + + +%notat.ent; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/archivecustom-mixes.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/archivecustom-mixes.ent new file mode 100644 index 0000000000000000000000000000000000000000..06116fe1426e7690ed187bc01c21b422770aa67c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/archivecustom-mixes.ent @@ -0,0 +1,306 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/archivecustom-models.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/archivecustom-models.ent new file mode 100644 index 0000000000000000000000000000000000000000..bafcc76d533de2435de4d2bfc0fe5a32ef63472a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/archivecustom-models.ent @@ -0,0 +1,756 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/archivecustom-modules.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/archivecustom-modules.ent new file mode 100644 index 0000000000000000000000000000000000000000..729d75cad16d634df71d806da71df862e7f54ab6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/archivecustom-modules.ent @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/articlemeta.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/articlemeta.ent new file mode 100644 index 0000000000000000000000000000000000000000..9bb3be21fbdb5ecd9f5b8cfdfcbf8b19060ab2be --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/articlemeta.ent @@ -0,0 +1,1811 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_100301.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_100301.dtd new file mode 100644 index 0000000000000000000000000000000000000000..78e2baeee60c394c56c763623b1587bfedd3e884 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_100301.dtd @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_110101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_110101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..78e2baeee60c394c56c763623b1587bfedd3e884 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_110101.dtd @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_120101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_120101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..78e2baeee60c394c56c763623b1587bfedd3e884 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_120101.dtd @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_130101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_130101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..8a4f338cf9b5c70839cf7b8bd7902d42e620fb7a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_130101.dtd @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_150101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_150101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..8a4f338cf9b5c70839cf7b8bd7902d42e620fb7a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/bookdoc_150101.dtd @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/common.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/common.ent new file mode 100644 index 0000000000000000000000000000000000000000..c149da891138327f6bd8389d28cdadea222ee4a8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/common.ent @@ -0,0 +1,2790 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/default-classes.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/default-classes.ent new file mode 100644 index 0000000000000000000000000000000000000000..ad7103867a19947044f44e84e8faa00cb171ecb2 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/default-classes.ent @@ -0,0 +1,704 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/display.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/display.ent new file mode 100644 index 0000000000000000000000000000000000000000..184bf527ef603c934f3babb547f7ff517feeea4a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/display.ent @@ -0,0 +1,1468 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/eInfo_020511.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/eInfo_020511.dtd new file mode 100644 index 0000000000000000000000000000000000000000..ac4a59f9af593535464e678b79f205f2d610f632 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/eInfo_020511.dtd @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/eLink_090910.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/eLink_090910.dtd new file mode 100644 index 0000000000000000000000000000000000000000..6aa4c477786a2c7530726e033e4fd4c8998adfd3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/eLink_090910.dtd @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/eSearch_020511.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/eSearch_020511.dtd new file mode 100644 index 0000000000000000000000000000000000000000..15e734bd9d0668421839558f134ab0c6b3db1225 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/eSearch_020511.dtd @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/eSpell.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/eSpell.dtd new file mode 100644 index 0000000000000000000000000000000000000000..18b6265eaa3b03c69cf3e8b9f094963523d64a7b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/eSpell.dtd @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/egquery.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/egquery.dtd new file mode 100644 index 0000000000000000000000000000000000000000..ff5334278d0d7d74b12c33f2fc2d375483a3db82 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/egquery.dtd @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/einfo.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/einfo.dtd new file mode 100644 index 0000000000000000000000000000000000000000..0a0ed13294a619c4602ca38be9eaea1745662e3a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/einfo.dtd @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/elink.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/elink.dtd new file mode 100644 index 0000000000000000000000000000000000000000..934b5a9653b72c2cb86f11fb93092db129cc69cb --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/elink.dtd @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/elink_020122.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/elink_020122.dtd new file mode 100644 index 0000000000000000000000000000000000000000..6f93374d50a059c64d2c652d8d17afd0667a231e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/elink_020122.dtd @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/epost.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/epost.dtd new file mode 100644 index 0000000000000000000000000000000000000000..3da74988067e5c862089ffeab747ff09111910b7 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/epost.dtd @@ -0,0 +1,14 @@ + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/esearch.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/esearch.dtd new file mode 100644 index 0000000000000000000000000000000000000000..bd11e35ab79bf317b683ba1d22d190dd2ed87e94 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/esearch.dtd @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/esummary_gene.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/esummary_gene.dtd new file mode 100644 index 0000000000000000000000000000000000000000..d84e28850c8b104d34d8781f4b05048ce798916c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/esummary_gene.dtd @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/format.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/format.ent new file mode 100644 index 0000000000000000000000000000000000000000..1987ac290d437e7aea7fd8975c8d0fbb35eb1541 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/format.ent @@ -0,0 +1,412 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/htmltable.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/htmltable.dtd new file mode 100644 index 0000000000000000000000000000000000000000..e463e4c88f7b82a7c465d65caca80761b0069e06 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/htmltable.dtd @@ -0,0 +1,334 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]> + + + +]]> + + + + + + +]]> + + + +]]> + + + + + + + + +]]> + + + +]]> + + + + + + + + +]]> + + + +]]> + + + + + + + + +]]> + + + +]]> + + + + + + + + +]]> + + + +]]> + + + + + + + + +]]> + + + +]]> + + + + + + +]]> + + + +]]> + + + + + + + + +]]> + + + +]]> + + + + + + +]]> + + + +]]> + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamsa.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamsa.ent new file mode 100644 index 0000000000000000000000000000000000000000..c413168bfc79c320df99e77bb278c26e7e57c284 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamsa.ent @@ -0,0 +1,167 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamsb.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamsb.ent new file mode 100644 index 0000000000000000000000000000000000000000..b74414ba8ecd67360c3570acc4a9dcfc76a809fd --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamsb.ent @@ -0,0 +1,143 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamsc.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamsc.ent new file mode 100644 index 0000000000000000000000000000000000000000..46ea2217c3ce11803544303d4dcd7aef5e34c3cf --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamsc.ent @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamsn.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamsn.ent new file mode 100644 index 0000000000000000000000000000000000000000..a1df8b737786ee6837d138821bc4b93f63b1ff00 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamsn.ent @@ -0,0 +1,114 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamso.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamso.ent new file mode 100644 index 0000000000000000000000000000000000000000..f99cf110cb520b96f26090d39b92fcd5554ef068 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isoamso.ent @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isocyr1.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isocyr1.ent new file mode 100644 index 0000000000000000000000000000000000000000..b4149c7454041aa7d7e0daad72412353e2bb9d45 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isocyr1.ent @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isocyr2.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isocyr2.ent new file mode 100644 index 0000000000000000000000000000000000000000..b038bd9118759dc9997004c652d653c7e051926e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isocyr2.ent @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isodia.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isodia.ent new file mode 100644 index 0000000000000000000000000000000000000000..39ccfcdfe56e9b563f73521c3861447a1c85cd1f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isodia.ent @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isogrk2.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isogrk2.ent new file mode 100644 index 0000000000000000000000000000000000000000..d27cc309b5a46aa40c2adb2f69d5ddbf906f3f06 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isogrk2.ent @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isogrk3.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isogrk3.ent new file mode 100644 index 0000000000000000000000000000000000000000..0cbde885f1005878aadb7dbd5f51c5e23cc5ff25 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isogrk3.ent @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isomopf.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isomopf.ent new file mode 100644 index 0000000000000000000000000000000000000000..4b264256a71b962af0ea90b33488d0daddeed3f0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isomopf.ent @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isomscr.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isomscr.ent new file mode 100644 index 0000000000000000000000000000000000000000..a2174f05118ee38d0b5bd788cd68969e99cb590a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isomscr.ent @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isopub.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isopub.ent new file mode 100644 index 0000000000000000000000000000000000000000..9b27b63d6acbbf71acf9ccde7188f1605bf87b5a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/isopub.ent @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/journalmeta.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/journalmeta.ent new file mode 100644 index 0000000000000000000000000000000000000000..09cd70ae234554d89cc6d7b6326fb77e4cccc4c3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/journalmeta.ent @@ -0,0 +1,341 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/list.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/list.ent new file mode 100644 index 0000000000000000000000000000000000000000..9428b0d1fd3f74ffc084e2e3bb6f4bb6d926728f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/list.ent @@ -0,0 +1,465 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/math.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/math.ent new file mode 100644 index 0000000000000000000000000000000000000000..a501866f0d1b004e32f9b7e307397f1343610813 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/math.ent @@ -0,0 +1,329 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/mathml-in-pubmed.mod b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/mathml-in-pubmed.mod new file mode 100644 index 0000000000000000000000000000000000000000..ce95673f579ce24380658868e6ee1b581ef0ddf3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/mathml-in-pubmed.mod @@ -0,0 +1,151 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]> + + + + + + + + + + + + + + + + + + + + + +%ent-mmlextra; + + + +%ent-mmlalias; + + +%isobox; +%isocyr1; +%isocyr2; +%isodia; +%isolat1; +%isolat2; +%isonum; +%isopub; +%isoamsa; +%isoamsb; +%isoamsc; +%isoamsn; +%isoamso; +%isoamsr; +%isogrk3; +%isomfrk; +%isomopf; +%isomscr; +%isotech; + + + + + + + + + + + + + + +%mathml.dtd; diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/mathml3-qname1.mod b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/mathml3-qname1.mod new file mode 100644 index 0000000000000000000000000000000000000000..254bdb24f43bffcbfd1ce42ee2a427f59196ba01 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/mathml3-qname1.mod @@ -0,0 +1,294 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]> + + + + +]]> + + + + +]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/mathmlsetup.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/mathmlsetup.ent new file mode 100644 index 0000000000000000000000000000000000000000..034be16e1539185429451c047244cbe6384b51d3 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/mathmlsetup.ent @@ -0,0 +1,191 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]> + + + + + + + + + + + + + +%mathml.dtd; + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/mmlextra.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/mmlextra.ent new file mode 100644 index 0000000000000000000000000000000000000000..850c7e7a75897e377b1a21cc3c356ff451e58698 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/mmlextra.ent @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/modules.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/modules.ent new file mode 100644 index 0000000000000000000000000000000000000000..8458753c47025ab3174bf477af1ab5ec41190a17 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/modules.ent @@ -0,0 +1,417 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlm-articleset-2.0.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlm-articleset-2.0.dtd new file mode 100644 index 0000000000000000000000000000000000000000..dd9988be1053600092fac3bfdefb222055f3dd93 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlm-articleset-2.0.dtd @@ -0,0 +1,1641 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmcatalogrecordset_170601.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmcatalogrecordset_170601.dtd new file mode 100644 index 0000000000000000000000000000000000000000..02a1993c25ad1d1f83416b4fd6455e7c9b14c61e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmcatalogrecordset_170601.dtd @@ -0,0 +1,280 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmcommon_080101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmcommon_080101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..ac0ae023ff13b944e197f3de9bb49e8b076a5a12 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmcommon_080101.dtd @@ -0,0 +1,201 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmcommon_090101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmcommon_090101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..787129beab2354bce02bfa8816a32781adc06da4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmcommon_090101.dtd @@ -0,0 +1,220 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedline_011101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedline_011101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..1c5aa06b0036ca36214ee014492033afff352f63 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedline_011101.dtd @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + +%MedlineCitation; + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedline_080101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedline_080101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..1f935d1ea10973bcec1863c95dfac8c44f84f052 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedline_080101.dtd @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + +%MedlineCitation; + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedline_090101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedline_090101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..d903ebd7ae7cdf36106ea718466a91bef2912467 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedline_090101.dtd @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + +%MedlineCitation; + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitation_011101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitation_011101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..6b8a447347fca98f8bcef467799a9ef0fb37658c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitation_011101.dtd @@ -0,0 +1,178 @@ + + + + + + + + + + +%NlmCommon; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitation_080101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitation_080101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..670005a6e466ea85532f941a02aecc269ffaae8c --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitation_080101.dtd @@ -0,0 +1,107 @@ + + + + + + + + + + + + + + + + + + +%NlmSharedCatCit; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_100101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_100101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..16fc7fac83bb3e6898f406ce71d75599f5c2dd1b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_100101.dtd @@ -0,0 +1,194 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_100301.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_100301.dtd new file mode 100644 index 0000000000000000000000000000000000000000..e6b4c487146441b28e2ce2bd0fcf346885bf5b3f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_100301.dtd @@ -0,0 +1,201 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_110101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_110101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..c520c6d600ce70164c5a1d6ce30ab02dbf7010e0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_110101.dtd @@ -0,0 +1,197 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_120101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_120101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..6489a8c5b86b84a821f416c54c4a7dfd766fc9cc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_120101.dtd @@ -0,0 +1,188 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_130101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_130101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..cda3746acd05f61c89643e7bbd15f6997b447953 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_130101.dtd @@ -0,0 +1,191 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_130501.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_130501.dtd new file mode 100644 index 0000000000000000000000000000000000000000..9566d38b04dc92d03f4a959211b44c2109bc9b7a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmmedlinecitationset_130501.dtd @@ -0,0 +1,191 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmserials_080101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmserials_080101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..c5781d8d4c037d5f4332af442b3d8aaf0721c4ee --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmserials_080101.dtd @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + +%NlmCommon; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmserials_100101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmserials_100101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..87c1dc2e46e7a0894c2f15b4b337d6eb64ddd85a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/nlmserials_100101.dtd @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/notat.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/notat.ent new file mode 100644 index 0000000000000000000000000000000000000000..b46a91df88db08660490fa6f993e616cb8805b0f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/notat.ent @@ -0,0 +1,172 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/para.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/para.ent new file mode 100644 index 0000000000000000000000000000000000000000..3c2f1146d484bf22fcfe8130cba45b70197775f0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/para.ent @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_080101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_080101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..11d61846d3e29a8675900f838262a9cc2dd59d28 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_080101.dtd @@ -0,0 +1,71 @@ + + + + + +%Medline; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_110101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_110101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..6298eb64bd6d0e3d2531f3de0d5cb97b4957e026 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_110101.dtd @@ -0,0 +1,79 @@ + + + + + +%Medline; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%Bookdoc; + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_130101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_130101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..82bd9c6f352d97f7a46eff9ea9c365e532afa42f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_130101.dtd @@ -0,0 +1,79 @@ + + + + + +%Medline; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%Bookdoc; + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_140101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_140101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..45708154c914a94e723ada0d5b6db79110ba4aeb --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_140101.dtd @@ -0,0 +1,79 @@ + + + + + +%Medline; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%Bookdoc; + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_150101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_150101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..7c0933d2be2d8e28d5814e6c0f7cd24ebeaa4423 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_150101.dtd @@ -0,0 +1,79 @@ + + + + + +%Medline; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%Bookdoc; + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_180101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_180101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..48bec8a8b5a85626a56381294aedafa2288f3f2b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_180101.dtd @@ -0,0 +1,434 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_180601.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_180601.dtd new file mode 100644 index 0000000000000000000000000000000000000000..aab61e779e296c4cff9f229bfc14e479132816a5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_180601.dtd @@ -0,0 +1,454 @@ + + + + + + + +%mathml-in-pubmed; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_230101.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_230101.dtd new file mode 100644 index 0000000000000000000000000000000000000000..fb1354e94eb04db2913eb71ba48cb4f301630c64 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/pubmed_230101.dtd @@ -0,0 +1,468 @@ + + + + + + + +%mathml-in-pubmed; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/references.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/references.ent new file mode 100644 index 0000000000000000000000000000000000000000..591cb9f11bf5531c24b5107db0815b210ef19f6b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/references.ent @@ -0,0 +1,726 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/section.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/section.ent new file mode 100644 index 0000000000000000000000000000000000000000..17d0128f85eddffbfde191eeab6e2fd959e3ac44 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/section.ent @@ -0,0 +1,220 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/taxon.dtd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/taxon.dtd new file mode 100644 index 0000000000000000000000000000000000000000..fadf481bcbdff9d63e44abf97d7b0deb5c777ce8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/taxon.dtd @@ -0,0 +1,131 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xhtml-inlstyle-1.mod b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xhtml-inlstyle-1.mod new file mode 100644 index 0000000000000000000000000000000000000000..79accd45d273afba190c3a7ea897f28c91e3d063 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xhtml-inlstyle-1.mod @@ -0,0 +1,34 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xmlspecchars.ent b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xmlspecchars.ent new file mode 100644 index 0000000000000000000000000000000000000000..bb15ade7dfe8ccad08487e65d6a1dfd882a24748 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/DTDs/xmlspecchars.ent @@ -0,0 +1,290 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +%ISOlat1; +%ISOlat2; +%ISObox; +%ISOdia; +%ISOnum; +%ISOpub; +%ISOtech; +%ISOgrk1; +%ISOgrk2; +%ISOgrk3; +%ISOgrk4; +%ISOcyr1; +%ISOcyr2; +%ISOamsa; +%ISOamsb; +%ISOamsc; +%ISOamsn; +%ISOamso; +%ISOamsr; +%ISOmscr; +%ISOmfrk; +%ISOmopf; + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/Parser.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/Parser.py new file mode 100644 index 0000000000000000000000000000000000000000..4e7bab984d8fa858f8cd9638d66fd73c9a714ca1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/Parser.py @@ -0,0 +1,1165 @@ +# Copyright 2008-2014 by Michiel de Hoon. All rights reserved. +# Revisions copyright 2008-2015 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Parser for XML results returned by NCBI's Entrez Utilities. + +This parser is used by the read() function in Bio.Entrez, and is not +intended be used directly. + +The question is how to represent an XML file as Python objects. Some +XML files returned by NCBI look like lists, others look like dictionaries, +and others look like a mix of lists and dictionaries. + +My approach is to classify each possible element in the XML as a plain +string, an integer, a list, a dictionary, or a structure. The latter is a +dictionary where the same key can occur multiple times; in Python, it is +represented as a dictionary where that key occurs once, pointing to a list +of values found in the XML file. + +The parser then goes through the XML and creates the appropriate Python +object for each element. The different levels encountered in the XML are +preserved on the Python side. So a subelement of a subelement of an element +is a value in a dictionary that is stored in a list which is a value in +some other dictionary (or a value in a list which itself belongs to a list +which is a value in a dictionary, and so on). Attributes encountered in +the XML are stored as a dictionary in a member .attributes of each element, +and the tag name is saved in a member .tag. + +To decide which kind of Python object corresponds to each element in the +XML, the parser analyzes the DTD referred at the top of (almost) every +XML file returned by the Entrez Utilities. This is preferred over a hand- +written solution, since the number of DTDs is rather large and their +contents may change over time. About half the code in this parser deals +with parsing the DTD, and the other half with the XML itself. +""" + +import os +import warnings +import xml.etree.ElementTree as ET +from collections import Counter +from io import BytesIO +from urllib.parse import urlparse +from urllib.request import urlopen +from xml.parsers import expat +from xml.sax.saxutils import escape + +from Bio import StreamModeError + +# The following four classes are used to add a member .attributes to integers, +# strings, lists, and dictionaries, respectively. + + +class NoneElement: + """NCBI Entrez XML element mapped to None.""" + + def __init__(self, tag, attributes, key): + """Create a NoneElement.""" + self.tag = tag + self.key = key + self.attributes = attributes + + def __repr__(self): + """Return a string representation of the object.""" + try: + attributes = self.attributes + except AttributeError: + return "NoneElement" + return "NoneElement(attributes=%r)" % attributes + + def __eq__(self, other): + if isinstance(other, NoneElement): + return True + return False + + +class IntegerElement(int): + """NCBI Entrez XML element mapped to an integer.""" + + def __new__(cls, value, *args, **kwargs): + """Create an IntegerElement.""" + return int.__new__(cls, value) + + def __init__(self, value, tag, attributes, key): + """Initialize an IntegerElement.""" + self.tag = tag + self.attributes = attributes + self.key = key + + def __repr__(self): + """Return a string representation of the object.""" + text = int.__repr__(self) + try: + attributes = self.attributes + except AttributeError: + return text + return f"IntegerElement({text}, attributes={attributes!r})" + + +class StringElement(str): + """NCBI Entrez XML element mapped to a string.""" + + def __new__(cls, value, *args, **kwargs): + """Create a StringElement.""" + return str.__new__(cls, value) + + def __init__(self, value, tag, attributes, key): + """Initialize a StringElement.""" + self.tag = tag + self.attributes = attributes + self.key = key + + def __repr__(self): + """Return a string representation of the object.""" + text = str.__repr__(self) + attributes = self.attributes + if not attributes: + return text + return f"StringElement({text}, attributes={attributes!r})" + + +class ListElement(list): + """NCBI Entrez XML element mapped to a list.""" + + def __init__(self, tag, attributes, allowed_tags, key=None): + """Create a ListElement.""" + self.tag = tag + if key is None: + self.key = tag + else: + self.key = key + self.attributes = attributes + self.allowed_tags = allowed_tags + + def __repr__(self): + """Return a string representation of the object.""" + text = list.__repr__(self) + attributes = self.attributes + if not attributes: + return text + return f"ListElement({text}, attributes={attributes!r})" + + def store(self, value): + """Append an element to the list, checking tags.""" + key = value.key + if self.allowed_tags is not None and key not in self.allowed_tags: + raise ValueError("Unexpected item '%s' in list" % key) + del value.key + self.append(value) + + +class DictionaryElement(dict): + """NCBI Entrez XML element mapped to a dictionaray.""" + + def __init__(self, tag, attrs, allowed_tags, repeated_tags=None, key=None): + """Create a DictionaryElement.""" + self.tag = tag + if key is None: + self.key = tag + else: + self.key = key + self.attributes = attrs + self.allowed_tags = allowed_tags + self.repeated_tags = repeated_tags + if repeated_tags: + for key in repeated_tags: + self[key] = [] + + def __repr__(self): + """Return a string representation of the object.""" + text = dict.__repr__(self) + attributes = self.attributes + if not attributes: + return text + return f"DictElement({text}, attributes={attributes!r})" + + def store(self, value): + """Add an entry to the dictionary, checking tags.""" + key = value.key + tag = value.tag + if self.allowed_tags is not None and tag not in self.allowed_tags: + raise ValueError("Unexpected item '%s' in dictionary" % key) + del value.key + if self.repeated_tags and key in self.repeated_tags: + self[key].append(value) + else: + self[key] = value + + +class OrderedListElement(list): + """NCBI Entrez XML element mapped to a list of lists. + + OrderedListElement is used to describe a list of repeating elements such as + A, B, C, A, B, C, A, B, C ... where each set of A, B, C forms a group. This + is then stored as [[A, B, C], [A, B, C], [A, B, C], ...] + """ + + def __init__(self, tag, attributes, allowed_tags, first_tag, key=None): + """Create an OrderedListElement.""" + self.tag = tag + if key is None: + self.key = tag + else: + self.key = key + self.attributes = attributes + self.allowed_tags = allowed_tags + self.first_tag = first_tag + + def __repr__(self): + """Return a string representation of the object.""" + text = list.__repr__(self) + attributes = self.attributes + if not attributes: + return text + return f"OrderedListElement({text}, attributes={attributes!r})" + + def store(self, value): + """Append an element to the list, checking tags.""" + key = value.key + if self.allowed_tags is not None and key not in self.allowed_tags: + raise ValueError("Unexpected item '%s' in list" % key) + if key == self.first_tag: + self.append([]) + self[-1].append(value) + + +class ErrorElement(str): + """NCBI Entrez XML element containing an error message.""" + + def __new__(cls, value, *args, **kwargs): + """Create an ErrorElement.""" + return str.__new__(cls, value) + + def __init__(self, value, tag): + """Initialize an ErrorElement.""" + self.tag = tag + self.key = tag + + def __repr__(self): + """Return the error message as a string.""" + text = str.__repr__(self) + return f"ErrorElement({text})" + + +class NotXMLError(ValueError): + """Failed to parse file as XML.""" + + def __init__(self, message): + """Initialize the class.""" + self.msg = message + + def __str__(self): + """Return a string summary of the exception.""" + return ( + "Failed to parse the XML data (%s). Please make sure that the input data " + "are in XML format." % self.msg + ) + + +class CorruptedXMLError(ValueError): + """Corrupted XML.""" + + def __init__(self, message): + """Initialize the class.""" + self.msg = message + + def __str__(self): + """Return a string summary of the exception.""" + return ( + "Failed to parse the XML data (%s). Please make sure that the input data " + "are not corrupted." % self.msg + ) + + +class ValidationError(ValueError): + """XML tag found which was not defined in the DTD. + + Validating parsers raise this error if the parser finds a tag in the XML + that is not defined in the DTD. Non-validating parsers do not raise this + error. The Bio.Entrez.read and Bio.Entrez.parse functions use validating + parsers by default (see those functions for more information). + """ + + def __init__(self, name): + """Initialize the class.""" + self.name = name + + def __str__(self): + """Return a string summary of the exception.""" + return ( + "Failed to find tag '%s' in the DTD. To skip all tags that " + "are not represented in the DTD, please call Bio.Entrez.read " + "or Bio.Entrez.parse with validate=False." % self.name + ) + + +class DataHandlerMeta(type): + """A metaclass is needed until Python supports @classproperty.""" + + def __init__(cls, *args, **kwargs): + """Initialize the class.""" + from Bio import Entrez + + try: + cls.directory = Entrez.local_cache # use default directory for local cache + except PermissionError: + cls._directory = Entrez.local_cache # no local cache + del Entrez + + @property + def directory(cls): + """Directory for caching XSD and DTD files.""" + return cls._directory + + @directory.setter + def directory(cls, value): + """Set a custom directory for the local DTD/XSD directories.""" + if value is None: + import platform + + if platform.system() == "Windows": + value = os.path.join(os.getenv("APPDATA"), "biopython") + else: # Unix/Linux/Mac + home = os.path.expanduser("~") + value = os.path.join(home, ".config", "biopython") + # Create DTD local directory + cls.local_dtd_dir = os.path.join(value, "Bio", "Entrez", "DTDs") + os.makedirs(cls.local_dtd_dir, exist_ok=True) + # Create XSD local directory + cls.local_xsd_dir = os.path.join(value, "Bio", "Entrez", "XSDs") + os.makedirs(cls.local_xsd_dir, exist_ok=True) + # Save the directory name after creating the DTD and XSD local + # directories to ensure there was no PermissionError. + cls._directory = value + + +class DataHandler(metaclass=DataHandlerMeta): + """Data handler for parsing NCBI XML from Entrez.""" + + from Bio import Entrez + + global_dtd_dir = os.path.join(Entrez.__path__[0], "DTDs") + global_xsd_dir = os.path.join(Entrez.__path__[0], "XSDs") + local_dtd_dir = None + local_xsd_dir = None + + del Entrez + + def __init__(self, validate, escape, ignore_errors): + """Create a DataHandler object.""" + self.dtd_urls = [] + self.element = None + self.level = 0 + self.bypass_url_security = False + self.data = [] + self.attributes = None + self.allowed_tags = None + self.constructors = {} + self.strings = {} + self.items = set() + self.errors = set() + self.validating = validate + self.ignore_errors = ignore_errors + self.parser = expat.ParserCreate(namespace_separator=" ") + self.parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS) + self.parser.XmlDeclHandler = self.xmlDeclHandler + self.schema_namespace = None + self.namespace_level = Counter() + self.namespace_prefix = {} + if escape: + self.characterDataHandler = self.characterDataHandlerEscape + else: + self.characterDataHandler = self.characterDataHandlerRaw + + def read(self, source): + """Set up the parser and let it read the XML results.""" + # Expat's parser.ParseFile function only accepts binary data; + # see also the comment below for Entrez.parse. + try: + stream = open(source, "rb") + except TypeError: # not a path, assume we received a stream + if source.read(0) != b"": + raise StreamModeError( + "the XML file must be opened in binary mode." + ) from None + stream = source + if stream.read(0) != b"": + raise TypeError("file should be opened in binary mode") + try: + self.parser.ParseFile(stream) + except expat.ExpatError as e: + if self.parser.StartElementHandler: + # We saw the initial = 2: + # Then the first record is finished, while the second record + # is still a work in progress. + record = records.pop(0) + yield record + + except expat.ExpatError as e: + if self.parser.StartElementHandler: + # We saw the initial " + self.data.append(tag) + self.parser.EndElementHandler = self.endRawElementHandler + self.level += 1 + + def startSkipElementHandler(self, name, attrs): + """Handle start of an XML skip element.""" + self.level += 1 + + def endStringElementHandler(self, tag): + """Handle end of an XML string element.""" + element = self.element + if element is not None: + self.parser.StartElementHandler = self.startElementHandler + self.parser.EndElementHandler = self.endElementHandler + self.parser.CharacterDataHandler = self.skipCharacterDataHandler + data = "".join(self.data) + self.data = [] + attributes = self.attributes + self.attributes = None + if self.namespace_prefix: + try: + uri, name = tag.split() + except ValueError: + pass + else: + prefix = self.namespace_prefix[uri] + tag = f"{prefix}:{name}" + if tag in self.items: + assert tag == "Item" + key = attributes["Name"] + del attributes["Name"] + else: + key = tag + value = StringElement(data, tag, attributes, key) + if element is None: + self.record = element + else: + element.store(value) + self.allowed_tags = None + + def endRawElementHandler(self, name): + """Handle end of an XML raw element.""" + self.level -= 1 + if self.level == 0: + self.parser.EndElementHandler = self.endStringElementHandler + if self.namespace_prefix: + try: + uri, name = name.split() + except ValueError: + pass + tag = "" % name + self.data.append(tag) + + def endSkipElementHandler(self, name): + """Handle end of an XML skip element.""" + self.level -= 1 + if self.level == 0: + self.parser.StartElementHandler = self.startElementHandler + self.parser.EndElementHandler = self.endElementHandler + + def endErrorElementHandler(self, tag): + """Handle end of an XML error element.""" + element = self.element + if element is not None: + self.parser.StartElementHandler = self.startElementHandler + self.parser.EndElementHandler = self.endElementHandler + self.parser.CharacterDataHandler = self.skipCharacterDataHandler + data = "".join(self.data) + if data == "": + return + if self.ignore_errors is False: + raise RuntimeError(data) + self.data = [] + value = ErrorElement(data, tag) + if element is None: + self.record = element + else: + element.store(value) + + def endElementHandler(self, name): + """Handle end of an XML element.""" + element = self.element + self.element = element.parent + del element.parent + + def endIntegerElementHandler(self, tag): + """Handle end of an XML integer element.""" + attributes = self.attributes + self.attributes = None + assert tag == "Item" + key = attributes["Name"] + del attributes["Name"] + if self.data: + value = int("".join(self.data)) + self.data = [] + value = IntegerElement(value, tag, attributes, key) + else: + value = NoneElement(tag, attributes, key) + element = self.element + if element is None: + self.record = value + else: + self.parser.EndElementHandler = self.endElementHandler + self.parser.CharacterDataHandler = self.skipCharacterDataHandler + if value is None: + return + element.store(value) + + def characterDataHandlerRaw(self, content): + """Handle character data as-is (raw).""" + self.data.append(content) + + def characterDataHandlerEscape(self, content): + """Handle character data by encoding it.""" + content = escape(content) + self.data.append(content) + + def skipCharacterDataHandler(self, content): + """Handle character data by skipping it.""" + + def parse_xsd(self, root): + """Parse an XSD file.""" + prefix = "{http://www.w3.org/2001/XMLSchema}" + for element in root: + isSimpleContent = False + attribute_keys = [] + keys = [] + multiple = [] + assert element.tag == prefix + "element" + name = element.attrib["name"] + assert len(element) == 1 + complexType = element[0] + assert complexType.tag == prefix + "complexType" + for component in complexType: + tag = component.tag + if tag == prefix + "attribute": + # we could distinguish by type; keeping string for now + attribute_keys.append(component.attrib["name"]) + elif tag == prefix + "sequence": + maxOccurs = component.attrib.get("maxOccurs", "1") + for key in component: + assert key.tag == prefix + "element" + ref = key.attrib["ref"] + keys.append(ref) + if maxOccurs != "1" or key.attrib.get("maxOccurs", "1") != "1": + multiple.append(ref) + elif tag == prefix + "simpleContent": + assert len(component) == 1 + extension = component[0] + assert extension.tag == prefix + "extension" + assert extension.attrib["base"] == "xs:string" + for attribute in extension: + assert attribute.tag == prefix + "attribute" + # we could distinguish by type; keeping string for now + attribute_keys.append(attribute.attrib["name"]) + isSimpleContent = True + allowed_tags = frozenset(keys) + if len(keys) == 1 and keys == multiple: + assert not isSimpleContent + args = (allowed_tags,) + self.constructors[name] = (ListElement, args) + elif len(keys) >= 1: + assert not isSimpleContent + repeated_tags = frozenset(multiple) + args = (allowed_tags, repeated_tags) + self.constructors[name] = (DictionaryElement, args) + else: + self.strings[name] = allowed_tags + + def elementDecl(self, name, model): + """Call a call-back function for each element declaration in a DTD. + + This is used for each element declaration in a DTD like:: + + + + The purpose of this function is to determine whether this element + should be regarded as a string, integer, list, dictionary, structure, + or error. + """ + if name.upper() == "ERROR": + self.errors.add(name) + return + if name == "Item" and model == ( + expat.model.XML_CTYPE_MIXED, + expat.model.XML_CQUANT_REP, + None, + ((expat.model.XML_CTYPE_NAME, expat.model.XML_CQUANT_NONE, "Item", ()),), + ): + # Special case. As far as I can tell, this only occurs in the + # eSummary DTD. + self.items.add(name) + return + # First, remove ignorable parentheses around declarations + while ( + model[0] in (expat.model.XML_CTYPE_SEQ, expat.model.XML_CTYPE_CHOICE) + and model[1] in (expat.model.XML_CQUANT_NONE, expat.model.XML_CQUANT_OPT) + and len(model[3]) == 1 + ): + model = model[3][0] + # PCDATA declarations correspond to strings + if model[0] in (expat.model.XML_CTYPE_MIXED, expat.model.XML_CTYPE_EMPTY): + if model[1] == expat.model.XML_CQUANT_REP: + children = model[3] + allowed_tags = frozenset(child[2] for child in children) + else: + allowed_tags = frozenset() + self.strings[name] = allowed_tags + return + # Children can be anything; use a dictionary-type element + if model == (expat.model.XML_CTYPE_ANY, expat.model.XML_CQUANT_NONE, None, ()): + allowed_tags = None + repeated_tags = None + args = (allowed_tags, repeated_tags) + self.constructors[name] = (DictionaryElement, args) + return + # List-type elements + if model[0] in ( + expat.model.XML_CTYPE_CHOICE, + expat.model.XML_CTYPE_SEQ, + ) and model[1] in (expat.model.XML_CQUANT_PLUS, expat.model.XML_CQUANT_REP): + children = model[3] + allowed_tags = frozenset(child[2] for child in children) + if model[0] == expat.model.XML_CTYPE_SEQ: + if len(children) > 1: + assert model[1] == expat.model.XML_CQUANT_PLUS + first_child = children[0] + assert first_child[1] == expat.model.XML_CQUANT_NONE + first_tag = first_child[2] + args = allowed_tags, first_tag + self.constructors[name] = (OrderedListElement, args) + return + assert len(children) == 1 + self.constructors[name] = (ListElement, (allowed_tags,)) + return + # This is the tricky case. Check which keys can occur multiple + # times. If only one key is possible, and it can occur multiple + # times, then this is a list. If more than one key is possible, + # but none of them can occur multiple times, then this is a + # dictionary. Otherwise, this is a structure. + # In 'single' and 'multiple', we keep track which keys can occur + # only once, and which can occur multiple times. + single = [] + multiple = [] + errors = [] + # The 'count' function is called recursively to make sure all the + # children in this model are counted. + + def count(model): + quantifier, key, children = model[1:] + if key is None: + if quantifier in ( + expat.model.XML_CQUANT_PLUS, + expat.model.XML_CQUANT_REP, + ): + for child in children: + multiple.append(child[2]) + else: + for child in children: + count(child) + elif key.upper() == "ERROR": + errors.append(key) + else: + if quantifier in ( + expat.model.XML_CQUANT_NONE, + expat.model.XML_CQUANT_OPT, + ): + single.append(key) + elif quantifier in ( + expat.model.XML_CQUANT_PLUS, + expat.model.XML_CQUANT_REP, + ): + multiple.append(key) + + count(model) + if len(single) == 0 and len(multiple) == 1: + allowed_tags = frozenset(multiple + errors) + self.constructors[name] = (ListElement, (allowed_tags,)) + else: + allowed_tags = frozenset(single + multiple + errors) + repeated_tags = frozenset(multiple) + args = (allowed_tags, repeated_tags) + self.constructors[name] = (DictionaryElement, args) + + def open_dtd_file(self, filename): + """Open specified DTD file.""" + if DataHandler.local_dtd_dir is not None: + path = os.path.join(DataHandler.local_dtd_dir, filename) + try: + handle = open(path, "rb") + except FileNotFoundError: + pass + else: + return handle + path = os.path.join(DataHandler.global_dtd_dir, filename) + try: + handle = open(path, "rb") + except FileNotFoundError: + pass + else: + return handle + return None + + def open_xsd_file(self, filename): + """Open specified XSD file.""" + if DataHandler.local_xsd_dir is not None: + path = os.path.join(DataHandler.local_xsd_dir, filename) + try: + handle = open(path, "rb") + except FileNotFoundError: + pass + else: + return handle + path = os.path.join(DataHandler.global_xsd_dir, filename) + try: + handle = open(path, "rb") + except FileNotFoundError: + pass + else: + return handle + return None + + def save_dtd_file(self, filename, text): + """Save DTD file to cache.""" + if DataHandler.local_dtd_dir is None: + return + path = os.path.join(DataHandler.local_dtd_dir, filename) + try: + handle = open(path, "wb") + except OSError: + warnings.warn(f"Failed to save {filename} at {path}") + else: + handle.write(text) + handle.close() + + def save_xsd_file(self, filename, text): + """Save XSD file to cache.""" + if DataHandler.local_xsd_dir is None: + return + path = os.path.join(DataHandler.local_xsd_dir, filename) + try: + handle = open(path, "wb") + except OSError: + warnings.warn(f"Failed to save {filename} at {path}") + else: + handle.write(text) + handle.close() + + def verify_security(self, url, verify_hostname=True): + """Check if the given URL is from a trustable source. + + When ``self.bypass_url_security`` evaluates to ``True``, + all URL security checks will be skipped. + """ + if not self.bypass_url_security: + parts = urlparse(url) + scheme = parts.scheme + hostname = parts.hostname + if scheme != "https" or ( + verify_hostname and not hostname.endswith(".nlm.nih.gov") + ): + raise ValueError(f"Expected secure URL to NCBI, found {url!r}") + + def externalEntityRefHandler(self, context, base, systemId, publicId): + """Handle external entity reference in order to cache DTD locally. + + The purpose of this function is to load the DTD locally, instead + of downloading it from the URL specified in the XML. Using the local + DTD results in much faster parsing. If the DTD is not found locally, + we try to download it. If new DTDs become available from NCBI, + putting them in Bio/Entrez/DTDs will allow the parser to see them. + """ + urlinfo = urlparse(systemId) + if urlinfo.scheme in ["http", "https", "ftp"]: + # Then this is an absolute path to the DTD. + url = systemId + elif urlinfo.scheme == "": + # Then this is a relative path to the DTD. + # Look at the parent URL to find the full path. + try: + source = self.dtd_urls[-1] + except IndexError: + # Assume the default URL for DTDs if the top parent + # does not contain an absolute path + source = "https://www.ncbi.nlm.nih.gov/dtd/" + else: + source = os.path.dirname(source) + # urls always have a forward slash, don't use os.path.join + url = source.rstrip("/") + "/" + systemId + else: + raise ValueError("Unexpected URL scheme %r" % urlinfo.scheme) + + # NOTE: This trusts any external references from a trusted parent, + # even if these external references go to unknown hosts, + # e.g. when NCBI starts referencing things on a new host + # from existing DTD files. + # Needs to be checked *prior* to appending to ``self.dtd_urls``. + self.verify_security(url, verify_hostname=not self.dtd_urls) + + # NOTE: Since ``self.dtd_urls`` being non-empty has security + # consequences with the check above, we use a ``finally`` wrap + # here, in order to guarantee that push and pop are matched. + self.dtd_urls.append(url) + try: + # First, try to load the local version of the DTD file + location, filename = os.path.split(systemId) + handle = self.open_dtd_file(filename) + if not handle: + # DTD is not available as a local file. Try accessing it through + # the internet instead. + try: + handle = urlopen(url) + except OSError: + raise RuntimeError( + f"Failed to access {filename} at {url}" + ) from None + text = handle.read() + handle.close() + self.save_dtd_file(filename, text) + handle = BytesIO(text) + + parser = self.parser.ExternalEntityParserCreate(context) + parser.ElementDeclHandler = self.elementDecl + parser.ParseFile(handle) + handle.close() + finally: + self.dtd_urls.pop() + + self.parser.StartElementHandler = self.startElementHandler + return 1 diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/IPGReportSet.xsd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/IPGReportSet.xsd new file mode 100644 index 0000000000000000000000000000000000000000..6194a26727bc0fa51df15e582b0b1fe87fb2589d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/IPGReportSet.xsd @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/NCBI_BlastOutput2.mod.xsd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/NCBI_BlastOutput2.mod.xsd new file mode 100644 index 0000000000000000000000000000000000000000..827422b44db36661b51bda703d6e888c1bc8a2b4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/NCBI_BlastOutput2.mod.xsd @@ -0,0 +1,360 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/NCBI_BlastOutput2.xsd b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/NCBI_BlastOutput2.xsd new file mode 100644 index 0000000000000000000000000000000000000000..ffe5c683dff985b8fb7c53e169aef03d98aee57b --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/XSDs/NCBI_BlastOutput2.xsd @@ -0,0 +1,22 @@ + + + + + + + + diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..17806d5a4fc605d58c6e999dff8ff1e442a1be9e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/__init__.py @@ -0,0 +1,747 @@ +# Copyright 1999-2000 by Jeffrey Chang. All rights reserved. +# Copyright 2008-2013 by Michiel de Hoon. All rights reserved. +# Revisions copyright 2011-2016 by Peter Cock. All rights reserved. +# Revisions copyright 2015 by Eric Rasche. All rights reserved. +# Revisions copyright 2015 by Carlos Pena. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Provides code to access NCBI over the WWW. + +The main Entrez web page is available at: +https://www.ncbi.nlm.nih.gov/search/ + +Entrez Programming Utilities web page is available at: +https://www.ncbi.nlm.nih.gov/books/NBK25501/ + +This module provides a number of functions like ``efetch`` (short for +Entrez Fetch) which will return the data as a handle object. This is +a standard interface used in Python for reading data from a file, or +in this case a remote network connection, and provides methods like +``.read()`` or offers iteration over the contents line by line. See +also "What the heck is a handle?" in the Biopython Tutorial and +Cookbook: https://biopython.org/docs/latest/Tutorial/index.html + +The handle returned by these functions can be either in text mode or +in binary mode, depending on the data requested and the results +returned by NCBI Entrez. Typically, XML data will be in binary mode +while other data will be in text mode, as required by the downstream +parser to parse the data. + +Unlike a handle to a file on disk from the ``open(filename)`` function, +which has a ``.name`` attribute giving the filename, the handles from +``Bio.Entrez`` all have a ``.url`` attribute instead giving the URL +used to connect to the NCBI Entrez API. + +The ``epost``, ``efetch``, and ``esummary`` tools take an "id" parameter +which corresponds to one or more database UIDs (or accession.version +identifiers in the case of sequence databases such as "nuccore" or +"protein"). The Python value of the "id" keyword passed to these functions +may be either a single ID as a string or integer or multiple IDs as an +iterable of strings/integers. You may also pass a single string containing +multiple IDs delimited by commas. The ``elink`` tool also accepts multiple +IDs but the argument is handled differently than the other three. See that +function's docstring for more information. + +All the functions that send requests to the NCBI Entrez API will +automatically respect the NCBI rate limit (of 3 requests per second +without an API key, or 10 requests per second with an API key) and +will automatically retry when encountering transient failures +(i.e. connection failures or HTTP 5XX codes). By default, Biopython +does a maximum of three tries before giving up, and sleeps for 15 +seconds between tries. You can tweak these parameters by setting +``Bio.Entrez.max_tries`` and ``Bio.Entrez.sleep_between_tries``. + +The Entrez module also provides an XML parser which takes a handle +as input. + +Variables: + + - email Set the Entrez email parameter (default is not set). + - tool Set the Entrez tool parameter (default is ``biopython``). + - api_key Personal API key from NCBI. If not set, only 3 queries per + second are allowed. 10 queries per seconds otherwise with a + valid API key. + - max_tries Configures how many times failed requests will be + automatically retried on error (default is 3). + - sleep_between_tries The delay, in seconds, before retrying a request on + error (default is 15). + +Functions: + + - efetch Retrieves records in the requested format from a list of one or + more primary IDs or from the user's environment + - epost Posts a file containing a list of primary IDs for future use in + the user's environment to use with subsequent search strategies + - esearch Searches and retrieves primary IDs (for use in EFetch, ELink, + and ESummary) and term translations and optionally retains + results for future use in the user's environment. + - elink Checks for the existence of an external or Related Articles link + from a list of one or more primary IDs. Retrieves primary IDs + and relevancy scores for links to Entrez databases or Related + Articles; creates a hyperlink to the primary LinkOut provider + for a specific ID and database, or lists LinkOut URLs + and Attributes for multiple IDs. + - einfo Provides field index term counts, last update, and available + links for each database. + - esummary Retrieves document summaries from a list of primary IDs or from + the user's environment. + - egquery Provides Entrez database counts in XML for a single search + using Global Query. + - espell Retrieves spelling suggestions. + - ecitmatch Retrieves PubMed IDs (PMIDs) that correspond to a set of + input citation strings. + + - read Parses the XML results returned by any of the above functions. + Alternatively, the XML data can be read from a file opened in binary mode. + Typical usage is: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> handle = Entrez.einfo() # or esearch, efetch, ... + >>> record = Entrez.read(handle) + >>> handle.close() + + where record is now a Python dictionary or list. + + - parse Parses the XML results returned by those of the above functions + which can return multiple records - such as efetch, esummary + and elink. Typical usage is: + + >>> handle = Entrez.efetch(db="taxonomy", id="9615,9685", retmode="xml") + >>> records = Entrez.parse(handle) + >>> for record in records: + ... print(record['TaxId'], record["OtherNames"]['GenbankCommonName']) + ... + 9615 dog + 9685 domestic cat + >>> handle.close() + + This function is appropriate only if the XML file contains + multiple records, and is particular useful for large files. + + - _open Internally used function. + +""" + +import io +import time +import warnings +from urllib.error import HTTPError +from urllib.error import URLError +from urllib.parse import urlencode +from urllib.request import Request +from urllib.request import urlopen + +from Bio._utils import function_with_previous + +email = None +max_tries = 3 +sleep_between_tries = 15 +tool = "biopython" +api_key = None +local_cache = None + + +# XXX retmode? +def epost(db, **keywds): + """Post a file of identifiers for future use. + + Posts a file containing a list of UIs for future use in the user's + environment to use with subsequent search strategies. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.EPost + + :returns: Handle to the results. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi" + variables = {"db": db} + variables.update(keywds) + request = _build_request(cgi, variables, post=True) + return _open(request) + + +def efetch(db, **keywords): + """Fetch Entrez results which are returned as a handle. + + EFetch retrieves records in the requested format from a list or set of one or + more UIs or from user's environment. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.EFetch + + Short example: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> handle = Entrez.efetch(db="nucleotide", id="AY851612", rettype="gb", retmode="text") + >>> print(handle.readline().strip()) + LOCUS AY851612 892 bp DNA linear PLN 10-APR-2007 + >>> handle.close() + + This will automatically use an HTTP POST rather than HTTP GET if there + are over 200 identifiers as recommended by the NCBI. + + **Warning:** The NCBI changed the default retmode in Feb 2012, so many + databases which previously returned text output now give XML. + + :returns: Handle to the results. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi" + variables = {"db": db} + variables.update(keywords) + request = _build_request(cgi, variables) + return _open(request) + + +def esearch(db, term, **keywds): + """Run an Entrez search and return a handle to the results. + + ESearch searches and retrieves primary IDs (for use in EFetch, ELink + and ESummary) and term translations, and optionally retains results + for future use in the user's environment. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch + + Short example: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> handle = Entrez.esearch( + ... db="nucleotide", retmax=10, idtype="acc", + ... term="opuntia[ORGN] accD 2007[Publication Date]" + ... ) + ... + >>> record = Entrez.read(handle) + >>> handle.close() + >>> int(record["Count"]) >= 2 + True + >>> "EF590893.1" in record["IdList"] + True + >>> "EF590892.1" in record["IdList"] + True + + :returns: Handle to the results, which are always in XML format. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi" + variables = {"db": db, "term": term} + variables.update(keywds) + request = _build_request(cgi, variables) + return _open(request) + + +def elink(**keywds): + """Check for linked external articles and return a handle. + + ELink checks for the existence of an external or Related Articles link + from a list of one or more primary IDs; retrieves IDs and relevancy + scores for links to Entrez databases or Related Articles; creates a + hyperlink to the primary LinkOut provider for a specific ID and + database, or lists LinkOut URLs and attributes for multiple IDs. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ELink + + Note that ELink treats the "id" parameter differently than the other + tools when multiple values are given. You should generally pass multiple + UIDs as a list of strings or integers. This will provide a "one-to-one" + mapping from source database UIDs to destination database UIDs in the + result. If multiple source UIDs are passed as a single comma-delimited + string all destination UIDs will be mixed together in the result. + + This example finds articles related to the Biopython application + note's entry in the PubMed database: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> pmid = "19304878" + >>> handle = Entrez.elink(dbfrom="pubmed", id=pmid, linkname="pubmed_pubmed") + >>> record = Entrez.read(handle) + >>> handle.close() + >>> print(record[0]["LinkSetDb"][0]["LinkName"]) + pubmed_pubmed + >>> linked = [link["Id"] for link in record[0]["LinkSetDb"][0]["Link"]] + >>> "14630660" in linked + True + + This is explained in much more detail in the Biopython Tutorial. + + :returns: Handle to the results, by default in XML format. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi" + variables = {} + variables.update(keywds) + request = _build_request(cgi, variables, join_ids=False) + return _open(request) + + +def einfo(**keywds): + """Return a summary of the Entrez databases as a results handle. + + EInfo provides field names, index term counts, last update, and + available links for each Entrez database. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.EInfo + + Short example: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> record = Entrez.read(Entrez.einfo()) + >>> 'pubmed' in record['DbList'] + True + + :returns: Handle to the results, by default in XML format. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/einfo.fcgi" + variables = {} + variables.update(keywds) + request = _build_request(cgi, variables) + return _open(request) + + +def esummary(**keywds): + """Retrieve document summaries as a results handle. + + ESummary retrieves document summaries from a list of primary IDs or + from the user's environment. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESummary + + This example discovers more about entry 19923 in the structure + database: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> handle = Entrez.esummary(db="structure", id="19923") + >>> record = Entrez.read(handle) + >>> handle.close() + >>> print(record[0]["Id"]) + 19923 + >>> print(record[0]["PdbDescr"]) + CRYSTAL STRUCTURE OF E. COLI ACONITASE B + + + :returns: Handle to the results, by default in XML format. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi" + variables = {} + variables.update(keywds) + request = _build_request(cgi, variables) + return _open(request) + + +def espell(**keywds): + """Retrieve spelling suggestions as a results handle. + + ESpell retrieves spelling suggestions, if available. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESpell + + Short example: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> record = Entrez.read(Entrez.espell(term="biopythooon")) + >>> print(record["Query"]) + biopythooon + >>> print(record["CorrectedQuery"]) + biopython + + :returns: Handle to the results, by default in XML format. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/espell.fcgi" + variables = {} + variables.update(keywds) + request = _build_request(cgi, variables) + return _open(request) + + +def _update_ecitmatch_variables(keywds): + # XML is the only supported value, and it actually returns TXT. + variables = {"retmode": "xml"} + citation_keys = ( + "journal_title", + "year", + "volume", + "first_page", + "author_name", + "key", + ) + + # Accept pre-formatted strings + if isinstance(keywds["bdata"], str): + variables.update(keywds) + else: + # Alternatively accept a nicer interface + variables["db"] = keywds["db"] + bdata = [] + for citation in keywds["bdata"]: + formatted_citation = "|".join( + [citation.get(key, "") for key in citation_keys] + ) + bdata.append(formatted_citation) + variables["bdata"] = "\r".join(bdata) + return variables + + +def ecitmatch(**keywds): + """Retrieve PMIDs for input citation strings, returned as a handle. + + ECitMatch retrieves PubMed IDs (PMIDs) that correspond to a set of input + citation strings. + + See the online documentation for an explanation of the parameters: + https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ECitMatch + + Short example: + + >>> from Bio import Entrez + >>> Entrez.email = "Your.Name.Here@example.org" + >>> citation_1 = {"journal_title": "proc natl acad sci u s a", + ... "year": "1991", "volume": "88", "first_page": "3248", + ... "author_name": "mann bj", "key": "citation_1"} + >>> handle = Entrez.ecitmatch(db="pubmed", bdata=[citation_1]) + >>> print(handle.read().strip().split("|")) + ['proc natl acad sci u s a', '1991', '88', '3248', 'mann bj', 'citation_1', '2014248'] + >>> handle.close() + + :returns: Handle to the results, by default in plain text. + :raises urllib.error.URLError: If there's a network error. + """ + cgi = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/ecitmatch.cgi" + variables = _update_ecitmatch_variables(keywds) + request = _build_request(cgi, variables, ecitmatch=True) + return _open(request) + + +def read(source, validate=True, escape=False, ignore_errors=False): + """Parse an XML file from the NCBI Entrez Utilities into python objects. + + This function parses an XML file created by NCBI's Entrez Utilities, + returning a multilevel data structure of Python lists and dictionaries. + Most XML files returned by NCBI's Entrez Utilities can be parsed by + this function, provided its DTD is available. Biopython includes the + DTDs for most commonly used Entrez Utilities. + + The argument ``source`` must be a file or file-like object opened in binary + mode, or a filename. The parser detects the encoding from the XML file, and + uses it to convert all text in the XML to the correct Unicode string. The + functions in Bio.Entrez to access NCBI Entrez will automatically return XML + data in binary mode. For files, use mode "rb" when opening the file, as in + + >>> from Bio import Entrez + >>> path = "Entrez/esearch1.xml" + >>> stream = open(path, "rb") # opened in binary mode + >>> record = Entrez.read(stream) + >>> print(record['QueryTranslation']) + "biopython"[All Fields] + >>> stream.close() + + Alternatively, you can use the filename directly, as in + + >>> record = Entrez.read(path) + >>> print(record['QueryTranslation']) + "biopython"[All Fields] + + which is safer, as the file stream will automatically be closed after the + record has been read, or if an error occurs. + + If validate is True (default), the parser will validate the XML file + against the DTD, and raise an error if the XML file contains tags that + are not represented in the DTD. If validate is False, the parser will + simply skip such tags. + + If escape is True, all characters that are not valid HTML are replaced + by HTML escape characters to guarantee that the returned strings are + valid HTML fragments. For example, a less-than sign (<) is replaced by + <. If escape is False (default), the string is returned as is. + + If ignore_errors is False (default), any error messages in the XML file + will raise a RuntimeError. If ignore_errors is True, error messages will + be stored as ErrorElement items, without raising an exception. + + Whereas the data structure seems to consist of generic Python lists, + dictionaries, strings, and so on, each of these is actually a class + derived from the base type. This allows us to store the attributes + (if any) of each element in a dictionary my_element.attributes, and + the tag name in my_element.tag. + """ + from .Parser import DataHandler + + handler = DataHandler(validate, escape, ignore_errors) + record = handler.read(source) + return record + + +def parse(source, validate=True, escape=False, ignore_errors=False): + """Parse an XML file from the NCBI Entrez Utilities into python objects. + + This function parses an XML file created by NCBI's Entrez Utilities, + returning a multilevel data structure of Python lists and dictionaries. + This function is suitable for XML files that (in Python) can be represented + as a list of individual records. Whereas 'read' reads the complete file + and returns a single Python list, 'parse' is a generator function that + returns the records one by one. This function is therefore particularly + useful for parsing large files. + + Most XML files returned by NCBI's Entrez Utilities can be parsed by + this function, provided its DTD is available. Biopython includes the + DTDs for most commonly used Entrez Utilities. + + The argument ``source`` must be a file or file-like object opened in binary + mode, or a filename. The parser detects the encoding from the XML file, and + uses it to convert all text in the XML to the correct Unicode string. The + functions in Bio.Entrez to access NCBI Entrez will automatically return XML + data in binary mode. For files, use mode "rb" when opening the file, as in + + >>> from Bio import Entrez + >>> path = "Entrez/taxonomy.xml" + >>> stream = open(path, "rb") # opened in binary mode + >>> records = Entrez.parse(stream) + >>> for record in records: + ... print(record['TaxId'], record["OtherNames"]['GenbankCommonName']) + ... + 9615 dog + 9685 domestic cat + >>> stream.close() + + Alternatively, you can use the filename directly, as in + + >>> records = Entrez.parse(path) + >>> for record in records: + ... print(record['TaxId'], record["OtherNames"]['GenbankCommonName']) + ... + 9615 dog + 9685 domestic cat + + which is safer, as the file stream will automatically be closed after all + the records have been read, or if an error occurs. + + If validate is True (default), the parser will validate the XML file + against the DTD, and raise an error if the XML file contains tags that + are not represented in the DTD. If validate is False, the parser will + simply skip such tags. + + If escape is True, all characters that are not valid HTML are replaced + by HTML escape characters to guarantee that the returned strings are + valid HTML fragments. For example, a less-than sign (<) is replaced by + <. If escape is False (default), the string is returned as is. + + If ignore_errors is False (default), any error messages in the XML file + will raise a RuntimeError. If ignore_errors is True, error messages will + be stored as ErrorElement items, without raising an exception. + + Whereas the data structure seems to consist of generic Python lists, + dictionaries, strings, and so on, each of these is actually a class + derived from the base type. This allows us to store the attributes + (if any) of each element in a dictionary my_element.attributes, and + the tag name in my_element.tag. + """ + from .Parser import DataHandler + + handler = DataHandler(validate, escape, ignore_errors) + records = handler.parse(source) + return records + + +@function_with_previous +def _open(request): + """Make an HTTP request to Entrez, handling errors and enforcing rate limiting (PRIVATE). + + Does some simple error checking and will try again after certain types of errors, up to + ``max_retries`` times. This function also enforces the "up to three queries per second + rule" to avoid abusing the NCBI servers (this limit is increased to 10 if using an API key). + + :param req_or_cgi: A Request object returned by ``_build_request``. + :type req_or_cgi: urllib.request.Request + :returns: Handle to HTTP response as returned by ``urllib.request.urlopen``. Will be wrapped in + an ``io.TextIOWrapper`` if its content type is plain text. + :rtype: http.client.HTTPResponse or io.TextIOWrapper + :raises urllib.error.URLError: Errors raised by ``urlopen`` past the maximum number of retries. + """ + # NCBI requirement: At most three queries per second if no API key is provided. + # Equivalently, at least a third of second between queries + # Using just 0.333333334 seconds sometimes hit the NCBI rate limit, + # the slightly longer pause of 0.37 seconds has been more reliable. + delay = 0.1 if _has_api_key(request) else 0.37 + current = time.time() + wait = _open.previous + delay - current + if wait > 0: + time.sleep(wait) + _open.previous = current + wait + else: + _open.previous = current + + for i in range(max_tries): + try: + handle = urlopen(request) + except HTTPError as exception: + # Reraise if the final try fails + if i >= max_tries - 1: + raise + # Reraise if the exception is triggered by a HTTP 4XX error + # indicating some kind of bad request, UNLESS it's specifically a + # 429 "Too Many Requests" response. NCBI seems to sometimes + # erroneously return 429s even when their rate limit is + # honored (and indeed even with the rate-limit-related fudging + # higher up in this function in place), so the best we can do is + # treat them as a serverside error and try again after sleeping + # for a bit. + if exception.code // 100 == 4 and exception.code != 429: + raise + except URLError: + # Reraise if the final try fails + if i >= max_tries - 1: + raise + # Treat as a transient error and try again after a brief delay: + time.sleep(sleep_between_tries) + else: + break + + subtype = handle.headers.get_content_subtype() + if subtype == "plain": + url = handle.url + handle = io.TextIOWrapper(handle, encoding="UTF-8") + handle.url = url + return handle + + +_open.previous = 0 + + +def _build_request(cgi, params=None, post=None, ecitmatch=False, join_ids=True): + """Build a Request object for an E-utility. + + :param str cgi: base URL for the CGI script to access. + :param params: Mapping containing options to pass to the CGI script. Keys must be strings. + :type params: dict or None + :param bool post: Whether to use the HTTP POST method rather than GET. By default (``post=None``), + POST is used if the URL encoded parameters would be over 1000 characters long, as is + suggested in the E-Utilities documentation. + :param bool ecitmatch: Don't URL-encode pipe ("|") characters, this is expected by the ecitmatch + tool. + :param bool join_ids: Passed to ``_construct_params``. + :returns: A request object ready to be passed to ``_open``. + :rtype: urllib.request.Request + """ + params = _construct_params(params, join_ids=join_ids) + + params_str = urlencode(params, doseq=True) + if ecitmatch: + params_str = params_str.replace("%7C", "|") + + # By default, post is None. Set to a boolean to over-ride length choice: + if post is None and len(params_str) > 1000: + post = True + + # NCBI prefers an HTTP POST instead of an HTTP GET if there are more than about 200 IDs + if post is None and "id" in params: + idcount = params["id"].count(",") + 1 + if idcount >= 200: + post = True + + if post: + return Request(cgi, data=params_str.encode("utf8"), method="POST") + else: + return Request(cgi + "?" + params_str, method="GET") + + +def _construct_params(params, join_ids=True): + """Construct/format parameter dict for an Entrez request. + + :param params: User-supplied parameters. + :type params: dict or None + :param bool join_ids: If True and the "id" key of ``params`` is a list + containing multiple UIDs, join them into a single comma-delimited string. + :returns: Parameters with defaults added and keys with None values removed. + :rtype: dict + """ + if params is None: + params = {} + + # Tell Entrez that we are using Biopython (or whatever the user has + # specified explicitly in the parameters or by changing the default) + params.setdefault("tool", tool) + + # Tell Entrez who we are + params.setdefault("email", email) + params.setdefault("api_key", api_key) + + # Remove None values from the parameters + for key, value in list(params.items()): + if value is None: + del params[key] + + # Warn if email not set + if "email" not in params: + warnings.warn( + """ + Email address is not specified. + + To make use of NCBI's E-utilities, NCBI requires you to specify your + email address with each request. As an example, if your email address + is A.N.Other@example.com, you can specify it as follows: + from Bio import Entrez + Entrez.email = 'A.N.Other@example.com' + In case of excessive usage of the E-utilities, NCBI will attempt to contact + a user at the email address provided before blocking access to the + E-utilities.""", + UserWarning, + ) + + # Format "id" parameter properly + if join_ids and "id" in params: + params["id"] = _format_ids(params["id"]) + + return params + + +def _format_ids(ids): + """Convert one or more UIDs to a single comma-delimited string. + + Input may be a single ID as an integer or string, an iterable of strings/ints, + or a string of IDs already separated by commas. + """ + if isinstance(ids, int): + # Single integer, just convert to str + return str(ids) + + if isinstance(ids, str): + # String which represents one or more IDs joined by commas + # Remove any whitespace around commas if they are present + return ",".join(id.strip() for id in ids.split(",")) + + # Not a string or integer, assume iterable + return ",".join(map(str, ids)) + + +def _has_api_key(request): + """Check if a Request has the api_key parameter set, to set the rate limit. + + Works with GET or POST requests. + """ + if request.method == "POST": + return b"api_key=" in request.data + return "api_key=" in request.full_url + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/__pycache__/Parser.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/__pycache__/Parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8bb0ecc78bc12b78a5e154d74340a32418acd8e1 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/__pycache__/Parser.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b367cad2fd8d1cdfff24051f2f277bf71c6e2fad Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Entrez/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Enzyme.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Enzyme.py new file mode 100644 index 0000000000000000000000000000000000000000..ca162b1013231b935a058fa814180766349c62d6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Enzyme.py @@ -0,0 +1,159 @@ +# Copyright 1999 by Jeffrey Chang. All rights reserved. +# Copyright 2009 by Michiel de Hoon. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +"""Parse the enzyme.dat file from Enzyme at ExPASy. + +See https://www.expasy.org/enzyme/ + +Tested with the release of 03-Mar-2009. + +Functions: + - read Reads a file containing one ENZYME entry + - parse Reads a file containing multiple ENZYME entries + +Classes: + - Record Holds ENZYME data. + +""" + + +def parse(handle): + """Parse ENZYME records. + + This function is for parsing ENZYME files containing multiple + records. + + Arguments: + - handle - handle to the file. + + """ + while True: + record = __read(handle) + if not record: + break + yield record + + +def read(handle): + """Read one ENZYME record. + + This function is for parsing ENZYME files containing + exactly one record. + + Arguments: + - handle - handle to the file. + + """ + record = __read(handle) + # We should have reached the end of the record by now + remainder = handle.read() + if remainder: + raise ValueError("More than one ENZYME record found") + return record + + +class Record(dict): + """Holds information from an ExPASy ENZYME record as a Python dictionary. + + Each record contains the following keys: + + - ID: EC number + - DE: Recommended name + - AN: Alternative names (if any) + - CA: Catalytic activity + - CF: Cofactors (if any) + - PR: Pointers to any Prosite documentation entries that correspond to the + enzyme + - DR: Pointers to any Swiss-Prot protein sequence entries that correspond + to the enzyme + - CC: Comments + + """ + + def __init__(self): + """Initialize the class.""" + dict.__init__(self) + self["ID"] = "" + self["DE"] = "" + self["AN"] = [] + self["CA"] = "" + self["CF"] = "" + self["CC"] = [] # one comment per line + self["PR"] = [] + self["DR"] = [] + + def __repr__(self): + """Return the canonical string representation of the Record object.""" + if self["ID"]: + if self["DE"]: + return f"{self.__class__.__name__} ({self['ID']}, {self['DE']})" + else: + return f"{self.__class__.__name__} ({self['ID']})" + else: + return f"{self.__class__.__name__} ( )" + + def __str__(self): + """Return a readable string representation of the Record object.""" + output = [ + "ID: " + self["ID"], + "DE: " + self["DE"], + "AN: " + repr(self["AN"]), + "CA: '" + self["CA"] + "'", + "CF: " + self["CF"], + "CC: " + repr(self["CC"]), + "PR: " + repr(self["PR"]), + "DR: %d Records" % len(self["DR"]), + ] + return "\n".join(output) + + +# Everything below is private + + +def __read(handle): + record = None + for line in handle: + key, value = line[:2], line[5:].rstrip() + if key == "ID": + record = Record() + record["ID"] = value + elif key == "DE": + record["DE"] += value + elif key == "AN": + if record["AN"] and not record["AN"][-1].endswith("."): + record["AN"][-1] += " " + value + else: + record["AN"].append(value) + elif key == "CA": + record["CA"] += value + elif key == "DR": + pair_data = value.rstrip(";").split(";") + for pair in pair_data: + t1, t2 = pair.split(",") + row = [t1.strip(), t2.strip()] + record["DR"].append(row) + elif key == "CF": + if record["CF"]: + record["CF"] += " " + value + else: + record["CF"] = value + elif key == "PR": + assert value.startswith("PROSITE; ") + value = value[9:].rstrip(";") + record["PR"].append(value) + elif key == "CC": + if value.startswith("-!- "): + record["CC"].append(value[4:]) + elif value.startswith(" ") and record["CC"]: + record["CC"][-1] += value[3:] + # copyright notice is silently skipped + elif key == "//": + if record: + return record + else: # This was the copyright notice + continue + if record: + raise ValueError("Unexpected end of stream") diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Prodoc.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Prodoc.py new file mode 100644 index 0000000000000000000000000000000000000000..8120b010ac42ae7d5fe6f92a3ce44b241d0d38c0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Prodoc.py @@ -0,0 +1,173 @@ +# Copyright 2000 by Jeffrey Chang. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +"""Code to work with the prosite.doc file from Prosite. + +See https://www.expasy.org/prosite/ + +Tested with: + - Release 15.0, July 1998 + - Release 16.0, July 1999 + - Release 20.22, 13 November 2007 + - Release 20.43, 10 February 2009 + +Functions: + - read Read a Prodoc file containing exactly one Prodoc entry. + - parse Iterates over entries in a Prodoc file. + +Classes: + - Record Holds Prodoc data. + - Reference Holds data from a Prodoc reference. + +""" + + +def read(handle): + """Read in a record from a file with exactly one Prodoc record.""" + record = __read(handle) + # We should have reached the end of the record by now + line = handle.readline() + if line: + raise ValueError("More than one Prodoc record found") + return record + + +def parse(handle): + """Iterate over the records in a Prodoc file.""" + while True: + record = __read(handle) + if not record: + return + yield record + + +class Record: + """Holds information from a Prodoc record. + + Attributes: + - accession Accession number of the record. + - prosite_refs List of tuples (prosite accession, prosite name). + - text Free format text. + - references List of reference objects. + + """ + + def __init__(self): + """Initialize the class.""" + self.accession = "" + self.prosite_refs = [] + self.text = "" + self.references = [] + + +class Reference: + """Holds information from a Prodoc citation. + + Attributes: + - number Number of the reference. (string) + - authors Names of the authors. + - citation Describes the citation. + + """ + + def __init__(self): + """Initialize the class.""" + self.number = "" + self.authors = "" + self.citation = "" + + +# Below are private functions + + +def __read_prosite_reference_line(record, line): + line = line.rstrip() + if line[-1] != "}": + raise ValueError(f"I don't understand the Prosite reference on line\n{line}") + acc, name = line[1:-1].split("; ") + record.prosite_refs.append((acc, name)) + + +def __read_text_line(record, line): + record.text += line + return True + + +def __read_reference_start(record, line): + # Read the references + reference = Reference() + reference.number = line[1:3].strip() + if line[1] == "E": + # If it's an electronic reference, then the URL is on the + # line, instead of the author. + reference.citation = line[4:].strip() + else: + reference.authors = line[4:].strip() + record.references.append(reference) + + +def __read_reference_line(record, line): + if not line.strip(): + return False + reference = record.references[-1] + if line.startswith(" "): + if reference.authors[-1] == ",": + reference.authors += line[4:].rstrip() + else: + reference.citation += line[5:] + return True + raise Exception(f"I don't understand the reference line\n{line}") + + +def __read_copyright_line(record, line): + # Skip the copyright statement + if line.startswith("+----"): + return False + return True + + +def __read(handle): + # Skip blank lines between records + for line in handle: + line = line.rstrip() + if line and not line.startswith("//"): + break + else: + return None + record = Record() + # Read the accession number + if not line.startswith("{PDOC"): + raise ValueError("Line does not start with '{PDOC':\n%s" % line) + if line[-1] != "}": + raise ValueError(f"I don't understand accession line\n{line}") + record.accession = line[1:-1] + # Read the Prosite references + for line in handle: + if line.startswith("{PS"): + __read_prosite_reference_line(record, line) + else: + break + else: + raise ValueError("Unexpected end of stream.") + # Read the actual text + if not line.startswith("{BEGIN"): + raise ValueError("Line does not start with '{BEGIN':\n%s" % line) + read_line = __read_text_line + for line in handle: + if line.startswith("{END}"): + # Clean up the record and return + for reference in record.references: + reference.citation = reference.citation.rstrip() + reference.authors = reference.authors.rstrip() + return record + elif line[0] == "[" and line[3] == "]" and line[4] == " ": + __read_reference_start(record, line) + read_line = __read_reference_line + elif line.startswith("+----"): + read_line = __read_copyright_line + elif read_line: + if not read_line(record, line): + read_line = None + raise ValueError("Unexpected end of stream.") diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Prosite.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Prosite.py new file mode 100644 index 0000000000000000000000000000000000000000..266ca68acdc3a301c9c37250d07f84d516797f35 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/Prosite.py @@ -0,0 +1,308 @@ +# Copyright 1999 by Jeffrey Chang. All rights reserved. +# Copyright 2000 by Jeffrey Chang. All rights reserved. +# Revisions Copyright 2007 by Peter Cock. All rights reserved. +# Revisions Copyright 2009 by Michiel de Hoon. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +"""Parser for the prosite dat file from Prosite at ExPASy. + +See https://www.expasy.org/prosite/ + +Tested with: + - Release 20.43, 10-Feb-2009 + - Release 2017_03 of 15-Mar-2017. + +Functions: + - read Reads a Prosite file containing one Prosite record + - parse Iterates over records in a Prosite file. + +Classes: + - Record Holds Prosite data. + +""" + + +def parse(handle): + """Parse Prosite records. + + This function is for parsing Prosite files containing multiple + records. + + Arguments: + - handle - handle to the file. + + """ + while True: + record = __read(handle) + if not record: + break + yield record + + +def read(handle): + """Read one Prosite record. + + This function is for parsing Prosite files containing + exactly one record. + + Arguments: + - handle - handle to the file. + + """ + record = __read(handle) + # We should have reached the end of the record by now + remainder = handle.read() + if remainder: + raise ValueError("More than one Prosite record found") + return record + + +class Record: + """Holds information from a Prosite record. + + Main attributes: + - name ID of the record. e.g. ADH_ZINC + - type Type of entry. e.g. PATTERN, MATRIX, or RULE + - accession e.g. PS00387 + - created Date the entry was created. (MMM-YYYY for releases + before January 2017, DD-MMM-YYYY since January 2017) + - data_update Date the 'primary' data was last updated. + - info_update Date data other than 'primary' data was last updated. + - pdoc ID of the PROSITE DOCumentation. + - description Free-format description. + - pattern The PROSITE pattern. See docs. + - matrix List of strings that describes a matrix entry. + - rules List of rule definitions (from RU lines). (strings) + - prorules List of prorules (from PR lines). (strings) + + NUMERICAL RESULTS: + - nr_sp_release SwissProt release. + - nr_sp_seqs Number of seqs in that release of Swiss-Prot. (int) + - nr_total Number of hits in Swiss-Prot. tuple of (hits, seqs) + - nr_positive True positives. tuple of (hits, seqs) + - nr_unknown Could be positives. tuple of (hits, seqs) + - nr_false_pos False positives. tuple of (hits, seqs) + - nr_false_neg False negatives. (int) + - nr_partial False negatives, because they are fragments. (int) + + COMMENTS: + - cc_taxo_range Taxonomic range. See docs for format + - cc_max_repeat Maximum number of repetitions in a protein + - cc_site Interesting site. list of tuples (pattern pos, desc.) + - cc_skip_flag Can this entry be ignored? + - cc_matrix_type + - cc_scaling_db + - cc_author + - cc_ft_key + - cc_ft_desc + - cc_version version number (introduced in release 19.0) + + The following are all lists if tuples (swiss-prot accession, swiss-prot name). + + DATA BANK REFERENCES: + - dr_positive + - dr_false_neg + - dr_false_pos + - dr_potential Potential hits, but fingerprint region not yet available. + - dr_unknown Could possibly belong + - pdb_structs List of PDB entries. + + """ + + def __init__(self): + """Initialize the class.""" + self.name = "" + self.type = "" + self.accession = "" + self.created = "" + self.data_update = "" + self.info_update = "" + self.pdoc = "" + + self.description = "" + self.pattern = "" + self.matrix = [] + self.rules = [] + self.prorules = [] + self.postprocessing = [] + + self.nr_sp_release = "" + self.nr_sp_seqs = "" + self.nr_total = (None, None) + self.nr_positive = (None, None) + self.nr_unknown = (None, None) + self.nr_false_pos = (None, None) + self.nr_false_neg = None + self.nr_partial = None + + self.cc_taxo_range = "" + self.cc_max_repeat = "" + self.cc_site = [] + self.cc_skip_flag = "" + + self.dr_positive = [] + self.dr_false_neg = [] + self.dr_false_pos = [] + self.dr_potential = [] + self.dr_unknown = [] + + self.pdb_structs = [] + + +# Everything below are private functions + + +def __read(handle): + import re + + record = None + for line in handle: + keyword, value = line[:2], line[5:].rstrip() + if keyword == "ID": + record = Record() + cols = value.split("; ") + if len(cols) != 2: + raise ValueError(f"I don't understand identification line\n{line}") + record.name = cols[0] + record.type = cols[1].rstrip(".") # don't want '.' + elif keyword == "AC": + record.accession = value.rstrip(";") + elif keyword == "DT": + # e.g. from January 2017, + # DT 01-APR-1990 CREATED; 01-APR-1990 DATA UPDATE; 01-APR-1990 INFO UPDATE. + # Older files had brackets round the date descriptions and used MMM-YYYY + dates = value.rstrip(".").split("; ") + if dates[0].endswith((" (CREATED)", " CREATED")): + # Remove last word + record.created = dates[0].rsplit(" ", 1)[0] + else: + raise ValueError(f"I don't understand date line\n{line}") + if dates[1].endswith((" (DATA UPDATE)", " DATA UPDATE")): + # Remove last two words + record.data_update = dates[1].rsplit(" ", 2)[0] + else: + raise ValueError(f"I don't understand date line\n{line}") + if dates[2].endswith((" (INFO UPDATE)", " INFO UPDATE")): + # Remove last two words + record.info_update = dates[2].rsplit(" ", 2)[0] + else: + raise ValueError(f"I don't understand date line\n{line}") + elif keyword == "DE": + record.description = value + elif keyword == "PA": + record.pattern += value + elif keyword == "MA": + record.matrix.append(value) + elif keyword == "PP": + record.postprocessing.extend(value.split(";")) + elif keyword == "RU": + record.rules.append(value) + elif keyword == "NR": + cols = value.split(";") + for col in cols: + if not col: + continue + qual, data = (word.lstrip() for word in col.split("=")) + if qual == "/RELEASE": + release, seqs = data.split(",") + record.nr_sp_release = release + record.nr_sp_seqs = int(seqs) + elif qual == "/FALSE_NEG": + record.nr_false_neg = int(data) + elif qual == "/PARTIAL": + record.nr_partial = int(data) + elif qual in ["/TOTAL", "/POSITIVE", "/UNKNOWN", "/FALSE_POS"]: + m = re.match(r"(\d+)\((\d+)\)", data) + if not m: + raise Exception(f"Broken data {data} in comment line\n{line!r}") + hits = tuple(map(int, m.groups())) + if qual == "/TOTAL": + record.nr_total = hits + elif qual == "/POSITIVE": + record.nr_positive = hits + elif qual == "/UNKNOWN": + record.nr_unknown = hits + elif qual == "/FALSE_POS": + record.nr_false_pos = hits + else: + raise ValueError(f"Unknown qual {qual} in comment line\n{line!r}") + elif keyword == "CC": + # Expect CC lines like this: + # CC /TAXO-RANGE=??EPV; /MAX-REPEAT=2; + # Can (normally) split on ";" and then on "=" + cols = value.split(";") + for col in cols: + if not col or col[:17] == "Automatic scaling": + # DNAJ_2 in Release 15 has a non-standard comment line: + # CC Automatic scaling using reversed database + # Throw it away. (Should I keep it?) + continue + if col.count("=") == 0: + # Missing qualifier! Can we recover gracefully? + # For example, from Bug 2403, in PS50293 have: + # CC /AUTHOR=K_Hofmann; N_Hulo + continue + qual, data = (word.lstrip() for word in col.split("=")) + if qual == "/TAXO-RANGE": + record.cc_taxo_range = data + elif qual == "/MAX-REPEAT": + record.cc_max_repeat = data + elif qual == "/SITE": + pos, desc = data.split(",") + record.cc_site.append((int(pos), desc)) + elif qual == "/SKIP-FLAG": + record.cc_skip_flag = data + elif qual == "/MATRIX_TYPE": + record.cc_matrix_type = data + elif qual == "/SCALING_DB": + record.cc_scaling_db = data + elif qual == "/AUTHOR": + record.cc_author = data + elif qual == "/FT_KEY": + record.cc_ft_key = data + elif qual == "/FT_DESC": + record.cc_ft_desc = data + elif qual == "/VERSION": + record.cc_version = data + else: + raise ValueError(f"Unknown qual {qual} in comment line\n{line!r}") + elif keyword == "DR": + refs = value.split(";") + for ref in refs: + if not ref: + continue + acc, name, type = (word.strip() for word in ref.split(",")) + if type == "T": + record.dr_positive.append((acc, name)) + elif type == "F": + record.dr_false_pos.append((acc, name)) + elif type == "N": + record.dr_false_neg.append((acc, name)) + elif type == "P": + record.dr_potential.append((acc, name)) + elif type == "?": + record.dr_unknown.append((acc, name)) + else: + raise ValueError(f"I don't understand type flag {type}") + elif keyword == "3D": + cols = value.split() + for id in cols: + record.pdb_structs.append(id.rstrip(";")) + elif keyword == "PR": + rules = value.split(";") + record.prorules.extend(rules) + elif keyword == "DO": + record.pdoc = value.rstrip(";") + elif keyword == "//": + if not record: + # Then this was the copyright statement + continue + break + else: + raise ValueError(f"Unknown keyword {keyword} found") + else: + return + if not record: + raise ValueError("Unexpected end of stream.") + return record diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/ScanProsite.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/ScanProsite.py new file mode 100644 index 0000000000000000000000000000000000000000..1eb2779b209a0cba7e711108c08ad9a538c83feb --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/ScanProsite.py @@ -0,0 +1,151 @@ +# Copyright 2009 by Michiel de Hoon. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +"""Code for calling and parsing ScanProsite from ExPASy.""" + +from urllib.parse import urlencode +from urllib.request import urlopen +from xml.sax import handler +from xml.sax.expatreader import ExpatParser + +# October 28th 2020 it was recognised that between October 10th 2020 and October +# 28th the main url of prosite changed from https://www.expasy.org to +# https://prosite.expasy.org. Thus a change in the mirror was issued from +# https://www.expasy.org to https://prosite.expasy.org. +PROSITE_URL = "https://prosite.expasy.org" + + +class Record(list): + """Represents search results returned by ScanProsite. + + This record is a list containing the search results returned by + ScanProsite. The record also contains the data members n_match, + n_seq, capped, and warning. + """ + + def __init__(self): + """Initialize the class.""" + self.n_match = None + self.n_seq = None + self.capped = None + self.warning = None + + +def scan(seq="", mirror=PROSITE_URL, output="xml", **keywords): + """Execute a ScanProsite search. + + Arguments: + - mirror: The ScanProsite mirror to be used + (default: PROSITE_URL). + - seq: The query sequence, or UniProtKB (Swiss-Prot, + TrEMBL) accession + - output: Format of the search results + (default: xml) + + Further search parameters can be passed as keywords; see the + documentation for programmatic access to ScanProsite at + https://prosite.expasy.org/scanprosite/scanprosite_doc.html + for a description of such parameters. + + This function returns a handle to the search results returned by + ScanProsite. Search results in the XML format can be parsed into a + Python object, by using the Bio.ExPASy.ScanProsite.read function. + + """ + if output != "xml": + raise NotImplementedError("Only output='xml' is supported currently.") + parameters = {"seq": seq, "output": output} + for key, value in keywords.items(): + if value is not None: + parameters[key] = value + command = urlencode(parameters) + url = f"{mirror}/cgi-bin/prosite/scanprosite/PSScan.cgi?{command}" + handle = urlopen(url) + return handle + + +def read(handle): + """Parse search results returned by ScanProsite into a Python object.""" + content_handler = ContentHandler() + saxparser = Parser() + saxparser.setContentHandler(content_handler) + saxparser.parse(handle) + record = content_handler.record + return record + + +# The classes below are considered private + + +class Parser(ExpatParser): + """Process the result from a ScanProsite search (PRIVATE).""" + + def __init__(self): + """Initialize the class.""" + ExpatParser.__init__(self) + self.firsttime = True + + def feed(self, data, isFinal=0): + """Raise an Error if plain text is received in the data. + + This is to show the Error messages returned by ScanProsite. + """ + # Error messages returned by the ScanProsite server are formatted as + # as plain text instead of an XML document. To catch such error + # messages, we override the feed method of the Expat parser. + # The error message is (hopefully) contained in the data that was just + # fed to the parser. + if self.firsttime: + if data[:22].decode("utf-8") != "": + raise ValueError(data) + self.firsttime = False + return ExpatParser.feed(self, data, isFinal) + + +class ContentHandler(handler.ContentHandler): + """Process and fill in the records, results of the search (PRIVATE).""" + + integers = ("start", "stop") + strings = ( + "sequence_ac", + "sequence_id", + "sequence_db", + "signature_ac", + "level", + "level_tag", + ) + + def __init__(self): + """Initialize the class.""" + self.element = [] + + def startElement(self, name, attrs): + """Define the beginning of a record and stores the search record.""" + self.element.append(name) + self.content = "" + if self.element == ["scanprosite_response", "matchset"]: + self.record = Record() + self.record.n_match = int(attrs["n_match"]) + self.record.n_seq = int(attrs["n_seq"]) + elif self.element == ["scanprosite_response", "matchset", "match"]: + match = {} + self.record.append(match) + + def endElement(self, name): + """Define the end of the search record.""" + assert name == self.element.pop() + if self.element == ["scanprosite_response", "matchset", "match"]: + match = self.record[-1] + if name in ContentHandler.integers: + match[name] = int(self.content) + elif name in ContentHandler.strings: + match[name] = self.content + else: + # Unknown type, treat it as a string + match[name] = self.content + + def characters(self, content): + """Store the record content.""" + self.content += content diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d72b486adc4e71edfcf3803ff6ed8349f9d63fa0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__init__.py @@ -0,0 +1,138 @@ +# Copyright 2000 by Jeffrey Chang. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +"""Code to access resources at ExPASy over the WWW. + +See https://www.expasy.org/ + + +Functions: + - get_prodoc_entry Interface to the get-prodoc-entry CGI script. + - get_prosite_entry Interface to the get-prosite-entry CGI script. + - get_prosite_raw Interface to the get-prosite-raw CGI script. + - get_sprot_raw Interface to the get-sprot-raw CGI script. + +""" + +import io +from urllib.error import HTTPError +from urllib.request import urlopen + + +def get_prodoc_entry( + id, cgi="https://prosite.expasy.org/cgi-bin/prosite/get-prodoc-entry" +): + """Get a text handle to a PRODOC entry at ExPASy in HTML format. + + >>> from Bio import ExPASy + >>> import os + >>> with ExPASy.get_prodoc_entry('PDOC00001') as in_handle: + ... html = in_handle.read() + ... + >>> with open("myprodocrecord.html", "w") as out_handle: + ... length = out_handle.write(html) + ... + >>> os.remove("myprodocrecord.html") # tidy up + + For a non-existing key XXX, ExPASy returns an HTML-formatted page + containing this text: 'There is currently no PROSITE entry for' + """ + return _open(f"{cgi}?{id}") + + +def get_prosite_entry( + id, cgi="https://prosite.expasy.org/cgi-bin/prosite/get-prosite-entry" +): + """Get a text handle to a PROSITE entry at ExPASy in HTML format. + + >>> from Bio import ExPASy + >>> import os + >>> with ExPASy.get_prosite_entry('PS00001') as in_handle: + ... html = in_handle.read() + ... + >>> with open("myprositerecord.html", "w") as out_handle: + ... length = out_handle.write(html) + ... + >>> os.remove("myprositerecord.html") # tidy up + + For a non-existing key XXX, ExPASy returns an HTML-formatted page + containing this text: 'There is currently no PROSITE entry for' + """ + return _open(f"{cgi}?{id}") + + +def get_prosite_raw(id, cgi=None): + """Get a text handle to a raw PROSITE or PRODOC record at ExPASy. + + The cgi argument is deprecated due to changes in the ExPASy + website. + + >>> from Bio import ExPASy + >>> from Bio.ExPASy import Prosite + >>> with ExPASy.get_prosite_raw('PS00001') as handle: + ... record = Prosite.read(handle) + ... + >>> print(record.accession) + PS00001 + + This function raises a ValueError if the identifier does not exist: + + >>> handle = ExPASy.get_prosite_raw("DOES_NOT_EXIST") + Traceback (most recent call last): + ... + ValueError: Failed to find entry 'DOES_NOT_EXIST' on ExPASy + + """ + try: + handle = _open(f"https://prosite.expasy.org/{id}.txt") + except HTTPError as exception: + if exception.code == 404: + raise ValueError("Failed to find entry '%s' on ExPASy" % id) from None + else: + raise + # This has happened historically, redirected to main page: + if handle.url == "https://www.expasy.org/": + raise ValueError(f"Failed to find entry '{id}' on ExPASy") from None + return handle + + +def get_sprot_raw(id): + """Get a text handle to a raw SwissProt entry at ExPASy. + + For an ID of XXX, fetches http://www.uniprot.org/uniprot/XXX.txt + (as per the https://www.expasy.org/expasy_urls.html documentation). + + >>> from Bio import ExPASy + >>> from Bio import SwissProt + >>> with ExPASy.get_sprot_raw("O23729") as handle: + ... record = SwissProt.read(handle) + ... + >>> print(record.entry_name) + CHS3_BROFI + + This function raises a ValueError if the identifier does not exist: + + >>> ExPASy.get_sprot_raw("DOES_NOT_EXIST") + Traceback (most recent call last): + ... + ValueError: Failed to find SwissProt entry 'DOES_NOT_EXIST' + + """ + try: + handle = _open(f"http://www.uniprot.org/uniprot/{id}.txt") + except HTTPError as exception: + if exception.code in (400, 404): + raise ValueError(f"Failed to find SwissProt entry '{id}'") from None + else: + raise + return handle + + +def _open(url): + """Open URL and convert to text assuming UTF-8 encoding (PRIVATE).""" + handle = urlopen(url) + text_handle = io.TextIOWrapper(handle, encoding="UTF-8") + text_handle.url = handle.url + return text_handle diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/Enzyme.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/Enzyme.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5b21dda05ae9617ee708372ae141f6f896f4e26 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/Enzyme.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/Prodoc.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/Prodoc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98204946702793db806baf147d37a27ae01c13be Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/Prodoc.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/Prosite.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/Prosite.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b336c8a0de5f5ab7f36e2f70fed576d15acaddae Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/Prosite.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/ScanProsite.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/ScanProsite.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27618d8c1eb748ac1d8c4ef5069edc0bdc08cd1d Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/ScanProsite.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01606201bb86bac2596ffcfaf823359404cedf2e Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/cellosaurus.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/cellosaurus.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa46418ba5575d865f3d50b953fdfc75ed1ae1e8 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/__pycache__/cellosaurus.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/cellosaurus.py b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/cellosaurus.py new file mode 100644 index 0000000000000000000000000000000000000000..53c19b1f6e0c72586688867cb7f2fbda88cf84cc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/ExPASy/cellosaurus.py @@ -0,0 +1,208 @@ +# Copyright 2016 by Stephen Marshall. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +"""Parser for the cellosaurus.txt file from ExPASy. + +See https://web.expasy.org/cellosaurus/ + +Tested with the release of Version 18 (July 2016). + +Functions: + - read Reads a file containing one cell line entry + - parse Reads a file containing multiple cell line entries + +Classes: + - Record Holds cell line data. + +Examples +-------- +This example downloads the Cellosaurus database and parses it. Note that +urlopen returns a stream of bytes, while the parser expects a stream of plain +string, so we use TextIOWrapper to convert bytes to string using the UTF-8 +encoding. This is not needed if you download the cellosaurus.txt file in +advance and open it (see the comment below). + + >>> from urllib.request import urlopen + >>> from io import TextIOWrapper + >>> from Bio.ExPASy import cellosaurus + >>> url = "ftp://ftp.expasy.org/databases/cellosaurus/cellosaurus.txt" + >>> bytestream = urlopen(url) + >>> textstream = TextIOWrapper(bytestream, "UTF-8") + >>> # alternatively, use + >>> # textstream = open("cellosaurus.txt") + >>> # if you downloaded the cellosaurus.txt file in advance. + >>> records = cellosaurus.parse(textstream) + >>> for record in records: + ... if 'Homo sapiens' in record['OX'][0]: + ... print(record['ID']) # doctest:+ELLIPSIS + ... + #15310-LN + #W7079 + (L)PC6 + 0.5alpha + ... + +""" + + +def parse(handle): + """Parse cell line records. + + This function is for parsing cell line files containing multiple + records. + + Arguments: + - handle - handle to the file. + + """ + while True: + record = __read(handle) + if not record: + break + yield record + + +def read(handle): + """Read one cell line record. + + This function is for parsing cell line files containing + exactly one record. + + Arguments: + - handle - handle to the file. + + """ + record = __read(handle) + # We should have reached the end of the record by now + remainder = handle.read() + if remainder: + raise ValueError("More than one cell line record found") + return record + + +class Record(dict): + """Holds information from an ExPASy Cellosaurus record as a Python dictionary. + + Each record contains the following keys: + + ========= ============================== ======================= + Line code Content Occurrence in an entry + ========= ============================== ======================= + ID Identifier (cell line name) Once; starts an entry + AC Accession (CVCL_xxxx) Once + AS Secondary accession number(s) Optional; once + SY Synonyms Optional; once + DR Cross-references Optional; once or more + RX References identifiers Optional: once or more + WW Web pages Optional; once or more + CC Comments Optional; once or more + ST STR profile data Optional; twice or more + DI Diseases Optional; once or more + OX Species of origin Once or more + HI Hierarchy Optional; once or more + OI Originate from same individual Optional; once or more + SX Sex of cell Optional; once + AG Age of donor at sampling Optional; once + CA Category Once + DT Date (entry history) Once + // Terminator Once; ends an entry + ========= ============================== ======================= + + """ + + def __init__(self): + """Initialize the class.""" + dict.__init__(self) + self["ID"] = "" + self["AC"] = "" + self["AS"] = "" + self["SY"] = "" + self["DR"] = [] + self["RX"] = [] + self["WW"] = [] + self["CC"] = [] + self["ST"] = [] + self["DI"] = [] + self["OX"] = [] + self["HI"] = [] + self["OI"] = [] + self["SX"] = "" + self["AG"] = "" + self["CA"] = "" + self["DT"] = "" + + def __repr__(self): + """Return the canonical string representation of the Record object.""" + if self["ID"]: + if self["AC"]: + return f"{self.__class__.__name__} ({self['ID']}, {self['AC']})" + else: + return f"{self.__class__.__name__} ({self['ID']})" + else: + return f"{self.__class__.__name__} ( )" + + def __str__(self): + """Return a readable string representation of the Record object.""" + output = "ID: " + self["ID"] + output += " AC: " + self["AC"] + output += " AS: " + self["AS"] + output += " SY: " + self["SY"] + output += " DR: " + repr(self["DR"]) + output += " RX: " + repr(self["RX"]) + output += " WW: " + repr(self["WW"]) + output += " CC: " + repr(self["CC"]) + output += " ST: " + repr(self["ST"]) + output += " DI: " + repr(self["DI"]) + output += " OX: " + repr(self["OX"]) + output += " HI: " + repr(self["HI"]) + output += " OI: " + repr(self["OI"]) + output += " SX: " + self["SX"] + output += " AG: " + self["AG"] + output += " CA: " + self["CA"] + output += " DT: " + self["DT"] + return output + + +# Everything below is private + + +def __read(handle): + record = None + + for line in handle: + key, value = line[:2], line[5:].rstrip() + if key == "ID": + record = Record() + record["ID"] = value + elif key in ["AC", "AS", "SY", "SX", "AG", "CA", "DT"]: + record[key] += value + elif key in [ + # just append to the fields defined as lists, not to strings + "RX", + "WW", + "CC", + "ST", + "DI", + "OX", + "HI", + "OI", + ]: + record[key].append(value) + elif key == "DR": + k, v = value.split(";") + record["DR"].append((k.strip(), v.strip())) + elif key == "//": + if record: + return record + else: + continue + if record: + raise ValueError("Unexpected end of stream") + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/Record.py b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/Record.py new file mode 100644 index 0000000000000000000000000000000000000000..b96da8bef4a5b1967d70ec7c35e931d20a95fccc --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/Record.py @@ -0,0 +1,669 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + +"""Hold GenBank data in a straightforward format. + +Classes: + - Record - All of the information in a GenBank record. + - Reference - hold reference data for a record. + - Feature - Hold the information in a Feature Table. + - Qualifier - Qualifiers on a Feature. + +""" + +import Bio.GenBank + + +def _wrapped_genbank(information, indent, wrap_space=1, split_char=" "): + """Write a line of GenBank info that can wrap over multiple lines (PRIVATE). + + This takes a line of information which can potentially wrap over + multiple lines, and breaks it up with carriage returns and + indentation so it fits properly into a GenBank record. + + Arguments: + - information - The string holding the information we want + wrapped in GenBank method. + - indent - The indentation on the lines we are writing. + - wrap_space - Whether or not to wrap only on spaces in the + information. + - split_char - A specific character to split the lines on. By default + spaces are used. + + """ + info_length = Record.GB_LINE_LENGTH - indent + + if not information: + # GenBank files use "." for missing data + return ".\n" + + if wrap_space: + info_parts = information.split(split_char) + else: + cur_pos = 0 + info_parts = [] + while cur_pos < len(information): + info_parts.append(information[cur_pos : cur_pos + info_length]) + cur_pos += info_length + + # first get the information string split up by line + output_parts = [] + cur_part = "" + for info_part in info_parts: + if len(cur_part) + 1 + len(info_part) > info_length: + if cur_part: + if split_char != " ": + cur_part += split_char + output_parts.append(cur_part) + cur_part = info_part + else: + if cur_part == "": + cur_part = info_part + else: + cur_part += split_char + info_part + + # add the last bit of information to the output + if cur_part: + output_parts.append(cur_part) + + # now format the information string for return + output_info = output_parts[0] + "\n" + for output_part in output_parts[1:]: + output_info += " " * indent + output_part + "\n" + + return output_info + + +def _indent_genbank(information, indent): + """Write out information with the specified indent (PRIVATE). + + Unlike _wrapped_genbank, this function makes no attempt to wrap + lines -- it assumes that the information already has newlines in the + appropriate places, and will add the specified indent to the start of + each line. + """ + # split the info into lines based on line breaks + info_parts = information.split("\n") + + # the first line will have no indent + output_info = info_parts[0] + "\n" + for info_part in info_parts[1:]: + output_info += " " * indent + info_part + "\n" + + return output_info + + +class Record: + """Hold GenBank information in a format similar to the original record. + + The Record class is meant to make data easy to get to when you are + just interested in looking at GenBank data. + + Attributes: + - locus - The name specified after the LOCUS keyword in the GenBank + record. This may be the accession number, or a clone id or something else. + - size - The size of the record. + - residue_type - The type of residues making up the sequence in this + record. Normally something like RNA, DNA or PROTEIN, but may be as + esoteric as 'ss-RNA circular'. + - data_file_division - The division this record is stored under in + GenBank (ie. PLN -> plants; PRI -> humans, primates; BCT -> bacteria...) + - date - The date of submission of the record, in a form like '28-JUL-1998' + - accession - list of all accession numbers for the sequence. + - nid - Nucleotide identifier number. + - pid - Proteint identifier number + - version - The accession number + version (ie. AB01234.2) + - db_source - Information about the database the record came from + - gi - The NCBI gi identifier for the record. + - keywords - A list of keywords related to the record. + - segment - If the record is one of a series, this is info about which + segment this record is (something like '1 of 6'). + - source - The source of material where the sequence came from. + - organism - The genus and species of the organism (ie. 'Homo sapiens') + - taxonomy - A listing of the taxonomic classification of the organism, + starting general and getting more specific. + - references - A list of Reference objects. + - comment - Text with any kind of comment about the record. + - features - A listing of Features making up the feature table. + - base_counts - A string with the counts of bases for the sequence. + - origin - A string specifying info about the origin of the sequence. + - sequence - A string with the sequence itself. + - contig - A string of location information for a CONTIG in a RefSeq file + - project - The genome sequencing project numbers + (will be replaced by the dblink cross-references in 2009). + - dblinks - The genome sequencing project number(s) and other links. + (will replace the project information in 2009). + + """ + + # constants for outputting GenBank information + GB_LINE_LENGTH = 79 + GB_BASE_INDENT = 12 + GB_FEATURE_INDENT = 21 + GB_INTERNAL_INDENT = 2 + GB_OTHER_INTERNAL_INDENT = 3 + GB_FEATURE_INTERNAL_INDENT = 5 + GB_SEQUENCE_INDENT = 9 + + BASE_FORMAT = "%-" + str(GB_BASE_INDENT) + "s" + INTERNAL_FORMAT = ( + " " * GB_INTERNAL_INDENT + "%-" + str(GB_BASE_INDENT - GB_INTERNAL_INDENT) + "s" + ) + OTHER_INTERNAL_FORMAT = ( + " " * GB_OTHER_INTERNAL_INDENT + + "%-" + + str(GB_BASE_INDENT - GB_OTHER_INTERNAL_INDENT) + + "s" + ) + + BASE_FEATURE_FORMAT = "%-" + str(GB_FEATURE_INDENT) + "s" + INTERNAL_FEATURE_FORMAT = ( + " " * GB_FEATURE_INTERNAL_INDENT + + "%-" + + str(GB_FEATURE_INDENT - GB_FEATURE_INTERNAL_INDENT) + + "s" + ) + SEQUENCE_FORMAT = "%" + str(GB_SEQUENCE_INDENT) + "s" + + def __init__(self): + """Initialize the class.""" + self.accession = [] + self.base_counts = "" + self.comment = "" + self.contig = "" + self.data_file_division = "" + self.date = "" + self.db_source = "" + self.dblinks = [] + self.definition = "" + self.features = [] + self.gi = "" + self.keywords = [] + self.locus = "" + self.molecule_type = "" + self.nid = "" + self.organism = "" + self.origin = "" + self.pid = "" + self.primary = [] + self.projects = [] + self.references = [] + self.residue_type = "" + self.segment = "" + self.sequence = "" + self.size = "" + self.source = "" + self.taxonomy = [] + self.topology = "" + self.version = "" + self.wgs = "" + self.wgs_scafld = [] + + def __str__(self): + """Provide a GenBank formatted output option for a Record. + + The objective of this is to provide an easy way to read in a GenBank + record, modify it somehow, and then output it in 'GenBank format.' + We are striving to make this work so that a parsed Record that is + output using this function will look exactly like the original + record. + + Much of the output is based on format description info at: + + ftp://ncbi.nlm.nih.gov/genbank/gbrel.txt + """ + output = self._locus_line() + output += self._definition_line() + output += self._accession_line() + output += self._version_line() + output += self._project_line() + output += self._dblink_line() + output += self._nid_line() + output += self._pid_line() + output += self._keywords_line() + output += self._db_source_line() + output += self._segment_line() + output += self._source_line() + output += self._organism_line() + for reference in self.references: + output += str(reference) + output += self._comment_line() + output += self._features_line() + for feature in self.features: + output += str(feature) + output += self._base_count_line() + output += self._origin_line() + output += self._sequence_line() + output += self._wgs_line() + output += self._wgs_scafld_line() + output += self._contig_line() + output += "//" + return output + + def _locus_line(self): + """Provide the output string for the LOCUS line (PRIVATE).""" + output = "LOCUS" + output += " " * 7 # 6-12 spaces + output += "%-9s" % self.locus + output += " " # 22 space + output += "%7s" % self.size + if "PROTEIN" in self.residue_type: + output += " aa" + else: + output += " bp " + + # treat circular types differently, since they'll have long residue + # types + if "circular" in self.residue_type: + output += "%17s" % self.residue_type + # second case: ss-DNA types of records + elif "-" in self.residue_type: + output += "%7s" % self.residue_type + output += " " * 10 # spaces for circular + else: + output += " " * 3 # spaces for stuff like ss- + output += "%-4s" % self.residue_type + output += " " * 10 # spaces for circular + + output += " " * 2 + output += "%3s" % self.data_file_division + output += " " * 7 # spaces for 56-63 + output += "%11s" % self.date + output += "\n" + return output + + def _definition_line(self): + """Provide output for the DEFINITION line (PRIVATE).""" + output = Record.BASE_FORMAT % "DEFINITION" + output += _wrapped_genbank(self.definition + ".", Record.GB_BASE_INDENT) + return output + + def _accession_line(self): + """Output for the ACCESSION line (PRIVATE).""" + if self.accession: + output = Record.BASE_FORMAT % "ACCESSION" + + acc_info = "" + for accession in self.accession: + acc_info += f"{accession} " + # strip off an extra space at the end + acc_info = acc_info.rstrip() + output += _wrapped_genbank(acc_info, Record.GB_BASE_INDENT) + else: + output = "" + + return output + + def _version_line(self): + """Output for the VERSION line (PRIVATE).""" + if self.version: + output = Record.BASE_FORMAT % "VERSION" + output += self.version + output += " GI:" + output += f"{self.gi}\n" + else: + output = "" + return output + + def _project_line(self): + output = "" + if len(self.projects) > 0: + output = Record.BASE_FORMAT % "PROJECT" + output += f"{' '.join(self.projects)}\n" + return output + + def _dblink_line(self): + output = "" + if len(self.dblinks) > 0: + output = Record.BASE_FORMAT % "DBLINK" + dblink_info = "\n".join(self.dblinks) + output += _wrapped_genbank(dblink_info, Record.GB_BASE_INDENT) + return output + + def _nid_line(self): + """Output for the NID line. Use of NID is obsolete in GenBank files (PRIVATE).""" + if self.nid: + output = Record.BASE_FORMAT % "NID" + output += f"{self.nid}\n" + else: + output = "" + return output + + def _pid_line(self): + """Output for PID line. Presumedly, PID usage is also obsolete (PRIVATE).""" + if self.pid: + output = Record.BASE_FORMAT % "PID" + output += f"{self.pid}\n" + else: + output = "" + return output + + def _keywords_line(self): + """Output for the KEYWORDS line (PRIVATE).""" + output = "" + if self.keywords: + output += Record.BASE_FORMAT % "KEYWORDS" + keyword_info = "" + for keyword in self.keywords: + keyword_info += f"{keyword}; " + # replace the ; at the end with a period + keyword_info = keyword_info[:-2] + keyword_info += "." + + output += _wrapped_genbank(keyword_info, Record.GB_BASE_INDENT) + + return output + + def _db_source_line(self): + """Output for DBSOURCE line (PRIVATE).""" + if self.db_source: + output = Record.BASE_FORMAT % "DBSOURCE" + output += f"{self.db_source}\n" + else: + output = "" + return output + + def _segment_line(self): + """Output for the SEGMENT line (PRIVATE).""" + output = "" + if self.segment: + output += Record.BASE_FORMAT % "SEGMENT" + output += _wrapped_genbank(self.segment, Record.GB_BASE_INDENT) + return output + + def _source_line(self): + """Output for SOURCE line on where the sample came from (PRIVATE).""" + output = Record.BASE_FORMAT % "SOURCE" + output += _wrapped_genbank(self.source, Record.GB_BASE_INDENT) + return output + + def _organism_line(self): + """Output for ORGANISM line with taxonomy info (PRIVATE).""" + output = Record.INTERNAL_FORMAT % "ORGANISM" + # Now that species names can be too long, this line can wrap (Bug 2591) + output += _wrapped_genbank(self.organism, Record.GB_BASE_INDENT) + output += " " * Record.GB_BASE_INDENT + taxonomy_info = "" + for tax in self.taxonomy: + taxonomy_info += f"{tax}; " + # replace the ; at the end with a period + taxonomy_info = taxonomy_info[:-2] + taxonomy_info += "." + output += _wrapped_genbank(taxonomy_info, Record.GB_BASE_INDENT) + + return output + + def _comment_line(self): + """Output for the COMMENT lines (PRIVATE).""" + output = "" + if self.comment: + output += Record.BASE_FORMAT % "COMMENT" + output += _indent_genbank(self.comment, Record.GB_BASE_INDENT) + return output + + def _features_line(self): + """Output for the FEATURES line (PRIVATE).""" + output = "" + if len(self.features) > 0: + output += Record.BASE_FEATURE_FORMAT % "FEATURES" + output += "Location/Qualifiers\n" + return output + + def _base_count_line(self): + """Output for the BASE COUNT line with base information (PRIVATE).""" + output = "" + if self.base_counts: + output += Record.BASE_FORMAT % "BASE COUNT " + # split up the base counts into their individual parts + count_parts = self.base_counts.split(" ") + while "" in count_parts: + count_parts.remove("") + # deal with the standard case, with a normal origin line + # like: 474 a 356 c 428 g 364 t + if len(count_parts) % 2 == 0: + while len(count_parts) > 0: + count_info = count_parts.pop(0) + count_type = count_parts.pop(0) + + output += f"{count_info:>7} {count_type}" + # deal with ugly ORIGIN lines like: + # 1311257 a2224835 c2190093 g1309889 t + # by just outputting the raw information + else: + output += self.base_counts + output += "\n" + return output + + def _origin_line(self): + """Output for the ORIGIN line (PRIVATE).""" + output = "" + # only output the ORIGIN line if we have a sequence + if self.sequence: + output += Record.BASE_FORMAT % "ORIGIN" + if self.origin: + output += _wrapped_genbank(self.origin, Record.GB_BASE_INDENT) + else: + output += "\n" + return output + + def _sequence_line(self): + """Output for all of the sequence (PRIVATE).""" + output = "" + if self.sequence: + cur_seq_pos = 0 + while cur_seq_pos < len(self.sequence): + output += Record.SEQUENCE_FORMAT % str(cur_seq_pos + 1) + + for section in range(6): + start_pos = cur_seq_pos + section * 10 + end_pos = start_pos + 10 + seq_section = self.sequence[start_pos:end_pos] + output += f" {seq_section.lower()}" + + # stop looping if we are out of sequence + if end_pos > len(self.sequence): + break + + output += "\n" + cur_seq_pos += 60 + return output + + def _wgs_line(self): + output = "" + if self.wgs: + output += Record.BASE_FORMAT % "WGS" + output += self.wgs + return output + + def _wgs_scafld_line(self): + output = "" + if self.wgs_scafld: + output += Record.BASE_FORMAT % "WGS_SCAFLD" + output += self.wgs_scafld + return output + + def _contig_line(self): + """Output for CONTIG location information from RefSeq (PRIVATE).""" + output = "" + if self.contig: + output += Record.BASE_FORMAT % "CONTIG" + output += _wrapped_genbank( + self.contig, Record.GB_BASE_INDENT, split_char="," + ) + return output + + +class Reference: + """Hold information from a GenBank reference. + + Attributes: + - number - The number of the reference in the listing of references. + - bases - The bases in the sequence the reference refers to. + - authors - String with all of the authors. + - consrtm - Consortium the authors belong to. + - title - The title of the reference. + - journal - Information about the journal where the reference appeared. + - medline_id - The medline id for the reference. + - pubmed_id - The pubmed_id for the reference. + - remark - Free-form remarks about the reference. + + """ + + def __init__(self): + """Initialize the class.""" + self.number = "" + self.bases = "" + self.authors = "" + self.consrtm = "" + self.title = "" + self.journal = "" + self.medline_id = "" + self.pubmed_id = "" + self.remark = "" + + def __str__(self): + """Convert the reference to a GenBank format string.""" + output = self._reference_line() + output += self._authors_line() + output += self._consrtm_line() + output += self._title_line() + output += self._journal_line() + output += self._medline_line() + output += self._pubmed_line() + output += self._remark_line() + + return output + + def _reference_line(self): + """Output for REFERENCE lines (PRIVATE).""" + output = Record.BASE_FORMAT % "REFERENCE" + if self.number: + if self.bases: + output += "%-3s" % self.number + output += f"{self.bases}" + else: + output += f"{self.number}" + + output += "\n" + return output + + def _authors_line(self): + """Output for AUTHORS information (PRIVATE).""" + output = "" + if self.authors: + output += Record.INTERNAL_FORMAT % "AUTHORS" + output += _wrapped_genbank(self.authors, Record.GB_BASE_INDENT) + return output + + def _consrtm_line(self): + """Output for CONSRTM information (PRIVATE).""" + output = "" + if self.consrtm: + output += Record.INTERNAL_FORMAT % "CONSRTM" + output += _wrapped_genbank(self.consrtm, Record.GB_BASE_INDENT) + return output + + def _title_line(self): + """Output for TITLE information (PRIVATE).""" + output = "" + if self.title: + output += Record.INTERNAL_FORMAT % "TITLE" + output += _wrapped_genbank(self.title, Record.GB_BASE_INDENT) + return output + + def _journal_line(self): + """Output for JOURNAL information (PRIVATE).""" + output = "" + if self.journal: + output += Record.INTERNAL_FORMAT % "JOURNAL" + output += _wrapped_genbank(self.journal, Record.GB_BASE_INDENT) + return output + + def _medline_line(self): + """Output for MEDLINE information (PRIVATE).""" + output = "" + if self.medline_id: + output += Record.INTERNAL_FORMAT % "MEDLINE" + output += self.medline_id + "\n" + return output + + def _pubmed_line(self): + """Output for PUBMED information (PRIVATE).""" + output = "" + if self.pubmed_id: + output += Record.OTHER_INTERNAL_FORMAT % "PUBMED" + output += self.pubmed_id + "\n" + return output + + def _remark_line(self): + """Output for REMARK information (PRIVATE).""" + output = "" + if self.remark: + output += Record.INTERNAL_FORMAT % "REMARK" + output += _wrapped_genbank(self.remark, Record.GB_BASE_INDENT) + return output + + +class Feature: + """Hold information about a Feature in the Feature Table of GenBank record. + + Attributes: + - key - The key name of the feature (ie. source) + - location - The string specifying the location of the feature. + - qualifiers - A list of Qualifier objects in the feature. + + """ + + def __init__(self, key="", location=""): + """Initialize the class.""" + self.key = key + self.location = location + self.qualifiers = [] + + def __repr__(self): + """Representation of the object for debugging or logging.""" + return f"Feature(key={self.key!r}, location={self.location!r})" + + def __str__(self): + """Return feature as a GenBank format string.""" + output = Record.INTERNAL_FEATURE_FORMAT % self.key + output += _wrapped_genbank( + self.location, Record.GB_FEATURE_INDENT, split_char="," + ) + for qualifier in self.qualifiers: + output += str(qualifier) + return output + + +class Qualifier: + """Hold information about a qualifier in a GenBank feature. + + Attributes: + - key - The key name of the qualifier (ie. /organism=) + - value - The value of the qualifier ("Dictyostelium discoideum"). + + """ + + def __init__(self, key="", value=""): + """Initialize the class.""" + self.key = key + self.value = value + + def __repr__(self): + """Representation of the object for debugging or logging.""" + return f"Qualifier(key={self.key!r}, value={self.value!r})" + + def __str__(self): + """Return feature qualifier as a GenBank format string.""" + output = " " * Record.GB_FEATURE_INDENT + # determine whether we can wrap on spaces + space_wrap = 1 + for no_space_key in Bio.GenBank._BaseGenBankConsumer.remove_space_keys: + if no_space_key in self.key: + space_wrap = 0 + # return double quotes as-is, leave it to the user to escape them + return output + _wrapped_genbank( + self.key + self.value, Record.GB_FEATURE_INDENT, space_wrap + ) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/Scanner.py b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/Scanner.py new file mode 100644 index 0000000000000000000000000000000000000000..7aaf38e5f2a537899978b6895b5ce02c66d82a81 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/Scanner.py @@ -0,0 +1,1929 @@ +# Copyright 2007-2017 by Peter Cock. All rights reserved. +# Revisions copyright 2010 by Uri Laserson. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +"""Internal code for parsing GenBank and EMBL files (PRIVATE). + +This code is NOT intended for direct use. It provides a basic scanner +(for use with a event consumer such as Bio.GenBank._FeatureConsumer) +to parse a GenBank or EMBL file (with their shared INSDC feature table). + +It is used by Bio.GenBank to parse GenBank files +It is also used by Bio.SeqIO to parse GenBank and EMBL files + +Feature Table Documentation: + +- http://www.insdc.org/files/feature_table.html +- http://www.ncbi.nlm.nih.gov/projects/collab/FT/index.html +- ftp://ftp.ncbi.nih.gov/genbank/docs/ +""" +# 17-MAR-2009: added wgs, wgs_scafld for GenBank whole genome shotgun master records. +# These are GenBank files that summarize the content of a project, and provide lists of +# scaffold and contig files in the project. These will be in annotations['wgs'] and +# annotations['wgs_scafld']. These GenBank files do not have sequences. See +# http://groups.google.com/group/bionet.molbio.genbank/browse_thread/thread/51fb88bf39e7dc36 +# http://is.gd/nNgk +# for more details of this format, and an example. +# Added by Ying Huang & Iddo Friedberg + +import re +import sys +import warnings +from collections import defaultdict + +from Bio import BiopythonParserWarning +from Bio.File import as_handle +from Bio.Seq import Seq +from Bio.SeqRecord import SeqRecord + + +class InsdcScanner: + """Basic functions for breaking up a GenBank/EMBL file into sub sections. + + The International Nucleotide Sequence Database Collaboration (INSDC) + between the DDBJ, EMBL, and GenBank. These organisations all use the + same "Feature Table" layout in their plain text flat file formats. + + However, the header and sequence sections of an EMBL file are very + different in layout to those produced by GenBank/DDBJ. + """ + + # These constants get redefined with sensible values in the sub classes: + RECORD_START = "XXX" # "LOCUS " or "ID " + HEADER_WIDTH = 3 # 12 or 5 + FEATURE_START_MARKERS = ["XXX***FEATURES***XXX"] + FEATURE_END_MARKERS = ["XXX***END FEATURES***XXX"] + FEATURE_QUALIFIER_INDENT = 0 + FEATURE_QUALIFIER_SPACER = "" + SEQUENCE_HEADERS = ["XXX"] # with right hand side spaces removed + + def __init__(self, debug=0): + """Initialize the class.""" + assert len(self.RECORD_START) == self.HEADER_WIDTH + for marker in self.SEQUENCE_HEADERS: + assert marker == marker.rstrip() + assert len(self.FEATURE_QUALIFIER_SPACER) == self.FEATURE_QUALIFIER_INDENT + self.debug = debug + self.handle = None + self.line = None + + def set_handle(self, handle): + """Set the handle attribute.""" + self.handle = handle + self.line = "" + + def find_start(self): + """Read in lines until find the ID/LOCUS line, which is returned. + + Any preamble (such as the header used by the NCBI on ``*.seq.gz`` archives) + will we ignored. + """ + while True: + if self.line: + line = self.line + self.line = "" + else: + line = self.handle.readline() + if not line: + if self.debug: + print("End of file") + return None + if isinstance(line[0], int): + # Same exception as for FASTQ files + raise ValueError("Is this handle in binary mode not text mode?") + if line[: self.HEADER_WIDTH] == self.RECORD_START: + if self.debug > 1: + print("Found the start of a record:\n" + line) + break + line = line.rstrip() + if line == "//": + if self.debug > 1: + print("Skipping // marking end of last record") + elif line == "": + if self.debug > 1: + print("Skipping blank line before record") + else: + # Ignore any header before the first ID/LOCUS line. + if self.debug > 1: + print("Skipping header line before record:\n" + line) + self.line = line + return line + + def parse_header(self): + """Return list of strings making up the header. + + New line characters are removed. + + Assumes you have just read in the ID/LOCUS line. + """ + if self.line[: self.HEADER_WIDTH] != self.RECORD_START: + raise ValueError("Not at start of record") + + header_lines = [] + while True: + line = self.handle.readline() + if not line: + raise ValueError("Premature end of line during sequence data") + line = line.rstrip() + if line in self.FEATURE_START_MARKERS: + if self.debug: + print("Found feature table") + break + # if line[:self.HEADER_WIDTH]==self.FEATURE_START_MARKER[:self.HEADER_WIDTH]: + # if self.debug : print("Found header table (?)") + # break + if line[: self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: + if self.debug: + print("Found start of sequence") + break + if line == "//": + raise ValueError("Premature end of sequence data marker '//' found") + header_lines.append(line) + self.line = line + return header_lines + + def parse_features(self, skip=False): + """Return list of tuples for the features (if present). + + Each feature is returned as a tuple (key, location, qualifiers) + where key and location are strings (e.g. "CDS" and + "complement(join(490883..490885,1..879))") while qualifiers + is a list of two string tuples (feature qualifier keys and values). + + Assumes you have already read to the start of the features table. + """ + if self.line.rstrip() not in self.FEATURE_START_MARKERS: + if self.debug: + print("Didn't find any feature table") + return [] + + while self.line.rstrip() in self.FEATURE_START_MARKERS: + self.line = self.handle.readline() + + features = [] + line = self.line + while True: + if not line: + raise ValueError("Premature end of line during features table") + if line[: self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: + if self.debug: + print("Found start of sequence") + break + line = line.rstrip() + if line == "//": + raise ValueError("Premature end of features table, marker '//' found") + if line in self.FEATURE_END_MARKERS: + if self.debug: + print("Found end of features") + line = self.handle.readline() + break + if line[2 : self.FEATURE_QUALIFIER_INDENT].strip() == "": + # This is an empty feature line between qualifiers. Empty + # feature lines within qualifiers are handled below (ignored). + line = self.handle.readline() + continue + if len(line) < self.FEATURE_QUALIFIER_INDENT: + warnings.warn( + f"line too short to contain a feature: {line!r}", + BiopythonParserWarning, + ) + line = self.handle.readline() + continue + + if skip: + line = self.handle.readline() + while ( + line[: self.FEATURE_QUALIFIER_INDENT] + == self.FEATURE_QUALIFIER_SPACER + ): + line = self.handle.readline() + else: + # Build up a list of the lines making up this feature: + if ( + line[self.FEATURE_QUALIFIER_INDENT] != " " + and " " in line[self.FEATURE_QUALIFIER_INDENT :] + ): + # The feature table design enforces a length limit on the feature keys. + # Some third party files (e.g. IGMT's EMBL like files) solve this by + # over indenting the location and qualifiers. + feature_key, line = line[2:].strip().split(None, 1) + feature_lines = [line] + warnings.warn( + f"Over indented {feature_key} feature?", + BiopythonParserWarning, + ) + else: + feature_key = line[2 : self.FEATURE_QUALIFIER_INDENT].strip() + feature_lines = [line[self.FEATURE_QUALIFIER_INDENT :]] + line = self.handle.readline() + while line[ + : self.FEATURE_QUALIFIER_INDENT + ] == self.FEATURE_QUALIFIER_SPACER or ( + line != "" and line.rstrip() == "" + ): # cope with blank lines in the midst of a feature + # Use strip to remove any harmless trailing white space AND and leading + # white space (e.g. out of spec files with too much indentation) + feature_lines.append(line[self.FEATURE_QUALIFIER_INDENT :].strip()) + line = self.handle.readline() + features.append(self.parse_feature(feature_key, feature_lines)) + self.line = line + return features + + def parse_feature(self, feature_key, lines): + r"""Parse a feature given as a list of strings into a tuple. + + Expects a feature as a list of strings, returns a tuple (key, location, + qualifiers) + + For example given this GenBank feature:: + + CDS complement(join(490883..490885,1..879)) + /locus_tag="NEQ001" + /note="conserved hypothetical [Methanococcus jannaschii]; + COG1583:Uncharacterized ACR; IPR001472:Bipartite nuclear + localization signal; IPR002743: Protein of unknown + function DUF57" + /codon_start=1 + /transl_table=11 + /product="hypothetical protein" + /protein_id="NP_963295.1" + /db_xref="GI:41614797" + /db_xref="GeneID:2732620" + /translation="MRLLLELKALNSIDKKQLSNYLIQGFIYNILKNTEYSWLHNWKK + EKYFNFTLIPKKDIIENKRYYLIISSPDKRFIEVLHNKIKDLDIITIGLAQFQLRKTK + KFDPKLRFPWVTITPIVLREGKIVILKGDKYYKVFVKRLEELKKYNLIKKKEPILEEP + IEISLNQIKDGWKIIDVKDRYYDFRNKSFSAFSNWLRDLKEQSLRKYNNFCGKNFYFE + EAIFEGFTFYKTVSIRIRINRGEAVYIGTLWKELNVYRKLDKEEREFYKFLYDCGLGS + LNSMGFGFVNTKKNSAR" + + Then should give input key="CDS" and the rest of the data as a list of strings + lines=["complement(join(490883..490885,1..879))", ..., "LNSMGFGFVNTKKNSAR"] + where the leading spaces and trailing newlines have been removed. + + Returns tuple containing: (key as string, location string, qualifiers as list) + as follows for this example: + + key = "CDS", string + location = "complement(join(490883..490885,1..879))", string + qualifiers = list of string tuples: + + [('locus_tag', '"NEQ001"'), + ('note', '"conserved hypothetical [Methanococcus jannaschii];\nCOG1583:..."'), + ('codon_start', '1'), + ('transl_table', '11'), + ('product', '"hypothetical protein"'), + ('protein_id', '"NP_963295.1"'), + ('db_xref', '"GI:41614797"'), + ('db_xref', '"GeneID:2732620"'), + ('translation', '"MRLLLELKALNSIDKKQLSNYLIQGFIYNILKNTEYSWLHNWKK\nEKYFNFT..."')] + + In the above example, the "note" and "translation" were edited for compactness, + and they would contain multiple new line characters (displayed above as \n) + + If a qualifier is quoted (in this case, everything except codon_start and + transl_table) then the quotes are NOT removed. + + Note that no whitespace is removed. + """ + # Skip any blank lines + iterator = (x for x in lines if x) + try: + line = next(iterator) + + feature_location = line.strip() + while feature_location[-1:] == ",": + # Multiline location, still more to come! + line = next(iterator) + feature_location += line.strip() + if feature_location.count("(") > feature_location.count(")"): + # Including the prev line in warning would be more explicit, + # but this way get one-and-only-one warning shown by default: + warnings.warn( + "Non-standard feature line wrapping (didn't break on comma)?", + BiopythonParserWarning, + ) + while feature_location[-1:] == "," or feature_location.count( + "(" + ) > feature_location.count(")"): + line = next(iterator) + feature_location += line.strip() + + qualifiers = [] + + for line_number, line in enumerate(iterator): + # check for extra wrapping of the location closing parentheses + if line_number == 0 and line.startswith(")"): + feature_location += line.strip() + elif line[0] == "/": + # New qualifier + i = line.find("=") + key = line[1:i] # does not work if i==-1 + value = line[i + 1 :] # we ignore 'value' if i==-1 + if i and value.startswith(" ") and value.lstrip().startswith('"'): + warnings.warn( + "White space after equals in qualifier", + BiopythonParserWarning, + ) + value = value.lstrip() + if i == -1: + # Qualifier with no key, e.g. /pseudo + key = line[1:] + qualifiers.append((key, None)) + elif not value: + # ApE can output /note= + qualifiers.append((key, "")) + elif value == '"': + # One single quote + if self.debug: + print(f"Single quote {key}:{value}") + # DO NOT remove the quote... + qualifiers.append((key, value)) + elif value[0] == '"': + # Quoted... + value_list = [value] + while value_list[-1][-1] != '"': + value_list.append(next(iterator)) + value = "\n".join(value_list) + # DO NOT remove the quotes... + qualifiers.append((key, value)) + else: + # Unquoted + # if debug : print("Unquoted line %s:%s" % (key,value)) + qualifiers.append((key, value)) + else: + # Unquoted continuation + assert len(qualifiers) > 0 + assert key == qualifiers[-1][0] + # if debug : print("Unquoted Cont %s:%s" % (key, line)) + if qualifiers[-1][1] is None: + raise StopIteration + qualifiers[-1] = (key, qualifiers[-1][1] + "\n" + line) + return feature_key, feature_location, qualifiers + except StopIteration: + # Bummer + raise ValueError( + "Problem with '%s' feature:\n%s" % (feature_key, "\n".join(lines)) + ) from None + + def parse_footer(self): + """Return a tuple containing a list of any misc strings, and the sequence.""" + # This is a basic bit of code to scan and discard the sequence, + # which was useful when developing the sub classes. + if self.line in self.FEATURE_END_MARKERS: + while self.line[: self.HEADER_WIDTH].rstrip() not in self.SEQUENCE_HEADERS: + self.line = self.handle.readline() + if not self.line: + raise ValueError("Premature end of file") + self.line = self.line.rstrip() + + if self.line[: self.HEADER_WIDTH].rstrip() not in self.SEQUENCE_HEADERS: + raise ValueError("Not at start of sequence") + while True: + line = self.handle.readline() + if not line: + raise ValueError("Premature end of line during sequence data") + line = line.rstrip() + if line == "//": + break + self.line = line + return [], "" # Dummy values! + + def _feed_first_line(self, consumer, line): + """Handle the LOCUS/ID line, passing data to the consumer (PRIVATE). + + This should be implemented by the EMBL / GenBank specific subclass + + Used by the parse_records() and parse() methods. + """ + + def _feed_header_lines(self, consumer, lines): + """Handle the header lines (list of strings), passing data to the consumer (PRIVATE). + + This should be implemented by the EMBL / GenBank specific subclass + + Used by the parse_records() and parse() methods. + """ + + @staticmethod + def _feed_feature_table(consumer, feature_tuples): + """Handle the feature table (list of tuples), passing data to the consumer (PRIVATE). + + Used by the parse_records() and parse() methods. + """ + consumer.start_feature_table() + for feature_key, location_string, qualifiers in feature_tuples: + consumer.feature_key(feature_key) + consumer.location(location_string) + for q_key, q_value in qualifiers: + if q_value is None: + consumer.feature_qualifier(q_key, q_value) + else: + consumer.feature_qualifier(q_key, q_value.replace("\n", " ")) + + def _feed_misc_lines(self, consumer, lines): + """Handle any lines between features and sequence (list of strings), passing data to the consumer (PRIVATE). + + This should be implemented by the EMBL / GenBank specific subclass + + Used by the parse_records() and parse() methods. + """ + + def feed(self, handle, consumer, do_features=True): + """Feed a set of data into the consumer. + + This method is intended for use with the "old" code in Bio.GenBank + + Arguments: + - handle - A handle with the information to parse. + - consumer - The consumer that should be informed of events. + - do_features - Boolean, should the features be parsed? + Skipping the features can be much faster. + + Return values: + - true - Passed a record + - false - Did not find a record + + """ + # Should work with both EMBL and GenBank files provided the + # equivalent Bio.GenBank._FeatureConsumer methods are called... + self.set_handle(handle) + if not self.find_start(): + # Could not find (another) record + consumer.data = None + return False + + # We use the above class methods to parse the file into a simplified format. + # The first line, header lines and any misc lines after the features will be + # dealt with by GenBank / EMBL specific derived classes. + + # First line and header: + self._feed_first_line(consumer, self.line) + self._feed_header_lines(consumer, self.parse_header()) + + # Features (common to both EMBL and GenBank): + if do_features: + self._feed_feature_table(consumer, self.parse_features(skip=False)) + else: + self.parse_features(skip=True) # ignore the data + + # Footer and sequence + misc_lines, sequence_string = self.parse_footer() + self._feed_misc_lines(consumer, misc_lines) + + consumer.sequence(sequence_string) + # Calls to consumer.base_number() do nothing anyway + consumer.record_end("//") + + assert self.line == "//" + + # And we are done + return True + + def parse(self, handle, do_features=True): + """Return a SeqRecord (with SeqFeatures if do_features=True). + + See also the method parse_records() for use on multi-record files. + """ + from Bio.GenBank import _FeatureConsumer + from Bio.GenBank.utils import FeatureValueCleaner + + consumer = _FeatureConsumer( + use_fuzziness=1, feature_cleaner=FeatureValueCleaner() + ) + + if self.feed(handle, consumer, do_features): + return consumer.data + else: + return None + + def parse_records(self, handle, do_features=True): + """Parse records, return a SeqRecord object iterator. + + Each record (from the ID/LOCUS line to the // line) becomes a SeqRecord + + The SeqRecord objects include SeqFeatures if do_features=True + + This method is intended for use in Bio.SeqIO + """ + # This is a generator function + with as_handle(handle) as handle: + while True: + record = self.parse(handle, do_features) + if record is None: + break + if record.id is None: + raise ValueError( + "Failed to parse the record's ID. Invalid ID line?" + ) + if record.name == "": + raise ValueError( + "Failed to parse the record's name. Invalid ID line?" + ) + if record.description == "": + raise ValueError("Failed to parse the record's description") + yield record + + def parse_cds_features( + self, handle, alphabet=None, tags2id=("protein_id", "locus_tag", "product") + ): + """Parse CDS features, return SeqRecord object iterator. + + Each CDS feature becomes a SeqRecord. + + Arguments: + - alphabet - Obsolete, should be left as None. + - tags2id - Tuple of three strings, the feature keys to use + for the record id, name and description, + + This method is intended for use in Bio.SeqIO + + """ + if alphabet is not None: + raise ValueError("The alphabet argument is no longer supported") + with as_handle(handle) as handle: + self.set_handle(handle) + while self.find_start(): + # Got an EMBL or GenBank record... + self.parse_header() # ignore header lines! + feature_tuples = self.parse_features() + # self.parse_footer() # ignore footer lines! + while True: + line = self.handle.readline() + if not line: + break + if line[:2] == "//": + break + self.line = line.rstrip() + + # Now go though those features... + for key, location_string, qualifiers in feature_tuples: + if key == "CDS": + # Create SeqRecord + # ================ + # SeqRecord objects cannot be created with annotations, they + # must be added afterwards. So create an empty record and + # then populate it: + record = SeqRecord(seq=None) + annotations = record.annotations + annotations["molecule_type"] = "protein" + # Should we add a location object to the annotations? + # I *think* that only makes sense for SeqFeatures with their + # sub features... + annotations["raw_location"] = location_string.replace(" ", "") + + for qualifier_name, qualifier_data in qualifiers: + if ( + qualifier_data is not None + and qualifier_data[0] == '"' + and qualifier_data[-1] == '"' + ): + # Remove quotes + qualifier_data = qualifier_data[1:-1] + # Append the data to the annotation qualifier... + if qualifier_name == "translation": + assert record.seq is None, "Multiple translations!" + record.seq = Seq(qualifier_data.replace("\n", "")) + elif qualifier_name == "db_xref": + # its a list, possibly empty. Its safe to extend + record.dbxrefs.append(qualifier_data) + else: + if qualifier_data is not None: + qualifier_data = qualifier_data.replace( + "\n", " " + ).replace(" ", " ") + try: + annotations[qualifier_name] += " " + qualifier_data + except KeyError: + # Not an addition to existing data, its the first bit + annotations[qualifier_name] = qualifier_data + + # Fill in the ID, Name, Description + # ================================= + try: + record.id = annotations[tags2id[0]] + except KeyError: + pass + try: + record.name = annotations[tags2id[1]] + except KeyError: + pass + try: + record.description = annotations[tags2id[2]] + except KeyError: + pass + + yield record + + +class EmblScanner(InsdcScanner): + """For extracting chunks of information in EMBL files.""" + + RECORD_START = "ID " + HEADER_WIDTH = 5 + FEATURE_START_MARKERS = ["FH Key Location/Qualifiers", "FH"] + FEATURE_END_MARKERS = ["XX"] # XX can also mark the end of many things! + FEATURE_QUALIFIER_INDENT = 21 + FEATURE_QUALIFIER_SPACER = "FT" + " " * (FEATURE_QUALIFIER_INDENT - 2) + SEQUENCE_HEADERS = ["SQ", "CO"] # Remove trailing spaces + + EMBL_INDENT = HEADER_WIDTH + EMBL_SPACER = " " * EMBL_INDENT + + def parse_footer(self): + """Return a tuple containing a list of any misc strings, and the sequence.""" + if self.line[: self.HEADER_WIDTH].rstrip() not in self.SEQUENCE_HEADERS: + raise ValueError(f"Footer format unexpected: '{self.line}'") + + # Note that the SQ line can be split into several lines... + misc_lines = [] + while self.line[: self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: + misc_lines.append(self.line) + self.line = self.handle.readline() + if not self.line: + raise ValueError("Premature end of file") + self.line = self.line.rstrip() + + if not ( + self.line[: self.HEADER_WIDTH] == " " * self.HEADER_WIDTH + or self.line.strip() == "//" + ): + raise ValueError(f"Unexpected content after SQ or CO line: {self.line!r}") + + seq_lines = [] + line = self.line + while True: + if not line: + raise ValueError("Premature end of file in sequence data") + line = line.strip() + if not line: + raise ValueError("Blank line in sequence data") + if line == "//": + break + if self.line[: self.HEADER_WIDTH] != (" " * self.HEADER_WIDTH): + raise ValueError( + "Problem with characters in header line, " + " or incorrect header width: " + self.line + ) + # Remove tailing number now, remove spaces later + linersplit = line.rsplit(None, 1) + if len(linersplit) == 2 and linersplit[1].isdigit(): + seq_lines.append(linersplit[0]) + elif line.isdigit(): + # Special case of final blank line with no bases + # just the sequence coordinate + pass + else: + warnings.warn( + "EMBL sequence line missing coordinates", BiopythonParserWarning + ) + seq_lines.append(line) + line = self.handle.readline() + self.line = line + return misc_lines, "".join(seq_lines).replace(" ", "") + + def _feed_first_line(self, consumer, line): + assert line[: self.HEADER_WIDTH].rstrip() == "ID" + if line[self.HEADER_WIDTH :].count(";") == 6: + # Looks like the semi colon separated style introduced in 2006 + self._feed_first_line_new(consumer, line) + elif line[self.HEADER_WIDTH :].count(";") == 3: + if line.rstrip().endswith(" SQ"): + # EMBL-bank patent data + self._feed_first_line_patents(consumer, line) + else: + # Looks like the pre 2006 style + self._feed_first_line_old(consumer, line) + elif line[self.HEADER_WIDTH :].count(";") == 2: + # Looks like KIKO patent data + self._feed_first_line_patents_kipo(consumer, line) + else: + raise ValueError("Did not recognise the ID line layout:\n" + line) + + def _feed_first_line_patents(self, consumer, line): + # Old style EMBL patent records where ID line ended SQ + # Not 100% sure that PRT here is really molecule type and + # not the data file division... + # + # Either Non-Redundant Level 1 database records, + # ID ; ; ; + # e.g. ID NRP_AX000635; PRT; NR1; 15 SQ + # + # Or, Non-Redundant Level 2 database records: + # ID ; ; ; + # e.g. ID NRP0000016E; PRT; NR2; 5 SQ + # e.g. ID NRP_AX000635; PRT; NR1; 15 SQ + fields = [ + data.strip() for data in line[self.HEADER_WIDTH :].strip()[:-3].split(";") + ] + assert len(fields) == 4 + consumer.locus(fields[0]) + consumer.residue_type(fields[1]) # semi-redundant + consumer.data_file_division(fields[2]) + # TODO - Record cluster size? + + def _feed_first_line_patents_kipo(self, consumer, line): + # EMBL format patent sequence from KIPO, e.g. + # ftp://ftp.ebi.ac.uk/pub/databases/patentdata/kipo_prt.dat.gz + # + # e.g. ID DI500001 STANDARD; PRT; 111 AA. + # + # This follows the style of _feed_first_line_old + assert line[: self.HEADER_WIDTH].rstrip() == "ID" + fields = [line[self.HEADER_WIDTH :].split(None, 1)[0]] + fields.extend(line[self.HEADER_WIDTH :].split(None, 1)[1].split(";")) + fields = [entry.strip() for entry in fields] + """ + The tokens represent: + + 0. Primary accession number + (space sep) + 1. ??? (e.g. standard) + (semi-colon) + 2. Molecule type (protein)? Division? Always 'PRT' + 3. Sequence length (e.g. '111 AA.') + """ + consumer.locus(fields[0]) # Should we also call the accession consumer? + # consumer.molecule_type(fields[2]) + self._feed_seq_length(consumer, fields[3]) + + def _feed_first_line_old(self, consumer, line): + # Expects an ID line in the style before 2006, e.g. + # ID SC10H5 standard; DNA; PRO; 4870 BP. + # ID BSUB9999 standard; circular DNA; PRO; 4214630 BP. + assert line[: self.HEADER_WIDTH].rstrip() == "ID" + fields = [line[self.HEADER_WIDTH :].split(None, 1)[0]] + fields.extend(line[self.HEADER_WIDTH :].split(None, 1)[1].split(";")) + fields = [entry.strip() for entry in fields] + """ + The tokens represent: + + 0. Primary accession number + (space sep) + 1. ??? (e.g. standard) + (semi-colon) + 2. Topology and/or Molecule type (e.g. 'circular DNA' or 'DNA') + 3. Taxonomic division (e.g. 'PRO') + 4. Sequence length (e.g. '4639675 BP.') + + """ + consumer.locus(fields[0]) # Should we also call the accession consumer? + consumer.residue_type(fields[2]) + if "circular" in fields[2]: + consumer.topology("circular") + consumer.molecule_type(fields[2].replace("circular", "").strip()) + elif "linear" in fields[2]: + consumer.topology("linear") + consumer.molecule_type(fields[2].replace("linear", "").strip()) + else: + consumer.molecule_type(fields[2].strip()) + consumer.data_file_division(fields[3]) + self._feed_seq_length(consumer, fields[4]) + + def _feed_first_line_new(self, consumer, line): + # Expects an ID line in the style introduced in 2006, e.g. + # ID X56734; SV 1; linear; mRNA; STD; PLN; 1859 BP. + # ID CD789012; SV 4; linear; genomic DNA; HTG; MAM; 500 BP. + assert line[: self.HEADER_WIDTH].rstrip() == "ID" + fields = [data.strip() for data in line[self.HEADER_WIDTH :].strip().split(";")] + assert len(fields) == 7 + """ + The tokens represent: + + 0. Primary accession number + 1. Sequence version number + 2. Topology: 'circular' or 'linear' + 3. Molecule type (e.g. 'genomic DNA') + 4. Data class (e.g. 'STD') + 5. Taxonomic division (e.g. 'PRO') + 6. Sequence length (e.g. '4639675 BP.') + + """ + + consumer.locus(fields[0]) + + # Call the accession consumer now, to make sure we record + # something as the record.id, in case there is no AC line + consumer.accession(fields[0]) + + # TODO - How to deal with the version field? At the moment the consumer + # will try and use this for the ID which isn't ideal for EMBL files. + version_parts = fields[1].split() + if ( + len(version_parts) == 2 + and version_parts[0] == "SV" + and version_parts[1].isdigit() + ): + consumer.version_suffix(version_parts[1]) + + # Based on how the old GenBank parser worked, merge these two: + consumer.residue_type(" ".join(fields[2:4])) # Semi-obsolete + + consumer.topology(fields[2]) + consumer.molecule_type(fields[3]) + + # consumer.xxx(fields[4]) # TODO - What should we do with the data class? + + consumer.data_file_division(fields[5]) + + self._feed_seq_length(consumer, fields[6]) + + @staticmethod + def _feed_seq_length(consumer, text): + length_parts = text.split() + assert len(length_parts) == 2, f"Invalid sequence length string {text!r}" + assert length_parts[1].upper() in ["BP", "BP.", "AA", "AA."] + consumer.size(length_parts[0]) + + def _feed_header_lines(self, consumer, lines): + consumer_dict = { + "AC": "accession", + "SV": "version", # SV line removed in June 2006, now part of ID line + "DE": "definition", + # 'RN' : 'reference_num', + # 'RC' : reference comment... TODO + # 'RP' : 'reference_bases', + # 'RX' : reference cross reference... DOI or Pubmed + "RG": "consrtm", # optional consortium + # 'RA' : 'authors', + # 'RT' : 'title', + "RL": "journal", + "OS": "organism", + "OC": "taxonomy", + # 'DR' : data reference + "CC": "comment", + # 'XX' : splitter + } + # We have to handle the following specially: + # RX (depending on reference type...) + for line in lines: + line_type = line[: self.EMBL_INDENT].strip() + data = line[self.EMBL_INDENT :].strip() + if line_type == "XX": + pass + elif line_type == "RN": + # Reformat reference numbers for the GenBank based consumer + # e.g. '[1]' becomes '1' + if data[0] == "[" and data[-1] == "]": + data = data[1:-1] + consumer.reference_num(data) + elif line_type == "RP": + if data.strip() == "[-]": + # Patent EMBL files from KIPO just use: RN [-] + pass + else: + # Reformat reference numbers for the GenBank based consumer + # e.g. '1-4639675' becomes '(bases 1 to 4639675)' + # and '160-550, 904-1055' becomes '(bases 160 to 550; 904 to 1055)' + # Note could be multi-line, and end with a comma + parts = [ + bases.replace("-", " to ").strip() + for bases in data.split(",") + if bases.strip() + ] + consumer.reference_bases(f"(bases {'; '.join(parts)})") + elif line_type == "RT": + # Remove the enclosing quotes and trailing semi colon. + # Note the title can be split over multiple lines. + if data.startswith('"'): + data = data[1:] + if data.endswith('";'): + data = data[:-2] + consumer.title(data) + elif line_type == "RX": + # EMBL support three reference types at the moment: + # - PUBMED PUBMED bibliographic database (NLM) + # - DOI Digital Object Identifier (International DOI Foundation) + # - AGRICOLA US National Agriculture Library (NAL) of the US Department + # of Agriculture (USDA) + # + # Format: + # RX resource_identifier; identifier. + # + # e.g. + # RX DOI; 10.1016/0024-3205(83)90010-3. + # RX PUBMED; 264242. + # + # Currently our reference object only supports PUBMED and MEDLINE + # (as these were in GenBank files?). + key, value = data.split(";", 1) + if value.endswith("."): + value = value[:-1] + value = value.strip() + if key == "PUBMED": + consumer.pubmed_id(value) + # TODO - Handle other reference types (here and in BioSQL bindings) + elif line_type == "CC": + # Have to pass a list of strings for this one (not just a string) + consumer.comment([data]) + elif line_type == "DR": + # Database Cross-reference, format: + # DR database_identifier; primary_identifier; secondary_identifier. + # + # e.g. + # DR MGI; 98599; Tcrb-V4. + # + # TODO - How should we store any secondary identifier? + parts = data.rstrip(".").split(";") + # Turn it into "database_identifier:primary_identifier" to + # mimic the GenBank parser. e.g. "MGI:98599" + if len(parts) == 1: + warnings.warn( + "Malformed DR line in EMBL file.", BiopythonParserWarning + ) + else: + consumer.dblink(f"{parts[0].strip()}:{parts[1].strip()}") + elif line_type == "RA": + # Remove trailing ; at end of authors list + consumer.authors(data.rstrip(";")) + elif line_type == "PR": + # In the EMBL patent files, this is a PR (PRiority) line which + # provides the earliest active priority within the family. + # The priority number comes first, followed by the priority date. + # + # e.g. + # PR JP19990377484 16-DEC-1999 + # + # However, in most EMBL files this is a PR (PRoject) line which + # gives the BioProject reference number. + # + # e.g. + # PR Project:PRJNA60715; + # + # In GenBank files this corresponds to the old PROJECT line + # which was later replaced with the DBLINK line. + if data.startswith("Project:"): + # Remove trailing ; at end of the project reference + consumer.project(data.rstrip(";")) + elif line_type == "KW": + consumer.keywords(data.rstrip(";")) + elif line_type in consumer_dict: + # Its a semi-automatic entry! + getattr(consumer, consumer_dict[line_type])(data) + else: + if self.debug: + print(f"Ignoring EMBL header line:\n{line}") + + def _feed_misc_lines(self, consumer, lines): + # TODO - Should we do something with the information on the SQ line(s)? + lines.append("") + line_iter = iter(lines) + try: + for line in line_iter: + if line.startswith("CO "): + line = line[5:].strip() + contig_location = line + while True: + line = next(line_iter) + if not line: + break + elif line.startswith("CO "): + # Don't need to preserve the whitespace here. + contig_location += line[5:].strip() + else: + raise ValueError( + "Expected CO (contig) continuation line, got:\n" + line + ) + consumer.contig_location(contig_location) + if line.startswith("SQ Sequence "): + # e.g. + # SQ Sequence 219 BP; 82 A; 48 C; 33 G; 45 T; 11 other; + # + # Or, EMBL-bank patent, e.g. + # SQ Sequence 465 AA; 3963407aa91d3a0d622fec679a4524e0; MD5; + self._feed_seq_length( + consumer, line[14:].rstrip().rstrip(";").split(";", 1)[0] + ) + # TODO - Record the checksum etc? + return + except StopIteration: + raise ValueError("Problem in misc lines before sequence") from None + + +class _ImgtScanner(EmblScanner): + """For extracting chunks of information in IMGT (EMBL like) files (PRIVATE). + + IMGT files are like EMBL files but in order to allow longer feature types + the features should be indented by 25 characters not 21 characters. In + practice the IMGT flat files tend to use either 21 or 25 characters, so we + must cope with both. + + This is private to encourage use of Bio.SeqIO rather than Bio.GenBank. + """ + + FEATURE_START_MARKERS = [ + "FH Key Location/Qualifiers", + "FH Key Location/Qualifiers (from EMBL)", + "FH Key Location/Qualifiers", + "FH", + ] + + def _feed_first_line(self, consumer, line): + assert line[: self.HEADER_WIDTH].rstrip() == "ID" + if line[self.HEADER_WIDTH :].count(";") != 5: + # Assume its an older EMBL-like line, + return EmblScanner._feed_first_line(self, consumer, line) + # Otherwise assume its the new (circa 2016) IMGT style + # as used in the IPD-IMGT/HLA Database + # + # https://github.com/ANHIG/IMGTHLA/ + # + # The key changes post 3.16 are the addition of an SV value + # to the ID line, these additions should make the format more + # similar to the ENA style. + # + # ID HLA00001 standard; DNA; HUM; 3503 BP. + # + # becomes + # + # ID HLA00001; SV 1; standard; DNA; HUM; 3503 BP. + fields = [data.strip() for data in line[self.HEADER_WIDTH :].strip().split(";")] + assert len(fields) == 6 + """ + The tokens represent: + + 0. Primary accession number (eg 'HLA00001') + 1. Sequence version number (eg 'SV 1') + 2. ??? eg 'standard' + 3. Molecule type (e.g. 'DNA') + 4. Taxonomic division (e.g. 'HUM') + 5. Sequence length (e.g. '3503 BP.') + """ + consumer.locus(fields[0]) + + # See TODO on the EMBL _feed_first_line_new about version field + version_parts = fields[1].split() + if ( + len(version_parts) == 2 + and version_parts[0] == "SV" + and version_parts[1].isdigit() + ): + consumer.version_suffix(version_parts[1]) + + consumer.residue_type(fields[3]) + if "circular" in fields[3]: + consumer.topology("circular") + consumer.molecule_type(fields[3].replace("circular", "").strip()) + elif "linear" in fields[3]: + consumer.topology("linear") + consumer.molecule_type(fields[3].replace("linear", "").strip()) + else: + consumer.molecule_type(fields[3].strip()) + consumer.data_file_division(fields[4]) + self._feed_seq_length(consumer, fields[5]) + + def parse_features(self, skip=False): + """Return list of tuples for the features (if present). + + Each feature is returned as a tuple (key, location, qualifiers) + where key and location are strings (e.g. "CDS" and + "complement(join(490883..490885,1..879))") while qualifiers + is a list of two string tuples (feature qualifier keys and values). + + Assumes you have already read to the start of the features table. + """ + if self.line.rstrip() not in self.FEATURE_START_MARKERS: + if self.debug: + print("Didn't find any feature table") + return [] + + while self.line.rstrip() in self.FEATURE_START_MARKERS: + self.line = self.handle.readline() + + bad_position_re = re.compile(r"([0-9]+)>") + + features = [] + line = self.line + while True: + if not line: + raise ValueError("Premature end of line during features table") + if line[: self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: + if self.debug: + print("Found start of sequence") + break + line = line.rstrip() + if line == "//": + raise ValueError("Premature end of features table, marker '//' found") + if line in self.FEATURE_END_MARKERS: + if self.debug: + print("Found end of features") + line = self.handle.readline() + break + if line[2 : self.FEATURE_QUALIFIER_INDENT].strip() == "": + # This is an empty feature line between qualifiers. Empty + # feature lines within qualifiers are handled below (ignored). + line = self.handle.readline() + continue + + if skip: + line = self.handle.readline() + while ( + line[: self.FEATURE_QUALIFIER_INDENT] + == self.FEATURE_QUALIFIER_SPACER + ): + line = self.handle.readline() + else: + assert line[:2] == "FT" + try: + feature_key, location_start = line[2:].strip().split() + except ValueError: + # e.g. "FT TRANSMEMBRANE-REGION2163..2240\n" + # Assume indent of 25 as per IMGT spec, with the location + # start in column 26 (one-based). + feature_key = line[2:25].strip() + location_start = line[25:].strip() + feature_lines = [location_start] + line = self.handle.readline() + while ( + line[: self.FEATURE_QUALIFIER_INDENT] + == self.FEATURE_QUALIFIER_SPACER + or line.rstrip() == "" + ): # cope with blank lines in the midst of a feature + # Use strip to remove any harmless trailing white space AND and leading + # white space (copes with 21 or 26 indents and orther variants) + assert line[:2] == "FT" + feature_lines.append(line[self.FEATURE_QUALIFIER_INDENT :].strip()) + line = self.handle.readline() + feature_key, location, qualifiers = self.parse_feature( + feature_key, feature_lines + ) + # Try to handle known problems with IMGT locations here: + if ">" in location: + # Nasty hack for common IMGT bug, should be >123 not 123> + # in a location string. At least here the meaning is clear, + # and since it is so common I don't want to issue a warning + # warnings.warn("Feature location %s is invalid, " + # "moving greater than sign before position" + # % location, BiopythonParserWarning) + location = bad_position_re.sub(r">\1", location) + features.append((feature_key, location, qualifiers)) + self.line = line + return features + + +class GenBankScanner(InsdcScanner): + """For extracting chunks of information in GenBank files.""" + + RECORD_START = "LOCUS " + HEADER_WIDTH = 12 + FEATURE_START_MARKERS = ["FEATURES Location/Qualifiers", "FEATURES"] + FEATURE_END_MARKERS: list[str] = [] + FEATURE_QUALIFIER_INDENT = 21 + FEATURE_QUALIFIER_SPACER = " " * FEATURE_QUALIFIER_INDENT + SEQUENCE_HEADERS = [ + "CONTIG", + "ORIGIN", + "BASE COUNT", + "WGS", + "TSA", + "TLS", + ] # trailing spaces removed + + GENBANK_INDENT = HEADER_WIDTH + GENBANK_SPACER = " " * GENBANK_INDENT + + STRUCTURED_COMMENT_START = "-START##" + STRUCTURED_COMMENT_END = "-END##" + STRUCTURED_COMMENT_DELIM = " :: " + + def parse_footer(self): + """Return a tuple containing a list of any misc strings, and the sequence.""" + if self.line[: self.HEADER_WIDTH].rstrip() not in self.SEQUENCE_HEADERS: + raise ValueError(f"Footer format unexpected: '{self.line}'") + + misc_lines = [] + while ( + self.line[: self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS + or self.line[: self.HEADER_WIDTH] == " " * self.HEADER_WIDTH + or "WGS" == self.line[:3] + ): + misc_lines.append(self.line.rstrip()) + self.line = self.handle.readline() + if not self.line: + raise ValueError("Premature end of file") + + if self.line[: self.HEADER_WIDTH].rstrip() in self.SEQUENCE_HEADERS: + raise ValueError(f"Eh? '{self.line}'") + + # Now just consume the sequence lines until reach the // marker + # or a CONTIG line + seq_lines = [] + line = self.line + while True: + if not line: + warnings.warn( + "Premature end of file in sequence data", BiopythonParserWarning + ) + line = "//" + break + line = line.rstrip() + if not line: + warnings.warn("Blank line in sequence data", BiopythonParserWarning) + line = self.handle.readline() + continue + if line == "//": + break + if line.startswith("CONTIG"): + break + if len(line) > 9 and line[9:10] != " ": + # Some broken programs indent the sequence by one space too many + # so try to get rid of that and test again. + warnings.warn( + "Invalid indentation for sequence line", BiopythonParserWarning + ) + line = line[1:] + if len(line) > 9 and line[9:10] != " ": + raise ValueError(f"Sequence line mal-formed, '{line}'") + seq_lines.append(line[10:]) # remove spaces later + line = self.handle.readline() + + self.line = line + return misc_lines, "".join(seq_lines).replace(" ", "") + + def _feed_first_line(self, consumer, line): + """Scan over and parse GenBank LOCUS line (PRIVATE). + + This must cope with several variants, primarily the old and new column + based standards from GenBank. Additionally EnsEMBL produces GenBank + files where the LOCUS line is space separated rather that following + the column based layout. + + We also try to cope with GenBank like files with partial LOCUS lines. + + As of release 229.0, the columns are no longer strictly in a given + position. See GenBank format release notes: + + "Historically, the LOCUS line has had a fixed length and its + elements have been presented at specific column positions... + But with the anticipated increases in the lengths of accession + numbers, and the advent of sequences that are gigabases long, + maintaining the column positions will not always be possible and + the overall length of the LOCUS line could exceed 79 characters." + + """ + ##################################### + # LOCUS line # + ##################################### + if line[0 : self.GENBANK_INDENT] != "LOCUS ": + raise ValueError("LOCUS line does not start correctly:\n" + line) + + # Have to break up the locus line, and handle the different bits of it. + # There are at least two different versions of the locus line... + if line[29:33] in [" bp ", " aa ", " rc "] and line[55:62] == " ": + # Old... note we insist on the 55:62 being empty to avoid trying + # to parse space separated LOCUS lines from Ensembl etc, see below. + # + # Positions Contents + # --------- -------- + # 00:06 LOCUS + # 06:12 spaces + # 12:?? Locus name + # ??:?? space + # ??:29 Length of sequence, right-justified + # 29:33 space, bp, space + # 33:41 strand type / molecule type, e.g. DNA + # 41:42 space + # 42:51 Blank (implies linear), linear or circular + # 51:52 space + # 52:55 The division code (e.g. BCT, VRL, INV) + # 55:62 space + # 62:73 Date, in the form dd-MMM-yyyy (e.g., 15-MAR-1991) + # + # assert line[29:33] in [' bp ', ' aa ',' rc '] , \ + # 'LOCUS line does not contain size units at expected position:\n' + line + if line[41:42] != " ": + raise ValueError( + "LOCUS line does not contain space at position 42:\n" + line + ) + if line[42:51].strip() not in ["", "linear", "circular"]: + raise ValueError( + "LOCUS line does not contain valid entry " + "(linear, circular, ...):\n" + line + ) + if line[51:52] != " ": + raise ValueError( + "LOCUS line does not contain space at position 52:\n" + line + ) + # if line[55:62] != ' ': + # raise ValueError('LOCUS line does not contain spaces from position 56 to 62:\n' + line) + parse_date = False + if line[62:73].strip(): + parse_date = True + if line[64:65] != "-": + parse_date = False + warnings.warn( + "LOCUS line does not contain - " + "at position 65 in date:\n" + line, + BiopythonParserWarning, + ) + if line[68:69] != "-": + parse_date = False + warnings.warn( + "LOCUS line does not contain - " + "at position 69 in date:\n" + line, + BiopythonParserWarning, + ) + + name_and_length_str = line[self.GENBANK_INDENT : 29] + while " " in name_and_length_str: + name_and_length_str = name_and_length_str.replace(" ", " ") + name_and_length = name_and_length_str.split(" ") + if len(name_and_length) > 2: + raise ValueError( + "Cannot parse the name and length in the LOCUS line:\n" + line + ) + if len(name_and_length) == 1: + raise ValueError("Name and length collide in the LOCUS line:\n" + line) + # Should be possible to split them based on position, if + # a clear definition of the standard exists THAT AGREES with + # existing files. + name, length = name_and_length + if len(name) > 16: + # As long as the sequence is short, can steal its leading spaces + # to extend the name over the current 16 character limit. + # However, that deserves a warning as it is out of spec. + warnings.warn( + "GenBank LOCUS line identifier over 16 characters", + BiopythonParserWarning, + ) + consumer.locus(name) + consumer.size(length) + # consumer.residue_type(line[33:41].strip()) + + if line[33:51].strip() == "" and line[29:33] == " aa ": + # Amino acids -> protein (even if there is no residue type given) + consumer.residue_type("PROTEIN") + else: + consumer.residue_type(line[33:51].strip()) + + consumer.molecule_type(line[33:41].strip()) + consumer.topology(line[42:51].strip()) + consumer.data_file_division(line[52:55]) + if parse_date: + consumer.date(line[62:73]) + elif line[40:44] in [" bp ", " aa ", " rc "] and line[54:64].strip() in [ + "", + "linear", + "circular", + ]: + # New... linear/circular/big blank test should avoid EnsEMBL style + # LOCUS line being treated like a proper column based LOCUS line. + # + # Positions Contents + # --------- -------- + # 00:06 LOCUS + # 06:12 spaces + # 12:?? Locus name + # ??:?? space + # ??:40 Length of sequence, right-justified + # 40:44 space, bp, space + # 44:47 Blank, ss-, ds-, ms- + # 47:54 Blank, DNA, RNA, tRNA, mRNA, uRNA, snRNA, cDNA + # 54:55 space + # 55:63 Blank (implies linear), linear or circular + # 63:64 space + # 64:67 The division code (e.g. BCT, VRL, INV) + # 67:68 space + # 68:79 Date, in the form dd-MMM-yyyy (e.g., 15-MAR-1991) + # + if len(line) < 79: + # JBEI genbank files seem to miss a division code and date + # See issue #1656 e.g. + # LOCUS pEH010 5743 bp DNA circular + warnings.warn( + f"Truncated LOCUS line found - is this correct?\n:{line!r}", + BiopythonParserWarning, + ) + padding_len = 79 - len(line) + padding = " " * padding_len + line += padding + + if line[40:44] not in [" bp ", " aa ", " rc "]: + raise ValueError( + "LOCUS line does not contain size units at " + "expected position:\n" + line + ) + if line[44:47] not in [" ", "ss-", "ds-", "ms-"]: + raise ValueError( + "LOCUS line does not have valid strand " + "type (Single stranded, ...):\n" + line + ) + + if not ( + line[47:54].strip() == "" + or "DNA" in line[47:54].strip().upper() + or "RNA" in line[47:54].strip().upper() + ): + raise ValueError( + "LOCUS line does not contain valid " + "sequence type (DNA, RNA, ...):\n" + line + ) + if line[54:55] != " ": + raise ValueError( + "LOCUS line does not contain space at position 55:\n" + line + ) + if line[55:63].strip() not in ["", "linear", "circular"]: + raise ValueError( + "LOCUS line does not contain valid " + "entry (linear, circular, ...):\n" + line + ) + if line[63:64] != " ": + raise ValueError( + "LOCUS line does not contain space at position 64:\n" + line + ) + if line[67:68] != " ": + raise ValueError( + "LOCUS line does not contain space at position 68:\n" + line + ) + parse_date = False + if line[68:79].strip(): + parse_date = True + if line[70:71] != "-": + parse_date = False + warnings.warn( + "LOCUS line does not contain - " + "at position 71 in date:\n" + line, + BiopythonParserWarning, + ) + if line[74:75] != "-": + parse_date = False + warnings.warn( + "LOCUS line does not contain - " + "at position 75 in date:\n" + line, + BiopythonParserWarning, + ) + + name_and_length_str = line[self.GENBANK_INDENT : 40] + while " " in name_and_length_str: + name_and_length_str = name_and_length_str.replace(" ", " ") + name_and_length = name_and_length_str.split(" ") + if len(name_and_length) > 2: + raise ValueError( + "Cannot parse the name and length in the LOCUS line:\n" + line + ) + if len(name_and_length) == 1: + raise ValueError("Name and length collide in the LOCUS line:\n" + line) + # Should be possible to split them based on position, if + # a clear definition of the stand exists THAT AGREES with + # existing files. + consumer.locus(name_and_length[0]) + consumer.size(name_and_length[1]) + + if line[44:54].strip() == "" and line[40:44] == " aa ": + # Amino acids -> protein (even if there is no residue type given) + consumer.residue_type(("PROTEIN " + line[54:63]).strip()) + else: + consumer.residue_type(line[44:63].strip()) + + consumer.molecule_type(line[44:54].strip()) + consumer.topology(line[55:63].strip()) + if line[64:76].strip(): + consumer.data_file_division(line[64:67]) + if parse_date: + consumer.date(line[68:79]) + elif line[self.GENBANK_INDENT :].strip().count(" ") == 0: + # Truncated LOCUS line, as produced by some EMBOSS tools - see bug 1762 + # + # e.g. + # + # "LOCUS U00096" + # + # rather than: + # + # "LOCUS U00096 4639675 bp DNA circular BCT" + # + # Positions Contents + # --------- -------- + # 00:06 LOCUS + # 06:12 spaces + # 12:?? Locus name + if line[self.GENBANK_INDENT :].strip() != "": + consumer.locus(line[self.GENBANK_INDENT :].strip()) + else: + # Must just have just "LOCUS ", is this even legitimate? + # We should be able to continue parsing... we need real world testcases! + warnings.warn( + f"Minimal LOCUS line found - is this correct?\n:{line!r}", + BiopythonParserWarning, + ) + elif ( + len(line.split()) == 8 + and line.split()[3] in ("aa", "bp") + and line.split()[5] in ("linear", "circular") + ): + # Cope with invalidly spaced GenBank LOCUS lines like + # LOCUS AB070938 6497 bp DNA linear BCT 11-OCT-2001 + # This will also cope with extra long accession numbers and + # sequence lengths + splitline = line.split() + consumer.locus(splitline[1]) + # Provide descriptive error message if the sequence is too long + # for python to handle + + if int(splitline[2]) > sys.maxsize: + raise ValueError( + "Tried to load a sequence with a length %s, " + "your installation of python can only load " + "sesquences of length %s" % (splitline[2], sys.maxsize) + ) + else: + consumer.size(splitline[2]) + + consumer.residue_type(splitline[4]) + consumer.topology(splitline[5]) + consumer.data_file_division(splitline[6]) + consumer.date(splitline[7]) + if len(line) < 80: + warnings.warn( + "Attempting to parse malformed locus line:\n%r\n" + "Found locus %r size %r residue_type %r\n" + "Some fields may be wrong." + % (line, splitline[1], splitline[2], splitline[4]), + BiopythonParserWarning, + ) + elif len(line.split()) == 7 and line.split()[3] in ["aa", "bp"]: + # Cope with EnsEMBL genbank files which use space separation rather + # than the expected column based layout. e.g. + # LOCUS HG531_PATCH 1000000 bp DNA HTG 18-JUN-2011 + # LOCUS HG531_PATCH 759984 bp DNA HTG 18-JUN-2011 + # LOCUS HG506_HG1000_1_PATCH 814959 bp DNA HTG 18-JUN-2011 + # LOCUS HG506_HG1000_1_PATCH 1219964 bp DNA HTG 18-JUN-2011 + # Notice that the 'bp' can occur in the position expected by either + # the old or the new fixed column standards (parsed above). + splitline = line.split() + consumer.locus(splitline[1]) + consumer.size(splitline[2]) + consumer.residue_type(splitline[4]) + consumer.data_file_division(splitline[5]) + consumer.date(splitline[6]) + elif len(line.split()) >= 4 and line.split()[3] in ["aa", "bp"]: + # Cope with EMBOSS seqret output where it seems the locus id can cause + # the other fields to overflow. We just IGNORE the other fields! + warnings.warn( + f"Malformed LOCUS line found - is this correct?\n:{line!r}", + BiopythonParserWarning, + ) + consumer.locus(line.split()[1]) + consumer.size(line.split()[2]) + elif len(line.split()) >= 4 and line.split()[-1] in ["aa", "bp"]: + # Cope with pseudo-GenBank files like this: + # "LOCUS RNA5 complete 1718 bp" + # Treat everything between LOCUS and the size as the identifier. + warnings.warn( + f"Malformed LOCUS line found - is this correct?\n:{line!r}", + BiopythonParserWarning, + ) + consumer.locus(line[5:].rsplit(None, 2)[0].strip()) + consumer.size(line.split()[-2]) + else: + raise ValueError("Did not recognise the LOCUS line layout:\n" + line) + + def _feed_header_lines(self, consumer, lines): + # Following dictionary maps GenBank lines to the associated + # consumer methods - the special cases like LOCUS where one + # genbank line triggers several consumer calls have to be + # handled individually. + consumer_dict = { + "DEFINITION": "definition", + "ACCESSION": "accession", + "NID": "nid", + "PID": "pid", + "DBSOURCE": "db_source", + "KEYWORDS": "keywords", + "SEGMENT": "segment", + "SOURCE": "source", + "AUTHORS": "authors", + "CONSRTM": "consrtm", + "PROJECT": "project", + "TITLE": "title", + "JOURNAL": "journal", + "MEDLINE": "medline_id", + "PUBMED": "pubmed_id", + "REMARK": "remark", + } + # We have to handle the following specially: + # ORIGIN (locus, size, residue_type, data_file_division and date) + # COMMENT (comment) + # VERSION (version and gi) + # DBLINK (database links like projects, newlines important) + # REFERENCE (eference_num and reference_bases) + # ORGANISM (organism and taxonomy) + lines = [_f for _f in lines if _f] + lines.append("") # helps avoid getting StopIteration all the time + line_iter = iter(lines) + try: + line = next(line_iter) + while True: + if not line: + break + line_type = line[: self.GENBANK_INDENT].strip() + data = line[self.GENBANK_INDENT :].strip() + + if line_type == "VERSION": + # Need to call consumer.version(), and maybe also consumer.gi() as well. + # e.g. + # VERSION AC007323.5 GI:6587720 + while " " in data: + data = data.replace(" ", " ") + if " GI:" not in data: + consumer.version(data) + else: + if self.debug: + print( + "Version [" + + data.split(" GI:")[0] + + "], gi [" + + data.split(" GI:")[1] + + "]" + ) + consumer.version(data.split(" GI:")[0]) + consumer.gi(data.split(" GI:")[1]) + # Read in the next line! + line = next(line_iter) + elif line_type == "DBLINK": + # Need to call consumer.dblink() for each line, e.g. + # DBLINK Project: 57779 + # BioProject: PRJNA57779 + line = data.strip() + # Read in the next line, and see if its more of the DBLINK section: + while True: + next_line = next(line_iter) + if next_line[: self.GENBANK_INDENT] == self.GENBANK_SPACER: + # No new tag on next line, continue to add dbrefs + if next_line.count(":") == 0: + # This is a continuation of previous dbref + line += " " + next_line.strip() + else: + # Add this continuation to the data string + consumer.dblink(line.strip()) + line = next_line + continue + else: + # Add this continuation to the data string + consumer.dblink(line.strip()) + # End of the DBLINK, leave this text in the variable "line" + line = next_line + break + line = next(line_iter) + elif line_type == "REFERENCE": + if self.debug > 1: + print("Found reference [" + data + "]") + # Need to call consumer.reference_num() and consumer.reference_bases() + # e.g. + # REFERENCE 1 (bases 1 to 86436) + # + # Note that this can be multiline, see Bug 1968, e.g. + # + # REFERENCE 42 (bases 1517 to 1696; 3932 to 4112; 17880 to 17975; 21142 to + # 28259) + # + # For such cases we will call the consumer once only. + data = data.strip() + + # Read in the next line, and see if its more of the reference: + while True: + line = next(line_iter) + if line[: self.GENBANK_INDENT] == self.GENBANK_SPACER: + # Add this continuation to the data string + data += " " + line[self.GENBANK_INDENT :] + if self.debug > 1: + print("Extended reference text [" + data + "]") + else: + # End of the reference, leave this text in the variable "line" + break + + # We now have all the reference line(s) stored in a string, data, + # which we pass to the consumer + while " " in data: + data = data.replace(" ", " ") + if " " not in data: + if self.debug > 2: + print('Reference number "' + data + '"') + consumer.reference_num(data) + else: + if self.debug > 2: + print( + 'Reference number "' + + data[: data.find(" ")] + + '", "' + + data[data.find(" ") + 1 :] + + '"' + ) + consumer.reference_num(data[: data.find(" ")]) + consumer.reference_bases(data[data.find(" ") + 1 :]) + elif line_type == "ORGANISM": + # Typically the first line is the organism, and subsequent lines + # are the taxonomy lineage. However, given longer and longer + # species names (as more and more strains and sub strains get + # sequenced) the oragnism name can now get wrapped onto multiple + # lines. The NCBI say we have to recognise the lineage line by + # the presence of semi-colon delimited entries. In the long term, + # they are considering adding a new keyword (e.g. LINEAGE). + # See Bug 2591 for details. + organism_data = data + lineage_data = "" + while True: + line = next(line_iter) + if line[0 : self.GENBANK_INDENT] == self.GENBANK_SPACER: + if ( + lineage_data + or ";" in line + or line[self.GENBANK_INDENT :].strip() + in ( + "Bacteria.", + "Archaea.", + "Eukaryota.", + "Unclassified.", + "Viruses.", + "cellular organisms.", + "other sequences.", + "unclassified sequences.", + ) + ): + lineage_data += " " + line[self.GENBANK_INDENT :] + elif line[self.GENBANK_INDENT :].strip() == ".": + # No lineage data, just . place holder + pass + else: + organism_data += ( + " " + line[self.GENBANK_INDENT :].strip() + ) + else: + # End of organism and taxonomy + break + consumer.organism(organism_data) + if lineage_data.strip() == "" and self.debug > 1: + print("Taxonomy line(s) missing or blank") + consumer.taxonomy(lineage_data.strip()) + del organism_data, lineage_data + elif line_type == "COMMENT": + # A COMMENT can either be plain text or tabular (Structured Comment), + # or contain both. Multi-line comments are common. The code calls + # consumer.comment() once with a list where each entry + # is a line. If there's a structured comment consumer.structured_comment() + # is called with a dict of dicts where the secondary key/value pairs are + # the same as those in the structured comment table. The primary key is + # the title or header of the table (e.g. Assembly-Data, FluData). See + # http://www.ncbi.nlm.nih.gov/genbank/structuredcomment + # for more information on Structured Comments. + data = line[self.GENBANK_INDENT :] + if self.debug > 1: + print("Found comment") + comment_list = [] + structured_comment_dict = defaultdict(dict) + regex = rf"([^#]+){self.STRUCTURED_COMMENT_START}$" + structured_comment_key = re.search(regex, data) + if structured_comment_key is not None: + structured_comment_key = structured_comment_key.group(1) + if self.debug > 1: + print("Found Structured Comment") + else: + comment_list.append(data) + + while True: + line = next(line_iter) + data = line[self.GENBANK_INDENT :] + if line[0 : self.GENBANK_INDENT] == self.GENBANK_SPACER: + if self.STRUCTURED_COMMENT_START in data: + regex = rf"([^#]+){self.STRUCTURED_COMMENT_START}$" + structured_comment_key = re.search(regex, data) + if structured_comment_key is not None: + structured_comment_key = ( + structured_comment_key.group(1) + ) + else: + comment_list.append(data) + elif ( + structured_comment_key is not None + and self.STRUCTURED_COMMENT_DELIM.strip() in data + ): + match = re.search( + rf"(.+?)\s*{self.STRUCTURED_COMMENT_DELIM.strip()}\s*(.*)", + data, + ) + structured_comment_dict[structured_comment_key][ + match.group(1) + ] = match.group(2) + if self.debug > 2: + print( + "Structured Comment continuation [" + data + "]" + ) + elif ( + structured_comment_key is not None + and self.STRUCTURED_COMMENT_END not in data + ): + # Don't die on a malformed comment, just warn and carry on + if ( + structured_comment_key + not in structured_comment_dict + ): + warnings.warn( + f"Structured comment not parsed on malformed header line: {line}", + BiopythonParserWarning, + ) + continue + + # The current structured comment has a multiline value + previous_value_line = structured_comment_dict[ + structured_comment_key + ][match.group(1)] + structured_comment_dict[structured_comment_key][ + match.group(1) + ] = (previous_value_line + " " + line.strip()) + elif self.STRUCTURED_COMMENT_END in data: + # End of structured comment + structured_comment_key = None + else: + comment_list.append(data) + if self.debug > 2: + print("Comment continuation [" + data + "]") + else: + # End of the comment + break + if comment_list: + consumer.comment(comment_list) + if structured_comment_dict: + consumer.structured_comment(structured_comment_dict) + del comment_list, structured_comment_key, structured_comment_dict + elif line_type in consumer_dict: + # It's a semi-automatic entry! + # Now, this may be a multi line entry... + while True: + line = next(line_iter) + if line[0 : self.GENBANK_INDENT] == self.GENBANK_SPACER: + data += " " + line[self.GENBANK_INDENT :] + else: + # We now have all the data for this entry: + + # The DEFINITION field must ends with a period + # # see ftp://ftp.ncbi.nih.gov/genbank/gbrel.txt [3.4.5] + # and discussion https://github.com/biopython/biopython/pull/616 + # We consider this period belong to the syntax, not to the data + # So remove it if it exist + if line_type == "DEFINITION" and data.endswith("."): + data = data[:-1] + getattr(consumer, consumer_dict[line_type])(data) + # End of continuation - return to top of loop! + break + else: + if self.debug: + print("Ignoring GenBank header line:\n" % line) + # Read in next line + line = next(line_iter) + except StopIteration: + raise ValueError("Problem in header") from None + + def _feed_misc_lines(self, consumer, lines): + # Deals with a few misc lines between the features and the sequence + lines.append("") + line_iter = iter(lines) + try: + for line in line_iter: + if line.startswith("BASE COUNT"): + line = line[10:].strip() + if line: + if self.debug: + print("base_count = " + line) + consumer.base_count(line) + if line.startswith("ORIGIN"): + line = line[6:].strip() + if line: + if self.debug: + print("origin_name = " + line) + consumer.origin_name(line) + if line.startswith("TLS "): + line = line[3:].strip() + consumer.tls(line) + if line.startswith("TSA "): + line = line[3:].strip() + consumer.tsa(line) + if line.startswith("WGS "): + line = line[3:].strip() + consumer.wgs(line) + if line.startswith("WGS_SCAFLD"): + line = line[10:].strip() + consumer.add_wgs_scafld(line) + if line.startswith("CONTIG"): + line = line[6:].strip() + contig_location = line + while True: + line = next(line_iter) + if not line: + break + elif line[: self.GENBANK_INDENT] == self.GENBANK_SPACER: + # Don't need to preserve the whitespace here. + contig_location += line[self.GENBANK_INDENT :].rstrip() + elif line.startswith("ORIGIN"): + # Strange, seen this in GenPept files via Entrez gbwithparts + line = line[6:].strip() + if line: + consumer.origin_name(line) + break + else: + raise ValueError( + "Expected CONTIG continuation line, got:\n" + line + ) + consumer.contig_location(contig_location) + return + except StopIteration: + raise ValueError("Problem in misc lines before sequence") from None diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b947bc89431dce1a4cb089412a12935839949097 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/__init__.py @@ -0,0 +1,1206 @@ +# Copyright 2000 by Jeffrey Chang, Brad Chapman. All rights reserved. +# Copyright 2006-2017 by Peter Cock. All rights reserved. +# +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +"""Code to work with GenBank formatted files. + +Rather than using Bio.GenBank, you are now encouraged to use Bio.SeqIO with +the "genbank" or "embl" format names to parse GenBank or EMBL files into +SeqRecord and SeqFeature objects (see the Biopython tutorial for details). + +Using Bio.GenBank directly to parse GenBank files is only useful if you want +to obtain GenBank-specific Record objects, which is a much closer +representation to the raw file contents than the SeqRecord alternative from +the FeatureParser (used in Bio.SeqIO). + +To use the Bio.GenBank parser, there are two helper functions: + + - read Parse a handle containing a single GenBank record + as Bio.GenBank specific Record objects. + - parse Iterate over a handle containing multiple GenBank + records as Bio.GenBank specific Record objects. + +The following internal classes are not intended for direct use and may +be deprecated in a future release. + +Classes: + - Iterator Iterate through a file of GenBank entries + - FeatureParser Parse GenBank data in SeqRecord and SeqFeature objects. + - RecordParser Parse GenBank data into a Record object. + +Exceptions: + - ParserFailureError Exception indicating a failure in the parser (ie. + scanner or consumer) + +""" + +import re +import warnings + +from Bio import BiopythonParserWarning +from Bio.Seq import Seq +from Bio.SeqFeature import Location +from Bio.SeqFeature import LocationParserError +from Bio.SeqFeature import Reference +from Bio.SeqFeature import SeqFeature +from Bio.SeqFeature import SimpleLocation + +from .Scanner import GenBankScanner +from .utils import FeatureValueCleaner + +# Constants used to parse GenBank header lines +GENBANK_INDENT = 12 +GENBANK_SPACER = " " * GENBANK_INDENT + +# Constants for parsing GenBank feature lines +FEATURE_KEY_INDENT = 5 +FEATURE_QUALIFIER_INDENT = 21 +FEATURE_KEY_SPACER = " " * FEATURE_KEY_INDENT +FEATURE_QUALIFIER_SPACER = " " * FEATURE_QUALIFIER_INDENT + + +class Iterator: + """Iterator interface to move over a file of GenBank entries one at a time (OBSOLETE). + + This class is likely to be deprecated in a future release of Biopython. + Please use Bio.SeqIO.parse(..., format="gb") or Bio.GenBank.parse(...) + for SeqRecord and GenBank specific Record objects respectively instead. + """ + + def __init__(self, handle, parser=None): + """Initialize the iterator. + + Arguments: + - handle - A handle with GenBank entries to iterate through. + - parser - An optional parser to pass the entries through before + returning them. If None, then the raw entry will be returned. + + """ + self.handle = handle + self._parser = parser + + def __next__(self): + """Return the next GenBank record from the handle. + + Will return None if we ran out of records. + """ + if self._parser is None: + lines = [] + while True: + line = self.handle.readline() + if not line: + return None # Premature end of file? + lines.append(line) + if line.rstrip() == "//": + break + return "".join(lines) + try: + return self._parser.parse(self.handle) + except StopIteration: + return None + + def __iter__(self): + """Iterate over the records.""" + return iter(self.__next__, None) + + +class ParserFailureError(ValueError): + """Failure caused by some kind of problem in the parser.""" + + +_cleaner = FeatureValueCleaner() + + +class FeatureParser: + """Parse GenBank files into Seq + Feature objects (OBSOLETE). + + Direct use of this class is discouraged, and may be deprecated in + a future release of Biopython. + + Please use Bio.SeqIO.parse(...) or Bio.SeqIO.read(...) instead. + """ + + def __init__(self, debug_level=0, use_fuzziness=1, feature_cleaner=None): + """Initialize a GenBank parser and Feature consumer. + + Arguments: + - debug_level - An optional argument that species the amount of + debugging information the parser should spit out. By default we have + no debugging info (the fastest way to do things), but if you want + you can set this as high as two and see exactly where a parse fails. + - use_fuzziness - Specify whether or not to use fuzzy representations. + The default is 1 (use fuzziness). + - feature_cleaner - A class which will be used to clean out the + values of features. This class must implement the function + clean_value. GenBank.utils has a "standard" cleaner class, which + is used by default. + + """ + self._scanner = GenBankScanner(debug_level) + self.use_fuzziness = use_fuzziness + if feature_cleaner: + self._cleaner = feature_cleaner + else: + self._cleaner = _cleaner # default + + def parse(self, handle): + """Parse the specified handle.""" + _consumer = _FeatureConsumer(self.use_fuzziness, self._cleaner) + self._scanner.feed(handle, _consumer) + return _consumer.data + + +class RecordParser: + """Parse GenBank files into Record objects (OBSOLETE). + + Direct use of this class is discouraged, and may be deprecated in + a future release of Biopython. + + Please use the Bio.GenBank.parse(...) or Bio.GenBank.read(...) functions + instead. + """ + + def __init__(self, debug_level=0): + """Initialize the parser. + + Arguments: + - debug_level - An optional argument that species the amount of + debugging information the parser should spit out. By default we have + no debugging info (the fastest way to do things), but if you want + you can set this as high as two and see exactly where a parse fails. + + """ + self._scanner = GenBankScanner(debug_level) + + def parse(self, handle): + """Parse the specified handle into a GenBank record.""" + _consumer = _RecordConsumer() + + self._scanner.feed(handle, _consumer) + return _consumer.data + + +class _BaseGenBankConsumer: + """Abstract GenBank consumer providing useful general functions (PRIVATE). + + This just helps to eliminate some duplication in things that most + GenBank consumers want to do. + """ + + # Special keys in GenBank records that we should remove spaces from + # For instance, \translation keys have values which are proteins and + # should have spaces and newlines removed from them. This class + # attribute gives us more control over specific formatting problems. + remove_space_keys = ["translation"] + + def __init__(self): + pass + + @staticmethod + def _split_keywords(keyword_string): + """Split a string of keywords into a nice clean list (PRIVATE).""" + # process the keywords into a python list + if keyword_string == "" or keyword_string == ".": + keywords = "" + elif keyword_string[-1] == ".": + keywords = keyword_string[:-1] + else: + keywords = keyword_string + keyword_list = keywords.split(";") + return [x.strip() for x in keyword_list] + + @staticmethod + def _split_accessions(accession_string): + """Split a string of accession numbers into a list (PRIVATE).""" + # first replace all line feeds with spaces + # Also, EMBL style accessions are split with ';' + accession = accession_string.replace("\n", " ").replace(";", " ") + + return [x.strip() for x in accession.split() if x.strip()] + + @staticmethod + def _split_taxonomy(taxonomy_string): + """Split a string with taxonomy info into a list (PRIVATE).""" + if not taxonomy_string or taxonomy_string == ".": + # Missing data, no taxonomy + return [] + + if taxonomy_string[-1] == ".": + tax_info = taxonomy_string[:-1] + else: + tax_info = taxonomy_string + tax_list = tax_info.split(";") + return [ + item.strip() + for tax_item in tax_list + for item in tax_item.split("\n") + if item + ] + + @staticmethod + def _clean_location(location_string): + """Clean whitespace out of a location string (PRIVATE). + + The location parser isn't a fan of whitespace, so we clean it out + before feeding it into the parser. + """ + # Originally this imported string.whitespace and did a replace + # via a loop. It's simpler to just split on whitespace and rejoin + # the string - and this avoids importing string too. See Bug 2684. + return "".join(location_string.split()) + + @staticmethod + def _remove_newlines(text): + """Remove any newlines in the passed text, returning the new string (PRIVATE).""" + # get rid of newlines in the qualifier value + newlines = ["\n", "\r"] + for ws in newlines: + text = text.replace(ws, "") + + return text + + @staticmethod + def _normalize_spaces(text): + """Replace multiple spaces in the passed text with single spaces (PRIVATE).""" + # get rid of excessive spaces + return " ".join(x for x in text.split(" ") if x) + + @staticmethod + def _remove_spaces(text): + """Remove all spaces from the passed text (PRIVATE).""" + return text.replace(" ", "") + + @staticmethod + def _convert_to_python_numbers(start, end): + """Convert a start and end range to python notation (PRIVATE). + + In GenBank, starts and ends are defined in "biological" coordinates, + where 1 is the first base and [i, j] means to include both i and j. + + In python, 0 is the first base and [i, j] means to include i, but + not j. + + So, to convert "biological" to python coordinates, we need to + subtract 1 from the start, and leave the end and things should + be converted happily. + """ + new_start = start - 1 + new_end = end + + return new_start, new_end + + +class _FeatureConsumer(_BaseGenBankConsumer): + """Create a SeqRecord object with Features to return (PRIVATE). + + Attributes: + - use_fuzziness - specify whether or not to parse with fuzziness in + feature locations. + - feature_cleaner - a class that will be used to provide specialized + cleaning-up of feature values. + + """ + + def __init__(self, use_fuzziness, feature_cleaner=None): + from Bio.SeqRecord import SeqRecord + + _BaseGenBankConsumer.__init__(self) + self.data = SeqRecord(None, id=None) + self.data.id = None + self.data.description = "" + + self._use_fuzziness = use_fuzziness + self._feature_cleaner = feature_cleaner + + self._seq_type = "" + self._seq_data = [] + self._cur_reference = None + self._cur_feature = None + self._expected_size = None + + def locus(self, locus_name): + """Set the locus name is set as the name of the Sequence.""" + self.data.name = locus_name + + def size(self, content): + """Record the sequence length.""" + self._expected_size = int(content) + + def residue_type(self, type): + """Record the sequence type (SEMI-OBSOLETE). + + This reflects the fact that the topology (linear/circular) and + molecule type (e.g. DNA vs RNA) were a single field in early + files. Current GenBank/EMBL files have two fields. + """ + self._seq_type = type.strip() + + def topology(self, topology): + """Validate and record sequence topology. + + The topology argument should be "linear" or "circular" (string). + """ + if topology: + if topology not in ["linear", "circular"]: + raise ParserFailureError( + f"Unexpected topology {topology!r} should be linear or circular" + ) + self.data.annotations["topology"] = topology + + def molecule_type(self, mol_type): + """Validate and record the molecule type (for round-trip etc).""" + if mol_type: + if "circular" in mol_type or "linear" in mol_type: + raise ParserFailureError( + f"Molecule type {mol_type!r} should not include topology" + ) + + # Writing out records will fail if we have a lower case DNA + # or RNA string in here, so upper case it. + # This is a bit ugly, but we don't want to upper case e.g. + # the m in mRNA, but thanks to the strip we lost the spaces + # so we need to index from the back + if mol_type[-3:].upper() in ("DNA", "RNA") and not mol_type[-3:].isupper(): + warnings.warn( + f"Non-upper case molecule type in LOCUS line: {mol_type}", + BiopythonParserWarning, + ) + + self.data.annotations["molecule_type"] = mol_type + + def data_file_division(self, division): + self.data.annotations["data_file_division"] = division + + def date(self, submit_date): + self.data.annotations["date"] = submit_date + + def definition(self, definition): + """Set the definition as the description of the sequence.""" + if self.data.description: + # Append to any existing description + # e.g. EMBL files with two DE lines. + self.data.description += " " + definition + else: + self.data.description = definition + + def accession(self, acc_num): + """Set the accession number as the id of the sequence. + + If we have multiple accession numbers, the first one passed is + used. + """ + new_acc_nums = self._split_accessions(acc_num) + + # Also record them ALL in the annotations + try: + # On the off chance there was more than one accession line: + for acc in new_acc_nums: + # Prevent repeat entries + if acc not in self.data.annotations["accessions"]: + self.data.annotations["accessions"].append(acc) + except KeyError: + self.data.annotations["accessions"] = new_acc_nums + + # if we haven't set the id information yet, add the first acc num + if not self.data.id: + if len(new_acc_nums) > 0: + # self.data.id = new_acc_nums[0] + # Use the FIRST accession as the ID, not the first on this line! + self.data.id = self.data.annotations["accessions"][0] + + def tls(self, content): + self.data.annotations["tls"] = content.split("-") + + def tsa(self, content): + self.data.annotations["tsa"] = content.split("-") + + def wgs(self, content): + self.data.annotations["wgs"] = content.split("-") + + def add_wgs_scafld(self, content): + self.data.annotations.setdefault("wgs_scafld", []).append(content.split("-")) + + def nid(self, content): + self.data.annotations["nid"] = content + + def pid(self, content): + self.data.annotations["pid"] = content + + def version(self, version_id): + # Want to use the versioned accession as the record.id + # This comes from the VERSION line in GenBank files, or the + # obsolete SV line in EMBL. For the new EMBL files we need + # both the version suffix from the ID line and the accession + # from the AC line. + if version_id.count(".") == 1 and version_id.split(".")[1].isdigit(): + self.accession(version_id.split(".")[0]) + self.version_suffix(version_id.split(".")[1]) + elif version_id: + # For backwards compatibility... + self.data.id = version_id + + def project(self, content): + """Handle the information from the PROJECT line as a list of projects. + + e.g.:: + + PROJECT GenomeProject:28471 + + or:: + + PROJECT GenomeProject:13543 GenomeProject:99999 + + This is stored as dbxrefs in the SeqRecord to be consistent with the + projected switch of this line to DBLINK in future GenBank versions. + Note the NCBI plan to replace "GenomeProject:28471" with the shorter + "Project:28471" as part of this transition. + """ + content = content.replace("GenomeProject:", "Project:") + self.data.dbxrefs.extend(p for p in content.split() if p) + + def dblink(self, content): + """Store DBLINK cross references as dbxrefs in our record object. + + This line type is expected to replace the PROJECT line in 2009. e.g. + + During transition:: + + PROJECT GenomeProject:28471 + DBLINK Project:28471 + Trace Assembly Archive:123456 + + Once the project line is dropped:: + + DBLINK Project:28471 + Trace Assembly Archive:123456 + + Note GenomeProject -> Project. + + We'll have to see some real examples to be sure, but based on the + above example we can expect one reference per line. + + Note that at some point the NCBI have included an extra space, e.g.:: + + DBLINK Project: 28471 + + """ + # During the transition period with both PROJECT and DBLINK lines, + # we don't want to add the same cross reference twice. + while ": " in content: + content = content.replace(": ", ":") + if content.strip() not in self.data.dbxrefs: + self.data.dbxrefs.append(content.strip()) + + def version_suffix(self, version): + """Set the version to overwrite the id. + + Since the version provides the same information as the accession + number, plus some extra info, we set this as the id if we have + a version. + """ + # e.g. GenBank line: + # VERSION U49845.1 GI:1293613 + # or the obsolete EMBL line: + # SV U49845.1 + # Scanner calls consumer.version("U49845.1") + # which then calls consumer.version_suffix(1) + # + # e.g. EMBL new line: + # ID X56734; SV 1; linear; mRNA; STD; PLN; 1859 BP. + # Scanner calls consumer.version_suffix(1) + assert version.isdigit() + self.data.annotations["sequence_version"] = int(version) + + def db_source(self, content): + self.data.annotations["db_source"] = content.rstrip() + + def gi(self, content): + self.data.annotations["gi"] = content + + def keywords(self, content): + if "keywords" in self.data.annotations: + # Multi-line keywords, append to list + # Note EMBL states "A keyword is never split between lines." + self.data.annotations["keywords"].extend(self._split_keywords(content)) + else: + self.data.annotations["keywords"] = self._split_keywords(content) + + def segment(self, content): + self.data.annotations["segment"] = content + + def source(self, content): + # Note that some software (e.g. VectorNTI) may produce an empty + # source (rather than using a dot/period as might be expected). + if content == "": + source_info = "" + elif content[-1] == ".": + source_info = content[:-1] + else: + source_info = content + self.data.annotations["source"] = source_info + + def organism(self, content): + self.data.annotations["organism"] = content + + def taxonomy(self, content): + """Record (another line of) the taxonomy lineage.""" + lineage = self._split_taxonomy(content) + try: + self.data.annotations["taxonomy"].extend(lineage) + except KeyError: + self.data.annotations["taxonomy"] = lineage + + def reference_num(self, content): + """Signal the beginning of a new reference object.""" + # if we have a current reference that hasn't been added to + # the list of references, add it. + if self._cur_reference is not None: + self.data.annotations["references"].append(self._cur_reference) + else: + self.data.annotations["references"] = [] + + self._cur_reference = Reference() + + def reference_bases(self, content): + """Attempt to determine the sequence region the reference entails. + + Possible types of information we may have to deal with: + + (bases 1 to 86436) + (sites) + (bases 1 to 105654; 110423 to 111122) + 1 (residues 1 to 182) + """ + # first remove the parentheses + assert content.endswith(")"), content + ref_base_info = content[1:-1] + + all_locations = [] + # parse if we've got 'bases' and 'to' + if "bases" in ref_base_info and "to" in ref_base_info: + # get rid of the beginning 'bases' + ref_base_info = ref_base_info[5:] + locations = self._split_reference_locations(ref_base_info) + all_locations.extend(locations) + elif "residues" in ref_base_info and "to" in ref_base_info: + residues_start = ref_base_info.find("residues") + # get only the information after "residues" + ref_base_info = ref_base_info[(residues_start + len("residues ")) :] + locations = self._split_reference_locations(ref_base_info) + all_locations.extend(locations) + + # make sure if we are not finding information then we have + # the string 'sites' or the string 'bases' + elif ref_base_info == "sites" or ref_base_info.strip() == "bases": + pass + # otherwise raise an error + else: + raise ValueError( + f"Could not parse base info {ref_base_info} in record {self.data.id}" + ) + + self._cur_reference.location = all_locations + + def _split_reference_locations(self, location_string): + """Get reference locations out of a string of reference information (PRIVATE). + + The passed string should be of the form:: + + 1 to 20; 20 to 100 + + This splits the information out and returns a list of location objects + based on the reference locations. + """ + # split possibly multiple locations using the ';' + all_base_info = location_string.split(";") + + new_locations = [] + for base_info in all_base_info: + start, end = base_info.split("to") + new_start, new_end = self._convert_to_python_numbers( + int(start.strip()), int(end.strip()) + ) + this_location = SimpleLocation(new_start, new_end) + new_locations.append(this_location) + return new_locations + + def authors(self, content): + if self._cur_reference.authors: + self._cur_reference.authors += " " + content + else: + self._cur_reference.authors = content + + def consrtm(self, content): + if self._cur_reference.consrtm: + self._cur_reference.consrtm += " " + content + else: + self._cur_reference.consrtm = content + + def title(self, content): + if self._cur_reference is None: + warnings.warn( + "GenBank TITLE line without REFERENCE line.", BiopythonParserWarning + ) + elif self._cur_reference.title: + self._cur_reference.title += " " + content + else: + self._cur_reference.title = content + + def journal(self, content): + if self._cur_reference.journal: + self._cur_reference.journal += " " + content + else: + self._cur_reference.journal = content + + def medline_id(self, content): + self._cur_reference.medline_id = content + + def pubmed_id(self, content): + self._cur_reference.pubmed_id = content + + def remark(self, content): + """Deal with a reference comment.""" + if self._cur_reference.comment: + self._cur_reference.comment += " " + content + else: + self._cur_reference.comment = content + + def comment(self, content): + try: + self.data.annotations["comment"] += "\n" + "\n".join(content) + except KeyError: + self.data.annotations["comment"] = "\n".join(content) + + def structured_comment(self, content): + self.data.annotations["structured_comment"] = content + + def features_line(self, content): + """Get ready for the feature table when we reach the FEATURE line.""" + self.start_feature_table() + + def start_feature_table(self): + """Indicate we've got to the start of the feature table.""" + # make sure we've added on our last reference object + if self._cur_reference is not None: + self.data.annotations["references"].append(self._cur_reference) + self._cur_reference = None + + def feature_key(self, content): + # start a new feature + self._cur_feature = SeqFeature() + self._cur_feature.type = content + self.data.features.append(self._cur_feature) + + def location(self, content): + """Parse out location information from the location string. + + This uses simple Python code with some regular expressions to do the + parsing, and then translates the results into appropriate objects. + """ + # clean up newlines and other whitespace inside the location before + # parsing - locations should have no whitespace whatsoever + location_line = self._clean_location(content) + + # Older records have junk like replace(266,"c") in the + # location line. Newer records just replace this with + # the number 266 and have the information in a more reasonable + # place. So we'll just grab out the number and feed this to the + # parser. We shouldn't really be losing any info this way. + if "replace" in location_line: + comma_pos = location_line.find(",") + location_line = location_line[8:comma_pos] + + length = self._expected_size + # Check if the sequence is circular for features that span the origin + is_circular = "circular" in self.data.annotations.get("topology", "").lower() + stranded = "PROTEIN" not in self._seq_type.upper() + + try: + location = Location.fromstring(location_line, length, is_circular, stranded) + except LocationParserError as e: + warnings.warn( + f"{e}; setting feature location to None.", BiopythonParserWarning + ) + location = None + self._cur_feature.location = location + + def feature_qualifier(self, key, value): + """When we get a qualifier key and its value. + + Can receive None, since you can have valueless keys such as /pseudo + """ + # Hack to try to preserve historical behaviour of /pseudo etc + if value is None: + # if the key doesn't exist yet, add an empty string + if key not in self._cur_feature.qualifiers: + self._cur_feature.qualifiers[key] = [""] + return + # otherwise just skip this key + return + + # Remove enclosing quotation marks + if len(value) > 1 and value[0] == '"' and value[-1] == '"': + value = value[1:-1] + + # Handle NCBI escaping + # Warn if escaping is not according to standard + if re.search(r'[^"]"[^"]|^"[^"]|[^"]"$', value): + warnings.warn( + 'The NCBI states double-quote characters like " should be escaped as "" ' + "(two double - quotes), but here it was not: %r" % value, + BiopythonParserWarning, + ) + # Undo escaping, repeated double quotes -> one double quote + value = value.replace('""', '"') + + if self._feature_cleaner is not None: + value = self._feature_cleaner.clean_value(key, value) + + # if the qualifier name exists, append the value + if key in self._cur_feature.qualifiers: + self._cur_feature.qualifiers[key].append(value) + # otherwise start a new list of the key with its values + else: + self._cur_feature.qualifiers[key] = [value] + + def feature_qualifier_name(self, content_list): + """Use feature_qualifier instead (OBSOLETE).""" + raise NotImplementedError("Use the feature_qualifier method instead.") + + def feature_qualifier_description(self, content): + """Use feature_qualifier instead (OBSOLETE).""" + raise NotImplementedError("Use the feature_qualifier method instead.") + + def contig_location(self, content): + """Deal with CONTIG information.""" + # Historically this was stored as a SeqFeature object, but it was + # stored under record.annotations["contig"] and not under + # record.features with the other SeqFeature objects. + # + # The CONTIG location line can include additional tokens like + # Gap(), Gap(100) or Gap(unk100) which are not used in the feature + # location lines, so storing it using SeqFeature based location + # objects is difficult. + # + # We now store this a string, which means for BioSQL we are now in + # much better agreement with how BioPerl records the CONTIG line + # in the database. + # + # NOTE - This code assumes the scanner will return all the CONTIG + # lines already combined into one long string! + self.data.annotations["contig"] = content + + def origin_name(self, content): + pass + + def base_count(self, content): + pass + + def base_number(self, content): + pass + + def sequence(self, content): + """Add up sequence information as we get it. + + To try and make things speedier, this puts all of the strings + into a list of strings, and then uses string.join later to put + them together. Supposedly, this is a big time savings + """ + assert " " not in content + self._seq_data.append(content.upper()) + + def record_end(self, content): + """Clean up when we've finished the record.""" + # Try and append the version number to the accession for the full id + if not self.data.id: + if "accessions" in self.data.annotations: + raise ValueError( + "Problem adding version number to accession: " + + str(self.data.annotations["accessions"]) + ) + self.data.id = self.data.name # Good fall back? + elif self.data.id.count(".") == 0: + try: + self.data.id += ".%i" % self.data.annotations["sequence_version"] + except KeyError: + pass + + # add the sequence information + + sequence = "".join(self._seq_data) + + if ( + self._expected_size is not None + and len(sequence) != 0 + and self._expected_size != len(sequence) + ): + warnings.warn( + "Expected sequence length %i, found %i (%s)." + % (self._expected_size, len(sequence), self.data.id), + BiopythonParserWarning, + ) + + molecule_type = None + if self._seq_type: + # mRNA is really also DNA, since it is actually cDNA + if "DNA" in self._seq_type.upper() or "MRNA" in self._seq_type.upper(): + molecule_type = "DNA" + # are there ever really RNA sequences in GenBank? + elif "RNA" in self._seq_type.upper(): + # Even for data which was from RNA, the sequence string + # is usually given as DNA (T not U). Bug 3010 + molecule_type = "RNA" + elif ( + "PROTEIN" in self._seq_type.upper() or self._seq_type == "PRT" + ): # PRT is used in EMBL-bank for patents + molecule_type = "protein" + # work around ugly GenBank records which have circular or + # linear but no indication of sequence type + elif self._seq_type in ["circular", "linear", "unspecified"]: + pass + # we have a bug if we get here + else: + raise ValueError( + f"Could not determine molecule_type for seq_type {self._seq_type}" + ) + # Don't overwrite molecule_type + if molecule_type is not None: + self.data.annotations["molecule_type"] = self.data.annotations.get( + "molecule_type", molecule_type + ) + if not sequence and self._expected_size: + self.data.seq = Seq(None, length=self._expected_size) + else: + self.data.seq = Seq(sequence) + + +class _RecordConsumer(_BaseGenBankConsumer): + """Create a GenBank Record object from scanner generated information (PRIVATE).""" + + def __init__(self): + _BaseGenBankConsumer.__init__(self) + from . import Record + + self.data = Record.Record() + + self._seq_data = [] + self._cur_reference = None + self._cur_feature = None + self._cur_qualifier = None + + def tls(self, content): + self.data.tls = content.split("-") + + def tsa(self, content): + self.data.tsa = content.split("-") + + def wgs(self, content): + self.data.wgs = content.split("-") + + def add_wgs_scafld(self, content): + self.data.wgs_scafld.append(content.split("-")) + + def locus(self, content): + self.data.locus = content + + def size(self, content): + self.data.size = content + + def residue_type(self, content): + # Be lenient about parsing, but technically lowercase residue types are malformed. + if "dna" in content or "rna" in content: + warnings.warn( + f"Invalid seq_type ({content}): DNA/RNA should be uppercase.", + BiopythonParserWarning, + ) + self.data.residue_type = content + + def data_file_division(self, content): + self.data.data_file_division = content + + def date(self, content): + self.data.date = content + + def definition(self, content): + self.data.definition = content + + def accession(self, content): + for acc in self._split_accessions(content): + if acc not in self.data.accession: + self.data.accession.append(acc) + + def molecule_type(self, mol_type): + """Validate and record the molecule type (for round-trip etc).""" + if mol_type: + if "circular" in mol_type or "linear" in mol_type: + raise ParserFailureError( + f"Molecule type {mol_type!r} should not include topology" + ) + + # Writing out records will fail if we have a lower case DNA + # or RNA string in here, so upper case it. + # This is a bit ugly, but we don't want to upper case e.g. + # the m in mRNA, but thanks to the strip we lost the spaces + # so we need to index from the back + if mol_type[-3:].upper() in ("DNA", "RNA") and not mol_type[-3:].isupper(): + warnings.warn( + f"Non-upper case molecule type in LOCUS line: {mol_type}", + BiopythonParserWarning, + ) + + self.data.molecule_type = mol_type + + def topology(self, topology): + """Validate and record sequence topology. + + The topology argument should be "linear" or "circular" (string). + """ + if topology: + if topology not in ["linear", "circular"]: + raise ParserFailureError( + f"Unexpected topology {topology!r} should be linear or circular" + ) + self.data.topology = topology + + def nid(self, content): + self.data.nid = content + + def pid(self, content): + self.data.pid = content + + def version(self, content): + self.data.version = content + + def db_source(self, content): + self.data.db_source = content.rstrip() + + def gi(self, content): + self.data.gi = content + + def keywords(self, content): + self.data.keywords = self._split_keywords(content) + + def project(self, content): + self.data.projects.extend(p for p in content.split() if p) + + def dblink(self, content): + self.data.dblinks.append(content) + + def segment(self, content): + self.data.segment = content + + def source(self, content): + self.data.source = content + + def organism(self, content): + self.data.organism = content + + def taxonomy(self, content): + self.data.taxonomy = self._split_taxonomy(content) + + def reference_num(self, content): + """Grab the reference number and signal the start of a new reference.""" + # check if we have a reference to add + if self._cur_reference is not None: + self.data.references.append(self._cur_reference) + + from . import Record + + self._cur_reference = Record.Reference() + self._cur_reference.number = content + + def reference_bases(self, content): + self._cur_reference.bases = content + + def authors(self, content): + self._cur_reference.authors = content + + def consrtm(self, content): + self._cur_reference.consrtm = content + + def title(self, content): + if self._cur_reference is None: + warnings.warn( + "GenBank TITLE line without REFERENCE line.", BiopythonParserWarning + ) + return + self._cur_reference.title = content + + def journal(self, content): + self._cur_reference.journal = content + + def medline_id(self, content): + self._cur_reference.medline_id = content + + def pubmed_id(self, content): + self._cur_reference.pubmed_id = content + + def remark(self, content): + self._cur_reference.remark = content + + def comment(self, content): + self.data.comment += "\n".join(content) + + def structured_comment(self, content): + self.data.structured_comment = content + + def primary_ref_line(self, content): + """Save reference data for the PRIMARY line.""" + self.data.primary.append(content) + + def primary(self, content): + pass + + def features_line(self, content): + """Get ready for the feature table when we reach the FEATURE line.""" + self.start_feature_table() + + def start_feature_table(self): + """Signal the start of the feature table.""" + # we need to add on the last reference + if self._cur_reference is not None: + self.data.references.append(self._cur_reference) + + def feature_key(self, content): + """Grab the key of the feature and signal the start of a new feature.""" + # first add on feature information if we've got any + self._add_feature() + + from . import Record + + self._cur_feature = Record.Feature() + self._cur_feature.key = content + + def _add_feature(self): + """Add a feature to the record, with relevant checks (PRIVATE). + + This does all of the appropriate checking to make sure we haven't + left any info behind, and that we are only adding info if it + exists. + """ + if self._cur_feature is not None: + # if we have a left over qualifier, add it to the qualifiers + # on the current feature + if self._cur_qualifier is not None: + self._cur_feature.qualifiers.append(self._cur_qualifier) + + self._cur_qualifier = None + self.data.features.append(self._cur_feature) + + def location(self, content): + self._cur_feature.location = self._clean_location(content) + + def feature_qualifier(self, key, value): + self.feature_qualifier_name([key]) + if value is not None: + self.feature_qualifier_description(value) + + def feature_qualifier_name(self, content_list): + """Deal with qualifier names. + + We receive a list of keys, since you can have valueless keys such as + /pseudo which would be passed in with the next key (since no other + tags separate them in the file) + """ + from . import Record + + for content in content_list: + # the record parser keeps the /s -- add them if we don't have 'em + if not content.startswith("/"): + content = f"/{content}" + # add on a qualifier if we've got one + if self._cur_qualifier is not None: + self._cur_feature.qualifiers.append(self._cur_qualifier) + + self._cur_qualifier = Record.Qualifier() + self._cur_qualifier.key = content + + def feature_qualifier_description(self, content): + # if we have info then the qualifier key should have a ='s + if "=" not in self._cur_qualifier.key: + self._cur_qualifier.key = f"{self._cur_qualifier.key}=" + cur_content = self._remove_newlines(content) + # remove all spaces from the value if it is a type where spaces + # are not important + for remove_space_key in self.__class__.remove_space_keys: + if remove_space_key in self._cur_qualifier.key: + cur_content = self._remove_spaces(cur_content) + self._cur_qualifier.value = self._normalize_spaces(cur_content) + + def base_count(self, content): + self.data.base_counts = content + + def origin_name(self, content): + self.data.origin = content + + def contig_location(self, content): + """Signal that we have contig information to add to the record.""" + self.data.contig = self._clean_location(content) + + def sequence(self, content): + """Add sequence information to a list of sequence strings. + + This removes spaces in the data and uppercases the sequence, and + then adds it to a list of sequences. Later on we'll join this + list together to make the final sequence. This is faster than + adding on the new string every time. + """ + assert " " not in content + self._seq_data.append(content.upper()) + + def record_end(self, content): + """Signal the end of the record and do any necessary clean-up.""" + # add together all of the sequence parts to create the + # final sequence string + self.data.sequence = "".join(self._seq_data) + # add on the last feature + self._add_feature() + + +def parse(handle): + """Iterate over GenBank formatted entries as Record objects. + + >>> from Bio import GenBank + >>> with open("GenBank/NC_000932.gb") as handle: + ... for record in GenBank.parse(handle): + ... print(record.accession) + ['NC_000932'] + + To get SeqRecord objects use Bio.SeqIO.parse(..., format="gb") + instead. + """ + return iter(Iterator(handle, RecordParser())) + + +def read(handle): + """Read a handle containing a single GenBank entry as a Record object. + + >>> from Bio import GenBank + >>> with open("GenBank/NC_000932.gb") as handle: + ... record = GenBank.read(handle) + ... print(record.accession) + ['NC_000932'] + + To get a SeqRecord object use Bio.SeqIO.read(..., format="gb") + instead. + """ + iterator = parse(handle) + try: + record = next(iterator) + except StopIteration: + raise ValueError("No records found in handle") from None + try: + next(iterator) + raise ValueError("More than one record found in handle") + except StopIteration: + pass + return record + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/utils.py b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..60c91f8715a812687325a1e1f0d6e81b0fefb007 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/GenBank/utils.py @@ -0,0 +1,66 @@ +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +# + +"""Useful utilities for helping in parsing GenBank files.""" + + +class FeatureValueCleaner: + r"""Provide specialized capabilities for cleaning up values in features. + + This class is designed to provide a mechanism to clean up and process + values in the key/value pairs of GenBank features. This is useful + because in cases like:: + + /translation="MED + YDPWNLRFQSKYKSRDA" + + you'll otherwise end up with white space in it. + + This cleaning needs to be done on a case by case basis since it is + impossible to interpret whether you should be concatenating everything + (as in translations), or combining things with spaces (as might be + the case with /notes). + + >>> cleaner = FeatureValueCleaner(["translation"]) + >>> cleaner + FeatureValueCleaner(['translation']) + >>> cleaner.clean_value("translation", "MED\nYDPWNLRFQSKYKSRDA") + 'MEDYDPWNLRFQSKYKSRDA' + """ + + keys_to_process = ["translation"] + + def __init__(self, to_process=keys_to_process): + """Initialize with the keys we should deal with.""" + self._to_process = to_process + + def __repr__(self): + """Return a string representation of the class.""" + return f"{self.__class__.__name__}({self._to_process!r})" + + def clean_value(self, key_name, value): + """Clean the specified value and return it. + + If the value is not specified to be dealt with, the original value + will be returned. + """ + if key_name in self._to_process: + try: + cleaner = getattr(self, f"_clean_{key_name}") + except AttributeError: + raise AssertionError(f"No function to clean key: {key_name}") from None + value = cleaner(value) + return value + + def _clean_translation(self, value): + """Concatenate a translation value to one long protein string (PRIVATE).""" + translation_parts = value.split() + return "".join(translation_parts) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/Record.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/Record.py new file mode 100644 index 0000000000000000000000000000000000000000..037ef2c089ff9cab08ccef17c60ab355a9ab37b8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/Record.py @@ -0,0 +1,90 @@ +# Copyright 2001 by Katharine Lindner. All rights reserved. +# Copyright 2006 by PeterC. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +"""Hold GEO data in a straightforward format. + +classes: +o Record - All of the information in an GEO record. + +See http://www.ncbi.nlm.nih.gov/geo/ +""" + + +class Record: + """Hold GEO information in a format similar to the original record. + + The Record class is meant to make data easy to get to when you are + just interested in looking at GEO data. + + Attributes: + entity_type + entity_id + entity_attributes + col_defs + table_rows + + """ + + def __init__(self): + """Initialize the class.""" + self.entity_type = "" + self.entity_id = "" + self.entity_attributes = {} + self.col_defs = {} + self.table_rows = [] + + def __str__(self): + """Return the GEO record as a string.""" + output = "" + output += f"GEO Type: {self.entity_type}\n" + output += f"GEO Id: {self.entity_id}\n" + att_keys = sorted(self.entity_attributes) + for key in att_keys: + contents = self.entity_attributes[key] + if isinstance(contents, list): + for item in contents: + try: + output += f"{key}: {item[:40]}\n" + output += out_block(item[40:]) + except Exception: # TODO: IndexError? + pass + elif isinstance(contents, str): + output += f"{key}: {contents[:40]}\n" + output += out_block(contents[40:]) + else: + raise RuntimeError(f"unexpected contents of type {type(contents)}") + col_keys = sorted(self.col_defs) + output += "Column Header Definitions\n" + for key in col_keys: + val = self.col_defs[key] + output += f" {key}: {val[:40]}\n" + output += out_block(val[40:], " ") + # May have to display VERY large tables, + # so only show the first 20 lines of data + MAX_ROWS = 20 + 1 # include header in count + for row in self.table_rows[0:MAX_ROWS]: + output += f"{self.table_rows.index(row)}: " + for col in row: + output += f"{col}\t" + output += "\n" + if len(self.table_rows) > MAX_ROWS: + output += "...\n" + row = self.table_rows[-1] + output += f"{self.table_rows.index(row)}: " + for col in row: + output += f"{col}\t" + output += "\n" + + return output + + +def out_block(text, prefix=""): + """Format text in blocks of 80 chars with an additional optional prefix.""" + output = "" + for j in range(0, len(text), 80): + output += f"{prefix}{text[j : j + 80]}\n" + output += "\n" + return output diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6735e9afb7878c2b8ce2aab6e1eca9b09ad53eb1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/__init__.py @@ -0,0 +1,67 @@ +# Copyright 2001 by Katharine Lindner. All rights reserved. +# Copyright 2006 by PeterC. All rights reserved. +# Copyright 2007 by Michiel de Hoon. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. +"""Parser for files from NCBI's Gene Expression Omnibus (GEO). + +http://www.ncbi.nlm.nih.gov/geo/ +""" + +from . import Record + + +def _read_key_value(line): + words = line[1:].split("=", 1) + try: + key, value = words + value = value.strip() + except ValueError: + key = words[0] + value = "" + key = key.strip() + return key, value + + +def parse(handle): + """Read Gene Expression Omnibus records from file handle. + + Returns a generator object which yields Bio.Geo.Record() objects. + """ + record = None + for line in handle: + line = line.strip("\n").strip("\r") + if not line: + continue # Ignore empty lines + c = line[0] + if c == "^": + if record: + yield record + record = Record.Record() + record.entity_type, record.entity_id = _read_key_value(line) + elif c == "!": + if line in ( + "!Sample_table_begin", + "!Sample_table_end", + "!Platform_table_begin", + "!Platform_table_end", + ): + continue + key, value = _read_key_value(line) + if key in record.entity_attributes: + if isinstance(record.entity_attributes[key], list): + record.entity_attributes[key].append(value) + else: + existing = record.entity_attributes[key] + record.entity_attributes[key] = [existing, value] + else: + record.entity_attributes[key] = value + elif c == "#": + key, value = _read_key_value(line) + assert key not in record.col_defs + record.col_defs[key] = value + else: + row = line.split("\t") + record.table_rows.append(row) + yield record diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/__pycache__/Record.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/__pycache__/Record.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2658cd46e9059eff8c37cf18e7ac7b518d3d6156 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/__pycache__/Record.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f505e0fc088d0b931c2ba47905914d7fd395e3a Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Geo/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/BasicChromosome.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/BasicChromosome.py new file mode 100644 index 0000000000000000000000000000000000000000..c54d7cba2e9504c734f194b9cc97cc8253f385c7 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/BasicChromosome.py @@ -0,0 +1,819 @@ +# Copyright 2001, 2003 by Brad Chapman. All rights reserved. +# Revisions copyright 2011 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Draw representations of organism chromosomes with added information. + +These classes are meant to model the drawing of pictures of chromosomes. +This can be useful for lots of things, including displaying markers on +a chromosome (ie. for genetic mapping) and showing syteny between two +chromosomes. + +The structure of these classes is intended to be a Composite, so that +it will be easy to plug in and switch different parts without +breaking the general drawing capabilities of the system. The +relationship between classes is that everything derives from +_ChromosomeComponent, which specifies the overall interface. The parts +then are related so that an Organism contains Chromosomes, and these +Chromosomes contain ChromosomeSegments. This representation differs +from the canonical composite structure in that we don't really have +'leaf' nodes here -- all components can potentially hold sub-components. + +Most of the time the ChromosomeSegment class is what you'll want to +customize for specific drawing tasks. + +For providing drawing capabilities, these classes use reportlab: + +http://www.reportlab.com + +This provides nice output in PDF, SVG and postscript. If you have +reportlab's renderPM module installed you can also use PNG etc. +""" + +from reportlab.graphics.shapes import ArcPath +from reportlab.graphics.shapes import Drawing +from reportlab.graphics.shapes import Line +from reportlab.graphics.shapes import Rect +from reportlab.graphics.shapes import String +from reportlab.graphics.shapes import Wedge +from reportlab.graphics.widgetbase import Widget +from reportlab.lib import colors +from reportlab.lib.pagesizes import letter +from reportlab.lib.units import inch +from reportlab.pdfbase.pdfmetrics import stringWidth + +from Bio.Graphics import _write +from Bio.Graphics.GenomeDiagram import _Colors + +_color_trans = _Colors.ColorTranslator() + + +class _ChromosomeComponent(Widget): + """Base class specifying the interface for a component of the system. + + This class should not be instantiated directly, but should be used + from derived classes. + """ + + def __init__(self): + """Initialize a chromosome component. + + Attributes: + - _sub_components -- Any components which are contained under + this parent component. This attribute should be accessed through + the add() and remove() functions. + + """ + self._sub_components = [] + + def add(self, component): + """Add a sub_component to the list of components under this item.""" + if not isinstance(component, _ChromosomeComponent): + raise TypeError(f"Expected a _ChromosomeComponent object, got {component}") + + self._sub_components.append(component) + + def remove(self, component): + """Remove the specified component from the subcomponents. + + Raises a ValueError if the component is not registered as a + sub_component. + """ + try: + self._sub_components.remove(component) + except ValueError: + raise ValueError( + f"Component {component} not found in sub_components." + ) from None + + def draw(self): + """Draw the specified component.""" + raise AssertionError("Subclasses must implement.") + + +class Organism(_ChromosomeComponent): + """Top level class for drawing chromosomes. + + This class holds information about an organism and all of its + chromosomes, and provides the top level object which could be used + for drawing a chromosome representation of an organism. + + Chromosomes should be added and removed from the Organism via the + add and remove functions. + """ + + def __init__(self, output_format="pdf"): + """Initialize the class.""" + _ChromosomeComponent.__init__(self) + + # customizable attributes + self.page_size = letter + self.title_size = 20 + + # Do we need this given we don't draw a legend? + # If so, should be a public API... + self._legend_height = 0 # 2 * inch + + self.output_format = output_format + + def draw(self, output_file, title): + """Draw out the information for the Organism. + + Arguments: + - output_file -- The name of a file specifying where the + document should be saved, or a handle to be written to. + The output format is set when creating the Organism object. + Alternatively, output_file=None will return the drawing using + the low-level ReportLab objects (for further processing, such + as adding additional graphics, before writing). + - title -- The output title of the produced document. + + """ + width, height = self.page_size + cur_drawing = Drawing(width, height) + + self._draw_title(cur_drawing, title, width, height) + + cur_x_pos = inch * 0.5 + if len(self._sub_components) > 0: + x_pos_change = (width - inch) / len(self._sub_components) + # no sub_components + else: + pass + + for sub_component in self._sub_components: + # set the drawing location of the chromosome + sub_component.start_x_position = cur_x_pos + 0.05 * x_pos_change + sub_component.end_x_position = cur_x_pos + 0.95 * x_pos_change + sub_component.start_y_position = height - 1.5 * inch + sub_component.end_y_position = self._legend_height + 1 * inch + + # do the drawing + sub_component.draw(cur_drawing) + + # update the locations for the next chromosome + cur_x_pos += x_pos_change + + self._draw_legend(cur_drawing, self._legend_height + 0.5 * inch, width) + + if output_file is None: + # Let the user take care of writing to the file... + return cur_drawing + + return _write(cur_drawing, output_file, self.output_format) + + def _draw_title(self, cur_drawing, title, width, height): + """Write out the title of the organism figure (PRIVATE).""" + title_string = String(width / 2, height - inch, title) + title_string.fontName = "Helvetica-Bold" + title_string.fontSize = self.title_size + title_string.textAnchor = "middle" + + cur_drawing.add(title_string) + + def _draw_legend(self, cur_drawing, start_y, width): + """Draw a legend for the figure (PRIVATE). + + Subclasses should implement this (see also self._legend_height) to + provide specialized legends. + """ + + +class Chromosome(_ChromosomeComponent): + """Class for drawing a chromosome of an organism. + + This organizes the drawing of a single organisms chromosome. This + class can be instantiated directly, but the draw method makes the + most sense to be called in the context of an organism. + """ + + def __init__(self, chromosome_name): + """Initialize a Chromosome for drawing. + + Arguments: + - chromosome_name - The label for the chromosome. + + Attributes: + - start_x_position, end_x_position - The x positions on the page + where the chromosome should be drawn. This allows multiple + chromosomes to be drawn on a single page. + - start_y_position, end_y_position - The y positions on the page + where the chromosome should be contained. + + Configuration Attributes: + - title_size - The size of the chromosome title. + - scale_num - A number of scale the drawing by. This is useful if + you want to draw multiple chromosomes of different sizes at the + same scale. If this is not set, then the chromosome drawing will + be scaled by the number of segments in the chromosome (so each + chromosome will be the exact same final size). + + """ + _ChromosomeComponent.__init__(self) + + self._name = chromosome_name + + self.start_x_position = -1 + self.end_x_position = -1 + self.start_y_position = -1 + self.end_y_position = -1 + + self.title_size = 20 + self.scale_num = None + + self.label_size = 6 + self.chr_percent = 0.25 + self.label_sep_percent = self.chr_percent * 0.5 + self._color_labels = False + + def subcomponent_size(self): + """Return the scaled size of all subcomponents of this component.""" + total_sub = 0 + for sub_component in self._sub_components: + total_sub += sub_component.scale + + return total_sub + + def draw(self, cur_drawing): + """Draw a chromosome on the specified template. + + Ideally, the x_position and y_*_position attributes should be + set prior to drawing -- otherwise we're going to have some problems. + """ + for position in ( + self.start_x_position, + self.end_x_position, + self.start_y_position, + self.end_y_position, + ): + assert position != -1, "Need to set drawing coordinates." + + # first draw all of the sub-sections of the chromosome -- this + # will actually be the picture of the chromosome + cur_y_pos = self.start_y_position + if self.scale_num: + y_pos_change = ( + self.start_y_position * 0.95 - self.end_y_position + ) / self.scale_num + elif len(self._sub_components) > 0: + y_pos_change = ( + self.start_y_position * 0.95 - self.end_y_position + ) / self.subcomponent_size() + # no sub_components to draw + else: + pass + + left_labels = [] + right_labels = [] + for sub_component in self._sub_components: + this_y_pos_change = sub_component.scale * y_pos_change + + # set the location of the component to draw + sub_component.start_x_position = self.start_x_position + sub_component.end_x_position = self.end_x_position + sub_component.start_y_position = cur_y_pos + sub_component.end_y_position = cur_y_pos - this_y_pos_change + + # draw the sub component + sub_component._left_labels = [] + sub_component._right_labels = [] + sub_component.draw(cur_drawing) + left_labels += sub_component._left_labels + right_labels += sub_component._right_labels + + # update the position for the next component + cur_y_pos -= this_y_pos_change + + self._draw_labels(cur_drawing, left_labels, right_labels) + self._draw_label(cur_drawing, self._name) + + def _draw_label(self, cur_drawing, label_name): + """Draw a label for the chromosome (PRIVATE).""" + x_position = 0.5 * (self.start_x_position + self.end_x_position) + y_position = self.end_y_position + + label_string = String(x_position, y_position, label_name) + label_string.fontName = "Times-BoldItalic" + label_string.fontSize = self.title_size + label_string.textAnchor = "middle" + + cur_drawing.add(label_string) + + def _draw_labels(self, cur_drawing, left_labels, right_labels): + """Layout and draw sub-feature labels for the chromosome (PRIVATE). + + Tries to place each label at the same vertical position as the + feature it applies to, but will adjust the positions to avoid or + at least reduce label overlap. + + Draws the label text and a coloured line linking it to the + location (i.e. feature) it applies to. + """ + if not self._sub_components: + return + color_label = self._color_labels + + segment_width = (self.end_x_position - self.start_x_position) * self.chr_percent + label_sep = ( + self.end_x_position - self.start_x_position + ) * self.label_sep_percent + segment_x = self.start_x_position + 0.5 * ( + self.end_x_position - self.start_x_position - segment_width + ) + + y_limits = [ + limit + for sub_component in self._sub_components + for limit in (sub_component.start_y_position, sub_component.end_y_position) + ] + y_min = min(y_limits) + y_max = max(y_limits) + del y_limits + # Now do some label placement magic... + # from reportlab.pdfbase import pdfmetrics + # font = pdfmetrics.getFont('Helvetica') + # h = (font.face.ascent + font.face.descent) * 0.90 + h = self.label_size + for x1, x2, labels, anchor in [ + ( + segment_x, + segment_x - label_sep, + _place_labels(left_labels, y_min, y_max, h), + "end", + ), + ( + segment_x + segment_width, + segment_x + segment_width + label_sep, + _place_labels(right_labels, y_min, y_max, h), + "start", + ), + ]: + for y1, y2, color, back_color, name in labels: + cur_drawing.add( + Line(x1, y1, x2, y2, strokeColor=color, strokeWidth=0.25) + ) + label_string = String(x2, y2, name, textAnchor=anchor) + label_string.fontName = "Helvetica" + label_string.fontSize = h + if color_label: + label_string.fillColor = color + if back_color: + w = stringWidth(name, label_string.fontName, label_string.fontSize) + if x1 > x2: + w = w * -1.0 + cur_drawing.add( + Rect( + x2, + y2 - 0.1 * h, + w, + h, + strokeColor=back_color, + fillColor=back_color, + ) + ) + cur_drawing.add(label_string) + + +class ChromosomeSegment(_ChromosomeComponent): + """Draw a segment of a chromosome. + + This class provides the important configurable functionality of drawing + a Chromosome. Each segment has some customization available here, or can + be subclassed to define additional functionality. Most of the interesting + drawing stuff is likely to happen at the ChromosomeSegment level. + """ + + def __init__(self): + """Initialize a ChromosomeSegment. + + Attributes: + - start_x_position, end_x_position - Defines the x range we have + to draw things in. + - start_y_position, end_y_position - Defines the y range we have + to draw things in. + + Configuration Attributes: + - scale - A scaling value for the component. By default this is + set at 1 (ie -- has the same scale as everything else). Higher + values give more size to the component, smaller values give less. + - fill_color - A color to fill in the segment with. Colors are + available in reportlab.lib.colors + - label - A label to place on the chromosome segment. This should + be a text string specifying what is to be included in the label. + - label_size - The size of the label. + - chr_percent - The percentage of area that the chromosome + segment takes up. + + """ + _ChromosomeComponent.__init__(self) + + self.start_x_position = -1 + self.end_x_position = -1 + self.start_y_position = -1 + self.end_y_position = -1 + + # --- attributes for configuration + self.scale = 1 + self.fill_color = None + self.label = None + self.label_size = 6 + self.chr_percent = 0.25 + + def draw(self, cur_drawing): + """Draw a chromosome segment. + + Before drawing, the range we are drawing in needs to be set. + """ + for position in ( + self.start_x_position, + self.end_x_position, + self.start_y_position, + self.end_y_position, + ): + assert position != -1, "Need to set drawing coordinates." + + self._draw_subcomponents(cur_drawing) # Anything behind + self._draw_segment(cur_drawing) + self._overdraw_subcomponents(cur_drawing) # Anything on top + self._draw_label(cur_drawing) + + def _draw_subcomponents(self, cur_drawing): + """Draw any subcomponents of the chromosome segment (PRIVATE). + + This should be overridden in derived classes if there are + subcomponents to be drawn. + """ + + def _draw_segment(self, cur_drawing): + """Draw the current chromosome segment (PRIVATE).""" + # set the coordinates of the segment -- it'll take up the MIDDLE part + # of the space we have. + segment_y = self.end_y_position + segment_width = (self.end_x_position - self.start_x_position) * self.chr_percent + segment_height = self.start_y_position - self.end_y_position + segment_x = self.start_x_position + 0.5 * ( + self.end_x_position - self.start_x_position - segment_width + ) + + # first draw the sides of the segment + right_line = Line(segment_x, segment_y, segment_x, segment_y + segment_height) + left_line = Line( + segment_x + segment_width, + segment_y, + segment_x + segment_width, + segment_y + segment_height, + ) + + cur_drawing.add(right_line) + cur_drawing.add(left_line) + + # now draw the box, if it is filled in + if self.fill_color is not None: + fill_rectangle = Rect(segment_x, segment_y, segment_width, segment_height) + fill_rectangle.fillColor = self.fill_color + fill_rectangle.strokeColor = None + + cur_drawing.add(fill_rectangle) + + def _overdraw_subcomponents(self, cur_drawing): + """Draw any subcomponents of the chromosome segment over the main part (PRIVATE). + + This should be overridden in derived classes if there are + subcomponents to be drawn. + """ + + def _draw_label(self, cur_drawing): + """Add a label to the chromosome segment (PRIVATE). + + The label will be applied to the right of the segment. + + This may be overlapped by any sub-feature labels on other segments! + """ + if self.label is not None: + label_x = 0.5 * (self.start_x_position + self.end_x_position) + ( + self.chr_percent + 0.05 + ) * (self.end_x_position - self.start_x_position) + label_y = ( + self.start_y_position - self.end_y_position + ) / 2 + self.end_y_position + + label_string = String(label_x, label_y, self.label) + label_string.fontName = "Helvetica" + label_string.fontSize = self.label_size + + cur_drawing.add(label_string) + + +def _spring_layout(desired, minimum, maximum, gap=0): + """Try to layout label coordinates or other floats (PRIVATE). + + Originally written for the y-axis vertical positioning of labels on a + chromosome diagram (where the minimum gap between y-axis coordinates is + the label height), it could also potentially be used for x-axis placement, + or indeed radial placement for circular chromosomes within GenomeDiagram. + + In essence this is an optimisation problem, balancing the desire to have + each label as close as possible to its data point, but also to spread out + the labels to avoid overlaps. This could be described with a cost function + (modelling the label distance from the desired placement, and the inter- + label separations as springs) and solved as a multi-variable minimization + problem - perhaps with NumPy or SciPy. + + For now however, the implementation is a somewhat crude ad hoc algorithm. + + NOTE - This expects the input data to have been sorted! + """ + count = len(desired) + if count <= 1: + return desired # Easy! + if minimum >= maximum: + raise ValueError(f"Bad min/max {minimum:f} and {maximum:f}") + if min(desired) < minimum or max(desired) > maximum: + raise ValueError( + "Data %f to %f out of bounds (%f to %f)" + % (min(desired), max(desired), minimum, maximum) + ) + equal_step = (maximum - minimum) / (count - 1) + + if equal_step < gap: + import warnings + + from Bio import BiopythonWarning + + warnings.warn("Too many labels to avoid overlap", BiopythonWarning) + # Crudest solution + return [minimum + i * equal_step for i in range(count)] + + good = True + if gap: + prev = desired[0] + for next in desired[1:]: + if prev - next < gap: + good = False + break + if good: + return desired + + span = maximum - minimum + for split in [0.5 * span, span / 3.0, 2 * span / 3.0, 0.25 * span, 0.75 * span]: + midpoint = minimum + split + low = [x for x in desired if x <= midpoint - 0.5 * gap] + high = [x for x in desired if x > midpoint + 0.5 * gap] + if len(low) + len(high) < count: + # Bad split point, points right on boundary + continue + elif not low and len(high) * gap <= (span - split) + 0.5 * gap: + # Give a little of the unused low space to the high points + return _spring_layout(high, midpoint + 0.5 * gap, maximum, gap) + elif not high and len(low) * gap <= split + 0.5 * gap: + # Give a little of the unused highspace to the low points + return _spring_layout(low, minimum, midpoint - 0.5 * gap, gap) + elif ( + len(low) * gap <= split - 0.5 * gap + and len(high) * gap <= (span - split) - 0.5 * gap + ): + return _spring_layout( + low, minimum, midpoint - 0.5 * gap, gap + ) + _spring_layout(high, midpoint + 0.5 * gap, maximum, gap) + + # This can be count-productive now we can split out into the telomere or + # spacer-segment's vertical space... + # Try not to spread out as far as the min/max unless needed + low = min(desired) + high = max(desired) + if (high - low) / (count - 1) >= gap: + # Good, we don't need the full range, and can position the + # min and max exactly as well :) + equal_step = (high - low) / (count - 1) + return [low + i * equal_step for i in range(count)] + + low = 0.5 * (minimum + min(desired)) + high = 0.5 * (max(desired) + maximum) + if (high - low) / (count - 1) >= gap: + # Good, we don't need the full range + equal_step = (high - low) / (count - 1) + return [low + i * equal_step for i in range(count)] + + # Crudest solution + return [minimum + i * equal_step for i in range(count)] + + +# assert False, _spring_layout([0.10,0.12,0.13,0.14,0.5,0.75, 1.0], 0, 1, 0.1) +# assert _spring_layout([0.10,0.12,0.13,0.14,0.5,0.75, 1.0], 0, 1, 0.1) == \ +# [0.0, 0.125, 0.25, 0.375, 0.5, 0.75, 1.0] +# assert _spring_layout([0.10,0.12,0.13,0.14,0.5,0.75, 1.0], 0, 1, 0.1) == \ +# [0.0, 0.16666666666666666, 0.33333333333333331, 0.5, +# 0.66666666666666663, 0.83333333333333326, 1.0] + + +def _place_labels(desired_etc, minimum, maximum, gap=0): + # Want a list of lists/tuples for desired_etc + desired_etc.sort() + placed = _spring_layout([row[0] for row in desired_etc], minimum, maximum, gap) + for old, y2 in zip(desired_etc, placed): + # (y1, a, b, c, ..., z) --> (y1, y2, a, b, c, ..., z) + yield (old[0], y2) + tuple(old[1:]) + + +class AnnotatedChromosomeSegment(ChromosomeSegment): + """Annotated chromosome segment. + + This is like the ChromosomeSegment, but accepts a list of features. + """ + + def __init__( + self, + bp_length, + features, + default_feature_color=colors.blue, + name_qualifiers=("gene", "label", "name", "locus_tag", "product"), + ): + """Initialize. + + The features can either be SeqFeature objects, or tuples of values: + start (int), end (int), strand (+1, -1, O or None), label (string), + ReportLab color (string or object), and optional ReportLab fill color. + + Note we require 0 <= start <= end <= bp_length, and within the vertical + space allocated to this segment lines will be places according to the + start/end coordinates (starting from the top). + + Positive stand features are drawn on the right, negative on the left, + otherwise all the way across. + + We recommend using consistent units for all the segment's scale values + (e.g. their length in base pairs). + + When providing features as SeqFeature objects, the default color + is used, unless the feature's qualifiers include an Artemis colour + string (functionality also in GenomeDiagram). The caption also follows + the GenomeDiagram approach and takes the first qualifier from the list + or tuple specified in name_qualifiers. + + Note additional attribute label_sep_percent controls the percentage of + area that the chromosome segment takes up, by default half of the + chr_percent attribute (half of 25%, thus 12.5%) + + """ + ChromosomeSegment.__init__(self) + self.bp_length = bp_length + self.features = features + self.default_feature_color = default_feature_color + self.name_qualifiers = name_qualifiers + self.label_sep_percent = self.chr_percent * 0.5 + + def _overdraw_subcomponents(self, cur_drawing): + """Draw any annotated features on the chromosome segment (PRIVATE). + + Assumes _draw_segment already called to fill out the basic shape, + and assmes that uses the same boundaries. + """ + # set the coordinates of the segment -- it'll take up the MIDDLE part + # of the space we have. + segment_y = self.end_y_position + segment_width = (self.end_x_position - self.start_x_position) * self.chr_percent + label_sep = ( + self.end_x_position - self.start_x_position + ) * self.label_sep_percent + segment_height = self.start_y_position - self.end_y_position + segment_x = self.start_x_position + 0.5 * ( + self.end_x_position - self.start_x_position - segment_width + ) + + left_labels = [] + right_labels = [] + for f in self.features: + try: + # Assume SeqFeature objects + start = f.location.start + end = f.location.end + strand = f.location.strand + try: + # Handles Artemis colour integers, HTML colors, etc + color = _color_trans.translate(f.qualifiers["color"][0]) + except Exception: # TODO: ValueError? + color = self.default_feature_color + fill_color = color + name = "" + for qualifier in self.name_qualifiers: + if qualifier in f.qualifiers: + name = f.qualifiers[qualifier][0] + break + except AttributeError: + # Assume tuple of ints, string, and color + start, end, strand, name, color = f[:5] + color = _color_trans.translate(color) + if len(f) > 5: + fill_color = _color_trans.translate(f[5]) + else: + fill_color = color + assert 0 <= start <= end <= self.bp_length + if strand == +1: + # Right side only + x = segment_x + segment_width * 0.6 + w = segment_width * 0.4 + elif strand == -1: + # Left side only + x = segment_x + w = segment_width * 0.4 + else: + # Both or neither - full width + x = segment_x + w = segment_width + local_scale = segment_height / self.bp_length + fill_rectangle = Rect( + x, + segment_y + segment_height - local_scale * start, + w, + local_scale * (start - end), + ) + fill_rectangle.fillColor = fill_color + fill_rectangle.strokeColor = color + cur_drawing.add(fill_rectangle) + if name: + if fill_color == color: + back_color = None + else: + back_color = fill_color + value = ( + segment_y + segment_height - local_scale * start, + color, + back_color, + name, + ) + if strand == -1: + self._left_labels.append(value) + else: + self._right_labels.append(value) + + +class TelomereSegment(ChromosomeSegment): + """A segment that is located at the end of a linear chromosome. + + This is just like a regular segment, but it draws the end of a chromosome + which is represented by a half circle. This just overrides the + _draw_segment class of ChromosomeSegment to provide that specialized + drawing. + """ + + def __init__(self, inverted=0): + """Initialize a segment at the end of a chromosome. + + See ChromosomeSegment for all of the attributes that can be + customized in a TelomereSegments. + + Arguments: + - inverted -- Whether or not the telomere should be inverted + (ie. drawn on the bottom of a chromosome) + + """ + ChromosomeSegment.__init__(self) + + self._inverted = inverted + + def _draw_segment(self, cur_drawing): + """Draw a half circle representing the end of a linear chromosome (PRIVATE).""" + # set the coordinates of the segment -- it'll take up the MIDDLE part + # of the space we have. + width = (self.end_x_position - self.start_x_position) * self.chr_percent + height = self.start_y_position - self.end_y_position + center_x = 0.5 * (self.end_x_position + self.start_x_position) + start_x = center_x - 0.5 * width + if self._inverted: + center_y = self.start_y_position + start_angle = 180 + end_angle = 360 + else: + center_y = self.end_y_position + start_angle = 0 + end_angle = 180 + + cap_wedge = Wedge(center_x, center_y, width / 2, start_angle, end_angle, height) + cap_wedge.strokeColor = None + cap_wedge.fillColor = self.fill_color + cur_drawing.add(cap_wedge) + + # Now draw an arc for the curved edge of the wedge, + # omitting the flat end. + cap_arc = ArcPath() + cap_arc.addArc(center_x, center_y, width / 2, start_angle, end_angle, height) + cur_drawing.add(cap_arc) + + +class SpacerSegment(ChromosomeSegment): + """A segment that is located at the end of a linear chromosome. + + Doesn't draw anything, just empty space which can be helpful + for layout purposes (e.g. making room for feature labels). + """ + + def draw(self, cur_diagram): + """Draw nothing to the current diagram (dummy method). + + The segment spacer has no actual image in the diagram, + so this method therefore does nothing, but is defined + to match the expected API of the other segment objects. + """ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/ColorSpiral.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/ColorSpiral.py new file mode 100644 index 0000000000000000000000000000000000000000..1186fb7877c23fe3dc09bc2dd0cb77ad2b799b92 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/ColorSpiral.py @@ -0,0 +1,205 @@ +# Copyright 2012 by Leighton Pritchard. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Generate RGB colours suitable for distinguishing categorical data. + +This module provides a class that implements a spiral 'path' through HSV +colour space, permitting the selection of a number of points along that path, +and returning the output in RGB colour space, suitable for use with ReportLab +and other graphics packages. + +This approach to colour choice was inspired by Bang Wong's Points of View +article: Color Coding, in Nature Methods _7_ 573 (https://doi.org/10.1038/nmeth0810-573). + +The module also provides helper functions that return a list for colours, or +a dictionary of colours (if passed an iterable containing the names of +categories to be coloured). +""" + +import colorsys # colour format conversions +import random # for jitter values +from math import exp +from math import floor +from math import log +from math import pi + + +class ColorSpiral: + """Implement a spiral path through HSV colour space. + + This class provides functions for sampling points along a logarithmic + spiral path through HSV colour space. + + The spiral is described by r = a * exp(b * t) where r is the distance + from the axis of the HSV cylinder to the current point in the spiral, + and t is the angle through which the spiral has turned to reach the + current point. a and b are (positive, real) parameters that control the + shape of the spiral. + + - a: the starting direction of the spiral + - b: the number of revolutions about the axis made by the spiral + + We permit the spiral to move along the cylinder ('in V-space') between + v_init and v_final, to give a gradation in V (essentially, brightness), + along the path, where v_init, v_final are in [0,1]. + + A brightness 'jitter' may also be provided as an absolute value in + V-space, to aid in distinguishing consecutive colour points on the + path. + """ + + def __init__(self, a=1, b=0.33, v_init=0.85, v_final=0.5, jitter=0.05): + """Initialize a logarithmic spiral path through HSV colour space. + + Arguments: + - a - Parameter a for the spiral, controls the initial spiral + direction. a > 0 + - b - parameter b for the spiral, controls the rate at which the + spiral revolves around the axis. b > 0 + - v_init - initial value of V (brightness) for the spiral. + v_init in [0,1] + - v_final - final value of V (brightness) for the spiral + v_final in [0,1] + - jitter - the degree of V (brightness) jitter to add to each + selected colour. The amount of jitter will be selected + from a uniform random distribution [-jitter, jitter], + and V will be maintained in [0,1]. + + """ + # Initialize attributes + self.a = a + self.b = b + self.v_init = v_init + self.v_final = v_final + self.jitter = jitter + + def get_colors(self, k, offset=0.1): + """Generate k different RBG colours evenly-space on the spiral. + + A generator returning the RGB colour space values for k + evenly-spaced points along the defined spiral in HSV space. + + Arguments: + - k - the number of points to return + - offset - how far along the spiral path to start. + + """ + # We use the offset to skip a number of similar colours near to HSV axis + assert offset > 0 and offset < 1, "offset must be in (0,1)" + v_rate = (self._v_final - self._v_init) / k + # Generator for colours: we have divided the arc length into sections + # of equal length, and step along them + for n in range(1, k + 1): + # For each value of n, t indicates the angle through which the + # spiral has turned, to this point + t = (1.0 / self._b) * ( + log(n + (k * offset)) - log((1 + offset) * k * self._a) + ) + # Put 0 <= h <= 2*pi, where h is the angular part of the polar + # coordinates for this point on the spiral + h = t + while h < 0: + h += 2 * pi + h = h - (floor(h / (2 * pi)) * pi) + # Now put h in [0, 1] for colorsys conversion + h = h / (2 * pi) + # r is the radial distance of this point from the centre + r = self._a * exp(self._b * t) + # v is the brightness of this point, linearly interpolated + # from self._v_init to self._v_final. Jitter size is sampled from + # a uniform distribution + if self._jitter: + jitter = random.random() * 2 * self._jitter - self._jitter + else: + jitter = 0 + v = self._v_init + (n * v_rate + jitter) + # We have arranged the arithmetic such that 0 <= r <= 1, so + # we can use this value directly as s in HSV + yield colorsys.hsv_to_rgb(h, r, max(0, min(v, 1))) + + def _get_a(self): + return self._a + + def _set_a(self, value): + self._a = max(0, value) + + def _get_b(self): + return self._b + + def _set_b(self, value): + self._b = max(0, value) + + def _get_v_init(self): + return self._v_init + + def _set_v_init(self, value): + self._v_init = max(0, min(1, value)) + + def _get_v_final(self): + return self._v_final + + def _set_v_final(self, value): + self._v_final = max(0, min(1, value)) + + def _get_jitter(self): + return self._jitter + + def _set_jitter(self, value): + self._jitter = max(0, min(1, value)) + + a = property( + _get_a, _set_a, doc="Parameter controlling initial spiral direction (a > 0)" + ) + b = property( + _get_b, + _set_b, + doc="Parameter controlling rate spiral revolves around axis (b > 0)", + ) + v_init = property( + _get_v_init, + _set_v_init, + doc="Initial value of V (brightness) for the spiral (range 0 to 1)", + ) + v_final = property( + _get_v_final, + _set_v_final, + doc="Final value of V (brightness) for the spiral (range 0 to 1)", + ) + jitter = property( + _get_jitter, + _set_jitter, + doc="Degree of V (brightness) jitter to add to each color (range 0 to 1)", + ) + + +# Convenience functions for those who don't want to bother with a +# ColorSpiral object +def get_colors(k, **kwargs): + """Return k colours selected by the ColorSpiral object, as a generator. + + Arguments: + - k - the number of colours to return + - kwargs - pass-through arguments to the ColorSpiral object + + """ + cs = ColorSpiral(**kwargs) + return cs.get_colors(k) + + +def get_color_dict(l, **kwargs): # noqa: E741 + """Return a dictionary of colours using the provided values as keys. + + Returns a dictionary, keyed by the members of iterable l, with a + colour assigned to each member. + + Arguments: + - l - an iterable representing classes to be coloured + - kwargs - pass-through arguments to the ColorSpiral object + + """ + cs = ColorSpiral(**kwargs) + colors = cs.get_colors(len(l)) + return dict(zip(l, colors)) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/Comparative.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/Comparative.py new file mode 100644 index 0000000000000000000000000000000000000000..22dccaa8ff250544d88c3078b8894496180dbfa4 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/Comparative.py @@ -0,0 +1,181 @@ +# Copyright 2001 by Brad Chapman. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Plots to compare information between different sources. + +This file contains high level plots which are designed to be used to +compare different types of information. The most basic example is comparing +two variables in a traditional scatter plot. +""" + +from reportlab.graphics.charts.lineplots import LinePlot +from reportlab.graphics.charts.markers import makeEmptyCircle +from reportlab.graphics.charts.markers import makeEmptySquare +from reportlab.graphics.charts.markers import makeFilledCircle +from reportlab.graphics.charts.markers import makeFilledDiamond +from reportlab.graphics.charts.markers import makeFilledSquare +from reportlab.graphics.charts.markers import makeSmiley +from reportlab.graphics.shapes import Drawing +from reportlab.graphics.shapes import String +from reportlab.lib import colors +from reportlab.lib.pagesizes import letter +from reportlab.lib.units import inch + +from Bio.Graphics import _write + + +class ComparativeScatterPlot: + """Display a scatter-type plot comparing two different kinds of info. + + Attributes; + - display_info - a 2D list of the information we'll be outputting. Each + top level list is a different data type, and each data point is a + two-tuple of the coordinates of a point. + + So if you had two distributions of points, it should look like:: + + display_info = [[(1, 2), (3, 4)], + [(5, 6), (7, 8)]] + + If everything is just one set of points, display_info can look like:: + + display_info = [[(1, 2), (3, 4), (5, 6)]] + + """ + + def __init__(self, output_format="pdf"): + """Initialize the class.""" + # customizable attributes + self.number_of_columns = 1 + self.page_size = letter + self.title_size = 20 + + self.output_format = output_format + + # the information we'll be writing + self.display_info = [] + + # initial colors and shapes used for drawing points + self.color_choices = [ + colors.red, + colors.green, + colors.blue, + colors.yellow, + colors.orange, + colors.black, + ] + self.shape_choices = [ + makeFilledCircle, + makeEmptySquare, + makeFilledDiamond, + makeFilledSquare, + makeEmptyCircle, + makeSmiley, + ] + + def draw_to_file(self, output_file, title): + """Write the comparative plot to a file. + + Arguments: + - output_file - The name of the file to output the information to, + or a handle to write to. + - title - A title to display on the graphic. + + """ + width, height = self.page_size + cur_drawing = Drawing(width, height) + + self._draw_title(cur_drawing, title, width, height) + + start_x = inch * 0.5 + end_x = width - inch * 0.5 + end_y = height - 1.5 * inch + start_y = 0.5 * inch + self._draw_scatter_plot(cur_drawing, start_x, start_y, end_x, end_y) + + return _write(cur_drawing, output_file, self.output_format) + + def _draw_title(self, cur_drawing, title, width, height): + """Add a title to the page we are outputting (PRIVATE).""" + title_string = String(width / 2, height - inch, title) + title_string.fontName = "Helvetica-Bold" + title_string.fontSize = self.title_size + title_string.textAnchor = "middle" + + cur_drawing.add(title_string) + + def _draw_scatter_plot(self, cur_drawing, x_start, y_start, x_end, y_end): + """Draw a scatter plot on the drawing with the given coordinates (PRIVATE).""" + scatter_plot = LinePlot() + + # set the dimensions of the scatter plot + scatter_plot.x = x_start + scatter_plot.y = y_start + scatter_plot.width = abs(x_start - x_end) + scatter_plot.height = abs(y_start - y_end) + + scatter_plot.data = self.display_info + + scatter_plot.joinedLines = 0 + + # set the axes of the plot + x_min, x_max, y_min, y_max = self._find_min_max(self.display_info) + scatter_plot.xValueAxis.valueMin = x_min + scatter_plot.xValueAxis.valueMax = x_max + scatter_plot.xValueAxis.valueStep = (x_max - x_min) / 10.0 + + scatter_plot.yValueAxis.valueMin = y_min + scatter_plot.yValueAxis.valueMax = y_max + scatter_plot.yValueAxis.valueStep = (y_max - y_min) / 10.0 + + self._set_colors_and_shapes(scatter_plot, self.display_info) + + cur_drawing.add(scatter_plot) + + def _set_colors_and_shapes(self, scatter_plot, display_info): + """Set the colors and shapes of the points displayed (PRIVATE). + + By default this just sets all of the points according to the order + of colors and shapes defined in self.color_choices and + self.shape_choices. The first 5 shapes and colors are unique, the + rest of them are just set to the same color and shape (since I + ran out of shapes!). + + You can change how this function works by either changing the + values of the color_choices and shape_choices attributes, or + by inheriting from this class and overriding this function. + """ + for value_num in range(len(display_info)): + # if we have unique colors, add them + if (value_num + 1) < len(self.color_choices): + scatter_plot.lines[value_num].strokeColor = self.color_choices[ + value_num + ] + scatter_plot.lines[value_num].symbol = self.shape_choices[value_num] + # otherwise just use the last number + else: + scatter_plot.lines[value_num].strokeColor = self.color_choices[-1] + scatter_plot.lines[value_num].symbol = self.shape_choices[-1] + + def _find_min_max(self, info): + """Find min and max for x and y coordinates in the given data (PRIVATE).""" + x_min = info[0][0][0] + x_max = info[0][0][0] + y_min = info[0][0][1] + y_max = info[0][0][1] + + for two_d_list in info: + for x, y in two_d_list: + if x > x_max: + x_max = x + if x < x_min: + x_min = x + if y > y_max: + y_max = y + if y < y_min: + y_min = y + + return x_min, x_max, y_min, y_max diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/DisplayRepresentation.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/DisplayRepresentation.py new file mode 100644 index 0000000000000000000000000000000000000000..8135ebb8b240ba7479f34b937a1d5f688930fafd --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/DisplayRepresentation.py @@ -0,0 +1,183 @@ +# Copyright 2001 by Brad Chapman. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Represent information for graphical display. + +Classes in this module are designed to hold information in a way that +makes it easy to draw graphical figures. +""" + +from reportlab.lib import colors + +from Bio.Graphics.BasicChromosome import ChromosomeSegment +from Bio.Graphics.BasicChromosome import TelomereSegment + +# --- constants +# This is a default color scheme based on the light spectrum. +# Based on my vague recollections from biology, this is our friend ROY G. BIV +RAINBOW_COLORS = { + (1, 1): colors.violet, + (2, 2): colors.indigo, + (3, 3): colors.blue, + (4, 4): colors.green, + (5, 5): colors.yellow, + (6, 6): colors.orange, + (7, 20): colors.red, +} + + +class ChromosomeCounts: + """Represent a chromosome with count information. + + This is used to display information about counts along a chromosome. + The segments are expected to have different count information, which + will be displayed using a color scheme. + + I envision using this class when you think that certain regions of + the chromosome will be especially abundant in the counts, and you + want to pick those out. + """ + + def __init__(self, segment_names, color_scheme=RAINBOW_COLORS): + """Initialize a representation of chromosome counts. + + Arguments: + - segment_names - An ordered list of all segment names along + the chromosome. The count and other information will be added + to these. + - color_scheme - A coloring scheme to use in the counts. This + should be a dictionary mapping count ranges to colors (specified + in reportlab.lib.colors). + + """ + self._names = segment_names + self._count_info = {} + self._label_info = {} + self._scale_info = {} + for name in self._names: + self._count_info[name] = 0 + self._label_info[name] = None + self._scale_info[name] = 1 + + self._color_scheme = color_scheme + + def add_count(self, segment_name, count=1): + """Add counts to the given segment name. + + Arguments: + - segment_name - The name of the segment we should add counts to. + If the name is not present, a KeyError will be raised. + - count - The counts to add the current segment. This defaults to + a single count. + + """ + try: + self._count_info[segment_name] += count + except KeyError: + raise KeyError(f"Segment name {segment_name} not found.") from None + + def scale_segment_value(self, segment_name, scale_value=None): + """Divide the counts for a segment by some kind of scale value. + + This is useful if segments aren't represented by raw counts, but + are instead counts divided by some number. + """ + try: + self._count_info[segment_name] /= scale_value + except KeyError: + raise KeyError(f"Segment name {segment_name} not found.") from None + + def add_label(self, segment_name, label): + """Add a label to a specific segment. + + Raises a KeyError is the specified segment name is not found. + """ + if segment_name in self._label_info: + self._label_info[segment_name] = label + else: + raise KeyError(f"Segment name {segment_name} not found.") + + def set_scale(self, segment_name, scale): + """Set the scale for a specific chromosome segment. + + By default all segments have the same scale -- this allows scaling + by the size of the segment. + + Raises a KeyError is the specified segment name is not found. + """ + if segment_name in self._label_info: + self._scale_info[segment_name] = scale + else: + raise KeyError(f"Segment name {segment_name} not found.") + + def get_segment_info(self): + """Retrieve the color and label info about the segments. + + Returns a list consisting of two tuples specifying the counts and + label name for each segment. The list is ordered according to the + original listing of names. Labels are set as None if no label + was specified. + """ + order_info = [] + + for seg_name in self._names: + order_info.append((self._count_info[seg_name], self._label_info[seg_name])) + + return order_info + + def fill_chromosome(self, chromosome): + """Add the collected segment information to a chromosome for drawing. + + Arguments: + - chromosome - A Chromosome graphics object that we can add + chromosome segments to. + + This creates ChromosomeSegment (and TelomereSegment) objects to + fill in the chromosome. The information is derived from the + label and count information, with counts transformed to the + specified color map. + + Returns the chromosome with all of the segments added. + """ + for seg_num in range(len(self._names)): + is_end_segment = 0 + # make the top and bottom telomeres + if seg_num == 0: + cur_segment = TelomereSegment() + is_end_segment = 1 + elif seg_num == len(self._names) - 1: + cur_segment = TelomereSegment(1) + is_end_segment = 1 + # otherwise, they are just regular segments + else: + cur_segment = ChromosomeSegment() + + seg_name = self._names[seg_num] + if self._count_info[seg_name] > 0: + color = self._color_from_count(self._count_info[seg_name]) + cur_segment.fill_color = color + + if self._label_info[seg_name] is not None: + cur_segment.label = self._label_info[seg_name] + + # give end segments extra size so they look right + if is_end_segment: + cur_segment.scale = 3 + else: + cur_segment.scale = self._scale_info[seg_name] + + chromosome.add(cur_segment) + + return chromosome + + def _color_from_count(self, count): + """Translate the given count into a color using the color scheme (PRIVATE).""" + for count_start, count_end in self._color_scheme: + if count >= count_start and count <= count_end: + return self._color_scheme[(count_start, count_end)] + + # if we got here we didn't find a color for the count + raise ValueError(f"Count value {count} was not found in the color scheme.") diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/Distribution.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/Distribution.py new file mode 100644 index 0000000000000000000000000000000000000000..70842ce6dbb60ea24841c6b0a0198c5c295d4c7d --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/Distribution.py @@ -0,0 +1,252 @@ +# Copyright 2001 by Brad Chapman. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Display information distributed across a Chromosome-like object. + +These classes are meant to show the distribution of some kind of information +as it changes across any kind of segment. It was designed with chromosome +distributions in mind, but could also work for chromosome regions, BAC clones +or anything similar. + +Reportlab is used for producing the graphical output. +""" + +import math + +from reportlab.graphics.charts.barcharts import BarChartProperties +from reportlab.graphics.charts.barcharts import VerticalBarChart +from reportlab.graphics.shapes import Drawing +from reportlab.graphics.shapes import String +from reportlab.graphics.widgetbase import TypedPropertyCollection +from reportlab.lib import colors +from reportlab.lib.pagesizes import letter +from reportlab.lib.units import inch + +from Bio.Graphics import _write + + +class DistributionPage: + """Display a grouping of distributions on a page. + + This organizes Distributions, and will display them nicely + on a single page. + """ + + def __init__(self, output_format="pdf"): + """Initialize the class.""" + self.distributions = [] + + # customizable attributes + self.number_of_columns = 1 + self.page_size = letter + self.title_size = 20 + + self.output_format = output_format + + def draw(self, output_file, title): + """Draw out the distribution information. + + Arguments: + - output_file - The name of the file to output the information to, + or a handle to write to. + - title - A title to display on the graphic. + + """ + width, height = self.page_size + cur_drawing = Drawing(width, height) + + self._draw_title(cur_drawing, title, width, height) + + # calculate the x and y position changes for each distribution + cur_x_pos = inch * 0.5 + end_x_pos = width - inch * 0.5 + cur_y_pos = height - 1.5 * inch + end_y_pos = 0.5 * inch + x_pos_change = (end_x_pos - cur_x_pos) / self.number_of_columns + num_y_rows = math.ceil(len(self.distributions) / self.number_of_columns) + y_pos_change = (cur_y_pos - end_y_pos) / num_y_rows + + self._draw_distributions( + cur_drawing, cur_x_pos, x_pos_change, cur_y_pos, y_pos_change, num_y_rows + ) + self._draw_legend(cur_drawing, 2.5 * inch, width) + + return _write(cur_drawing, output_file, self.output_format) + + def _draw_title(self, cur_drawing, title, width, height): + """Add the title of the figure to the drawing (PRIVATE).""" + title_string = String(width / 2, height - inch, title) + title_string.fontName = "Helvetica-Bold" + title_string.fontSize = self.title_size + title_string.textAnchor = "middle" + + cur_drawing.add(title_string) + + def _draw_distributions( + self, + cur_drawing, + start_x_pos, + x_pos_change, + start_y_pos, + y_pos_change, + num_y_drawings, + ): + """Draw all of the distributions on the page (PRIVATE). + + Arguments: + - cur_drawing - The drawing we are working with. + - start_x_pos - The x position on the page to start drawing at. + - x_pos_change - The change in x position between each figure. + - start_y_pos - The y position on the page to start drawing at. + - y_pos_change - The change in y position between each figure. + - num_y_drawings - The number of drawings we'll have in the y + (up/down) direction. + + """ + for y_drawing in range(int(num_y_drawings)): + # if we are on the last y position, we may not be able + # to fill all of the x columns + if (y_drawing + 1) * self.number_of_columns > len(self.distributions): + num_x_drawings = ( + len(self.distributions) - y_drawing * self.number_of_columns + ) + else: + num_x_drawings = self.number_of_columns + for x_drawing in range(num_x_drawings): + dist_num = y_drawing * self.number_of_columns + x_drawing + cur_distribution = self.distributions[dist_num] + + # find the x and y boundaries of the distribution + x_pos = start_x_pos + x_drawing * x_pos_change + end_x_pos = x_pos + x_pos_change + end_y_pos = start_y_pos - y_drawing * y_pos_change + y_pos = end_y_pos - y_pos_change + + # draw the distribution + cur_distribution.draw(cur_drawing, x_pos, y_pos, end_x_pos, end_y_pos) + + def _draw_legend(self, cur_drawing, start_y, width): + """Add a legend to the figure (PRIVATE). + + Subclasses can implement to provide a specialized legend. + """ + + +class BarChartDistribution: + """Display the distribution of values as a bunch of bars.""" + + def __init__(self, display_info=None): + """Initialize a Bar Chart display of distribution info. + + Attributes: + - display_info - the information to be displayed in the distribution. + This should be ordered as a list of lists, where each internal list + is a data set to display in the bar chart. + + """ + if display_info is None: + display_info = [] + self.display_info = display_info + + self.x_axis_title = "" + self.y_axis_title = "" + self.chart_title = "" + self.chart_title_size = 10 + + self.padding_percent = 0.15 + + def draw(self, cur_drawing, start_x, start_y, end_x, end_y): + """Draw a bar chart with the info in the specified range.""" + bar_chart = VerticalBarChart() + if self.chart_title: + self._draw_title( + cur_drawing, self.chart_title, start_x, start_y, end_x, end_y + ) + # set the position of the bar chart + x_start, x_end, y_start, y_end = self._determine_position( + start_x, start_y, end_x, end_y + ) + + bar_chart.x = x_start + bar_chart.y = y_start + bar_chart.width = abs(x_start - x_end) + bar_chart.height = abs(y_start - y_end) + + # set the information in the bar chart + bar_chart.data = self.display_info + bar_chart.valueAxis.valueMin = min(self.display_info[0]) + bar_chart.valueAxis.valueMax = max(self.display_info[0]) + for data_set in self.display_info[1:]: + if min(data_set) < bar_chart.valueAxis.valueMin: + bar_chart.valueAxis.valueMin = min(data_set) + if max(data_set) > bar_chart.valueAxis.valueMax: + bar_chart.valueAxis.valueMax = max(data_set) + + # set other formatting options + if len(self.display_info) == 1: + bar_chart.groupSpacing = 0 + style = TypedPropertyCollection(BarChartProperties) + style.strokeWidth = 0 + style.strokeColor = colors.green + style[0].fillColor = colors.green + + bar_chart.bars = style + + # set the labels + # XXX labels don't work yet + # bar_chart.valueAxis.title = self.x_axis_title + # bar_chart.categoryAxis.title = self.y_axis_title + + cur_drawing.add(bar_chart) + + def _draw_title(self, cur_drawing, title, start_x, start_y, end_x, end_y): + """Add the title of the figure to the drawing (PRIVATE).""" + x_center = start_x + (end_x - start_x) / 2 + y_pos = end_y + (self.padding_percent * (start_y - end_y)) / 2 + title_string = String(x_center, y_pos, title) + title_string.fontName = "Helvetica-Bold" + title_string.fontSize = self.chart_title_size + title_string.textAnchor = "middle" + + cur_drawing.add(title_string) + + def _determine_position(self, start_x, start_y, end_x, end_y): + """Calculate the position of the chart with blank space (PRIVATE). + + This uses some padding around the chart, and takes into account + whether the chart has a title. It returns 4 values, which are, + in order, the x_start, x_end, y_start and y_end of the chart + itself. + """ + x_padding = self.padding_percent * (end_x - start_x) + y_padding = self.padding_percent * (start_y - end_y) + + new_x_start = start_x + x_padding + new_x_end = end_x - x_padding + + if self.chart_title: + new_y_start = start_y - y_padding - self.chart_title_size + else: + new_y_start = start_y - y_padding + + new_y_end = end_y + y_padding + + return new_x_start, new_x_end, new_y_start, new_y_end + + +class LineDistribution: + """Display the distribution of values as connected lines. + + This distribution displays the change in values across the object as + lines. This also allows multiple distributions to be displayed on a + single graph. + """ + + def __init__(self): + """Initialize the class.""" + + def draw(self, cur_drawing, start_x, start_y, end_x, end_y): + """Draw a line distribution into the current drawing.""" diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_AbstractDrawer.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_AbstractDrawer.py new file mode 100644 index 0000000000000000000000000000000000000000..40d14be58def6195df1272e478ce673c24e6cee5 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_AbstractDrawer.py @@ -0,0 +1,565 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# Revisions copyright 2008-2017 by Peter Cock. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""AbstractDrawer module (considered to be a private module, the API may change!). + +Provides: + - AbstractDrawer - Superclass for methods common to the Drawer objects + - page_sizes - Method that returns a ReportLab pagesize when passed + a valid ISO size + - draw_box - Method that returns a closed path object when passed + the proper coordinates. For HORIZONTAL boxes only. + - angle2trig - Method that returns a tuple of values that are the + vector for rotating a point through a passed angle, + about an origin + - intermediate_points - Method that returns a list of values intermediate + between the points in a passed dataset + +For drawing capabilities, this module uses reportlab to draw and write +the diagram: http://www.reportlab.com + +For dealing with biological information, the package expects Biopython objects +like SeqFeatures. +""" + +from itertools import islice +from math import cos +from math import pi +from math import sin + +from reportlab.graphics.shapes import Polygon +from reportlab.lib import colors +from reportlab.lib import pagesizes + +################################################################################ +# METHODS +################################################################################ + + +# Utility method to translate strings to ISO page sizes +def page_sizes(size): + """Convert size string into a Reportlab pagesize. + + Arguments: + - size - A string representing a standard page size, eg 'A4' or 'LETTER' + + """ + sizes = { # ReportLab pagesizes, keyed by ISO string + "A0": pagesizes.A0, + "A1": pagesizes.A1, + "A2": pagesizes.A2, + "A3": pagesizes.A3, + "A4": pagesizes.A4, + "A5": pagesizes.A5, + "A6": pagesizes.A6, + "B0": pagesizes.B0, + "B1": pagesizes.B1, + "B2": pagesizes.B2, + "B3": pagesizes.B3, + "B4": pagesizes.B4, + "B5": pagesizes.B5, + "B6": pagesizes.B6, + "ELEVENSEVENTEEN": pagesizes.ELEVENSEVENTEEN, + "LEGAL": pagesizes.LEGAL, + "LETTER": pagesizes.LETTER, + } + try: + return sizes[size] + except KeyError: + raise ValueError(f"{size} not in list of page sizes") from None + + +def _stroke_and_fill_colors(color, border): + """Deal with border and fill colors (PRIVATE).""" + if not isinstance(color, colors.Color): + raise ValueError(f"Invalid color {color!r}") + + if color == colors.white and border is None: + # Force black border on white boxes with undefined border + strokecolor = colors.black + elif border is None: + strokecolor = color # use fill color + elif border: + if not isinstance(border, colors.Color): + raise ValueError(f"Invalid border color {border!r}") + strokecolor = border + else: + # e.g. False + strokecolor = None + + return strokecolor, color + + +def draw_box( + point1, point2, color=colors.lightgreen, border=None, colour=None, **kwargs +): + """Draw a box. + + Arguments: + - point1, point2 - coordinates for opposite corners of the box + (x,y tuples) + - color /colour - The color for the box (colour takes priority + over color) + - border - Border color for the box + + Returns a closed path object, beginning at (x1,y1) going round + the four points in order, and filling with the passed color. + """ + x1, y1 = point1 + x2, y2 = point2 + + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + del colour + + strokecolor, color = _stroke_and_fill_colors(color, border) + + x1, y1, x2, y2 = min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2) + return Polygon( + [x1, y1, x2, y1, x2, y2, x1, y2], + strokeColor=strokecolor, + fillColor=color, + strokewidth=0, + **kwargs, + ) + + +def draw_cut_corner_box( + point1, point2, corner=0.5, color=colors.lightgreen, border=None, **kwargs +): + """Draw a box with the corners cut off.""" + x1, y1 = point1 + x2, y2 = point2 + + if not corner: + return draw_box(point1, point2, color, border) + elif corner < 0: + raise ValueError("Arrow head length ratio should be positive") + + strokecolor, color = _stroke_and_fill_colors(color, border) + + boxheight = y2 - y1 + boxwidth = x2 - x1 + x_corner = min(boxheight * 0.5 * corner, boxwidth * 0.5) + y_corner = min(boxheight * 0.5 * corner, boxheight * 0.5) + + points = [ + x1, + y1 + y_corner, + x1, + y2 - y_corner, + x1 + x_corner, + y2, + x2 - x_corner, + y2, + x2, + y2 - y_corner, + x2, + y1 + y_corner, + x2 - x_corner, + y1, + x1 + x_corner, + y1, + ] + return Polygon( + deduplicate(points), + strokeColor=strokecolor, + strokeWidth=1, + strokeLineJoin=1, # 1=round + fillColor=color, + **kwargs, + ) + + +def draw_polygon( + list_of_points, color=colors.lightgreen, border=None, colour=None, **kwargs +): + """Draw polygon. + + Arguments: + - list_of_point - list of (x,y) tuples for the corner coordinates + - color / colour - The color for the box + + Returns a closed path object, beginning at (x1,y1) going round + the four points in order, and filling with the passed colour. + + """ + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + del colour + + strokecolor, color = _stroke_and_fill_colors(color, border) + + xy_list = [] + for x, y in list_of_points: + xy_list.append(x) + xy_list.append(y) + + return Polygon( + deduplicate(xy_list), + strokeColor=strokecolor, + fillColor=color, + strokewidth=0, + **kwargs, + ) + + +def draw_arrow( + point1, + point2, + color=colors.lightgreen, + border=None, + shaft_height_ratio=0.4, + head_length_ratio=0.5, + orientation="right", + colour=None, + **kwargs, +): + """Draw an arrow. + + Returns a closed path object representing an arrow enclosed by the + box with corners at {point1=(x1,y1), point2=(x2,y2)}, a shaft height + given by shaft_height_ratio (relative to box height), a head length + given by head_length_ratio (also relative to box height), and + an orientation that may be 'left' or 'right'. + """ + x1, y1 = point1 + x2, y2 = point2 + + if shaft_height_ratio < 0 or 1 < shaft_height_ratio: + raise ValueError("Arrow shaft height ratio should be in range 0 to 1") + if head_length_ratio < 0: + raise ValueError("Arrow head length ratio should be positive") + + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + del colour + + strokecolor, color = _stroke_and_fill_colors(color, border) + + # Depending on the orientation, we define the bottom left (x1, y1) and + # top right (x2, y2) coordinates differently, but still draw the box + # using the same relative coordinates: + xmin, ymin = min(x1, x2), min(y1, y2) + xmax, ymax = max(x1, x2), max(y1, y2) + if orientation == "right": + x1, x2, y1, y2 = xmin, xmax, ymin, ymax + elif orientation == "left": + x1, x2, y1, y2 = xmax, xmin, ymin, ymax + else: + raise ValueError( + f"Invalid orientation {orientation!r}, should be 'left' or 'right'" + ) + + # We define boxheight and boxwidth accordingly, and calculate the shaft + # height from these. We also ensure that the maximum head length is + # the width of the box enclosure + boxheight = y2 - y1 + boxwidth = x2 - x1 + shaftheight = boxheight * shaft_height_ratio + headlength = min(abs(boxheight) * head_length_ratio, abs(boxwidth)) + if boxwidth < 0: + headlength *= -1 # reverse it + + shafttop = 0.5 * (boxheight + shaftheight) + shaftbase = boxheight - shafttop + headbase = boxwidth - headlength + midheight = 0.5 * boxheight + + points = [ + x1, + y1 + shafttop, + x1 + headbase, + y1 + shafttop, + x1 + headbase, + y2, + x2, + y1 + midheight, + x1 + headbase, + y1, + x1 + headbase, + y1 + shaftbase, + x1, + y1 + shaftbase, + ] + + return Polygon( + deduplicate(points), + strokeColor=strokecolor, + # strokeWidth=max(1, int(boxheight/40.)), + strokeWidth=1, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + fillColor=color, + **kwargs, + ) + + +def deduplicate(points): + """Remove adjacent duplicate points. + + This is important for use with the Polygon class since reportlab has a + bug with duplicate points. + + Arguments: + - points - list of points [x1, y1, x2, y2,...] + + Returns a list in the same format with consecutive duplicates removed + """ + assert len(points) % 2 == 0 + if len(points) < 2: + return points + newpoints = points[0:2] + for x, y in zip(islice(points, 2, None, 2), islice(points, 3, None, 2)): + if x != newpoints[-2] or y != newpoints[-1]: + newpoints.append(x) + newpoints.append(y) + return newpoints + + +def angle2trig(theta): + """Convert angle to a reportlab ready tuple. + + Arguments: + - theta - Angle in degrees, counter clockwise from horizontal + + Returns a representation of the passed angle in a format suitable + for ReportLab rotations (i.e. cos(theta), sin(theta), -sin(theta), + cos(theta) tuple) + """ + c = cos(theta * pi / 180) + s = sin(theta * pi / 180) + return (c, s, -s, c) # Vector for rotating point around an origin + + +def intermediate_points(start, end, graph_data): + """Generate intermediate points describing provided graph data.. + + Returns a list of (start, end, value) tuples describing the passed + graph data as 'bins' between position midpoints. + """ + newdata = [] # data in form (X0, X1, val) + # add first block + newdata.append( + ( + start, + graph_data[0][0] + (graph_data[1][0] - graph_data[0][0]) / 2.0, + graph_data[0][1], + ) + ) + # add middle set + for index in range(1, len(graph_data) - 1): + lastxval, lastyval = graph_data[index - 1] + xval, yval = graph_data[index] + nextxval, nextyval = graph_data[index + 1] + newdata.append( + (lastxval + (xval - lastxval) / 2.0, xval + (nextxval - xval) / 2.0, yval) + ) + # add last block + newdata.append((xval + (nextxval - xval) / 2.0, end, graph_data[-1][1])) + return newdata + + +################################################################################ +# CLASSES +################################################################################ + + +class AbstractDrawer: + """Abstract Drawer. + + Attributes: + - tracklines Boolean for whether to draw lines delineating tracks + - pagesize Tuple describing the size of the page in pixels + - x0 Float X co-ord for leftmost point of drawable area + - xlim Float X co-ord for rightmost point of drawable area + - y0 Float Y co-ord for lowest point of drawable area + - ylim Float Y co-ord for topmost point of drawable area + - pagewidth Float pixel width of drawable area + - pageheight Float pixel height of drawable area + - xcenter Float X co-ord of center of drawable area + - ycenter Float Y co-ord of center of drawable area + - start Int, base to start drawing from + - end Int, base to stop drawing at + - length Size of sequence to be drawn + - cross_track_links List of tuples each with four entries (track A, + feature A, track B, feature B) to be linked. + + """ + + def __init__( + self, + parent, + pagesize="A3", + orientation="landscape", + x=0.05, + y=0.05, + xl=None, + xr=None, + yt=None, + yb=None, + start=None, + end=None, + tracklines=0, + cross_track_links=None, + ): + """Create the object. + + Arguments: + - parent Diagram object containing the data that the drawer draws + - pagesize String describing the ISO size of the image, or a tuple + of pixels + - orientation String describing the required orientation of the + final drawing ('landscape' or 'portrait') + - x Float (0->1) describing the relative size of the X + margins to the page + - y Float (0->1) describing the relative size of the Y + margins to the page + - xl Float (0->1) describing the relative size of the left X + margin to the page (overrides x) + - xr Float (0->1) describing the relative size of the right X + margin to the page (overrides x) + - yt Float (0->1) describing the relative size of the top Y + margin to the page (overrides y) + - yb Float (0->1) describing the relative size of the lower Y + margin to the page (overrides y) + - start Int, the position to begin drawing the diagram at + - end Int, the position to stop drawing the diagram at + - tracklines Boolean flag to show (or not) lines delineating tracks + on the diagram + - cross_track_links List of tuples each with four entries (track A, + feature A, track B, feature B) to be linked. + + """ + self._parent = parent # The calling Diagram object + + # Perform 'administrative' tasks of setting up the page + self.set_page_size(pagesize, orientation) # Set drawing size + self.set_margins(x, y, xl, xr, yt, yb) # Set page margins + self.set_bounds(start, end) # Set limits on what will be drawn + self.tracklines = tracklines # Set flags + if cross_track_links is None: + cross_track_links = [] + else: + self.cross_track_links = cross_track_links + + def set_page_size(self, pagesize, orientation): + """Set page size of the drawing.. + + Arguments: + - pagesize Size of the output image, a tuple of pixels (width, + height, or a string in the reportlab.lib.pagesizes + set of ISO sizes. + - orientation String: 'landscape' or 'portrait' + + """ + if isinstance(pagesize, str): # A string, so translate + pagesize = page_sizes(pagesize) + elif isinstance(pagesize, tuple): # A tuple, so don't translate + pass + else: + raise ValueError(f"Page size {pagesize} not recognised") + shortside, longside = min(pagesize), max(pagesize) + + orientation = orientation.lower() + if orientation not in ("landscape", "portrait"): + raise ValueError(f"Orientation {orientation} not recognised") + if orientation == "landscape": + self.pagesize = (longside, shortside) + else: + self.pagesize = (shortside, longside) + + def set_margins(self, x, y, xl, xr, yt, yb): + """Set page margins. + + Arguments: + - x Float(0->1), Absolute X margin as % of page + - y Float(0->1), Absolute Y margin as % of page + - xl Float(0->1), Left X margin as % of page + - xr Float(0->1), Right X margin as % of page + - yt Float(0->1), Top Y margin as % of page + - yb Float(0->1), Bottom Y margin as % of page + + Set the page margins as proportions of the page 0->1, and also + set the page limits x0, y0 and xlim, ylim, and page center + xorigin, yorigin, as well as overall page width and height + """ + # Set left, right, top and bottom margins + xmargin_l = xl or x + xmargin_r = xr or x + ymargin_top = yt or y + ymargin_btm = yb or y + + # Set page limits, center and height/width + self.x0, self.y0 = self.pagesize[0] * xmargin_l, self.pagesize[1] * ymargin_btm + self.xlim, self.ylim = ( + self.pagesize[0] * (1 - xmargin_r), + self.pagesize[1] * (1 - ymargin_top), + ) + self.pagewidth = self.xlim - self.x0 + self.pageheight = self.ylim - self.y0 + self.xcenter, self.ycenter = ( + self.x0 + self.pagewidth / 2.0, + self.y0 + self.pageheight / 2.0, + ) + + def set_bounds(self, start, end): + """Set start and end points for the drawing as a whole. + + Arguments: + - start - The first base (or feature mark) to draw from + - end - The last base (or feature mark) to draw to + + """ + low, high = self._parent.range() # Extent of tracks + + if start is not None and end is not None and start > end: + start, end = end, start + + if start is None or start < 0: # Check validity of passed args and + start = 0 # default to 0 + if end is None or end < 0: + end = high + 1 # default to track range top limit + + self.start, self.end = int(start), int(end) + self.length = self.end - self.start + 1 + + def is_in_bounds(self, value): + """Check if given value is within the region selected for drawing. + + Arguments: + - value - A base position + + """ + if value >= self.start and value <= self.end: + return 1 + return 0 + + def __len__(self): + """Return the length of the region to be drawn.""" + return self.length + + def _current_track_start_end(self): + track = self._parent[self.current_track_level] + if track.start is None: + start = self.start + else: + start = max(self.start, track.start) + if track.end is None: + end = self.end + else: + end = min(self.end, track.end) + return start, end diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Colors.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Colors.py new file mode 100644 index 0000000000000000000000000000000000000000..a37e1071d4596c53866a1f117384c0aff5389e69 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Colors.py @@ -0,0 +1,234 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""Colors module. + +Provides: + +- ColorTranslator - class to convert tuples of integers and floats into + colors.Color objects + +For drawing capabilities, this module uses reportlab to define colors: +http://www.reportlab.com +""" + +# ReportLab imports +from reportlab.lib import colors + + +class ColorTranslator: + """Class providing methods for translating representations of color into. + + Examples + -------- + >>> from Bio.Graphics import GenomeDiagram + >>> gdct=GenomeDiagram._Colors.ColorTranslator() + >>> print(gdct.float1_color((0.5, 0.5, 0.5))) + Color(.5,.5,.5,1) + >>> print(gdct.int255_color((1, 75, 240))) + Color(.003922,.294118,.941176,1) + >>> print(gdct.artemis_color(7)) + Color(1,1,0,1) + >>> print(gdct.scheme_color(2)) + Color(1,0,0,1) + >>> gdct.get_artemis_colorscheme() + {0: (Color(1,1,1,1), 'pathogenicity, adaptation, chaperones'), 1: (Color(.39,.39,.39,1), 'energy metabolism'), 2: (Color(1,0,0,1), 'information transfer'), 3: (Color(0,1,0,1), 'surface'), 4: (Color(0,0,1,1), 'stable RNA'), 5: (Color(0,1,1,1), 'degradation of large molecules'), 6: (Color(1,0,1,1), 'degradation of small molecules'), 7: (Color(1,1,0,1), 'central/intermediary/miscellaneous metabolism'), 8: (Color(.6,.98,.6,1), 'unknown'), 9: (Color(.53,.81,.98,1), 'regulators'), 10: (Color(1,.65,0,1), 'conserved hypotheticals'), 11: (Color(.78,.59,.39,1), 'pseudogenes and partial genes'), 12: (Color(1,.78,.78,1), 'phage/IS elements'), 13: (Color(.7,.7,.7,1), 'some miscellaneous information'), 14: (Color(0,0,0,1), ''), 15: (Color(1,.25,.25,1), 'secondary metabolism'), 16: (Color(1,.5,.5,1), ''), 17: (Color(1,.75,.75,1), '')} + + >>> print(gdct.translate((0.5, 0.5, 0.5))) + Color(.5,.5,.5,1) + >>> print(gdct.translate((1, 75, 240))) + Color(.003922,.294118,.941176,1) + >>> print(gdct.translate(7)) + Color(1,1,0,1) + >>> print(gdct.translate(2)) + Color(1,0,0,1) + + """ + + def __init__(self, filename=None): + """Initialize. + + Argument filename is the location of a file containing + colorscheme information. + """ + self._artemis_colorscheme = { + 0: (colors.Color(1, 1, 1), "pathogenicity, adaptation, chaperones"), + 1: (colors.Color(0.39, 0.39, 0.39), "energy metabolism"), + 2: (colors.Color(1, 0, 0), "information transfer"), + 3: (colors.Color(0, 1, 0), "surface"), + 4: (colors.Color(0, 0, 1), "stable RNA"), + 5: (colors.Color(0, 1, 1), "degradation of large molecules"), + 6: (colors.Color(1, 0, 1), "degradation of small molecules"), + 7: (colors.Color(1, 1, 0), "central/intermediary/miscellaneous metabolism"), + 8: (colors.Color(0.60, 0.98, 0.60), "unknown"), + 9: (colors.Color(0.53, 0.81, 0.98), "regulators"), + 10: (colors.Color(1, 0.65, 0), "conserved hypotheticals"), + 11: (colors.Color(0.78, 0.59, 0.39), "pseudogenes and partial genes"), + 12: (colors.Color(1, 0.78, 0.78), "phage/IS elements"), + 13: (colors.Color(0.70, 0.70, 0.70), "some miscellaneous information"), + 14: (colors.Color(0, 0, 0), ""), + 15: (colors.Color(1, 0.25, 0.25), "secondary metabolism"), + 16: (colors.Color(1, 0.5, 0.5), ""), + 17: (colors.Color(1, 0.75, 0.75), ""), + } # Hardwired Artemis color scheme + self._colorscheme = {} + if filename is not None: + self.read_colorscheme(filename) # Imported color scheme + else: + self._colorscheme = self._artemis_colorscheme + + def translate(self, color=None, colour=None): + """Translate a color into a ReportLab Color object. + + Arguments: + - color - Color defined as an int, a tuple of three ints 0->255 + or a tuple of three floats 0 -> 1, or a string giving + one of the named colors defined by ReportLab, or a + ReportLab color object (returned as is). + - colour - Backwards compatible alias using UK spelling (which + will over-ride any color argument). + + Returns a colors.Color object, determined semi-intelligently + depending on the input values + """ + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + + if color is None: + raise ValueError("Passed color (or colour) must be a valid color type") + elif isinstance(color, int): + color = self.scheme_color(color) + elif isinstance(color, colors.Color): + return color + elif isinstance(color, str): + # Assume its a named reportlab color like "red". + color = colors.toColor(color) + elif isinstance(color, tuple) and isinstance(color[0], float): + color = self.float1_color(color) + elif isinstance(color, tuple) and isinstance(color[0], int): + color = self.int255_color(color) + return color + + def read_colorscheme(self, filename): + r"""Load colour scheme from file. + + Reads information from a file containing color information and stores + it internally. + + Argument filename is the location of a file defining colors in + tab-separated format plaintext as:: + + INT \t RED \t GREEN \t BLUE \t Comment + + Where RED, GREEN and BLUE are intensities in the range 0 -> 255, e.g.:: + + 2 \t 255 \t 0 \t 0 \t Red: Information transfer + + """ + with open(filename).readlines() as lines: + for line in lines: + data = line.strip().split("\t") + try: + label = int(data[0]) + red, green, blue = int(data[1]), int(data[2]), int(data[3]) + if len(data) > 4: + comment = data[4] + else: + comment = "" + self._colorscheme[label] = ( + self.int255_color((red, green, blue)), + comment, + ) + except ValueError: + raise ValueError( + "Expected INT \t INT \t INT \t INT \t string input" + ) from None + + def get_artemis_colorscheme(self): + """Return the Artemis color scheme as a dictionary.""" + return self._artemis_colorscheme + + def artemis_color(self, value): + """Artemis color (integer) to ReportLab Color object. + + Arguments: + - value: An int representing a functional class in the Artemis + color scheme (see www.sanger.ac.uk for a description), + or a string from a GenBank feature annotation for the + color which may be dot delimited (in which case the + first value is used). + + Takes an int representing a functional class in the Artemis color + scheme, and returns the appropriate colors.Color object + """ + try: + value = int(value) + except ValueError: + if value.count("."): # dot-delimited + value = int(value.split(".", 1)[0]) # Use only first integer + else: + raise + if value in self._artemis_colorscheme: + return self._artemis_colorscheme[value][0] + else: + raise ValueError("Artemis color out of range: %d" % value) + + def get_colorscheme(self): + """Return the user-defined color scheme as a dictionary.""" + return self._colorscheme + + def scheme_color(self, value): + """Map a user-defined color integer to a ReportLab Color object. + + - value: An int representing a single color in the user-defined + color scheme + + Takes an int representing a user-defined color and returns the + appropriate colors.Color object. + """ + if value in self._colorscheme: + return self._colorscheme[value][0] + else: + raise ValueError("Scheme color out of range: %d" % value) + + def int255_color(self, values): + """Map integer (red, green, blue) tuple to a ReportLab Color object. + + - values: A tuple of (red, green, blue) intensities as + integers in the range 0->255 + + Takes a tuple of (red, green, blue) intensity values in the range + 0 -> 255 and returns an appropriate colors.Color object. + """ + red, green, blue = values + factor = 1 / 255.0 + red, green, blue = red * factor, green * factor, blue * factor + return colors.Color(red, green, blue) + + def float1_color(self, values): + """Map float (red, green, blue) tuple to a ReportLab Color object. + + - values: A tuple of (red, green, blue) intensities as floats + in the range 0 -> 1 + + Takes a tuple of (red, green, blue) intensity values in the range + 0 -> 1 and returns an appropriate colors.Color object. + """ + red, green, blue = values + return colors.Color(red, green, blue) + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=2) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_CrossLink.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_CrossLink.py new file mode 100644 index 0000000000000000000000000000000000000000..7958de4d51c3a4fc21da6eba81ad18baa57e3921 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_CrossLink.py @@ -0,0 +1,100 @@ +# Copyright 2011-2017 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Genome Diagram Feature cross-link module.""" + +from reportlab.lib import colors + + +class CrossLink: + """Hold information for drawing a cross link between features.""" + + def __init__( + self, featureA, featureB, color=colors.lightgreen, border=None, flip=False + ): + """Create a new cross link. + + Arguments featureA and featureB should GenomeDiagram feature objects, + or 3-tuples (track object, start, end), and currently must be on + different tracks. + + The color and border arguments should be ReportLab colour objects, or + for border use a boolean False for no border, otherwise it defaults to + the same as the main colour. + + The flip argument draws an inverted cross link, useful for showing a + mapping where one sequence has been reversed. It is conventional to + also use a different colour (e.g. red for simple links, blue for any + flipped links). + """ + # Initialize attributes + self.featureA = featureA + self.featureB = featureB + self.color = color # default color to draw the feature + self.border = border + self.flip = flip + + @property + def startA(self): + """Start position of Feature A.""" + try: + return self.featureA.start + except AttributeError: + track, start, end = self.featureA + return start + + @property + def endA(self): + """End position of Feature A.""" + try: + return self.featureA.end + except AttributeError: + track, start, end = self.featureA + return end + + def _trackA(self, tracks): + try: + track, start, end = self.featureA + assert track in tracks + return track + except TypeError: + for track in tracks: + for feature_set in track.get_sets(): + if hasattr(feature_set, "features"): + if self.featureA in feature_set.features.values(): + return track + return None + + @property + def startB(self): + """Start position of Feature B.""" + try: + return self.featureB.start + except AttributeError: + track, start, end = self.featureB + return start + + @property + def endB(self): + """End position of Feature B.""" + try: + return self.featureB.end + except AttributeError: + track, start, end = self.featureB + return end + + def _trackB(self, tracks): + try: + track, start, end = self.featureB + assert track in tracks + return track + except TypeError: + for track in tracks: + for feature_set in track.get_sets(): + if hasattr(feature_set, "features"): + if self.featureB in feature_set.features.values(): + return track + return None diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Diagram.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Diagram.py new file mode 100644 index 0000000000000000000000000000000000000000..076de2267124ed00c5b69107772ee4942962420e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Diagram.py @@ -0,0 +1,411 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +"""Provides a container for information concerning the tracks to be drawn in a diagram. + +It also provides the interface for defining the diagram (possibly split these +functions in later version?). + +For drawing capabilities, this module uses reportlab to draw and write the +diagram: + +http://www.reportlab.com + +For dealing with biological information, the package expects BioPython +objects - namely SeqRecord objects containing SeqFeature objects. +""" + +try: + from reportlab.graphics import renderPM +except ImportError: + # This is an optional part of ReportLab, so may not be installed. + renderPM = None + +from Bio.Graphics import _write + +from ._CircularDrawer import CircularDrawer +from ._LinearDrawer import LinearDrawer +from ._Track import Track + + +def _first_defined(*args): + """Return the first non-null argument (PRIVATE).""" + for arg in args: + if arg is not None: + return arg + return None + + +class Diagram: + """Diagram container. + + Arguments: + - name - a string, identifier for the diagram. + - tracks - a list of Track objects comprising the diagram. + - format - a string, format of the diagram 'circular' or + 'linear', depending on the sort of diagram required. + - pagesize - a string, the pagesize of output describing the ISO + size of the image, or a tuple of pixels. + - orientation - a string describing the required orientation of the + final drawing ('landscape' or 'portrait'). + - x - a float (0->1), the proportion of the page to take + up with even X margins t the page. + - y - a float (0->1), the proportion of the page to take + up with even Y margins to the page. + - xl - a float (0->1), the proportion of the page to take + up with the left X margin to the page (overrides x). + - xr - a float (0->1), the proportion of the page to take + up with the right X margin to the page (overrides x). + - yt - a float (0->1), the proportion of the page to take + up with the top Y margin to the page (overrides y). + - yb - a float (0->1), the proportion of the page to take + up with the bottom Y margin to the page (overrides y). + - circle_core - a float, the proportion of the available radius to + leave empty at the center of a circular diagram (0 to 1). + - start - an integer, the base/aa position to start the diagram at. + - end - an integer, the base/aa position to end the diagram at. + - tracklines - a boolean, True if track guidelines are to be drawn. + - fragments - and integer, for a linear diagram, the number of equal + divisions into which the sequence is divided. + - fragment_size - a float (0->1), the proportion of the space + available to each fragment that should be used in drawing. + - track_size - a float (0->1), the proportion of the space + available to each track that should be used in drawing with sigils. + - circular - a boolean, True if the genome/sequence to be drawn + is, in reality, circular. + + """ + + def __init__( + self, + name=None, + format="circular", + pagesize="A3", + orientation="landscape", + x=0.05, + y=0.05, + xl=None, + xr=None, + yt=None, + yb=None, + start=None, + end=None, + tracklines=False, + fragments=10, + fragment_size=None, + track_size=0.75, + circular=True, + circle_core=0.0, + ): + """Initialize. + + gdd = Diagram(name=None) + """ + self.tracks = {} # Holds all Track objects, keyed by level + self.name = name # Description of the diagram + # Diagram page setup attributes + self.format = format + self.pagesize = pagesize + self.orientation = orientation + self.x = x + self.y = y + self.xl = xl + self.xr = xr + self.yt = yt + self.yb = yb + self.start = start + self.end = end + self.tracklines = tracklines + self.fragments = fragments + if fragment_size is not None: + self.fragment_size = fragment_size + else: + if self.fragments == 1: + # For single fragments, default to full height + self.fragment_size = 1 + else: + # Otherwise keep a 10% gap between fragments + self.fragment_size = 0.9 + self.track_size = track_size + self.circular = circular + self.circle_core = circle_core + self.cross_track_links = [] + self.drawing = None + + def set_all_tracks(self, attr, value): + """Set the passed attribute of all tracks in the set to the passed value. + + Arguments: + - attr - An attribute of the Track class. + - value - The value to set that attribute. + + set_all_tracks(self, attr, value) + """ + for track in self.tracks.values(): + if hasattr(track, attr): + # If the feature has the attribute set it to the passed value + setattr(track, attr, value) + + def draw( + self, + format=None, + pagesize=None, + orientation=None, + x=None, + y=None, + xl=None, + xr=None, + yt=None, + yb=None, + start=None, + end=None, + tracklines=None, + fragments=None, + fragment_size=None, + track_size=None, + circular=None, + circle_core=None, + cross_track_links=None, + ): + """Draw the diagram, with passed parameters overriding existing attributes. + + gdd.draw(format='circular') + """ + # Pass the parameters to the drawer objects that will build the + # diagrams. At the moment, we detect overrides with an or in the + # Instantiation arguments, but I suspect there's a neater way to do + # this. + if format == "linear": + drawer = LinearDrawer( + self, + _first_defined(pagesize, self.pagesize), + _first_defined(orientation, self.orientation), + _first_defined(x, self.x), + _first_defined(y, self.y), + _first_defined(xl, self.xl), + _first_defined(xr, self.xr), + _first_defined(yt, self.yt), + _first_defined(yb, self.yb), + _first_defined(start, self.start), + _first_defined(end, self.end), + _first_defined(tracklines, self.tracklines), + _first_defined(fragments, self.fragments), + _first_defined(fragment_size, self.fragment_size), + _first_defined(track_size, self.track_size), + _first_defined(cross_track_links, self.cross_track_links), + ) + else: + drawer = CircularDrawer( + self, + _first_defined(pagesize, self.pagesize), + _first_defined(orientation, self.orientation), + _first_defined(x, self.x), + _first_defined(y, self.y), + _first_defined(xl, self.xl), + _first_defined(xr, self.xr), + _first_defined(yt, self.yt), + _first_defined(yb, self.yb), + _first_defined(start, self.start), + _first_defined(end, self.end), + _first_defined(tracklines, self.tracklines), + _first_defined(track_size, self.track_size), + _first_defined(circular, self.circular), + _first_defined(circle_core, self.circle_core), + _first_defined(cross_track_links, self.cross_track_links), + ) + drawer.draw() # Tell the drawer to complete the drawing + self.drawing = drawer.drawing # Get the completed drawing + + def write(self, filename="test1.ps", output="PS", dpi=72): + """Write the drawn diagram to a specified file, in a specified format. + + Arguments: + - filename - a string indicating the name of the output file, + or a handle to write to. + - output - a string indicating output format, one of PS, PDF, + SVG, or provided the ReportLab renderPM module is installed, one + of the bitmap formats JPG, BMP, GIF, PNG, TIFF or TIFF. The + format can be given in upper or lower case. + - dpi - an integer. Resolution (dots per inch) for bitmap formats. + + Returns: + No return value. + + write(self, filename='test1.ps', output='PS', dpi=72) + + """ + return _write(self.drawing, filename, output, dpi=dpi) + + def write_to_string(self, output="PS", dpi=72): + """Return a byte string containing the diagram in the requested format. + + Arguments: + - output - a string indicating output format, one of PS, PDF, + SVG, JPG, BMP, GIF, PNG, TIFF or TIFF (as specified for the write + method). + - dpi - Resolution (dots per inch) for bitmap formats. + + Returns: + Return the completed drawing as a bytes string in a prescribed + format. + + """ + # The ReportLab drawToString method, which this function used to call, + # originally just used a StringIO handle with the drawToFile method. + # + # TODO - Rename this method to include keyword bytes? + from io import BytesIO + + handle = BytesIO() + self.write(handle, output, dpi) + return handle.getvalue() + + def add_track(self, track, track_level): + """Add a Track object to the diagram. + + It also accepts instructions to place it at a particular level on the + diagram. + + Arguments: + - track - Track object to draw. + - track_level - an integer. The level at which the track will be + drawn (above an arbitrary baseline). + + add_track(self, track, track_level) + """ + if track is None: + raise ValueError("Must specify track") + if track_level not in self.tracks: # No track at that level + self.tracks[track_level] = track # so just add it + else: # Already a track there, so shunt all higher tracks up one + occupied_levels = sorted( + self.get_levels() + ) # Get list of occupied levels... + occupied_levels.reverse() # ...reverse it (highest first) + for val in occupied_levels: + # If track value >= that to be added + if val >= track.track_level: + self.tracks[val + 1] = self.tracks[val] # ...increment by 1 + self.tracks[track_level] = track # And put the new track in + self.tracks[track_level].track_level = track_level + + def new_track(self, track_level, **args): + """Add a new Track to the diagram at a given level. + + The track is returned for further user manipulation. + + Arguments: + - track_level - an integer. The level at which the track will be + drawn (above an arbitrary baseline). + + new_track(self, track_level) + """ + newtrack = Track() + for key in args: + setattr(newtrack, key, args[key]) + if track_level not in self.tracks: # No track at that level + self.tracks[track_level] = newtrack # so just add it + else: # Already a track there, so shunt all higher tracks up one + occupied_levels = sorted( + self.get_levels() + ) # Get list of occupied levels... + occupied_levels.reverse() # ...reverse (highest first)... + for val in occupied_levels: + if val >= track_level: + # Track value >= that to be added, increment by 1 + self.tracks[val + 1] = self.tracks[val] + self.tracks[track_level] = newtrack # And put the new track in + self.tracks[track_level].track_level = track_level + return newtrack + + def del_track(self, track_level): + """Remove the track to be drawn at a particular level on the diagram. + + Arguments: + - track_level - an integer. The level of the track on the diagram + to delete. + + del_track(self, track_level) + """ + del self.tracks[track_level] + + def get_tracks(self): + """Return a list of the tracks contained in the diagram.""" + return list(self.tracks.values()) + + def move_track(self, from_level, to_level): + """Move a track from one level on the diagram to another. + + Arguments: + - from_level - an integer. The level at which the track to be + moved is found. + - to_level - an integer. The level to move the track to. + + """ + aux = self.tracks[from_level] + del self.tracks[from_level] + self.add_track(aux, to_level) + + def renumber_tracks(self, low=1, step=1): + """Renumber all tracks consecutively. + + Optionally from a passed lowest number. + + Arguments: + - low - an integer. The track number to start from. + - step - an integer. The track interval for separation of + tracks. + + """ + track = low # Start numbering from here + levels = self.get_levels() + + conversion = {} # Holds new set of levels + for level in levels: # Starting at low... + conversion[track] = self.tracks[level] # Add old tracks to new set + conversion[track].track_level = track + track += step # step interval + self.tracks = conversion # Replace old set of levels with new set + + def get_levels(self): + """Return a sorted list of levels occupied by tracks in the diagram.""" + return sorted(self.tracks) + + def get_drawn_levels(self): + """Return a sorted list of levels occupied by tracks. + + These tracks are not explicitly hidden. + """ + return sorted(key for key in self.tracks if not self.tracks[key].hide) + + def range(self): + """Return lowest and highest base numbers from track features. + + Returned type is a tuple. + """ + lows, highs = [], [] + for track in self.tracks.values(): # Get ranges for each track + low, high = track.range() + lows.append(low) + highs.append(high) + return min(lows), max(highs) # Return extremes from all tracks + + def __getitem__(self, key): + """Return the track contained at the level of the passed key.""" + return self.tracks[key] + + def __str__(self): + """Return a formatted string describing the diagram.""" + outstr = [f"\n<{self.__class__}: {self.name}>"] + outstr.append("%d tracks" % len(self.tracks)) + for level in self.get_levels(): + outstr.append("Track %d: %s\n" % (level, self.tracks[level])) + outstr = "\n".join(outstr) + return outstr diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Feature.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Feature.py new file mode 100644 index 0000000000000000000000000000000000000000..e3be610f62351d9980a62353c67211714e5b6ed6 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Feature.py @@ -0,0 +1,197 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""Feature module. + +Provides: + - Feature - class to wrap Bio.SeqFeature objects with drawing information + +For drawing capabilities, this module uses reportlab to define colors: +http://www.reportlab.com +""" + +# ReportLab imports +from reportlab.lib import colors + +# GenomeDiagram imports +from ._Colors import ColorTranslator + + +class Feature: + """Class to wrap Bio.SeqFeature objects for GenomeDiagram. + + Attributes: + - parent FeatureSet, container for the object + - id Unique id + - color color.Color, color to draw the feature + - hide Boolean for whether the feature will be drawn or not + - sigil String denoting the type of sigil to use for the feature. + Currently either "BOX" or "ARROW" are supported. + - arrowhead_length Float denoting length of the arrow head to be drawn, + relative to the bounding box height. The arrow shaft + takes up the remainder of the bounding box's length. + - arrowshaft_height Float denoting length of the representative arrow + shaft to be drawn, relative to the bounding box height. + The arrow head takes the full height of the bound box. + - name_qualifiers List of Strings, describes the qualifiers that may + contain feature names in the wrapped Bio.SeqFeature object + - label Boolean, 1 if the label should be shown + - label_font String describing the font to use for the feature label + - label_size Int describing the feature label font size + - label_color color.Color describing the feature label color + - label_angle Float describing the angle through which to rotate the + feature label in degrees (default = 45, linear only) + - label_position String, 'start', 'end' or 'middle' denoting where + to place the feature label. Leave as None for the default + which is 'start' for linear diagrams, and at the bottom of + the feature as drawn on circular diagrams. + - label_strand Integer -1 or +1 to explicitly place the label on the + forward or reverse strand. Default (None) follows th + feature's strand. Use -1 to put labels under (linear) or + inside (circular) the track, +1 to put them above (linear) + or outside (circular) the track. + - locations List of tuples of (start, end) ints describing where the + feature and any subfeatures start and end + - type String denoting the feature type + - name String denoting the feature name + - strand Int describing the strand on which the feature is found + + """ + + def __init__( + self, + parent=None, + feature_id=None, + feature=None, + color=colors.lightgreen, + label=0, + border=None, + colour=None, + ): + """Initialize. + + Arguments: + - parent FeatureSet containing the feature + - feature_id Unique id for the feature + - feature Bio.SeqFeature object to be wrapped + - color color.Color Color to draw the feature (overridden + by backwards compatible argument with UK spelling, colour). + Either argument is overridden if 'color' is found in feature + qualifiers + - border color.Color Color to draw the feature border, use + None for the same as the fill color, False for no border. + - label Boolean, 1 if the label should be shown + + """ + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + + self._colortranslator = ColorTranslator() + + # Initialize attributes + self.parent = parent + self.id = feature_id + self.color = color # default color to draw the feature + self.border = border + self._feature = None # Bio.SeqFeature object to wrap + self.hide = 0 # show by default + self.sigil = "BOX" + self.arrowhead_length = 0.5 # 50% of the box height + self.arrowshaft_height = 0.4 # 40% of the box height + self.name_qualifiers = ["gene", "label", "name", "locus_tag", "product"] + self.label = label + self.label_font = "Helvetica" + self.label_size = 6 + self.label_color = colors.black + self.label_angle = 45 + self.label_position = None # Expect 'start', 'middle', or 'end' (plus aliases) + self.label_strand = None # Expect +1 or -1 if overriding this + + if feature is not None: + self.set_feature(feature) + + def set_feature(self, feature): + """Define the Bio.SeqFeature object to be wrapped.""" + self._feature = feature + self.__process_feature() + + def __process_feature(self): + """Examine wrapped feature and set some properties accordingly (PRIVATE).""" + self.locations = [] + bounds = [] + # This will be a list of length one for a SimpleLocation: + for location in self._feature.location.parts: + start = int(location.start) + end = int(location.end) + # if start > end and self.strand == -1: + # start, end = end, start + self.locations.append((start, end)) + bounds += [start, end] + self.type = str(self._feature.type) # Feature type + # TODO - Strand can vary with subfeatures (e.g. mixed strand tRNA) + if self._feature.location.strand is None: + # This is the SeqFeature default (None), but the drawing code + # only expects 0, +1 or -1. + self.strand = 0 + else: + self.strand = int(self._feature.location.strand) # Feature strand + if "color" in self._feature.qualifiers: # Artemis color (if present) + self.color = self._colortranslator.artemis_color( + self._feature.qualifiers["color"][0] + ) + self.name = self.type + for qualifier in self.name_qualifiers: + if qualifier in self._feature.qualifiers: + self.name = self._feature.qualifiers[qualifier][0] + break + # Note will be 0 to N for origin wrapping feature on genome of length N + self.start, self.end = min(bounds), max(bounds) + + def get_feature(self): + """Return the unwrapped Bio.SeqFeature object.""" + return self._feature + + def set_colour(self, colour): + """Backwards compatible variant of set_color(self, color) using UK spelling.""" + color = self._colortranslator.translate(colour) + self.color = color + + def set_color(self, color): + """Set the color in which the feature will be drawn. + + Arguments: + - color The color to draw the feature - either a colors.Color + object, an RGB tuple of floats, or an integer corresponding a + colors in colors.txt + + """ + # TODO - Make this into the set method for a color property? + color = self._colortranslator.translate(color) + self.color = color + + def __getattr__(self, name): + """Get attribute by name. + + If the Feature class doesn't have the attribute called for, + check in self._feature for it. + """ + return getattr(self._feature, name) # try to get the attribute from the feature + + +################################################################################ +# RUN AS SCRIPT +################################################################################ + +if __name__ == "__main__": + # Test code + gdf = Feature() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Graph.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Graph.py new file mode 100644 index 0000000000000000000000000000000000000000..bda541613ba6a0cae74667db622f3c5ec5f0ac68 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Graph.py @@ -0,0 +1,190 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# Revisions copyright 2008-2009 by Peter Cock. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""Graph module. + +Provides: + - GraphData - Contains data from which a graph will be drawn, and + information about its presentation + +For drawing capabilities, this module uses reportlab to draw and write +the diagram: http://www.reportlab.com +""" + +from math import sqrt + +from reportlab.lib import colors + + +class GraphData: + """Graph Data. + + Attributes: + - id Unique identifier for the data + - data Dictionary of describing the data, keyed by position + - name String describing the data + - style String ('bar', 'heat', 'line') describing how to draw the data + - poscolor colors.Color for drawing high (some styles) or all + values + - negcolor colors.Color for drawing low values (some styles) + - linewidth Int, thickness to draw the line in 'line' styles + + """ + + def __init__( + self, + id=None, + data=None, + name=None, + style="bar", + color=colors.lightgreen, + altcolor=colors.darkseagreen, + center=None, + colour=None, + altcolour=None, + ): + """Initialize. + + Arguments: + - id Unique ID for the graph + - data List of (position, value) tuples + - name String describing the graph + - style String describing the presentation style ('bar', 'line', + 'heat') + - color colors.Color describing the color to draw all or the + 'high' (some styles) values (overridden by backwards + compatible argument with UK spelling, colour). + - altcolor colors.Color describing the color to draw the 'low' + values (some styles only) (overridden by backwards + compatible argument with UK spelling, colour). + - center Value at which x-axis crosses y-axis. + + """ + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + if altcolour is not None: + altcolor = altcolour + + self.id = id # Unique identifier for the graph + self.data = {} # holds values, keyed by sequence position + if data is not None: + self.set_data(data) + self.name = name # Descriptive string + + # Attributes describing how the graph will be drawn + self.style = style # One of 'bar', 'heat' or 'line' + self.poscolor = color # Color to draw all, or 'high' values + self.negcolor = altcolor # Color to draw 'low' values + self.linewidth = 2 # linewidth to use in line graphs + self.center = center # value at which x-axis crosses y-axis + + def set_data(self, data): + """Add data as a list of (position, value) tuples.""" + for pos, val in data: # Fill data dictionary + self.data[pos] = val + + def get_data(self): + """Return data as a list of sorted (position, value) tuples.""" + data = [] + for xval in self.data: + yval = self.data[xval] + data.append((xval, yval)) + data.sort() + return data + + def add_point(self, point): + """Add a single point to the set of data as a (position, value) tuple.""" + pos, val = point + self.data[pos] = val + + def quartiles(self): + """Return (minimum, lowerQ, medianQ, upperQ, maximum) values as tuple.""" + data = sorted(self.data.values()) + datalen = len(data) + return ( + data[0], + data[datalen // 4], + data[datalen // 2], + data[3 * datalen // 4], + data[-1], + ) + + def range(self): + """Return range of data as (start, end) tuple. + + Returns the range of the data, i.e. its start and end points on + the genome as a (start, end) tuple. + """ + positions = sorted(self.data) # i.e. dict keys + # Return first and last positions in graph + # print(len(self.data)) + return (positions[0], positions[-1]) + + def mean(self): + """Return the mean value for the data points (float).""" + data = list(self.data.values()) + return sum(data) / len(data) + + def stdev(self): + """Return the sample standard deviation for the data (float).""" + data = list(self.data.values()) + m = self.mean() + runtotal = 0.0 + for entry in data: + runtotal += (entry - m) ** 2 + # This is sample standard deviation; population stdev would involve + # division by len(data), rather than len(data)-1 + return sqrt(runtotal / (len(data) - 1)) + + def __len__(self): + """Return the number of points in the data set.""" + return len(self.data) + + def __getitem__(self, index): + """Return data value(s) at the given position. + + Given an integer representing position on the sequence + returns a float - the data value at the passed position. + + If a slice, returns graph data from the region as a list or + (position, value) tuples. Slices with step are not supported. + """ + if isinstance(index, int): + return self.data[index] + elif isinstance(index, slice): + # TODO - Why does it treat the end points both as inclusive? + # This doesn't match Python norms does it? + low = index.start + high = index.stop + if index.step is not None and index.step != 1: + raise ValueError + outlist = [] + for pos in sorted(self.data): + if pos >= low and pos <= high: + outlist.append((pos, self.data[pos])) + return outlist + else: + raise TypeError("Need an integer or a slice") + + def __str__(self): + """Return a string describing the graph data.""" + outstr = [f"\nGraphData: {self.name}, ID: {self.id}"] + outstr.append("Number of points: %d" % len(self.data)) + outstr.append(f"Mean data value: {self.mean()}") + outstr.append(f"Sample SD: {self.stdev():.3f}") + outstr.append( + "Minimum: %s\n1Q: %s\n2Q: %s\n3Q: %s\nMaximum: %s" % self.quartiles() + ) + outstr.append("Sequence Range: %s..%s" % self.range()) + return "\n".join(outstr) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_GraphSet.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_GraphSet.py new file mode 100644 index 0000000000000000000000000000000000000000..aeafee2931fa4fa4df9fe6dd0f78fef2b2a9db49 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_GraphSet.py @@ -0,0 +1,171 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# Revisions copyright 2008-2010 by Peter Cock. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ +# +# TODO: Make representation of Ymax and Ymin values at this level, so that +# calculation of graph/axis drawing is simplified + +"""GraphSet module. + +Provides: + - GraphSet - container for GraphData objects + +For drawing capabilities, this module uses reportlab to draw and write +the diagram: http://www.reportlab.com +""" + +# ReportLab imports + +from reportlab.lib import colors + +from ._Graph import GraphData + + +class GraphSet: + """Graph Set. + + Attributes: + - id Unique identifier for the set + - name String describing the set + + """ + + def __init__(self, name=None): + """Initialize. + + Arguments: + - name String identifying the graph set sensibly + + """ + self.id = id # Unique identifier for the set + self._next_id = 0 # Holds unique ids for graphs + self._graphs = {} # Holds graphs, keyed by unique id + self.name = name # Holds description of graph + + def new_graph( + self, + data, + name=None, + style="bar", + color=colors.lightgreen, + altcolor=colors.darkseagreen, + linewidth=1, + center=None, + colour=None, + altcolour=None, + centre=None, + ): + """Add a GraphData object to the diagram. + + Arguments: + - data List of (position, value) int tuples + - name String, description of the graph + - style String ('bar', 'heat', 'line') describing how the graph + will be drawn + - color colors.Color describing the color to draw all or 'high' + (some styles) data (overridden by backwards compatible + argument with UK spelling, colour). + - altcolor colors.Color describing the color to draw 'low' (some + styles) data (overridden by backwards compatible argument + with UK spelling, colour). + - linewidth Float describing linewidth for graph + - center Float setting the value at which the x-axis + crosses the y-axis (overridden by backwards + compatible argument with UK spelling, centre) + + Add a GraphData object to the diagram (will be stored internally). + """ + # Let the UK spelling (colour) override the USA spelling (color) + if colour is not None: + color = colour + if altcolour is not None: + altcolor = altcolour + if centre is not None: + center = centre + + id = self._next_id # get id number + graph = GraphData(id, data, name, style, color, altcolor, center) + graph.linewidth = linewidth + self._graphs[id] = graph # add graph data + self._next_id += 1 # increment next id + return graph + + def del_graph(self, graph_id): + """Remove a graph from the set, indicated by its id.""" + del self._graphs[graph_id] + + def get_graphs(self): + """Return list of all graphs in the graph set, sorted by id. + + Sorting is to ensure reliable stacking. + """ + return [self._graphs[id] for id in sorted(self._graphs)] + + def get_ids(self): + """Return a list of all ids for the graph set.""" + return list(self._graphs.keys()) + + def range(self): + """Return the lowest and highest base (or mark) numbers as a tuple.""" + lows, highs = [], [] + for graph in self._graphs.values(): + low, high = graph.range() + lows.append(low) + highs.append(high) + return (min(lows), max(highs)) + + def data_quartiles(self): + """Return (minimum, lowerQ, medianQ, upperQ, maximum) values as a tuple.""" + data = [] + for graph in self._graphs.values(): + data += list(graph.data.values()) + data.sort() + datalen = len(data) + return ( + data[0], + data[datalen / 4], + data[datalen / 2], + data[3 * datalen / 4], + data[-1], + ) + + def to_string(self, verbose=0): + """Return a formatted string with information about the set. + + Arguments: + - verbose - Flag indicating whether a short or complete account + of the set is required + + """ + if not verbose: + return f"{self}" + else: + outstr = [f"\n<{self.__class__}: {self.name}>"] + outstr.append("%d graphs" % len(self._graphs)) + for key in self._graphs: + outstr.append(f"{self._graphs[key]}") + return "\n".join(outstr) + + def __len__(self): + """Return the number of graphs in the set.""" + return len(self._graphs) + + def __getitem__(self, key): + """Return a graph, keyed by id.""" + return self._graphs[key] + + def __str__(self): + """Return a formatted string with information about the feature set.""" + outstr = [f"\n<{self.__class__}: {self.name}>"] + outstr.append("%d graphs" % len(self._graphs)) + outstr = "\n".join(outstr) + return outstr diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_LinearDrawer.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_LinearDrawer.py new file mode 100644 index 0000000000000000000000000000000000000000..39da87964e429b1c7ed631a6006b3e2e7ff6fbf8 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_LinearDrawer.py @@ -0,0 +1,1584 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# Revisions copyright 2008-2009 by Peter Cock. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""Linear Drawer module. + +Provides: + - LinearDrawer - Drawing object for linear diagrams + +For drawing capabilities, this module uses reportlab to draw and write +the diagram: http://www.reportlab.com +""" + +from math import ceil + +from reportlab.graphics.shapes import Drawing +from reportlab.graphics.shapes import Group +from reportlab.graphics.shapes import Line +from reportlab.graphics.shapes import Polygon +from reportlab.graphics.shapes import String +from reportlab.lib import colors + +from ._AbstractDrawer import _stroke_and_fill_colors +from ._AbstractDrawer import AbstractDrawer +from ._AbstractDrawer import angle2trig +from ._AbstractDrawer import deduplicate +from ._AbstractDrawer import draw_arrow +from ._AbstractDrawer import draw_box +from ._AbstractDrawer import draw_cut_corner_box +from ._AbstractDrawer import intermediate_points +from ._FeatureSet import FeatureSet +from ._GraphSet import GraphSet + + +class LinearDrawer(AbstractDrawer): + """Linear Drawer. + + Inherits from: + - AbstractDrawer + + Attributes: + - tracklines Boolean for whether to draw lines delineating tracks + - pagesize Tuple describing the size of the page in pixels + - x0 Float X co-ord for leftmost point of drawable area + - xlim Float X co-ord for rightmost point of drawable area + - y0 Float Y co-ord for lowest point of drawable area + - ylim Float Y co-ord for topmost point of drawable area + - pagewidth Float pixel width of drawable area + - pageheight Float pixel height of drawable area + - xcenter Float X co-ord of center of drawable area + - ycenter Float Y co-ord of center of drawable area + - start Int, base to start drawing from + - end Int, base to stop drawing at + - length Int, size of sequence to be drawn + - fragments Int, number of fragments into which to divide the + drawn sequence + - fragment_size Float (0->1) the proportion of the fragment height to + draw in + - track_size Float (0->1) the proportion of the track height to + draw in + - drawing Drawing canvas + - drawn_tracks List of ints denoting which tracks are to be drawn + - current_track_level Int denoting which track is currently being + drawn + - fragment_height Float total fragment height in pixels + - fragment_bases Int total fragment length in bases + - fragment_lines Dictionary of top and bottom y-coords of fragment, + keyed by fragment number + - fragment_limits Dictionary of start and end bases of each fragment, + keyed by fragment number + - track_offsets Dictionary of number of pixels that each track top, + center and bottom is offset from the base of a fragment, keyed by track + - cross_track_links List of tuples each with four entries (track A, + feature A, track B, feature B) to be linked. + + """ + + def __init__( + self, + parent=None, + pagesize="A3", + orientation="landscape", + x=0.05, + y=0.05, + xl=None, + xr=None, + yt=None, + yb=None, + start=None, + end=None, + tracklines=0, + fragments=10, + fragment_size=None, + track_size=0.75, + cross_track_links=None, + ): + """Initialize. + + Arguments: + - parent Diagram object containing the data that the drawer draws + - pagesize String describing the ISO size of the image, or a tuple + of pixels + - orientation String describing the required orientation of the + final drawing ('landscape' or 'portrait') + - x Float (0->1) describing the relative size of the X + margins to the page + - y Float (0->1) describing the relative size of the Y + margins to the page + - xl Float (0->1) describing the relative size of the left X + margin to the page (overrides x) + - xl Float (0->1) describing the relative size of the left X + margin to the page (overrides x) + - xr Float (0->1) describing the relative size of the right X + margin to the page (overrides x) + - yt Float (0->1) describing the relative size of the top Y + margin to the page (overrides y) + - yb Float (0->1) describing the relative size of the lower Y + margin to the page (overrides y) + - start Int, the position to begin drawing the diagram at + - end Int, the position to stop drawing the diagram at + - tracklines Boolean flag to show (or not) lines delineating tracks + on the diagram + - fragments Int, the number of equal fragments into which the + sequence should be divided for drawing + - fragment_size Float(0->1) The proportion of the available height + for the fragment that should be taken up in drawing + - track_size The proportion of the available track height that + should be taken up in drawing + - cross_track_links List of tuples each with four entries (track A, + feature A, track B, feature B) to be linked. + """ + # Use the superclass' instantiation method + AbstractDrawer.__init__( + self, + parent, + pagesize, + orientation, + x, + y, + xl, + xr, + yt, + yb, + start, + end, + tracklines, + cross_track_links, + ) + + # Useful measurements on the page + self.fragments = fragments + if fragment_size is not None: + self.fragment_size = fragment_size + else: + if self.fragments == 1: + # For single fragments, default to full height + self.fragment_size = 1 + else: + # Otherwise keep a 10% gap between fragments + self.fragment_size = 0.9 + self.track_size = track_size + + def draw(self): + """Draw a linear diagram of the data in the parent Diagram object.""" + # Instantiate the drawing canvas + self.drawing = Drawing(self.pagesize[0], self.pagesize[1]) + + feature_elements = [] # holds feature elements + feature_labels = [] # holds feature labels + greytrack_bgs = [] # holds track background + greytrack_labels = [] # holds track foreground labels + scale_axes = [] # holds scale axes + scale_labels = [] # holds scale axis labels + + # Get the tracks to be drawn + self.drawn_tracks = self._parent.get_drawn_levels() + + # Set fragment and track sizes + self.init_fragments() + self.set_track_heights() + + # Go through each track in the parent (if it is to be drawn) one by + # one and collate the data as drawing elements + for track_level in self.drawn_tracks: # only use tracks to be drawn + self.current_track_level = track_level # establish track level + track = self._parent[track_level] # get the track at that level + gbgs, glabels = self.draw_greytrack(track) # get greytrack elements + greytrack_bgs.append(gbgs) + greytrack_labels.append(glabels) + features, flabels = self.draw_track(track) # get feature and graph elements + feature_elements.append(features) + feature_labels.append(flabels) + if track.scale: + axes, slabels = self.draw_scale(track) # get scale elements + scale_axes.append(axes) + scale_labels.append(slabels) + + feature_cross_links = [] + for cross_link_obj in self.cross_track_links: + cross_link_elements = self.draw_cross_link(cross_link_obj) + if cross_link_elements: + feature_cross_links.append(cross_link_elements) + + # Groups listed in order of addition to page (from back to front) + # Draw track backgrounds + # Draw feature cross track links + # Draw features and graphs + # Draw scale axes + # Draw scale labels + # Draw feature labels + # Draw track labels + element_groups = [ + greytrack_bgs, + feature_cross_links, + feature_elements, + scale_axes, + scale_labels, + feature_labels, + greytrack_labels, + ] + for element_group in element_groups: + for element_list in element_group: + [self.drawing.add(element) for element in element_list] + + if self.tracklines: # Draw test tracks over top of diagram + self.draw_test_tracks() + + def init_fragments(self): + """Initialize useful values for positioning diagram elements.""" + # Set basic heights, lengths etc + self.fragment_height = self.pageheight / self.fragments + # total fragment height in pixels + self.fragment_bases = ceil(self.length / self.fragments) + # fragment length in bases + + # Key fragment base and top lines by fragment number + # Holds bottom and top line locations of fragments, keyed by fragment number + self.fragment_lines = {} + # Number of pixels to crop the fragment: + fragment_crop = (1 - self.fragment_size) / 2 + fragy = self.ylim # Holder for current absolute fragment base + for fragment in range(self.fragments): + fragtop = fragy - fragment_crop * self.fragment_height # top - crop + fragbtm = ( + fragy - (1 - fragment_crop) * self.fragment_height + ) # bottom + crop + self.fragment_lines[fragment] = (fragbtm, fragtop) + fragy -= self.fragment_height # next fragment base + + # Key base starts and ends for each fragment by fragment number + self.fragment_limits = {} # Holds first and last base positions in a fragment + fragment_step = self.fragment_bases # bases per fragment + fragment_count = 0 + # Add start and end positions for each fragment to dictionary + for marker in range(int(self.start), int(self.end), int(fragment_step)): + self.fragment_limits[fragment_count] = (marker, marker + fragment_step) + fragment_count += 1 + + def set_track_heights(self): + """Set track heights. + + Since tracks may not be of identical heights, the bottom and top + offsets of each track relative to the fragment top and bottom is + stored in a dictionary - self.track_offsets, keyed by track number. + """ + bot_track = min(min(self.drawn_tracks), 1) + top_track = max(self.drawn_tracks) # The 'highest' track number to draw + + trackunit_sum = 0 # Total number of 'units' for the tracks + trackunits = {} # The start and end units for each track, keyed by track number + heightholder = 0 # placeholder variable + for track in range(bot_track, top_track + 1): # for all track numbers to 'draw' + try: + trackheight = self._parent[track].height # Get track height + except Exception: # TODO: IndexError? + trackheight = 1 # ...or default to 1 + trackunit_sum += trackheight # increment total track unit height + trackunits[track] = (heightholder, heightholder + trackheight) + heightholder += trackheight # move to next height + trackunit_height = self.fragment_height * self.fragment_size / trackunit_sum + + # Calculate top and bottom offsets for each track, relative to fragment + # base + track_offsets = {} # The offsets from fragment base for each track + track_crop = ( + trackunit_height * (1 - self.track_size) / 2.0 + ) # 'step back' in pixels + assert track_crop >= 0 + for track in trackunits: + top = trackunits[track][1] * trackunit_height - track_crop # top offset + btm = trackunits[track][0] * trackunit_height + track_crop # bottom offset + ctr = btm + (top - btm) / 2.0 # center offset + track_offsets[track] = (btm, ctr, top) + self.track_offsets = track_offsets + + def draw_test_tracks(self): + """Draw test tracks. + + Draw red lines indicating the top and bottom of each fragment, + and blue ones indicating tracks to be drawn. + """ + # Add lines for each fragment + for fbtm, ftop in self.fragment_lines.values(): + self.drawing.add( + Line(self.x0, ftop, self.xlim, ftop, strokeColor=colors.red) + ) # top line + self.drawing.add( + Line(self.x0, fbtm, self.xlim, fbtm, strokeColor=colors.red) + ) # bottom line + + # Add track lines for this fragment - but only for drawn tracks + for track in self.drawn_tracks: + trackbtm = fbtm + self.track_offsets[track][0] + trackctr = fbtm + self.track_offsets[track][1] + tracktop = fbtm + self.track_offsets[track][2] + self.drawing.add( + Line( + self.x0, tracktop, self.xlim, tracktop, strokeColor=colors.blue + ) + ) # top line + self.drawing.add( + Line( + self.x0, trackctr, self.xlim, trackctr, strokeColor=colors.green + ) + ) # center line + self.drawing.add( + Line( + self.x0, trackbtm, self.xlim, trackbtm, strokeColor=colors.blue + ) + ) # bottom line + + def draw_track(self, track): + """Draw track. + + Arguments: + - track Track object + + Returns a tuple (list of elements in the track, list of labels in + the track). + """ + track_elements = [] # Holds elements from features and graphs + track_labels = [] # Holds labels from features and graphs + + # Distribution dictionary for dealing with different set types + set_methods = {FeatureSet: self.draw_feature_set, GraphSet: self.draw_graph_set} + + for set in track.get_sets(): # Draw the feature or graph sets + elements, labels = set_methods[set.__class__](set) + track_elements += elements + track_labels += labels + return track_elements, track_labels + + def draw_tick(self, tickpos, ctr, ticklen, track, draw_label): + """Draw tick. + + Arguments: + - tickpos Int, position of the tick on the sequence + - ctr Float, Y co-ord of the center of the track + - ticklen How long to draw the tick + - track Track, the track the tick is drawn on + - draw_label Boolean, write the tick label? + + Returns a drawing element that is the tick on the scale + """ + if self.start >= tickpos and tickpos >= self.end: + raise RuntimeError( + "Tick at %i, but showing %i to %i" % (tickpos, self.start, self.end) + ) + if not ( + (track.start is None or track.start <= tickpos) + and (track.end is None or tickpos <= track.end) + ): + raise RuntimeError( + "Tick at %i, but showing %r to %r for track" + % (tickpos, track.start, track.end) + ) + fragment, tickx = self.canvas_location(tickpos) # Tick coordinates + assert fragment >= 0, "Fragment %i, tickpos %i" % (fragment, tickpos) + tctr = ctr + self.fragment_lines[fragment][0] # Center line of the track + tickx += self.x0 # Tick X co-ord + ticktop = tctr + ticklen # Y co-ord of tick top + tick = Line(tickx, tctr, tickx, ticktop, strokeColor=track.scale_color) + if draw_label: # Put tick position on as label + if track.scale_format == "SInt": + if tickpos >= 1000000: + tickstring = str(tickpos // 1000000) + " Mbp" + elif tickpos >= 1000: + tickstring = str(tickpos // 1000) + " Kbp" + else: + tickstring = str(tickpos) + else: + tickstring = str(tickpos) + label = String( + 0, + 0, + tickstring, # Make label string + fontName=track.scale_font, + fontSize=track.scale_fontsize, + fillColor=track.scale_color, + ) + labelgroup = Group(label) + rotation = angle2trig(track.scale_fontangle) + labelgroup.transform = ( + rotation[0], + rotation[1], + rotation[2], + rotation[3], + tickx, + ticktop, + ) + else: + labelgroup = None + return tick, labelgroup + + def draw_scale(self, track): + """Draw scale. + + Argument: + - track Track object + + Returns a tuple of (list of elements in the scale, list of labels + in the scale). + """ + scale_elements = [] # Holds axes and ticks + scale_labels = [] # Holds labels + + if not track.scale: # No scale required, exit early + return [], [] + + # Get track location + btm, ctr, top = self.track_offsets[self.current_track_level] + trackheight = top - ctr + + # For each fragment, draw the scale for this track + start, end = self._current_track_start_end() + start_f, start_x = self.canvas_location(start) + end_f, end_x = self.canvas_location(end) + + for fragment in range(start_f, end_f + 1): + tbtm = btm + self.fragment_lines[fragment][0] + tctr = ctr + self.fragment_lines[fragment][0] + ttop = top + self.fragment_lines[fragment][0] + # X-axis + if fragment == start_f: + x_left = start_x + else: + x_left = 0 + if fragment == end_f: + x_right = end_x + # Y-axis end marker + scale_elements.append( + Line( + self.x0 + x_right, + tbtm, + self.x0 + x_right, + ttop, + strokeColor=track.scale_color, + ) + ) + else: + x_right = self.xlim - self.x0 + scale_elements.append( + Line( + self.x0 + x_left, + tctr, + self.x0 + x_right, + tctr, + strokeColor=track.scale_color, + ) + ) + # Y-axis start marker + scale_elements.append( + Line( + self.x0 + x_left, + tbtm, + self.x0 + x_left, + ttop, + strokeColor=track.scale_color, + ) + ) + + start, end = self._current_track_start_end() + if track.scale_ticks: # Ticks are required on the scale + # Draw large ticks + # I want the ticks to be consistently positioned relative to + # the start of the sequence (position 0), not relative to the + # current viewpoint (self.start and self.end) + + ticklen = track.scale_largeticks * trackheight + tickiterval = int(track.scale_largetick_interval) + # Note that we could just start the list of ticks using + # range(0,self.end,tickinterval) and the filter out the + # ones before self.start - but this seems wasteful. + # Using tickiterval * (self.start//tickiterval) is a shortcut. + for tickpos in range( + tickiterval * (self.start // tickiterval), int(self.end), tickiterval + ): + if tickpos <= start or end <= tickpos: + continue + tick, label = self.draw_tick( + tickpos, ctr, ticklen, track, track.scale_largetick_labels + ) + scale_elements.append(tick) + if label is not None: # If there's a label, add it + scale_labels.append(label) + # Draw small ticks + ticklen = track.scale_smallticks * trackheight + tickiterval = int(track.scale_smalltick_interval) + for tickpos in range( + tickiterval * (self.start // tickiterval), int(self.end), tickiterval + ): + if tickpos <= start or end <= tickpos: + continue + tick, label = self.draw_tick( + tickpos, ctr, ticklen, track, track.scale_smalltick_labels + ) + scale_elements.append(tick) + if label is not None: # If there's a label, add it + scale_labels.append(label) + + # Check to see if the track contains a graph - if it does, get the + # minimum and maximum values, and put them on the scale Y-axis + if track.axis_labels: + for set in track.get_sets(): # Check all sets... + if set.__class__ is GraphSet: # ...for a graph set + graph_label_min = [] + graph_label_mid = [] + graph_label_max = [] + for graph in set.get_graphs(): + quartiles = graph.quartiles() + minval, maxval = quartiles[0], quartiles[4] + if graph.center is None: + midval = (maxval + minval) / 2.0 + graph_label_min.append(f"{minval:.3f}") + graph_label_max.append(f"{maxval:.3f}") + else: + diff = max((graph.center - minval), (maxval - graph.center)) + minval = graph.center - diff + maxval = graph.center + diff + midval = graph.center + graph_label_mid.append(f"{midval:.3f}") + graph_label_min.append(f"{minval:.3f}") + graph_label_max.append(f"{maxval:.3f}") + for fragment in range( + start_f, end_f + 1 + ): # Add to all used fragment axes + tbtm = btm + self.fragment_lines[fragment][0] + tctr = ctr + self.fragment_lines[fragment][0] + ttop = top + self.fragment_lines[fragment][0] + if fragment == start_f: + x_left = start_x + else: + x_left = 0 + for val, pos in [ + (";".join(graph_label_min), tbtm), + (";".join(graph_label_max), ttop), + (";".join(graph_label_mid), tctr), + ]: + label = String( + 0, + 0, + val, + fontName=track.scale_font, + fontSize=track.scale_fontsize, + fillColor=track.scale_color, + ) + labelgroup = Group(label) + rotation = angle2trig(track.scale_fontangle) + labelgroup.transform = ( + rotation[0], + rotation[1], + rotation[2], + rotation[3], + self.x0 + x_left, + pos, + ) + scale_labels.append(labelgroup) + + return scale_elements, scale_labels + + def draw_greytrack(self, track): + """Draw greytrack. + + Arguments: + - track Track object + + Put in a grey background to the current track in all fragments, + if track specifies that we should. + """ + greytrack_bgs = [] # Holds grey track backgrounds + greytrack_labels = [] # Holds grey foreground labels + + if not track.greytrack: # No greytrack required, return early + return [], [] + + # Get track location + btm, ctr, top = self.track_offsets[self.current_track_level] + + start, end = self._current_track_start_end() + start_fragment, start_offset = self.canvas_location(start) + end_fragment, end_offset = self.canvas_location(end) + + # Add greytrack to all fragments for this track + for fragment in range(start_fragment, end_fragment + 1): + tbtm = btm + self.fragment_lines[fragment][0] + tctr = ctr + self.fragment_lines[fragment][0] + ttop = top + self.fragment_lines[fragment][0] + if fragment == start_fragment: + x1 = self.x0 + start_offset + else: + x1 = self.x0 + if fragment == end_fragment: + x2 = self.x0 + end_offset + else: + x2 = self.xlim + box = draw_box( + (x1, tbtm), + (x2, ttop), + colors.Color(0.96, 0.96, 0.96), # Grey track bg + ) # is just a box + greytrack_bgs.append(box) + + if track.greytrack_labels: # If labels are required + # # how far apart should they be? + labelstep = self.pagewidth / track.greytrack_labels + label = String( + 0, + 0, + track.name, # label contents + fontName=track.greytrack_font, + fontSize=track.greytrack_fontsize, + fillColor=track.greytrack_fontcolor, + ) + # Create a new labelgroup at each position the label is required + for x in range(int(self.x0), int(self.xlim), int(labelstep)): + if fragment == start_fragment and x < start_offset: + continue + if ( + fragment == end_fragment + and end_offset < x + label.getBounds()[2] + ): + continue + labelgroup = Group(label) + rotation = angle2trig(track.greytrack_font_rotation) + labelgroup.transform = ( + rotation[0], + rotation[1], + rotation[2], + rotation[3], + x, + tbtm, + ) + if not self.xlim - x <= labelstep: + # Don't overlap the end of the track + greytrack_labels.append(labelgroup) + + return greytrack_bgs, greytrack_labels + + def draw_feature_set(self, set): + """Draw feature set. + + Arguments: + - set FeatureSet object + + Returns a tuple (list of elements describing features, list of + labels for elements). + """ + # print("draw feature set") + feature_elements = [] # Holds diagram elements belonging to the features + label_elements = [] # Holds diagram elements belonging to feature labels + + # Collect all the elements for the feature set + for feature in set.get_features(): + if self.is_in_bounds(feature.start) or self.is_in_bounds(feature.end): + features, labels = self.draw_feature(feature) # get elements and labels + feature_elements += features + label_elements += labels + + return feature_elements, label_elements + + def draw_feature(self, feature): + """Draw feature. + + Arguments: + - feature Feature containing location info + + Returns tuple of (list of elements describing single feature, list + of labels for those elements). + """ + if feature.hide: # Feature hidden, don't draw it... + return [], [] + + feature_elements = [] # Holds diagram elements belonging to the feature + label_elements = [] # Holds labels belonging to the feature + + start, end = self._current_track_start_end() + # A single feature may be split into subfeatures, so loop over them + for locstart, locend in feature.locations: + if locend < start: + continue + locstart = max(locstart, start) + if end < locstart: + continue + locend = min(locend, end) + feature_boxes = self.draw_feature_location(feature, locstart, locend) + for box, label in feature_boxes: + feature_elements.append(box) + if label is not None: + label_elements.append(label) + + return feature_elements, label_elements + + def draw_feature_location(self, feature, locstart, locend): + """Draw feature location.""" + feature_boxes = [] + # Get start and end positions for feature/subfeatures + start_fragment, start_offset = self.canvas_location(locstart) + end_fragment, end_offset = self.canvas_location(locend) + # print("start_fragment, start_offset", start_fragment, start_offset) + # print("end_fragment, end_offset", end_fragment, end_offset) + # print("start, end", locstart, locend) + + # Note that there is a strange situation where a feature may be in + # several parts, and one or more of those parts may end up being + # drawn on a non-existent fragment. So we check that the start and + # end fragments do actually exist in terms of the drawing + allowed_fragments = list(self.fragment_limits.keys()) + if start_fragment in allowed_fragments and end_fragment in allowed_fragments: + # print(feature.name, feature.start, feature.end, start_offset, end_offset) + if start_fragment == end_fragment: # Feature is found on one fragment + feature_box, label = self.get_feature_sigil( + feature, start_offset, end_offset, start_fragment + ) + feature_boxes.append((feature_box, label)) + # feature_elements.append(feature_box) + # if label is not None: # There is a label for the feature + # label_elements.append(label) + else: # Feature is split over two or more fragments + fragment = start_fragment + start = start_offset + # The bit that runs up to the end of the first fragment, + # and any bits that subsequently span whole fragments + while self.fragment_limits[fragment][1] < locend: + # print(fragment, self.fragment_limits[fragment][1], locend) + feature_box, label = self.get_feature_sigil( + feature, start, self.pagewidth, fragment + ) + + fragment += 1 # move to next fragment + start = 0 # start next sigil from start of fragment + feature_boxes.append((feature_box, label)) + # feature_elements.append(feature_box) + # if label is not None: # There's a label for the feature + # label_elements.append(label) + # The last bit of the feature + # print(locend, self.end, fragment) + # print(self.fragment_bases, self.length) + feature_box, label = self.get_feature_sigil( + feature, 0, end_offset, fragment + ) + feature_boxes.append((feature_box, label)) + # if locstart > locend: + # print(locstart, locend, feature.location.strand, feature_boxes, feature.name) + return feature_boxes + + def draw_cross_link(self, cross_link): + """Draw cross-link between two features.""" + startA = cross_link.startA + startB = cross_link.startB + endA = cross_link.endA + endB = cross_link.endB + + if not self.is_in_bounds(startA) and not self.is_in_bounds(endA): + return None + if not self.is_in_bounds(startB) and not self.is_in_bounds(endB): + return None + + if startA < self.start: + startA = self.start + if startB < self.start: + startB = self.start + if self.end < endA: + endA = self.end + if self.end < endB: + endB = self.end + + trackobjA = cross_link._trackA(list(self._parent.tracks.values())) + trackobjB = cross_link._trackB(list(self._parent.tracks.values())) + assert trackobjA is not None + assert trackobjB is not None + if trackobjA == trackobjB: + raise NotImplementedError + + if trackobjA.start is not None: + if endA < trackobjA.start: + return + startA = max(startA, trackobjA.start) + if trackobjA.end is not None: + if trackobjA.end < startA: + return + endA = min(endA, trackobjA.end) + if trackobjB.start is not None: + if endB < trackobjB.start: + return + startB = max(startB, trackobjB.start) + if trackobjB.end is not None: + if trackobjB.end < startB: + return + endB = min(endB, trackobjB.end) + + for track_level in self._parent.get_drawn_levels(): + track = self._parent[track_level] + if track == trackobjA: + trackA = track_level + if track == trackobjB: + trackB = track_level + if trackA == trackB: + raise NotImplementedError + + strokecolor, fillcolor = _stroke_and_fill_colors( + cross_link.color, cross_link.border + ) + + allowed_fragments = list(self.fragment_limits.keys()) + + start_fragmentA, start_offsetA = self.canvas_location(startA) + end_fragmentA, end_offsetA = self.canvas_location(endA) + if ( + start_fragmentA not in allowed_fragments + or end_fragmentA not in allowed_fragments + ): + return + + start_fragmentB, start_offsetB = self.canvas_location(startB) + end_fragmentB, end_offsetB = self.canvas_location(endB) + if ( + start_fragmentB not in allowed_fragments + or end_fragmentB not in allowed_fragments + ): + return + + # TODO - Better drawing of flips when split between fragments + + answer = [] + for fragment in range( + min(start_fragmentA, start_fragmentB), max(end_fragmentA, end_fragmentB) + 1 + ): + btmA, ctrA, topA = self.track_offsets[trackA] + btmA += self.fragment_lines[fragment][0] + ctrA += self.fragment_lines[fragment][0] + topA += self.fragment_lines[fragment][0] + + btmB, ctrB, topB = self.track_offsets[trackB] + btmB += self.fragment_lines[fragment][0] + ctrB += self.fragment_lines[fragment][0] + topB += self.fragment_lines[fragment][0] + + if self.fragment_limits[fragment][1] < endA: + xAe = self.x0 + self.pagewidth + crop_rightA = True + else: + xAe = self.x0 + end_offsetA + crop_rightA = False + if self.fragment_limits[fragment][1] < endB: + xBe = self.x0 + self.pagewidth + crop_rightB = True + else: + xBe = self.x0 + end_offsetB + crop_rightB = False + + if fragment < start_fragmentA: + xAs = self.x0 + self.pagewidth + xAe = xAs + crop_leftA = False + elif fragment == start_fragmentA: + xAs = self.x0 + start_offsetA + crop_leftA = False + else: + xAs = self.x0 + crop_leftA = True + + if fragment < start_fragmentB: + xBs = self.x0 + self.pagewidth + xBe = xBs + crop_leftB = False + elif fragment == start_fragmentB: + xBs = self.x0 + start_offsetB + crop_leftB = False + else: + xBs = self.x0 + crop_leftB = True + + if ctrA < ctrB: + yA = topA + yB = btmB + else: + yA = btmA + yB = topB + + if fragment < start_fragmentB or end_fragmentB < fragment: + if cross_link.flip: + # Just draw A as a triangle to left/right + if fragment < start_fragmentB: + extra = [self.x0 + self.pagewidth, 0.5 * (yA + yB)] + else: + extra = [self.x0, 0.5 * (yA + yB)] + else: + if fragment < start_fragmentB: + extra = [ + self.x0 + self.pagewidth, + 0.7 * yA + 0.3 * yB, + self.x0 + self.pagewidth, + 0.3 * yA + 0.7 * yB, + ] + else: + extra = [ + self.x0, + 0.3 * yA + 0.7 * yB, + self.x0, + 0.7 * yA + 0.3 * yB, + ] + answer.append( + Polygon( + deduplicate([xAs, yA, xAe, yA] + extra), + strokeColor=strokecolor, + fillColor=fillcolor, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + ) + elif fragment < start_fragmentA or end_fragmentA < fragment: + if cross_link.flip: + # Just draw B as a triangle to left + if fragment < start_fragmentA: + extra = [self.x0 + self.pagewidth, 0.5 * (yA + yB)] + else: + extra = [self.x0, 0.5 * (yA + yB)] + else: + if fragment < start_fragmentA: + extra = [ + self.x0 + self.pagewidth, + 0.3 * yA + 0.7 * yB, + self.x0 + self.pagewidth, + 0.7 * yA + 0.3 * yB, + ] + else: + extra = [ + self.x0, + 0.7 * yA + 0.3 * yB, + self.x0, + 0.3 * yA + 0.7 * yB, + ] + answer.append( + Polygon( + deduplicate([xBs, yB, xBe, yB] + extra), + strokeColor=strokecolor, + fillColor=fillcolor, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + ) + elif cross_link.flip and ( + (crop_leftA and not crop_rightA) or (crop_leftB and not crop_rightB) + ): + # On left end of fragment... force "crossing" to margin + answer.append( + Polygon( + deduplicate( + [ + xAs, + yA, + xAe, + yA, + self.x0, + 0.5 * (yA + yB), + xBe, + yB, + xBs, + yB, + ] + ), + strokeColor=strokecolor, + fillColor=fillcolor, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + ) + elif cross_link.flip and ( + (crop_rightA and not crop_leftA) or (crop_rightB and not crop_leftB) + ): + # On right end... force "crossing" to margin + answer.append( + Polygon( + deduplicate( + [ + xAs, + yA, + xAe, + yA, + xBe, + yB, + xBs, + yB, + self.x0 + self.pagewidth, + 0.5 * (yA + yB), + ] + ), + strokeColor=strokecolor, + fillColor=fillcolor, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + ) + elif cross_link.flip: + answer.append( + Polygon( + deduplicate([xAs, yA, xAe, yA, xBs, yB, xBe, yB]), + strokeColor=strokecolor, + fillColor=fillcolor, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + ) + else: + answer.append( + Polygon( + deduplicate([xAs, yA, xAe, yA, xBe, yB, xBs, yB]), + strokeColor=strokecolor, + fillColor=fillcolor, + # default is mitre/miter which can stick out too much: + strokeLineJoin=1, # 1=round + strokewidth=0, + ) + ) + return answer + + def get_feature_sigil(self, feature, x0, x1, fragment, **kwargs): + """Get feature sigil. + + Arguments: + - feature Feature object + - x0 Start X coordinate on diagram + - x1 End X coordinate on diagram + - fragment The fragment on which the feature appears + + Returns a drawable indicator of the feature, and any required label + for it. + """ + # Establish coordinates for drawing + x0, x1 = self.x0 + x0, self.x0 + x1 + btm, ctr, top = self.track_offsets[self.current_track_level] + try: + btm += self.fragment_lines[fragment][0] + ctr += self.fragment_lines[fragment][0] + top += self.fragment_lines[fragment][0] + except Exception: # Only called if the method screws up big time + print("We've got a screw-up") + print(f"{self.start} {self.end}") + print(self.fragment_bases) + print(f"{x0!r} {x1!r}") + for locstart, locend in feature.locations: + print(self.canvas_location(locstart)) + print(self.canvas_location(locend)) + print(f"FEATURE\n{feature}") + raise + + # Distribution dictionary for various ways of drawing the feature + draw_methods = { + "BOX": self._draw_sigil_box, + "ARROW": self._draw_sigil_arrow, + "BIGARROW": self._draw_sigil_big_arrow, + "OCTO": self._draw_sigil_octo, + "JAGGY": self._draw_sigil_jaggy, + } + + method = draw_methods[feature.sigil] + kwargs["head_length_ratio"] = feature.arrowhead_length + kwargs["shaft_height_ratio"] = feature.arrowshaft_height + + # Support for clickable links... needs ReportLab 2.4 or later + # which added support for links in SVG output. + if hasattr(feature, "url"): + kwargs["hrefURL"] = feature.url + kwargs["hrefTitle"] = feature.name + + # Get sigil for the feature, give it the bounding box straddling + # the axis (it decides strand specific placement) + sigil = method( + btm, + ctr, + top, + x0, + x1, + strand=feature.location.strand, + color=feature.color, + border=feature.border, + **kwargs, + ) + + if feature.label_strand: + strand = feature.label_strand + else: + strand = feature.location.strand + if feature.label: # Feature requires a label + label = String( + 0, + 0, + feature.name, + fontName=feature.label_font, + fontSize=feature.label_size, + fillColor=feature.label_color, + ) + labelgroup = Group(label) + # Feature is on top, or covers both strands (location affects + # the height and rotation of the label) + if strand != -1: + rotation = angle2trig(feature.label_angle) + if feature.label_position in ("end", "3'", "right"): + pos = x1 + elif feature.label_position in ("middle", "center", "centre"): + pos = (x1 + x0) / 2.0 + else: + # Default to start, i.e. 'start', "5'", 'left' + pos = x0 + labelgroup.transform = ( + rotation[0], + rotation[1], + rotation[2], + rotation[3], + pos, + top, + ) + else: # Feature on bottom strand + rotation = angle2trig(feature.label_angle + 180) + if feature.label_position in ("end", "3'", "right"): + pos = x0 + elif feature.label_position in ("middle", "center", "centre"): + pos = (x1 + x0) / 2.0 + else: + # Default to start, i.e. 'start', "5'", 'left' + pos = x1 + labelgroup.transform = ( + rotation[0], + rotation[1], + rotation[2], + rotation[3], + pos, + btm, + ) + else: + labelgroup = None + return sigil, labelgroup + + def draw_graph_set(self, set): + """Draw graph set. + + Arguments: + - set GraphSet object + + Returns tuple (list of graph elements, list of graph labels). + """ + # print('draw graph set') + elements = [] # Holds graph elements + + # Distribution dictionary for how to draw the graph + style_methods = { + "line": self.draw_line_graph, + "heat": self.draw_heat_graph, + "bar": self.draw_bar_graph, + } + + for graph in set.get_graphs(): + elements += style_methods[graph.style](graph) + + return elements, [] + + def draw_line_graph(self, graph): + """Return a line graph as a list of drawable elements. + + Arguments: + - graph Graph object + + """ + # print('\tdraw_line_graph') + line_elements = [] # Holds drawable elements + + # Get graph data + data_quartiles = graph.quartiles() + minval, maxval = data_quartiles[0], data_quartiles[4] + btm, ctr, top = self.track_offsets[self.current_track_level] + trackheight = 0.5 * (top - btm) + datarange = maxval - minval + if datarange == 0: + datarange = trackheight + + start, end = self._current_track_start_end() + data = graph[start:end] + + # midval is the value at which the x-axis is plotted, and is the + # central ring in the track + if graph.center is None: + midval = (maxval + minval) / 2.0 + else: + midval = graph.center + # Whichever is the greatest difference: max-midval or min-midval, is + # taken to specify the number of pixel units resolved along the + # y-axis + resolution = max((midval - minval), (maxval - midval)) + + # Start from first data point + pos, val = data[0] + lastfrag, lastx = self.canvas_location(pos) + lastx += self.x0 # Start xy co-ords + lasty = ( + trackheight * (val - midval) / resolution + + self.fragment_lines[lastfrag][0] + + ctr + ) + lastval = val + # Add a series of lines linking consecutive data points + for pos, val in data: + frag, x = self.canvas_location(pos) + x += self.x0 # next xy co-ords + y = ( + trackheight * (val - midval) / resolution + + self.fragment_lines[frag][0] + + ctr + ) + if frag == lastfrag: # Points on the same fragment: draw the line + line_elements.append( + Line( + lastx, + lasty, + x, + y, + strokeColor=graph.poscolor, + strokeWidth=graph.linewidth, + ) + ) + else: # Points not on the same fragment, so interpolate + tempy = ( + trackheight * (val - midval) / resolution + + self.fragment_lines[lastfrag][0] + + ctr + ) + line_elements.append( + Line( + lastx, + lasty, + self.xlim, + tempy, + strokeColor=graph.poscolor, + strokeWidth=graph.linewidth, + ) + ) + tempy = ( + trackheight * (val - midval) / resolution + + self.fragment_lines[frag][0] + + ctr + ) + line_elements.append( + Line( + self.x0, + tempy, + x, + y, + strokeColor=graph.poscolor, + strokeWidth=graph.linewidth, + ) + ) + lastfrag, lastx, lasty, lastval = frag, x, y, val + + return line_elements + + def draw_heat_graph(self, graph): + """Return a list of drawable elements for the heat graph.""" + # print('\tdraw_heat_graph') + # At each point contained in the graph data, we draw a box that is the + # full height of the track, extending from the midpoint between the + # previous and current data points to the midpoint between the current + # and next data points + heat_elements = [] # Holds drawable elements for the graph + + # Get graph data and information + data_quartiles = graph.quartiles() + minval, maxval = data_quartiles[0], data_quartiles[4] + midval = (maxval + minval) / 2.0 # mid is the value at the X-axis + btm, ctr, top = self.track_offsets[self.current_track_level] + trackheight = top - btm + + start, end = self._current_track_start_end() + data = intermediate_points(start, end, graph[start:end]) + + if not data: + return [] + + # Create elements on the graph, indicating a large positive value by + # the graph's poscolor, and a large negative value by the graph's + # negcolor attributes + for pos0, pos1, val in data: + # assert start <= pos0 <= pos1 <= end + fragment0, x0 = self.canvas_location(pos0) + fragment1, x1 = self.canvas_location(pos1) + x0, x1 = self.x0 + x0, self.x0 + x1 # account for margin + # print('x1 before:', x1) + + # Calculate the heat color, based on the differential between + # the value and the median value + heat = colors.linearlyInterpolatedColor( + graph.poscolor, graph.negcolor, maxval, minval, val + ) + + # Draw heat box + if fragment0 == fragment1: # Box is contiguous on one fragment + if pos1 >= self.fragment_limits[fragment0][1]: + x1 = self.xlim + ttop = top + self.fragment_lines[fragment0][0] + tbtm = btm + self.fragment_lines[fragment0][0] + # print('equal', pos0, pos1, val) + # print(pos0, pos1, fragment0, fragment1) + heat_elements.append( + draw_box((x0, tbtm), (x1, ttop), color=heat, border=None) + ) + else: # box is split over two or more fragments + # if pos0 >= self.fragment_limits[fragment0][0]: + # fragment0 += 1 + fragment = fragment0 + start_x = x0 + while self.fragment_limits[fragment][1] <= pos1: + # print(pos0, self.fragment_limits[fragment][1], pos1) + ttop = top + self.fragment_lines[fragment][0] + tbtm = btm + self.fragment_lines[fragment][0] + heat_elements.append( + draw_box( + (start_x, tbtm), (self.xlim, ttop), color=heat, border=None + ) + ) + fragment += 1 + start_x = self.x0 + ttop = top + self.fragment_lines[fragment][0] + tbtm = btm + self.fragment_lines[fragment][0] + # Add the last part of the bar + # print('x1 after:', x1, '\n') + heat_elements.append( + draw_box((self.x0, tbtm), (x1, ttop), color=heat, border=None) + ) + + return heat_elements + + def draw_bar_graph(self, graph): + """Return list of drawable elements for a bar graph.""" + # print('\tdraw_bar_graph') + # At each point contained in the graph data, we draw a vertical bar + # from the track center to the height of the datapoint value (positive + # values go up in one color, negative go down in the alternative + # color). + bar_elements = [] # Holds drawable elements for the graph + + # Set the number of pixels per unit for the data + data_quartiles = graph.quartiles() + minval, maxval = data_quartiles[0], data_quartiles[4] + btm, ctr, top = self.track_offsets[self.current_track_level] + trackheight = 0.5 * (top - btm) + datarange = maxval - minval + if datarange == 0: + datarange = trackheight + data = graph[self.start : self.end] + # midval is the value at which the x-axis is plotted, and is the + # central ring in the track + if graph.center is None: + midval = (maxval + minval) / 2.0 + else: + midval = graph.center + + # Convert data into 'binned' blocks, covering half the distance to the + # next data point on either side, accounting for the ends of fragments + # and tracks + start, end = self._current_track_start_end() + data = intermediate_points(start, end, graph[start:end]) + + if not data: + return [] + + # Whichever is the greatest difference: max-midval or min-midval, is + # taken to specify the number of pixel units resolved along the + # y-axis + resolution = max((midval - minval), (maxval - midval)) + if resolution == 0: + resolution = trackheight + + # Create elements for the bar graph based on newdata + for pos0, pos1, val in data: + fragment0, x0 = self.canvas_location(pos0) + fragment1, x1 = self.canvas_location(pos1) + x0, x1 = self.x0 + x0, self.x0 + x1 # account for margin + barval = trackheight * (val - midval) / resolution + if barval >= 0: # Different colors for bars that extend above... + barcolor = graph.poscolor + else: # ...or below the axis + barcolor = graph.negcolor + + # Draw bar + if fragment0 == fragment1: # Box is contiguous + if pos1 >= self.fragment_limits[fragment0][1]: + x1 = self.xlim + tctr = ctr + self.fragment_lines[fragment0][0] + barval += tctr + bar_elements.append(draw_box((x0, tctr), (x1, barval), color=barcolor)) + else: # Box is split over two or more fragments + fragment = fragment0 + # if pos0 >= self.fragment_limits[fragment0][0]: + # fragment += 1 + start = x0 + while self.fragment_limits[fragment][1] < pos1: + tctr = ctr + self.fragment_lines[fragment][0] + thisbarval = barval + tctr + bar_elements.append( + draw_box((start, tctr), (self.xlim, thisbarval), color=barcolor) + ) + fragment += 1 + start = self.x0 + tctr = ctr + self.fragment_lines[fragment1][0] + barval += tctr + # Add the last part of the bar + bar_elements.append( + draw_box((self.x0, tctr), (x1, barval), color=barcolor) + ) + + return bar_elements + + def canvas_location(self, base): + """Canvas location of a base on the genome. + + Arguments: + - base The base number on the genome sequence + + Returns the x-coordinate and fragment number of a base on the + genome sequence, in the context of the current drawing setup + """ + base = int(base - self.start) # number of bases we are from the start + fragment = int(base / self.fragment_bases) + if fragment < 1: # First fragment + base_offset = base + fragment = 0 + elif fragment >= self.fragments: + fragment = self.fragments - 1 + base_offset = self.fragment_bases + else: # Calculate number of bases from start of fragment + base_offset = base % self.fragment_bases + assert fragment < self.fragments, ( + base, + self.start, + self.end, + self.length, + self.fragment_bases, + ) + # Calculate number of pixels from start of fragment + x_offset = self.pagewidth * base_offset / self.fragment_bases + return fragment, x_offset + + def _draw_sigil_box(self, bottom, center, top, x1, x2, strand, **kwargs): + """Draw BOX sigil (PRIVATE).""" + if strand == 1: + y1 = center + y2 = top + elif strand == -1: + y1 = bottom + y2 = center + else: + y1 = bottom + y2 = top + return draw_box((x1, y1), (x2, y2), **kwargs) + + def _draw_sigil_octo(self, bottom, center, top, x1, x2, strand, **kwargs): + """Draw OCTO sigil, a box with the corners cut off (PRIVATE).""" + if strand == 1: + y1 = center + y2 = top + elif strand == -1: + y1 = bottom + y2 = center + else: + y1 = bottom + y2 = top + return draw_cut_corner_box((x1, y1), (x2, y2), **kwargs) + + def _draw_sigil_jaggy( + self, bottom, center, top, x1, x2, strand, color, border=None, **kwargs + ): + """Draw JAGGY sigil (PRIVATE). + + Although we may in future expose the head/tail jaggy lengths, for now + both the left and right edges are drawn jagged. + """ + if strand == 1: + y1 = center + y2 = top + teeth = 2 + elif strand == -1: + y1 = bottom + y2 = center + teeth = 2 + else: + y1 = bottom + y2 = top + teeth = 4 + + xmin = min(x1, x2) + xmax = max(x1, x2) + height = y2 - y1 + boxwidth = x2 - x1 + tooth_length = min(height / teeth, boxwidth * 0.5) + + headlength = tooth_length + taillength = tooth_length + + strokecolor, color = _stroke_and_fill_colors(color, border) + + points = [] + for i in range(teeth): + points.extend( + ( + xmin, + y1 + i * height / teeth, + xmin + taillength, + y1 + (i + 1) * height / teeth, + ) + ) + for i in range(teeth): + points.extend( + ( + xmax, + y1 + (teeth - i) * height / teeth, + xmax - headlength, + y1 + (teeth - i - 1) * height / teeth, + ) + ) + + return Polygon( + deduplicate(points), + strokeColor=strokecolor, + strokeWidth=1, + strokeLineJoin=1, # 1=round + fillColor=color, + **kwargs, + ) + + def _draw_sigil_arrow(self, bottom, center, top, x1, x2, strand, **kwargs): + """Draw ARROW sigil (PRIVATE).""" + if strand == 1: + y1 = center + y2 = top + orientation = "right" + elif strand == -1: + y1 = bottom + y2 = center + orientation = "left" + else: + y1 = bottom + y2 = top + orientation = "right" # backward compatibility + return draw_arrow((x1, y1), (x2, y2), orientation=orientation, **kwargs) + + def _draw_sigil_big_arrow(self, bottom, center, top, x1, x2, strand, **kwargs): + """Draw BIGARROW sigil, like ARROW but straddles the axis (PRIVATE).""" + if strand == -1: + orientation = "left" + else: + orientation = "right" + return draw_arrow((x1, bottom), (x2, top), orientation=orientation, **kwargs) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Track.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Track.py new file mode 100644 index 0000000000000000000000000000000000000000..1db922f49a62d76c2ed5a1b238280a72a34f292e --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/_Track.py @@ -0,0 +1,284 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +################################################################################ + +"""Track module. + +Provides: + - Track - Container for a single track on the diagram, containing + FeatureSet and GraphSet objects + +For drawing capabilities, this module uses reportlab to draw and write +the diagram: http://www.reportlab.com +""" + +from reportlab.lib import colors + +# GenomeDiagram imports +from ._FeatureSet import FeatureSet +from ._GraphSet import GraphSet + +_grey = colors.Color(0.6, 0.6, 0.6) + + +class Track: + """Track. + + Attributes: + - height Int describing the relative height to other trackscale_fontsizes + in the diagram + - name String describing the track + - hide Boolean, 0 if the track is not to be drawn + - start, end Integers (or None) specifying start/end to draw just + a partial track. + - greytrack Boolean, 1 if a grey background to the track is to be + drawn + - greytrack_labels Int describing how many track-identifying labels + should be placed on the track at regular intervals + - greytrack_font String describing the font to use for the greytrack + labels + - greytrack_fontsize Int describing the font size to display the + labels on the grey track + - greytrack_font_rotation Int describing the angle through which to + rotate the grey track labels (Linear only) + - greytrack_font_color colors.Color describing the color to draw + the grey track labels + - scale Boolean, 1 if a scale is to be drawn on the track + - scale_format String, defaults to None, when scale values are written + as numerals. Setting this to 'SInt' invokes SI + unit-like multiples, such as Mbp, Kbp and so on. + - scale_color colors.Color to draw the elements of the scale + - scale_font String describing the font to use for the scale labels + - scale_fontsize Int describing the size of the scale label font + - scale_fontangle Int describing the angle at which to draw the scale + labels (linear only) + - scale_ticks Boolean, 1 if ticks should be drawn at all on the + scale + - scale_largeticks Float (0->1) describing the height of large + scale ticks relative to the track height. + - scale_smallticks Float (0->1) describing the height of large + scale ticks relative to the track height. + - scale_largetick_interval Int, describing the number of bases that + should separate large ticks + - scale_smalltick_interval Int, describing the number of bases that + should separate small ticks + - scale_largetick_labels Boolean describing whether position labels + should be written over large ticks + - scale_smalltick_labels Boolean describing whether position labels + should be written over small ticks + - axis_labels Boolean describing whether the value labels should + be placed on the Y axes + + """ + + def __init__( + self, + name=None, + height=1, + hide=0, + greytrack=0, + greytrack_labels=5, + greytrack_fontsize=8, + greytrack_font="Helvetica", + greytrack_font_rotation=0, + greytrack_font_color=_grey, + scale=1, + scale_format=None, + scale_color=colors.black, + scale_font="Helvetica", + scale_fontsize=6, + scale_fontangle=45, + scale_largeticks=0.5, + scale_ticks=1, + scale_smallticks=0.3, + scale_largetick_interval=1e6, + scale_smalltick_interval=1e4, + scale_largetick_labels=1, + scale_smalltick_labels=0, + axis_labels=1, + start=None, + end=None, + greytrack_font_colour=None, + scale_colour=None, + ): + """Initialize. + + Arguments: + - height Int describing the relative height to other tracks in the + diagram + - name String describing the track + - hide Boolean, 0 if the track is not to be drawn + - greytrack Boolean, 1 if a grey background to the track is to be + drawn + - greytrack_labels Int describing how many track-identifying labels + should be placed on the track at regular intervals + - greytrack_font String describing the font to use for the greytrack + labels + - greytrack_fontsize Int describing the font size to display the + labels on the grey track + - greytrack_font_rotation Int describing the angle through which to + rotate the grey track labels (Linear only) + - greytrack_font_color colors.Color describing the color to draw + the grey track labels (overridden by backwards compatible argument + with UK spelling, colour). + - scale Boolean, 1 if a scale is to be drawn on the track + - scale_color colors.Color to draw the elements of the scale + (overridden by backwards compatible argument with UK + spelling, colour). + - scale_font String describing the font to use for the scale labels + - scale_fontsize Int describing the size of the scale label font + - scale_fontangle Int describing the angle at which to draw the scale + labels (linear only) + - scale_ticks Boolean, 1 if ticks should be drawn at all on the + scale + - scale_largeticks Float (0->1) describing the height of large + scale ticks relative to the track height. + - scale_smallticks Float (0->1) describing the height of large + scale ticks relative to the track height. + - scale_largetick_interval Int, describing the number of bases that + should separate large ticks + - scale_smalltick_interval Int, describing the number of bases that + should separate small ticks + - scale_largetick_labels Boolean describing whether position labels + should be written over large ticks + - scale_smalltick_labels Boolean describing whether position labels + should be written over small ticks + - name String to help identify the track + - height Relative height to draw the track + - axis_labels Boolean describing whether the value labels should + be placed on the Y axes + + """ + # Let the UK spelling (colour) override the USA spelling (color) + if greytrack_font_colour is not None: + greytrack_font_color = greytrack_font_colour + if scale_colour is not None: + scale_color = scale_colour + + self._next_id = 0 # This will count sets as they are added to the track + self._sets = {} # Holds sets, keyed by unique ID + + # Assign attribute values from instantiation + self.height = height + if name is not None: + self.name = str(name) + else: + self.name = "Track" + self.hide = hide + self.start = start + self.end = end + + # Attributes for the grey track background and labels + self.greytrack = greytrack + self.greytrack_labels = greytrack_labels + self.greytrack_fontsize = greytrack_fontsize + self.greytrack_font = greytrack_font + self.greytrack_font_rotation = greytrack_font_rotation + self.greytrack_fontcolor = greytrack_font_color + + # Attributes for the track scale + self.scale = scale + self.scale_format = scale_format + self.scale_color = scale_color + self.scale_font = scale_font + self.scale_fontsize = scale_fontsize + self.scale_fontangle = scale_fontangle + self.scale_ticks = scale_ticks + self.scale_largeticks = scale_largeticks + self.scale_smallticks = scale_smallticks + self.scale_largetick_interval = scale_largetick_interval + self.scale_smalltick_interval = scale_smalltick_interval + self.scale_largetick_labels = scale_largetick_labels + self.scale_smalltick_labels = scale_smalltick_labels + self.axis_labels = axis_labels + + def add_set(self, set): + """Add a preexisting FeatureSet or GraphSet object to the track.""" + set.id = self._next_id # Assign unique id to set + set.parent = self # Make set's parent this track + self._sets[self._next_id] = set # Add set, keyed by unique id + self._next_id += 1 # Increment unique set ids + + def new_set(self, type="feature", **args): + """Create a new FeatureSet or GraphSet object. + + Create a new FeatureSet or GraphSet object, add it to the + track, and return for user manipulation + """ + type_dict = {"feature": FeatureSet, "graph": GraphSet} + set = type_dict[type]() + for key in args: + setattr(set, key, args[key]) + set.id = self._next_id # Assign unique id to set + set.parent = self # Make set's parent this track + self._sets[self._next_id] = set # Add set, keyed by unique id + self._next_id += 1 # Increment unique set ids + return set + + def del_set(self, set_id): + """Remove the set with the passed id from the track.""" + del self._sets[set_id] + + def get_sets(self): + """Return the sets contained in this track.""" + return list(self._sets.values()) + + def get_ids(self): + """Return the ids of all sets contained in this track.""" + return list(self._sets.keys()) + + def range(self): + """Return the lowest and highest base (or mark) numbers as a tuple.""" + lows, highs = [], [] # Holds set of low and high values from sets + if self.start is not None: + lows.append(self.start) + if self.end is not None: + highs.append(self.end) + for set in self._sets.values(): + low, high = set.range() # Get each set range + lows.append(low) + highs.append(high) + if lows: + low = min(lows) + else: + low = None + if highs: + high = max(highs) + else: + high = None + return low, high # Return lowest and highest values + + def to_string(self, verbose=0): + """Return a formatted string with information about the track. + + Arguments: + - verbose - Boolean indicating whether a short or complete + account of the track is required + + """ + if not verbose: # Return the short description + return f"{self}" # Use __str__ method instead + else: # Return the long description + outstr = [f"\n<{self.__class__}: {self.name}>"] + outstr.append("%d sets" % len(self._sets)) + for key in self._sets: + outstr.append(f"set: {self._sets[key]}") + return "\n".join(outstr) + + def __getitem__(self, key): + """Return the set with the passed id.""" + return self._sets[key] + + def __str__(self): + """Return a formatted string with information about the Track.""" + outstr = [f"\n<{self.__class__}: {self.name}>"] + outstr.append("%d sets" % len(self._sets)) + return "\n".join(outstr) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1712a4ab7a39ded55a67b5d1f420ef28bb12f801 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/GenomeDiagram/__init__.py @@ -0,0 +1,37 @@ +# Copyright 2003-2008 by Leighton Pritchard. All rights reserved. +# Revisions copyright 2009 by Peter Cock. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +# +# Contact: Leighton Pritchard, The James Hutton Institute, +# Invergowrie, Dundee, Scotland, DD2 5DA, UK +# Leighton.Pritchard@hutton.ac.uk +# ############################################################################# + +"""GenomeDiagram module integrated into Biopython.""" + +# Local imports, to make these classes available directly under the +# Bio.Graphics.GenomeDiagram namespace: + +from ._Colors import ColorTranslator +from ._CrossLink import CrossLink +from ._Diagram import Diagram +from ._Feature import Feature +from ._FeatureSet import FeatureSet +from ._Graph import GraphData +from ._GraphSet import GraphSet +from ._Track import Track + +__all__ = ( + "Diagram", + "Track", + "FeatureSet", + "Feature", + "GraphSet", + "GraphData", + "CrossLink", + "ColorTranslator", +) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/KGML_vis.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/KGML_vis.py new file mode 100644 index 0000000000000000000000000000000000000000..12f9608356b4c55867b57d5a53da1bb02600a40a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/KGML_vis.py @@ -0,0 +1,442 @@ +# Copyright 2013 Leighton Pritchard. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Classes and functions to visualise a KGML Pathway Map. + +The KGML definition is as of release KGML v0.7.1 +(http://www.kegg.jp/kegg/xml/docs/) + +Classes: +""" + +import os +import tempfile +from io import BytesIO + +try: + from reportlab.lib import colors + from reportlab.pdfgen import canvas +except ImportError: + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Install reportlab if you want to use KGML_vis." + ) from None + +try: + from PIL import Image +except ImportError: + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Install pillow if you want to use KGML_vis." + ) from None + +from urllib.request import urlopen + +from Bio.KEGG.KGML.KGML_pathway import Pathway + + +def darken(color, factor=0.7): + """Return darkened color as a ReportLab RGB color. + + Take a passed color and returns a Reportlab color that is darker by the + factor indicated in the parameter. + """ + newcol = color_to_reportlab(color) + for a in ["red", "green", "blue"]: + setattr(newcol, a, factor * getattr(newcol, a)) + return newcol + + +def color_to_reportlab(color): + """Return the passed color in Reportlab Color format. + + We allow colors to be specified as hex values, tuples, or Reportlab Color + objects, and with or without an alpha channel. This function acts as a + Rosetta stone for conversion of those formats to a Reportlab Color + object, with alpha value. + + Any other color specification is returned directly + """ + # Reportlab Color objects are in the format we want already + if isinstance(color, colors.Color): + return color + elif isinstance(color, str): # String implies hex color + if color.startswith("0x"): # Standardise to octothorpe + color.replace("0x", "#") + if len(color) == 7: + return colors.HexColor(color) + else: + try: + return colors.HexColor(color, hasAlpha=True) + except TypeError: # Catch pre-2.7 Reportlab + raise RuntimeError( + "Your reportlab seems to be too old, try 2.7 onwards" + ) from None + elif isinstance(color, tuple): # Tuple implies RGB(alpha) tuple + return colors.Color(*color) + return color + + +def get_temp_imagefilename(url): + """Return filename of temporary file containing downloaded image. + + Create a new temporary file to hold the image file at the passed URL + and return the filename. + """ + img = urlopen(url).read() + im = Image.open(BytesIO(img)) + # im.transpose(Image.FLIP_TOP_BOTTOM) + f = tempfile.NamedTemporaryFile(delete=False, suffix=".png") + fname = f.name + f.close() + im.save(fname, "PNG") + return fname + + +class KGMLCanvas: + """Reportlab Canvas-based representation of a KGML pathway map.""" + + def __init__( + self, + pathway, + import_imagemap=False, + label_compounds=True, + label_orthologs=True, + label_reaction_entries=True, + label_maps=True, + show_maps=False, + fontname="Helvetica", + fontsize=6, + draw_relations=True, + show_orthologs=True, + show_compounds=True, + show_genes=True, + show_reaction_entries=True, + margins=(0.02, 0.02), + ): + """Initialize the class.""" + self.pathway = pathway + self.show_maps = show_maps + self.show_orthologs = show_orthologs + self.show_compounds = show_compounds + self.show_genes = show_genes + self.show_reaction_entries = show_reaction_entries + self.label_compounds = label_compounds + self.label_orthologs = label_orthologs + self.label_reaction_entries = label_reaction_entries + self.label_maps = label_maps + self.fontname = fontname + self.fontsize = fontsize + self.draw_relations = draw_relations + self.non_reactant_transparency = 0.3 + self.import_imagemap = import_imagemap # Import the map .png from URL + # percentage of canvas that will be margin in on either side in the + # X and Y directions + self.margins = margins + + def draw(self, filename): + """Add the map elements to the drawing.""" + # Instantiate the drawing, first + # size x_max, y_max for now - we can add margins, later + if self.import_imagemap: + # We're drawing directly on the image, so we set the canvas to the + # same size as the image + if os.path.isfile(self.pathway.image): + imfilename = self.pathway.image + else: + imfilename = get_temp_imagefilename(self.pathway.image) + im = Image.open(imfilename) + cwidth, cheight = im.size + else: + # No image, so we set the canvas size to accommodate visible + # elements + cwidth, cheight = (self.pathway.bounds[1][0], self.pathway.bounds[1][1]) + # Instantiate canvas + self.drawing = canvas.Canvas( + filename, + bottomup=0, + pagesize=( + cwidth * (1 + 2 * self.margins[0]), + cheight * (1 + 2 * self.margins[1]), + ), + ) + self.drawing.setFont(self.fontname, self.fontsize) + # Transform the canvas to add the margins + self.drawing.translate( + self.margins[0] * self.pathway.bounds[1][0], + self.margins[1] * self.pathway.bounds[1][1], + ) + # Add the map image, if required + if self.import_imagemap: + self.drawing.saveState() + self.drawing.scale(1, -1) + self.drawing.translate(0, -cheight) + self.drawing.drawImage(imfilename, 0, 0) + self.drawing.restoreState() + # Add the reactions, compounds and maps + # Maps go on first, to be overlaid by more information. + # By default, they're slightly transparent. + if self.show_maps: + self.__add_maps() + if self.show_reaction_entries: + self.__add_reaction_entries() + if self.show_orthologs: + self.__add_orthologs() + if self.show_compounds: + self.__add_compounds() + if self.show_genes: + self.__add_genes() + # TODO: complete draw_relations code + # if self.draw_relations: + # self.__add_relations() + # Write the pathway map to PDF + self.drawing.save() + + def __add_maps(self): + """Add maps to the drawing of the map (PRIVATE). + + We do this first, as they're regional labels to be overlaid by + information. Also, we want to set the color to something subtle. + + We're using Hex colors because that's what KGML uses, and + Reportlab doesn't mind. + """ + for m in self.pathway.maps: + for g in m.graphics: + self.drawing.setStrokeColor("#888888") + self.drawing.setFillColor("#DDDDDD") + self.__add_graphics(g) + if self.label_maps: + self.drawing.setFillColor("#888888") + self.__add_labels(g) + + def __add_graphics(self, graphics): + """Add the passed graphics object to the map (PRIVATE). + + Add text, add after the graphics object, for sane Z-ordering. + """ + if graphics.type == "line": + p = self.drawing.beginPath() + x, y = graphics.coords[0] + # There are optional settings for lines that aren't necessarily + # part of the KGML DTD + if graphics.width is not None: + self.drawing.setLineWidth(graphics.width) + else: + self.drawing.setLineWidth(1) + p.moveTo(x, y) + for x, y in graphics.coords: + p.lineTo(x, y) + self.drawing.drawPath(p) + self.drawing.setLineWidth(1) # Return to default + # KGML defines the (x, y) coordinates as the centre of the circle/ + # rectangle/roundrectangle, but Reportlab uses the coordinates of the + # lower-left corner for rectangle/elif. + if graphics.type == "circle": + self.drawing.circle( + graphics.x, graphics.y, graphics.width * 0.5, stroke=1, fill=1 + ) + elif graphics.type == "roundrectangle": + self.drawing.roundRect( + graphics.x - graphics.width * 0.5, + graphics.y - graphics.height * 0.5, + graphics.width, + graphics.height, + min(graphics.width, graphics.height) * 0.1, + stroke=1, + fill=1, + ) + elif graphics.type == "rectangle": + self.drawing.rect( + graphics.x - graphics.width * 0.5, + graphics.y - graphics.height * 0.5, + graphics.width, + graphics.height, + stroke=1, + fill=1, + ) + + def __add_labels(self, graphics): + """Add labels for the passed graphics objects to the map (PRIVATE). + + We don't check that the labels fit inside objects such as circles/ + rectangles/roundrectangles. + """ + if graphics.type == "line": + # We use the midpoint of the line - sort of - we take the median + # line segment (list-wise, not in terms of length), and use the + # midpoint of that line. We could have other options here, + # maybe even parameterising it to a proportion of the total line + # length. + mid_idx = len(graphics.coords) * 0.5 + if int(mid_idx) != mid_idx: + idx1, idx2 = int(mid_idx - 0.5), int(mid_idx + 0.5) + else: + idx1, idx2 = int(mid_idx - 1), int(mid_idx) + x1, y1 = graphics.coords[idx1] + x2, y2 = graphics.coords[idx2] + x, y = 0.5 * (x1 + x2), 0.5 * (y1 + y2) + elif graphics.type == "circle": + x, y = graphics.x, graphics.y + elif graphics.type in ("rectangle", "roundrectangle"): + x, y = graphics.x, graphics.y + # How big so we want the text, and how many characters? + if graphics._parent.type == "map": + text = graphics.name + self.drawing.setFont(self.fontname, self.fontsize + 2) + elif len(graphics.name) < 15: + text = graphics.name + else: + text = graphics.name[:12] + "..." + self.drawing.drawCentredString(x, y, text) + self.drawing.setFont(self.fontname, self.fontsize) + + def __add_orthologs(self): + """Add 'ortholog' Entry elements to the drawing of the map (PRIVATE). + + In KGML, these are typically line objects, so we render them + before the compound circles to cover the unsightly ends/junctions. + """ + for ortholog in self.pathway.orthologs: + for g in ortholog.graphics: + self.drawing.setStrokeColor(color_to_reportlab(g.fgcolor)) + self.drawing.setFillColor(color_to_reportlab(g.bgcolor)) + self.__add_graphics(g) + if self.label_orthologs: + # We want the label color to be slightly darker + # (where possible), so it can be read + self.drawing.setFillColor(darken(g.fgcolor)) + self.__add_labels(g) + + def __add_reaction_entries(self): + """Add Entry elements for Reactions to the map drawing (PRIVATE). + + In KGML, these are typically line objects, so we render them + before the compound circles to cover the unsightly ends/junctions + """ + for reaction in self.pathway.reaction_entries: + for g in reaction.graphics: + self.drawing.setStrokeColor(color_to_reportlab(g.fgcolor)) + self.drawing.setFillColor(color_to_reportlab(g.bgcolor)) + self.__add_graphics(g) + if self.label_reaction_entries: + # We want the label color to be slightly darker + # (where possible), so it can be read + self.drawing.setFillColor(darken(g.fgcolor)) + self.__add_labels(g) + + def __add_compounds(self): + """Add compound elements to the drawing of the map (PRIVATE).""" + for compound in self.pathway.compounds: + for g in compound.graphics: + # Modify transparency of compounds that don't participate + # in reactions + fillcolor = color_to_reportlab(g.bgcolor) + if not compound.is_reactant: + fillcolor.alpha *= self.non_reactant_transparency + self.drawing.setStrokeColor(color_to_reportlab(g.fgcolor)) + self.drawing.setFillColor(fillcolor) + self.__add_graphics(g) + if self.label_compounds: + if not compound.is_reactant: + t = 0.3 + else: + t = 1 + self.drawing.setFillColor(colors.Color(0.2, 0.2, 0.2, t)) + self.__add_labels(g) + + def __add_genes(self): + """Add gene elements to the drawing of the map (PRIVATE).""" + for gene in self.pathway.genes: + for g in gene.graphics: + self.drawing.setStrokeColor(color_to_reportlab(g.fgcolor)) + self.drawing.setFillColor(color_to_reportlab(g.bgcolor)) + self.__add_graphics(g) + if self.label_compounds: + self.drawing.setFillColor(darken(g.fgcolor)) + self.__add_labels(g) + + def __add_relations(self): + """Add relations to the map (PRIVATE). + + This is tricky. There is no defined graphic in KGML for a + relation, and the corresponding entries are typically defined + as objects 'to be connected somehow'. KEGG uses KegSketch, which + is not public, and most third-party software draws straight line + arrows, with heads to indicate the appropriate direction + (at both ends for reversible reactions), using solid lines for + ECrel relation types, and dashed lines for maplink relation types. + + The relation has: + - entry1: 'from' node + - entry2: 'to' node + - subtype: what the relation refers to + + Typically we have entry1 = map/ortholog; entry2 = map/ortholog, + subtype = compound. + """ + # Dashed lines for maplinks, solid for everything else + for relation in list(self.pathway.relations): + if relation.type == "maplink": + self.drawing.setDash(6, 3) + else: + self.drawing.setDash() + for s in relation.subtypes: + subtype = self.pathway.entries[s[1]] + # Our aim is to draw an arrow from the entry1 object to the + # entry2 object, via the subtype object. + # 1) Entry 1 to subtype + self.__draw_arrow(relation.entry1, subtype) + # 2) subtype to Entry 2 + self.__draw_arrow(subtype, relation.entry2) + + def __draw_arrow(self, g_from, g_to): + """Draw an arrow between given Entry objects (PRIVATE). + + Draws an arrow from the g_from Entry object to the g_to + Entry object; both must have Graphics objects. + """ + # Centre and bound coordinates for the from and two objects + bounds_from, bounds_to = g_from.bounds, g_to.bounds + centre_from = ( + 0.5 * (bounds_from[0][0] + bounds_from[1][0]), + 0.5 * (bounds_from[0][1] + bounds_from[1][1]), + ) + centre_to = ( + 0.5 * (bounds_to[0][0] + bounds_to[1][0]), + 0.5 * (bounds_to[0][1] + bounds_to[1][1]), + ) + p = self.drawing.beginPath() + # print(True, g_from.name, g_to.name, bounds_to, bounds_from) + # If the 'from' and 'to' graphics are vertically-aligned, draw a line + # from the 'from' to the 'to' entity + if bounds_to[0][0] < centre_from[0] < bounds_to[1][0]: + # print(True, g_from.name, g_to.name, bounds_to, bounds_from) + if centre_to[1] > centre_from[1]: # to above from + p.moveTo(centre_from[0], bounds_from[1][1]) + p.lineTo(centre_from[0], bounds_to[0][1]) + # Draw arrow point - TODO + else: # to below from + p.moveTo(centre_from[0], bounds_from[0][1]) + p.lineTo(centre_from[0], bounds_to[1][1]) + # Draw arrow point - TODO + elif bounds_from[0][0] < centre_to[0] < bounds_from[1][0]: + # print(True, g_from.name, g_to.name, bounds_to, bounds_from) + if centre_to[1] > centre_from[1]: # to above from + p.moveTo(centre_to[0], bounds_from[1][1]) + p.lineTo(centre_to[0], bounds_to[0][1]) + # Draw arrow point - TODO + else: # to below from + p.moveTo(centre_to[0], bounds_from[0][1]) + p.lineTo(centre_to[0], bounds_to[1][1]) + # Draw arrow point - TODO + self.drawing.drawPath(p) # Draw arrow shaft + # print(g_from) + # print(bounds_from) + # print(g_to) + # print(bounds_to) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..70372cee09af14576c532000fd5a231e1ab6b008 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Graphics/__init__.py @@ -0,0 +1,92 @@ +# Copyright 2008 by Brad Chapman. All rights reserved. +# Copyright 2008 by Michiel de Hoon. All rights reserved. +# Copyright 2009-2017 by Peter Cock. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""Bio.Graphics offers several graphical outputs, all using ReportLab.""" + +# Check if ReportLab is installed. +try: + import reportlab as r + + del r +except ImportError: + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError( + "Please install ReportLab if you want " + "to use Bio.Graphics. You can find ReportLab at " + "http://www.reportlab.com/software/opensource/" + ) from None + + +# The following code is to allow all the Bio.Graphics +# code to deal with the different ReportLab renderers +# and the API quirks consistently. + + +def _write(drawing, output_file, format, dpi=72): + """Standardize output to files (PRIVATE). + + Writes the provided drawing out to a file in a prescribed format. + + - drawing - suitable ReportLab drawing object. + - output_file - a handle to write to, or a filename to write to. + - format - String indicating output format, one of PS, PDF, SVG, + or provided the ReportLab renderPM module is installed, + one of the bitmap formats JPG, BMP, GIF, PNG, TIFF or TIFF. + The format can be given in any case. + - dpi - Resolution (dots per inch) for bitmap formats. + + No return value. + """ + from reportlab.graphics import renderPDF + from reportlab.graphics import renderPS + from reportlab.graphics import renderSVG + + try: + from reportlab.graphics import renderPM + except ImportError: + # This is an optional part of ReportLab, so may not be installed. + # We'll raise a missing dependency error if rendering to a + # bitmap format is attempted. + renderPM = None + + formatdict = { + "PS": renderPS, + "EPS": renderPS, + # not sure which you actually get, PS or EPS, but + # GenomeDiagram used PS while other modules used EPS. + "PDF": renderPDF, + "SVG": renderSVG, + "JPG": renderPM, + "BMP": renderPM, + "GIF": renderPM, + "PNG": renderPM, + "TIFF": renderPM, + "TIF": renderPM, + } + try: + # If output is not a string, then .upper() will trigger + # an attribute error... + drawmethod = formatdict[format.upper()] # select drawing method + except (KeyError, AttributeError): + raise ValueError( + f"Output format should be one of {', '.join(formatdict)}" + ) from None + + if drawmethod is None: + # i.e. We wanted renderPM but it isn't installed + # See the import at the top of the function. + from Bio import MissingPythonDependencyError + + raise MissingPythonDependencyError("Please install ReportLab's renderPM module") + + if drawmethod == renderPM: + # This has a different API to the other render objects + return drawmethod.drawToFile(drawing, output_file, format, dpi=dpi) + else: + return drawmethod.drawToFile(drawing, output_file) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a47710838931d12a3d58d6913fb879b9171e203a --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/__init__.py @@ -0,0 +1,5 @@ +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. +"""A selection of Hidden Markov Model code.""" diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c1b0b0fc6a405e22de0bae87a8ede40840a15b6 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/HMM/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..352cb2a550ac1cf2be76bc902c65ba569a3bdfc0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/__init__.py @@ -0,0 +1,180 @@ +# Copyright 2001 by Tarjei Mikkelsen. All rights reserved. +# Copyright 2007 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Code to work with the KEGG Ligand/Compound database. + +Functions: + - parse - Returns an iterator giving Record objects. + +Classes: + - Record - A representation of a KEGG Ligand/Compound. +""" + +from Bio.KEGG import _default_wrap +from Bio.KEGG import _struct_wrap +from Bio.KEGG import _wrap_kegg +from Bio.KEGG import _write_kegg + +# Set up line wrapping rules (see Bio.KEGG._wrap_kegg) +name_wrap = [0, "", (" ", "$", 1, 1), ("-", "$", 1, 1)] +id_wrap = _default_wrap +struct_wrap = _struct_wrap + + +class Record: + """Holds info from a KEGG Ligand/Compound record. + + Attributes: + - entry The entry identifier. + - name A list of the compound names. + - formula The chemical formula for the compound + - mass The molecular weight for the compound + - pathway A list of 3-tuples: ('PATH', pathway id, pathway) + - enzyme A list of the EC numbers. + - structures A list of 2-tuples: (database, list of struct ids) + - dblinks A list of 2-tuples: (database, list of link ids) + + """ + + def __init__(self): + """Initialize as new record.""" + self.entry = "" + self.name = [] + self.formula = "" + self.mass = "" + self.pathway = [] + self.enzyme = [] + self.structures = [] + self.dblinks = [] + + def __str__(self): + """Return a string representation of this Record.""" + return ( + self._entry() + + self._name() + + self._formula() + + self._mass() + + self._pathway() + + self._enzyme() + + self._structures() + + self._dblinks() + + "///" + ) + + def _entry(self): + return _write_kegg("ENTRY", [self.entry]) + + def _name(self): + return _write_kegg( + "NAME", [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.name] + ) + + def _formula(self): + return _write_kegg("FORMULA", [self.formula]) + + def _mass(self): + return _write_kegg("MASS", [self.mass]) + + def _pathway(self): + s = [] + for entry in self.pathway: + s.append(entry[0] + " " + entry[1]) + return _write_kegg( + "PATHWAY", [_wrap_kegg(line, wrap_rule=id_wrap(16)) for line in s] + ) + + def _enzyme(self): + return _write_kegg( + "ENZYME", [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.enzyme] + ) + + def _structures(self): + s = [] + for entry in self.structures: + s.append(entry[0] + ": " + " ".join(entry[1]) + " ") + return _write_kegg( + "STRUCTURES", [_wrap_kegg(line, wrap_rule=struct_wrap(5)) for line in s] + ) + + def _dblinks(self): + s = [] + for entry in self.dblinks: + s.append(entry[0] + ": " + " ".join(entry[1])) + return _write_kegg( + "DBLINKS", [_wrap_kegg(line, wrap_rule=id_wrap(9)) for line in s] + ) + + +def parse(handle): + """Parse a KEGG Ligan/Compound file, returning Record objects. + + This is an iterator function, typically used in a for loop. For + example, using one of the example KEGG files in the Biopython + test suite, + + >>> with open("KEGG/compound.sample") as handle: + ... for record in parse(handle): + ... print("%s %s" % (record.entry, record.name[0])) + ... + C00023 Iron + C00017 Protein + C00099 beta-Alanine + C00294 Inosine + C00298 Trypsin + C00348 all-trans-Undecaprenyl phosphate + C00349 2-Methyl-3-oxopropanoate + C01386 NH2Mec + + """ + record = Record() + for line in handle: + if line[:3] == "///": + yield record + record = Record() + continue + if line[:12] != " ": + keyword = line[:12] + data = line[12:].strip() + if keyword == "ENTRY ": + words = data.split() + record.entry = words[0] + elif keyword == "NAME ": + data = data.strip(";") + record.name.append(data) + elif keyword == "ENZYME ": + while data: + column = data[:16] + data = data[16:] + enzyme = column.strip() + record.enzyme.append(enzyme) + elif keyword == "PATHWAY ": + map, name = data.split(" ") + pathway = ("PATH", map, name) + record.pathway.append(pathway) + elif keyword == "FORMULA ": + record.formula = data + elif keyword in ("MASS ", "EXACT_MASS "): + record.mass = data + elif keyword == "DBLINKS ": + if ":" in data: + key, values = data.split(":") + values = values.split() + row = (key, values) + record.dblinks.append(row) + else: + row = record.dblinks[-1] + key, values = row + values.extend(data.split()) + row = key, values + record.dblinks[-1] = row + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c81dc052bea427e58ebb3308a5a386615393848b Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Compound/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3d06cf529d50d1f145caca7d0285581b732f567 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/__init__.py @@ -0,0 +1,339 @@ +# Copyright 2001 by Tarjei Mikkelsen. All rights reserved. +# Copyright 2007 by Michiel de Hoon. All rights reserved. +# This code is part of the Biopython distribution and governed by its +# license. Please see the LICENSE file that should have been included +# as part of this package. + +"""Code to work with the KEGG Enzyme database. + +Functions: + - parse - Returns an iterator giving Record objects. + +Classes: + - Record - Holds the information from a KEGG Enzyme record. +""" + +from Bio.KEGG import _default_wrap +from Bio.KEGG import _struct_wrap +from Bio.KEGG import _wrap_kegg +from Bio.KEGG import _write_kegg + +# Set up line wrapping rules (see Bio.KEGG._wrap_kegg) +rxn_wrap = [ + 0, + "", + (" + ", "", 1, 1), + (" = ", "", 1, 1), + (" ", "$", 1, 1), + ("-", "$", 1, 1), +] +name_wrap = [0, "", (" ", "$", 1, 1), ("-", "$", 1, 1)] +id_wrap = _default_wrap +struct_wrap = _struct_wrap + + +class Record: + """Holds info from a KEGG Enzyme record. + + Attributes: + - entry The EC number (without the 'EC '). + - name A list of the enzyme names. + - classname A list of the classification terms. + - sysname The systematic name of the enzyme. + - reaction A list of the reaction description strings. + - substrate A list of the substrates. + - product A list of the products. + - inhibitor A list of the inhibitors. + - cofactor A list of the cofactors. + - effector A list of the effectors. + - comment A list of the comment strings. + - pathway A list of 3-tuples: (database, id, pathway) + - genes A list of 2-tuples: (organism, list of gene ids) + - disease A list of 3-tuples: (database, id, disease) + - structures A list of 2-tuples: (database, list of struct ids) + - dblinks A list of 2-tuples: (database, list of db ids) + + """ + + def __init__(self): + """Initialize a new Record.""" + self.entry = "" + self.name = [] + self.classname = [] + self.sysname = [] + self.reaction = [] + self.substrate = [] + self.product = [] + self.inhibitor = [] + self.cofactor = [] + self.effector = [] + self.comment = [] + self.pathway = [] + self.genes = [] + self.disease = [] + self.structures = [] + self.dblinks = [] + + def __str__(self): + """Return a string representation of this Record.""" + return ( + self._entry() + + self._name() + + self._classname() + + self._sysname() + + self._reaction() + + self._substrate() + + self._product() + + self._inhibitor() + + self._cofactor() + + self._effector() + + self._comment() + + self._pathway() + + self._genes() + + self._disease() + + self._structures() + + self._dblinks() + + "///" + ) + + def _entry(self): + return _write_kegg("ENTRY", ["EC " + self.entry]) + + def _name(self): + return _write_kegg( + "NAME", [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.name] + ) + + def _classname(self): + return _write_kegg("CLASS", self.classname) + + def _sysname(self): + return _write_kegg( + "SYSNAME", [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.sysname] + ) + + def _reaction(self): + return _write_kegg( + "REACTION", [_wrap_kegg(line, wrap_rule=rxn_wrap) for line in self.reaction] + ) + + def _substrate(self): + return _write_kegg( + "SUBSTRATE", + [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.substrate], + ) + + def _product(self): + return _write_kegg( + "PRODUCT", [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.product] + ) + + def _inhibitor(self): + return _write_kegg( + "INHIBITOR", + [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.inhibitor], + ) + + def _cofactor(self): + return _write_kegg( + "COFACTOR", + [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.cofactor], + ) + + def _effector(self): + return _write_kegg( + "EFFECTOR", + [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.effector], + ) + + def _comment(self): + return _write_kegg( + "COMMENT", [_wrap_kegg(line, wrap_rule=id_wrap(0)) for line in self.comment] + ) + + def _pathway(self): + s = [] + for entry in self.pathway: + s.append(entry[0] + ": " + entry[1] + " " + entry[2]) + return _write_kegg( + "PATHWAY", [_wrap_kegg(line, wrap_rule=id_wrap(16)) for line in s] + ) + + def _genes(self): + s = [] + for entry in self.genes: + s.append(entry[0] + ": " + " ".join(entry[1])) + return _write_kegg( + "GENES", [_wrap_kegg(line, wrap_rule=id_wrap(5)) for line in s] + ) + + def _disease(self): + s = [] + for entry in self.disease: + s.append(entry[0] + ": " + entry[1] + " " + entry[2]) + return _write_kegg( + "DISEASE", [_wrap_kegg(line, wrap_rule=id_wrap(13)) for line in s] + ) + + def _structures(self): + s = [] + for entry in self.structures: + s.append(entry[0] + ": " + " ".join(entry[1]) + " ") + return _write_kegg( + "STRUCTURES", [_wrap_kegg(line, wrap_rule=struct_wrap(5)) for line in s] + ) + + def _dblinks(self): + # This is a bit of a cheat that won't work if enzyme entries + # have more than one link id per db id. For now, that's not + # the case - storing links ids in a list is only to make + # this class similar to the Compound.Record class. + s = [] + for entry in self.dblinks: + s.append(entry[0] + ": " + " ".join(entry[1])) + return _write_kegg("DBLINKS", s) + + +def parse(handle): + """Parse a KEGG Enzyme file, returning Record objects. + + This is an iterator function, typically used in a for loop. For + example, using one of the example KEGG files in the Biopython + test suite, + + >>> with open("KEGG/enzyme.sample") as handle: + ... for record in parse(handle): + ... print("%s %s" % (record.entry, record.name[0])) + ... + 1.1.1.1 alcohol dehydrogenase + 1.1.1.62 17beta-estradiol 17-dehydrogenase + 1.1.1.68 Transferred to 1.5.1.20 + 1.6.5.3 NADH:ubiquinone reductase (H+-translocating) + 1.14.13.28 3,9-dihydroxypterocarpan 6a-monooxygenase + 2.4.1.68 glycoprotein 6-alpha-L-fucosyltransferase + 3.1.1.6 acetylesterase + 2.7.2.1 acetate kinase + + """ + record = Record() + for line in handle: + if line[:3] == "///": + yield record + record = Record() + continue + if line[:12] != " ": + keyword = line[:12] + data = line[12:].strip() + if keyword == "ENTRY ": + words = data.split() + record.entry = words[1] + elif keyword == "CLASS ": + record.classname.append(data) + elif keyword == "COFACTOR ": + record.cofactor.append(data) + elif keyword == "COMMENT ": + record.comment.append(data) + elif keyword == "DBLINKS ": + if ":" in data: + key, values = data.split(":") + values = values.split() + row = (key, values) + record.dblinks.append(row) + else: + row = record.dblinks[-1] + key, values = row + values.extend(data.split()) + row = key, values + record.dblinks[-1] = row + elif keyword == "DISEASE ": + if ":" in data: + database, data = data.split(":") + number, name = data.split(None, 1) + row = (database, number, name) + record.disease.append(row) + else: + row = record.disease[-1] + database, number, name = row + name = name + " " + data + row = database, number, name + record.disease[-1] = row + elif keyword == "EFFECTOR ": + record.effector.append(data.strip(";")) + elif keyword == "GENES ": + if data[3:5] == ": " or data[4:6] == ": ": + key, values = data.split(":", 1) + values = [value.split("(")[0] for value in values.split()] + row = (key, values) + record.genes.append(row) + else: + row = record.genes[-1] + key, values = row + for value in data.split(): + value = value.split("(")[0] + values.append(value) + row = key, values + record.genes[-1] = row + elif keyword == "INHIBITOR ": + record.inhibitor.append(data.strip(";")) + elif keyword == "NAME ": + record.name.append(data.strip(";")) + elif keyword == "PATHWAY ": + if data[:5] == "PATH:": + _, map_num, name = data.split(None, 2) + pathway = ("PATH", map_num, name) + record.pathway.append(pathway) + else: + ec_num, name = data.split(None, 1) + pathway = "PATH", ec_num, name + record.pathway.append(pathway) + elif keyword == "PRODUCT ": + record.product.append(data.strip(";")) + elif keyword == "REACTION ": + record.reaction.append(data.strip(";")) + elif keyword == "STRUCTURES ": + if data[:4] == "PDB:": + database = data[:3] + accessions = data[4:].split() + row = (database, accessions) + record.structures.append(row) + else: + row = record.structures[-1] + database, accessions = row + accessions.extend(data.split()) + row = (database, accessions) + record.structures[-1] = row + elif keyword == "SUBSTRATE ": + record.substrate.append(data.strip(";")) + elif keyword == "SYSNAME ": + record.sysname.append(data.strip(";")) + + +def read(handle): + """Parse a KEGG Enzyme file with exactly one entry. + + If the handle contains no records, or more than one record, + an exception is raised. For example: + + >>> with open("KEGG/enzyme.new") as handle: + ... record = read(handle) + ... print("%s %s" % (record.entry, record.name[0])) + ... + 6.2.1.25 benzoate---CoA ligase + """ + records = parse(handle) + try: + record = next(records) + except StopIteration: + raise ValueError("No records found in handle") from None + try: + next(records) + raise ValueError("More than one record found in handle") + except StopIteration: + pass + return record + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ff36a6175f9f63eac8748b999a3bf5161f71f46 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Enzyme/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e64ce8ab32381583680024d41ba86138dfb2c20f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/__init__.py @@ -0,0 +1,142 @@ +# Copyright 2017 by Kozo Nishida. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Code to work with the KEGG Gene database. + +Functions: +- parse - Returns an iterator giving Record objects. + +Classes: +- Record - A representation of a KEGG Gene. + +""" + +from Bio.KEGG import _default_wrap +from Bio.KEGG import _wrap_kegg +from Bio.KEGG import _write_kegg + +# Set up line wrapping rules (see Bio.KEGG._wrap_kegg) +name_wrap = [0, "", (" ", "$", 1, 1), ("-", "$", 1, 1)] +id_wrap = _default_wrap + + +class Record: + """Holds info from a KEGG Gene record. + + Attributes: + - entry The entry identifier. + - name A list of the gene names. + - definition The definition for the gene. + - orthology A list of 2-tuples: (orthology id, role) + - organism A tuple: (organism id, organism) + - position The position for the gene + - motif A list of 2-tuples: (database, list of link ids) + - dblinks A list of 2-tuples: (database, list of link ids) + + """ + + def __init__(self): + """Initialize new record.""" + self.entry = "" + self.name = [] + self.definition = "" + self.orthology = [] + self.organism = "" + self.position = "" + self.motif = [] + self.dblinks = [] + + def __str__(self): + """Return a string representation of this Record.""" + return self._entry() + self._name() + self._dblinks() + "///" + + def _entry(self): + return _write_kegg("ENTRY", [self.entry]) + + def _name(self): + return _write_kegg( + "NAME", [_wrap_kegg(line, wrap_rule=name_wrap) for line in self.name] + ) + + def _definition(self): + return _write_kegg("DEFINITION", [self.definition]) + + def _dblinks(self): + s = [] + for entry in self.dblinks: + s.append(entry[0] + ": " + " ".join(entry[1])) + return _write_kegg( + "DBLINKS", [_wrap_kegg(line, wrap_rule=id_wrap(9)) for line in s] + ) + + +def parse(handle): + """Parse a KEGG Gene file, returning Record objects. + + This is an iterator function, typically used in a for loop. For + example, using one of the example KEGG files in the Biopython + test suite, + + >>> with open("KEGG/gene.sample") as handle: + ... for record in parse(handle): + ... print("%s %s" % (record.entry, record.name[0])) + ... + b1174 minE + b1175 minD + + + """ + record = Record() + for line in handle: + if line[:3] == "///": + yield record + record = Record() + continue + if line[:12] != " ": + keyword = line[:12] + data = line[12:].strip() + if keyword == "ENTRY ": + words = data.split() + record.entry = words[0] + elif keyword == "NAME ": + data = data.strip(";") + record.name.append(data) + elif keyword == "DEFINITION ": + record.definition = data + elif keyword == "ORTHOLOGY ": + id, name = data.split(" ") + orthology = (id, name) + record.orthology.append(orthology) + elif keyword == "ORGANISM ": + id, name = data.split(" ") + organism = (id, name) + record.organism = organism + elif keyword == "POSITION ": + record.position = data + elif keyword == "MOTIF ": + key, values = data.split(": ") + values = values.split() + row = (key, values) + record.motif.append(row) + elif keyword == "DBLINKS ": + if ":" in data: + key, values = data.split(": ") + values = values.split() + row = (key, values) + record.dblinks.append(row) + else: + row = record.dblinks[-1] + key, values = row + values.extend(data.split()) + row = key, values + record.dblinks[-1] = row + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest() diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47933e55c532be084f87e8a48d0e8ad1453a9594 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Gene/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/KGML_parser.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/KGML_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..4132cfab0631bc36cf86bad8377852a144ee66df --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/KGML_parser.py @@ -0,0 +1,193 @@ +# Copyright 2013 by Leighton Pritchard. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Classes and functions to parse a KGML pathway map. + +The KGML pathway map is parsed into the object structure defined in +KGML_Pathway.py in this module. + +Classes: + - KGMLParser - Parses KGML file + +Functions: + - read - Returns a single Pathway object, using KGMLParser internally + +""" + +from io import StringIO +from xml.etree import ElementTree + +from Bio.KEGG.KGML.KGML_pathway import Component +from Bio.KEGG.KGML.KGML_pathway import Entry +from Bio.KEGG.KGML.KGML_pathway import Graphics +from Bio.KEGG.KGML.KGML_pathway import Pathway +from Bio.KEGG.KGML.KGML_pathway import Reaction +from Bio.KEGG.KGML.KGML_pathway import Relation + + +def read(handle): + """Parse a single KEGG Pathway from given file handle. + + Returns a single Pathway object. There should be one and only + one pathway in each file, but there may well be pathological + examples out there. + """ + pathways = parse(handle) + try: + pathway = next(pathways) + except StopIteration: + raise ValueError("No pathways found in handle") from None + try: + next(pathways) + raise ValueError("More than one pathway found in handle") + except StopIteration: + pass + return pathway + + +def parse(handle): + """Return an iterator over Pathway elements. + + Arguments: + - handle - file handle to a KGML file for parsing, or a KGML string + + This is a generator for the return of multiple Pathway objects. + + """ + # Check handle + try: + handle.read(0) + except AttributeError: + try: + handle = StringIO(handle) + except TypeError: + raise TypeError( + "An XML-containing handle or an XML string must be provided" + ) from None + # Parse XML and return each Pathway + for event, elem in ElementTree.iterparse(handle, events=("start", "end")): + if event == "end" and elem.tag == "pathway": + yield KGMLParser(elem).parse() + elem.clear() + + +class KGMLParser: + """Parses a KGML XML Pathway entry into a Pathway object. + + Example: Read and parse large metabolism file + + >>> from Bio.KEGG.KGML.KGML_parser import read + >>> pathway = read(open('KEGG/ko01100.xml', 'r')) + >>> print(len(pathway.entries)) + 3628 + >>> print(len(pathway.reactions)) + 1672 + >>> print(len(pathway.maps)) + 149 + + >>> pathway = read(open('KEGG/ko00010.xml', 'r')) + >>> print(pathway) #doctest: +NORMALIZE_WHITESPACE + Pathway: Glycolysis / Gluconeogenesis + KEGG ID: path:ko00010 + Image file: http://www.kegg.jp/kegg/pathway/ko/ko00010.png + Organism: ko + Entries: 99 + Entry types: + ortholog: 61 + compound: 31 + map: 7 + + """ + + def __init__(self, elem): + """Initialize the class.""" + self.entry = elem + + def parse(self): + """Parse the input elements.""" + + def _parse_pathway(attrib): + for k, v in attrib.items(): + self.pathway.__setattr__(k, v) + + def _parse_entry(element): + new_entry = Entry() + for k, v in element.attrib.items(): + new_entry.__setattr__(k, v) + for subelement in element: + if subelement.tag == "graphics": + _parse_graphics(subelement, new_entry) + elif subelement.tag == "component": + _parse_component(subelement, new_entry) + self.pathway.add_entry(new_entry) + + def _parse_graphics(element, entry): + new_graphics = Graphics(entry) + for k, v in element.attrib.items(): + new_graphics.__setattr__(k, v) + entry.add_graphics(new_graphics) + + def _parse_component(element, entry): + new_component = Component(entry) + for k, v in element.attrib.items(): + new_component.__setattr__(k, v) + entry.add_component(new_component) + + def _parse_reaction(element): + new_reaction = Reaction() + for k, v in element.attrib.items(): + new_reaction.__setattr__(k, v) + for subelement in element: + if subelement.tag == "substrate": + new_reaction.add_substrate(int(subelement.attrib["id"])) + elif subelement.tag == "product": + new_reaction.add_product(int(subelement.attrib["id"])) + self.pathway.add_reaction(new_reaction) + + def _parse_relation(element): + new_relation = Relation() + new_relation.entry1 = int(element.attrib["entry1"]) + new_relation.entry2 = int(element.attrib["entry2"]) + new_relation.type = element.attrib["type"] + for subtype in element: + name, value = subtype.attrib["name"], subtype.attrib["value"] + if name in ("compound", "hidden compound"): + new_relation.subtypes.append((name, int(value))) + else: + new_relation.subtypes.append((name, value)) + self.pathway.add_relation(new_relation) + + # ========== + # Initialize Pathway + self.pathway = Pathway() + # Get information about the pathway itself + _parse_pathway(self.entry.attrib) + for element in self.entry: + if element.tag == "entry": + _parse_entry(element) + elif element.tag == "reaction": + _parse_reaction(element) + elif element.tag == "relation": + _parse_relation(element) + # Parsing of some elements not implemented - no examples yet + else: + # This should warn us of any unimplemented tags + import warnings + + from Bio import BiopythonParserWarning + + warnings.warn( + f"Warning: tag {element.tag} not implemented in parser", + BiopythonParserWarning, + ) + return self.pathway + + +if __name__ == "__main__": + from Bio._utils import run_doctest + + run_doctest(verbose=0) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/KGML_pathway.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/KGML_pathway.py new file mode 100644 index 0000000000000000000000000000000000000000..8e8c44b63b194c2963d6f7576dd38cfd7ef83abe --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/KGML_pathway.py @@ -0,0 +1,857 @@ +# Copyright 2013 by Leighton Pritchard. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Classes to represent a KGML Pathway Map. + +The KGML definition is as of release KGML v0.7.2 +(http://www.kegg.jp/kegg/xml/docs/) + +Classes: + - Pathway - Specifies graph information for the pathway map + - Relation - Specifies a relationship between two proteins or KOs, + or protein and compound. There is an implied direction to the + relationship in some cases. + - Reaction - A specific chemical reaction between a substrate and + a product. + - Entry - A node in the pathway graph + - Graphics - Entry subelement describing its visual representation + +""" + +import time +import xml.etree.ElementTree as ET +from itertools import chain +from xml.dom import minidom + + +# Pathway +class Pathway: + """Represents a KGML pathway from KEGG. + + Specifies graph information for the pathway map, as described in + release KGML v0.7.2 (http://www.kegg.jp/kegg/xml/docs/) + + Attributes: + - name - KEGGID of the pathway map + - org - ko/ec/[org prefix] + - number - map number (integer) + - title - the map title + - image - URL of the image map for the pathway + - link - URL of information about the pathway + - entries - Dictionary of entries in the pathway, keyed by node ID + - reactions - Set of reactions in the pathway + + The name attribute has a restricted format, so we make it a property and + enforce the formatting. + + The Pathway object is the only allowed route for adding/removing + Entry, Reaction, or Relation elements. + + Entries are held in a dictionary and keyed by the node ID for the + pathway graph - this allows for ready access via the Reaction/Relation + etc. elements. Entries must be added before reference by any other + element. + + Reactions are held in a dictionary, keyed by node ID for the path. + The elements referred to in the reaction must be added before the + reaction itself. + + """ + + def __init__(self): + """Initialize the class.""" + self._name = "" + self.org = "" + self._number = None + self.title = "" + self.image = "" + self.link = "" + self.entries = {} + self._reactions = {} + self._relations = set() + + def get_KGML(self): + """Return the pathway as a string in prettified KGML format.""" + header = "\n".join( + [ + '', + "', + f"", + ] + ) + rough_xml = header + ET.tostring(self.element, "utf-8").decode() + reparsed = minidom.parseString(rough_xml) + return reparsed.toprettyxml(indent=" ") + + def add_entry(self, entry): + """Add an Entry element to the pathway.""" + # We insist that the node ID is an integer + if not isinstance(entry.id, int): + raise TypeError( + f"Node ID must be an integer, got {type(entry.id)} ({entry.id})" + ) + entry._pathway = self # Let the entry know about the pathway + self.entries[entry.id] = entry + + def remove_entry(self, entry): + """Remove an Entry element from the pathway.""" + if not isinstance(entry.id, int): + raise TypeError( + f"Node ID must be an integer, got {type(entry.id)} ({entry.id})" + ) + # We need to remove the entry from any other elements that may + # contain it, which means removing those elements + # TODO + del self.entries[entry.id] + + def add_reaction(self, reaction): + """Add a Reaction element to the pathway.""" + # We insist that the node ID is an integer and corresponds to an entry + if not isinstance(reaction.id, int): + raise ValueError( + f"Node ID must be an integer, got {type(reaction.id)} ({reaction.id})" + ) + if reaction.id not in self.entries: + raise ValueError("Reaction ID %d has no corresponding entry" % reaction.id) + reaction._pathway = self # Let the reaction know about the pathway + self._reactions[reaction.id] = reaction + + def remove_reaction(self, reaction): + """Remove a Reaction element from the pathway.""" + if not isinstance(reaction.id, int): + raise TypeError( + f"Node ID must be an integer, got {type(reaction.id)} ({reaction.id})" + ) + # We need to remove the reaction from any other elements that may + # contain it, which means removing those elements + # TODO + del self._reactions[reaction.id] + + def add_relation(self, relation): + """Add a Relation element to the pathway.""" + relation._pathway = self # Let the reaction know about the pathway + self._relations.add(relation) + + def remove_relation(self, relation): + """Remove a Relation element from the pathway.""" + self._relations.remove(relation) + + def __str__(self): + """Return a readable summary description string.""" + outstr = [ + f"Pathway: {self.title}", + f"KEGG ID: {self.name}", + f"Image file: {self.image}", + f"Organism: {self.org}", + "Entries: %d" % len(self.entries), + "Entry types:", + ] + for t in ["ortholog", "enzyme", "reaction", "gene", "group", "compound", "map"]: + etype = [e for e in self.entries.values() if e.type == t] + if len(etype): + outstr.append("\t%s: %d" % (t, len(etype))) + return "\n".join(outstr) + "\n" + + # Assert correct formatting of the pathway name, and other attributes + def _getname(self): + return self._name + + def _setname(self, value): + if not value.startswith("path:"): + raise ValueError(f"Pathway name should begin with 'path:', got {value}") + self._name = value + + def _delname(self): + del self._name + + name = property(_getname, _setname, _delname, "The KEGGID for the pathway map.") + + def _getnumber(self): + return self._number + + def _setnumber(self, value): + self._number = int(value) + + def _delnumber(self): + del self._number + + number = property(_getnumber, _setnumber, _delnumber, "The KEGG map number.") + + @property + def compounds(self): + """Get a list of entries of type compound.""" + return [e for e in self.entries.values() if e.type == "compound"] + + @property + def maps(self): + """Get a list of entries of type map.""" + return [e for e in self.entries.values() if e.type == "map"] + + @property + def orthologs(self): + """Get a list of entries of type ortholog.""" + return [e for e in self.entries.values() if e.type == "ortholog"] + + @property + def genes(self): + """Get a list of entries of type gene.""" + return [e for e in self.entries.values() if e.type == "gene"] + + @property + def reactions(self): + """Get a list of reactions in the pathway.""" + return self._reactions.values() + + @property + def reaction_entries(self): + """List of entries corresponding to each reaction in the pathway.""" + return [self.entries[i] for i in self._reactions] + + @property + def relations(self): + """Get a list of relations in the pathway.""" + return list(self._relations) + + @property + def element(self): + """Return the Pathway as a valid KGML element.""" + # The root is this Pathway element + pathway = ET.Element("pathway") + pathway.attrib = { + "name": self._name, + "org": self.org, + "number": str(self._number), + "title": self.title, + "image": self.image, + "link": self.link, + } + # We add the Entries in node ID order + for eid, entry in sorted(self.entries.items()): + pathway.append(entry.element) + # Next we add Relations + for relation in self._relations: + pathway.append(relation.element) + for eid, reaction in sorted(self._reactions.items()): + pathway.append(reaction.element) + return pathway + + @property + def bounds(self): + """Coordinate bounds for all Graphics elements in the Pathway. + + Returns the [(xmin, ymin), (xmax, ymax)] coordinates for all + Graphics elements in the Pathway + """ + xlist, ylist = [], [] + for b in [g.bounds for g in self.entries.values()]: + xlist.extend([b[0][0], b[1][0]]) + ylist.extend([b[0][1], b[1][1]]) + return [(min(xlist), min(ylist)), (max(xlist), max(ylist))] + + +# Entry +class Entry: + """Represent an Entry from KGML. + + Each Entry element is a node in the pathway graph, as described in + release KGML v0.7.2 (http://www.kegg.jp/kegg/xml/docs/) + + Attributes: + - id - The ID of the entry in the pathway map (integer) + - names - List of KEGG IDs for the entry + - type - The type of the entry + - link - URL of information about the entry + - reaction - List of KEGG IDs of the corresponding reactions + (integer) + - graphics - List of Graphics objects describing the Entry's visual + representation + - components - List of component node ID for this Entry ('group') + - alt - List of alternate names for the Entry + + NOTE: The alt attribute represents a subelement of the substrate and + product elements in the KGML file + + """ + + def __init__(self): + """Initialize the class.""" + self._id = None + self._names = [] + self.type = "" + self.image = "" + self.link = "" + self.graphics = [] + self.components = set() + self.alt = [] + self._pathway = None + self._reactions = [] + + def __str__(self): + """Return readable descriptive string.""" + outstr = [ + "Entry node ID: %d" % self.id, + f"Names: {self.name}", + f"Type: {self.type}", + f"Components: {self.components}", + f"Reactions: {self.reaction}", + "Graphics elements: %d %s" % (len(self.graphics), self.graphics), + ] + return "\n".join(outstr) + "\n" + + def add_component(self, element): + """Add an element to the entry. + + If the Entry is already part of a pathway, make sure + the component already exists. + """ + if self._pathway is not None: + if element.id not in self._pathway.entries: + raise ValueError( + f"Component {element.id} is not an entry in the pathway" + ) + self.components.add(element) + + def remove_component(self, value): + """Remove the entry with the passed ID from the group.""" + self.components.remove(value) + + def add_graphics(self, entry): + """Add the Graphics entry.""" + self.graphics.append(entry) + + def remove_graphics(self, entry): + """Remove the Graphics entry with the passed ID from the group.""" + self.graphics.remove(entry) + + # Names may be given as a space-separated list of KEGG identifiers + def _getname(self): + return " ".join(self._names) + + def _setname(self, value): + self._names = value.split() + + def _delname(self): + self._names = [] + + name = property( + _getname, _setname, _delname, "List of KEGG identifiers for the Entry." + ) + + # Reactions may be given as a space-separated list of KEGG identifiers + def _getreaction(self): + return " ".join(self._reactions) + + def _setreaction(self, value): + self._reactions = value.split() + + def _delreaction(self): + self._reactions = [] + + reaction = property( + _getreaction, + _setreaction, + _delreaction, + "List of reaction KEGG IDs for this Entry.", + ) + + # We make sure that the node ID is an integer + def _getid(self): + return self._id + + def _setid(self, value): + self._id = int(value) + + def _delid(self): + del self._id + + id = property(_getid, _setid, _delid, "The pathway graph node ID for the Entry.") + + @property + def element(self): + """Return the Entry as a valid KGML element.""" + # The root is this Entry element + entry = ET.Element("entry") + entry.attrib = { + "id": str(self._id), + "name": self.name, + "link": self.link, + "type": self.type, + } + if len(self._reactions): + entry.attrib["reaction"] = self.reaction + if len(self.graphics): + for g in self.graphics: + entry.append(g.element) + if len(self.components): + for c in self.components: + entry.append(c.element) + return entry + + @property + def bounds(self): + """Coordinate bounds for all Graphics elements in the Entry. + + Return the [(xmin, ymin), (xmax, ymax)] coordinates for the Entry + Graphics elements. + """ + xlist, ylist = [], [] + for b in [g.bounds for g in self.graphics]: + xlist.extend([b[0][0], b[1][0]]) + ylist.extend([b[0][1], b[1][1]]) + return [(min(xlist), min(ylist)), (max(xlist), max(ylist))] + + @property + def is_reactant(self): + """Return true if this Entry participates in any reaction in its parent pathway.""" + for rxn in self._pathway.reactions: + if self._id in rxn.reactant_ids: + return True + return False + + +# Component +class Component: + """An Entry subelement used to represents a complex node. + + A subelement of the Entry element, used when the Entry is a complex + node, as described in release KGML v0.7.2 + (http://www.kegg.jp/kegg/xml/docs/) + + The Component acts as a collection (with type 'group', and typically + its own Graphics subelement), having only an ID. + """ + + def __init__(self, parent): + """Initialize the class.""" + self._id = None + self._parent = parent + + # We make sure that the node ID is an integer + def _getid(self): + return self._id + + def _setid(self, value): + self._id = int(value) + + def _delid(self): + del self._id + + id = property(_getid, _setid, _delid, "The pathway graph node ID for the Entry") + + @property + def element(self): + """Return the Component as a valid KGML element.""" + # The root is this Component element + component = ET.Element("component") + component.attrib = {"id": str(self._id)} + return component + + +# Graphics +class Graphics: + """An Entry subelement used to represents the visual representation. + + A subelement of Entry, specifying its visual representation, as + described in release KGML v0.7.2 (http://www.kegg.jp/kegg/xml/docs/) + + Attributes: + - name Label for the graphics object + - x X-axis position of the object (int) + - y Y-axis position of the object (int) + - coords polyline coordinates, list of (int, int) tuples + - type object shape + - width object width (int) + - height object height (int) + - fgcolor object foreground color (hex RGB) + - bgcolor object background color (hex RGB) + + Some attributes are present only for specific graphics types. For + example, line types do not (typically) have a width. + We permit non-DTD attributes and attribute settings, such as + + dash List of ints, describing an on/off pattern for dashes + + """ + + def __init__(self, parent): + """Initialize the class.""" + self.name = "" + self._x = None + self._y = None + self._coords = None + self.type = "" + self._width = None + self._height = None + self.fgcolor = "" + self.bgcolor = "" + self._parent = parent + + # We make sure that the XY coordinates, width and height are numbers + def _getx(self): + return self._x + + def _setx(self, value): + self._x = float(value) + + def _delx(self): + del self._x + + x = property(_getx, _setx, _delx, "The X coordinate for the graphics element.") + + def _gety(self): + return self._y + + def _sety(self, value): + self._y = float(value) + + def _dely(self): + del self._y + + y = property(_gety, _sety, _dely, "The Y coordinate for the graphics element.") + + def _getwidth(self): + return self._width + + def _setwidth(self, value): + self._width = float(value) + + def _delwidth(self): + del self._width + + width = property( + _getwidth, _setwidth, _delwidth, "The width of the graphics element." + ) + + def _getheight(self): + return self._height + + def _setheight(self, value): + self._height = float(value) + + def _delheight(self): + del self._height + + height = property( + _getheight, _setheight, _delheight, "The height of the graphics element." + ) + + # We make sure that the polyline coordinates are integers, too + def _getcoords(self): + return self._coords + + def _setcoords(self, value): + clist = [int(e) for e in value.split(",")] + self._coords = [tuple(clist[i : i + 2]) for i in range(0, len(clist), 2)] + + def _delcoords(self): + del self._coords + + coords = property( + _getcoords, + _setcoords, + _delcoords, + "Polyline coordinates for the graphics element.", + ) + + # Set default colors + def _getfgcolor(self): + return self._fgcolor + + def _setfgcolor(self, value): + if value == "none": + self._fgcolor = "#000000" # this default defined in KGML spec + else: + self._fgcolor = value + + def _delfgcolor(self): + del self._fgcolor + + fgcolor = property(_getfgcolor, _setfgcolor, _delfgcolor, "Foreground color.") + + def _getbgcolor(self): + return self._bgcolor + + def _setbgcolor(self, value): + if value == "none": + self._bgcolor = "#000000" # this default defined in KGML spec + else: + self._bgcolor = value + + def _delbgcolor(self): + del self._bgcolor + + bgcolor = property(_getbgcolor, _setbgcolor, _delbgcolor, "Background color.") + + @property + def element(self): + """Return the Graphics as a valid KGML element.""" + # The root is this Component element + graphics = ET.Element("graphics") + if isinstance(self.fgcolor, str): # Assumes that string is hexstring + fghex = self.fgcolor + else: # Assumes ReportLab Color object + fghex = "#" + self.fgcolor.hexval()[2:] + if isinstance(self.bgcolor, str): # Assumes that string is hexstring + bghex = self.bgcolor + else: # Assumes ReportLab Color object + bghex = "#" + self.bgcolor.hexval()[2:] + graphics.attrib = { + "name": self.name, + "type": self.type, + "fgcolor": fghex, + "bgcolor": bghex, + } + for n, attr in [ + ("x", "_x"), + ("y", "_y"), + ("width", "_width"), + ("height", "_height"), + ]: + if getattr(self, attr) is not None: + graphics.attrib[n] = str(getattr(self, attr)) + if self.type == "line": # Need to write polycoords + graphics.attrib["coords"] = ",".join( + [str(e) for e in chain.from_iterable(self.coords)] + ) + return graphics + + @property + def bounds(self): + """Coordinate bounds for the Graphics element. + + Return the bounds of the Graphics object as an [(xmin, ymin), + (xmax, ymax)] tuple. Coordinates give the centre of the + circle, rectangle, roundrectangle elements, so we have to + adjust for the relevant width/height. + """ + if self.type == "line": + xlist = [x for x, y in self.coords] + ylist = [y for x, y in self.coords] + return [(min(xlist), min(ylist)), (max(xlist), max(ylist))] + else: + return [ + (self.x - self.width * 0.5, self.y - self.height * 0.5), + (self.x + self.width * 0.5, self.y + self.height * 0.5), + ] + + @property + def centre(self): + """Return the centre of the Graphics object as an (x, y) tuple.""" + return ( + 0.5 * (self.bounds[0][0] + self.bounds[1][0]), + 0.5 * (self.bounds[0][1] + self.bounds[1][1]), + ) + + +# Reaction +class Reaction: + """A specific chemical reaction with substrates and products. + + This describes a specific chemical reaction between one or more + substrates and one or more products. + + Attributes: + - id Pathway graph node ID of the entry + - names List of KEGG identifier(s) from the REACTION database + - type String: reversible or irreversible + - substrate Entry object of the substrate + - product Entry object of the product + + """ + + def __init__(self): + """Initialize the class.""" + self._id = None + self._names = [] + self.type = "" + self._substrates = set() + self._products = set() + self._pathway = None + + def __str__(self): + """Return an informative human-readable string.""" + outstr = [ + f"Reaction node ID: {self.id}", + f"Reaction KEGG IDs: {self.name}", + f"Type: {self.type}", + f"Substrates: {','.join([s.name for s in self.substrates])}", + f"Products: {','.join([s.name for s in self.products])}", + ] + return "\n".join(outstr) + "\n" + + def add_substrate(self, substrate_id): + """Add a substrate, identified by its node ID, to the reaction.""" + if self._pathway is not None: + if int(substrate_id) not in self._pathway.entries: + raise ValueError( + "Couldn't add substrate, no node ID %d in Pathway" + % int(substrate_id) + ) + self._substrates.add(substrate_id) + + def add_product(self, product_id): + """Add a product, identified by its node ID, to the reaction.""" + if self._pathway is not None: + if int(product_id) not in self._pathway.entries: + raise ValueError( + "Couldn't add product, no node ID %d in Pathway" % product_id + ) + self._products.add(int(product_id)) + + # The node ID is also the node ID of the Entry that corresponds to the + # reaction; we get the corresponding Entry when there is an associated + # Pathway + def _getid(self): + return self._id + + def _setid(self, value): + self._id = int(value) + + def _delid(self): + del self._id + + id = property(_getid, _setid, _delid, "Node ID for the reaction.") + + # Names may show up as a space-separated list of several KEGG identifiers + def _getnames(self): + return " ".join(self._names) + + def _setnames(self, value): + self._names.extend(value.split()) + + def _delnames(self): + del self.names + + name = property( + _getnames, _setnames, _delnames, "List of KEGG identifiers for the reaction." + ) + + # products and substrates are read-only properties, returning lists + # of Entry objects + @property + def substrates(self): + """Return list of substrate Entry elements.""" + return [self._pathway.entries[sid] for sid in self._substrates] + + @property + def products(self): + """Return list of product Entry elements.""" + return [self._pathway.entries[pid] for pid in self._products] + + @property + def entry(self): + """Return the Entry corresponding to this reaction.""" + return self._pathway.entries[self._id] + + @property + def reactant_ids(self): + """Return a list of substrate and product reactant IDs.""" + return self._products.union(self._substrates) + + @property + def element(self): + """Return KGML element describing the Reaction.""" + # The root is this Relation element + reaction = ET.Element("reaction") + reaction.attrib = {"id": str(self.id), "name": self.name, "type": self.type} + for s in self._substrates: + substrate = ET.Element("substrate") + substrate.attrib["id"] = str(s) + substrate.attrib["name"] = self._pathway.entries[s].name + reaction.append(substrate) + for p in self._products: + product = ET.Element("product") + product.attrib["id"] = str(p) + product.attrib["name"] = self._pathway.entries[p].name + reaction.append(product) + return reaction + + +# Relation +class Relation: + """A relationship between to products, KOs, or protein and compound. + + This describes a relationship between two products, KOs, or protein + and compound, as described in release KGML v0.7.2 + (http://www.kegg.jp/kegg/xml/docs/) + + Attributes: + - entry1 - The first Entry object node ID defining the + relation (int) + - entry2 - The second Entry object node ID defining the + relation (int) + - type - The relation type + - subtypes - List of subtypes for the relation, as a list of + (name, value) tuples + + """ + + def __init__(self): + """Initialize the class.""" + self._entry1 = None + self._entry2 = None + self.type = "" + self.subtypes = [] + self._pathway = None + + def __str__(self): + """Return a useful human-readable string.""" + outstr = [ + "Relation (subtypes: %d):" % len(self.subtypes), + "Entry1:", + str(self.entry1), + "Entry2:", + str(self.entry2), + ] + for s in self.subtypes: + outstr.extend([f"Subtype: {s[0]}", str(s[1])]) + return "\n".join(outstr) + + # Properties entry1 and entry2 + def _getentry1(self): + if self._pathway is not None: + return self._pathway.entries[self._entry1] + return self._entry1 + + def _setentry1(self, value): + self._entry1 = int(value) + + def _delentry1(self): + del self._entry1 + + entry1 = property(_getentry1, _setentry1, _delentry1, "Entry1 of the relation.") + + def _getentry2(self): + if self._pathway is not None: + return self._pathway.entries[self._entry2] + return self._entry2 + + def _setentry2(self, value): + self._entry2 = int(value) + + def _delentry2(self): + del self._entry2 + + entry2 = property(_getentry2, _setentry2, _delentry2, "Entry2 of the relation.") + + @property + def element(self): + """Return KGML element describing the Relation.""" + # The root is this Relation element + relation = ET.Element("relation") + relation.attrib = { + "entry1": str(self._entry1), + "entry2": str(self._entry2), + "type": self.type, + } + for name, value in self.subtypes: + subtype = ET.Element("subtype") + subtype.attrib = {"name": name, "value": str(value)} + relation.append(subtype) + return relation diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9063911e55b86145856c2354636891db4d95ebd0 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__init__.py @@ -0,0 +1,16 @@ +# Copyright 2013 by Leighton Pritchard. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Code to work with data from the KEGG database. + +References: +Kanehisa, M. and Goto, S.; KEGG: Kyoto Encyclopedia of Genes and Genomes. +Nucleic Acids Res. 28, 29-34 (2000). + +URL: http://www.genome.ad.jp/kegg/ + +""" diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__pycache__/KGML_parser.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__pycache__/KGML_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85c973e3e848df6a10c17dd74ff887f9d5e3e05e Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__pycache__/KGML_parser.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__pycache__/KGML_pathway.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__pycache__/KGML_pathway.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..857e9a391dd0e7956180435074fbd8b727f0d331 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__pycache__/KGML_pathway.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8dd881396d69953aca25d5d7cb1939cfeca879d0 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/KGML/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/__init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b37f763fbd5f6c4980b4220752016f979d2d14 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/__init__.py @@ -0,0 +1,49 @@ +# Copyright 2001 by Tarjei Mikkelsen. All rights reserved. +# Copyright 2007 by Michiel de Hoon. All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Load KEGG Pathway maps for use with the Biopython Pathway module. + +The pathway maps are in the format:: + + RXXXXX:[X.X.X.X:] A + 2 B <=> C + RXXXXX:[X.X.X.X:] 3C <=> 2 D + E + ... + +where RXXXXX is a five-digit reaction id, and X.X.X.X is the optional +EC number of the enzyme that catalyze the reaction. +""" + +from Bio.Pathway import Reaction + + +def parse(handle): + """Parse a KEGG pathway map.""" + for line in handle: + data, catalysts, reaction = line.split(":") + catalysts = [(catalysts,)] + reactants = {} + before, after = reaction.split("<=>") + compounds = before.split(" + ") + for compound in compounds: + compound = compound.strip() + try: + number, compound = compound.split() + number = -int(number) + except ValueError: + number = -1 + reactants[compound] = number + compounds = after.split(" + ") + for compound in compounds: + compound = compound.strip() + try: + number, compound = compound.split() + number = int(number) + except ValueError: + number = +1 + reactants[compound] = number + yield Reaction(reactants, catalysts, True, data) diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/__pycache__/__init__.cpython-312.pyc b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f107573c888a11fec5f5232c5e9ce1b824771a3d Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/Map/__pycache__/__init__.cpython-312.pyc differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/REST.py b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/REST.py new file mode 100644 index 0000000000000000000000000000000000000000..151f391c091ccbd774b46a425eb5d24e7170e724 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/KEGG/REST.py @@ -0,0 +1,330 @@ +# Copyright 2014 by Kevin Wu. +# Revisions copyright 2014 by Peter Cock. +# All rights reserved. +# +# This file is part of the Biopython distribution and governed by your +# choice of the "Biopython License Agreement" or the "BSD 3-Clause License". +# Please see the LICENSE file that should have been included as part of this +# package. + +"""Provides code to access the REST-style KEGG online API. + +This module aims to make the KEGG online REST-style API easier to use. See: +https://www.kegg.jp/kegg/rest/keggapi.html + +The KEGG REST-style API provides simple access to a range of KEGG databases. +This works using simple URLs (which this module will construct for you), +with any errors indicated via HTTP error levels. + +The functionality is somewhat similar to Biopython's Bio.TogoWS and Bio.Entrez +modules. + +Currently KEGG does not provide any usage guidelines (unlike the NCBI whose +requirements are reasonably clear). To avoid risking overloading the service, +Biopython will only allow three calls per second. + +References: +Kanehisa, M. and Goto, S.; KEGG: Kyoto Encyclopedia of Genes and Genomes. +Nucleic Acids Res. 28, 29-34 (2000). + +""" + +import io +import time +from urllib.request import urlopen + +from Bio._utils import function_with_previous + + +@function_with_previous +def _q(op, arg1, arg2=None, arg3=None): + delay = 0.333333333 # one third of a second + current = time.time() + wait = _q.previous + delay - current + if wait > 0: + time.sleep(wait) + _q.previous = current + wait + else: + _q.previous = current + + URL = "https://rest.kegg.jp/%s" + if arg2 and arg3: + args = f"{op}/{arg1}/{arg2}/{arg3}" + elif arg2: + args = f"{op}/{arg1}/{arg2}" + else: + args = f"{op}/{arg1}" + resp = urlopen(URL % (args)) + + if "image" == arg2: + return resp + + handle = io.TextIOWrapper(resp, encoding="UTF-8") + handle.url = resp.url + return handle + + +_q.previous = 0 + + +# https://www.kegg.jp/kegg/rest/keggapi.html +def kegg_info(database): + """KEGG info - Displays the current statistics of a given database. + + db - database or organism (string) + + The argument db can be a KEGG database name (e.g. 'pathway' or its + official abbreviation, 'path'), or a KEGG organism code or T number + (e.g. 'hsa' or 'T01001' for human). + + A valid list of organism codes and their T numbers can be obtained + via kegg_info('organism') or https://rest.kegg.jp/list/organism + + """ + # TODO - return a string (rather than the handle?) + # TODO - cache and validate the organism code / T numbers? + # TODO - can we parse the somewhat formatted output? + # + # https://rest.kegg.jp/info/ + # + # = pathway | brite | module | disease | drug | environ | + # ko | genome | | compound | glycan | reaction | + # rpair | rclass | enzyme | genomes | genes | ligand | kegg + # = KEGG organism code or T number + return _q("info", database) + + +def kegg_list(database, org=None): + """KEGG list - Entry list for database, or specified database entries. + + db - database or organism (string) + org - optional organism (string), see below. + + For the pathway and module databases the optional organism can be + used to restrict the results. + + """ + # TODO - split into two functions (dbentries seems separate)? + # + # https://rest.kegg.jp/list// + # + # = pathway | module + # = KEGG organism code + if database in ("pathway", "module") and org: + resp = _q("list", database, org) + elif isinstance(database, str) and database and org: + raise ValueError("Invalid database arg for kegg list request.") + + # https://rest.kegg.jp/list/ + # + # = pathway | brite | module | disease | drug | environ | + # ko | genome | | compound | glycan | reaction | + # rpair | rclass | enzyme | organism + # = KEGG organism code or T number + # + # + # https://rest.kegg.jp/list/ + # + # = KEGG database entries involving the following + # = pathway | brite | module | disease | drug | environ | + # ko | genome | | compound | glycan | reaction | + # rpair | rclass | enzyme + # = KEGG organism code or T number + else: + if isinstance(database, list): + if len(database) > 100: + raise ValueError( + "Maximum number of databases is 100 for kegg list query" + ) + database = ("+").join(database) + resp = _q("list", database) + + return resp + + +def kegg_find(database, query, option=None): + """KEGG find - Data search. + + Finds entries with matching query keywords or other query data in + a given database. + + db - database or organism (string) + query - search terms (string) + option - search option (string), see below. + + For the compound and drug database, set option to the string 'formula', + 'exact_mass' or 'mol_weight' to search on that field only. The + chemical formula search is a partial match irrespective of the order + of atoms given. The exact mass (or molecular weight) is checked by + rounding off to the same decimal place as the query data. A range of + values may also be specified with the minus(-) sign. + + """ + # TODO - return list of tuples? + # + # https://rest.kegg.jp/find///