tsalign 8.0.0__cp315-cp315-win_amd64.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.
tsalign/__init__.py ADDED
@@ -0,0 +1,258 @@
1
+ from __future__ import annotations
2
+
3
+ import pathlib
4
+ from typing import List, Optional, Tuple, Union
5
+
6
+ from tsalign._tsalign import Aligner as _Aligner # type: ignore[import]
7
+ from tsalign._tsalign import TSPairwiseAlignment as _TSPairwiseAlignment # type: ignore[import]
8
+ from tsalign._types import (
9
+ AlignmentOp,
10
+ AlignmentRange,
11
+ SimpleAlignmentOp,
12
+ TemplateSwitchEntranceOp,
13
+ TemplateSwitchExitOp,
14
+ _parse_op,
15
+ )
16
+
17
+ _ALIGNER_KWARG_NAMES = frozenset(
18
+ {"no_ts", "min_length_strategy", "chaining_strategy", "total_length_strategy", "costs", "costs_file"}
19
+ )
20
+
21
+ __all__ = [
22
+ "Aligner",
23
+ "Alignment",
24
+ "align",
25
+ "AlignmentRange",
26
+ "AlignmentOp",
27
+ "SimpleAlignmentOp",
28
+ "TemplateSwitchEntranceOp",
29
+ "TemplateSwitchExitOp",
30
+ ]
31
+
32
+
33
+ class Alignment:
34
+ """Result of a pairwise alignment that may contain template switches.
35
+
36
+ Obtain an instance via :meth:`Aligner.align` or the module-level :func:`align`.
37
+ """
38
+
39
+ def __init__(self, inner: _TSPairwiseAlignment) -> None:
40
+ self._inner = inner
41
+
42
+ def cigar(self) -> Optional[str]:
43
+ """CIGAR string of the alignment.
44
+
45
+ Template switch operations are encoded as extended CIGAR tokens.
46
+ Returns ``None`` if no valid alignment target was found.
47
+ """
48
+ return self._inner.cigar()
49
+
50
+ def stats(self) -> dict:
51
+ """Dictionary of alignment statistics.
52
+
53
+ Keys include: ``cost``, ``cost_per_base``, ``duration_seconds``,
54
+ ``opened_nodes``, ``closed_nodes``, ``template_switch_amount``, and
55
+ nested ``result`` and ``sequences`` dicts.
56
+ """
57
+ return self._inner.stats()
58
+
59
+ def alignments(self) -> Optional[List[Tuple[int, AlignmentOp]]]:
60
+ """Compact list of alignment operations.
61
+
62
+ Each entry is ``(count, op)`` where ``count`` is the repetition count and
63
+ ``op`` is one of:
64
+
65
+ - :class:`SimpleAlignmentOp` — a basic edit (match, substitution,
66
+ insertion, deletion) in the primary or secondary track.
67
+ - :class:`TemplateSwitchEntranceOp` — start of a template switch.
68
+ - :class:`TemplateSwitchExitOp` — end of a template switch.
69
+
70
+ Returns ``None`` if the alignment has no valid target.
71
+ """
72
+ raw = self._inner.alignments()
73
+ if raw is None:
74
+ return None
75
+ return [(count, _parse_op(op)) for count, op in raw]
76
+
77
+ def viz_template_switches(self) -> None:
78
+ """Print an ASCII visualisation of template switch jumps to stdout."""
79
+ self._inner.viz_template_switches()
80
+
81
+
82
+ class Aligner:
83
+ """Pairwise DNA sequence aligner with template switch detection.
84
+
85
+ Template switches are short-range translocations where a query region
86
+ aligns to a different part of the reference, possibly on the reverse
87
+ complement strand. The aligner uses A* search under a configurable
88
+ gap-affine cost model.
89
+
90
+ Parameters
91
+ ----------
92
+ no_ts : bool
93
+ Disable template switch detection (plain gap-affine alignment).
94
+ Default: ``False``.
95
+ min_length_strategy : str
96
+ Strategy for enforcing the minimum template switch length.
97
+ One of ``"none"``, ``"lookahead"`` (default), ``"preprocess_price"``,
98
+ ``"preprocess_filter"``, ``"preprocess_lookahead"``.
99
+ chaining_strategy : str
100
+ A* lower-bound chaining strategy.
101
+ One of ``"none"`` (default), ``"lower_bound"``.
102
+ total_length_strategy : str
103
+ Total template switch length strategy.
104
+ One of ``"none"``, ``"maximise"`` (default).
105
+ costs : str, optional
106
+ Cost configuration as a raw ``.tsa``-format string.
107
+ costs_file : str or Path, optional
108
+ Path to a ``.tsa`` cost configuration file.
109
+ Mutually exclusive with ``costs``.
110
+ See ``sample_tsa_config/config.tsa`` for a skeleton.
111
+
112
+ Examples
113
+ --------
114
+ Default settings::
115
+
116
+ aligner = tsalign.Aligner()
117
+
118
+ Custom cost file::
119
+
120
+ aligner = tsalign.Aligner(costs_file="sample_tsa_config/config.tsa")
121
+ """
122
+
123
+ def __init__(
124
+ self,
125
+ *,
126
+ no_ts: bool = False,
127
+ min_length_strategy: str = "lookahead",
128
+ chaining_strategy: str = "none",
129
+ total_length_strategy: str = "maximise",
130
+ costs: Optional[str] = None,
131
+ costs_file: Optional[Union[str, pathlib.Path]] = None,
132
+ ) -> None:
133
+ if costs is not None and costs_file is not None:
134
+ raise ValueError("Provide at most one of 'costs' or 'costs_file'.")
135
+ if costs_file is not None:
136
+ costs = pathlib.Path(costs_file).read_text()
137
+ kwargs: dict = {
138
+ "no_ts": no_ts,
139
+ "min_length_strategy": min_length_strategy,
140
+ "chaining_strategy": chaining_strategy,
141
+ "total_length_strategy": total_length_strategy,
142
+ }
143
+ if costs is not None:
144
+ kwargs["costs"] = costs
145
+ self._inner = _Aligner(**kwargs)
146
+
147
+ def align(
148
+ self,
149
+ reference: object,
150
+ query: object,
151
+ *,
152
+ reference_name: str = "reference",
153
+ query_name: str = "query",
154
+ range: Optional[AlignmentRange] = None,
155
+ reference_start: Optional[int] = None,
156
+ reference_limit: Optional[int] = None,
157
+ query_start: Optional[int] = None,
158
+ query_limit: Optional[int] = None,
159
+ gap_characters: str = "",
160
+ cost_limit: Optional[int] = None,
161
+ memory_limit: Optional[int] = None,
162
+ ) -> Optional[Alignment]:
163
+ """Align two DNA sequences, accounting for template switches.
164
+
165
+ Parameters
166
+ ----------
167
+ reference : str-like
168
+ Reference sequence. Any object with a string representation is
169
+ accepted (e.g. ``Bio.Seq``).
170
+ query : str-like
171
+ Query sequence.
172
+ reference_name : str
173
+ Label for the reference sequence. Default: ``"reference"``.
174
+ query_name : str
175
+ Label for the query sequence. Default: ``"query"``.
176
+ range : AlignmentRange, optional
177
+ Coordinate window to align within. When provided, overrides the
178
+ individual ``reference_start`` / ``reference_limit`` /
179
+ ``query_start`` / ``query_limit`` arguments.
180
+ All coordinates refer to the sequences after removing
181
+ ``gap_characters``.
182
+ reference_start : int, optional
183
+ Start position in the reference (inclusive). Default: ``0``.
184
+ reference_limit : int, optional
185
+ End position in the reference (exclusive). Default: full length.
186
+ query_start : int, optional
187
+ Start position in the query (inclusive). Default: ``0``.
188
+ query_limit : int, optional
189
+ End position in the query (exclusive). Default: full length.
190
+ gap_characters : str
191
+ ASCII characters to remove from both sequences before aligning,
192
+ e.g. ``"-"``.
193
+ Default: ``""`` (remove nothing).
194
+ cost_limit : int, optional
195
+ Return ``None`` if there is no alignment with cost at most this
196
+ value. The limit is inclusive: an alignment whose cost equals the
197
+ limit is returned.
198
+ memory_limit : int, optional
199
+ Approximate memory limit in bytes. Abandon the search and return
200
+ ``None`` if it is exceeded.
201
+
202
+ Returns
203
+ -------
204
+ Alignment or None
205
+ ``None`` if no valid alignment was found within the given limits.
206
+ """
207
+ if range is not None:
208
+ reference_start = range.reference_start
209
+ reference_limit = range.reference_end
210
+ query_start = range.query_start
211
+ query_limit = range.query_end
212
+
213
+ inner = self._inner.align(
214
+ reference,
215
+ query,
216
+ reference_name=reference_name,
217
+ query_name=query_name,
218
+ reference_start=reference_start,
219
+ reference_limit=reference_limit,
220
+ query_start=query_start,
221
+ query_limit=query_limit,
222
+ gap_characters=gap_characters,
223
+ cost_limit=cost_limit,
224
+ memory_limit=memory_limit,
225
+ )
226
+ return Alignment(inner) if inner is not None else None
227
+
228
+
229
+ def align(
230
+ reference: object,
231
+ query: object,
232
+ **kwargs: object,
233
+ ) -> Optional[Alignment]:
234
+ """Align two DNA sequences in a single call.
235
+
236
+ A convenience wrapper that creates a temporary :class:`Aligner` and
237
+ immediately calls :meth:`~Aligner.align`.
238
+
239
+ Keyword arguments that belong to the aligner (``no_ts``,
240
+ ``min_length_strategy``, ``chaining_strategy``, ``total_length_strategy``,
241
+ ``costs``, ``costs_file``) are forwarded to the constructor; all remaining
242
+ keyword arguments are forwarded to :meth:`~Aligner.align`.
243
+
244
+ Returns
245
+ -------
246
+ Alignment or None
247
+ ``None`` if no valid alignment was found within the given limits.
248
+
249
+ Examples
250
+ --------
251
+ ::
252
+
253
+ result = tsalign.align("ACGTACGT", "ACGACGT")
254
+ print(result.cigar())
255
+ """
256
+ aligner_kwargs = {k: v for k, v in kwargs.items() if k in _ALIGNER_KWARG_NAMES}
257
+ align_kwargs = {k: v for k, v in kwargs.items() if k not in _ALIGNER_KWARG_NAMES}
258
+ return Aligner(**aligner_kwargs).align(reference, query, **align_kwargs)
Binary file
tsalign/_types.py ADDED
@@ -0,0 +1,75 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Union
5
+
6
+
7
+ @dataclass
8
+ class AlignmentRange:
9
+ """Coordinate bounds for a pairwise alignment."""
10
+
11
+ reference_start: int = 0
12
+ reference_end: "int | None" = None
13
+ query_start: int = 0
14
+ query_end: "int | None" = None
15
+
16
+
17
+ @dataclass
18
+ class SimpleAlignmentOp:
19
+ """A basic edit operation in the primary or secondary alignment track.
20
+
21
+ The ``kind`` attribute is one of: ``PrimaryMatch``, ``PrimarySubstitution``,
22
+ ``PrimaryInsertion``, ``PrimaryDeletion``, ``PrimaryFlankMatch``,
23
+ ``PrimaryFlankSubstitution``, ``PrimaryFlankInsertion``, ``PrimaryFlankDeletion``,
24
+ ``SecondaryMatch``, ``SecondarySubstitution``, ``SecondaryInsertion``,
25
+ ``SecondaryDeletion``.
26
+ """
27
+
28
+ kind: str
29
+
30
+
31
+ @dataclass
32
+ class TemplateSwitchEntranceOp:
33
+ """Entrance into a template switch region."""
34
+
35
+ kind: str # always "TemplateSwitchEntrance"
36
+ first_offset: int
37
+ descendant: str # "Reference" or "Query"
38
+ ancestor: str # "Reference" or "Query"
39
+ direction: str # "Forward" or "Reverse"
40
+ # {start_left_shift, start_right_shift, end_left_shift, end_right_shift},
41
+ # or None if the uncertainty range was not computed
42
+ uncertainty_range: "dict | None"
43
+
44
+
45
+ @dataclass
46
+ class TemplateSwitchExitOp:
47
+ """Exit from a template switch region."""
48
+
49
+ kind: str # always "TemplateSwitchExit"
50
+ anti_descendant_gap: int
51
+
52
+
53
+ AlignmentOp = Union[SimpleAlignmentOp, TemplateSwitchEntranceOp, TemplateSwitchExitOp]
54
+
55
+
56
+ def _parse_op(raw: object) -> AlignmentOp:
57
+ if isinstance(raw, str):
58
+ return SimpleAlignmentOp(kind=raw)
59
+ if isinstance(raw, dict):
60
+ if "TemplateSwitchEntrance" in raw:
61
+ d = raw["TemplateSwitchEntrance"]
62
+ return TemplateSwitchEntranceOp(
63
+ kind="TemplateSwitchEntrance",
64
+ first_offset=d["first_offset"],
65
+ descendant=d["descendant"],
66
+ ancestor=d["ancestor"],
67
+ direction=d["direction"],
68
+ uncertainty_range=d["uncertainty_range"],
69
+ )
70
+ if "TemplateSwitchExit" in raw:
71
+ return TemplateSwitchExitOp(
72
+ kind="TemplateSwitchExit",
73
+ anti_descendant_gap=raw["TemplateSwitchExit"]["anti_descendant_gap"],
74
+ )
75
+ raise ValueError(f"Unknown alignment op: {raw!r}")
tsalign/py.typed ADDED
File without changes
@@ -0,0 +1,153 @@
1
+ Metadata-Version: 2.4
2
+ Name: tsalign
3
+ Version: 8.0.0
4
+ Classifier: Programming Language :: Rust
5
+ Classifier: Programming Language :: Python :: Implementation :: CPython
6
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
9
+
10
+ # Python Bindings for [`lib_tsalign`](https://crates.io/crates/lib_tsalign)
11
+
12
+ [![PyPI](https://img.shields.io/pypi/v/tsalign)](https://pypi.org/project/tsalign/)
13
+
14
+ Python bindings for the template switch aligner. Aligns two DNA sequences
15
+ while detecting template switches — short-range translocations where a query
16
+ region is copied from (or aligns to) a different location, possibly on the
17
+ reverse complement strand.
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ pip install tsalign
23
+ ```
24
+
25
+ ## Quick start
26
+
27
+ ```python
28
+ import tsalign
29
+
30
+ result = tsalign.align("ACGTACGT", "ACGACGT")
31
+ print(result.cigar()) # compact alignment string
32
+ print(result.stats()) # cost, duration, node counts, …
33
+ ```
34
+
35
+ ## Aligner options
36
+
37
+ Create an `Aligner` once and reuse it for many sequences:
38
+
39
+ ```python
40
+ aligner = tsalign.Aligner(
41
+ min_length_strategy="preprocess_lookahead", # default: "lookahead"
42
+ chaining_strategy="lower_bound", # default: "none"
43
+ total_length_strategy="maximise", # default: "maximise"
44
+ no_ts=False, # set True for plain gap-affine
45
+ )
46
+
47
+ result = aligner.align("ACGTACGT", "ACGACGT")
48
+ ```
49
+
50
+ ## Custom cost configuration
51
+
52
+ Costs are specified in `.tsa` format. Use `sample_tsa_config/config.tsa`
53
+ as a starting point and consult the [main repository README](../README.md#modifying-the-cost-function) for a description
54
+ of each parameter.
55
+
56
+ ```python
57
+ aligner = tsalign.Aligner(costs_file="sample_tsa_config/config.tsa")
58
+ result = aligner.align("ACGTACGT", "ACGACGT")
59
+ ```
60
+
61
+ You can also pass the cost string directly:
62
+
63
+ ```python
64
+ with open("my_costs.tsa") as f:
65
+ cost_str = f.read()
66
+ aligner = tsalign.Aligner(costs=cost_str)
67
+ ```
68
+
69
+ ## Restricting the alignment range
70
+
71
+ Use `AlignmentRange` to align only a window of the input sequences:
72
+
73
+ ```python
74
+ from tsalign import Aligner, AlignmentRange
75
+
76
+ aligner = Aligner()
77
+ result = aligner.align(
78
+ "NNNACGTACGTNNN",
79
+ "ACGACGT",
80
+ range=AlignmentRange(reference_start=3, reference_end=11),
81
+ )
82
+ print(result.cigar())
83
+ ```
84
+
85
+ Individual start/limit keyword arguments are also accepted when `range` is
86
+ not provided:
87
+
88
+ ```python
89
+ result = aligner.align(
90
+ "NNNACGTACGTNNN",
91
+ "ACGACGT",
92
+ reference_start=3,
93
+ reference_limit=11,
94
+ )
95
+ ```
96
+
97
+ ## Skipping gap characters
98
+
99
+ Characters listed in `gap_characters` are removed from both sequences
100
+ before aligning. Range coordinates refer to the sequences without these characters.
101
+
102
+ ```python
103
+ result = aligner.align("ACG-TACGT", "AC-GACGT", gap_characters="-")
104
+ ```
105
+
106
+ ## Working with alignment operations
107
+
108
+ `alignment.alignments()` returns a typed list of `(count, op)` pairs:
109
+
110
+ ```python
111
+ from tsalign import align, TemplateSwitchEntranceOp, TemplateSwitchExitOp
112
+
113
+ result = align(reference, query)
114
+ for count, op in result.alignments():
115
+ if isinstance(op, TemplateSwitchEntranceOp):
116
+ print(f"Template switch: {op.direction}, descendant={op.descendant}, offset={op.first_offset}")
117
+ elif isinstance(op, TemplateSwitchExitOp):
118
+ print(f"Exit, anti-descendant gap: {op.anti_descendant_gap}")
119
+ else:
120
+ # SimpleAlignmentOp — a basic edit in the primary or secondary track
121
+ print(f"{count}x {op.kind}")
122
+ ```
123
+
124
+ ## Visualisation
125
+
126
+ ```python
127
+ result = tsalign.align(reference, query)
128
+ result.viz_template_switches() # prints ASCII art to stdout
129
+ ```
130
+
131
+ ## Limiting search resources
132
+
133
+ ```python
134
+ result = aligner.align(
135
+ reference,
136
+ query,
137
+ cost_limit=100, # return None if every alignment costs more than this (inclusive limit)
138
+ memory_limit=500_000, # return None if memory exceeds roughly this number of bytes
139
+ )
140
+ if result is None:
141
+ print("No alignment found within limits")
142
+ ```
143
+
144
+ ## Accepted sequence types
145
+
146
+ Any object whose `str()` representation is a valid DNA string (ACGTN) is
147
+ accepted — including `Bio.Seq`:
148
+
149
+ ```python
150
+ from Bio.Seq import Seq
151
+ result = tsalign.align(Seq("ACGTACGT"), Seq("ACGACGT"))
152
+ ```
153
+
@@ -0,0 +1,8 @@
1
+ tsalign/__init__.py,sha256=zxHnBk5flQjAY6RLvtGaGPSQiu_XeI4hQKuLPT2a2-Y,9457
2
+ tsalign/_tsalign.cp315-win_amd64.pyd,sha256=7HwfIpWMPODvjtk199aCLXiQnWYypCEbwXKwT4FTAqQ,6536704
3
+ tsalign/_types.py,sha256=iU-12Fb64AqP-d1Fh1V2LNnw0PaFHkddcFMJC-7VoVQ,2445
4
+ tsalign/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ tsalign-8.0.0.dist-info/METADATA,sha256=QrUkmabBJ01MKM3dgIWQi9dc3CwsqK7DddpRH1HK_D0,4329
6
+ tsalign-8.0.0.dist-info/WHEEL,sha256=Q5QdGvjBfn8x6ihg-B4VQuuGKk7DT67L9DVrwEH_qj8,97
7
+ tsalign-8.0.0.dist-info/sboms/py_lib_tsalign.cyclonedx.json,sha256=TC1wteIhGL3gDsXrnLW0-8XoZBnj3a5_eHU9rTwFFb0,179830
8
+ tsalign-8.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: maturin (1.16.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp315-cp315-win_amd64