clipkit 2.12.2__tar.gz → 2.13.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.
Files changed (38) hide show
  1. {clipkit-2.12.2 → clipkit-2.13.0}/PKG-INFO +20 -1
  2. {clipkit-2.12.2 → clipkit-2.13.0}/README.md +19 -0
  3. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/api.py +4 -4
  4. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/args_processing.py +17 -2
  5. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/clipkit.py +60 -14
  6. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/exceptions.py +4 -0
  7. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/modes.py +6 -0
  8. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/msa.py +98 -23
  9. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/parser.py +36 -20
  10. clipkit-2.13.0/clipkit/stop_codons.py +67 -0
  11. clipkit-2.13.0/clipkit/version.py +1 -0
  12. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/write.py +33 -20
  13. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit.egg-info/PKG-INFO +20 -1
  14. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit.egg-info/SOURCES.txt +1 -0
  15. clipkit-2.12.2/clipkit/version.py +0 -1
  16. {clipkit-2.12.2 → clipkit-2.13.0}/LICENSE.md +0 -0
  17. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/__init__.py +0 -0
  18. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/__main__.py +0 -0
  19. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/ecomp/__init__.py +0 -0
  20. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/ecomp/reader.py +0 -0
  21. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/ecomp/writer.py +0 -0
  22. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/files.py +0 -0
  23. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/guide_tree.py +0 -0
  24. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/helpers.py +0 -0
  25. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/logger.py +0 -0
  26. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/plot_report.py +0 -0
  27. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/settings.py +0 -0
  28. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/site_classification.py +0 -0
  29. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/smart_gap_helper.py +0 -0
  30. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/stats.py +0 -0
  31. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit/warnings.py +0 -0
  32. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit.egg-info/dependency_links.txt +0 -0
  33. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit.egg-info/entry_points.txt +0 -0
  34. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit.egg-info/requires.txt +0 -0
  35. {clipkit-2.12.2 → clipkit-2.13.0}/clipkit.egg-info/top_level.txt +0 -0
  36. {clipkit-2.12.2 → clipkit-2.13.0}/pyproject.toml +0 -0
  37. {clipkit-2.12.2 → clipkit-2.13.0}/setup.cfg +0 -0
  38. {clipkit-2.12.2 → clipkit-2.13.0}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clipkit
3
- Version: 2.12.2
3
+ Version: 2.13.0
4
4
  Summary: Alignment trimming software for phylogenetics.
5
5
  Home-page: https://github.com/jlsteenwyk/clipkit
6
6
  Author: Jacob L. Steenwyk
@@ -101,6 +101,25 @@ Release automation details are documented in [RELEASE.md](RELEASE.md).
101
101
  pip install clipkit
102
102
  # run
103
103
  clipkit input.fa
104
+
105
+ # mask all in-frame stops in a codon-aligned nucleotide MSA
106
+ clipkit coding.fa --codon --sequence_type nt --remove_stop_codons all
107
+ ```
108
+
109
+ The same operation is available through the Python API:
110
+
111
+ ```python
112
+ from clipkit import clipkit
113
+
114
+ trim_run, stats = clipkit(
115
+ input_file_path="coding.fa",
116
+ mode="gappy",
117
+ gaps=0.9,
118
+ sequence_type="nt",
119
+ codon=True,
120
+ remove_stop_codons="all",
121
+ )
122
+ print(trim_run.stop_codon_masking.summary)
104
123
  ```
105
124
 
106
125
  **eComp archives**
@@ -67,6 +67,25 @@ Release automation details are documented in [RELEASE.md](RELEASE.md).
67
67
  pip install clipkit
68
68
  # run
69
69
  clipkit input.fa
70
+
71
+ # mask all in-frame stops in a codon-aligned nucleotide MSA
72
+ clipkit coding.fa --codon --sequence_type nt --remove_stop_codons all
73
+ ```
74
+
75
+ The same operation is available through the Python API:
76
+
77
+ ```python
78
+ from clipkit import clipkit
79
+
80
+ trim_run, stats = clipkit(
81
+ input_file_path="coding.fa",
82
+ mode="gappy",
83
+ gaps=0.9,
84
+ sequence_type="nt",
85
+ codon=True,
86
+ remove_stop_codons="all",
87
+ )
88
+ print(trim_run.stop_codon_masking.summary)
70
89
  ```
71
90
 
72
91
  **eComp archives**
@@ -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 TrimmingMode
8
+ from .modes import StopCodonMode, TrimmingMode
9
9
  from .plot_report import write_trim_plot_report
10
10
 
11
11
  if TYPE_CHECKING:
@@ -28,6 +28,7 @@ def clipkit(
28
28
  output_file_format=FileFormat.fasta,
29
29
  sequence_type: Union[SeqType, str, None] = None,
30
30
  codon: bool = False,
31
+ remove_stop_codons: Union[StopCodonMode, str, None] = None,
31
32
  ends_only=False,
32
33
  threads: int = 1,
33
34
  plot_trim_report_path: Union[str, None] = None,
@@ -43,9 +44,7 @@ def clipkit(
43
44
  has_raw_alignment = raw_alignment is not None
44
45
  has_input_path = input_file_path is not None
45
46
  if has_raw_alignment == has_input_path:
46
- raise ValueError(
47
- "Provide exactly one of raw_alignment or input_file_path."
48
- )
47
+ raise ValueError("Provide exactly one of raw_alignment or input_file_path.")
49
48
  if has_raw_alignment and raw_alignment == "":
50
49
  raise ValueError("raw_alignment cannot be empty.")
51
50
  if has_input_path and input_file_path == "":
@@ -94,6 +93,7 @@ def clipkit(
94
93
  quiet,
95
94
  ends_only,
96
95
  threads,
96
+ remove_stop_codons,
97
97
  )
98
98
 
99
99
  if plot_trim_report_path:
@@ -3,7 +3,8 @@ import os.path
3
3
  import sys
4
4
 
5
5
  from .helpers import SeqType
6
- from .modes import TrimmingMode
6
+ from .exceptions import StopCodonValidationError
7
+ from .modes import StopCodonMode, TrimmingMode
7
8
  from .settings import DEFAULT_AA_GAP_CHARS
8
9
 
9
10
  logger = logging.getLogger(__name__)
@@ -70,6 +71,17 @@ def process_args(args) -> dict:
70
71
  use_log = args.log or False
71
72
  quiet = args.quiet or False
72
73
  sequence_type = SeqType(args.sequence_type.lower()) if args.sequence_type else None
74
+ remove_stop_codons_arg = getattr(args, "remove_stop_codons", None)
75
+ remove_stop_codons = (
76
+ StopCodonMode(remove_stop_codons_arg) if remove_stop_codons_arg else None
77
+ )
78
+
79
+ if remove_stop_codons is not None and not codon:
80
+ raise StopCodonValidationError("Stop codon masking requires --codon.")
81
+ if remove_stop_codons is not None and sequence_type == SeqType.aa:
82
+ raise StopCodonValidationError(
83
+ "Stop codon masking requires nucleotide input (--sequence_type nt)."
84
+ )
73
85
 
74
86
  if codon and mode == TrimmingMode.c3:
75
87
  logger.warning(
@@ -94,7 +106,9 @@ def process_args(args) -> dict:
94
106
 
95
107
  if mode == TrimmingMode.cst:
96
108
  if not auxiliary_file:
97
- logger.warning("CST mode requires an auxiliary file via -a/--auxiliary_file.")
109
+ logger.warning(
110
+ "CST mode requires an auxiliary file via -a/--auxiliary_file."
111
+ )
98
112
  sys.exit()
99
113
  if not os.path.isfile(auxiliary_file):
100
114
  logger.warning("Auxiliary file does not exist.")
@@ -107,6 +121,7 @@ def process_args(args) -> dict:
107
121
  output_file_format=args.output_file_format,
108
122
  auxiliary_file=auxiliary_file,
109
123
  codon=codon,
124
+ remove_stop_codons=remove_stop_codons,
110
125
  sequence_type=sequence_type,
111
126
  complement=complement,
112
127
  gaps=gaps,
@@ -9,7 +9,7 @@ from multiprocessing import cpu_count
9
9
 
10
10
  from Bio.Align import MultipleSeqAlignment
11
11
  from .args_processing import process_args
12
- from .exceptions import InvalidInputFileFormat
12
+ from .exceptions import InvalidInputFileFormat, StopCodonValidationError
13
13
  from .files import (
14
14
  get_alignment_and_format,
15
15
  FileFormat,
@@ -26,12 +26,17 @@ 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 TrimmingMode
29
+ from .modes import 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
33
33
  from .settings import DEFAULT_AA_GAP_CHARS, DEFAULT_NT_GAP_CHARS
34
34
  from .smart_gap_helper import smart_gap_threshold_determination
35
+ from .stop_codons import (
36
+ StopCodonMaskingStats,
37
+ normalize_stop_codon_mode,
38
+ validate_stop_codon_configuration,
39
+ )
35
40
  from .version import __version__ as current_version
36
41
  from .warnings import (
37
42
  warn_if_all_sites_were_trimmed,
@@ -43,7 +48,7 @@ from .write import (
43
48
  write_output_files_message,
44
49
  )
45
50
 
46
- from dataclasses import dataclass
51
+ from dataclasses import dataclass, field
47
52
 
48
53
 
49
54
  @dataclass
@@ -56,6 +61,9 @@ class TrimRun:
56
61
  output_file_format: FileFormat
57
62
  gaps: float
58
63
  codon: bool
64
+ stop_codon_masking: StopCodonMaskingStats = field(
65
+ default_factory=StopCodonMaskingStats
66
+ )
59
67
  version: str = current_version
60
68
 
61
69
  @property
@@ -127,13 +135,23 @@ def run(
127
135
  quiet: bool,
128
136
  ends_only: bool,
129
137
  threads: int = 1,
138
+ remove_stop_codons: Union[StopCodonMode, str, None] = None,
130
139
  ):
131
- alignment, input_file_format = get_alignment_and_format(input_file, input_file_format)
140
+ alignment, input_file_format = get_alignment_and_format(
141
+ input_file, input_file_format
142
+ )
132
143
 
133
144
  if threads < 1:
134
145
  raise ValueError("threads must be an integer >= 1")
135
146
 
136
147
  sequence_type = sequence_type or get_seq_type(alignment)
148
+ remove_stop_codons = normalize_stop_codon_mode(remove_stop_codons)
149
+ validate_stop_codon_configuration(
150
+ remove_stop_codons,
151
+ codon=codon,
152
+ sequence_type=sequence_type,
153
+ alignment_length=alignment.get_alignment_length(),
154
+ )
137
155
 
138
156
  if not gap_characters:
139
157
  gap_characters = get_gap_chars(sequence_type)
@@ -171,6 +189,12 @@ def run(
171
189
  )
172
190
 
173
191
  msa = create_msa(alignment, gap_characters, effective_threads)
192
+ stop_codon_masking = (
193
+ msa.mask_stop_codons(remove_stop_codons)
194
+ if remove_stop_codons is not None
195
+ else StopCodonMaskingStats()
196
+ )
197
+ gap_characters = msa.gap_chars
174
198
 
175
199
  # determine smart_gap threshold
176
200
  if mode in {
@@ -197,14 +221,15 @@ def run(
197
221
  )
198
222
 
199
223
  trim_run = TrimRun(
200
- alignment,
201
- msa,
202
- gap_characters,
203
- sequence_type,
204
- input_file_format,
205
- output_file_format,
206
- gaps,
207
- codon,
224
+ alignment=alignment,
225
+ msa=msa,
226
+ gap_characters=gap_characters,
227
+ sequence_type=sequence_type,
228
+ input_file_format=input_file_format,
229
+ output_file_format=output_file_format,
230
+ gaps=gaps,
231
+ codon=codon,
232
+ stop_codon_masking=stop_codon_masking,
208
233
  )
209
234
 
210
235
  return trim_run, msa.stats
@@ -230,6 +255,7 @@ def execute(
230
255
  plot_trim_report: Union[str, None] = None,
231
256
  auxiliary_file: str = None,
232
257
  threads: int = 1,
258
+ remove_stop_codons: Union[StopCodonMode, str, None] = None,
233
259
  **kwargs,
234
260
  ) -> None:
235
261
  fh = None
@@ -248,6 +274,7 @@ def execute(
248
274
  logger.disabled = True
249
275
 
250
276
  start_time = time.time()
277
+ remove_stop_codons = normalize_stop_codon_mode(remove_stop_codons)
251
278
 
252
279
  if validate_only:
253
280
  try:
@@ -261,6 +288,12 @@ def execute(
261
288
  return
262
289
 
263
290
  validated_sequence_type = sequence_type or get_seq_type(alignment)
291
+ validate_stop_codon_configuration(
292
+ remove_stop_codons,
293
+ codon=codon,
294
+ sequence_type=validated_sequence_type,
295
+ alignment_length=alignment.get_alignment_length(),
296
+ )
264
297
  validated_gap_characters = gap_characters or get_gap_chars(
265
298
  validated_sequence_type
266
299
  )
@@ -292,6 +325,9 @@ def execute(
292
325
  gap_characters=validated_gap_characters,
293
326
  mode=mode.value,
294
327
  codon=codon,
328
+ stop_codon_masking=StopCodonMaskingStats(
329
+ mode=remove_stop_codons
330
+ ).summary,
295
331
  complement=complement,
296
332
  ends_only=ends_only,
297
333
  threads_requested=threads,
@@ -317,6 +353,7 @@ def execute(
317
353
  quiet,
318
354
  ends_only,
319
355
  threads,
356
+ remove_stop_codons,
320
357
  )
321
358
  except InvalidInputFileFormat:
322
359
  logger.error(
@@ -338,6 +375,7 @@ def execute(
338
375
  codon,
339
376
  use_log,
340
377
  ends_only,
378
+ trim_run.stop_codon_masking,
341
379
  )
342
380
 
343
381
  if dry_run:
@@ -385,6 +423,7 @@ def execute(
385
423
  gap_characters=trim_run.gap_characters,
386
424
  mode=mode.value,
387
425
  codon=codon,
426
+ stop_codon_masking=trim_run.stop_codon_masking.summary,
388
427
  complement=complement,
389
428
  ends_only=ends_only,
390
429
  threads_requested=threads,
@@ -404,7 +443,11 @@ def execute(
404
443
  )
405
444
  logger.info(f"Wrote trim plot report to {plot_trim_report}")
406
445
 
407
- write_output_stats(stats, start_time)
446
+ write_output_stats(
447
+ stats,
448
+ start_time,
449
+ stop_codon_masking=trim_run.stop_codon_masking,
450
+ )
408
451
  finally:
409
452
  if fh is not None:
410
453
  log_file_logger.removeHandler(fh)
@@ -432,7 +475,10 @@ def main(argv=None):
432
475
 
433
476
  args = parser.parse_args(argv)
434
477
 
435
- execute(**process_args(args))
478
+ try:
479
+ execute(**process_args(args))
480
+ except StopCodonValidationError as exc:
481
+ parser.error(str(exc))
436
482
 
437
483
 
438
484
  if __name__ == "__main__":
@@ -4,3 +4,7 @@ class ClipKITException(Exception):
4
4
 
5
5
  class InvalidInputFileFormat(ClipKITException):
6
6
  pass
7
+
8
+
9
+ class StopCodonValidationError(ValueError):
10
+ pass
@@ -23,3 +23,9 @@ class TrimmingMode(Enum):
23
23
  kpic_smart_gap = "kpic-smart-gap"
24
24
  cst = "cst" # custom site trimming
25
25
  c3 = "c3"
26
+
27
+
28
+ class StopCodonMode(Enum):
29
+ terminal = "terminal"
30
+ internal = "internal"
31
+ all = "all"
@@ -6,7 +6,8 @@ import math
6
6
  from typing import Union
7
7
  from Bio.Phylo.BaseTree import Tree
8
8
 
9
- from .modes import TrimmingMode
9
+ from .modes import StopCodonMode, TrimmingMode
10
+
10
11
  # Always import the standard version for compatibility
11
12
  from .site_classification import (
12
13
  SiteClassificationType,
@@ -15,7 +16,7 @@ from .site_classification import (
15
16
 
16
17
  from .settings import DEFAULT_AA_GAP_CHARS
17
18
  from .stats import TrimmingStats
18
-
19
+ from .stop_codons import STOP_CODONS, StopCodonMaskingStats
19
20
 
20
21
  # Counting a batch at a time bounds the temporary integer matrix while still
21
22
  # letting np.bincount process many columns in one compiled operation.
@@ -54,9 +55,11 @@ def _column_character_counts(seq_array: np.ndarray) -> tuple[np.ndarray, np.ndar
54
55
  encoded = code_points[:, start_idx:end_idx].astype(np.int64)
55
56
  encoded -= min_code
56
57
  encoded += offsets[:width]
57
- counts[:, start_idx:end_idx] = np.bincount(
58
- encoded.ravel(), minlength=width * code_span
59
- ).reshape(width, code_span).T
58
+ counts[:, start_idx:end_idx] = (
59
+ np.bincount(encoded.ravel(), minlength=width * code_span)
60
+ .reshape(width, code_span)
61
+ .T
62
+ )
60
63
 
61
64
  present = np.any(counts, axis=1)
62
65
  states = np.array(
@@ -75,9 +78,11 @@ def _column_character_counts(seq_array: np.ndarray) -> tuple[np.ndarray, np.ndar
75
78
  width = end_idx - start_idx
76
79
  encoded = np.searchsorted(states, seq_array[:, start_idx:end_idx])
77
80
  encoded += offsets[:width]
78
- counts[:, start_idx:end_idx] = np.bincount(
79
- encoded.ravel(), minlength=width * len(states)
80
- ).reshape(width, len(states)).T
81
+ counts[:, start_idx:end_idx] = (
82
+ np.bincount(encoded.ravel(), minlength=width * len(states))
83
+ .reshape(width, len(states))
84
+ .T
85
+ )
81
86
  return states, counts
82
87
 
83
88
 
@@ -108,7 +113,9 @@ class MSA:
108
113
  self._site_composition_bias_cache = None
109
114
 
110
115
  @staticmethod
111
- def from_bio_msa(alignment: MultipleSeqAlignment, gap_chars=None, threads=1) -> "MSA":
116
+ def from_bio_msa(
117
+ alignment: MultipleSeqAlignment, gap_chars=None, threads=1
118
+ ) -> "MSA":
112
119
  header_info = []
113
120
  sequences = []
114
121
  requires_uppercase_normalization = False
@@ -144,11 +151,77 @@ class MSA:
144
151
  def complement_to_bio_msa(self) -> MultipleSeqAlignment:
145
152
  return self._to_bio_msa(self.sites_trimmed)
146
153
 
154
+ def mask_stop_codons(self, mode: StopCodonMode) -> StopCodonMaskingStats:
155
+ """Replace selected in-frame stop codons with gap characters."""
156
+ if not isinstance(mode, StopCodonMode):
157
+ mode = StopCodonMode(mode)
158
+
159
+ if self._original_length % self._codon_size != 0:
160
+ raise ValueError(
161
+ "Stop codon masking requires an alignment length divisible by 3."
162
+ )
163
+ if self._original_length == 0:
164
+ return StopCodonMaskingStats(mode=mode)
165
+
166
+ if "-" not in self._gap_chars:
167
+ self._gap_chars = [*self._gap_chars, "-"]
168
+
169
+ codons = np.char.upper(self.seq_records).reshape(
170
+ self.seq_records.shape[0], -1, self._codon_size
171
+ )
172
+ gap_chars = np.char.upper(np.asarray(self._gap_chars, dtype="U1"))
173
+ complete_codons = ~np.any(np.isin(codons, gap_chars), axis=2)
174
+ codon_strings = (
175
+ np.ascontiguousarray(codons).view("U3").reshape(codons.shape[:2])
176
+ )
177
+ stop_codons = np.isin(codon_strings, tuple(STOP_CODONS)) & complete_codons
178
+
179
+ terminal_to_mask = np.zeros(stop_codons.shape, dtype=bool)
180
+ internal_to_mask = np.zeros(stop_codons.shape, dtype=bool)
181
+
182
+ for sequence_index in range(self.seq_records.shape[0]):
183
+ complete_positions = np.flatnonzero(complete_codons[sequence_index])
184
+ if complete_positions.size == 0:
185
+ continue
186
+
187
+ terminal_position = complete_positions[-1]
188
+ terminal_to_mask[sequence_index, terminal_position] = stop_codons[
189
+ sequence_index, terminal_position
190
+ ]
191
+ internal_to_mask[sequence_index] = stop_codons[sequence_index]
192
+ internal_to_mask[sequence_index, terminal_position] = False
193
+
194
+ selected = np.zeros(stop_codons.shape, dtype=bool)
195
+ if mode in (StopCodonMode.terminal, StopCodonMode.all):
196
+ selected |= terminal_to_mask
197
+ if mode in (StopCodonMode.internal, StopCodonMode.all):
198
+ selected |= internal_to_mask
199
+
200
+ selected_sites = np.repeat(selected, self._codon_size, axis=1)
201
+ self.seq_records[selected_sites] = "-"
202
+ self._reset_analysis_caches()
203
+
204
+ return StopCodonMaskingStats(
205
+ mode=mode,
206
+ terminal_masked=int(np.count_nonzero(terminal_to_mask & selected)),
207
+ internal_masked=int(np.count_nonzero(internal_to_mask & selected)),
208
+ )
209
+
210
+ def _reset_analysis_caches(self) -> None:
211
+ self._site_classification_types = None
212
+ self._column_character_frequencies = None
213
+ self._column_character_count_cache = {}
214
+ self._site_gappyness_cache = None
215
+ self._site_entropy_cache = None
216
+ self._site_composition_bias_cache = None
217
+
147
218
  def _to_bio_msa(self, sites) -> MultipleSeqAlignment:
148
219
  # NOTE: we use the description as the id to preserve the full sequence description - see issue #20
149
220
  if sites.shape[1] == 0:
150
221
  sequence_rows = [""] * sites.shape[0]
151
- elif sites.dtype.kind == "U" and sites.dtype.itemsize == np.dtype("U1").itemsize:
222
+ elif (
223
+ sites.dtype.kind == "U" and sites.dtype.itemsize == np.dtype("U1").itemsize
224
+ ):
152
225
  contiguous_sites = np.ascontiguousarray(sites)
153
226
  sequence_rows = (
154
227
  contiguous_sites.view(f"U{sites.shape[1]}").reshape(-1).tolist()
@@ -158,9 +231,7 @@ class MSA:
158
231
 
159
232
  return MultipleSeqAlignment(
160
233
  [
161
- SeqRecord(
162
- Seq(rec), id=str(info["description"]), description=""
163
- )
234
+ SeqRecord(Seq(rec), id=str(info["description"]), description="")
164
235
  for rec, info in zip(sequence_rows, self.header_info)
165
236
  ]
166
237
  )
@@ -353,11 +424,11 @@ class MSA:
353
424
  key = (cache_key, normalize_case)
354
425
  if key not in self._column_character_count_cache:
355
426
  seq_array = (
356
- np.char.upper(self.seq_records)
357
- if normalize_case
358
- else self.seq_records
427
+ np.char.upper(self.seq_records) if normalize_case else self.seq_records
428
+ )
429
+ self._column_character_count_cache[key] = _column_character_counts(
430
+ seq_array
359
431
  )
360
- self._column_character_count_cache[key] = _column_character_counts(seq_array)
361
432
  return self._column_character_count_cache[key]
362
433
 
363
434
  def _get_non_gap_character_counts(
@@ -387,9 +458,7 @@ class MSA:
387
458
 
388
459
  _, counts_by_state = self._get_non_gap_character_counts()
389
460
  observed_states = np.count_nonzero(counts_by_state, axis=0)
390
- states_occurring_at_least_twice = np.count_nonzero(
391
- counts_by_state >= 2, axis=0
392
- )
461
+ states_occurring_at_least_twice = np.count_nonzero(counts_by_state >= 2, axis=0)
393
462
 
394
463
  site_classification_types = np.empty(self._original_length, dtype=object)
395
464
  site_classification_types.fill(SiteClassificationType.other)
@@ -418,7 +487,9 @@ class MSA:
418
487
  sites_to_trim = np.where(self.site_gappyness >= gap_threshold)[0]
419
488
  elif mode == TrimmingMode.block_gappy:
420
489
  high_gap_sites = np.where(self.site_gappyness >= gap_threshold)[0]
421
- sites_to_trim = self._retain_contiguous_sites(high_gap_sites, min_block_size=2)
490
+ sites_to_trim = self._retain_contiguous_sites(
491
+ high_gap_sites, min_block_size=2
492
+ )
422
493
  elif mode == TrimmingMode.gappyout:
423
494
  # Keep sites at the inferred boundary and trim strictly above it.
424
495
  sites_to_trim = np.where(self.site_gappyness > gap_threshold)[0]
@@ -525,7 +596,9 @@ class MSA:
525
596
  if clade.is_terminal():
526
597
  continue
527
598
 
528
- taxa_names = [str(t.name) for t in clade.get_terminals() if t.name is not None]
599
+ taxa_names = [
600
+ str(t.name) for t in clade.get_terminals() if t.name is not None
601
+ ]
529
602
  indices = sorted(
530
603
  terminal_to_index[name]
531
604
  for name in taxa_names
@@ -655,7 +728,9 @@ class MSA:
655
728
  triplets = []
656
729
  for block in np.unique(blocks):
657
730
  start = block * self._codon_size
658
- positions = np.arange(start, min(start + self._codon_size, self._original_length))
731
+ positions = np.arange(
732
+ start, min(start + self._codon_size, self._original_length)
733
+ )
659
734
  triplets.extend(positions)
660
735
 
661
736
  return np.unique(triplets)
@@ -8,18 +8,18 @@ from argparse import (
8
8
 
9
9
  from .helpers import SeqType
10
10
  from .files import FileFormat
11
- from .modes import TrimmingMode
11
+ from .modes import StopCodonMode, TrimmingMode
12
12
  from .version import __version__
13
13
 
14
14
  _MAIN_DESCRIPTION_TEMPLATE = r"""\
15
- _____ _ _ _ _______ _______
15
+ _____ _ _ _ _______ _______
16
16
  / ____| (_) | |/ /_ _|__ __|
17
- | | | |_ _ __ | ' / | | | |
18
- | | | | | '_ \| < | | | |
19
- | |____| | | |_) | . \ _| |_ | |
20
- \_____|_|_| .__/|_|\_\_____| |_|
21
- | |
22
- |_|
17
+ | | | |_ _ __ | ' / | | | |
18
+ | | | | | '_ \| < | | | |
19
+ | |____| | | |_) | . \ _| |_ | |
20
+ \_____|_|_| .__/|_|\_\_____| |_|
21
+ | |
22
+ |_|
23
23
 
24
24
  Version: {version}
25
25
  Citation: Steenwyk et al. 2020, PLOS Biology. doi: 10.1371/journal.pbio.3001007
@@ -36,10 +36,10 @@ _REQUIRED_ARGUMENTS_DESCRIPTION = """\
36
36
  """
37
37
 
38
38
  _OPTIONAL_ARGUMENTS_DESCRIPTION = """\
39
- -o, --output <output_file_name> output file name
39
+ -o, --output <output_file_name> output file name
40
40
  (default: input file named with '.clipkit' suffix)
41
41
 
42
- -m, --mode <smart-gap, trimming mode
42
+ -m, --mode <smart-gap, trimming mode
43
43
  entropy,
44
44
  gappy,
45
45
  block-gappy,
@@ -47,14 +47,14 @@ _OPTIONAL_ARGUMENTS_DESCRIPTION = """\
47
47
  composition-bias,
48
48
  heterotachy,
49
49
  kpic,
50
- kpic-smart-gap,
51
- kpic-gappy,
50
+ kpic-smart-gap,
51
+ kpic-gappy,
52
52
  kpi,
53
53
  kpi-smart-gap,
54
54
  kpi-gappy,
55
55
  cst,
56
- c3>
57
-
56
+ c3>
57
+
58
58
  -g, --gaps <threshold_of_gaps> specifies gaps threshold
59
59
  (default: 0.9; entropy/composition-bias/heterotachy default: 0.8)
60
60
 
@@ -63,7 +63,7 @@ _OPTIONAL_ARGUMENTS_DESCRIPTION = """\
63
63
  default for nt: XxNn-?*)
64
64
 
65
65
  -if, --input_file_format <file_format> specifies input file format
66
- (default: auto-detect)
66
+ (default: auto-detect)
67
67
 
68
68
  -s, --sequence_type <nt, aa> specifies sequence type of input file
69
69
  (default: auto-detect)
@@ -82,6 +82,10 @@ _OPTIONAL_ARGUMENTS_DESCRIPTION = """\
82
82
 
83
83
  -co, --codon conduct trimming of codons
84
84
 
85
+ --remove_stop_codons <terminal, mask selected in-frame stop codons as gaps
86
+ internal,
87
+ all> (requires nucleotide input and --codon)
88
+
85
89
  -eo, --ends_only trim only from the ends of the alignment
86
90
 
87
91
  -t, --threads <number_of_threads> requested number of threads to use for parallel processing
@@ -104,7 +108,7 @@ _OPTIONAL_ARGUMENTS_DESCRIPTION = """\
104
108
 
105
109
 
106
110
  -------------------------------------
107
- | Detailed explanation of arguments |
111
+ | Detailed explanation of arguments |
108
112
  -------------------------------------
109
113
  Modes
110
114
  smart-gap: dynamic determination of gaps threshold
@@ -163,7 +167,7 @@ Input and output file formats
163
167
  Log
164
168
  Creates a log file that summarizes the characteristics of each position.
165
169
  The log file has four columns.
166
- - Column 1 is the position in the alignment (starting at 1),
170
+ - Column 1 is the position in the alignment (starting at 1),
167
171
  - Column 2 reports if the site was trimmed or kept (trim and keep, respectively),
168
172
  - Column 3 reports if the site is a parsimony informative site or not (PI and nPI, respectively), or
169
173
  a constant site or not (Const and nConst, respectively), or neither (nConst, nPI)
@@ -176,6 +180,13 @@ Codon
176
180
  Trims codon-based alignments. If one position in a codon should be trimmed, the whole
177
181
  codon will be trimmed.
178
182
 
183
+ Remove stop codons
184
+ Masks in-frame stop codons with "---" before gap statistics and trimming.
185
+ "terminal" masks only a stop at the final complete non-gap codon in each
186
+ sequence, "internal" masks all other stop codons, and "all" masks both.
187
+ DNA and RNA stops are recognized case-insensitively. This option requires
188
+ nucleotide input, --codon, and an alignment length divisible by three.
189
+
179
190
  Threads
180
191
  Requested number of threads to use for parallel processing.
181
192
  For kpi/kpic family modes, ClipKIT may automatically use fewer
@@ -203,9 +214,7 @@ Plot trim report
203
214
 
204
215
 
205
216
  def _main_description() -> str:
206
- return textwrap.dedent(
207
- _MAIN_DESCRIPTION_TEMPLATE.format(version=__version__)
208
- )
217
+ return textwrap.dedent(_MAIN_DESCRIPTION_TEMPLATE.format(version=__version__))
209
218
 
210
219
 
211
220
  def create_parser() -> ArgumentParser:
@@ -346,6 +355,13 @@ def create_parser() -> ArgumentParser:
346
355
  help=SUPPRESS,
347
356
  )
348
357
 
358
+ optional.add_argument(
359
+ "--remove_stop_codons",
360
+ choices=[mode.value for mode in StopCodonMode],
361
+ required=False,
362
+ help=SUPPRESS,
363
+ )
364
+
349
365
  optional.add_argument(
350
366
  "-eo",
351
367
  "--ends_only",
@@ -0,0 +1,67 @@
1
+ from dataclasses import dataclass
2
+ from typing import Optional, Union
3
+
4
+ from .exceptions import StopCodonValidationError
5
+ from .modes import StopCodonMode
6
+
7
+ STOP_CODONS = frozenset({"TAA", "TAG", "TGA", "UAA", "UAG", "UGA"})
8
+
9
+
10
+ def normalize_stop_codon_mode(
11
+ mode: Union[StopCodonMode, str, None],
12
+ ) -> Optional[StopCodonMode]:
13
+ if mode is None or isinstance(mode, StopCodonMode):
14
+ return mode
15
+
16
+ try:
17
+ return StopCodonMode(mode)
18
+ except ValueError as exc:
19
+ choices = ", ".join(f"'{choice.value}'" for choice in StopCodonMode)
20
+ raise StopCodonValidationError(
21
+ f"remove_stop_codons must be one of: {choices}, or None."
22
+ ) from exc
23
+
24
+
25
+ def validate_stop_codon_configuration(
26
+ mode: Optional[StopCodonMode],
27
+ *,
28
+ codon: bool,
29
+ sequence_type,
30
+ alignment_length: int,
31
+ ) -> None:
32
+ if mode is None:
33
+ return
34
+ if not codon:
35
+ raise StopCodonValidationError(
36
+ "Stop codon masking requires codon-aware trimming "
37
+ "(codon=True / --codon)."
38
+ )
39
+ if getattr(sequence_type, "value", sequence_type) != "nt":
40
+ raise StopCodonValidationError(
41
+ "Stop codon masking requires nucleotide input "
42
+ "(sequence_type='nt' / --sequence_type nt)."
43
+ )
44
+ if alignment_length % 3 != 0:
45
+ raise StopCodonValidationError(
46
+ "Stop codon masking requires an alignment length divisible by 3."
47
+ )
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class StopCodonMaskingStats:
52
+ mode: Optional[StopCodonMode] = None
53
+ terminal_masked: int = 0
54
+ internal_masked: int = 0
55
+
56
+ @property
57
+ def total_masked(self) -> int:
58
+ return self.terminal_masked + self.internal_masked
59
+
60
+ @property
61
+ def summary(self) -> dict:
62
+ return {
63
+ "mode": self.mode.value if self.mode is not None else None,
64
+ "terminal_masked": self.terminal_masked,
65
+ "internal_masked": self.internal_masked,
66
+ "total_masked": self.total_masked,
67
+ }
@@ -0,0 +1 @@
1
+ __version__ = "2.13.0"
@@ -3,12 +3,13 @@ import time
3
3
  from .logger import logger
4
4
  from .stats import TrimmingStats
5
5
 
6
- from typing import TYPE_CHECKING
6
+ from typing import TYPE_CHECKING, Optional
7
7
 
8
8
  if TYPE_CHECKING:
9
9
  from .files import FileFormat
10
10
  from .helpers import SeqType
11
11
  from .modes import TrimmingMode
12
+ from .stop_codons import StopCodonMaskingStats
12
13
 
13
14
 
14
15
  def write_user_args(
@@ -24,6 +25,7 @@ def write_user_args(
24
25
  codon: bool,
25
26
  use_log: bool,
26
27
  ends_only: bool,
28
+ stop_codon_masking: "Optional[StopCodonMaskingStats]" = None,
27
29
  ) -> None:
28
30
  if seq_type.value == "nt":
29
31
  seq_type_name = "Nucleotides"
@@ -32,9 +34,13 @@ def write_user_args(
32
34
  """
33
35
  Function to print user arguments to stdout
34
36
  """
35
- logger.info(
36
- textwrap.dedent(
37
- f"""\
37
+ stop_codon_summary = ""
38
+ if stop_codon_masking is not None and stop_codon_masking.mode is not None:
39
+ stop_codon_summary = (
40
+ f" Stop codon masking mode: {stop_codon_masking.mode.value}\n"
41
+ )
42
+
43
+ logger.info(textwrap.dedent(f"""\
38
44
 
39
45
  -------------
40
46
  | Arguments |
@@ -47,11 +53,10 @@ def write_user_args(
47
53
  Trimming mode: {mode.value}
48
54
  Create complementary output: {complement}
49
55
  Process as codons: {codon}
56
+ {stop_codon_summary}\
50
57
  Trim ends only: {ends_only}
51
58
  Create log file: {use_log}
52
- """ # noqa
53
- )
54
- )
59
+ """)) # noqa
55
60
 
56
61
 
57
62
  def write_output_files_message(
@@ -60,9 +65,7 @@ def write_output_files_message(
60
65
  """
61
66
  Function to print out that the output files are being written
62
67
  """
63
- logger.info(
64
- textwrap.dedent(
65
- f"""\
68
+ logger.info(textwrap.dedent(f"""\
66
69
 
67
70
  ------------------------
68
71
  | Writing output files |
@@ -70,18 +73,29 @@ def write_output_files_message(
70
73
  Trimmed alignment: {out_file_name}
71
74
  Complement file: {out_file_name + '.complement' if complement else False}
72
75
  Log file: {out_file_name + '.log' if use_log else False}
73
- """
74
- )
75
- )
76
+ """))
76
77
 
77
78
 
78
- def write_output_stats(stats: "TrimmingStats", start_time: float) -> None:
79
+ def write_output_stats(
80
+ stats: "TrimmingStats",
81
+ start_time: float,
82
+ stop_codon_masking: "Optional[StopCodonMaskingStats]" = None,
83
+ ) -> None:
79
84
  """
80
85
  Function to print out output statistics
81
86
  """
82
- logger.info(
83
- textwrap.dedent(
84
- f"""\
87
+ stop_codon_summary = ""
88
+ if stop_codon_masking is not None and stop_codon_masking.mode is not None:
89
+ stop_codon_summary = (
90
+ f" Stop codon masking mode: {stop_codon_masking.mode.value}\n"
91
+ " Terminal stop codons masked: "
92
+ f"{stop_codon_masking.terminal_masked}\n"
93
+ " Internal stop codons masked: "
94
+ f"{stop_codon_masking.internal_masked}\n"
95
+ f" Total stop codons masked: {stop_codon_masking.total_masked}\n\n"
96
+ )
97
+
98
+ logger.info(textwrap.dedent(f"""\
85
99
 
86
100
  ---------------------
87
101
  | Output Statistics |
@@ -91,7 +105,6 @@ def write_output_stats(stats: "TrimmingStats", start_time: float) -> None:
91
105
  Number of sites trimmed: {stats.trimmed_length}
92
106
  Percentage of alignment trimmed: {stats.trimmed_percentage}%
93
107
 
108
+ {stop_codon_summary}\
94
109
  Execution time: {round(time.time() - start_time, 3)}s
95
- """
96
- )
97
- )
110
+ """))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: clipkit
3
- Version: 2.12.2
3
+ Version: 2.13.0
4
4
  Summary: Alignment trimming software for phylogenetics.
5
5
  Home-page: https://github.com/jlsteenwyk/clipkit
6
6
  Author: Jacob L. Steenwyk
@@ -101,6 +101,25 @@ Release automation details are documented in [RELEASE.md](RELEASE.md).
101
101
  pip install clipkit
102
102
  # run
103
103
  clipkit input.fa
104
+
105
+ # mask all in-frame stops in a codon-aligned nucleotide MSA
106
+ clipkit coding.fa --codon --sequence_type nt --remove_stop_codons all
107
+ ```
108
+
109
+ The same operation is available through the Python API:
110
+
111
+ ```python
112
+ from clipkit import clipkit
113
+
114
+ trim_run, stats = clipkit(
115
+ input_file_path="coding.fa",
116
+ mode="gappy",
117
+ gaps=0.9,
118
+ sequence_type="nt",
119
+ codon=True,
120
+ remove_stop_codons="all",
121
+ )
122
+ print(trim_run.stop_codon_masking.summary)
104
123
  ```
105
124
 
106
125
  **eComp archives**
@@ -20,6 +20,7 @@ clipkit/settings.py
20
20
  clipkit/site_classification.py
21
21
  clipkit/smart_gap_helper.py
22
22
  clipkit/stats.py
23
+ clipkit/stop_codons.py
23
24
  clipkit/version.py
24
25
  clipkit/warnings.py
25
26
  clipkit/write.py
@@ -1 +0,0 @@
1
- __version__ = "2.12.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