smftools 0.3.1__py3-none-any.whl → 0.3.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- smftools/_version.py +1 -1
- smftools/cli/chimeric_adata.py +1563 -0
- smftools/cli/helpers.py +18 -2
- smftools/cli/hmm_adata.py +18 -1
- smftools/cli/latent_adata.py +522 -67
- smftools/cli/load_adata.py +2 -2
- smftools/cli/preprocess_adata.py +32 -93
- smftools/cli/recipes.py +26 -0
- smftools/cli/spatial_adata.py +23 -109
- smftools/cli/variant_adata.py +423 -0
- smftools/cli_entry.py +41 -5
- smftools/config/conversion.yaml +0 -10
- smftools/config/deaminase.yaml +3 -0
- smftools/config/default.yaml +49 -13
- smftools/config/experiment_config.py +96 -3
- smftools/constants.py +4 -0
- smftools/hmm/call_hmm_peaks.py +1 -1
- smftools/informatics/binarize_converted_base_identities.py +2 -89
- smftools/informatics/converted_BAM_to_adata.py +53 -13
- smftools/informatics/h5ad_functions.py +83 -0
- smftools/informatics/modkit_extract_to_adata.py +4 -0
- smftools/plotting/__init__.py +26 -12
- smftools/plotting/autocorrelation_plotting.py +22 -4
- smftools/plotting/chimeric_plotting.py +1893 -0
- smftools/plotting/classifiers.py +28 -14
- smftools/plotting/general_plotting.py +58 -3362
- smftools/plotting/hmm_plotting.py +1586 -2
- smftools/plotting/latent_plotting.py +804 -0
- smftools/plotting/plotting_utils.py +243 -0
- smftools/plotting/position_stats.py +16 -8
- smftools/plotting/preprocess_plotting.py +281 -0
- smftools/plotting/qc_plotting.py +8 -3
- smftools/plotting/spatial_plotting.py +1134 -0
- smftools/plotting/variant_plotting.py +1231 -0
- smftools/preprocessing/__init__.py +3 -0
- smftools/preprocessing/append_base_context.py +1 -1
- smftools/preprocessing/append_mismatch_frequency_sites.py +35 -6
- smftools/preprocessing/append_sequence_mismatch_annotations.py +171 -0
- smftools/preprocessing/append_variant_call_layer.py +480 -0
- smftools/preprocessing/flag_duplicate_reads.py +4 -4
- smftools/preprocessing/invert_adata.py +1 -0
- smftools/readwrite.py +109 -85
- smftools/tools/__init__.py +6 -0
- smftools/tools/calculate_knn.py +121 -0
- smftools/tools/calculate_nmf.py +18 -7
- smftools/tools/calculate_pca.py +180 -0
- smftools/tools/calculate_umap.py +70 -154
- smftools/tools/position_stats.py +4 -4
- smftools/tools/rolling_nn_distance.py +640 -3
- smftools/tools/sequence_alignment.py +140 -0
- smftools/tools/tensor_factorization.py +52 -4
- {smftools-0.3.1.dist-info → smftools-0.3.2.dist-info}/METADATA +3 -1
- {smftools-0.3.1.dist-info → smftools-0.3.2.dist-info}/RECORD +56 -42
- {smftools-0.3.1.dist-info → smftools-0.3.2.dist-info}/WHEEL +0 -0
- {smftools-0.3.1.dist-info → smftools-0.3.2.dist-info}/entry_points.txt +0 -0
- {smftools-0.3.1.dist-info → smftools-0.3.2.dist-info}/licenses/LICENSE +0 -0
|
@@ -6,6 +6,9 @@ _LAZY_ATTRS = {
|
|
|
6
6
|
"append_base_context": "smftools.preprocessing.append_base_context",
|
|
7
7
|
"append_binary_layer_by_base_context": "smftools.preprocessing.append_binary_layer_by_base_context",
|
|
8
8
|
"append_mismatch_frequency_sites": "smftools.preprocessing.append_mismatch_frequency_sites",
|
|
9
|
+
"append_variant_call_layer": "smftools.preprocessing.append_variant_call_layer",
|
|
10
|
+
"append_variant_segment_layer": "smftools.preprocessing.append_variant_call_layer",
|
|
11
|
+
"append_sequence_mismatch_annotations": "smftools.preprocessing.append_sequence_mismatch_annotations",
|
|
9
12
|
"binarize_adata": "smftools.preprocessing.binarize",
|
|
10
13
|
"binarize_on_Youden": "smftools.preprocessing.binarize_on_Youden",
|
|
11
14
|
"calculate_complexity_II": "smftools.preprocessing.calculate_complexity_II",
|
|
@@ -51,7 +51,7 @@ def append_base_context(
|
|
|
51
51
|
site_types += ["A_site"]
|
|
52
52
|
|
|
53
53
|
for ref in references:
|
|
54
|
-
# Assess if the strand is the top or bottom strand
|
|
54
|
+
# Assess if the modified strand is the top or bottom strand.
|
|
55
55
|
if "top" in ref:
|
|
56
56
|
strand = "top"
|
|
57
57
|
elif "bottom" in ref:
|
|
@@ -5,7 +5,7 @@ from typing import TYPE_CHECKING, Iterable, Sequence
|
|
|
5
5
|
import numpy as np
|
|
6
6
|
import pandas as pd
|
|
7
7
|
|
|
8
|
-
from smftools.constants import MODKIT_EXTRACT_SEQUENCE_BASE_TO_INT
|
|
8
|
+
from smftools.constants import BASE_QUALITY_SCORES, MODKIT_EXTRACT_SEQUENCE_BASE_TO_INT
|
|
9
9
|
from smftools.logging_utils import get_logger
|
|
10
10
|
|
|
11
11
|
if TYPE_CHECKING:
|
|
@@ -19,6 +19,7 @@ def append_mismatch_frequency_sites(
|
|
|
19
19
|
ref_column: str = "Reference_strand",
|
|
20
20
|
mismatch_layer: str = "mismatch_integer_encoding",
|
|
21
21
|
read_span_layer: str = "read_span_mask",
|
|
22
|
+
quality_layer: str | None = None,
|
|
22
23
|
mismatch_frequency_range: Sequence[float] | None = (0.05, 0.95),
|
|
23
24
|
uns_flag: str = "append_mismatch_frequency_sites_performed",
|
|
24
25
|
force_redo: bool = False,
|
|
@@ -31,6 +32,7 @@ def append_mismatch_frequency_sites(
|
|
|
31
32
|
ref_column: Obs column defining reference categories.
|
|
32
33
|
mismatch_layer: Layer containing mismatch integer encodings.
|
|
33
34
|
read_span_layer: Layer containing read span masks (1=covered, 0=not covered).
|
|
35
|
+
quality_layer: Layer containing base quality scores for Q-value based error rates.
|
|
34
36
|
mismatch_frequency_range: Lower/upper bounds (inclusive) for variable site flagging.
|
|
35
37
|
uns_flag: Flag in ``adata.uns`` indicating prior completion.
|
|
36
38
|
force_redo: Whether to rerun even if ``uns_flag`` is set.
|
|
@@ -73,6 +75,16 @@ def append_mismatch_frequency_sites(
|
|
|
73
75
|
read_span_layer,
|
|
74
76
|
)
|
|
75
77
|
|
|
78
|
+
if quality_layer is None:
|
|
79
|
+
if BASE_QUALITY_SCORES in adata.layers:
|
|
80
|
+
quality_layer = BASE_QUALITY_SCORES
|
|
81
|
+
elif "base_qualities" in adata.layers:
|
|
82
|
+
quality_layer = "base_qualities"
|
|
83
|
+
|
|
84
|
+
if quality_layer is not None and quality_layer not in adata.layers:
|
|
85
|
+
logger.debug("Quality layer '%s' not found; falling back to range flagging.", quality_layer)
|
|
86
|
+
quality_layer = None
|
|
87
|
+
|
|
76
88
|
references = adata.obs[ref_column].cat.categories
|
|
77
89
|
n_vars = adata.shape[1]
|
|
78
90
|
|
|
@@ -125,11 +137,28 @@ def append_mismatch_frequency_sites(
|
|
|
125
137
|
)
|
|
126
138
|
frequency_values = np.where(ref_position_mask.values, frequency_values, np.nan)
|
|
127
139
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
140
|
+
mean_error_rate: np.ndarray | None = None
|
|
141
|
+
if quality_layer is not None:
|
|
142
|
+
quality_matrix = np.asarray(adata.layers[quality_layer][ref_mask]).astype(float)
|
|
143
|
+
quality_matrix[quality_matrix < 0] = np.nan
|
|
144
|
+
if has_span_mask:
|
|
145
|
+
quality_matrix = np.where(coverage_mask, quality_matrix, np.nan)
|
|
146
|
+
error_matrix = np.power(10.0, -quality_matrix / 10.0)
|
|
147
|
+
mean_error_rate = np.nanmean(error_matrix, axis=0)
|
|
148
|
+
mean_error_rate = np.where(ref_position_mask.values, mean_error_rate, np.nan)
|
|
149
|
+
|
|
150
|
+
if mean_error_rate is None:
|
|
151
|
+
variable_flags = (
|
|
152
|
+
(frequency_values >= lower_bound)
|
|
153
|
+
& (frequency_values <= upper_bound)
|
|
154
|
+
& ref_position_mask.values
|
|
155
|
+
)
|
|
156
|
+
else:
|
|
157
|
+
variable_flags = (
|
|
158
|
+
(frequency_values > mean_error_rate)
|
|
159
|
+
& ref_position_mask.values
|
|
160
|
+
& np.isfinite(mean_error_rate)
|
|
161
|
+
)
|
|
133
162
|
|
|
134
163
|
base_counts_by_int: dict[int, np.ndarray] = {}
|
|
135
164
|
for base_int in base_int_to_label:
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
from smftools.logging_utils import get_logger
|
|
9
|
+
from smftools.tools.sequence_alignment import align_sequences_with_mismatches
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
import anndata as ad
|
|
13
|
+
|
|
14
|
+
logger = get_logger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _format_mismatch_identity(event: str, seq1_base: str | None, seq2_base: str | None) -> str:
|
|
18
|
+
if event == "substitution":
|
|
19
|
+
return f"{seq1_base}->{seq2_base}"
|
|
20
|
+
if event == "insertion":
|
|
21
|
+
return f"ins:{seq2_base}"
|
|
22
|
+
return f"del:{seq1_base}"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def append_sequence_mismatch_annotations(
|
|
26
|
+
adata: "ad.AnnData",
|
|
27
|
+
seq1_column: str,
|
|
28
|
+
seq2_column: str,
|
|
29
|
+
output_prefix: str | None = None,
|
|
30
|
+
match_score: int = 1,
|
|
31
|
+
mismatch_score: int = -1,
|
|
32
|
+
gap_score: int = -2,
|
|
33
|
+
ignore_n: bool = True,
|
|
34
|
+
bypass: bool = False,
|
|
35
|
+
force_redo: bool = False,
|
|
36
|
+
uns_flag: str = "append_sequence_mismatch_annotations_performed",
|
|
37
|
+
) -> None:
|
|
38
|
+
"""Append mismatch annotations by aligning full reference sequences.
|
|
39
|
+
|
|
40
|
+
Extracts the full reference sequences from per-position base columns in
|
|
41
|
+
``adata.var``, performs a single global alignment, and maps mismatches
|
|
42
|
+
(substitutions, insertions, deletions) back to ``adata.var`` indices.
|
|
43
|
+
|
|
44
|
+
Results stored in ``adata.var``:
|
|
45
|
+
- ``{prefix}_mismatch_type``: Per-position str — ``"substitution"``,
|
|
46
|
+
``"insertion"``, ``"deletion"``, or ``""`` (no mismatch).
|
|
47
|
+
- ``{prefix}_mismatch_identity``: Per-position str — e.g. ``"A->G"``,
|
|
48
|
+
``"ins:T"``, ``"del:C"``, or ``""``).
|
|
49
|
+
- ``{prefix}_is_mismatch``: Per-position bool flag.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
adata: AnnData object.
|
|
53
|
+
seq1_column: Column in ``adata.var`` with per-position bases for reference 1.
|
|
54
|
+
seq2_column: Column in ``adata.var`` with per-position bases for reference 2.
|
|
55
|
+
output_prefix: Prefix for output columns. Defaults to ``{seq1_column}__{seq2_column}``.
|
|
56
|
+
match_score: Alignment match score.
|
|
57
|
+
mismatch_score: Alignment mismatch score.
|
|
58
|
+
gap_score: Alignment gap score.
|
|
59
|
+
ignore_n: Whether to ignore mismatches involving ``N`` bases.
|
|
60
|
+
bypass: Whether to skip processing.
|
|
61
|
+
force_redo: Whether to rerun even if ``uns_flag`` is set.
|
|
62
|
+
uns_flag: Flag in ``adata.uns`` indicating prior completion.
|
|
63
|
+
"""
|
|
64
|
+
already = bool(adata.uns.get(uns_flag, False))
|
|
65
|
+
if (already and not force_redo) or bypass:
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
if seq1_column not in adata.var:
|
|
69
|
+
raise KeyError(f"Sequence column '{seq1_column}' not found in adata.var")
|
|
70
|
+
if seq2_column not in adata.var:
|
|
71
|
+
raise KeyError(f"Sequence column '{seq2_column}' not found in adata.var")
|
|
72
|
+
|
|
73
|
+
output_prefix = output_prefix or f"{seq1_column}__{seq2_column}"
|
|
74
|
+
|
|
75
|
+
seq1_series = adata.var[seq1_column]
|
|
76
|
+
seq2_series = adata.var[seq2_column]
|
|
77
|
+
n_vars = adata.shape[1]
|
|
78
|
+
|
|
79
|
+
# ---- Build full sequences from positions where each ref has a valid (non-N) base ----
|
|
80
|
+
valid1_mask = seq1_series.notna() & (seq1_series != "N")
|
|
81
|
+
valid2_mask = seq2_series.notna() & (seq2_series != "N")
|
|
82
|
+
|
|
83
|
+
# var indices (integers) for each valid base
|
|
84
|
+
var_indices_1 = np.where(valid1_mask.values)[0]
|
|
85
|
+
var_indices_2 = np.where(valid2_mask.values)[0]
|
|
86
|
+
|
|
87
|
+
full_seq1 = "".join(str(seq1_series.iloc[i]) for i in var_indices_1)
|
|
88
|
+
full_seq2 = "".join(str(seq2_series.iloc[i]) for i in var_indices_2)
|
|
89
|
+
|
|
90
|
+
logger.info(
|
|
91
|
+
"Aligning full sequences: '%s' (%d bases) vs '%s' (%d bases).",
|
|
92
|
+
seq1_column,
|
|
93
|
+
len(full_seq1),
|
|
94
|
+
seq2_column,
|
|
95
|
+
len(full_seq2),
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
# ---- Global alignment ----
|
|
99
|
+
aligned_seq1, aligned_seq2, mismatches = align_sequences_with_mismatches(
|
|
100
|
+
full_seq1,
|
|
101
|
+
full_seq2,
|
|
102
|
+
match_score=match_score,
|
|
103
|
+
mismatch_score=mismatch_score,
|
|
104
|
+
gap_score=gap_score,
|
|
105
|
+
ignore_n=ignore_n,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
logger.info(
|
|
109
|
+
"Alignment complete. Aligned length: %d, mismatches: %d.",
|
|
110
|
+
len(aligned_seq1),
|
|
111
|
+
len(mismatches),
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# ---- Map alignment mismatches back to var indices ----
|
|
115
|
+
mismatch_type_arr = [""] * n_vars
|
|
116
|
+
mismatch_identity_arr = [""] * n_vars
|
|
117
|
+
is_mismatch_arr = np.zeros(n_vars, dtype=bool)
|
|
118
|
+
|
|
119
|
+
# For substitutions, store the paired var indices from both references.
|
|
120
|
+
# This is needed because indels shift the coordinate systems so that the
|
|
121
|
+
# same alignment column maps to different var indices in each reference.
|
|
122
|
+
substitution_map: list[dict] = []
|
|
123
|
+
|
|
124
|
+
for mm in mismatches:
|
|
125
|
+
# Determine which var index this mismatch maps to.
|
|
126
|
+
# For substitutions and deletions, seq1_pos is defined.
|
|
127
|
+
# For insertions, only seq2_pos is defined (gap in seq1).
|
|
128
|
+
if mm.seq1_pos is not None:
|
|
129
|
+
var_idx = int(var_indices_1[mm.seq1_pos])
|
|
130
|
+
elif mm.seq2_pos is not None:
|
|
131
|
+
var_idx = int(var_indices_2[mm.seq2_pos])
|
|
132
|
+
else:
|
|
133
|
+
continue
|
|
134
|
+
|
|
135
|
+
mismatch_type_arr[var_idx] = mm.event
|
|
136
|
+
mismatch_identity_arr[var_idx] = _format_mismatch_identity(
|
|
137
|
+
mm.event, mm.seq1_base, mm.seq2_base
|
|
138
|
+
)
|
|
139
|
+
is_mismatch_arr[var_idx] = True
|
|
140
|
+
|
|
141
|
+
if mm.event == "substitution" and mm.seq1_pos is not None and mm.seq2_pos is not None:
|
|
142
|
+
substitution_map.append(
|
|
143
|
+
{
|
|
144
|
+
"seq1_var_idx": int(var_indices_1[mm.seq1_pos]),
|
|
145
|
+
"seq2_var_idx": int(var_indices_2[mm.seq2_pos]),
|
|
146
|
+
"seq1_base": mm.seq1_base,
|
|
147
|
+
"seq2_base": mm.seq2_base,
|
|
148
|
+
}
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
adata.var[f"{output_prefix}_mismatch_type"] = pd.Series(
|
|
152
|
+
mismatch_type_arr, index=adata.var.index
|
|
153
|
+
)
|
|
154
|
+
adata.var[f"{output_prefix}_mismatch_identity"] = pd.Series(
|
|
155
|
+
mismatch_identity_arr, index=adata.var.index
|
|
156
|
+
)
|
|
157
|
+
adata.var[f"{output_prefix}_is_mismatch"] = pd.Series(is_mismatch_arr, index=adata.var.index)
|
|
158
|
+
# Store substitution map as a DataFrame in adata.uns (h5ad-serializable)
|
|
159
|
+
if substitution_map:
|
|
160
|
+
adata.uns[f"{output_prefix}_substitution_map"] = pd.DataFrame(substitution_map)
|
|
161
|
+
adata.uns[uns_flag] = True
|
|
162
|
+
|
|
163
|
+
n_sub = sum(1 for t in mismatch_type_arr if t == "substitution")
|
|
164
|
+
n_ins = sum(1 for t in mismatch_type_arr if t == "insertion")
|
|
165
|
+
n_del = sum(1 for t in mismatch_type_arr if t == "deletion")
|
|
166
|
+
logger.info(
|
|
167
|
+
"Mismatch annotations: %d substitutions, %d insertions, %d deletions.",
|
|
168
|
+
n_sub,
|
|
169
|
+
n_ins,
|
|
170
|
+
n_del,
|
|
171
|
+
)
|