CandyCrunch 0.5.2__tar.gz → 0.5.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch/prediction.py +5 -4
  2. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch.egg-info/PKG-INFO +5 -3
  3. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch.egg-info/SOURCES.txt +1 -3
  4. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch.egg-info/requires.txt +2 -1
  5. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/PKG-INFO +5 -3
  6. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/pyproject.toml +3 -2
  7. CandyCrunch-0.5.2/tests/test_CandyCrumbs.py +0 -102
  8. CandyCrunch-0.5.2/tests/test_CandyCrunch.py +0 -162
  9. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch/__init__.py +0 -0
  10. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch/analysis.py +0 -0
  11. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch/candycrunch.pt +0 -0
  12. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch/cli.py +0 -0
  13. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch/glycans.pkl +0 -0
  14. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch/glytoucan_mapping.pkl +0 -0
  15. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch/model.py +0 -0
  16. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch.egg-info/dependency_links.txt +0 -0
  17. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch.egg-info/entry_points.txt +0 -0
  18. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/CandyCrunch.egg-info/top_level.txt +0 -0
  19. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/LICENSE +0 -0
  20. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/README.md +0 -0
  21. {CandyCrunch-0.5.2 → candycrunch-0.5.4}/setup.cfg +0 -0
@@ -1429,7 +1429,6 @@ def finalise_predictions(df_out,get_missing,pred_thresh,mode,modification,mass_t
1429
1429
  df_out = canonicalize_biosynthesis(df_out, pred_thresh)
1430
1430
  except ValueError:
1431
1431
  pass
1432
- spectra_out = df_out.pop('peak_d').values.tolist()
1433
1432
  # Calculate ppm error
1434
1433
  valid_indices, ppm_errors = [], []
1435
1434
  df_out = df_out[df_out['predictions'].apply(len)>0]
@@ -1454,6 +1453,7 @@ def finalise_predictions(df_out,get_missing,pred_thresh,mode,modification,mass_t
1454
1453
  df_out['rel_abundance'] = df_out['rel_abundance'] / df_out['rel_abundance'].sum() * 100
1455
1454
  else:
1456
1455
  df_out.drop(['rel_abundance'], axis = 1, inplace = True)
1456
+ spectra_out = df_out.pop('peak_d').values.tolist()
1457
1457
  df_out.index.name = "m/z"
1458
1458
  if plot_glycans:
1459
1459
  from glycowork.motif.draw import plot_glycans_excel
@@ -1582,7 +1582,6 @@ def wrap_inference(spectra_filepath, glycan_class, model = candycrunch, glycans
1582
1582
  df_out = df_out[df_out['predictions'].str.len() > 0]
1583
1583
  # Reprioritize predictions based on how well they are explained by biosynthetic precursors in the same file (e.g., core 1 O-glycan making extended core 1 O-glycans more likely)
1584
1584
  df_out = canonicalize_biosynthesis(df_out, pred_thresh)
1585
- spectra_out = df_out.pop('peak_d').values.tolist()
1586
1585
  # Calculate ppm error
1587
1586
  valid_indices, ppm_errors = [], []
1588
1587
  for preds, obs_mass in zip(df_out['predictions'], df_out.index):
@@ -1608,6 +1607,7 @@ def wrap_inference(spectra_filepath, glycan_class, model = candycrunch, glycans
1608
1607
  df_out['rel_abundance'] = df_out['rel_abundance'] / df_out['rel_abundance'].sum() * 100
1609
1608
  else:
1610
1609
  df_out.drop(['rel_abundance'], axis = 1, inplace = True)
1610
+ spectra_out = df_out.pop('peak_d').values.tolist()
1611
1611
  df_out.index.name = "m/z"
1612
1612
  if plot_glycans:
1613
1613
  from glycowork.motif.draw import plot_glycans_excel
@@ -1732,8 +1732,9 @@ def wrap_inference_batch(spectra_filepath_list, glycan_class, intra_cat_thresh,
1732
1732
  mode, modification, mass_tag, filter_out, taxonomy_filter,
1733
1733
  reduced, mass_tolerance, mass_dic)
1734
1734
  # Finalize predictions
1735
- df_out = finalise_predictions(df_out, get_missing, pred_thresh, mode, modification,
1736
- mass_tag, multiplier, plot_glycans, file_label, spectra)
1735
+ if len(df_out)>0:
1736
+ df_out = finalise_predictions(df_out, get_missing, pred_thresh, mode, modification,
1737
+ mass_tag, multiplier, plot_glycans, file_label, spectra)
1737
1738
  inference_dfs[file_label] = df_out
1738
1739
  all_outputs = pd.concat(inference_dfs.values())
1739
1740
  combined_batch = all_outputs.pivot_table(index='top1_pred',columns='condition_label',values='rel_abundance',aggfunc='sum')
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: CandyCrunch
3
- Version: 0.5.2
3
+ Version: 0.5.4
4
4
  Summary: Package for predicting glycan structure from LC-MS/MS data
5
5
  Author-email: Daniel Bojar <daniel.bojar@gu.se>
6
6
  License: MIT
@@ -11,7 +11,8 @@ Classifier: Operating System :: OS Independent
11
11
  Requires-Python: >=3.8
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
- Requires-Dist: glycowork~=1.5.0
14
+ Requires-Dist: glycowork[draw]~=1.5.0
15
+ Requires-Dist: requests
15
16
  Requires-Dist: regex
16
17
  Requires-Dist: networkx
17
18
  Requires-Dist: scipy
@@ -28,6 +29,7 @@ Requires-Dist: openpyxl
28
29
  Requires-Dist: tabulate
29
30
  Provides-Extra: draw
30
31
  Requires-Dist: glycowork[draw]~=1.5.0; extra == "draw"
32
+ Dynamic: license-file
31
33
 
32
34
  <p align="center">
33
35
  <img src="/images/candycrunch_logo_light_banner_pt.svg" style="height:100%;width:100%;">
@@ -14,6 +14,4 @@ CandyCrunch.egg-info/SOURCES.txt
14
14
  CandyCrunch.egg-info/dependency_links.txt
15
15
  CandyCrunch.egg-info/entry_points.txt
16
16
  CandyCrunch.egg-info/requires.txt
17
- CandyCrunch.egg-info/top_level.txt
18
- tests/test_CandyCrumbs.py
19
- tests/test_CandyCrunch.py
17
+ CandyCrunch.egg-info/top_level.txt
@@ -1,4 +1,5 @@
1
- glycowork~=1.5.0
1
+ glycowork[draw]~=1.5.0
2
+ requests
2
3
  regex
3
4
  networkx
4
5
  scipy
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: CandyCrunch
3
- Version: 0.5.2
3
+ Version: 0.5.4
4
4
  Summary: Package for predicting glycan structure from LC-MS/MS data
5
5
  Author-email: Daniel Bojar <daniel.bojar@gu.se>
6
6
  License: MIT
@@ -11,7 +11,8 @@ Classifier: Operating System :: OS Independent
11
11
  Requires-Python: >=3.8
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
- Requires-Dist: glycowork~=1.5.0
14
+ Requires-Dist: glycowork[draw]~=1.5.0
15
+ Requires-Dist: requests
15
16
  Requires-Dist: regex
16
17
  Requires-Dist: networkx
17
18
  Requires-Dist: scipy
@@ -28,6 +29,7 @@ Requires-Dist: openpyxl
28
29
  Requires-Dist: tabulate
29
30
  Provides-Extra: draw
30
31
  Requires-Dist: glycowork[draw]~=1.5.0; extra == "draw"
32
+ Dynamic: license-file
31
33
 
32
34
  <p align="center">
33
35
  <img src="/images/candycrunch_logo_light_banner_pt.svg" style="height:100%;width:100%;">
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "CandyCrunch"
7
- version = "0.5.2"
7
+ version = "0.5.4"
8
8
  description = "Package for predicting glycan structure from LC-MS/MS data"
9
9
  readme = "README.md"
10
10
  authors = [
@@ -18,7 +18,8 @@ classifiers = [
18
18
  ]
19
19
  requires-python = ">=3.8"
20
20
  dependencies = [
21
- "glycowork~=1.5.0",
21
+ "glycowork[draw]~=1.5.0",
22
+ "requests",
22
23
  "regex",
23
24
  "networkx",
24
25
  "scipy",
@@ -1,102 +0,0 @@
1
- import pytest
2
- import unittest
3
- from CandyCrunch.analysis import CandyCrumbs
4
-
5
- TEST_DICTS = [{'glycan_string':'GalNAc(b1-4)GlcNAc(b1-3)[GalNAc(b1-4)GlcNAc(b1-6)]Gal(b1-4)Glc',
6
- 'charge': -2,
7
- 'label_mass':2.0156,
8
- 'masses': [405.07,423.05,465.11,528.14,549.15,567.17,713.21,731.22,749.24,892.27,934.28,952.28,973.25,1095.31,1113.32],
9
- 'annotations': [['B_2_Alpha'],['C_2_Alpha'],['24A_3_Alpha'],['Z_2_Alpha','Y_3_Beta'],['C_3_Alpha','Z_2_Alpha'],['C_3_Alpha','Y_2_Alpha'],['Z_3_Alpha','Z_3_Beta'],['Z_2_Alpha'],['Y_2_Alpha'],[],['Z_3_Alpha'],['Y_3_Alpha'],['C_3_Alpha'],['M_C2H4O2'],['M_C2H2O']],
10
- 'ref': 'JC_Pygmy_Hippo_milk_(neutral)',
11
- 'max_cleavages':4
12
- },
13
- {'glycan_string': 'Gal(a1-3)Gal(b1-4)GlcNAc(b1-6)[GalNAc(b1-4)GlcNAc(b1-3)]Gal(b1-4)Glc',
14
- 'charge': -2,
15
- 'label_mass':2.0156,
16
- 'masses': [405.11,425.07,443.07,528.17,546.19,586.18,670.19,688.20,731.24,749.25,852.25,870.26,892.28,934.30,952.30,1013.27,1055.28,1073.30,1094.30,1114.31,1216.32,1234.33],
17
- 'annotations': [['B_2_Beta'],['02A_3_Alpha','M_H2O'],['02A_3_Alpha'],['Z_2_Alpha','Y_3_Beta'],['Y_2_Alpha','Y_3_Beta'],['04A_4_Alpha'],['C_3_Alpha','Z_2_Beta'],['C_3_Alpha','Y_2_Beta'],['Z_2_Alpha'],['Y_2_Alpha'],['Z_2_Beta'],['Y_2_Beta'],[],['Z_3_Alpha'],['Y_3_Alpha'],[],['Z_3_Beta'],['Y_3_Beta'],['C_4_Alpha'],['Y_4_Alpha'],['M_C2H4O2'],['M_C2H2O']],
18
- 'ref': 'JC_Pygmy_Hippo_milk_(neutral)'
19
- },
20
- {'glycan_string': 'Fuc(a1-2)Gal(b1-3)[Gal(a1-3)[Fuc(a1-2)]Gal(b1-4)GlcNAc(b1-6)]GalNAc',
21
- 'charge': -1,
22
- 'label_mass':2.0156,
23
- 'masses': [389.15,407.14,503.22,529.15,571.49,655.16,697.20,715.20,733.24,859.35,877.26,895.24,1005.26,1023.27,1041.33,1058.21,1143.45,1161.34],
24
- 'annotations': [['Z_2_Alpha','Z_1_Gamma'],['Y_2_Alpha','Z_1_Gamma'],['Z_3_Alpha','Z_3_Beta','Z_1_Gamma','M_H2O'],['24A_3_Alpha'],['02A_3_Alpha','M_H2O'],[],['Z_3_Alpha','Z_1_Gamma'],['Y_3_Alpha','Z_1_Gamma'],['Y_2_Alpha'],[],['Z_1_Gamma'],['Y_1_Gamma'],[],['Z_3_Alpha'],['Y_3_Alpha'],['Y_2_Gamma'],['M_C2H4O2'],['M_C2H2O']],
25
- 'ref': '10.1074/mcp.M116.067983'
26
- },
27
- {'glycan_string': 'Fuc(a1-2)[GalNAc(a1-3)]Gal(b1-3)[GalNAc(a1-3)[Fuc(a1-2)]Gal(b1-4)[Fuc(a1-2)]GlcNAc(b1-6)]GalNAc',
28
- 'charge': -2,
29
- 'label_mass':2.0156,
30
- 'masses': [246.99,306.87,510.14,540.75,553.26,694.70,733.22,766.26,861.36,900.13,919.09,1064.16,1082.30,1330.37,1372.21,1390.18],
31
- 'annotations': [['Y_3_Alpha','B_2_Alpha','M_C2H4O2'],['Y_3_Alpha','B_2_Alpha'],['B_2_Alpha'],['Y_1_Gamma'],['Y_2_Alpha','Z_1_Gamma'],['Y_2_Gamma'],['Y_1_Alpha'],[],['Y_3_Alpha','Z_1_Gamma'],['Z_2_Alpha','Z_2_Beta'],['04A_0_Alpha'],['Z_1_Gamma'],['Y_1_Gamma'],[],['Z_2_Gamma'],['Y_3_Gamma']],
32
- 'ref': '10.1074/mcp.M116.067983'
33
- },
34
- {'glycan_string': 'Neu5Ac(a2-6)GalNAc',
35
- 'charge': -1,
36
- 'label_mass':2.0156,
37
- 'masses': [170.03,204.07,222.12,276.10,290.11,308.12],
38
- 'annotations': [[],['Z_1_Alpha'],['Y_1_Alpha'],[],['B_1_Alpha'],['C_1_Alpha']],
39
- 'ref': '10.1074/mcp.M116.067983'
40
- },
41
- {'glycan_string': 'Fuc(a1-2)[Gal(b1-3)]Gal(b1-3)[Neu5Ac(a2-3)Gal(?1-?)[Fuc(?1-?)]GlcNAc(b1-6)]GalNAc',
42
- 'charge': -1,
43
- 'label_mass':2.0156,
44
- 'masses': [553.20,571.18,674.17,692.36,715.49,733.28,829.06,859.36,1023.38,1041.20,1057.28,1185.35,1203.34,1333.37,1416.40,1434.44],
45
- 'annotations': [['Y_2_Alpha','Z_1_Gamma'],['Y_2_Alpha','Y_1_Gamma'],['Z_1_Alpha'],['Y_1_Alpha'],['Y_3_Alpha','Z_1_Gamma'],[],['Z_2_Alpha','Z_2_Beta','M_CH2O'],['Y_2_Alpha','Z_2_Beta'],['Z_2_Alpha'],['Y_2_Alpha'],['Y_3_Alpha','Y_3_Beta'],['Z_3_Alpha'],['Y_3_Alpha'],['Y_2_Gamma'],[],['M_C2H4O2']],
46
- 'ref': '10.1074/mcp.M116.067983'
47
- },
48
- {'glycan_string':"AVAVT*Neu5Ac(a2-3)Gal(a1-3)[Neu5Ac(a2-3)Gal(b1-4)GlcNAc(b1-6)]GalNAc*LQSH",
49
- 'charge':+2,
50
- 'label_mass':0,
51
- 'masses':[156.076, 204.086, 228.09, 243.108, 259.176, 274.092, 292.102, 355.148, 366.14, 425.178, 454.155, 468.232, 564.797, 657.234, 666.339, 747.365, 791.372, 828.393, 860.311, 892.912, 925.51, 973.939, 990.897, 1022.361, 1026.430, 1075.959, 1128.589, 1236.557, 1267.642, 1290.641, 1313.451, 1771.752, 1884.831, 1981.806],
52
- 'annotations':[[['y_1'],['loss of glycan 1']],[['No_Peptide'],['C_4_Alpha', 'Z_1_Beta', 'Z_1_Alpha']],[['z_2'],['loss of glycan 1']],[['y_2'],['loss of glycan 1']],[['c_3'],['loss of glycan 1']],[['No Peptide'], ['B_1_Beta', 'M_H2O']],[['No Peptide'], ['B_1_Beta']],[['z_3'], ['loss of glycan 1']],[['No Peptide'], ['Y_3_Alpha', 'B_3_Alpha']],[['w_4'], ['loss of glycan 1']],[['No Peptide'], ['B_2_Alpha']],[['z_4'], ['loss of glycan 1']],[['Peptide'], ['Y_1_Beta', 'Y_1_Alpha']],[['No Peptide'], ['B_3_Alpha']],[['Peptide'], ['Y_1_Beta', 'Y_2_Alpha']],[['Peptide'], ['Y_1_Beta', 'Y_3_Alpha']],[['Peptide'], ['Y_1_Alpha']],[['Peptide'], ['Y_2_Beta', 'Y_3_Alpha']],[['No Peptide'], ['Y_1_Beta']],[['Peptide'], ['Y_1_Beta']], [['Peptide'], ['Y_0_Alpha']],[['Peptide'], ['Y_3_Alpha']], [['z_6'], ['M']], [['No Peptide'], ['Y_3_Alpha']], [['z_7'], ['M']], [['z_8'], ['M']], [['Peptide'], ['Y_1_Beta', 'Y_1_Alpha']], [], [], [['Peptide'], ['Y_1_Alpha', 'Y_2_Beta']], [['No Peptide'], ['B_4_Alpha']], [['c_5'], ['M']], [['c_6'], ['M']], [['z_6'], ['M']]],
53
- 'ref':'https://doi.org/10.1007/s13361-018-1945-7'
54
- }
55
- ]
56
- THRESHOLD = 0.1
57
- TOP5_THRESHOLD = 0.63
58
- @pytest.mark.parametrize("test_dict", TEST_DICTS)
59
- def test_candycrumbs_accuracy(test_dict):
60
- result = CandyCrumbs(test_dict['glycan_string'], test_dict['masses'], 0.4, charge=test_dict['charge'],mass_tag=test_dict['label_mass'],max_cleavages=test_dict.get('max_cleavages',3))
61
- total_annotations = len(test_dict['annotations'])
62
- correct_annotations = 0
63
- assert len(result) == total_annotations
64
- for mass, expected_annotations in zip(test_dict['masses'], test_dict['annotations']):
65
- if not expected_annotations:
66
- total_annotations=total_annotations-1
67
- continue
68
- if mass in result:
69
- if result[mass]:
70
- predicted_annotations = result[mass]['Domon-Costello nomenclatures'][0]
71
- if predicted_annotations == sorted(expected_annotations):
72
- correct_annotations += 1
73
- elif not expected_annotations:
74
- correct_annotations += 1 # Credit for correctly predicting no annotations
75
-
76
- score = correct_annotations / total_annotations
77
- # Set a threshold for acceptable performance (e.g., 80% correct)
78
- print(f"Score: {score:.2f}, Threshold: {THRESHOLD}")
79
- assert score > THRESHOLD
80
-
81
- @pytest.mark.parametrize("test_dict", TEST_DICTS)
82
- def test_candycrumbs_accuracy_top5(test_dict):
83
- result = CandyCrumbs(test_dict['glycan_string'], test_dict['masses'], 0.4, charge=test_dict['charge'],mass_tag=test_dict['label_mass'],simplify=False)
84
- total_annotations = len(test_dict['annotations'])
85
- correct_annotations = 0
86
- assert len(result) == total_annotations
87
- for mass, expected_annotations in zip(test_dict['masses'], test_dict['annotations']):
88
- if not expected_annotations:
89
- total_annotations=total_annotations-1
90
- continue
91
- if mass in result:
92
- if result[mass]:
93
- predicted_annotations = result[mass]['Domon-Costello nomenclatures']
94
- if expected_annotations in predicted_annotations:
95
- correct_annotations += 1
96
- elif not expected_annotations:
97
- correct_annotations += 1 # Credit for correctly predicting no annotations
98
-
99
- score = correct_annotations / total_annotations
100
- # Set a threshold for acceptable performance (e.g., 80% correct)
101
- print(f"Score: {score:.2f}, Threshold: {TOP5_THRESHOLD}")
102
- assert score > TOP5_THRESHOLD
@@ -1,162 +0,0 @@
1
- import pytest
2
- import unittest
3
- import os
4
- import pathlib
5
- import sys
6
- from tabulate import tabulate
7
- import numpy as np
8
- from collections import defaultdict
9
-
10
- from CandyCrunch.prediction import *
11
- from glycowork.motif.graph import compare_glycans,get_possible_topologies,graph_to_string
12
- from itertools import product
13
- import time
14
-
15
- BASE_DIR = pathlib.Path(__file__).parent.parent # Go up one level from the test file
16
- TEST_DATA_DIR = BASE_DIR / "tests" / "data"
17
- TEST_DICTS = [
18
- {'name':'milk','args': {'glycan_class':'free'}, 'mass_threshold':0.5, 'RT_threshold':1},
19
- {'name':'GPST000350','args': {'glycan_class':'O','taxonomy_level':'Kingdom','taxonomy_filter':'Animalia'},'test_files':[x for x in os.listdir(f"{TEST_DATA_DIR}/GPST000350/") if 'O.' in x],'mass_threshold':0.5, 'RT_threshold':1},
20
- {'name':'GPST000350','args': {'glycan_class':'N','taxonomy_level':'Kingdom','taxonomy_filter':'Animalia'},'test_files':[x for x in os.listdir(f"{TEST_DATA_DIR}/GPST000350/") if 'N' in x],'mass_threshold':0.5, 'RT_threshold':1},
21
- {'name':'GPST000017','args': {'glycan_class':'O','taxonomy_level':'Kingdom','taxonomy_filter':'Animalia'}, 'test_files':[x for x in os.listdir(f"{TEST_DATA_DIR}/GPST000017/") if 'PGMb' not in x if 'JC' in x],'mass_threshold':0.5, 'RT_threshold':2},
22
- {'name':'GPST000029','args': {'glycan_class':'O','taxonomy_level':'Kingdom','taxonomy_filter':'Animalia'}, 'mass_threshold':0.5, 'RT_threshold':1},
23
- {'name':'PMC8950484_CHO','args': {'glycan_class':'O','taxonomy_level':'Kingdom','taxonomy_filter':'Animalia'}, 'mass_threshold':0.5, 'RT_threshold':1},
24
- {'name':'GPST000307','args': {'glycan_class':'O','taxonomy_level':'Kingdom','taxonomy_filter':'Animalia'}, 'mass_threshold':0.5, 'RT_threshold':1},
25
- {'name':'GPST000487','args': {'glycan_class':'N','taxonomy_level':'Kingdom','taxonomy_filter':'Animalia'},'test_files':[x for x in os.listdir(f"{TEST_DATA_DIR}/GPST000487/")],'mass_threshold':0.5, 'RT_threshold':1},
26
- {'name':'GPST000134','args': {'glycan_class':'N','taxonomy_level':'Kingdom','taxonomy_filter':'Animalia','mode':'positive'},'test_files':[x for x in os.listdir(f"{TEST_DATA_DIR}/GPST000134/") if 'glycans_1' in x][:1],'mass_threshold':0.5, 'RT_threshold':1}
27
-
28
- ]
29
-
30
- def match_spectra(array1, array2, mass_threshold=0.3, rt_threshold=0.9):
31
- matches = []
32
-
33
- for i, (mass1, rt1) in enumerate(array1):
34
- # Find all potential matches based on mass
35
- mass_diffs = np.abs(array2[:, 0] - mass1)
36
- potential_matches = np.where(mass_diffs <= mass_threshold)[0]
37
-
38
- if len(potential_matches) == 0:
39
- continue
40
-
41
- # If only one match, check retention time
42
- if len(potential_matches) == 1:
43
- j = potential_matches[0]
44
- if abs(rt1 - array2[j, 1]) <= rt_threshold:
45
- matches.append((i, j))
46
- else:
47
- # Multiple matches, find the closest retention time
48
- rt_diffs = np.abs(array2[potential_matches, 1] - rt1)
49
- best_match = potential_matches[np.argmin(rt_diffs)]
50
- if rt_diffs[np.argmin(rt_diffs)] <= rt_threshold:
51
- matches.append((i, best_match))
52
-
53
- return matches
54
-
55
- def add_pred_column(df_in,col_name,matches,pred_df,rt_col):
56
- df_in[col_name] = None
57
- for gt_idx,pred_idx in matches:
58
- df_in.at[gt_idx,col_name] = pred_df.iloc[pred_idx,:]['top1_pred']
59
- extra_preds = pred_df[~(pred_df.index.isin([x[1] for x in matches]))][['m/z','RT','top1_pred']].rename(columns={'m/z':'Mass','top1_pred':col_name,'RT':rt_col})
60
- df_in = pd.concat([df_in,extra_preds]).sort_values(['Mass',rt_col])
61
- return df_in
62
-
63
- def evaluate_predictions(predictions,gt,rt_col,mass_thresh,RT_thresh):
64
- assert len(predictions)>0
65
- if len(predictions)==0:
66
- print('empty preds')
67
- return 0,0,0,0,0,0
68
- predictions['converted_masses'] = [m_z for m_z,charge in zip(predictions.reset_index()['m/z'],predictions['charge'])]
69
- pairs = predictions.reset_index()[['m/z','RT']].round(2).values
70
- gt_pairs = gt.reset_index()[['Mass',rt_col]].round(2).values
71
- matched_pairs = match_spectra(gt_pairs, pairs,mass_threshold=mass_thresh,rt_threshold=RT_thresh)
72
- merge_df = gt[['Mass',rt_col,'glycan']].reset_index(drop=True)
73
- new_md = add_pred_column(merge_df,'batch_pred',matched_pairs,predictions.reset_index(),rt_col)
74
- # correct_preds = [compare_glycans(x,y) if (isinstance(x,str) and isinstance(y,str)) else False for x,y in zip(new_md['glycan'],new_md['batch_pred'])]
75
- correct_preds = []
76
- for gt_glycan, pred_glycan in zip(new_md['glycan'],new_md['batch_pred']):
77
- if not (isinstance(gt_glycan,str) and isinstance(pred_glycan,str)):
78
- correct_preds.append(False)
79
- continue
80
- if '{' in gt_glycan:
81
- possible_structures = [graph_to_string(x) for x in get_possible_topologies(gt_glycan)]
82
- correct_preds.append(any([compare_glycans(p,pred_glycan) for p in possible_structures]))
83
- else:
84
- correct_preds.append(compare_glycans(gt_glycan,pred_glycan))
85
- new_md['correct_preds'] = correct_preds
86
- tp = len(np.where(new_md['correct_preds'] == True)[0])
87
- fp = len(np.where((new_md['glycan'].isnull())&(new_md['batch_pred'].notnull()))[0])
88
- fn = len(np.where((new_md['glycan'].notnull())&(new_md['correct_preds'] == False))[0])
89
- peaks_not_picked = len(np.where((new_md['glycan'].notnull())&(new_md['batch_pred'].isnull()))[0])
90
- incorrect_predictions = len(np.where((new_md['glycan'].notnull())&(new_md['batch_pred'].notnull())&(new_md['correct_preds'] == False))[0])
91
- Precision = (tp / (tp + fp)+1e-4)+1e-4
92
- Recall = (tp / (tp + fn)+1e-4)+1e-4
93
- F1_score = 2 * (Precision * Recall) / (Precision + Recall)
94
- return F1_score,Precision,Recall,peaks_not_picked,incorrect_predictions,tp,fp,fn
95
-
96
- def posthoc_process_df(df_in,posthoc_params):
97
- for arg in posthoc_params:
98
- df_arg = arg.split('posthoc_')[1]
99
- if 'lowerthan' in arg:
100
- df_arg = df_arg.split('lowerthan_')[1]
101
- df_in = df_in[(df_in[df_arg]<posthoc_params[arg])]
102
- else:
103
- df_in = df_in[(df_in[df_arg]>posthoc_params[arg])]
104
- return df_in
105
-
106
- AVG_THRESHOLD = 0.05
107
-
108
- extra_param_dict = {
109
- 'test_dict': TEST_DICTS,
110
- 'supplement': [True],
111
- 'experimental': [True]
112
- }
113
-
114
- test_params = [
115
- dict(zip([x for x in extra_param_dict], combo))
116
- for combo in product(*[v for v in extra_param_dict.values()])
117
- ]
118
-
119
- @pytest.mark.parametrize("test_params", test_params)
120
- def test_candycrunch_accuracy(test_params,result_collector,test_files=None):
121
- if result_collector.param_names is None:
122
- result_collector.param_names = {k:k for k in extra_param_dict.keys()}
123
- start_time = time.time() # Start timing
124
- test_outputs = []
125
- test_dict = test_params['test_dict']
126
- test_files = test_params['test_dict'].get('test_files',None)
127
- if not test_files:
128
- test_files = [x for x in os.listdir(f"{TEST_DATA_DIR}/{test_dict['name']}")]
129
- test_files = [x for x in test_files if 'df_mz' not in x if not x.startswith(".")]
130
- for filename in test_files:
131
- inference_params = {k:v for k,v in test_params.items() if 'posthoc' not in k if k!= 'test_dict'}
132
- posthoc_params = {k:v for k,v in test_params.items() if 'posthoc' in k}
133
- print(filename)
134
- print(inference_params|posthoc_params)
135
- start_time = time.time()
136
- preds_out = wrap_inference(f"{TEST_DATA_DIR}/{test_dict['name']}/{filename}",**test_dict['args'],
137
- **inference_params)
138
- end_time = time.time() # End timing
139
- execution_time = end_time - start_time
140
- print(f"\nTest execution time: {execution_time:.2f} seconds") # Print execution time
141
- preds_out = posthoc_process_df(preds_out,posthoc_params)
142
- loaded_gt = pd.read_csv(f"{TEST_DATA_DIR}/{test_dict['name']}/df_mz_{test_dict['name']}.csv")
143
- col_name = filename.split(".")[0]
144
- rt_col_name = 'RT' if 'RT' in loaded_gt.columns else col_name+'_RT'
145
- eval_scores = evaluate_predictions(preds_out,loaded_gt[loaded_gt[col_name]>0].dropna(subset='glycan'),rt_col_name,test_dict['mass_threshold'],test_dict['RT_threshold'])
146
- print('True Positives',eval_scores[-3])
147
- print('False Positives',eval_scores[-2])
148
- print('False Negatives',eval_scores[-1])
149
- print('incorrect_preds',eval_scores[-4])
150
- print('peaks_not_picked',eval_scores[-5])
151
- test_outputs.append(eval_scores)
152
- print(f'file_score:{eval_scores[0]}')
153
- result_collector.add_result(test_params, eval_scores[0])
154
-
155
- param_key = tuple(
156
- test_params[key] if key != 'test_dict' else test_params['test_dict']['name']
157
- for key in test_params
158
- )
159
- result_collector.check_performance(test_dict['name'], param_key, eval_scores[0])
160
- print("Adding results to collector") # Debug print
161
- print(f'avg_score:{np.mean([x[0] for x in test_outputs])}')
162
- assert np.mean([x[0] for x in test_outputs])>AVG_THRESHOLD
File without changes
File without changes
File without changes