-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdiann2mztab.py
More file actions
1666 lines (1474 loc) · 59.8 KB
/
diann2mztab.py
File metadata and controls
1666 lines (1474 loc) · 59.8 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
"""
This script converts the output from DIA-NN into three standard formats: MSstats, Triqler and mzTab.
License: Apache 2.0
Authors: Hong Wong, Yasset Perez-Riverol
Revisions:
2023-Aug-05: J. Sebastian Paez
"""
import logging
import os
import re
import warnings
from pathlib import Path
from typing import Any, Dict, List, Set, Tuple, Union
import click
import numpy as np
import pandas as pd
from pyopenms import AASequence, FASTAFile, ModificationsDB
from pyopenms.Constants import PROTON_MASS_U
from quantmsutils.utils.constants import MS_LEVEL, RETENTION_TIME, SCAN, EXPERIMENTAL_MASS_TO_CHARGE
pd.set_option("display.max_rows", 500)
pd.set_option("display.max_columns", 500)
pd.set_option("display.width", 1000)
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
REVISION = "0.1.1"
logging.basicConfig(
format="%(asctime)s [%(funcName)s] - %(message)s", level=logging.DEBUG
)
logger = logging.getLogger(__name__)
@click.command(
"diann2mztab", short_help="Convert DIA-NN output to MSstats, Triqler or mzTab"
)
@click.option("--folder", "-f")
@click.option("--exp_design", "-d")
@click.option("--diann_version", "-v")
@click.option("--dia_params", "-p")
@click.option("--charge", "-c")
@click.option("--missed_cleavages", "-m")
@click.option("--qvalue_threshold", "-q", type=float)
@click.pass_context
def diann2mztab(
ctx,
folder,
exp_design,
dia_params,
diann_version,
charge,
missed_cleavages,
qvalue_threshold,
):
"""
Convert DIA-NN output to MSstats, Triqler or mzTab.
The output formats are used for quality control and downstream analysis.
:param ctx: Click context
:param folder: DiannConvert specifies the folder where the required file resides. The folder contains
the DiaNN main report, protein matrix, precursor matrix, experimental design file, protein sequence
FASTA file, version file of DiaNN and ms_info parquet
:param exp_design: Experimental design file
:param dia_params: A list contains DIA parameters
:type dia_params: list
:param diann_version: Path to a version file of DIA-NN
:type diann_version: str
:param charge: The charge assigned by DIA-NN(max_precursor_charge)
:type charge: int
:param missed_cleavages: Allowed missed cleavages assigned by DIA-NN
:type missed_cleavages: int
:param qvalue_threshold: Threshold for filtering q value
:type qvalue_threshold: float
"""
logger.debug(f"Revision {REVISION}")
logger.debug("Reading input files...")
diann_directory = DiannDirectory(folder, diann_version_file=diann_version)
report = diann_directory.main_report_df(qvalue_threshold=qvalue_threshold)
s_data_frame, f_table = get_exp_design_dfs(exp_design)
# Convert to MSstats
msstats_columns_keep = [
"Protein.Names",
"Modified.Sequence",
"Precursor.Charge",
"Precursor.Quantity",
"File.Name",
"Run",
]
logger.debug("Converting to MSstats format...")
out_msstats = report[msstats_columns_keep]
out_msstats.columns = [
"ProteinName",
"PeptideSequence",
"PrecursorCharge",
"Intensity",
"Reference",
"Run",
]
out_msstats = out_msstats[out_msstats["Intensity"] != 0]
# Q: What is this line doing?
out_msstats.loc[:, "PeptideSequence"] = out_msstats.apply(
lambda x: AASequence.fromString(x["PeptideSequence"]).toString(), axis=1
)
out_msstats["FragmentIon"] = "NA"
out_msstats["ProductCharge"] = "0"
out_msstats["IsotopeLabelType"] = "L"
unique_reference_map = {
k: os.path.basename(k) for k in out_msstats["Reference"].unique()
}
out_msstats["Reference"] = out_msstats["Reference"].map(unique_reference_map)
del unique_reference_map
logger.debug("\n\nReference Column >>>")
logger.debug(out_msstats["Reference"])
logger.debug(f"\n\nout_msstats ({out_msstats.shape}) >>>")
logger.debug(out_msstats.head(5))
logger.debug(f"\n\nf_table ({f_table.shape})>>>")
logger.debug(f_table.head(5))
logger.debug(f"\n\ns_DataFrame ({s_data_frame.shape})>>>")
logger.debug(s_data_frame.head(5))
logger.debug("Adding Fraction, BioReplicate, Condition columns")
# Changing implementation from apply to merge went from several minutes to
# ~50ms
out_msstats = out_msstats.merge(
(
s_data_frame[["Sample", "MSstats_Condition", "MSstats_BioReplicate"]]
.merge(f_table[["Fraction", "Sample", "run"]], on="Sample")
.rename(
columns={
"run": "Run",
"MSstats_BioReplicate": "BioReplicate",
"MSstats_Condition": "Condition",
}
)
.drop(columns=["Sample"])
),
on="Run",
validate="many_to_one",
)
exp_out_prefix = Path(exp_design).stem
out_msstats.to_csv(exp_out_prefix + "_msstats_in.csv", sep=",", index=False)
logger.info(f"MSstats input file is saved as {exp_out_prefix}_msstats_in.csv")
# Convert to Triqler
triqler_cols = [
"ProteinName",
"PeptideSequence",
"PrecursorCharge",
"Intensity",
"Run",
"Condition",
]
out_triqler = out_msstats[triqler_cols]
del out_msstats
out_triqler.columns = [
"proteins",
"peptide",
"charge",
"intensity",
"run",
"condition",
]
out_triqler = out_triqler[out_triqler["intensity"] != 0]
out_triqler.loc[:, "searchScore"] = report["Q.Value"]
out_triqler.loc[:, "searchScore"] = 1 - out_triqler["searchScore"]
out_triqler.to_csv(exp_out_prefix + "_triqler_in.tsv", sep="\t", index=False)
logger.info(f"Triqler input file is saved as {exp_out_prefix}_triqler_in.tsv")
del out_triqler
mztab_out = f"{Path(exp_design).stem}_out.mzTab"
# Convert to mzTab
diann_directory.convert_to_mztab(
report=report,
f_table=f_table,
charge=charge,
missed_cleavages=missed_cleavages,
dia_params=dia_params,
out=mztab_out,
)
def _true_stem(x):
"""
Return the true stem of a file name, i.e. the
file name without the extension.
:param x: The file name
:type x: str
:return: The true stem of the file name
:rtype: str
Examples:
>>> _true_stem("foo.mzML")
'foo'
>>> _true_stem("foo.d.tar")
'foo'
These examples can be tested with pytest:
$ pytest -v --doctest-modules
"""
split = os.path.basename(x).split(".")
stem = split[0]
# Should I check here that the extensions are
# allowed? I can see how this would break if the
# file name contains a period.
return stem
def get_exp_design_dfs(exp_design_file):
logger.info(f"Reading experimental design file: {exp_design_file}")
with open(exp_design_file, "r") as f:
data = f.readlines()
empty_row = data.index("\n")
f_table = [i.replace("\n", "").split("\t") for i in data[1:empty_row]]
f_header = data[0].replace("\n", "").split("\t")
f_table = pd.DataFrame(f_table, columns=f_header)
f_table.loc[:, "run"] = f_table.apply(
lambda x: _true_stem(x["Spectra_Filepath"]), axis=1
)
s_table = [i.replace("\n", "").split("\t") for i in data[empty_row + 1:]][1:]
s_header = data[empty_row + 1].replace("\n", "").split("\t")
s_data_frame = pd.DataFrame(s_table, columns=s_header)
return s_data_frame, f_table
def compute_mass_modified_peptide(peptide_seq: str) -> float:
"""
Function that takes a peptide sequence including modifications and compute the mass using the AASequence class from
pyopenms. The notation of a peptidoform for pyopenms is the following:
if not modifications is present:
AVQVHQDTLRTMYFAXR -> AVQVHQDTLRTMYFAX[178.995499]R
if modification is present in Methionine:
AVQVHQDTLRTM(Oxidation)YFAXR -> AVQVHQDTLRTM(Oxidation)YFAX[178.995499]R
@param peptide_seq: str, peptide sequence
@return: float, mass of the peptide
"""
peptide_parts: List[str] = []
not_mod = True
aa_mass = {
"X": "X[178.98493453312]", # 196.995499 - 17.003288 - 1.00727646688
"U": "X[132.94306553312]", # 150.95363 - 17.003288 - 1.00727646688
"O": "X[237.14773053312]", # 255.158295 - 17.003288 - 1.00727646688
}
for aa in peptide_seq:
# Check if the letter is in aminoacid
if aa == "(":
not_mod = False
elif aa == ")":
not_mod = True
# Check aminoacid letter
if aa in aa_mass and not_mod:
aa = aa_mass[aa]
elif (
aa
not in [
"G",
"A",
"V",
"L",
"I",
"F",
"M",
"P",
"W",
"S",
"C",
"T",
"Y",
"N",
"Q",
"D",
"E",
"K",
"R",
"H",
]
and not_mod
and aa != ")"
):
logger.info(f"Unknown amino acid with mass not known:{aa}")
peptide_parts.append(aa)
new_peptide_seq = "".join(peptide_parts)
mass = AASequence.fromString(new_peptide_seq).getMonoWeight()
logger.debug(new_peptide_seq + ":" + str(mass))
return mass
class DiannDirectory:
def __init__(self, base_path, diann_version_file):
self.base_path = Path(base_path)
if not self.base_path.exists() and not self.base_path.is_dir():
raise NotADirectoryError(f"Path {self.base_path} does not exist")
self.diann_version_file = Path(diann_version_file)
if not self.diann_version_file.is_file():
raise FileNotFoundError(f"Path {self.diann_version_file} does not exist")
def find_first_file_with_suffix(self, suffix: str) -> os.PathLike:
"""Finds a file with a given suffix in the directory.
:param suffix: The suffix to search for
:type suffix: str
:raises FileNotFoundError: If no file with the given suffix is found
"""
try:
return next(self.base_path.glob(f"**/*{suffix}"))
except StopIteration:
raise FileNotFoundError(f"Could not find file with suffix {suffix}")
@property
def report(self) -> os.PathLike:
return self.find_first_file_with_suffix("report.tsv")
@property
def pg_matrix(self) -> os.PathLike:
return self.find_first_file_with_suffix("pg_matrix.tsv")
@property
def pr_matrix(self) -> os.PathLike:
return self.find_first_file_with_suffix("pr_matrix.tsv")
@property
def fasta(self) -> os.PathLike:
try:
return self.find_first_file_with_suffix(".fasta")
except FileNotFoundError:
return self.find_first_file_with_suffix(".fa")
@property
def ms_info(self) -> os.PathLike:
return self.find_first_file_with_suffix("ms_info.parquet")
@property
def diann_version(self) -> str:
logger.debug("Validating DIANN version")
diann_version_id = None
with open(self.diann_version_file) as f:
for line in f:
if "DIA-NN" in line:
logger.debug(f"Found DIA-NN version: {line}")
diann_version_id = line.rstrip("\n").split(": ")[1]
if diann_version_id is None:
raise ValueError(
f"Could not find DIA-NN version in file {self.diann_version_file}"
)
return diann_version_id
def validate_diann_version(self) -> None:
supported_diann_versions = ["1.8.1", "1.9.beta.1", "1.9.2"]
if self.diann_version not in supported_diann_versions:
raise ValueError(f"Unsupported DIANN version {self.diann_version}")
def convert_to_mztab(
self,
report,
f_table,
charge: int,
missed_cleavages: int,
dia_params: List[Any],
out: Union[os.PathLike, str],
) -> None:
logger.info("Converting to mzTab")
self.validate_diann_version()
# This could be a branching point if we want to support other versions
# of DIA-NN, maybe something like this:
# if diann_version_id == "1.8.1":
# self.convert_to_mztab_1_8_1(report, f_table, charge, missed_cleavages, dia_params)
# else:
# raise ValueError(f"Unsupported DIANN version {diann_version_id}, supported versions are 1.8.1 ...")
logger.info(f"Reading fasta file: {self.fasta}")
entries: list = []
f = FASTAFile()
f.load(str(self.fasta), entries)
fasta_entries = [(e.identifier, e.sequence, len(e.sequence)) for e in entries]
fasta_df = pd.DataFrame(fasta_entries, columns=["id", "seq", "len"])
logger.info("Mapping run information to report")
index_ref = f_table.copy()
index_ref.rename(
columns={
"Fraction_Group": "ms_run",
"Sample": "study_variable",
"run": "Run",
},
inplace=True,
)
index_ref["ms_run"] = index_ref["ms_run"].astype("int")
index_ref["study_variable"] = index_ref["study_variable"].astype("int")
report = report.merge(
index_ref[["ms_run", "Run", "study_variable"]],
on="Run",
validate="many_to_one",
)
mtd, database = mztab_mtd(
index_ref, dia_params, str(self.fasta), charge, missed_cleavages, self.diann_version
)
pg = pd.read_csv(
self.pg_matrix,
sep="\t",
header=0,
)
prh = mztab_prh(report, pg, index_ref, database, fasta_df)
del pg
pr = pd.read_csv(
self.pr_matrix,
sep="\t",
header=0,
)
precursor_list = list(report["Precursor.Id"].unique())
peh = mztab_peh(report, pr, precursor_list, index_ref, database)
del pr
psh = mztab_psh(report, str(self.base_path), database)
del report
mtd.loc["", :] = ""
prh.loc[len(prh) + 1, :] = ""
peh.loc[len(peh) + 1, :] = ""
with open(out, "w", newline="") as f:
mtd.to_csv(f, mode="w", sep="\t", index=False, header=False)
prh.to_csv(f, mode="w", sep="\t", index=False, header=True)
peh.to_csv(f, mode="w", sep="\t", index=False, header=True)
psh.to_csv(f, mode="w", sep="\t", index=False, header=True)
logger.info(f"mzTab file generated successfully! at {out}_out.mzTab")
def main_report_df(self, qvalue_threshold: float) -> pd.DataFrame:
remain_cols = [
"File.Name",
"Run",
"Protein.Group",
"Protein.Names",
"Protein.Ids",
"First.Protein.Description",
"PG.MaxLFQ",
"RT",
"MS2.Scan",
"Global.Q.Value",
"Lib.Q.Value",
"PEP",
"Precursor.Normalised",
"Precursor.Id",
"Q.Value",
"Modified.Sequence",
"Stripped.Sequence",
"Precursor.Charge",
"Precursor.Quantity",
"Global.PG.Q.Value",
"MS2.Scan"
]
report = pd.read_csv(self.report, sep="\t", header=0, usecols=remain_cols)
# filter based on qvalue parameter for downstream analysiss
logger.debug(
f"Filtering report based on qvalue threshold: {qvalue_threshold}, {len(report)} rows"
)
report = report[report["Q.Value"] < qvalue_threshold]
logger.debug(f"Report filtered, {len(report)} rows remaining")
logger.debug("Calculating Precursor.Mz")
# Making the map is 10x faster, and includes the mass of
# the modification. with respect to the previous implementation.
uniq_masses = {
k: compute_mass_modified_peptide(k)
for k in report["Modified.Sequence"].unique()
}
mass_vector = report["Modified.Sequence"].map(uniq_masses)
report["Calculate.Precursor.Mz"] = (
mass_vector + (PROTON_MASS_U * report["Precursor.Charge"])
) / report["Precursor.Charge"]
logger.debug("Indexing Precursors")
# Making the map is 1500x faster
precursor_index_map = {
k: i for i, k in enumerate(report["Precursor.Id"].unique())
}
report["precursor.Index"] = report["Precursor.Id"].map(precursor_index_map)
logger.debug(f"Shape of main report {report.shape}")
logger.debug(str(report.head()))
return report
def mtd_mod_info(fix_mod, var_mod):
"""
Convert fixed and variable modifications to the format required by the MTD sub-table.
:param fix_mod: Fixed modifications from DIA parameter list
:type fix_mod: str
:param var_mod: Variable modifications from DIA parameter list
:type var_mod: str
:return: A tuple contains fixed and variable modifications, and flags indicating whether they are null
:rtype: tuple
"""
var_ptm = []
fix_ptm = []
mods_db = ModificationsDB()
if fix_mod != "null":
fix_flag = 1
for mod in fix_mod.split(","):
mod_obj = mods_db.getModification(mod)
mod_name = mod_obj.getId()
mod_accession = mod_obj.getUniModAccession()
site = mod_obj.getOrigin()
fix_ptm.append(
("[UNIMOD, " + mod_accession.upper() + ", " + mod_name + ", ]", site)
)
else:
fix_flag = 0
fix_ptm.append("[MS, MS:1002453, No fixed modifications searched, ]")
if var_mod != "null":
var_flag = 1
for mod in var_mod.split(","):
mod_obj = mods_db.getModification(mod)
mod_name = mod_obj.getId()
mod_accession = mod_obj.getUniModAccession()
site = mod_obj.getOrigin()
var_ptm.append(
("[UNIMOD, " + mod_accession.upper() + ", " + mod_name + ", ]", site)
)
else:
var_flag = 0
var_ptm.append("[MS, MS:1002454, No variable modifications searched, ]")
return fix_ptm, var_ptm, fix_flag, var_flag
def mztab_mtd(index_ref, dia_params, fasta, charge, missed_cleavages, diann_version):
"""
Construct MTD sub-table.
:param index_ref: On the basis of f_table, two columns "MS_run" and "study_variable" are added for matching
:type index_ref: pandas.core.frame.DataFrame
:param dia_params: A list contains DIA parameters
:type dia_params: list
:param fasta: Fasta file path
:type fasta: str
:param charge: Charges set by Dia-NN
:type charge: int
:param missed_cleavages: Missed cleavages set by Dia-NN
:type missed_cleavages: int
:return: MTD sub-table
:rtype: pandas.core.frame.DataFrame
"""
logger.info("Constructing MTD sub-table...")
dia_params_list = dia_params.split(";")
dia_params_list = ["null" if i == "" else i for i in dia_params_list]
fragment_mass_tolerance = dia_params_list[0]
fragment_mass_tolerance_unit = dia_params_list[1]
precursor_mass_tolerance = dia_params_list[2]
precursor_mass_tolerance_unit = dia_params_list[3]
enzyme = dia_params_list[4]
fixed_modifications = dia_params_list[5]
variable_modifications = dia_params_list[6]
out_mztab_mtd = pd.DataFrame()
out_mztab_mtd.loc[1, "mzTab-version"] = "1.0.0"
out_mztab_mtd.loc[1, "mzTab-mode"] = "Summary"
out_mztab_mtd.loc[1, "mzTab-type"] = "Quantification"
out_mztab_mtd.loc[1, "title"] = "ConsensusMap export from OpenMS"
out_mztab_mtd.loc[1, "description"] = "OpenMS export from consensusXML"
out_mztab_mtd.loc[1, "protein_search_engine_score[1]"] = (
"[, , DIA-NN Global.PG.Q.Value, ]"
)
out_mztab_mtd.loc[1, "peptide_search_engine_score[1]"] = (
"[, , DIA-NN Q.Value (minimum of the respective precursor q-values), ]"
)
out_mztab_mtd.loc[1, "psm_search_engine_score[1]"] = (
"[MS, MS:MS:1001869, protein-level q-value, ]"
)
out_mztab_mtd.loc[1, "software[1]"] = "[MS, MS:1003253, DIA-NN, {}]".format(diann_version)
out_mztab_mtd.loc[1, "software[1]-setting[1]"] = fasta
out_mztab_mtd.loc[1, "software[1]-setting[2]"] = "db_version:null"
out_mztab_mtd.loc[1, "software[1]-setting[3]"] = (
"fragment_mass_tolerance:" + fragment_mass_tolerance
)
out_mztab_mtd.loc[1, "software[1]-setting[4]"] = (
"fragment_mass_tolerance_unit:" + fragment_mass_tolerance_unit
)
out_mztab_mtd.loc[1, "software[1]-setting[5]"] = (
"precursor_mass_tolerance:" + precursor_mass_tolerance
)
out_mztab_mtd.loc[1, "software[1]-setting[6]"] = (
"precursor_mass_tolerance_unit:" + precursor_mass_tolerance_unit
)
out_mztab_mtd.loc[1, "software[1]-setting[7]"] = "enzyme:" + enzyme
out_mztab_mtd.loc[1, "software[1]-setting[8]"] = "enzyme_term_specificity:full"
out_mztab_mtd.loc[1, "software[1]-setting[9]"] = "charges:" + str(charge)
out_mztab_mtd.loc[1, "software[1]-setting[10]"] = "missed_cleavages:" + str(
missed_cleavages
)
out_mztab_mtd.loc[1, "software[1]-setting[11]"] = (
"fixed_modifications:" + fixed_modifications
)
out_mztab_mtd.loc[1, "software[1]-setting[12]"] = (
"variable_modifications:" + variable_modifications
)
(fixed_mods, variable_mods, fix_flag, var_flag) = mtd_mod_info(
fixed_modifications, variable_modifications
)
if fix_flag == 1:
for i in range(1, len(fixed_mods) + 1):
out_mztab_mtd.loc[1, "fixed_mod[" + str(i) + "]"] = fixed_mods[i - 1][0]
out_mztab_mtd.loc[1, "fixed_mod[" + str(i) + "]-site"] = fixed_mods[i - 1][
1
]
out_mztab_mtd.loc[1, "fixed_mod[" + str(i) + "]-position"] = "Anywhere"
else:
out_mztab_mtd.loc[1, "fixed_mod[1]"] = fixed_mods[0]
if var_flag == 1:
for i in range(1, len(variable_mods) + 1):
out_mztab_mtd.loc[1, "variable_mod[" + str(i) + "]"] = variable_mods[i - 1][
0
]
out_mztab_mtd.loc[1, "variable_mod[" + str(i) + "]-site"] = variable_mods[
i - 1
][1]
out_mztab_mtd.loc[1, "variable_mod[" + str(i) + "]-position"] = "Anywhere"
else:
out_mztab_mtd.loc[1, "variable_mod[1]"] = variable_mods[0]
out_mztab_mtd.loc[1, "quantification_method"] = (
"[MS, MS:1001834, LC-MS label-free quantitation analysis, ]"
)
out_mztab_mtd.loc[1, "protein-quantification_unit"] = "[, , Abundance, ]"
out_mztab_mtd.loc[1, "peptide-quantification_unit"] = "[, , Abundance, ]"
for i in range(1, max(index_ref["ms_run"]) + 1):
out_mztab_mtd.loc[1, "ms_run[" + str(i) + "]-format"] = (
"[MS, MS:1000584, mzML file, ]"
)
out_mztab_mtd.loc[1, "ms_run[" + str(i) + "]-location"] = (
"file://"
+ index_ref[index_ref["ms_run"] == i]["Spectra_Filepath"].values[0]
)
out_mztab_mtd.loc[1, "ms_run[" + str(i) + "]-id_format"] = (
"[MS, MS:1000777, spectrum identifier nativeID format, ]"
)
out_mztab_mtd.loc[1, "assay[" + str(i) + "]-quantification_reagent"] = (
"[MS, MS:1002038, unlabeled sample, ]"
)
out_mztab_mtd.loc[1, "assay[" + str(i) + "]-ms_run_ref"] = (
"ms_run[" + str(i) + "]"
)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# This is used here in order to ignore performance warnings from pandas.
for i in range(1, max(index_ref["study_variable"]) + 1):
study_variable = []
for j in list(index_ref[index_ref["study_variable"] == i]["ms_run"].values):
study_variable.append("assay[" + str(j) + "]")
out_mztab_mtd.loc[1, "study_variable[" + str(i) + "]-assay_refs"] = (
",".join(study_variable)
)
out_mztab_mtd.loc[1, "study_variable[" + str(i) + "]-description"] = (
"no description given"
)
# The former loop makes a very sharded frame, this
# makes the frame more compact in memory.
out_mztab_mtd = out_mztab_mtd.copy()
out_mztab_mtd.loc[2, :] = "MTD"
# Transpose out_mztab_MTD
col = list(out_mztab_mtd.columns)
row = list(out_mztab_mtd.index)
out_mztab_mtd_t = pd.DataFrame(out_mztab_mtd.values.T, index=col, columns=row)
out_mztab_mtd_t.columns = ["inf", "index"]
out_mztab_mtd_t.insert(0, "title", out_mztab_mtd_t.index)
index = out_mztab_mtd_t.loc[:, "index"]
out_mztab_mtd_t.drop(labels=["index"], axis=1, inplace=True)
out_mztab_mtd_t.insert(0, "index", index)
database = os.path.basename(fasta.split(".")[-2])
return out_mztab_mtd_t, database
def mztab_prh(report, pg, index_ref, database, fasta_df):
"""
Construct PRH sub-table.
:param report: Dataframe for Dia-NN main report
:type report: pandas.core.frame.DataFrame
:param pg: Dataframe for Dia-NN protein groups matrix
:type pg: pandas.core.frame.DataFrame
:param index_ref: On the basis of f_table, two columns "ms_run" and "study_variable" are added for matching
:type index_ref: pandas.core.frame.DataFrame
:param database: Path to fasta file
:type database: str
:param fasta_df: A dataframe contains protein IDs, sequences and lengths
:type fasta_df: pandas.core.frame.DataFrame
:return: PRH sub-table
:rtype: pandas.core.frame.DataFrame
"""
logger.info("Constructing PRH sub-table...")
logger.debug(
f"Input report shape: {report.shape},"
f" input pg shape: {pg.shape},"
f" input index_ref shape: {index_ref.shape},"
f" input fasta_df shape: {fasta_df.shape}"
)
file = list(pg.columns[5:])
col = {}
for i in file:
col[i] = (
"protein_abundance_assay["
+ str(index_ref[index_ref["Run"] == _true_stem(i)]["ms_run"].values[0])
+ "]"
)
pg.rename(columns=col, inplace=True)
logger.debug("Classifying results type ...")
pg["opt_global_result_type"] = "single_protein"
pg.loc[pg["Protein.Group"].str.contains(";"), "opt_global_result_type"] = (
"indistinguishable_protein_group"
)
out_mztab_prh = pg
del pg
out_mztab_prh = out_mztab_prh.drop(["Protein.Names"], axis=1)
out_mztab_prh.rename(
columns={
"First.Protein.Description": "description",
},
inplace=True,
)
out_mztab_prh.loc[:, "database"] = database
null_col = [
"taxid",
"species",
"database_version",
"search_engine",
"opt_global_Posterior_Probability_score",
"opt_global_nr_found_peptides",
"opt_global_cv_PRIDE:0000303_decoy_hit",
]
for i in null_col:
out_mztab_prh.loc[:, i] = "null"
logger.debug("Extracting accession values (keeping first)...")
out_mztab_prh.loc[:, "accession"] = out_mztab_prh.apply(
lambda x: x["Protein.Group"].split(";")[0], axis=1
)
protein_details_df = out_mztab_prh[
out_mztab_prh["opt_global_result_type"] == "indistinguishable_protein_group"
]
prh_series = (
protein_details_df["Protein.Group"]
.str.split(";", expand=True)
.stack()
.reset_index(level=1, drop=True)
)
prh_series.name = "accession"
protein_details_df = (
protein_details_df.drop("accession", axis=1)
.join(prh_series)
.reset_index()
.drop(columns="index")
)
if len(protein_details_df) > 0:
logger.info(f"Found {len(protein_details_df)} indistinguishable protein groups")
# The Following line fails if there are no indistinguishable protein groups
protein_details_df.loc[:, "col"] = "protein_details"
# protein_details_df = protein_details_df[-protein_details_df["accession"].str.contains("-")]
out_mztab_prh = pd.concat([out_mztab_prh, protein_details_df]).reset_index(
drop=True
)
else:
logger.info("No indistinguishable protein groups found")
logger.debug("Calculating protein coverage (bottleneck)...")
# This is a bottleneck
# reimplementation runs in 67s vs 137s (old) in my data
out_mztab_prh.loc[:, "protein_coverage"] = calculate_protein_coverages(
report=report, out_mztab_prh=out_mztab_prh, fasta_df=fasta_df
)
logger.debug("Getting ambiguity members...")
# IN THEORY this should be the same as
# out_mztab_PRH["ambiguity_members"] = out_mztab_PRH["Protein.Ids"]
# out_mztab_PRH.loc[out_mztab_PRH["opt_global_result_type"] == "single_protein", "ambiguity_members"] = "null"
# or out_mztab_PRH.loc[out_mztab_PRH["Protein.Ids"] == out_mztab_PRH["accession"], "ambiguity_members"] = "null"
out_mztab_prh.loc[:, "ambiguity_members"] = out_mztab_prh.apply(
lambda x: (
x["Protein.Group"]
if x["opt_global_result_type"] == "indistinguishable_protein_group"
else "null"
),
axis=1,
)
logger.debug("Matching PRH to best search engine score...")
score_looker = ModScoreLooker(report)
out_mztab_prh[["modifiedSequence", "best_search_engine_score[1]"]] = (
out_mztab_prh.apply(
lambda x: score_looker.get_score(x["Protein.Group"]),
axis=1,
result_type="expand",
)
)
logger.debug("Matching PRH to modifications...")
out_mztab_prh.loc[:, "modifications"] = out_mztab_prh.apply(
lambda x: find_modification(x["modifiedSequence"]), axis=1, result_type="expand"
)
logger.debug("Matching PRH to protein quantification...")
# quantity at protein level: PG.MaxLFQ
# This used to be a bottleneck in performance
# This implementation drops the run time from 57s to 25ms
protein_agg_report = (
report[["PG.MaxLFQ", "Protein.Group", "study_variable"]]
.groupby(["study_variable", "Protein.Group"])
.agg({"PG.MaxLFQ": ["mean", "std", "sem"]})
.reset_index()
.pivot(columns=["study_variable"], index="Protein.Group")
.reset_index()
)
protein_agg_report.columns = [
"::".join([str(s) for s in col]).strip()
for col in protein_agg_report.columns.values
]
subname_mapper = {
"Protein.Group::::": "Protein.Group",
"PG.MaxLFQ::mean": "protein_abundance_study_variable",
"PG.MaxLFQ::std": "protein_abundance_stdev_study_variable",
"PG.MaxLFQ::sem": "protein_abundance_std_error_study_variable",
}
name_mapper = name_mapper_builder(subname_mapper)
protein_agg_report.rename(columns=name_mapper, inplace=True)
# out_mztab_PRH has columns accession and Protein.Ids; 'Q9NZJ9', 'A0A024RBG1;Q9NZJ9;Q9NZJ9-2']
# the report table has 'Protein.Group' and 'Protein.Ids': 'Q9NZJ9', 'A0A024RBG1;Q9NZJ9;Q9NZJ9-2'
# Oddly enough the last implementation mapped the the accession (Q9NZJ9) in the mztab
# to the Protein.Ids (A0A024RBG1;Q9NZJ9;Q9NZJ9-2), leading to A LOT of missing values.
out_mztab_prh = out_mztab_prh.merge(
protein_agg_report,
on="Protein.Group",
how="left",
validate="many_to_one",
copy=True,
)
del name_mapper
del subname_mapper
del protein_agg_report
# end of (former) bottleneck
out_mztab_prh.loc[:, "PRH"] = "PRT"
index = out_mztab_prh.loc[:, "PRH"]
out_mztab_prh.drop(
["PRH", "Genes", "modifiedSequence", "Protein.Group"], axis=1, inplace=True
)
out_mztab_prh.insert(0, "PRH", index)
out_mztab_prh.fillna("null", inplace=True)
out_mztab_prh.loc[:, "database"] = database
new_cols = [col for col in out_mztab_prh.columns if not col.startswith("opt_")] + [
col for col in out_mztab_prh.columns if col.startswith("opt_")
]
out_mztab_prh = out_mztab_prh[new_cols]
return out_mztab_prh
def mztab_peh(
report: pd.DataFrame,
pr: pd.DataFrame,
precursor_list: List[str],
index_ref: pd.DataFrame,
database: os.PathLike,
) -> pd.DataFrame:
"""
Construct PEH sub-table.
:param report: Dataframe for Dia-NN main report
:type report: pandas.core.frame.DataFrame
:param pr: Dataframe for Dia-NN precursors matrix
:type pr: pandas.core.frame.DataFrame
:param precursor_list: A list contains all precursor IDs
:type precursor_list: list
:param index_ref: On the basis of f_table, two columns "ms_run" and "study_variable" are added for matching
:type index_ref: pandas.core.frame.DataFrame
:param database: Path to fasta file
:type database: str
:return: PEH sub-table
:rtype: pandas.core.frame.DataFrame
"""
logger.info("Constructing PEH sub-table...")
logger.debug(
f"report.shape: {report.shape}, "
f" pr.shape: {pr.shape},"
f" len(precursor_list): {len(precursor_list)},"
f" index_ref.shape: {index_ref.shape}"
)
out_mztab_peh = pd.DataFrame()
out_mztab_peh = pr.iloc[:, 0:10]
out_mztab_peh.drop(
["Protein.Ids", "Protein.Names", "First.Protein.Description", "Proteotypic"],
axis=1,
inplace=True,
)
out_mztab_peh.rename(
columns={
"Stripped.Sequence": "sequence",
"Protein.Group": "accession",
"Modified.Sequence": "opt_global_cv_MS:1000889_peptidoform_sequence",
"Precursor.Charge": "charge",
},
inplace=True,
)
logger.debug("Finding modifications...")
out_mztab_peh.loc[:, "modifications"] = out_mztab_peh.apply(
lambda x: find_modification(x["opt_global_cv_MS:1000889_peptidoform_sequence"]),
axis=1,
result_type="expand",
)
logger.debug("Extracting sequence...")
out_mztab_peh.loc[:, "opt_global_cv_MS:1000889_peptidoform_sequence"] = (
out_mztab_peh.apply(
lambda x: AASequence.fromString(
x["opt_global_cv_MS:1000889_peptidoform_sequence"]
).toString(),
axis=1,
)
)
logger.debug("Checking accession uniqueness...")
out_mztab_peh.loc[:, "unique"] = out_mztab_peh.apply(
lambda x: "0" if ";" in str(x["accession"]) else "1",
axis=1,
result_type="expand",
)
null_col = [
"database_version",
"search_engine",
"retention_time_window",
"mass_to_charge",
"opt_global_feature_id",
]
for i in null_col:
out_mztab_peh.loc[:, i] = "null"
out_mztab_peh.loc[:, "opt_global_cv_MS:1002217_decoy_peptide"] = "0"
logger.debug("Matching precursor IDs...")
# Pre-calculating the indices and using a lookup table drops run time from
# ~6.5s to 11ms
precursor_indices = {k: i for i, k in enumerate(precursor_list)}
pr_ids = out_mztab_peh["Precursor.Id"].map(precursor_indices)
out_mztab_peh["pr_id"] = pr_ids
del precursor_indices
logger.debug("Getting scores per run")
# This implementation is 422-700x faster than the apply-based one
tmp = (
report.groupby(["precursor.Index", "ms_run"])
.agg({"Q.Value": ["min"]})
.reset_index()
.pivot(columns=["ms_run"], index="precursor.Index")
.reset_index()
)
tmp.columns = pd.Index(
["::".join([str(s) for s in col]).strip() for col in tmp.columns.values]
)
subname_mapper = {
"precursor.Index::::": "precursor.Index",
"Q.Value::min": "search_engine_score[1]_ms_run",
}
name_mapper = name_mapper_builder(subname_mapper)
tmp.rename(columns=name_mapper, inplace=True)
out_mztab_peh = out_mztab_peh.merge(
tmp.rename(columns={"precursor.Index": "pr_id"}),
on="pr_id",
validate="one_to_one",