clipkit 2.13.2__tar.gz → 2.14.0__tar.gz
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.
- {clipkit-2.13.2 → clipkit-2.14.0}/PKG-INFO +14 -1
- {clipkit-2.13.2 → clipkit-2.14.0}/README.md +13 -0
- clipkit-2.14.0/clipkit/ambiguity.py +80 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/api.py +13 -1
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/args_processing.py +5 -1
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/clipkit.py +19 -2
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/helpers.py +17 -7
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/modes.py +8 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/msa.py +235 -48
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/parser.py +26 -2
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/plot_report.py +20 -6
- clipkit-2.14.0/clipkit/version.py +1 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/write.py +6 -1
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit.egg-info/PKG-INFO +14 -1
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit.egg-info/SOURCES.txt +1 -0
- clipkit-2.13.2/clipkit/version.py +0 -1
- {clipkit-2.13.2 → clipkit-2.14.0}/LICENSE.md +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/__init__.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/__main__.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/ecomp/__init__.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/ecomp/reader.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/ecomp/writer.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/exceptions.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/files.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/guide_tree.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/logger.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/settings.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/site_classification.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/smart_gap_helper.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/stats.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/stop_codons.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit/warnings.py +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit.egg-info/dependency_links.txt +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit.egg-info/entry_points.txt +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit.egg-info/requires.txt +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/clipkit.egg-info/top_level.txt +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/pyproject.toml +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/setup.cfg +0 -0
- {clipkit-2.13.2 → clipkit-2.14.0}/setup.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: clipkit
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.14.0
|
|
4
4
|
Summary: Alignment trimming software for phylogenetics.
|
|
5
5
|
Home-page: https://github.com/jlsteenwyk/clipkit
|
|
6
6
|
Author: Jacob L. Steenwyk
|
|
@@ -107,8 +107,21 @@ clipkit input.fa
|
|
|
107
107
|
|
|
108
108
|
# mask all in-frame stops in a codon-aligned nucleotide MSA
|
|
109
109
|
clipkit coding.fa --codon --sequence_type nt --remove_stop_codons all
|
|
110
|
+
|
|
111
|
+
# fractionally weight IUPAC ambiguity symbols in entropy/composition analyses
|
|
112
|
+
clipkit ambiguous.fa --sequence_type nt --ambiguity_handling fractional
|
|
110
113
|
```
|
|
111
114
|
|
|
115
|
+
ClipKIT handles recognized IUPAC ambiguity symbols conservatively by default:
|
|
116
|
+
they are treated as missing evidence and contribute to the effective
|
|
117
|
+
unavailable fraction used by gap-based modes. Use `fractional` to distribute
|
|
118
|
+
them across possible states for entropy, composition, and the clade-entropy
|
|
119
|
+
part of heterotachy analysis, or `literal`
|
|
120
|
+
for legacy behavior. Configured gap characters take precedence, and alignment
|
|
121
|
+
symbols are never rewritten. See the
|
|
122
|
+
[ambiguity-handling documentation](https://jlsteenwyk.com/ClipKIT/advanced/#ambiguity-handling)
|
|
123
|
+
for the full nucleotide/protein mappings and mode-specific behavior.
|
|
124
|
+
|
|
112
125
|
The same operation is available through the Python API:
|
|
113
126
|
|
|
114
127
|
```python
|
|
@@ -73,8 +73,21 @@ clipkit input.fa
|
|
|
73
73
|
|
|
74
74
|
# mask all in-frame stops in a codon-aligned nucleotide MSA
|
|
75
75
|
clipkit coding.fa --codon --sequence_type nt --remove_stop_codons all
|
|
76
|
+
|
|
77
|
+
# fractionally weight IUPAC ambiguity symbols in entropy/composition analyses
|
|
78
|
+
clipkit ambiguous.fa --sequence_type nt --ambiguity_handling fractional
|
|
76
79
|
```
|
|
77
80
|
|
|
81
|
+
ClipKIT handles recognized IUPAC ambiguity symbols conservatively by default:
|
|
82
|
+
they are treated as missing evidence and contribute to the effective
|
|
83
|
+
unavailable fraction used by gap-based modes. Use `fractional` to distribute
|
|
84
|
+
them across possible states for entropy, composition, and the clade-entropy
|
|
85
|
+
part of heterotachy analysis, or `literal`
|
|
86
|
+
for legacy behavior. Configured gap characters take precedence, and alignment
|
|
87
|
+
symbols are never rewritten. See the
|
|
88
|
+
[ambiguity-handling documentation](https://jlsteenwyk.com/ClipKIT/advanced/#ambiguity-handling)
|
|
89
|
+
for the full nucleotide/protein mappings and mode-specific behavior.
|
|
90
|
+
|
|
78
91
|
The same operation is available through the Python API:
|
|
79
92
|
|
|
80
93
|
```python
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""IUPAC ambiguity definitions and helpers used during alignment analysis."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
|
|
5
|
+
NT_RESOLVED_STATES = frozenset("ACGTU")
|
|
6
|
+
AA_RESOLVED_STATES = frozenset("ACDEFGHIKLMNPQRSTVWYOU")
|
|
7
|
+
|
|
8
|
+
# Nucleotide ambiguity definitions use T internally. For RNA-only alignments,
|
|
9
|
+
# ``ambiguity_map`` substitutes U so fractional weights remain in the observed
|
|
10
|
+
# alphabet rather than introducing thymine into an RNA alignment.
|
|
11
|
+
_NT_AMBIGUITY_MAP = {
|
|
12
|
+
"R": frozenset("AG"),
|
|
13
|
+
"Y": frozenset("CT"),
|
|
14
|
+
"S": frozenset("GC"),
|
|
15
|
+
"W": frozenset("AT"),
|
|
16
|
+
"K": frozenset("GT"),
|
|
17
|
+
"M": frozenset("AC"),
|
|
18
|
+
"B": frozenset("CGT"),
|
|
19
|
+
"D": frozenset("AGT"),
|
|
20
|
+
"H": frozenset("ACT"),
|
|
21
|
+
"V": frozenset("ACG"),
|
|
22
|
+
"N": frozenset("ACGT"),
|
|
23
|
+
"X": frozenset("ACGT"),
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
_AA_STANDARD_STATES = frozenset("ACDEFGHIKLMNPQRSTVWY")
|
|
27
|
+
_AA_AMBIGUITY_MAP = {
|
|
28
|
+
"B": frozenset("DN"),
|
|
29
|
+
"Z": frozenset("EQ"),
|
|
30
|
+
"J": frozenset("IL"),
|
|
31
|
+
"X": _AA_STANDARD_STATES,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def normalize_sequence_type(sequence_type: object) -> str:
|
|
36
|
+
"""Return ``aa`` or ``nt`` for enum and string sequence-type values."""
|
|
37
|
+
value = getattr(sequence_type, "value", sequence_type)
|
|
38
|
+
value = str(value).lower()
|
|
39
|
+
if value not in {"aa", "nt"}:
|
|
40
|
+
raise ValueError("sequence_type must be 'aa' or 'nt'")
|
|
41
|
+
return value
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def ambiguity_map(
|
|
45
|
+
sequence_type: object, observed_states: Iterable[str] = ()
|
|
46
|
+
) -> dict[str, frozenset[str]]:
|
|
47
|
+
"""Return the relevant IUPAC ambiguity expansion map."""
|
|
48
|
+
if normalize_sequence_type(sequence_type) == "aa":
|
|
49
|
+
return _AA_AMBIGUITY_MAP
|
|
50
|
+
|
|
51
|
+
observed_upper = {str(state).upper() for state in observed_states}
|
|
52
|
+
if "U" not in observed_upper or "T" in observed_upper:
|
|
53
|
+
return _NT_AMBIGUITY_MAP
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
symbol: frozenset("U" if state == "T" else state for state in states)
|
|
57
|
+
for symbol, states in _NT_AMBIGUITY_MAP.items()
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def ambiguity_symbols(sequence_type: object) -> frozenset[str]:
|
|
62
|
+
"""Return recognized ambiguity symbols for a sequence type."""
|
|
63
|
+
if normalize_sequence_type(sequence_type) == "aa":
|
|
64
|
+
return frozenset(_AA_AMBIGUITY_MAP)
|
|
65
|
+
return frozenset(_NT_AMBIGUITY_MAP)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def resolved_symbols(sequence_type: object) -> frozenset[str]:
|
|
69
|
+
"""Return unambiguous biological states for a sequence type."""
|
|
70
|
+
if normalize_sequence_type(sequence_type) == "aa":
|
|
71
|
+
return AA_RESOLVED_STATES
|
|
72
|
+
return NT_RESOLVED_STATES
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def is_nucleotide_alphabet(characters: Iterable[str]) -> bool:
|
|
76
|
+
"""Whether all observed characters belong to the IUPAC nucleotide alphabet."""
|
|
77
|
+
nucleotide_symbols = NT_RESOLVED_STATES | ambiguity_symbols("nt")
|
|
78
|
+
ignored_symbols = frozenset("-?*.")
|
|
79
|
+
observed = {str(character).upper() for character in characters}
|
|
80
|
+
return observed.issubset(nucleotide_symbols | ignored_symbols)
|
|
@@ -5,7 +5,7 @@ from .clipkit import run
|
|
|
5
5
|
from .files import FileFormat
|
|
6
6
|
from .helpers import SeqType, write_msa
|
|
7
7
|
from .logger import logger
|
|
8
|
-
from .modes import StopCodonMode, TrimmingMode
|
|
8
|
+
from .modes import AmbiguityHandling, StopCodonMode, TrimmingMode
|
|
9
9
|
from .plot_report import write_trim_plot_report
|
|
10
10
|
|
|
11
11
|
if TYPE_CHECKING:
|
|
@@ -29,6 +29,7 @@ def clipkit(
|
|
|
29
29
|
sequence_type: Union[SeqType, str, None] = None,
|
|
30
30
|
codon: bool = False,
|
|
31
31
|
remove_stop_codons: Union[StopCodonMode, str, None] = None,
|
|
32
|
+
ambiguity_handling: Union[AmbiguityHandling, str] = AmbiguityHandling.missing,
|
|
32
33
|
ends_only=False,
|
|
33
34
|
threads: int = 1,
|
|
34
35
|
plot_trim_report_path: Union[str, None] = None,
|
|
@@ -71,6 +72,15 @@ def clipkit(
|
|
|
71
72
|
"sequence_type must be one of: 'aa', 'nt', SeqType.aa, SeqType.nt, or None."
|
|
72
73
|
) from exc
|
|
73
74
|
|
|
75
|
+
if isinstance(ambiguity_handling, str):
|
|
76
|
+
try:
|
|
77
|
+
ambiguity_handling = AmbiguityHandling(ambiguity_handling.lower())
|
|
78
|
+
except ValueError as exc:
|
|
79
|
+
raise ValueError(
|
|
80
|
+
"ambiguity_handling must be one of: 'missing', 'fractional', "
|
|
81
|
+
"'literal', or the corresponding AmbiguityHandling value."
|
|
82
|
+
) from exc
|
|
83
|
+
|
|
74
84
|
# override options not currently available through programmatic interface
|
|
75
85
|
complement = False
|
|
76
86
|
use_log = False
|
|
@@ -94,6 +104,7 @@ def clipkit(
|
|
|
94
104
|
ends_only,
|
|
95
105
|
threads,
|
|
96
106
|
remove_stop_codons,
|
|
107
|
+
ambiguity_handling,
|
|
97
108
|
)
|
|
98
109
|
|
|
99
110
|
if plot_trim_report_path:
|
|
@@ -103,6 +114,7 @@ def clipkit(
|
|
|
103
114
|
mode=TrimmingMode(mode).value,
|
|
104
115
|
gaps=trim_run.gaps,
|
|
105
116
|
sequence_type=trim_run.sequence_type.value,
|
|
117
|
+
ambiguity_handling=trim_run.ambiguity_handling.value,
|
|
106
118
|
)
|
|
107
119
|
|
|
108
120
|
if not output_file_path:
|
|
@@ -4,7 +4,7 @@ import sys
|
|
|
4
4
|
|
|
5
5
|
from .helpers import SeqType
|
|
6
6
|
from .exceptions import StopCodonValidationError
|
|
7
|
-
from .modes import StopCodonMode, TrimmingMode
|
|
7
|
+
from .modes import AmbiguityHandling, StopCodonMode, TrimmingMode
|
|
8
8
|
from .settings import DEFAULT_AA_GAP_CHARS
|
|
9
9
|
|
|
10
10
|
logger = logging.getLogger(__name__)
|
|
@@ -75,6 +75,9 @@ def process_args(args) -> dict:
|
|
|
75
75
|
remove_stop_codons = (
|
|
76
76
|
StopCodonMode(remove_stop_codons_arg) if remove_stop_codons_arg else None
|
|
77
77
|
)
|
|
78
|
+
ambiguity_handling = AmbiguityHandling(
|
|
79
|
+
getattr(args, "ambiguity_handling", None) or AmbiguityHandling.missing.value
|
|
80
|
+
)
|
|
78
81
|
|
|
79
82
|
if remove_stop_codons is not None and not codon:
|
|
80
83
|
raise StopCodonValidationError("Stop codon masking requires --codon.")
|
|
@@ -122,6 +125,7 @@ def process_args(args) -> dict:
|
|
|
122
125
|
auxiliary_file=auxiliary_file,
|
|
123
126
|
codon=codon,
|
|
124
127
|
remove_stop_codons=remove_stop_codons,
|
|
128
|
+
ambiguity_handling=ambiguity_handling,
|
|
125
129
|
sequence_type=sequence_type,
|
|
126
130
|
complement=complement,
|
|
127
131
|
gaps=gaps,
|
|
@@ -26,7 +26,7 @@ from .helpers import (
|
|
|
26
26
|
)
|
|
27
27
|
from .guide_tree import build_parsimony_guide_tree
|
|
28
28
|
from .logger import logger, log_file_logger
|
|
29
|
-
from .modes import StopCodonMode, TrimmingMode
|
|
29
|
+
from .modes import AmbiguityHandling, StopCodonMode, TrimmingMode
|
|
30
30
|
from .msa import MSA
|
|
31
31
|
from .parser import create_parser
|
|
32
32
|
from .plot_report import write_trim_plot_report
|
|
@@ -61,6 +61,7 @@ class TrimRun:
|
|
|
61
61
|
output_file_format: FileFormat
|
|
62
62
|
gaps: float
|
|
63
63
|
codon: bool
|
|
64
|
+
ambiguity_handling: AmbiguityHandling = AmbiguityHandling.missing
|
|
64
65
|
stop_codon_masking: StopCodonMaskingStats = field(
|
|
65
66
|
default_factory=StopCodonMaskingStats
|
|
66
67
|
)
|
|
@@ -136,6 +137,7 @@ def run(
|
|
|
136
137
|
ends_only: bool,
|
|
137
138
|
threads: int = 1,
|
|
138
139
|
remove_stop_codons: Union[StopCodonMode, str, None] = None,
|
|
140
|
+
ambiguity_handling: Union[AmbiguityHandling, str] = AmbiguityHandling.missing,
|
|
139
141
|
):
|
|
140
142
|
alignment, input_file_format = get_alignment_and_format(
|
|
141
143
|
input_file, input_file_format
|
|
@@ -145,6 +147,7 @@ def run(
|
|
|
145
147
|
raise ValueError("threads must be an integer >= 1")
|
|
146
148
|
|
|
147
149
|
sequence_type = sequence_type or get_seq_type(alignment)
|
|
150
|
+
ambiguity_handling = AmbiguityHandling(ambiguity_handling)
|
|
148
151
|
remove_stop_codons = normalize_stop_codon_mode(remove_stop_codons)
|
|
149
152
|
validate_stop_codon_configuration(
|
|
150
153
|
remove_stop_codons,
|
|
@@ -188,7 +191,13 @@ def run(
|
|
|
188
191
|
alignment.get_alignment_length(),
|
|
189
192
|
)
|
|
190
193
|
|
|
191
|
-
msa = create_msa(
|
|
194
|
+
msa = create_msa(
|
|
195
|
+
alignment,
|
|
196
|
+
gap_characters,
|
|
197
|
+
effective_threads,
|
|
198
|
+
sequence_type=sequence_type,
|
|
199
|
+
ambiguity_handling=ambiguity_handling,
|
|
200
|
+
)
|
|
192
201
|
stop_codon_masking = (
|
|
193
202
|
msa.mask_stop_codons(remove_stop_codons)
|
|
194
203
|
if remove_stop_codons is not None
|
|
@@ -235,6 +244,7 @@ def run(
|
|
|
235
244
|
output_file_format=output_file_format,
|
|
236
245
|
gaps=gaps,
|
|
237
246
|
codon=codon,
|
|
247
|
+
ambiguity_handling=ambiguity_handling,
|
|
238
248
|
stop_codon_masking=stop_codon_masking,
|
|
239
249
|
)
|
|
240
250
|
|
|
@@ -262,6 +272,7 @@ def execute(
|
|
|
262
272
|
auxiliary_file: str = None,
|
|
263
273
|
threads: int = 1,
|
|
264
274
|
remove_stop_codons: Union[StopCodonMode, str, None] = None,
|
|
275
|
+
ambiguity_handling: Union[AmbiguityHandling, str] = AmbiguityHandling.missing,
|
|
265
276
|
**kwargs,
|
|
266
277
|
) -> None:
|
|
267
278
|
fh = None
|
|
@@ -281,6 +292,7 @@ def execute(
|
|
|
281
292
|
|
|
282
293
|
start_time = time.time()
|
|
283
294
|
remove_stop_codons = normalize_stop_codon_mode(remove_stop_codons)
|
|
295
|
+
ambiguity_handling = AmbiguityHandling(ambiguity_handling)
|
|
284
296
|
|
|
285
297
|
if validate_only:
|
|
286
298
|
try:
|
|
@@ -327,6 +339,7 @@ def execute(
|
|
|
327
339
|
input_file_format=detected_input_format.value,
|
|
328
340
|
output_file_format=resolved_output_format.value,
|
|
329
341
|
sequence_type=validated_sequence_type.value,
|
|
342
|
+
ambiguity_handling=ambiguity_handling.value,
|
|
330
343
|
gaps=gaps,
|
|
331
344
|
gap_characters=validated_gap_characters,
|
|
332
345
|
mode=mode.value,
|
|
@@ -360,6 +373,7 @@ def execute(
|
|
|
360
373
|
ends_only,
|
|
361
374
|
threads,
|
|
362
375
|
remove_stop_codons,
|
|
376
|
+
ambiguity_handling,
|
|
363
377
|
)
|
|
364
378
|
except InvalidInputFileFormat:
|
|
365
379
|
logger.error(
|
|
@@ -382,6 +396,7 @@ def execute(
|
|
|
382
396
|
use_log,
|
|
383
397
|
ends_only,
|
|
384
398
|
trim_run.stop_codon_masking,
|
|
399
|
+
trim_run.ambiguity_handling,
|
|
385
400
|
)
|
|
386
401
|
|
|
387
402
|
if dry_run:
|
|
@@ -425,6 +440,7 @@ def execute(
|
|
|
425
440
|
input_file_format=trim_run.input_file_format.value,
|
|
426
441
|
output_file_format=trim_run.output_file_format.value,
|
|
427
442
|
sequence_type=trim_run.sequence_type.value,
|
|
443
|
+
ambiguity_handling=trim_run.ambiguity_handling.value,
|
|
428
444
|
gaps=trim_run.gaps,
|
|
429
445
|
gap_characters=trim_run.gap_characters,
|
|
430
446
|
mode=mode.value,
|
|
@@ -446,6 +462,7 @@ def execute(
|
|
|
446
462
|
mode=mode.value,
|
|
447
463
|
gaps=trim_run.gaps,
|
|
448
464
|
sequence_type=trim_run.sequence_type.value,
|
|
465
|
+
ambiguity_handling=trim_run.ambiguity_handling.value,
|
|
449
466
|
)
|
|
450
467
|
logger.info(f"Wrote trim plot report to {plot_trim_report}")
|
|
451
468
|
|
|
@@ -5,8 +5,9 @@ from Bio.Align import MultipleSeqAlignment
|
|
|
5
5
|
import numpy as np
|
|
6
6
|
from typing import Optional
|
|
7
7
|
|
|
8
|
+
from .ambiguity import is_nucleotide_alphabet
|
|
8
9
|
from .msa import MSA
|
|
9
|
-
from .modes import TrimmingMode
|
|
10
|
+
from .modes import AmbiguityHandling, TrimmingMode
|
|
10
11
|
from .settings import DEFAULT_AA_GAP_CHARS, DEFAULT_NT_GAP_CHARS
|
|
11
12
|
from .files import FileFormat
|
|
12
13
|
from .stats import TrimmingStats
|
|
@@ -32,10 +33,7 @@ def get_seq_type(alignment: MultipleSeqAlignment) -> SeqType:
|
|
|
32
33
|
seq = "".join([str(record.seq) for record in alignment])
|
|
33
34
|
seq = remove_gaps(seq)
|
|
34
35
|
|
|
35
|
-
if
|
|
36
|
-
sequence_type = SeqType.aa
|
|
37
|
-
else:
|
|
38
|
-
sequence_type = SeqType.nt
|
|
36
|
+
sequence_type = SeqType.nt if is_nucleotide_alphabet(seq) else SeqType.aa
|
|
39
37
|
|
|
40
38
|
return sequence_type
|
|
41
39
|
|
|
@@ -47,11 +45,23 @@ def get_gap_chars(seq_type: SeqType) -> list[str]:
|
|
|
47
45
|
return DEFAULT_AA_GAP_CHARS
|
|
48
46
|
|
|
49
47
|
|
|
50
|
-
def create_msa(
|
|
48
|
+
def create_msa(
|
|
49
|
+
alignment: MultipleSeqAlignment,
|
|
50
|
+
gap_chars: list[str] = None,
|
|
51
|
+
threads: int = 1,
|
|
52
|
+
sequence_type: Optional[SeqType] = None,
|
|
53
|
+
ambiguity_handling: AmbiguityHandling = AmbiguityHandling.missing,
|
|
54
|
+
) -> MSA:
|
|
51
55
|
"""
|
|
52
56
|
Create MSA class
|
|
53
57
|
"""
|
|
54
|
-
return MSA.from_bio_msa(
|
|
58
|
+
return MSA.from_bio_msa(
|
|
59
|
+
alignment,
|
|
60
|
+
gap_chars,
|
|
61
|
+
threads,
|
|
62
|
+
sequence_type=sequence_type,
|
|
63
|
+
ambiguity_handling=ambiguity_handling,
|
|
64
|
+
)
|
|
55
65
|
|
|
56
66
|
|
|
57
67
|
def write_msa(
|
|
@@ -29,3 +29,11 @@ class StopCodonMode(Enum):
|
|
|
29
29
|
terminal = "terminal"
|
|
30
30
|
internal = "internal"
|
|
31
31
|
all = "all"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class AmbiguityHandling(Enum):
|
|
35
|
+
"""How recognized IUPAC ambiguity symbols contribute to analysis."""
|
|
36
|
+
|
|
37
|
+
missing = "missing"
|
|
38
|
+
fractional = "fractional"
|
|
39
|
+
literal = "literal"
|
|
@@ -3,10 +3,18 @@ from Bio.Seq import Seq
|
|
|
3
3
|
from Bio.SeqRecord import SeqRecord
|
|
4
4
|
import numpy as np
|
|
5
5
|
import math
|
|
6
|
+
from itertools import chain
|
|
6
7
|
from typing import Union
|
|
7
8
|
from Bio.Phylo.BaseTree import Tree
|
|
8
9
|
|
|
9
|
-
from .
|
|
10
|
+
from .ambiguity import (
|
|
11
|
+
ambiguity_map,
|
|
12
|
+
ambiguity_symbols,
|
|
13
|
+
is_nucleotide_alphabet,
|
|
14
|
+
normalize_sequence_type,
|
|
15
|
+
resolved_symbols,
|
|
16
|
+
)
|
|
17
|
+
from .modes import AmbiguityHandling, StopCodonMode, TrimmingMode
|
|
10
18
|
|
|
11
19
|
# Always import the standard version for compatibility
|
|
12
20
|
from .site_classification import (
|
|
@@ -96,6 +104,8 @@ class MSA:
|
|
|
96
104
|
gap_chars=DEFAULT_AA_GAP_CHARS,
|
|
97
105
|
threads=1,
|
|
98
106
|
requires_uppercase_normalization=False,
|
|
107
|
+
sequence_type="aa",
|
|
108
|
+
ambiguity_handling=AmbiguityHandling.missing,
|
|
99
109
|
) -> None:
|
|
100
110
|
self.header_info = header_info
|
|
101
111
|
self.seq_records = seq_records
|
|
@@ -105,18 +115,29 @@ class MSA:
|
|
|
105
115
|
self._site_classification_types = None
|
|
106
116
|
self._column_character_frequencies = None
|
|
107
117
|
self._column_character_count_cache = {}
|
|
118
|
+
self._observed_sequence_states_cache = None
|
|
108
119
|
self._gap_chars = gap_chars or DEFAULT_AA_GAP_CHARS
|
|
109
120
|
self._codon_size = 3
|
|
110
121
|
self._threads = threads
|
|
111
122
|
self._requires_uppercase_normalization = requires_uppercase_normalization
|
|
123
|
+
self._sequence_type = normalize_sequence_type(sequence_type)
|
|
124
|
+
self._ambiguity_handling = AmbiguityHandling(ambiguity_handling)
|
|
112
125
|
# Cache for expensive computations
|
|
113
126
|
self._site_gappyness_cache = None
|
|
127
|
+
self._site_gap_fraction_cache = None
|
|
128
|
+
self._site_ambiguity_cache = None
|
|
129
|
+
self._site_resolved_fraction_cache = None
|
|
130
|
+
self._site_analyzable_fraction_cache = None
|
|
114
131
|
self._site_entropy_cache = None
|
|
115
132
|
self._site_composition_bias_cache = None
|
|
116
133
|
|
|
117
134
|
@staticmethod
|
|
118
135
|
def from_bio_msa(
|
|
119
|
-
alignment: MultipleSeqAlignment,
|
|
136
|
+
alignment: MultipleSeqAlignment,
|
|
137
|
+
gap_chars=None,
|
|
138
|
+
threads=1,
|
|
139
|
+
sequence_type=None,
|
|
140
|
+
ambiguity_handling=AmbiguityHandling.missing,
|
|
120
141
|
) -> "MSA":
|
|
121
142
|
header_info = []
|
|
122
143
|
sequences = []
|
|
@@ -130,6 +151,11 @@ class MSA:
|
|
|
130
151
|
if not requires_uppercase_normalization and seq != seq.upper():
|
|
131
152
|
requires_uppercase_normalization = True
|
|
132
153
|
|
|
154
|
+
if sequence_type is None:
|
|
155
|
+
sequence_type = (
|
|
156
|
+
"nt" if is_nucleotide_alphabet(chain.from_iterable(sequences)) else "aa"
|
|
157
|
+
)
|
|
158
|
+
|
|
133
159
|
alignment_length = len(sequences[0])
|
|
134
160
|
if alignment_length == 0:
|
|
135
161
|
seq_records = np.empty((len(sequences), 0), dtype="U1")
|
|
@@ -145,6 +171,8 @@ class MSA:
|
|
|
145
171
|
gap_chars,
|
|
146
172
|
threads,
|
|
147
173
|
requires_uppercase_normalization=requires_uppercase_normalization,
|
|
174
|
+
sequence_type=sequence_type,
|
|
175
|
+
ambiguity_handling=ambiguity_handling,
|
|
148
176
|
)
|
|
149
177
|
|
|
150
178
|
def to_bio_msa(self) -> MultipleSeqAlignment:
|
|
@@ -178,7 +206,8 @@ class MSA:
|
|
|
178
206
|
codons = normalized_records.reshape(
|
|
179
207
|
self.seq_records.shape[0], -1, self._codon_size
|
|
180
208
|
)
|
|
181
|
-
|
|
209
|
+
unavailable_chars = self._effective_unavailable_chars
|
|
210
|
+
gap_chars = np.asarray(sorted(unavailable_chars), dtype="U1")
|
|
182
211
|
complete_codons = ~np.any(np.isin(codons, gap_chars), axis=2)
|
|
183
212
|
codon_strings = (
|
|
184
213
|
np.ascontiguousarray(codons).view("U3").reshape(codons.shape[:2])
|
|
@@ -220,7 +249,12 @@ class MSA:
|
|
|
220
249
|
self._site_classification_types = None
|
|
221
250
|
self._column_character_frequencies = None
|
|
222
251
|
self._column_character_count_cache = {}
|
|
252
|
+
self._observed_sequence_states_cache = None
|
|
223
253
|
self._site_gappyness_cache = None
|
|
254
|
+
self._site_gap_fraction_cache = None
|
|
255
|
+
self._site_ambiguity_cache = None
|
|
256
|
+
self._site_resolved_fraction_cache = None
|
|
257
|
+
self._site_analyzable_fraction_cache = None
|
|
224
258
|
self._site_entropy_cache = None
|
|
225
259
|
self._site_composition_bias_cache = None
|
|
226
260
|
|
|
@@ -272,32 +306,125 @@ class MSA:
|
|
|
272
306
|
return self._gap_chars
|
|
273
307
|
|
|
274
308
|
@property
|
|
275
|
-
def
|
|
276
|
-
|
|
277
|
-
|
|
309
|
+
def sequence_type(self) -> str:
|
|
310
|
+
return self._sequence_type
|
|
311
|
+
|
|
312
|
+
@property
|
|
313
|
+
def ambiguity_handling(self) -> AmbiguityHandling:
|
|
314
|
+
return self._ambiguity_handling
|
|
315
|
+
|
|
316
|
+
@property
|
|
317
|
+
def _normalized_gap_chars(self) -> frozenset[str]:
|
|
318
|
+
return frozenset(str(char).upper() for char in self._gap_chars)
|
|
319
|
+
|
|
320
|
+
@property
|
|
321
|
+
def _ambiguity_chars(self) -> frozenset[str]:
|
|
322
|
+
return ambiguity_symbols(self._sequence_type)
|
|
323
|
+
|
|
324
|
+
@property
|
|
325
|
+
def _effective_unavailable_chars(self) -> frozenset[str]:
|
|
326
|
+
if self._ambiguity_handling == AmbiguityHandling.missing:
|
|
327
|
+
return self._normalized_gap_chars | self._ambiguity_chars
|
|
328
|
+
return self._normalized_gap_chars
|
|
329
|
+
|
|
330
|
+
@property
|
|
331
|
+
def _observed_sequence_states(self) -> np.ndarray:
|
|
332
|
+
if self._observed_sequence_states_cache is None:
|
|
333
|
+
seq_array = (
|
|
334
|
+
np.char.upper(self.seq_records)
|
|
335
|
+
if self._requires_uppercase_normalization
|
|
336
|
+
else self.seq_records
|
|
337
|
+
)
|
|
338
|
+
self._observed_sequence_states_cache = np.unique(seq_array)
|
|
339
|
+
return self._observed_sequence_states_cache
|
|
278
340
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
341
|
+
def _site_fraction_for_states(
|
|
342
|
+
self, states_to_count: frozenset[str], cache_key: str
|
|
343
|
+
) -> np.ndarray:
|
|
282
344
|
shared_counts = (
|
|
283
345
|
self._column_character_count_cache.get(("frequencies", False))
|
|
284
346
|
if not self._requires_uppercase_normalization
|
|
285
347
|
else None
|
|
286
348
|
)
|
|
287
|
-
if
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
349
|
+
if (
|
|
350
|
+
shared_counts is None
|
|
351
|
+
and self.seq_records.size < _MIN_CELLS_FOR_COLUMN_COUNTING
|
|
352
|
+
):
|
|
353
|
+
seq_array = (
|
|
354
|
+
np.char.upper(self.seq_records)
|
|
355
|
+
if self._requires_uppercase_normalization
|
|
356
|
+
else self.seq_records
|
|
357
|
+
)
|
|
358
|
+
return np.around(
|
|
359
|
+
np.isin(seq_array, tuple(states_to_count)).mean(axis=0), decimals=4
|
|
360
|
+
)
|
|
361
|
+
if shared_counts is None:
|
|
294
362
|
states, counts = self._get_column_character_counts(
|
|
295
|
-
normalize_case=
|
|
363
|
+
normalize_case=True, cache_key=cache_key
|
|
364
|
+
)
|
|
365
|
+
else:
|
|
366
|
+
states, counts = shared_counts
|
|
367
|
+
matching_counts = counts[np.isin(states, tuple(states_to_count))].sum(axis=0)
|
|
368
|
+
fractions = matching_counts / self.seq_records.shape[0]
|
|
369
|
+
self._column_character_count_cache.pop(
|
|
370
|
+
(cache_key, self._requires_uppercase_normalization), None
|
|
371
|
+
)
|
|
372
|
+
return np.around(fractions, decimals=4)
|
|
373
|
+
|
|
374
|
+
@property
|
|
375
|
+
def site_gap_fraction(self) -> np.ndarray:
|
|
376
|
+
"""Fraction of configured gap characters at each site."""
|
|
377
|
+
if self._site_gap_fraction_cache is None:
|
|
378
|
+
self._site_gap_fraction_cache = self._site_fraction_for_states(
|
|
379
|
+
self._normalized_gap_chars, "gap_fraction"
|
|
380
|
+
)
|
|
381
|
+
return self._site_gap_fraction_cache
|
|
382
|
+
|
|
383
|
+
@property
|
|
384
|
+
def site_ambiguity(self) -> np.ndarray:
|
|
385
|
+
"""Fraction of recognized IUPAC ambiguity symbols at each site."""
|
|
386
|
+
if self._site_ambiguity_cache is None:
|
|
387
|
+
self._site_ambiguity_cache = self._site_fraction_for_states(
|
|
388
|
+
self._ambiguity_chars, "ambiguity_fraction"
|
|
296
389
|
)
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
390
|
+
return self._site_ambiguity_cache
|
|
391
|
+
|
|
392
|
+
@property
|
|
393
|
+
def site_resolved_fraction(self) -> np.ndarray:
|
|
394
|
+
"""Fraction of unambiguous biological states at each site."""
|
|
395
|
+
if self._site_resolved_fraction_cache is None:
|
|
396
|
+
self._site_resolved_fraction_cache = self._site_fraction_for_states(
|
|
397
|
+
resolved_symbols(self._sequence_type), "resolved_fraction"
|
|
398
|
+
)
|
|
399
|
+
return self._site_resolved_fraction_cache
|
|
400
|
+
|
|
401
|
+
@property
|
|
402
|
+
def site_analyzable_fraction(self) -> np.ndarray:
|
|
403
|
+
"""Fraction of entries contributing to entropy/composition analysis."""
|
|
404
|
+
if self._site_analyzable_fraction_cache is None:
|
|
405
|
+
_, counts = self._get_non_gap_character_counts(
|
|
406
|
+
cache_key="analyzable_fraction"
|
|
407
|
+
)
|
|
408
|
+
self._site_analyzable_fraction_cache = np.around(
|
|
409
|
+
counts.sum(axis=0) / self.seq_records.shape[0], decimals=4
|
|
410
|
+
)
|
|
411
|
+
self._column_character_count_cache.pop(
|
|
412
|
+
(
|
|
413
|
+
"analyzable_fraction",
|
|
414
|
+
self._requires_uppercase_normalization,
|
|
415
|
+
),
|
|
416
|
+
None,
|
|
417
|
+
)
|
|
418
|
+
return self._site_analyzable_fraction_cache
|
|
419
|
+
|
|
420
|
+
@property
|
|
421
|
+
def site_gappyness(self) -> np.floating:
|
|
422
|
+
if self._site_gappyness_cache is not None:
|
|
423
|
+
return self._site_gappyness_cache
|
|
424
|
+
|
|
425
|
+
self._site_gappyness_cache = self._site_fraction_for_states(
|
|
426
|
+
self._effective_unavailable_chars, "gappyness"
|
|
427
|
+
)
|
|
301
428
|
return self._site_gappyness_cache
|
|
302
429
|
|
|
303
430
|
@property
|
|
@@ -314,9 +441,7 @@ class MSA:
|
|
|
314
441
|
if self._site_entropy_cache is not None:
|
|
315
442
|
return self._site_entropy_cache
|
|
316
443
|
|
|
317
|
-
_, counts_by_state = self._get_non_gap_character_counts(
|
|
318
|
-
normalize_gap_chars=True, cache_key="entropy"
|
|
319
|
-
)
|
|
444
|
+
_, counts_by_state = self._get_non_gap_character_counts(cache_key="entropy")
|
|
320
445
|
total_counts = counts_by_state.sum(axis=0).astype(float)
|
|
321
446
|
observed_states = np.count_nonzero(counts_by_state, axis=0)
|
|
322
447
|
raw_entropy = np.zeros(counts_by_state.shape[1], dtype=float)
|
|
@@ -384,8 +509,9 @@ class MSA:
|
|
|
384
509
|
|
|
385
510
|
def is_any_entry_sequence_only_gaps(self) -> tuple[bool, Union[str, None]]:
|
|
386
511
|
for idx, row in enumerate(self.trimmed):
|
|
387
|
-
|
|
388
|
-
|
|
512
|
+
normalized_row = np.char.upper(row)
|
|
513
|
+
if np.all(
|
|
514
|
+
np.isin(normalized_row, tuple(self._effective_unavailable_chars))
|
|
389
515
|
):
|
|
390
516
|
return True, self.header_info[idx].get("id")
|
|
391
517
|
return False, None
|
|
@@ -436,7 +562,7 @@ class MSA:
|
|
|
436
562
|
dict(
|
|
437
563
|
zip(
|
|
438
564
|
states[present],
|
|
439
|
-
counts_by_state[present, col_idx].
|
|
565
|
+
counts_by_state[present, col_idx].tolist(),
|
|
440
566
|
)
|
|
441
567
|
)
|
|
442
568
|
)
|
|
@@ -459,19 +585,58 @@ class MSA:
|
|
|
459
585
|
|
|
460
586
|
def _get_non_gap_character_counts(
|
|
461
587
|
self,
|
|
462
|
-
normalize_gap_chars: bool = False,
|
|
463
588
|
cache_key: str = "frequencies",
|
|
589
|
+
classification: bool = False,
|
|
464
590
|
) -> tuple[np.ndarray, np.ndarray]:
|
|
465
591
|
states, counts = self._get_column_character_counts(
|
|
466
592
|
normalize_case=True, cache_key=cache_key
|
|
467
593
|
)
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
594
|
+
non_gap_states = ~np.isin(states, tuple(self._normalized_gap_chars))
|
|
595
|
+
states = states[non_gap_states]
|
|
596
|
+
counts = counts[non_gap_states]
|
|
597
|
+
|
|
598
|
+
if self._ambiguity_handling == AmbiguityHandling.literal:
|
|
599
|
+
return states, counts
|
|
600
|
+
|
|
601
|
+
recognized_ambiguity = np.isin(states, tuple(self._ambiguity_chars))
|
|
602
|
+
if self._ambiguity_handling == AmbiguityHandling.missing or classification:
|
|
603
|
+
return states[~recognized_ambiguity], counts[~recognized_ambiguity]
|
|
604
|
+
|
|
605
|
+
return self._fractionally_expand_ambiguities(states, counts)
|
|
606
|
+
|
|
607
|
+
def _fractionally_expand_ambiguities(
|
|
608
|
+
self,
|
|
609
|
+
states: np.ndarray,
|
|
610
|
+
counts: np.ndarray,
|
|
611
|
+
observed_states: np.ndarray = None,
|
|
612
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
613
|
+
expansions = ambiguity_map(
|
|
614
|
+
self._sequence_type,
|
|
615
|
+
states if observed_states is None else observed_states,
|
|
616
|
+
)
|
|
617
|
+
expanded_counts: dict[str, np.ndarray] = {}
|
|
618
|
+
|
|
619
|
+
for state, state_counts in zip(states, counts):
|
|
620
|
+
destinations = expansions.get(str(state))
|
|
621
|
+
if destinations is None:
|
|
622
|
+
expanded_counts[str(state)] = (
|
|
623
|
+
expanded_counts.get(str(state), 0) + state_counts
|
|
624
|
+
)
|
|
625
|
+
continue
|
|
626
|
+
|
|
627
|
+
weight = state_counts.astype(float) / len(destinations)
|
|
628
|
+
for destination in destinations:
|
|
629
|
+
expanded_counts[destination] = (
|
|
630
|
+
expanded_counts.get(destination, 0) + weight
|
|
631
|
+
)
|
|
632
|
+
|
|
633
|
+
if not expanded_counts:
|
|
634
|
+
return np.empty(0, dtype="U1"), np.empty((0, counts.shape[1]), dtype=float)
|
|
635
|
+
|
|
636
|
+
expanded_states = np.array(sorted(expanded_counts), dtype="U1")
|
|
637
|
+
return expanded_states, np.vstack(
|
|
638
|
+
[expanded_counts[state] for state in expanded_states]
|
|
472
639
|
)
|
|
473
|
-
non_gap_states = ~np.isin(states, gap_chars)
|
|
474
|
-
return states[non_gap_states], counts[non_gap_states]
|
|
475
640
|
|
|
476
641
|
@property
|
|
477
642
|
def site_classification_types(self):
|
|
@@ -482,7 +647,7 @@ class MSA:
|
|
|
482
647
|
self._site_classification_types = np.array([])
|
|
483
648
|
return self._site_classification_types
|
|
484
649
|
|
|
485
|
-
_, counts_by_state = self._get_non_gap_character_counts()
|
|
650
|
+
_, counts_by_state = self._get_non_gap_character_counts(classification=True)
|
|
486
651
|
observed_states = np.count_nonzero(counts_by_state, axis=0)
|
|
487
652
|
states_occurring_at_least_twice = np.count_nonzero(counts_by_state >= 2, axis=0)
|
|
488
653
|
|
|
@@ -520,14 +685,23 @@ class MSA:
|
|
|
520
685
|
# Keep sites at the inferred boundary and trim strictly above it.
|
|
521
686
|
sites_to_trim = np.where(self.site_gappyness > gap_threshold)[0]
|
|
522
687
|
elif mode == TrimmingMode.entropy:
|
|
523
|
-
|
|
688
|
+
trim_mask = self.site_entropy >= gap_threshold
|
|
689
|
+
if self._ambiguity_handling == AmbiguityHandling.missing:
|
|
690
|
+
trim_mask |= self.site_analyzable_fraction == 0
|
|
691
|
+
sites_to_trim = np.where(trim_mask)[0]
|
|
524
692
|
elif mode == TrimmingMode.composition_bias:
|
|
525
|
-
|
|
693
|
+
trim_mask = self.site_composition_bias >= gap_threshold
|
|
694
|
+
if self._ambiguity_handling == AmbiguityHandling.missing:
|
|
695
|
+
trim_mask |= self.site_analyzable_fraction == 0
|
|
696
|
+
sites_to_trim = np.where(trim_mask)[0]
|
|
526
697
|
elif mode == TrimmingMode.heterotachy:
|
|
527
698
|
if guide_tree is None:
|
|
528
699
|
raise ValueError("heterotachy mode requires a guide tree")
|
|
529
700
|
site_heterotachy = self.determine_site_heterotachy(guide_tree)
|
|
530
|
-
|
|
701
|
+
trim_mask = site_heterotachy >= gap_threshold
|
|
702
|
+
if self._ambiguity_handling == AmbiguityHandling.missing:
|
|
703
|
+
trim_mask |= self.site_analyzable_fraction == 0
|
|
704
|
+
sites_to_trim = np.where(trim_mask)[0]
|
|
531
705
|
elif mode == TrimmingMode.kpi:
|
|
532
706
|
site_classification_types = self.site_classification_types
|
|
533
707
|
sites_to_trim = np.where(
|
|
@@ -660,20 +834,33 @@ class MSA:
|
|
|
660
834
|
clade_indices: list[int],
|
|
661
835
|
site_idx: int,
|
|
662
836
|
) -> float:
|
|
663
|
-
column = self.seq_records[clade_indices, site_idx]
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
837
|
+
column = np.char.upper(self.seq_records[clade_indices, site_idx])
|
|
838
|
+
states, counts = np.unique(column, return_counts=True)
|
|
839
|
+
counts = counts.reshape(-1, 1)
|
|
840
|
+
|
|
841
|
+
non_gap_states = ~np.isin(states, tuple(self._normalized_gap_chars))
|
|
842
|
+
states = states[non_gap_states]
|
|
843
|
+
counts = counts[non_gap_states]
|
|
844
|
+
if self._ambiguity_handling != AmbiguityHandling.literal:
|
|
845
|
+
recognized_ambiguity = np.isin(states, tuple(self._ambiguity_chars))
|
|
846
|
+
if self._ambiguity_handling == AmbiguityHandling.missing:
|
|
847
|
+
states = states[~recognized_ambiguity]
|
|
848
|
+
counts = counts[~recognized_ambiguity]
|
|
849
|
+
else:
|
|
850
|
+
states, counts = self._fractionally_expand_ambiguities(
|
|
851
|
+
states,
|
|
852
|
+
counts,
|
|
853
|
+
observed_states=self._observed_sequence_states,
|
|
854
|
+
)
|
|
669
855
|
|
|
670
|
-
|
|
671
|
-
|
|
856
|
+
present_counts = counts[:, 0]
|
|
857
|
+
present_counts = present_counts[present_counts > 0]
|
|
858
|
+
if len(present_counts) <= 1:
|
|
672
859
|
return 0.0
|
|
673
860
|
|
|
674
|
-
probs =
|
|
861
|
+
probs = present_counts.astype(float) / float(np.sum(present_counts))
|
|
675
862
|
raw_entropy = -float(np.sum(probs * np.log2(probs)))
|
|
676
|
-
max_entropy = math.log2(len(
|
|
863
|
+
max_entropy = math.log2(len(present_counts))
|
|
677
864
|
return raw_entropy / max_entropy if max_entropy > 0 else 0.0
|
|
678
865
|
|
|
679
866
|
@staticmethod
|
|
@@ -8,7 +8,7 @@ from argparse import (
|
|
|
8
8
|
|
|
9
9
|
from .helpers import SeqType
|
|
10
10
|
from .files import FileFormat
|
|
11
|
-
from .modes import StopCodonMode, TrimmingMode
|
|
11
|
+
from .modes import AmbiguityHandling, StopCodonMode, TrimmingMode
|
|
12
12
|
from .version import __version__
|
|
13
13
|
|
|
14
14
|
_MAIN_DESCRIPTION_TEMPLATE = r"""\
|
|
@@ -68,6 +68,10 @@ _OPTIONAL_ARGUMENTS_DESCRIPTION = """\
|
|
|
68
68
|
-s, --sequence_type <nt, aa> specifies sequence type of input file
|
|
69
69
|
(default: auto-detect)
|
|
70
70
|
|
|
71
|
+
--ambiguity_handling <missing, controls how recognized IUPAC ambiguity symbols
|
|
72
|
+
fractional, contribute to trimming statistics
|
|
73
|
+
literal> (default: missing)
|
|
74
|
+
|
|
71
75
|
-of, --output_file_format <file_format> specifies output file format
|
|
72
76
|
(default: same as input file format)
|
|
73
77
|
|
|
@@ -157,6 +161,16 @@ Sequence type
|
|
|
157
161
|
gaps. For nucleotide sequences, the same characters are
|
|
158
162
|
considered gaps as well as N.
|
|
159
163
|
|
|
164
|
+
Ambiguity handling
|
|
165
|
+
Controls how recognized IUPAC ambiguity symbols are analyzed. "missing"
|
|
166
|
+
excludes them from entropy, composition, and KPI/KPIC state counts and
|
|
167
|
+
includes them in the unavailable fraction used by gap-based modes.
|
|
168
|
+
"fractional" distributes each symbol equally among its possible states
|
|
169
|
+
for entropy and composition, but excludes it from KPI/KPIC classification.
|
|
170
|
+
"literal" treats each ambiguity code as a separate state, matching the
|
|
171
|
+
legacy ambiguity interpretation. Configured gap characters take precedence.
|
|
172
|
+
Input and output alignment symbols are never rewritten.
|
|
173
|
+
|
|
160
174
|
Input and output file formats
|
|
161
175
|
Supported input files include:
|
|
162
176
|
fasta, clustal, maf, mauve, phylip, phylip-sequential,
|
|
@@ -171,7 +185,8 @@ Log
|
|
|
171
185
|
- Column 2 reports if the site was trimmed or kept (trim and keep, respectively),
|
|
172
186
|
- Column 3 reports if the site is a parsimony informative site or not (PI and nPI, respectively), or
|
|
173
187
|
a constant site or not (Const and nConst, respectively), or neither (nConst, nPI)
|
|
174
|
-
- Column 4 reports the
|
|
188
|
+
- Column 4 reports the effective unavailable fraction. In missing mode this
|
|
189
|
+
combines configured gaps and recognized ambiguity symbols.
|
|
175
190
|
|
|
176
191
|
Complementary
|
|
177
192
|
Creates an alignment file of only the trimmed sequences
|
|
@@ -269,6 +284,15 @@ def create_parser() -> ArgumentParser:
|
|
|
269
284
|
choices=seq_type_choices,
|
|
270
285
|
)
|
|
271
286
|
|
|
287
|
+
optional.add_argument(
|
|
288
|
+
"--ambiguity_handling",
|
|
289
|
+
"--ambiguity-handling",
|
|
290
|
+
choices=[handling.value for handling in AmbiguityHandling],
|
|
291
|
+
default=AmbiguityHandling.missing.value,
|
|
292
|
+
required=False,
|
|
293
|
+
help=SUPPRESS,
|
|
294
|
+
)
|
|
295
|
+
|
|
272
296
|
optional.add_argument(
|
|
273
297
|
"-h",
|
|
274
298
|
"--help",
|
|
@@ -4,6 +4,8 @@ from typing import Any
|
|
|
4
4
|
|
|
5
5
|
import numpy as np
|
|
6
6
|
|
|
7
|
+
from .ambiguity import is_nucleotide_alphabet
|
|
8
|
+
|
|
7
9
|
|
|
8
10
|
def _to_list(values: Any) -> list:
|
|
9
11
|
if values is None:
|
|
@@ -21,7 +23,6 @@ def _site_class_values(site_classes: Any) -> list[str]:
|
|
|
21
23
|
|
|
22
24
|
|
|
23
25
|
def _infer_sequence_type(msa) -> str:
|
|
24
|
-
nt_chars = set("ACGTUN-?*X")
|
|
25
26
|
observed = set()
|
|
26
27
|
for row in msa.seq_records.tolist():
|
|
27
28
|
for char in row:
|
|
@@ -33,7 +34,7 @@ def _infer_sequence_type(msa) -> str:
|
|
|
33
34
|
if len(observed) > 40:
|
|
34
35
|
break
|
|
35
36
|
|
|
36
|
-
if observed and observed
|
|
37
|
+
if observed and is_nucleotide_alphabet(observed):
|
|
37
38
|
return "nt"
|
|
38
39
|
return "aa"
|
|
39
40
|
|
|
@@ -74,25 +75,37 @@ def write_trim_plot_report(
|
|
|
74
75
|
mode: str,
|
|
75
76
|
gaps: float,
|
|
76
77
|
sequence_type: str | None = None,
|
|
78
|
+
ambiguity_handling: str | None = None,
|
|
77
79
|
) -> None:
|
|
78
80
|
trimmed_positions = [int(x) for x in _to_list(msa._site_positions_to_trim)]
|
|
79
81
|
alignment_length = int(msa.original_length)
|
|
80
82
|
trimmed_count = len(trimmed_positions)
|
|
81
83
|
kept_count = max(0, alignment_length - trimmed_count)
|
|
82
84
|
trimmed_percent = (
|
|
83
|
-
round((trimmed_count / alignment_length) * 100.0, 3)
|
|
85
|
+
round((trimmed_count / alignment_length) * 100.0, 3)
|
|
86
|
+
if alignment_length
|
|
87
|
+
else 0.0
|
|
84
88
|
)
|
|
85
89
|
resolved_sequence_type = sequence_type or _infer_sequence_type(msa)
|
|
90
|
+
resolved_ambiguity_handling = ambiguity_handling or getattr(
|
|
91
|
+
getattr(msa, "ambiguity_handling", None), "value", "missing"
|
|
92
|
+
)
|
|
86
93
|
|
|
87
94
|
payload = {
|
|
88
95
|
"mode": mode,
|
|
89
96
|
"gaps": gaps,
|
|
90
97
|
"sequence_type": resolved_sequence_type,
|
|
98
|
+
"ambiguity_handling": resolved_ambiguity_handling,
|
|
91
99
|
"alignment_length": alignment_length,
|
|
92
100
|
"trimmed_count": trimmed_count,
|
|
93
101
|
"kept_count": kept_count,
|
|
94
102
|
"trimmed_percent": trimmed_percent,
|
|
95
103
|
"site_gappyness": [float(x) for x in _to_list(msa.site_gappyness)],
|
|
104
|
+
"site_gap_fraction": [float(x) for x in _to_list(msa.site_gap_fraction)],
|
|
105
|
+
"site_ambiguity": [float(x) for x in _to_list(msa.site_ambiguity)],
|
|
106
|
+
"site_resolved_fraction": [
|
|
107
|
+
float(x) for x in _to_list(msa.site_resolved_fraction)
|
|
108
|
+
],
|
|
96
109
|
"site_entropy": [float(x) for x in _to_list(msa.site_entropy)],
|
|
97
110
|
"site_classification": _site_class_values(msa.site_classification_types),
|
|
98
111
|
"trimmed_positions": trimmed_positions,
|
|
@@ -304,6 +317,7 @@ def write_trim_plot_report(
|
|
|
304
317
|
<section class=\"cards\">
|
|
305
318
|
<article class=\"card\"><div class=\"label\">Mode</div><div class=\"value\">{escape(mode)}</div></article>
|
|
306
319
|
<article class=\"card\"><div class=\"label\">Sequence Type</div><div class=\"value\">{escape(resolved_sequence_type)}</div></article>
|
|
320
|
+
<article class=\"card\"><div class=\"label\">Ambiguity Handling</div><div class=\"value\">{escape(resolved_ambiguity_handling)}</div></article>
|
|
307
321
|
<article class=\"card\"><div class=\"label\">Threshold</div><div class=\"value\">{gaps}</div></article>
|
|
308
322
|
<article class=\"card\"><div class=\"label\">Alignment Length</div><div class=\"value\">{alignment_length}</div></article>
|
|
309
323
|
<article class=\"card\"><div class=\"label\">Sites Kept</div><div class=\"value\">{kept_count}</div></article>
|
|
@@ -313,14 +327,14 @@ def write_trim_plot_report(
|
|
|
313
327
|
<section class=\"panel\">
|
|
314
328
|
<h2>Per-site Tracks</h2>
|
|
315
329
|
<div class=\"legend\">
|
|
316
|
-
<span><span class=\"dot\" style=\"background: var(--accent);\"></span>
|
|
330
|
+
<span><span class=\"dot\" style=\"background: var(--accent);\"></span>effective unavailable fraction (binned bars)</span>
|
|
317
331
|
<span><span class=\"dot\" style=\"background: var(--warm);\"></span>entropy (line)</span>
|
|
318
332
|
<span><span class=\"dot\" style=\"background: var(--trim);\"></span>trimmed columns (red vertical bands)</span>
|
|
319
333
|
</div>
|
|
320
334
|
<div class=\"controls\">
|
|
321
335
|
<button class=\"btn\" id=\"export-track-png\" type=\"button\">Export Per-site Tracks (PNG)</button>
|
|
322
336
|
</div>
|
|
323
|
-
<p class=\"legend-note\">Trimmed columns are highlighted in red here and
|
|
337
|
+
<p class=\"legend-note\">In missing mode, the effective unavailable fraction combines configured gaps and recognized ambiguity symbols. Trimmed columns are highlighted in red here and below.</p>
|
|
324
338
|
<div class=\"track-wrap\">
|
|
325
339
|
<canvas id=\"track\" width=\"1200\" height=\"240\"></canvas>
|
|
326
340
|
</div>
|
|
@@ -455,7 +469,7 @@ def write_trim_plot_report(
|
|
|
455
469
|
const drawW = (canvas.clientWidth || 1200) - pad * 2;
|
|
456
470
|
const x = Math.max(pad, Math.min(pad + drawW - 1, Math.round(event.clientX - rect.left)));
|
|
457
471
|
const site = Math.min(n - 1, Math.max(0, Math.floor((x - pad) * n / drawW)));
|
|
458
|
-
tooltip.textContent = `Site ${{site + 1}} |
|
|
472
|
+
tooltip.textContent = `Site ${{site + 1}} | unavailable=${{data.site_gappyness[site].toFixed(4)}} | configured gaps=${{data.site_gap_fraction[site].toFixed(4)}} | ambiguity=${{data.site_ambiguity[site].toFixed(4)}} | entropy=${{data.site_entropy[site].toFixed(4)}} | class=${{data.site_classification[site]}} | status=${{trimmed.has(site) ? "trimmed" : "kept"}}`;
|
|
459
473
|
}});
|
|
460
474
|
|
|
461
475
|
canvas.addEventListener("mouseleave", () => {{
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "2.14.0"
|
|
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Optional
|
|
|
8
8
|
if TYPE_CHECKING:
|
|
9
9
|
from .files import FileFormat
|
|
10
10
|
from .helpers import SeqType
|
|
11
|
-
from .modes import TrimmingMode
|
|
11
|
+
from .modes import AmbiguityHandling, TrimmingMode
|
|
12
12
|
from .stop_codons import StopCodonMaskingStats
|
|
13
13
|
|
|
14
14
|
|
|
@@ -26,6 +26,7 @@ def write_user_args(
|
|
|
26
26
|
use_log: bool,
|
|
27
27
|
ends_only: bool,
|
|
28
28
|
stop_codon_masking: "Optional[StopCodonMaskingStats]" = None,
|
|
29
|
+
ambiguity_handling: "Optional[AmbiguityHandling]" = None,
|
|
29
30
|
) -> None:
|
|
30
31
|
if seq_type.value == "nt":
|
|
31
32
|
seq_type_name = "Nucleotides"
|
|
@@ -39,6 +40,9 @@ def write_user_args(
|
|
|
39
40
|
stop_codon_summary = (
|
|
40
41
|
f" Stop codon masking mode: {stop_codon_masking.mode.value}\n"
|
|
41
42
|
)
|
|
43
|
+
ambiguity_summary = (
|
|
44
|
+
ambiguity_handling.value if ambiguity_handling is not None else "missing"
|
|
45
|
+
)
|
|
42
46
|
|
|
43
47
|
logger.info(textwrap.dedent(f"""\
|
|
44
48
|
|
|
@@ -48,6 +52,7 @@ def write_user_args(
|
|
|
48
52
|
Input file: {in_file_name} (format: {in_file_format.value})
|
|
49
53
|
Output file: {out_file_name} (format: {out_file_format.value})
|
|
50
54
|
Sequence type: {seq_type_name}
|
|
55
|
+
Ambiguity handling: {ambiguity_summary}
|
|
51
56
|
Gaps threshold: {gaps}
|
|
52
57
|
Gap characters: {gap_chars}
|
|
53
58
|
Trimming mode: {mode.value}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: clipkit
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.14.0
|
|
4
4
|
Summary: Alignment trimming software for phylogenetics.
|
|
5
5
|
Home-page: https://github.com/jlsteenwyk/clipkit
|
|
6
6
|
Author: Jacob L. Steenwyk
|
|
@@ -107,8 +107,21 @@ clipkit input.fa
|
|
|
107
107
|
|
|
108
108
|
# mask all in-frame stops in a codon-aligned nucleotide MSA
|
|
109
109
|
clipkit coding.fa --codon --sequence_type nt --remove_stop_codons all
|
|
110
|
+
|
|
111
|
+
# fractionally weight IUPAC ambiguity symbols in entropy/composition analyses
|
|
112
|
+
clipkit ambiguous.fa --sequence_type nt --ambiguity_handling fractional
|
|
110
113
|
```
|
|
111
114
|
|
|
115
|
+
ClipKIT handles recognized IUPAC ambiguity symbols conservatively by default:
|
|
116
|
+
they are treated as missing evidence and contribute to the effective
|
|
117
|
+
unavailable fraction used by gap-based modes. Use `fractional` to distribute
|
|
118
|
+
them across possible states for entropy, composition, and the clade-entropy
|
|
119
|
+
part of heterotachy analysis, or `literal`
|
|
120
|
+
for legacy behavior. Configured gap characters take precedence, and alignment
|
|
121
|
+
symbols are never rewritten. See the
|
|
122
|
+
[ambiguity-handling documentation](https://jlsteenwyk.com/ClipKIT/advanced/#ambiguity-handling)
|
|
123
|
+
for the full nucleotide/protein mappings and mode-specific behavior.
|
|
124
|
+
|
|
112
125
|
The same operation is available through the Python API:
|
|
113
126
|
|
|
114
127
|
```python
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
__version__ = "2.13.2"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|