-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmumdia.py
More file actions
1800 lines (1558 loc) · 61.9 KB
/
mumdia.py
File metadata and controls
1800 lines (1558 loc) · 61.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
MuMDIA: Multi-modal Data-Independent Acquisition proteomics analysis.
This module contains the core feature calculation and machine learning pipeline
for peptide-spectrum match scoring using retention time, fragment intensity,
and MS1 precursor features.
"""
import concurrent.futures
import logging
import os
import pickle
import sys
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Dict, List, Optional
# Optional Rust backend: provides ~3x faster numerical functions and GIL release
try:
import mumdia_rs
_RUST_BACKEND = True
except ImportError:
_RUST_BACKEND = False
# Optional numba: provide no-op decorator if unavailable
try:
import numba as nb
except Exception:
class _NB:
def njit(self, *args, **kwargs):
def deco(f):
return f
return deco
nb = _NB()
import numpy as np
import polars as pl
# Defer keras/scikeras imports to runtime in create_model/run_mokapot
# Optional tqdm: fallback to identity iterator if unavailable
try:
from tqdm import tqdm
except Exception:
def tqdm(iterable=None, *args, **kwargs):
return iterable if iterable is not None else []
# Optional scipy: create a lazy placeholder that errors on use
try:
from scipy import stats
except Exception:
class _Stats:
def __getattr__(self, name):
raise ImportError("scipy is required for this functionality")
stats = _Stats()
from data_structures import PickleConfig, SpectraData
from feature_generators.features_fragment_intensity import (
get_features_fragment_intensity,
)
from feature_generators.features_general import add_count_and_filter_peptides
from feature_generators.features_retention_time import add_retention_time_features
from prediction_wrappers.wrapper_deeplc import get_predictions_retention_time_mainloop
from prediction_wrappers.wrapper_ms2pip import (
get_predictions_fragment_intensity_main_loop,
)
from quantification.lfq import quantify_fragments
from utilities.logger import log_info
from utilities.plotting import plot_rt_margin_histogram, plot_XIC_with_margins
# Re-export for backward compatibility
__all__ = ["main", "PickleConfig", "SpectraData", "run_mokapot"]
# Set maximum threads for Polars to one to avoid oversubscription
os.environ["POLARS_MAX_THREADS"] = "1"
# Configure logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
#############################################
# Numba-accelerated functions
#############################################
@nb.njit
def numba_percentile(data, q):
"""
Compute the q-th percentile of a 1D array using a simple linear interpolation.
q should be given as a float between 0 and 100.
"""
n = data.shape[0]
if n == 0:
return 0.0
sorted_data = np.sort(data)
pos = (q / 100.0) * (n - 1)
lower = int(pos)
upper = lower if lower == n - 1 else lower + 1
weight = pos - lower
return sorted_data[lower] * (1.0 - weight) + sorted_data[upper] * weight
@nb.njit
def numba_percentile_sorted(sorted_data, q):
"""
Compute the q-th percentile of a 1D array using a simple linear interpolation.
q should be given as a float between 0 and 100.
"""
n = sorted_data.shape[0]
if n == 0:
return 0.0
pos = (q / 100.0) * (n - 1)
lower = int(pos)
upper = lower if lower == n - 1 else lower + 1
weight = pos - lower
return sorted_data[lower] * (1.0 - weight) + sorted_data[upper] * weight
@nb.njit
def numba_percentile_sorted_idx(sorted_data, q):
"""
Compute the q-th percentile of a 1D array using a simple linear interpolation.
q should be given as a float between 0 and 100.
"""
n = sorted_data.shape[0]
if n == 0:
return 0.0, 0
pos = (q / 100.0) * (n - 1)
lower = int(pos)
upper = lower if lower == n - 1 else lower + 1
weight = pos - lower
return sorted_data[lower] * (1.0 - weight) + sorted_data[upper] * weight, int(pos)
@nb.njit
def compute_percentiles_nb(data, qs):
"""
Compute an array of percentiles given a 1D array and an array of q values.
"""
m = qs.shape[0]
result = np.empty(m, dtype=np.float64)
data = np.sort(data)
for i in range(m):
result[i] = numba_percentile_sorted(data, qs[i])
return result
@nb.njit
def compute_percentiles_nb_idx(data, qs, idx_lookup):
"""
Compute an array of percentiles given a 1D array `data` and an array of q values `qs`,
and use the provided `idx_lookup` array to retrieve index information.
"""
m = qs.shape[0]
result = np.empty(m, dtype=np.float64)
computed_idx = np.empty(m, dtype=np.float64)
for i in range(m):
result[i], pos = numba_percentile_sorted_idx(data, qs[i])
computed_idx[i] = idx_lookup[pos]
return result, computed_idx
@nb.njit
def compute_top_nb(data, m):
"""
Sort the array in descending order and return the first m values.
If there are fewer than m elements, pad with zeros.
"""
n = data.shape[0]
sorted_data = np.sort(data)[::-1]
result = np.empty(m, dtype=np.float64)
for i in range(m):
if i < n:
result[i] = sorted_data[i]
else:
result[i] = 0.0
return result
@nb.njit
def compute_top_nb_idx(data, m, idx_ret_list):
"""
Sort the array in descending order and return the first m values.
If there are fewer than m elements, pad with zeros.
"""
n = data.shape[0]
sorted_data = np.sort(data)[::-1] # Descending sort
result = np.empty(m, dtype=np.float64)
result_idx = np.empty(m, dtype=np.float64)
for i in range(m):
if i < n:
result[i] = sorted_data[i]
# NOTE: This is a no-op (self-assignment). The idx_ret_list indices
# are not reordered to match the sorted values. This means the index
# tracking does not correspond to the actual top-k positions.
idx_ret_list[i] = idx_ret_list[i]
else:
result[i] = 0.0
idx_ret_list[i] = 0.0
return result, idx_ret_list
@nb.njit
def corr_np_nb(data1, data2):
"""
Compute the Pearson correlation coefficient between two 1D arrays.
WARNING: No zero-variance guard — will produce NaN/inf if either array
is constant. Use corr_np_nb_new() for a safe version.
"""
n = data1.shape[0]
sum1 = 0.0
sum2 = 0.0
for i in range(n):
sum1 += data1[i]
sum2 += data2[i]
mean1 = sum1 / n
mean2 = sum2 / n
cov = 0.0
var1 = 0.0
var2 = 0.0
for i in range(n):
diff1 = data1[i] - mean1
diff2 = data2[i] - mean2
cov += diff1 * diff2
var1 += diff1 * diff1
var2 += diff2 * diff2
std1 = (var1 / n) ** 0.5
std2 = (var2 / n) ** 0.5
# Division by zero if either std is 0 (constant array) — no guard here
return cov / n / (std1 * std2)
@nb.njit
def pearson_np_nb(x, y):
"""
Compute the Pearson correlation between a 2D array x and a 1D array y.
Returns a 1D array with the correlation for each column of x.
"""
m = x.shape[1]
result = np.empty(m, dtype=np.float64)
for i in range(m):
result[i] = corr_np_nb(x[:, i], y)
return result
#############################################
# End of Numba functions
#############################################
def create_model(meta=None):
"""
Create and compile a Keras model for Mokapot PSM scoring.
Args:
meta: Metadata dict from scikit-keras containing n_features_in_,
n_classes_, etc. Automatically passed by KerasClassifier at
fit time with the actual feature count from training data.
"""
try:
from keras.layers import Dense
from keras.models import Sequential
except Exception as e:
raise ImportError(
f"Keras is required to build the model for mokapot integration ({e})."
)
# Extract feature count from scikit-keras metadata, or fall back to default
n_features = meta["n_features_in_"] if meta else 69
model = Sequential()
model.add(Dense(100, input_dim=n_features, activation="relu"))
model.add(Dense(50, activation="relu"))
model.add(Dense(20, activation="relu"))
model.add(Dense(1, activation="sigmoid")) # Binary output: target vs decoy
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])
return model
def transform_bool(value: bool) -> int:
"""
Return -1 if True, otherwise 1.
"""
return -1 if value else 1
def run_mokapot(output_dir="results/") -> None:
"""
Run the mokapot analysis on PSMs read from a PIN file.
The results are saved to tab-delimited text files.
"""
try:
import mokapot
from scikeras.wrappers import KerasClassifier
except Exception as e:
log_info(
f"mokapot is not installed or failed to import ({e}). Skipping mokapot run."
)
return None
psms = mokapot.read_pin(f"{output_dir}/outfile.pin")
model = KerasClassifier(
build_fn=create_model, epochs=100, batch_size=1000, verbose=10
)
results, models = mokapot.brew(psms, mokapot.Model(model), folds=3) # psms)
result_files = results.to_txt(dest_dir=output_dir)
return result_files
def collapse_columns(
df_psms_sub_peptidoform: pl.DataFrame,
collapse_max_columns: List[str] = [],
collapse_min_columns: List[str] = [],
collapse_mean_columns: List[str] = [],
collapse_sum_columns: List[str] = [],
get_first_entry: List[str] = [],
):
"""
Collapse multiple PSM rows for one peptidoform into a single feature row.
Takes all PSMs for a peptidoform and produces one row by:
- Taking the first row's values for metadata columns (get_first_entry)
- Aggregating numeric columns via max/min/mean/sum, suffixed as e.g. "hyperscore_max"
Returns a 1-row DataFrame with all collapsed columns concatenated horizontally.
"""
# Take metadata from the first PSM row (arbitrary — these are identical per peptidoform)
collapsed_columns = [df_psms_sub_peptidoform.select(get_first_entry).head(1)]
operations = (
("max", collapse_max_columns),
("min", collapse_min_columns),
("mean", collapse_mean_columns),
("sum", collapse_sum_columns),
)
for op, collapse_list in operations:
if collapse_list:
# Apply aggregation across all rows, rename columns with suffix
collapsed_columns.append(
getattr(df_psms_sub_peptidoform[collapse_list], op)().rename(
{col: f"{col}_{op}" for col in collapse_list}
)
)
# Horizontal concat: one metadata block + one block per aggregation type
return pl.concat(collapsed_columns, how="horizontal")
def add_feature_columns_nb(data, feature_name, values, method, add_index, pad_size=10):
"""
Compute a feature vector from the input data using Numba-accelerated routines.
Returns a dictionary mapping column names to computed scalar values.
"""
# logging.info(
# f"add_feature_columns_nb: feature_name={feature_name}, method={method}, values={values}, pad_size={pad_size}"
# )
data = np.asarray(data, dtype=np.float64)
required_length = len(values)
computed_idx = np.array([], dtype=np.float64)
# logging.debug(f"Input data size: {data.size}")
if data.size == 0:
# logging.info("Input data is empty, returning zeros.")
computed = np.zeros(required_length, dtype=np.float64)
if len(add_index) > 0:
computed_idx = np.zeros(required_length, dtype=np.float64)
elif method == "percentile":
qs = np.array(values, dtype=np.float64)
# logging.info(f"Computing percentiles: qs={qs}")
if len(add_index) > 0:
computed, computed_idx = compute_percentiles_nb_idx(data, qs, add_index)
# logging.debug(
# f"Percentile results: computed={computed}, computed_idx={computed_idx}"
# )
else:
if _RUST_BACKEND:
computed = mumdia_rs.compute_percentiles(data, qs)
else:
computed = compute_percentiles_nb(data, qs)
elif method == "top":
if len(add_index) > 0:
computed, computed_idx = compute_top_nb_idx(
data, required_length, add_index
)
else:
if _RUST_BACKEND:
computed = mumdia_rs.compute_top(data, required_length)
else:
computed = compute_top_nb(data, required_length)
else:
logging.error(f"Unknown method: {method}")
raise ValueError(f"Unknown method: {method}")
# Ensure computed is of the required length
if computed.size < required_length:
# logging.info(
# f"Padded computed array from size {computed.size} to {required_length}"
# )
padded = np.zeros(required_length, dtype=np.float64)
padded[: computed.size] = computed
computed = padded
if len(add_index) > 0:
padded_idx = np.zeros(required_length, dtype=np.float64)
if computed_idx.size > 0:
padded_idx[: computed_idx.size] = computed_idx
computed_idx = padded_idx
else:
computed = computed[:required_length]
if len(add_index) > 0 and computed_idx.size > 0:
computed_idx = computed_idx[:required_length]
if len(add_index) > 0:
# logging.info(f"Returning feature dict with index columns for {feature_name}")
return {
**{f"{feature_name}_{v}": computed[i] for i, v in enumerate(values)},
**{
f"{feature_name}_{v}_idx": computed_idx[i] for i, v in enumerate(values)
},
}
else:
# logging.info(f"Returning feature dict for {feature_name}")
return {f"{feature_name}_{v}": computed[i] for i, v in enumerate(values)}
def run_peptidoform_df(
df_psms_sub_peptidoform: pl.DataFrame,
collapse_max_columns: List[str] = [
"fragment_ppm",
"rank",
"delta_next",
"delta_rt_model",
"matched_peaks",
"longest_b",
"longest_y",
"matched_intensity_pct",
"spectrum_q",
"peptide_q",
"rt_prediction_error_abs_relative",
"precursor_ppm",
"hyperscore",
# "protein_q",
"precursor_intensity_M",
"precursor_intensity_M+1",
"precursor_intensity_M-1",
],
collapse_min_columns: List[str] = [
"fragment_ppm",
"rank",
"delta_next",
"delta_rt_model",
"matched_peaks",
"longest_b",
"longest_y",
"matched_intensity_pct",
"fragment_intensity",
"poisson",
"spectrum_q",
"peptide_q",
"rt",
"rt_predictions",
"rt_prediction_error_abs",
"rt_prediction_error_abs_relative",
"precursor_ppm",
"hyperscore",
"delta_best",
# "protein_q",
"precursor_intensity_M",
"precursor_intensity_M+1",
"precursor_intensity_M-1",
],
collapse_mean_columns: List[str] = [
"spectrum_q",
"peptide_q",
# "protein_q",
"precursor_intensity_M",
"precursor_intensity_M+1",
"precursor_intensity_M-1",
],
collapse_sum_columns: List[str] = [
"precursor_intensity_M",
"precursor_intensity_M+1",
"precursor_intensity_M-1",
],
get_first_entry: List[str] = [
"psm_id",
"filename",
"scannr",
"peptide",
"num_proteins",
"proteins",
"expmass",
"calcmass",
"is_decoy",
"charge",
"peptide_len",
"missed_cleavages",
],
) -> pl.DataFrame:
"""
Collapse all PSMs for one peptidoform into a single feature row for the PIN file.
Takes a peptidoform-grouped sub-DataFrame containing multiple PSMs and:
1. Collapses numeric Sage score columns via max/min/mean/sum aggregation
2. Converts is_decoy (bool) to Label format (-1 for decoy, +1 for target)
3. Creates SpecId as "psm_id|filename|scannr" (unique peptidoform identifier)
The collapse_*_columns defaults define which Sage output columns get which
aggregation. These are hardcoded here and NOT read from the config system.
"""
df_psms_sub_peptidoform_collapsed = collapse_columns(
df_psms_sub_peptidoform,
collapse_max_columns=collapse_max_columns,
collapse_min_columns=collapse_min_columns,
collapse_mean_columns=collapse_mean_columns,
collapse_sum_columns=collapse_sum_columns,
get_first_entry=get_first_entry,
)
df_psms_sub_peptidoform_collapsed = df_psms_sub_peptidoform_collapsed.with_columns(
pl.when(pl.col("is_decoy")).then(-1).otherwise(1).alias("is_decoy")
)
df_psms_sub_peptidoform_collapsed = df_psms_sub_peptidoform_collapsed.with_columns(
pl.Series(
"SpecId",
df_psms_sub_peptidoform_collapsed["psm_id"]
+ "|"
+ df_psms_sub_peptidoform_collapsed["filename"]
+ "|"
+ df_psms_sub_peptidoform_collapsed["scannr"],
)
)
return df_psms_sub_peptidoform_collapsed
def pearson_pvalue(r, n):
"""
Compute the two-tailed p-value for a Pearson correlation coefficient
given the sample size n.
Parameters
----------
r : float
Pearson correlation coefficient.
n : int
Number of datapoints used in the correlation.
Returns
-------
float
Two-tailed p-value. Returns np.nan if n <= 2.
"""
if n <= 2:
return np.nan # Not enough datapoints for a meaningful p-value.
t_stat = r * np.sqrt((n - 2) / (1 - r**2))
p_value = 2 * stats.t.sf(np.abs(t_stat), df=n - 2)
return p_value
@nb.njit
def corr_np_nb_new(data1: np.ndarray, data2: np.ndarray) -> float:
"""
Compute Pearson correlation coefficient using Numba acceleration.
Args:
data1: First data array
data2: Second data array
Returns:
Pearson correlation coefficient
"""
n = data1.shape[0]
if n == 0:
return 0.0
# Compute means
sum1 = 0.0
sum2 = 0.0
for i in range(n):
sum1 += data1[i]
sum2 += data2[i]
mean1 = sum1 / n
mean2 = sum2 / n
# Compute correlation
cov = 0.0
var1 = 0.0
var2 = 0.0
for i in range(n):
diff1 = data1[i] - mean1
diff2 = data2[i] - mean2
cov += diff1 * diff2
var1 += diff1 * diff1
var2 += diff2 * diff2
std1 = (var1 / n) ** 0.5
std2 = (var2 / n) ** 0.5
if std1 == 0.0 or std2 == 0.0:
return 0.0
return cov / n / (std1 * std2)
@nb.njit
def corr_np_with_n_new(data1, data2):
"""
Compute Pearson correlation coefficient and return both the correlation
and the number of datapoints used.
Args:
data1: First 1D array.
data2: Second 1D array (same length as data1).
Returns:
Tuple of (correlation_coefficient, n) where n is the array length.
"""
n = data1.shape[0]
# Compute correlation as before
sum1 = 0.0
sum2 = 0.0
for i in range(n):
sum1 += data1[i]
sum2 += data2[i]
mean1 = sum1 / n
mean2 = sum2 / n
cov = 0.0
var1 = 0.0
var2 = 0.0
for i in range(n):
diff1 = data1[i] - mean1
diff2 = data2[i] - mean2
cov += diff1 * diff2
var1 += diff1 * diff1
var2 += diff2 * diff2
std1 = (var1 / n) ** 0.5
std2 = (var2 / n) ** 0.5
# Return both the correlation and the count of datapoints
return cov / n / (std1 * std2), n
def run_peptidoform_correlation(
correlations_list,
collect_distributions: List[int] = [
0,
25,
50,
75,
100,
], # [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
collect_top: List[int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], # [1, 2, 3, 4, 5],
pad_size=10,
):
"""
Compute correlation-based features and return a one-row Polars DataFrame.
"""
(
correlations,
correlation_result_counts,
sum_pred_frag_intens,
correlation_matrix_psm_ids,
correlation_matrix_frag_ids,
most_intens_cor,
most_intens_cos,
mse_avg_pred_intens,
mse_avg_pred_intens_total,
) = correlations_list
# Fast path: single Rust call replaces 10 Python→Rust round trips
if _RUST_BACKEND:
feature_dict = mumdia_rs.batch_correlation_features(
np.asarray(correlations, dtype=np.float64),
np.asarray(correlation_result_counts, dtype=np.float64),
np.asarray(correlation_matrix_psm_ids, dtype=np.float64),
np.asarray(correlation_matrix_frag_ids, dtype=np.float64),
float(most_intens_cor),
float(most_intens_cos),
float(mse_avg_pred_intens),
float(mse_avg_pred_intens_total),
[float(x) for x in collect_distributions],
[int(x) for x in collect_top],
pad_size,
)
return pl.DataFrame(feature_dict)
# Fallback: Python path with 10 separate calls
feature_dict = {}
params = [
(
correlation_matrix_psm_ids,
"distribution_correlation_matrix_psm_ids",
collect_distributions,
"percentile",
len(collect_distributions),
[],
),
(
correlation_matrix_frag_ids,
"distribution_correlation_matrix_frag_ids",
collect_distributions,
"percentile",
len(collect_distributions),
[],
),
(
correlations,
"distribution_correlation_individual",
collect_distributions,
"percentile",
len(collect_distributions),
correlation_result_counts,
),
(
correlation_matrix_psm_ids,
"top_correlation_matrix_psm_ids",
collect_top,
"top",
pad_size,
[],
),
(
correlation_matrix_frag_ids,
"top_correlation_matrix_frag_ids",
collect_top,
"top",
pad_size,
[],
),
([most_intens_cos], "top_correlation_cos", [1], "top", pad_size, []),
# BUG: Same feature name "top_correlation_cos" as above — Pearson overwrites cosine.
# Should likely be "top_correlation_pearson" or "top_correlation_cor".
([most_intens_cor], "top_correlation_cos", [1], "top", pad_size, []),
([mse_avg_pred_intens], "mse_avg_pred_intens", [1], "top", pad_size, []),
(
[mse_avg_pred_intens_total],
"mse_avg_pred_intens_total",
[1],
"top",
pad_size,
[],
),
(correlations, "top_correlation_individual", collect_top, "top", pad_size, []),
]
for data, feat_name, values, method, ps, add_index in params:
feature_dict.update(
add_feature_columns_nb(
data, feat_name, values, method, add_index, pad_size=ps
)
)
df = pl.DataFrame(feature_dict)
return df
_diann_generator = None
def _get_diann_generator():
"""Return a shared DIANNFeatureGenerator, creating it once on first call."""
global _diann_generator
if _diann_generator is None:
from feature_generators.diann_feature_generator import (
DIANNFeatureGenerator,
FeatureConfig,
)
_diann_generator = DIANNFeatureGenerator(FeatureConfig(n_jobs=1))
return _diann_generator
def _prepare_diann_ms1(spectra_data):
"""Pre-convert ms1_dict to sorted numpy arrays for the DIA-NN generator."""
gen = _get_diann_generator()
if gen._ms1_prepared is None and spectra_data and spectra_data.ms1_dict:
gen.prepare_ms1_dict(spectra_data.ms1_dict)
def run_peptidoform_diann(df_psms_sub, df_fragment_sub, spectra_data, ms2pip_preds):
"""
Compute DIA-NN-style features for one peptidoform.
Returns a 1-row Polars DataFrame with diann_* prefixed feature columns.
Uses Rust implementation when available (mumdia_rs.compute_diann_features),
falling back to the Python DIANNFeatureGenerator.
"""
import re
# === Fast path: Rust DIA-NN features ===
if _RUST_BACKEND and "fragment_name" in df_fragment_sub.columns:
try:
# Extract precursor info from first PSM row
first_row = df_psms_sub.row(0, named=True)
peptide = first_row.get("peptide", "")
calcmass = float(first_row.get("calcmass", 0.0))
charge = int(first_row.get("charge", 2))
precursor_mz = calcmass / charge + 1.007276466812
peptide_length = len(re.sub(r"\[.*?\]", "", peptide))
# Build fragment name → index mapping
frag_name_col = df_fragment_sub["fragment_name"]
unique_names = frag_name_col.unique().sort().to_list()
name_to_idx = {name: i for i, name in enumerate(unique_names)}
# Extract parallel arrays for Rust
rts = df_fragment_sub["rt"].to_numpy().astype(np.float64)
frag_ids = np.array(
[name_to_idx[n] for n in frag_name_col.to_list()], dtype=np.uint32
)
intensities = (
df_fragment_sub["fragment_intensity"].to_numpy().astype(np.float64)
)
features = mumdia_rs.compute_diann_features(
rts,
frag_ids,
intensities,
unique_names,
precursor_mz,
charge,
peptide_length,
na_strategy=_diann_na_strategy,
)
# Replace NaN with 0.0
features = {k: (0.0 if v != v else v) for k, v in features.items()}
return pl.DataFrame(features)
except Exception:
pass # Fall through to Python path
# === Python fallback: DIANNFeatureGenerator ===
generator = _get_diann_generator()
precursor_pd = df_psms_sub.head(1).to_pandas()
fragments_pd = df_fragment_sub.to_pandas()
if (
"fragment_name" in fragments_pd.columns
and "fragment_names" not in fragments_pd.columns
):
fragments_pd = fragments_pd.rename(columns={"fragment_name": "fragment_names"})
if (
"fragment_ppm" in fragments_pd.columns
and "ppm_error" not in fragments_pd.columns
):
fragments_pd["ppm_error"] = fragments_pd["fragment_ppm"]
if (
"stripped_peptide" not in precursor_pd.columns
and "peptide" in precursor_pd.columns
):
precursor_pd["stripped_peptide"] = precursor_pd["peptide"].apply(
lambda p: re.sub(r"\[.*?\]", "", p)
)
use_ms1 = (
generator.config.enable_ms1_features and spectra_data and spectra_data.ms1_dict
)
try:
features = generator.calculate_all_features(
precursor=precursor_pd,
fragments=fragments_pd,
ms1_dict=spectra_data.ms1_dict if use_ms1 else None,
ms2dict=spectra_data.ms2_dict if spectra_data else None,
intensity_predictions=ms2pip_preds,
parallel=False,
)
except Exception:
return pl.DataFrame({"diann_failed": [1.0]})
flat = {}
for name, value in features.items():
if isinstance(value, np.ndarray):
for i, v in enumerate(value):
try:
flat[f"diann_{name}_{i}"] = (
float(v) if not np.isnan(float(v)) else 0.0
)
except (ValueError, TypeError):
flat[f"diann_{name}_{i}"] = 0.0
else:
try:
flat[f"diann_{name}"] = (
float(value) if not np.isnan(float(value)) else 0.0
)
except (ValueError, TypeError):
flat[f"diann_{name}"] = 0.0
generator.clear_cache()
return pl.DataFrame(flat)
def _run_diann_packed(packed_args):
"""Unpack args and run DIA-NN features. Module-level for ProcessPoolExecutor pickling."""
return run_peptidoform_diann(*packed_args)
_use_diann_features = True # Set from config in calculate_features()
_diann_na_strategy = "overlap_only" # "overlap_only" or "fill_zero"
def process_peptidoform(args):
"""
Process a single peptidoform group by computing its feature DataFrames and concatenating them.
Computes: collapsed PSM features, correlation features, and optionally DIA-NN features.
"""
(
df_psms_sub_peptidoform,
df_fragment_sub_peptidoform,
correlations_list,
spectra_data,
ms2pip_preds,
) = args
df1 = run_peptidoform_df(df_psms_sub_peptidoform)
df2 = run_peptidoform_correlation(correlations_list)
if _use_diann_features:
df3 = run_peptidoform_diann(
df_psms_sub_peptidoform,
df_fragment_sub_peptidoform,
spectra_data,
ms2pip_preds,
)
return pl.concat([df1, df2, df3], how="horizontal")
return pl.concat([df1, df2], how="horizontal")
# TODO move to feature generators
def find_mz_indices(spectrum, target_mz, ppm_tolerance=20):
"""
Find indices in the sorted m/z array that are within a specified ppm tolerance of a target m/z value.
Parameters
----------
spectrum : dict
Dictionary containing the spectrum data with keys 'mz', 'intensity', etc.
target_mz : float
The target m/z value to search for.
ppm_tolerance : float, optional
The tolerance in parts-per-million (default is 20 ppm).
Returns
-------
indices : numpy.ndarray
Array of indices in spectrum['mz'] that lie within the specified tolerance.
"""
# Calculate the absolute tolerance
tol = target_mz * ppm_tolerance * 1e-6
# Define the lower and upper bounds of the m/z window
lower_bound = target_mz - tol
upper_bound = target_mz + tol
# Use np.searchsorted to determine the range of indices
mz_array = spectrum["mz"]
lower_index = np.searchsorted(mz_array, lower_bound, side="left")
upper_index = np.searchsorted(mz_array, upper_bound, side="right")
# Return all indices within the window
return np.arange(lower_index, upper_index)
def find_all_three_isotopic_peaks(
spectrum,
target_mz,
charge,
ppm_tolerance=20,
isotope_mass_diff=1.0033548378,
return_intensity=False,
):
"""
Find indices for the target m/z value and its two neighboring isotopic peaks:
M–1, M, and M+1. If return_intensity is True, return the intensity value (max intensity)
corresponding to each peak instead of the indices.
Parameters
----------
spectrum : dict
Dictionary containing the spectrum data with key 'mz' (a sorted NumPy array)
and 'intensity' (a NumPy array of intensities).
target_mz : float
The target m/z value (typically corresponding to the monoisotopic peak).
charge : int
The charge state of the peptide.
ppm_tolerance : float, optional
Tolerance in parts-per-million for matching (default is 20 ppm).
isotope_mass_diff : float, optional
The nominal mass difference between isotopes (default is 1.0033548378 Da).
return_intensity : bool, optional
If True, returns the intensity value (maximum intensity among the matching peaks)
instead of the indices.
Returns
-------
dict
A dictionary with keys 'M-1', 'M', and 'M+1'. Depending on return_intensity,
each key maps either to a NumPy array of indices or to a single intensity value.
"""
# Calculate the spacing for the given charge.