diff --git a/.gitattributes b/.gitattributes index b1e133721b77031ac01ce1770500a7830ed03932..ddfd3acf316a12208651e43bb1e0f615ef366cd2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -61,3 +61,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text .venv_haddock/bin/python filter=lfs diff=lfs merge=lfs -text .venv_haddock/bin/python3 filter=lfs diff=lfs merge=lfs -text .venv_haddock/bin/python3.12 filter=lfs diff=lfs merge=lfs -text +.venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text 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/._.DS_Store b/.venv_haddock/lib/._.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..28c42fb20a1f27e695fb64323501fc6476578b13 Binary files /dev/null and b/.venv_haddock/lib/._.DS_Store differ diff --git a/.venv_haddock/lib/._python3.12 b/.venv_haddock/lib/._python3.12 new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/._python3.12 differ diff --git a/.venv_haddock/lib/python3.12/._.DS_Store b/.venv_haddock/lib/python3.12/._.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..28c42fb20a1f27e695fb64323501fc6476578b13 Binary files /dev/null and b/.venv_haddock/lib/python3.12/._.DS_Store differ diff --git a/.venv_haddock/lib/python3.12/._site-packages b/.venv_haddock/lib/python3.12/._site-packages new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/._site-packages differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._.DS_Store b/.venv_haddock/lib/python3.12/site-packages/._.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..28c42fb20a1f27e695fb64323501fc6476578b13 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._.DS_Store differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._Bio b/.venv_haddock/lib/python3.12/site-packages/._Bio new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._Bio differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._BioSQL b/.venv_haddock/lib/python3.12/site-packages/._BioSQL new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._BioSQL differ diff --git a/.venv_haddock/lib/python3.12/site-packages/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/.__distutils_hack b/.venv_haddock/lib/python3.12/site-packages/.__distutils_hack new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/.__distutils_hack differ diff --git a/.venv_haddock/lib/python3.12/site-packages/.__plotly_utils b/.venv_haddock/lib/python3.12/site-packages/.__plotly_utils new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/.__plotly_utils differ diff --git a/.venv_haddock/lib/python3.12/site-packages/.__yaml b/.venv_haddock/lib/python3.12/site-packages/.__yaml new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/.__yaml differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._biopython-1.87.dist-info b/.venv_haddock/lib/python3.12/site-packages/._biopython-1.87.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._biopython-1.87.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._dateutil b/.venv_haddock/lib/python3.12/site-packages/._dateutil new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._dateutil differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._distutils-precedence.pth b/.venv_haddock/lib/python3.12/site-packages/._distutils-precedence.pth new file mode 100644 index 0000000000000000000000000000000000000000..1a316d03852d90a87a52d7747cdf1a6805e49e0f --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/._distutils-precedence.pth @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbd1f4c19356c9f782c0fce50a927d08f5a7a89ae88cc56fe8e671aeba8ef15d +size 4096 diff --git a/.venv_haddock/lib/python3.12/site-packages/._freesasa-2.2.1.dist-info b/.venv_haddock/lib/python3.12/site-packages/._freesasa-2.2.1.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._freesasa-2.2.1.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._freesasa.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/._freesasa.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._freesasa.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._haddock b/.venv_haddock/lib/python3.12/site-packages/._haddock new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._haddock differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._haddock3-2026.3.0.dist-info b/.venv_haddock/lib/python3.12/site-packages/._haddock3-2026.3.0.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._haddock3-2026.3.0.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._jsonpickle b/.venv_haddock/lib/python3.12/site-packages/._jsonpickle new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._jsonpickle differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._jsonpickle-4.1.1.dist-info b/.venv_haddock/lib/python3.12/site-packages/._jsonpickle-4.1.1.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._jsonpickle-4.1.1.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._narwhals b/.venv_haddock/lib/python3.12/site-packages/._narwhals new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._narwhals differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._narwhals-2.19.0.dist-info b/.venv_haddock/lib/python3.12/site-packages/._narwhals-2.19.0.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._narwhals-2.19.0.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._numpy b/.venv_haddock/lib/python3.12/site-packages/._numpy new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._numpy differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._numpy-2.4.4.dist-info b/.venv_haddock/lib/python3.12/site-packages/._numpy-2.4.4.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._numpy-2.4.4.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._packaging b/.venv_haddock/lib/python3.12/site-packages/._packaging new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._packaging differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._packaging-26.1.dist-info b/.venv_haddock/lib/python3.12/site-packages/._packaging-26.1.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._packaging-26.1.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._pandas b/.venv_haddock/lib/python3.12/site-packages/._pandas new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._pandas differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._pandas-2.3.3.dist-info b/.venv_haddock/lib/python3.12/site-packages/._pandas-2.3.3.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._pandas-2.3.3.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._pdb_tools-2.6.1.dist-info b/.venv_haddock/lib/python3.12/site-packages/._pdb_tools-2.6.1.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._pdb_tools-2.6.1.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._pdbtools b/.venv_haddock/lib/python3.12/site-packages/._pdbtools new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._pdbtools differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._pip b/.venv_haddock/lib/python3.12/site-packages/._pip new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._pip differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._pip-26.0.1.dist-info b/.venv_haddock/lib/python3.12/site-packages/._pip-26.0.1.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._pip-26.0.1.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._plotly b/.venv_haddock/lib/python3.12/site-packages/._plotly new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._plotly differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._plotly-6.5.2.dist-info b/.venv_haddock/lib/python3.12/site-packages/._plotly-6.5.2.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._plotly-6.5.2.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._prodigy_lig b/.venv_haddock/lib/python3.12/site-packages/._prodigy_lig new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._prodigy_lig differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._prodigy_lig-1.1.4.dist-info b/.venv_haddock/lib/python3.12/site-packages/._prodigy_lig-1.1.4.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._prodigy_lig-1.1.4.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._prodigy_prot b/.venv_haddock/lib/python3.12/site-packages/._prodigy_prot new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._prodigy_prot differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._prodigy_prot-2.3.0.dist-info b/.venv_haddock/lib/python3.12/site-packages/._prodigy_prot-2.3.0.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._prodigy_prot-2.3.0.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._python_dateutil-2.9.0.post0.dist-info b/.venv_haddock/lib/python3.12/site-packages/._python_dateutil-2.9.0.post0.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._python_dateutil-2.9.0.post0.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._pytz b/.venv_haddock/lib/python3.12/site-packages/._pytz new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._pytz differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._pytz-2026.1.post1.dist-info b/.venv_haddock/lib/python3.12/site-packages/._pytz-2026.1.post1.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._pytz-2026.1.post1.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._pyyaml-6.0.3.dist-info b/.venv_haddock/lib/python3.12/site-packages/._pyyaml-6.0.3.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._pyyaml-6.0.3.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._scipy b/.venv_haddock/lib/python3.12/site-packages/._scipy new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._scipy differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._scipy-1.17.1.dist-info b/.venv_haddock/lib/python3.12/site-packages/._scipy-1.17.1.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._scipy-1.17.1.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._setuptools b/.venv_haddock/lib/python3.12/site-packages/._setuptools new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._setuptools differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._setuptools-82.0.1.dist-info b/.venv_haddock/lib/python3.12/site-packages/._setuptools-82.0.1.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._setuptools-82.0.1.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._six-1.17.0.dist-info b/.venv_haddock/lib/python3.12/site-packages/._six-1.17.0.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._six-1.17.0.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._six.py b/.venv_haddock/lib/python3.12/site-packages/._six.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._six.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._toml b/.venv_haddock/lib/python3.12/site-packages/._toml new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._toml differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._toml-0.10.2.dist-info b/.venv_haddock/lib/python3.12/site-packages/._toml-0.10.2.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._toml-0.10.2.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._tzdata b/.venv_haddock/lib/python3.12/site-packages/._tzdata new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._tzdata differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._tzdata-2026.1.dist-info b/.venv_haddock/lib/python3.12/site-packages/._tzdata-2026.1.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._tzdata-2026.1.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._wheel b/.venv_haddock/lib/python3.12/site-packages/._wheel new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._wheel differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._wheel-0.46.3.dist-info b/.venv_haddock/lib/python3.12/site-packages/._wheel-0.46.3.dist-info new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._wheel-0.46.3.dist-info differ diff --git a/.venv_haddock/lib/python3.12/site-packages/._yaml b/.venv_haddock/lib/python3.12/site-packages/._yaml new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/._yaml differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Affy b/.venv_haddock/lib/python3.12/site-packages/Bio/._Affy new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Affy differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Align b/.venv_haddock/lib/python3.12/site-packages/Bio/._Align new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Align differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._AlignIO b/.venv_haddock/lib/python3.12/site-packages/Bio/._AlignIO new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._AlignIO differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Alphabet b/.venv_haddock/lib/python3.12/site-packages/Bio/._Alphabet new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Alphabet differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Blast b/.venv_haddock/lib/python3.12/site-packages/Bio/._Blast new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Blast differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._CAPS b/.venv_haddock/lib/python3.12/site-packages/Bio/._CAPS new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._CAPS differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Cluster b/.venv_haddock/lib/python3.12/site-packages/Bio/._Cluster new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Cluster differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Compass b/.venv_haddock/lib/python3.12/site-packages/Bio/._Compass new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Compass differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Data b/.venv_haddock/lib/python3.12/site-packages/Bio/._Data new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Data differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Emboss b/.venv_haddock/lib/python3.12/site-packages/Bio/._Emboss new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Emboss differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Entrez b/.venv_haddock/lib/python3.12/site-packages/Bio/._Entrez new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Entrez differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._ExPASy b/.venv_haddock/lib/python3.12/site-packages/Bio/._ExPASy new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._ExPASy differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._File.py b/.venv_haddock/lib/python3.12/site-packages/Bio/._File.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._File.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._GenBank b/.venv_haddock/lib/python3.12/site-packages/Bio/._GenBank new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._GenBank differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Geo b/.venv_haddock/lib/python3.12/site-packages/Bio/._Geo new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Geo differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Graphics b/.venv_haddock/lib/python3.12/site-packages/Bio/._Graphics new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Graphics differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._HMM b/.venv_haddock/lib/python3.12/site-packages/Bio/._HMM new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._HMM differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._KEGG b/.venv_haddock/lib/python3.12/site-packages/Bio/._KEGG new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._KEGG differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Medline b/.venv_haddock/lib/python3.12/site-packages/Bio/._Medline new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Medline differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._NMR b/.venv_haddock/lib/python3.12/site-packages/Bio/._NMR new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._NMR differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Nexus b/.venv_haddock/lib/python3.12/site-packages/Bio/._Nexus new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Nexus differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._PDB b/.venv_haddock/lib/python3.12/site-packages/Bio/._PDB new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._PDB differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Pathway b/.venv_haddock/lib/python3.12/site-packages/Bio/._Pathway new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Pathway differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Phylo b/.venv_haddock/lib/python3.12/site-packages/Bio/._Phylo new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Phylo differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._PopGen b/.venv_haddock/lib/python3.12/site-packages/Bio/._PopGen new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._PopGen differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Restriction b/.venv_haddock/lib/python3.12/site-packages/Bio/._Restriction new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Restriction differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._SCOP b/.venv_haddock/lib/python3.12/site-packages/Bio/._SCOP new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._SCOP differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._SVDSuperimposer b/.venv_haddock/lib/python3.12/site-packages/Bio/._SVDSuperimposer new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._SVDSuperimposer differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._SearchIO b/.venv_haddock/lib/python3.12/site-packages/Bio/._SearchIO new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._SearchIO differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Seq.py b/.venv_haddock/lib/python3.12/site-packages/Bio/._Seq.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Seq.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._SeqFeature.py b/.venv_haddock/lib/python3.12/site-packages/Bio/._SeqFeature.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._SeqFeature.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._SeqIO b/.venv_haddock/lib/python3.12/site-packages/Bio/._SeqIO new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._SeqIO differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._SeqRecord.py b/.venv_haddock/lib/python3.12/site-packages/Bio/._SeqRecord.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._SeqRecord.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._SeqUtils b/.venv_haddock/lib/python3.12/site-packages/Bio/._SeqUtils new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._SeqUtils differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._Sequencing b/.venv_haddock/lib/python3.12/site-packages/Bio/._Sequencing new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._Sequencing differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._SwissProt b/.venv_haddock/lib/python3.12/site-packages/Bio/._SwissProt new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._SwissProt differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._TogoWS b/.venv_haddock/lib/python3.12/site-packages/Bio/._TogoWS new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._TogoWS differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._UniGene b/.venv_haddock/lib/python3.12/site-packages/Bio/._UniGene new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._UniGene differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._UniProt b/.venv_haddock/lib/python3.12/site-packages/Bio/._UniProt new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._UniProt differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/Bio/.___init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/.___pycache__ differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/.__utils.py b/.venv_haddock/lib/python3.12/site-packages/Bio/.__utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/.__utils.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._bgzf.py b/.venv_haddock/lib/python3.12/site-packages/Bio/._bgzf.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._bgzf.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._codonalign b/.venv_haddock/lib/python3.12/site-packages/Bio/._codonalign new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._codonalign differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._cpairwise2.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/Bio/._cpairwise2.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._cpairwise2.cpython-312-darwin.so differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._cpairwise2module.c b/.venv_haddock/lib/python3.12/site-packages/Bio/._cpairwise2module.c new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._cpairwise2module.c differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._motifs b/.venv_haddock/lib/python3.12/site-packages/Bio/._motifs new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._motifs differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._pairwise2.py b/.venv_haddock/lib/python3.12/site-packages/Bio/._pairwise2.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._pairwise2.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._phenotype b/.venv_haddock/lib/python3.12/site-packages/Bio/._phenotype new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._phenotype differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/._py.typed b/.venv_haddock/lib/python3.12/site-packages/Bio/._py.typed new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/._py.typed differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/._CelFile.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Affy/.___pycache__ differ 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/Align/._AlignInfo.py b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._AlignInfo.py new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._AlignInfo.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/.___pycache__ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/.__aligncore.c differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/.__alignmentcounts.c differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/.__codonaligner.c differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/.__pairwisealigner.c differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/.__pairwisealigner.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/.__pairwisealigner.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/.__pairwisealigner.cpython-312-darwin.so differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/.__pairwisealigner.h differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._a2m.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._analysis.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._bed.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._bigbed.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._bigmaf.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._bigpsl.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._chain.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._clustal.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._emboss.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._exonerate.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._fasta.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._hhr.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._interfaces.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._maf.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._mauve.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._msf.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._nexus.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._phylip.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._psl.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._sam.py differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._stockholm.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._substitution_matrices b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._substitution_matrices new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._substitution_matrices differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/._tabular.py 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/_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.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.cpython-312-darwin.so new file mode 100644 index 0000000000000000000000000000000000000000..f0707490855e3f85a3bf9dc507613ff16c74ede1 --- /dev/null +++ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/_pairwisealigner.cpython-312-darwin.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34592b58728dc446174a1c26651fae128f590eb3e6801bcf932f29a82420a956 +size 191432 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/.___init__.py differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/.___pycache__ new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/.___pycache__ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/.__arraycore.c differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/.__arraycore.h differ diff --git a/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/._data b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/._data new file mode 100644 index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/._data differ 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/_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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._BENNER22 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._BENNER6 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._BENNER74 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._BLASTN differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._BLASTP differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._BLOSUM45 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._BLOSUM50 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._BLOSUM62 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._BLOSUM80 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._BLOSUM90 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._DAYHOFF differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._FENG differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._GENETIC differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._GONNET1992 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._HOXD70 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._JOHNSON differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._JONES differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._LEVIN differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._MCLACHLAN differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._MDM78 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._MEGABLAST differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._NUC.4.4 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._PAM250 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._PAM30 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._PAM70 differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._RAO differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._RISLER differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._SCHNEIDER differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._STR differ 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..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82 Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/Bio/Align/substitution_matrices/data/._TRANS differ 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