gapcheck 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gapcheck/__init__.py +23 -0
- gapcheck/cli.py +145 -0
- gapcheck/core.py +788 -0
- gapcheck-0.1.0.dist-info/METADATA +136 -0
- gapcheck-0.1.0.dist-info/RECORD +9 -0
- gapcheck-0.1.0.dist-info/WHEEL +5 -0
- gapcheck-0.1.0.dist-info/entry_points.txt +2 -0
- gapcheck-0.1.0.dist-info/licenses/LICENSE +21 -0
- gapcheck-0.1.0.dist-info/top_level.txt +1 -0
gapcheck/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from .core import (
|
|
2
|
+
AA20,
|
|
3
|
+
GAP_CHARS,
|
|
4
|
+
GapCheck,
|
|
5
|
+
GapCheckError,
|
|
6
|
+
audit_alignment,
|
|
7
|
+
parse_subfamilies,
|
|
8
|
+
read_fasta,
|
|
9
|
+
reliability_panel,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0"
|
|
13
|
+
__all__ = [
|
|
14
|
+
"AA20",
|
|
15
|
+
"GAP_CHARS",
|
|
16
|
+
"GapCheck",
|
|
17
|
+
"GapCheckError",
|
|
18
|
+
"__version__",
|
|
19
|
+
"audit_alignment",
|
|
20
|
+
"parse_subfamilies",
|
|
21
|
+
"read_fasta",
|
|
22
|
+
"reliability_panel",
|
|
23
|
+
]
|
gapcheck/cli.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from . import __version__
|
|
7
|
+
from .core import (
|
|
8
|
+
DEFAULT_MAX_GAP_FRAC,
|
|
9
|
+
DEFAULT_MIN_EFFECTIVE,
|
|
10
|
+
DEFAULT_SEED,
|
|
11
|
+
GapCheck,
|
|
12
|
+
GapCheckError,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
17
|
+
parser = argparse.ArgumentParser(
|
|
18
|
+
prog="gapcheck",
|
|
19
|
+
description=(
|
|
20
|
+
"GapCheck: Pre-scoring alignment diagnostics for gap inflation and\n"
|
|
21
|
+
"clade-partitioned conservation masking.\n\n"
|
|
22
|
+
"Column gap-inflation audit:\n"
|
|
23
|
+
" gapcheck -i alignment.fasta -o gapcheck_audit.csv\n\n"
|
|
24
|
+
"Full two-mode subfamily reliability panel:\n"
|
|
25
|
+
" gapcheck -i family.fasta -o panel.csv --ref P18827 --own SDC1 \\\n"
|
|
26
|
+
' --subfamilies "SDC1=Syndecan-1;SDC2=Syndecan-2;SDC3=Syndecan-3;SDC4=Syndecan-4"'
|
|
27
|
+
),
|
|
28
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
inp = parser.add_argument_group("Input and output")
|
|
32
|
+
inp.add_argument(
|
|
33
|
+
"-i",
|
|
34
|
+
"--input",
|
|
35
|
+
"--fasta",
|
|
36
|
+
dest="fasta",
|
|
37
|
+
metavar="FASTA",
|
|
38
|
+
required=True,
|
|
39
|
+
help="Aligned FASTA file (.fasta, .fa, .afa, .aln).",
|
|
40
|
+
)
|
|
41
|
+
inp.add_argument(
|
|
42
|
+
"-o",
|
|
43
|
+
"--output",
|
|
44
|
+
metavar="CSV",
|
|
45
|
+
default="gapcheck_report.csv",
|
|
46
|
+
help="Output CSV path [default: gapcheck_report.csv].",
|
|
47
|
+
)
|
|
48
|
+
inp.add_argument(
|
|
49
|
+
"--pdb",
|
|
50
|
+
metavar="PDB",
|
|
51
|
+
default=None,
|
|
52
|
+
help="Optional PDB coordinate file to project diagnostic scores into B-factors.",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
sub = parser.add_argument_group("Reference and subfamily options")
|
|
56
|
+
sub.add_argument(
|
|
57
|
+
"--ref",
|
|
58
|
+
metavar="HEADER_SUBSTR",
|
|
59
|
+
default=None,
|
|
60
|
+
help="Substring identifying a target reference sequence header.",
|
|
61
|
+
)
|
|
62
|
+
sub.add_argument(
|
|
63
|
+
"--own",
|
|
64
|
+
metavar="LABEL",
|
|
65
|
+
default=None,
|
|
66
|
+
help="Subfamily label to which the reference sequence belongs.",
|
|
67
|
+
)
|
|
68
|
+
sub.add_argument(
|
|
69
|
+
"--subfamilies",
|
|
70
|
+
metavar="SPEC",
|
|
71
|
+
default=None,
|
|
72
|
+
help='Semicolon-delimited subfamily rules: "SUB1=pat1;SUB2=pat2".',
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
thr = parser.add_argument_group("Thresholds and permutation settings")
|
|
76
|
+
thr.add_argument(
|
|
77
|
+
"--max-gap",
|
|
78
|
+
type=float,
|
|
79
|
+
default=DEFAULT_MAX_GAP_FRAC,
|
|
80
|
+
help=f"Gap-fraction flag threshold [default: {DEFAULT_MAX_GAP_FRAC}].",
|
|
81
|
+
)
|
|
82
|
+
thr.add_argument(
|
|
83
|
+
"--min-effective",
|
|
84
|
+
type=int,
|
|
85
|
+
default=DEFAULT_MIN_EFFECTIVE,
|
|
86
|
+
help=f"Minimum ungapped comparator sequences [default: {DEFAULT_MIN_EFFECTIVE}].",
|
|
87
|
+
)
|
|
88
|
+
thr.add_argument(
|
|
89
|
+
"--n-perm",
|
|
90
|
+
type=int,
|
|
91
|
+
default=1000,
|
|
92
|
+
help="Number of column permutations for subfamily SEF null [default: 1000].",
|
|
93
|
+
)
|
|
94
|
+
thr.add_argument(
|
|
95
|
+
"--seed",
|
|
96
|
+
type=int,
|
|
97
|
+
default=DEFAULT_SEED,
|
|
98
|
+
help=f"Random seed for reproducible permutation p-values [default: {DEFAULT_SEED}].",
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
beh = parser.add_argument_group("Behaviour")
|
|
102
|
+
beh.add_argument(
|
|
103
|
+
"-q",
|
|
104
|
+
"--quiet",
|
|
105
|
+
action="store_true",
|
|
106
|
+
default=False,
|
|
107
|
+
help="Suppress terminal progress and summary output.",
|
|
108
|
+
)
|
|
109
|
+
beh.add_argument(
|
|
110
|
+
"--version",
|
|
111
|
+
action="version",
|
|
112
|
+
version=f"%(prog)s {__version__}",
|
|
113
|
+
)
|
|
114
|
+
return parser
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def main(argv=None) -> None:
|
|
118
|
+
parser = build_parser()
|
|
119
|
+
args, unknown = parser.parse_known_args(argv)
|
|
120
|
+
if unknown and not args.quiet:
|
|
121
|
+
print(f"[gapcheck] Ignoring unrecognized arguments: {unknown}", file=sys.stderr)
|
|
122
|
+
|
|
123
|
+
runner = GapCheck(
|
|
124
|
+
fasta_file=args.fasta,
|
|
125
|
+
output_file=args.output,
|
|
126
|
+
ref=args.ref,
|
|
127
|
+
own=args.own,
|
|
128
|
+
subfamilies=args.subfamilies,
|
|
129
|
+
max_gap_frac=args.max_gap,
|
|
130
|
+
min_effective=args.min_effective,
|
|
131
|
+
n_perm=args.n_perm,
|
|
132
|
+
seed=args.seed,
|
|
133
|
+
pdb_file=args.pdb,
|
|
134
|
+
verbose=not args.quiet,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
try:
|
|
138
|
+
runner.run_all()
|
|
139
|
+
except (GapCheckError, OSError) as exc:
|
|
140
|
+
print(f"[gapcheck] Error: {exc}", file=sys.stderr)
|
|
141
|
+
sys.exit(1)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
if __name__ == "__main__":
|
|
145
|
+
main()
|
gapcheck/core.py
ADDED
|
@@ -0,0 +1,788 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import io
|
|
5
|
+
import math
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from collections import Counter
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
AA20 = "ACDEFGHIKLMNPQRSTVWY"
|
|
15
|
+
AA_SET = frozenset(AA20)
|
|
16
|
+
GAP_CHARS = frozenset("-.~")
|
|
17
|
+
LOG2_21 = math.log2(21.0)
|
|
18
|
+
LOG2_20 = math.log2(20.0)
|
|
19
|
+
|
|
20
|
+
DEFAULT_MAX_GAP_FRAC = 0.25
|
|
21
|
+
DEFAULT_MIN_EFFECTIVE = 5
|
|
22
|
+
DEFAULT_H_MIN = 0.50
|
|
23
|
+
DEFAULT_SEF_HI = 0.50
|
|
24
|
+
DEFAULT_SEF_LO = 0.25
|
|
25
|
+
DEFAULT_P_MAX = 0.05
|
|
26
|
+
DEFAULT_MIN_SUBFAMILY_N = 2
|
|
27
|
+
DEFAULT_INV_FAM_MAX = 0.50
|
|
28
|
+
DEFAULT_INV_OWN_MIN = 0.90
|
|
29
|
+
DEFAULT_SISTER_FIX = 1.0
|
|
30
|
+
DEFAULT_SEED = 20261007
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class GapCheckError(ValueError):
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def read_fasta(source: Union[str, os.PathLike]) -> Dict[str, str]:
|
|
38
|
+
text: str
|
|
39
|
+
if isinstance(source, os.PathLike) or (
|
|
40
|
+
isinstance(source, str) and "\n" not in source and os.path.exists(source)
|
|
41
|
+
):
|
|
42
|
+
with open(source, "r", encoding="utf-8") as fh:
|
|
43
|
+
text = fh.read()
|
|
44
|
+
elif isinstance(source, str):
|
|
45
|
+
if not source.lstrip().startswith(">") and not source.lstrip().startswith(";"):
|
|
46
|
+
raise GapCheckError(f"FASTA file not found or invalid FASTA text: {source!r}")
|
|
47
|
+
text = source
|
|
48
|
+
else:
|
|
49
|
+
raise GapCheckError("Expected a file path or FASTA string.")
|
|
50
|
+
|
|
51
|
+
seqs: Dict[str, List[str]] = {}
|
|
52
|
+
current: Optional[str] = None
|
|
53
|
+
for raw_line in text.splitlines():
|
|
54
|
+
line = raw_line.strip()
|
|
55
|
+
if not line or line.startswith(";"):
|
|
56
|
+
continue
|
|
57
|
+
if line.startswith(">"):
|
|
58
|
+
header = line[1:].strip() or f"sequence_{len(seqs) + 1}"
|
|
59
|
+
if header in seqs:
|
|
60
|
+
raise GapCheckError(f"Duplicate FASTA header: {header!r}")
|
|
61
|
+
seqs[header] = []
|
|
62
|
+
current = header
|
|
63
|
+
else:
|
|
64
|
+
if current is None:
|
|
65
|
+
raise GapCheckError(
|
|
66
|
+
f"Content appears before first '>' header: {line[:48]!r}"
|
|
67
|
+
)
|
|
68
|
+
seqs[current].append(re.sub(r"\s+", "", line))
|
|
69
|
+
|
|
70
|
+
if not seqs:
|
|
71
|
+
raise GapCheckError("No FASTA headers found.")
|
|
72
|
+
|
|
73
|
+
out: Dict[str, str] = {}
|
|
74
|
+
for header, parts in seqs.items():
|
|
75
|
+
joined = "".join(parts)
|
|
76
|
+
if not joined:
|
|
77
|
+
raise GapCheckError(f"Sequence {header!r} has a header with zero residues.")
|
|
78
|
+
out[header] = joined
|
|
79
|
+
|
|
80
|
+
widths = {len(s) for s in out.values()}
|
|
81
|
+
if len(widths) != 1:
|
|
82
|
+
first_h = next(iter(out))
|
|
83
|
+
bad_h = next(h for h, s in out.items() if len(s) != len(out[first_h]))
|
|
84
|
+
raise GapCheckError(
|
|
85
|
+
f"Sequences do not share a common aligned width: {first_h!r} has "
|
|
86
|
+
f"{len(out[first_h])} columns while {bad_h!r} has {len(out[bad_h])}."
|
|
87
|
+
)
|
|
88
|
+
if len(out) < 2:
|
|
89
|
+
raise GapCheckError("At least two aligned sequences are required.")
|
|
90
|
+
|
|
91
|
+
return out
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _spearman_rho(x: Sequence[float], y: Sequence[float]) -> Optional[float]:
|
|
95
|
+
if len(x) < 3 or len(x) != len(y):
|
|
96
|
+
return None
|
|
97
|
+
ax = np.asarray(x, dtype=float)
|
|
98
|
+
ay = np.asarray(y, dtype=float)
|
|
99
|
+
if np.all(ax == ax[0]) or np.all(ay == ay[0]):
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
def _ranks(arr: np.ndarray) -> np.ndarray:
|
|
103
|
+
order = np.argsort(arr, kind="mergesort")
|
|
104
|
+
ranks = np.empty_like(arr, dtype=float)
|
|
105
|
+
n = len(arr)
|
|
106
|
+
i = 0
|
|
107
|
+
while i < n:
|
|
108
|
+
j = i
|
|
109
|
+
while j + 1 < n and arr[order[j + 1]] == arr[order[i]]:
|
|
110
|
+
j += 1
|
|
111
|
+
avg = 0.5 * (i + j) + 1.0
|
|
112
|
+
ranks[order[i : j + 1]] = avg
|
|
113
|
+
i = j + 1
|
|
114
|
+
return ranks
|
|
115
|
+
|
|
116
|
+
rx = _ranks(ax)
|
|
117
|
+
ry = _ranks(ay)
|
|
118
|
+
rx -= rx.mean()
|
|
119
|
+
ry -= ry.mean()
|
|
120
|
+
denom = float(np.sqrt(np.sum(rx * rx) * np.sum(ry * ry)))
|
|
121
|
+
return float(np.sum(rx * ry) / denom) if denom > 0.0 else None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _pearson_r(x: Sequence[float], y: Sequence[float]) -> Optional[float]:
|
|
125
|
+
if len(x) < 3 or len(x) != len(y):
|
|
126
|
+
return None
|
|
127
|
+
ax = np.asarray(x, dtype=float)
|
|
128
|
+
ay = np.asarray(y, dtype=float)
|
|
129
|
+
ax = ax - ax.mean()
|
|
130
|
+
ay = ay - ay.mean()
|
|
131
|
+
denom = float(np.sqrt(np.sum(ax * ax) * np.sum(ay * ay)))
|
|
132
|
+
return float(np.sum(ax * ay) / denom) if denom > 0.0 else None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _resolve_reference(msa: Mapping[str, str], ref: Optional[str]) -> Optional[str]:
|
|
136
|
+
if ref is None:
|
|
137
|
+
return None
|
|
138
|
+
if ref in msa:
|
|
139
|
+
return ref
|
|
140
|
+
matches = [h for h in msa if ref in h]
|
|
141
|
+
if not matches:
|
|
142
|
+
raise GapCheckError(f"No FASTA header matches reference substring {ref!r}.")
|
|
143
|
+
if len(matches) > 1:
|
|
144
|
+
raise GapCheckError(
|
|
145
|
+
f"Reference substring {ref!r} matched {len(matches)} headers: {matches[:4]!r}"
|
|
146
|
+
)
|
|
147
|
+
return matches[0]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@dataclass
|
|
151
|
+
class TableResult:
|
|
152
|
+
mode: str
|
|
153
|
+
rows: List[Dict[str, object]]
|
|
154
|
+
summary: Dict[str, object]
|
|
155
|
+
fieldnames: List[str]
|
|
156
|
+
|
|
157
|
+
def to_csv(self, path: Optional[Union[str, os.PathLike]] = None) -> str:
|
|
158
|
+
buf = io.StringIO()
|
|
159
|
+
writer = csv.DictWriter(
|
|
160
|
+
buf, fieldnames=self.fieldnames, extrasaction="ignore", lineterminator="\n"
|
|
161
|
+
)
|
|
162
|
+
writer.writeheader()
|
|
163
|
+
for row in self.rows:
|
|
164
|
+
clean = {
|
|
165
|
+
k: ("" if row.get(k) is None else row.get(k)) for k in self.fieldnames
|
|
166
|
+
}
|
|
167
|
+
writer.writerow(clean)
|
|
168
|
+
content = buf.getvalue()
|
|
169
|
+
if path is not None:
|
|
170
|
+
out_dir = os.path.dirname(os.path.abspath(path))
|
|
171
|
+
if out_dir and not os.path.exists(out_dir):
|
|
172
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
173
|
+
with open(path, "w", encoding="utf-8", newline="") as fh:
|
|
174
|
+
fh.write(content)
|
|
175
|
+
return content
|
|
176
|
+
|
|
177
|
+
def to_dataframe(self):
|
|
178
|
+
try:
|
|
179
|
+
import pandas as pd
|
|
180
|
+
except ImportError as exc:
|
|
181
|
+
raise ImportError(
|
|
182
|
+
"Install pandas ('pip install gapcheck[dataframe]') to call to_dataframe()."
|
|
183
|
+
) from exc
|
|
184
|
+
return pd.DataFrame(self.rows, columns=self.fieldnames)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def audit_alignment(
|
|
188
|
+
msa_or_path: Union[Mapping[str, str], str, os.PathLike],
|
|
189
|
+
ref: Optional[str] = None,
|
|
190
|
+
max_gap_frac: float = DEFAULT_MAX_GAP_FRAC,
|
|
191
|
+
min_effective: int = DEFAULT_MIN_EFFECTIVE,
|
|
192
|
+
) -> TableResult:
|
|
193
|
+
msa = (
|
|
194
|
+
dict(msa_or_path)
|
|
195
|
+
if isinstance(msa_or_path, Mapping)
|
|
196
|
+
else read_fasta(msa_or_path)
|
|
197
|
+
)
|
|
198
|
+
seqs = list(msa.values())
|
|
199
|
+
n_seqs = len(seqs)
|
|
200
|
+
width = len(seqs[0])
|
|
201
|
+
|
|
202
|
+
ref_header = _resolve_reference(msa, ref)
|
|
203
|
+
ref_row = msa[ref_header] if ref_header is not None else None
|
|
204
|
+
col_to_ref: Dict[int, Tuple[int, str]] = {}
|
|
205
|
+
if ref_row is not None:
|
|
206
|
+
pos = 0
|
|
207
|
+
for col_idx, ch in enumerate(ref_row):
|
|
208
|
+
up = ch.upper()
|
|
209
|
+
if up not in GAP_CHARS:
|
|
210
|
+
pos += 1
|
|
211
|
+
col_to_ref[col_idx] = (pos, up)
|
|
212
|
+
|
|
213
|
+
rows: List[Dict[str, object]] = []
|
|
214
|
+
pairs_rep: List[Tuple[float, float]] = []
|
|
215
|
+
pairs_free: List[Tuple[float, float]] = []
|
|
216
|
+
|
|
217
|
+
for c in range(width):
|
|
218
|
+
cnt: Counter = Counter()
|
|
219
|
+
n_gap = 0
|
|
220
|
+
n_other = 0
|
|
221
|
+
for s in seqs:
|
|
222
|
+
ch = s[c].upper()
|
|
223
|
+
if ch in GAP_CHARS:
|
|
224
|
+
n_gap += 1
|
|
225
|
+
elif ch in AA_SET:
|
|
226
|
+
cnt[ch] += 1
|
|
227
|
+
else:
|
|
228
|
+
n_other += 1
|
|
229
|
+
|
|
230
|
+
n_res = sum(cnt.values())
|
|
231
|
+
n_used = n_res + n_gap
|
|
232
|
+
h21 = 0.0
|
|
233
|
+
h20 = 0.0
|
|
234
|
+
if n_used > 0:
|
|
235
|
+
for v in list(cnt.values()) + ([n_gap] if n_gap else []):
|
|
236
|
+
p = v / n_used
|
|
237
|
+
h21 -= p * math.log2(p)
|
|
238
|
+
if n_res > 0:
|
|
239
|
+
for v in cnt.values():
|
|
240
|
+
q = v / n_res
|
|
241
|
+
h20 -= q * math.log2(q)
|
|
242
|
+
|
|
243
|
+
gf = n_gap / n_used if n_used > 0 else 1.0
|
|
244
|
+
rep = 1.0 - (h21 / LOG2_21) if n_used > 0 else None
|
|
245
|
+
free = 1.0 - (h20 / LOG2_20) if n_res > 0 else None
|
|
246
|
+
delta = (rep - free) if (rep is not None and free is not None) else None
|
|
247
|
+
|
|
248
|
+
if gf > max_gap_frac:
|
|
249
|
+
verdict = "gap_inflated"
|
|
250
|
+
error_sign = "reported conservation too high"
|
|
251
|
+
elif n_res < min_effective:
|
|
252
|
+
verdict = "depth_starved"
|
|
253
|
+
error_sign = "no estimate"
|
|
254
|
+
else:
|
|
255
|
+
verdict = "usable"
|
|
256
|
+
error_sign = ""
|
|
257
|
+
|
|
258
|
+
if rep is not None:
|
|
259
|
+
pairs_rep.append((gf, rep))
|
|
260
|
+
if free is not None:
|
|
261
|
+
pairs_free.append((gf, free))
|
|
262
|
+
|
|
263
|
+
row: Dict[str, object] = {
|
|
264
|
+
"column": c + 1,
|
|
265
|
+
"gap_fraction": gf,
|
|
266
|
+
"effective_comparators": n_res,
|
|
267
|
+
"conservation_reported": rep,
|
|
268
|
+
"conservation_gap_free": free,
|
|
269
|
+
"delta": delta,
|
|
270
|
+
"verdict": verdict,
|
|
271
|
+
"error_sign": error_sign,
|
|
272
|
+
"nonstandard": n_other,
|
|
273
|
+
}
|
|
274
|
+
if ref_header is not None:
|
|
275
|
+
ref_info = col_to_ref.get(c)
|
|
276
|
+
row["ref_position"] = ref_info[0] if ref_info else None
|
|
277
|
+
row["wt"] = ref_info[1] if ref_info else None
|
|
278
|
+
rows.append(row)
|
|
279
|
+
|
|
280
|
+
counts = Counter(str(r["verdict"]) for r in rows)
|
|
281
|
+
r_rep = _pearson_r([x for x, _ in pairs_rep], [y for _, y in pairs_rep])
|
|
282
|
+
r_free = _pearson_r([x for x, _ in pairs_free], [y for _, y in pairs_free])
|
|
283
|
+
rho_rep = _spearman_rho([x for x, _ in pairs_rep], [y for _, y in pairs_rep])
|
|
284
|
+
rho_free = _spearman_rho([x for x, _ in pairs_free], [y for _, y in pairs_free])
|
|
285
|
+
|
|
286
|
+
summary: Dict[str, object] = {
|
|
287
|
+
"n_sequences": n_seqs,
|
|
288
|
+
"n_columns": width,
|
|
289
|
+
"reference": ref_header,
|
|
290
|
+
"usable": counts.get("usable", 0),
|
|
291
|
+
"gap_inflated": counts.get("gap_inflated", 0),
|
|
292
|
+
"depth_starved": counts.get("depth_starved", 0),
|
|
293
|
+
"flagged": width - counts.get("usable", 0),
|
|
294
|
+
"pearson_gap_vs_reported": r_rep,
|
|
295
|
+
"pearson_gap_vs_gap_free": r_free,
|
|
296
|
+
"spearman_gap_vs_reported": rho_rep,
|
|
297
|
+
"spearman_gap_vs_gap_free": rho_free,
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
fieldnames = [
|
|
301
|
+
"column",
|
|
302
|
+
*(["ref_position", "wt"] if ref_header is not None else []),
|
|
303
|
+
"gap_fraction",
|
|
304
|
+
"effective_comparators",
|
|
305
|
+
"conservation_reported",
|
|
306
|
+
"conservation_gap_free",
|
|
307
|
+
"delta",
|
|
308
|
+
"verdict",
|
|
309
|
+
"error_sign",
|
|
310
|
+
"nonstandard",
|
|
311
|
+
]
|
|
312
|
+
return TableResult(mode="audit", rows=rows, summary=summary, fieldnames=fieldnames)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def parse_subfamilies(spec: Union[str, Mapping[str, Union[str, Sequence[str]]]]) -> Dict[str, Tuple[str, ...]]:
|
|
316
|
+
if isinstance(spec, Mapping):
|
|
317
|
+
out_map: Dict[str, Tuple[str, ...]] = {}
|
|
318
|
+
for lab, pats in spec.items():
|
|
319
|
+
if isinstance(pats, str):
|
|
320
|
+
out_map[str(lab).strip()] = (pats,)
|
|
321
|
+
else:
|
|
322
|
+
out_map[str(lab).strip()] = tuple(str(x) for x in pats if str(x))
|
|
323
|
+
return out_map
|
|
324
|
+
|
|
325
|
+
out: Dict[str, List[str]] = {}
|
|
326
|
+
for part in str(spec).split(";"):
|
|
327
|
+
if not part.strip():
|
|
328
|
+
continue
|
|
329
|
+
if "=" not in part:
|
|
330
|
+
raise GapCheckError(f"Subfamily specification {part!r} must use 'label=pattern'.")
|
|
331
|
+
lab, pat = part.split("=", 1)
|
|
332
|
+
lab_clean = lab.strip()
|
|
333
|
+
pat_clean = pat.strip()
|
|
334
|
+
if not lab_clean or not pat_clean:
|
|
335
|
+
raise GapCheckError(f"Empty label or pattern in {part!r}.")
|
|
336
|
+
out.setdefault(lab_clean, []).append(pat_clean)
|
|
337
|
+
if not out:
|
|
338
|
+
raise GapCheckError("No subfamily patterns parsed.")
|
|
339
|
+
return {k: tuple(v) for k, v in out.items()}
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _protein_label_target(header: str) -> str:
|
|
343
|
+
m = re.search(r"\|\S+\s+(.+?)\s+OS=", header)
|
|
344
|
+
return m.group(1) if m else header
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _assign_subfamily_labels(
|
|
348
|
+
headers: Iterable[str], patterns: Mapping[str, Sequence[str]]
|
|
349
|
+
) -> Tuple[Dict[str, str], List[str]]:
|
|
350
|
+
labels: Dict[str, str] = {}
|
|
351
|
+
unlabelled: List[str] = []
|
|
352
|
+
for h in headers:
|
|
353
|
+
target = _protein_label_target(h)
|
|
354
|
+
hits = [
|
|
355
|
+
lab
|
|
356
|
+
for lab, pats in patterns.items()
|
|
357
|
+
if any(p in target or p in h for p in pats)
|
|
358
|
+
]
|
|
359
|
+
if len(hits) > 1:
|
|
360
|
+
raise GapCheckError(
|
|
361
|
+
f"Header {h!r} matched multiple subfamilies {sorted(hits)!r}; patterns must form a disjoint partition."
|
|
362
|
+
)
|
|
363
|
+
if hits:
|
|
364
|
+
labels[h] = hits[0]
|
|
365
|
+
else:
|
|
366
|
+
unlabelled.append(h)
|
|
367
|
+
return labels, unlabelled
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _entropy_bits(counts: Counter, n: int) -> float:
|
|
371
|
+
if n <= 0:
|
|
372
|
+
return 0.0
|
|
373
|
+
h = -sum((v / n) * math.log2(v / n) for v in counts.values() if v > 0)
|
|
374
|
+
return abs(h)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _sef(residues: Sequence[str], labels: Sequence[str]) -> Tuple[Optional[float], float, float]:
|
|
378
|
+
n = len(residues)
|
|
379
|
+
if n == 0:
|
|
380
|
+
return None, 0.0, 0.0
|
|
381
|
+
h_total = _entropy_bits(Counter(residues), n)
|
|
382
|
+
if h_total <= 0.0:
|
|
383
|
+
return None, 0.0, 0.0
|
|
384
|
+
h_within = 0.0
|
|
385
|
+
for lab in set(labels):
|
|
386
|
+
grp = [r for r, l in zip(residues, labels) if l == lab]
|
|
387
|
+
h_within += (len(grp) / n) * _entropy_bits(Counter(grp), len(grp))
|
|
388
|
+
mi = h_total - h_within
|
|
389
|
+
return max(0.0, mi) / h_total, h_total, mi
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _column_partition(
|
|
393
|
+
residues: Sequence[str], labels: Sequence[str], rng: np.random.Generator, n_perm: int
|
|
394
|
+
) -> Dict[str, object]:
|
|
395
|
+
sef_val, h_total, mi = _sef(residues, labels)
|
|
396
|
+
if sef_val is None:
|
|
397
|
+
return {
|
|
398
|
+
"n": len(residues),
|
|
399
|
+
"h_total": 0.0,
|
|
400
|
+
"mi": 0.0,
|
|
401
|
+
"sef": None,
|
|
402
|
+
"sef_null": None,
|
|
403
|
+
"sef_adj": None,
|
|
404
|
+
"z": None,
|
|
405
|
+
"p_perm": None,
|
|
406
|
+
}
|
|
407
|
+
arr = np.asarray(residues)
|
|
408
|
+
null = np.empty(n_perm, dtype=float)
|
|
409
|
+
for i in range(n_perm):
|
|
410
|
+
perm = rng.permutation(arr).tolist()
|
|
411
|
+
null[i] = _sef(perm, labels)[0] or 0.0
|
|
412
|
+
null_mean = float(null.mean())
|
|
413
|
+
null_sd = float(null.std(ddof=1)) if n_perm > 1 else 0.0
|
|
414
|
+
denom = 1.0 - null_mean
|
|
415
|
+
sef_adj = max(0.0, (sef_val - null_mean) / denom) if denom > 1e-12 else 0.0
|
|
416
|
+
z = (sef_val - null_mean) / null_sd if null_sd > 1e-12 else float("inf")
|
|
417
|
+
p_perm = (1.0 + float(np.sum(null >= sef_val - 1e-12))) / (n_perm + 1.0)
|
|
418
|
+
return {
|
|
419
|
+
"n": len(residues),
|
|
420
|
+
"h_total": h_total,
|
|
421
|
+
"mi": mi,
|
|
422
|
+
"sef": sef_val,
|
|
423
|
+
"sef_null": null_mean,
|
|
424
|
+
"sef_adj": sef_adj,
|
|
425
|
+
"z": z,
|
|
426
|
+
"p_perm": p_perm,
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def reliability_panel(
|
|
431
|
+
msa_or_path: Union[Mapping[str, str], str, os.PathLike],
|
|
432
|
+
ref: str,
|
|
433
|
+
own: str,
|
|
434
|
+
subfamilies: Union[str, Mapping[str, Union[str, Sequence[str]]]],
|
|
435
|
+
max_gap_frac: float = DEFAULT_MAX_GAP_FRAC,
|
|
436
|
+
min_effective: int = DEFAULT_MIN_EFFECTIVE,
|
|
437
|
+
min_subfamily_n: int = DEFAULT_MIN_SUBFAMILY_N,
|
|
438
|
+
h_min: float = DEFAULT_H_MIN,
|
|
439
|
+
sef_hi: float = DEFAULT_SEF_HI,
|
|
440
|
+
sef_lo: float = DEFAULT_SEF_LO,
|
|
441
|
+
p_max: float = DEFAULT_P_MAX,
|
|
442
|
+
sister_fix: float = DEFAULT_SISTER_FIX,
|
|
443
|
+
n_perm: int = 1000,
|
|
444
|
+
seed: int = DEFAULT_SEED,
|
|
445
|
+
) -> TableResult:
|
|
446
|
+
msa_all = (
|
|
447
|
+
dict(msa_or_path)
|
|
448
|
+
if isinstance(msa_or_path, Mapping)
|
|
449
|
+
else read_fasta(msa_or_path)
|
|
450
|
+
)
|
|
451
|
+
subs = parse_subfamilies(subfamilies)
|
|
452
|
+
if own not in subs:
|
|
453
|
+
raise GapCheckError(f"Own subfamily {own!r} is not in {sorted(subs)!r}.")
|
|
454
|
+
|
|
455
|
+
ref_header = _resolve_reference(msa_all, ref)
|
|
456
|
+
assert ref_header is not None
|
|
457
|
+
labels, unlabelled = _assign_subfamily_labels(msa_all.keys(), subs)
|
|
458
|
+
if labels.get(ref_header) != own:
|
|
459
|
+
raise GapCheckError(
|
|
460
|
+
f"Reference header {ref_header!r} was assigned label {labels.get(ref_header)!r}, expected {own!r}."
|
|
461
|
+
)
|
|
462
|
+
|
|
463
|
+
msa = {h: s.upper() for h, s in msa_all.items() if h in labels}
|
|
464
|
+
sister_labels = sorted(lab for lab in set(labels.values()) if lab != own)
|
|
465
|
+
ref_row = msa[ref_header]
|
|
466
|
+
|
|
467
|
+
pos_to_col: List[Tuple[int, int, str]] = []
|
|
468
|
+
pos = 0
|
|
469
|
+
for col_idx, ch in enumerate(ref_row):
|
|
470
|
+
if ch not in GAP_CHARS:
|
|
471
|
+
pos += 1
|
|
472
|
+
pos_to_col.append((pos, col_idx, ch))
|
|
473
|
+
|
|
474
|
+
rng = np.random.default_rng(seed)
|
|
475
|
+
rows: List[Dict[str, object]] = []
|
|
476
|
+
|
|
477
|
+
for ref_pos, col_idx, wt in pos_to_col:
|
|
478
|
+
raw_comparators = [
|
|
479
|
+
(h, msa[h][col_idx]) for h in msa if h != ref_header
|
|
480
|
+
]
|
|
481
|
+
n_gapped = sum(1 for _, ch in raw_comparators if ch in GAP_CHARS)
|
|
482
|
+
gap_frac = n_gapped / len(raw_comparators) if raw_comparators else 1.0
|
|
483
|
+
|
|
484
|
+
ungapped = [
|
|
485
|
+
(h, ch) for h, ch in raw_comparators if ch in AA_SET
|
|
486
|
+
]
|
|
487
|
+
sub_sizes = Counter(labels[h] for h, _ in ungapped)
|
|
488
|
+
dropped = sorted(lab for lab, cnt_s in sub_sizes.items() if cnt_s < min_subfamily_n)
|
|
489
|
+
kept = [(h, ch) for h, ch in ungapped if labels[h] not in dropped]
|
|
490
|
+
|
|
491
|
+
res_list = [ch for _, ch in kept]
|
|
492
|
+
lab_list = [labels[h] for h, _ in kept]
|
|
493
|
+
stat = _column_partition(res_list, lab_list, rng=rng, n_perm=n_perm)
|
|
494
|
+
|
|
495
|
+
sef_val = stat["sef"]
|
|
496
|
+
h_total = float(stat["h_total"])
|
|
497
|
+
sef_adj = stat["sef_adj"]
|
|
498
|
+
p_perm = stat["p_perm"]
|
|
499
|
+
|
|
500
|
+
if sef_val is None or h_total < h_min:
|
|
501
|
+
call = "conserved"
|
|
502
|
+
elif sef_adj is not None and p_perm is not None and sef_adj >= sef_hi and p_perm <= p_max:
|
|
503
|
+
call = "diagnostic"
|
|
504
|
+
elif sef_adj is not None and sef_adj < sef_lo:
|
|
505
|
+
call = "tolerant"
|
|
506
|
+
else:
|
|
507
|
+
call = "indeterminate"
|
|
508
|
+
|
|
509
|
+
n_eff = int(stat["n"])
|
|
510
|
+
if gap_frac > max_gap_frac:
|
|
511
|
+
verdict = "gap_inflated"
|
|
512
|
+
sign = "reported conservation too high"
|
|
513
|
+
elif n_eff < min_effective:
|
|
514
|
+
verdict = "depth_starved"
|
|
515
|
+
sign = "no estimate"
|
|
516
|
+
elif call == "diagnostic":
|
|
517
|
+
verdict = "clade_partitioned"
|
|
518
|
+
sign = "family conservation too low"
|
|
519
|
+
else:
|
|
520
|
+
verdict = "ok"
|
|
521
|
+
sign = ""
|
|
522
|
+
|
|
523
|
+
fam_res = [ch for _, ch in ungapped]
|
|
524
|
+
own_res = [ch for h, ch in ungapped if labels[h] == own]
|
|
525
|
+
f_fam = (fam_res.count(wt) / len(fam_res)) if fam_res else None
|
|
526
|
+
f_own = (own_res.count(wt) / len(own_res)) if own_res else None
|
|
527
|
+
is_inv = (
|
|
528
|
+
bool(f_fam < DEFAULT_INV_FAM_MAX and f_own >= DEFAULT_INV_OWN_MIN)
|
|
529
|
+
if (f_fam is not None and f_own is not None)
|
|
530
|
+
else None
|
|
531
|
+
)
|
|
532
|
+
|
|
533
|
+
sisters: List[str] = []
|
|
534
|
+
for s_lab in sister_labels:
|
|
535
|
+
vals = [ch for h, ch in ungapped if labels[h] == s_lab]
|
|
536
|
+
if not vals:
|
|
537
|
+
continue
|
|
538
|
+
top_aa, top_n = Counter(vals).most_common(1)[0]
|
|
539
|
+
if (top_n / len(vals)) >= sister_fix and top_aa != wt:
|
|
540
|
+
sisters.append(f"{wt}>{top_aa}:{s_lab}")
|
|
541
|
+
|
|
542
|
+
dist_str = " ".join(f"{aa}:{cnt_a}" for aa, cnt_a in Counter(res_list).most_common())
|
|
543
|
+
rows.append(
|
|
544
|
+
{
|
|
545
|
+
"position": ref_pos,
|
|
546
|
+
"column": col_idx + 1,
|
|
547
|
+
"wt": wt,
|
|
548
|
+
"verdict": verdict,
|
|
549
|
+
"error_sign": sign,
|
|
550
|
+
"n_effective": n_eff,
|
|
551
|
+
"gap_frac": round(gap_frac, 4),
|
|
552
|
+
"dropped_subfamilies": ";".join(dropped),
|
|
553
|
+
"h_total": round(h_total, 4),
|
|
554
|
+
"sef": None if sef_val is None else round(float(sef_val), 4),
|
|
555
|
+
"sef_adj": None if sef_adj is None else round(float(sef_adj), 4),
|
|
556
|
+
"p_perm": None if p_perm is None else round(float(p_perm), 6),
|
|
557
|
+
"call": call,
|
|
558
|
+
"f_family": None if f_fam is None else round(f_fam, 4),
|
|
559
|
+
"n_family": len(fam_res),
|
|
560
|
+
"f_own": None if f_own is None else round(f_own, 4),
|
|
561
|
+
"n_own": len(own_res),
|
|
562
|
+
"inverted": is_inv,
|
|
563
|
+
"sister_substitutions": ";".join(sisters),
|
|
564
|
+
"n_sister": len(sisters),
|
|
565
|
+
"distribution": dist_str,
|
|
566
|
+
}
|
|
567
|
+
)
|
|
568
|
+
|
|
569
|
+
v_counts = Counter(str(r["verdict"]) for r in rows)
|
|
570
|
+
summary = {
|
|
571
|
+
"reference": ref_header,
|
|
572
|
+
"own_subfamily": own,
|
|
573
|
+
"n_labelled_sequences": len(msa),
|
|
574
|
+
"n_unlabelled_excluded": len(unlabelled),
|
|
575
|
+
"n_positions": len(rows),
|
|
576
|
+
"ok": v_counts.get("ok", 0),
|
|
577
|
+
"gap_inflated": v_counts.get("gap_inflated", 0),
|
|
578
|
+
"depth_starved": v_counts.get("depth_starved", 0),
|
|
579
|
+
"clade_partitioned": v_counts.get("clade_partitioned", 0),
|
|
580
|
+
"flagged": len(rows) - v_counts.get("ok", 0),
|
|
581
|
+
}
|
|
582
|
+
fieldnames = [
|
|
583
|
+
"position",
|
|
584
|
+
"column",
|
|
585
|
+
"wt",
|
|
586
|
+
"verdict",
|
|
587
|
+
"error_sign",
|
|
588
|
+
"n_effective",
|
|
589
|
+
"gap_frac",
|
|
590
|
+
"dropped_subfamilies",
|
|
591
|
+
"h_total",
|
|
592
|
+
"sef",
|
|
593
|
+
"sef_adj",
|
|
594
|
+
"p_perm",
|
|
595
|
+
"call",
|
|
596
|
+
"f_family",
|
|
597
|
+
"n_family",
|
|
598
|
+
"f_own",
|
|
599
|
+
"n_own",
|
|
600
|
+
"inverted",
|
|
601
|
+
"sister_substitutions",
|
|
602
|
+
"n_sister",
|
|
603
|
+
"distribution",
|
|
604
|
+
]
|
|
605
|
+
return TableResult(mode="panel", rows=rows, summary=summary, fieldnames=fieldnames)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
class GapCheck:
|
|
609
|
+
def __init__(
|
|
610
|
+
self,
|
|
611
|
+
fasta_file: Union[str, os.PathLike, Mapping[str, str]],
|
|
612
|
+
output_file: Optional[Union[str, os.PathLike]] = None,
|
|
613
|
+
ref: Optional[str] = None,
|
|
614
|
+
own: Optional[str] = None,
|
|
615
|
+
subfamilies: Optional[Union[str, Mapping[str, Union[str, Sequence[str]]]]] = None,
|
|
616
|
+
max_gap_frac: float = DEFAULT_MAX_GAP_FRAC,
|
|
617
|
+
min_effective: int = DEFAULT_MIN_EFFECTIVE,
|
|
618
|
+
n_perm: int = 1000,
|
|
619
|
+
seed: int = DEFAULT_SEED,
|
|
620
|
+
pdb_file: Optional[Union[str, os.PathLike]] = None,
|
|
621
|
+
verbose: bool = True,
|
|
622
|
+
) -> None:
|
|
623
|
+
self.fasta_source = fasta_file
|
|
624
|
+
self.output_file = output_file
|
|
625
|
+
self.ref = ref
|
|
626
|
+
self.own = own
|
|
627
|
+
self.subfamilies = subfamilies
|
|
628
|
+
self.max_gap_frac = max_gap_frac
|
|
629
|
+
self.min_effective = min_effective
|
|
630
|
+
self.n_perm = n_perm
|
|
631
|
+
self.seed = seed
|
|
632
|
+
self.pdb_file = pdb_file
|
|
633
|
+
self.verbose = verbose
|
|
634
|
+
self.msa: Optional[Dict[str, str]] = None
|
|
635
|
+
self.result: Optional[TableResult] = None
|
|
636
|
+
|
|
637
|
+
def load(self) -> "GapCheck":
|
|
638
|
+
self.msa = (
|
|
639
|
+
dict(self.fasta_source)
|
|
640
|
+
if isinstance(self.fasta_source, Mapping)
|
|
641
|
+
else read_fasta(self.fasta_source)
|
|
642
|
+
)
|
|
643
|
+
return self
|
|
644
|
+
|
|
645
|
+
def run(self) -> "GapCheck":
|
|
646
|
+
if self.msa is None:
|
|
647
|
+
self.load()
|
|
648
|
+
assert self.msa is not None
|
|
649
|
+
if self.subfamilies is not None:
|
|
650
|
+
if not self.ref or not self.own:
|
|
651
|
+
raise GapCheckError(
|
|
652
|
+
"Both 'ref' and 'own' are required when 'subfamilies' is provided."
|
|
653
|
+
)
|
|
654
|
+
self.result = reliability_panel(
|
|
655
|
+
self.msa,
|
|
656
|
+
ref=self.ref,
|
|
657
|
+
own=self.own,
|
|
658
|
+
subfamilies=self.subfamilies,
|
|
659
|
+
max_gap_frac=self.max_gap_frac,
|
|
660
|
+
min_effective=self.min_effective,
|
|
661
|
+
n_perm=self.n_perm,
|
|
662
|
+
seed=self.seed,
|
|
663
|
+
)
|
|
664
|
+
else:
|
|
665
|
+
self.result = audit_alignment(
|
|
666
|
+
self.msa,
|
|
667
|
+
ref=self.ref,
|
|
668
|
+
max_gap_frac=self.max_gap_frac,
|
|
669
|
+
min_effective=self.min_effective,
|
|
670
|
+
)
|
|
671
|
+
return self
|
|
672
|
+
|
|
673
|
+
def save(self, path: Optional[Union[str, os.PathLike]] = None) -> "GapCheck":
|
|
674
|
+
if self.result is None:
|
|
675
|
+
self.run()
|
|
676
|
+
assert self.result is not None
|
|
677
|
+
target = path or self.output_file
|
|
678
|
+
if target is not None:
|
|
679
|
+
self.result.to_csv(target)
|
|
680
|
+
if self.verbose:
|
|
681
|
+
print(f"[gapcheck] Wrote CSV: {target} ({len(self.result.rows)} rows)")
|
|
682
|
+
if self.pdb_file is not None:
|
|
683
|
+
self.map_structure(self.pdb_file)
|
|
684
|
+
return self
|
|
685
|
+
|
|
686
|
+
def map_structure(self, pdb_path: Union[str, os.PathLike]) -> Optional[str]:
|
|
687
|
+
if self.result is None:
|
|
688
|
+
self.run()
|
|
689
|
+
assert self.result is not None
|
|
690
|
+
|
|
691
|
+
pos_key = "position" if self.result.mode == "panel" else (
|
|
692
|
+
"ref_position" if "ref_position" in self.result.fieldnames else "column"
|
|
693
|
+
)
|
|
694
|
+
val_key = "sef_adj" if self.result.mode == "panel" else "delta"
|
|
695
|
+
|
|
696
|
+
score_map: Dict[int, float] = {}
|
|
697
|
+
for row in self.result.rows:
|
|
698
|
+
p_val = row.get(pos_key)
|
|
699
|
+
s_val = row.get(val_key)
|
|
700
|
+
if isinstance(p_val, int) and isinstance(s_val, (int, float)):
|
|
701
|
+
score_map[p_val] = float(s_val) * 10.0
|
|
702
|
+
|
|
703
|
+
with open(pdb_path, "r", encoding="utf-8") as fh:
|
|
704
|
+
lines = fh.readlines()
|
|
705
|
+
|
|
706
|
+
mapped_lines: List[str] = []
|
|
707
|
+
for line in lines:
|
|
708
|
+
if line.startswith(("ATOM", "HETATM")) and len(line) >= 66:
|
|
709
|
+
try:
|
|
710
|
+
res_id = int(line[22:26].strip())
|
|
711
|
+
bfac = score_map.get(res_id, 0.0)
|
|
712
|
+
line = f"{line[:60]}{bfac:6.2f}{line[66:]}"
|
|
713
|
+
except ValueError:
|
|
714
|
+
pass
|
|
715
|
+
mapped_lines.append(line)
|
|
716
|
+
|
|
717
|
+
base, _ = os.path.splitext(str(pdb_path))
|
|
718
|
+
if self.output_file:
|
|
719
|
+
out_dir = os.path.dirname(os.path.abspath(self.output_file))
|
|
720
|
+
stem = os.path.splitext(os.path.basename(str(pdb_path)))[0]
|
|
721
|
+
out_pdb = os.path.join(out_dir, f"{stem}_gapcheck_{val_key}.pdb")
|
|
722
|
+
else:
|
|
723
|
+
out_pdb = f"{base}_gapcheck_{val_key}.pdb"
|
|
724
|
+
|
|
725
|
+
with open(out_pdb, "w", encoding="utf-8") as fh:
|
|
726
|
+
fh.writelines(mapped_lines)
|
|
727
|
+
|
|
728
|
+
pml_path = f"{os.path.splitext(out_pdb)[0]}.pml"
|
|
729
|
+
pdb_basename = os.path.basename(out_pdb)
|
|
730
|
+
pml_script = (
|
|
731
|
+
"reinitialize\n"
|
|
732
|
+
f"load {pdb_basename}, protein\n"
|
|
733
|
+
"hide everything, protein\n"
|
|
734
|
+
"show cartoon, protein\n"
|
|
735
|
+
"cartoon putty, protein\n"
|
|
736
|
+
"set cartoon_putty_scale_min, 0.5\n"
|
|
737
|
+
"set cartoon_putty_scale_max, 3.8\n"
|
|
738
|
+
"spectrum b, white_magenta, protein, minimum=0, maximum=10\n"
|
|
739
|
+
"bg_color white\n"
|
|
740
|
+
"set specular, 0.35\n"
|
|
741
|
+
"zoom protein\n"
|
|
742
|
+
)
|
|
743
|
+
with open(pml_path, "w", encoding="utf-8") as fh:
|
|
744
|
+
fh.write(pml_script)
|
|
745
|
+
|
|
746
|
+
if self.verbose:
|
|
747
|
+
print(f"[gapcheck] Wrote mapped PDB: {out_pdb} and PyMOL script: {pml_path}")
|
|
748
|
+
return out_pdb
|
|
749
|
+
|
|
750
|
+
def summary(self) -> Dict[str, object]:
|
|
751
|
+
if self.result is None:
|
|
752
|
+
self.run()
|
|
753
|
+
assert self.result is not None
|
|
754
|
+
s = self.result.summary
|
|
755
|
+
if self.verbose:
|
|
756
|
+
if self.result.mode == "audit":
|
|
757
|
+
n_col = int(s["n_columns"])
|
|
758
|
+
print(
|
|
759
|
+
f"[gapcheck] Alignment audit: {s['n_sequences']} sequences, {n_col} columns"
|
|
760
|
+
)
|
|
761
|
+
for key in ("usable", "gap_inflated", "depth_starved"):
|
|
762
|
+
cnt = int(s[key])
|
|
763
|
+
pct = (100.0 * cnt / n_col) if n_col else 0.0
|
|
764
|
+
print(f" {key:<16s} {cnt:5d} ({pct:5.1f}%)")
|
|
765
|
+
r_rep = s["pearson_gap_vs_reported"]
|
|
766
|
+
r_free = s["pearson_gap_vs_gap_free"]
|
|
767
|
+
if r_rep is not None and r_free is not None:
|
|
768
|
+
print(
|
|
769
|
+
f" gap vs conservation r: reported={r_rep:+.3f}, residues_only={r_free:+.3f}"
|
|
770
|
+
)
|
|
771
|
+
else:
|
|
772
|
+
n_pos = int(s["n_positions"])
|
|
773
|
+
print(
|
|
774
|
+
f"[gapcheck] Reliability panel ({s['own_subfamily']}): "
|
|
775
|
+
f"{s['n_labelled_sequences']} labelled sequences, {n_pos} reference positions"
|
|
776
|
+
)
|
|
777
|
+
for key in ("ok", "gap_inflated", "depth_starved", "clade_partitioned"):
|
|
778
|
+
cnt = int(s[key])
|
|
779
|
+
pct = (100.0 * cnt / n_pos) if n_pos else 0.0
|
|
780
|
+
print(f" {key:<18s} {cnt:5d} ({pct:5.1f}%)")
|
|
781
|
+
return s
|
|
782
|
+
|
|
783
|
+
def run_all(self) -> TableResult:
|
|
784
|
+
self.load().run().save()
|
|
785
|
+
if self.verbose:
|
|
786
|
+
self.summary()
|
|
787
|
+
assert self.result is not None
|
|
788
|
+
return self.result
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gapcheck
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Pre-scoring multiple sequence alignment diagnostics for gap inflation and clade-partitioned conservation masking
|
|
5
|
+
Author-email: Taner Karagöl <karagolt@mit.edu>, Alper Karagöl <akaragol@mit.edu>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://www.tanerkaragol.com/gapcheck
|
|
8
|
+
Project-URL: Mirror, https://www.karagolresearch.com/gapcheck
|
|
9
|
+
Project-URL: Repository, https://github.com/karagol-taner/conservation-score-reliability
|
|
10
|
+
Project-URL: Preprint, https://doi.org/10.64898/2026.10.20.760363
|
|
11
|
+
Keywords: bioinformatics,multiple-sequence-alignment,conservation-scoring,variant-effect-prediction,phylogenetics,structural-biology
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
22
|
+
Requires-Python: >=3.8
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: numpy>=1.20.0
|
|
26
|
+
Provides-Extra: dataframe
|
|
27
|
+
Requires-Dist: pandas>=1.3.0; extra == "dataframe"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# GapCheck: Pre-Scoring Alignment Gap Inflation and Clade-Partitioning Diagnostics
|
|
31
|
+
|
|
32
|
+
Evolutionary conservation scores are frequently interpreted as intrinsic properties of individual amino acid positions, even though the same residue can receive opposite calls depending on gap treatment and comparator selection. `gapcheck` audits multiple sequence alignments (MSAs) before downstream conservation scoring to quantify and flag two opposite distortion modes:
|
|
33
|
+
|
|
34
|
+
1. **Gap inflation (`gap_inflated`):** Shannon-entropy formulas over a 21-symbol alphabet ($1 - H/\log_2 21$) treat the gap character as a twenty-first residue, causing all-gap or gap-dominated columns to score as highly conserved. `gapcheck` reports per-column gap fraction, effective comparator depth, 21-symbol reported conservation, renormalized 20-residue conservation ($1 - H/\log_2 20$), and the inflation delta.
|
|
35
|
+
2. **Clade partitioning (`clade_partitioned`):** Pooling divergent subfamilies into a single alignment treats fixed between-clade divergence as mutational tolerance. When subfamily patterns are supplied, `gapcheck` computes total column entropy, raw and permutation-adjusted subfamily-explained entropy fractions (`sef`, `sef_adj`), own-clade versus family identity, and fixed sister-subfamily states, together with the direction of expected score error.
|
|
36
|
+
|
|
37
|
+
Interactive client-side browser versions are also available at https://www.tanerkaragol.com/gapcheck and https://www.karagolresearch.com/gapcheck.
|
|
38
|
+
|
|
39
|
+
## Installation
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install gapcheck
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Optional pandas DataFrame export:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
pip install "gapcheck[dataframe]"
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Command-Line Usage
|
|
52
|
+
|
|
53
|
+
### 1. Fast Column Gap-Inflation Audit
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
gapcheck -i alignment.fasta -o gapcheck_audit.csv
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Optionally anchor residue numbering to a target sequence in the alignment and project inflation deltas onto PDB B-factors (with an accompanying PyMOL `.pml` putty script):
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
gapcheck -i alignment.fasta -o gapcheck_audit.csv --ref HUMAN --pdb structure.pdb
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### 2. Full Two-Mode Subfamily Reliability Panel
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
gapcheck -i family_aligned.fasta -o reliability_panel.csv \
|
|
69
|
+
--ref P18827 \
|
|
70
|
+
--own SDC1 \
|
|
71
|
+
--subfamilies "SDC1=Syndecan-1;SDC2=Syndecan-2;SDC3=Syndecan-3;SDC4=Syndecan-4"
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### CLI Options
|
|
75
|
+
|
|
76
|
+
| Flag | Long form | Default | Description |
|
|
77
|
+
|------|-----------|---------|-------------|
|
|
78
|
+
| `-i` | `--input`, `--fasta` | *(required)* | Aligned FASTA file (`.fasta`, `.fa`, `.afa`, `.aln`) |
|
|
79
|
+
| `-o` | `--output` | `gapcheck_report.csv` | Output CSV path |
|
|
80
|
+
| | `--ref` | `None` | Substring matching the target reference sequence header |
|
|
81
|
+
| | `--own` | `None` | Subfamily label containing the reference sequence |
|
|
82
|
+
| | `--subfamilies` | `None` | Semicolon-delimited subfamily map (`"SUB1=pat1;SUB2=pat2"`) |
|
|
83
|
+
| | `--max-gap` | `0.25` | Column gap-fraction threshold above which `gap_inflated` is raised |
|
|
84
|
+
| | `--min-effective` | `5` | Minimum ungapped comparators below which `depth_starved` is raised |
|
|
85
|
+
| | `--n-perm` | `1000` | Column permutations for `sef_adj` and `p_perm` |
|
|
86
|
+
| | `--seed` | `20261007` | Random seed for reproducible permutation nulls |
|
|
87
|
+
| | `--pdb` | `None` | Optional PDB structure for B-factor score projection |
|
|
88
|
+
| `-q` | `--quiet` | `False` | Suppress terminal summary output |
|
|
89
|
+
| | `--version` | | Print version and exit |
|
|
90
|
+
|
|
91
|
+
## Python API
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from gapcheck import GapCheck, audit_alignment, reliability_panel
|
|
95
|
+
|
|
96
|
+
audit = audit_alignment("alignment.fasta", ref="seq_1")
|
|
97
|
+
print(audit.summary)
|
|
98
|
+
audit.to_csv("gapcheck_audit.csv")
|
|
99
|
+
|
|
100
|
+
panel = reliability_panel(
|
|
101
|
+
"family_aligned.fasta",
|
|
102
|
+
ref="SDC1_HUMAN",
|
|
103
|
+
own="SDC1",
|
|
104
|
+
subfamilies={
|
|
105
|
+
"SDC1": ["SDC1_", "Syndecan-1"],
|
|
106
|
+
"SDC2": ["SDC2_", "Syndecan-2"],
|
|
107
|
+
"SDC3": ["SDC3_", "Syndecan-3"],
|
|
108
|
+
"SDC4": ["SDC4_", "Syndecan-4"],
|
|
109
|
+
},
|
|
110
|
+
n_perm=1000,
|
|
111
|
+
)
|
|
112
|
+
print(panel.summary)
|
|
113
|
+
panel.to_csv("reliability_panel.csv")
|
|
114
|
+
|
|
115
|
+
GapCheck(
|
|
116
|
+
fasta_file="alignment.fasta",
|
|
117
|
+
output_file="gapcheck_audit.csv",
|
|
118
|
+
ref="seq_1",
|
|
119
|
+
pdb_file="model.pdb",
|
|
120
|
+
).run_all()
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Requirements
|
|
124
|
+
|
|
125
|
+
- Python >= 3.8
|
|
126
|
+
- NumPy >= 1.20.0
|
|
127
|
+
|
|
128
|
+
## Citation
|
|
129
|
+
|
|
130
|
+
If you use `gapcheck` in your research, please cite:
|
|
131
|
+
|
|
132
|
+
- Karagöl, T., Karagöl, A. (2026). Two opposite failure modes in alignment-based conservation scores, one inflating and one concealing constraint, are computable before the score is used. *bioRxiv*. https://doi.org/10.64898/2026.10.20.760363
|
|
133
|
+
|
|
134
|
+
## License
|
|
135
|
+
|
|
136
|
+
Released under the MIT License. See [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
gapcheck/__init__.py,sha256=6ma2SMFTNkh262h93N60gy37cTrf17cN17GnYWIP3DI,376
|
|
2
|
+
gapcheck/cli.py,sha256=-0VFwqFWpGWeA5tp6YVsNlTKz0CHJrDBFA9jpN-dlbo,4138
|
|
3
|
+
gapcheck/core.py,sha256=CnMfTCzrkw7ORSUbMTgfMy2gr_3AD-wtAukZeRRqVDE,27578
|
|
4
|
+
gapcheck-0.1.0.dist-info/licenses/LICENSE,sha256=NSVHeRuqAhtv3vmM9W2mir_AZKQtfviq0BIP_SFZZAI,1090
|
|
5
|
+
gapcheck-0.1.0.dist-info/METADATA,sha256=FPxtSTsurqu71f49fMxsJs940cy_xGkq66G6gnRAwtU,5868
|
|
6
|
+
gapcheck-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
gapcheck-0.1.0.dist-info/entry_points.txt,sha256=eTJIKEbkr50Nt96N-N7uCaAIaKtnuGfQGJql3ikn7cM,47
|
|
8
|
+
gapcheck-0.1.0.dist-info/top_level.txt,sha256=0NtDYqzjLcYOQ1wZ5amxq9HVrxp67ALCWbQcqV8XUXw,9
|
|
9
|
+
gapcheck-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Taner Karagöl and Alper Karagöl
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
gapcheck
|