CoreMS 4.0.0__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.
Files changed (171) hide show
  1. corems/__init__.py +63 -0
  2. corems/chroma_peak/__init__.py +0 -0
  3. corems/chroma_peak/calc/ChromaPeakCalc.py +480 -0
  4. corems/chroma_peak/calc/__init__.py +0 -0
  5. corems/chroma_peak/calc/subset.py +196 -0
  6. corems/chroma_peak/factory/__init__.py +0 -0
  7. corems/chroma_peak/factory/chroma_peak_classes.py +1178 -0
  8. corems/encapsulation/__init__.py +0 -0
  9. corems/encapsulation/constant.py +1283 -0
  10. corems/encapsulation/factory/__init__.py +0 -0
  11. corems/encapsulation/factory/parameters.py +392 -0
  12. corems/encapsulation/factory/processingSetting.py +1244 -0
  13. corems/encapsulation/input/__init__.py +0 -0
  14. corems/encapsulation/input/parameter_from_json.py +579 -0
  15. corems/encapsulation/output/__init__.py +0 -0
  16. corems/encapsulation/output/parameter_to_dict.py +142 -0
  17. corems/encapsulation/output/parameter_to_json.py +332 -0
  18. corems/mass_spectra/__init__.py +0 -0
  19. corems/mass_spectra/calc/GC_Calc.py +84 -0
  20. corems/mass_spectra/calc/GC_Deconvolution.py +558 -0
  21. corems/mass_spectra/calc/GC_RI_Calibration.py +44 -0
  22. corems/mass_spectra/calc/MZSearch.py +249 -0
  23. corems/mass_spectra/calc/SignalProcessing.py +656 -0
  24. corems/mass_spectra/calc/__init__.py +0 -0
  25. corems/mass_spectra/calc/lc_calc.py +5790 -0
  26. corems/mass_spectra/calc/lc_calc_operations.py +1127 -0
  27. corems/mass_spectra/factory/GC_Class.py +791 -0
  28. corems/mass_spectra/factory/__init__.py +0 -0
  29. corems/mass_spectra/factory/chromat_data.py +51 -0
  30. corems/mass_spectra/factory/lc_class.py +2721 -0
  31. corems/mass_spectra/input/__init__.py +0 -0
  32. corems/mass_spectra/input/andiNetCDF.py +200 -0
  33. corems/mass_spectra/input/boosterHDF5.py +216 -0
  34. corems/mass_spectra/input/brukerSolarix.py +153 -0
  35. corems/mass_spectra/input/brukerSolarix_utils.py +73 -0
  36. corems/mass_spectra/input/corems_hdf5.py +1710 -0
  37. corems/mass_spectra/input/massList.py +133 -0
  38. corems/mass_spectra/input/mzml.py +668 -0
  39. corems/mass_spectra/input/parserbase.py +239 -0
  40. corems/mass_spectra/input/rawFileReader.py +1839 -0
  41. corems/mass_spectra/output/__init__.py +0 -0
  42. corems/mass_spectra/output/export.py +2800 -0
  43. corems/mass_spectrum/__init__.py +0 -0
  44. corems/mass_spectrum/calc/AutoRecalibration.py +237 -0
  45. corems/mass_spectrum/calc/Calibration.py +602 -0
  46. corems/mass_spectrum/calc/CalibrationCalc.py +253 -0
  47. corems/mass_spectrum/calc/KendrickGroup.py +239 -0
  48. corems/mass_spectrum/calc/MassErrorPrediction.py +436 -0
  49. corems/mass_spectrum/calc/MassSpectrumCalc.py +303 -0
  50. corems/mass_spectrum/calc/MeanResolvingPowerFilter.py +212 -0
  51. corems/mass_spectrum/calc/NoiseCalc.py +371 -0
  52. corems/mass_spectrum/calc/NoiseCalc_Bayes.py +93 -0
  53. corems/mass_spectrum/calc/PeakPicking.py +994 -0
  54. corems/mass_spectrum/calc/__init__.py +0 -0
  55. corems/mass_spectrum/factory/MassSpectrumClasses.py +1753 -0
  56. corems/mass_spectrum/factory/__init__.py +0 -0
  57. corems/mass_spectrum/input/__init__.py +0 -0
  58. corems/mass_spectrum/input/baseClass.py +531 -0
  59. corems/mass_spectrum/input/boosterHDF5.py +161 -0
  60. corems/mass_spectrum/input/coremsHDF5.py +475 -0
  61. corems/mass_spectrum/input/massList.py +402 -0
  62. corems/mass_spectrum/input/numpyArray.py +133 -0
  63. corems/mass_spectrum/output/__init__.py +0 -0
  64. corems/mass_spectrum/output/export.py +841 -0
  65. corems/molecular_formula/__init__.py +0 -0
  66. corems/molecular_formula/calc/MolecularFormulaCalc.py +885 -0
  67. corems/molecular_formula/calc/__init__.py +0 -0
  68. corems/molecular_formula/factory/MolecularFormulaFactory.py +895 -0
  69. corems/molecular_formula/factory/__init__.py +0 -0
  70. corems/molecular_formula/input/__init__.py +0 -0
  71. corems/molecular_formula/input/masslist_ref.py +355 -0
  72. corems/molecular_id/__init__.py +0 -0
  73. corems/molecular_id/calc/ClusterFilter.py +251 -0
  74. corems/molecular_id/calc/MolecularFilter.py +122 -0
  75. corems/molecular_id/calc/SpectralSimilarity.py +632 -0
  76. corems/molecular_id/calc/__init__.py +0 -0
  77. corems/molecular_id/calc/math_distance.py +1637 -0
  78. corems/molecular_id/data/FAMES_REF.msp +980 -0
  79. corems/molecular_id/data/PNNLMetV20191015.msp +157267 -0
  80. corems/molecular_id/factory/EI_SQL.py +650 -0
  81. corems/molecular_id/factory/MolecularLookupTable.py +914 -0
  82. corems/molecular_id/factory/__init__.py +0 -0
  83. corems/molecular_id/factory/classification.py +884 -0
  84. corems/molecular_id/factory/lipid_molecular_metadata.py +50 -0
  85. corems/molecular_id/factory/molecularSQL.py +827 -0
  86. corems/molecular_id/factory/spectrum_search_results.py +119 -0
  87. corems/molecular_id/input/__init__.py +0 -0
  88. corems/molecular_id/input/nistMSI.py +148 -0
  89. corems/molecular_id/search/__init__.py +0 -0
  90. corems/molecular_id/search/compoundSearch.py +214 -0
  91. corems/molecular_id/search/database_interfaces.py +1527 -0
  92. corems/molecular_id/search/findOxygenPeaks.py +330 -0
  93. corems/molecular_id/search/lcms_spectral_search.py +348 -0
  94. corems/molecular_id/search/molecularFormulaSearch.py +1117 -0
  95. corems/molecular_id/search/priorityAssignment.py +723 -0
  96. corems/ms_peak/__init__.py +0 -0
  97. corems/ms_peak/calc/MSPeakCalc.py +1010 -0
  98. corems/ms_peak/calc/__init__.py +0 -0
  99. corems/ms_peak/factory/MSPeakClasses.py +542 -0
  100. corems/ms_peak/factory/__init__.py +0 -0
  101. corems/transient/__init__.py +0 -0
  102. corems/transient/calc/TransientCalc.py +362 -0
  103. corems/transient/calc/__init__.py +0 -0
  104. corems/transient/factory/TransientClasses.py +457 -0
  105. corems/transient/factory/__init__.py +0 -0
  106. corems/transient/input/__init__.py +0 -0
  107. corems/transient/input/brukerSolarix.py +461 -0
  108. corems/transient/input/midasDatFile.py +172 -0
  109. corems-4.0.0.dist-info/METADATA +475 -0
  110. corems-4.0.0.dist-info/RECORD +171 -0
  111. corems-4.0.0.dist-info/WHEEL +5 -0
  112. corems-4.0.0.dist-info/licenses/LICENSE +22 -0
  113. corems-4.0.0.dist-info/top_level.txt +4 -0
  114. examples/archive/scripts/CoreMS_tutorial.py +94 -0
  115. examples/archive/scripts/DI HR-MS Halogens Bruker.py +196 -0
  116. examples/archive/scripts/DI HR-MS MassList.py +385 -0
  117. examples/archive/scripts/GC-MS MetabRef.py +213 -0
  118. examples/archive/scripts/GC-MS NetCDF.py +217 -0
  119. examples/archive/scripts/HR-MS Thermo Raw 21T.py +136 -0
  120. examples/archive/scripts/LC-ICPMS_metal_peaks.py +297 -0
  121. examples/archive/scripts/LCMS-Thermo.py +460 -0
  122. examples/archive/scripts/LCMS_isotopes.py +283 -0
  123. examples/archive/scripts/MSParams_example.py +21 -0
  124. examples/archive/scripts/Molecular Formula Data Aggreation.py +84 -0
  125. examples/archive/scripts/Single Mz Search.py +69 -0
  126. examples/test_notebooks.py +145 -0
  127. ext_lib/ChemstationMSFileReader.dll +0 -0
  128. ext_lib/ChemstationMSFileReader.xml +126 -0
  129. ext_lib/RawFileReaderLicense.doc +0 -0
  130. ext_lib/ThermoFisher.CommonCore.BackgroundSubtraction.dll +0 -0
  131. ext_lib/ThermoFisher.CommonCore.BackgroundSubtraction.xml +2307 -0
  132. ext_lib/ThermoFisher.CommonCore.Data.dll +0 -0
  133. ext_lib/ThermoFisher.CommonCore.Data.xml +28974 -0
  134. ext_lib/ThermoFisher.CommonCore.MassPrecisionEstimator.dll +0 -0
  135. ext_lib/ThermoFisher.CommonCore.MassPrecisionEstimator.xml +241 -0
  136. ext_lib/ThermoFisher.CommonCore.RawFileReader.dll +0 -0
  137. ext_lib/ThermoFisher.CommonCore.RawFileReader.xml +31174 -0
  138. ext_lib/__init__.py +0 -0
  139. ext_lib/dotnet/OpenMcdf.Extensions.dll +0 -0
  140. ext_lib/dotnet/OpenMcdf.dll +0 -0
  141. ext_lib/dotnet/OpenMcdf.xml +1154 -0
  142. ext_lib/dotnet/System.IO.FileSystem.AccessControl.dll +0 -0
  143. ext_lib/dotnet/System.IO.FileSystem.AccessControl.xml +506 -0
  144. ext_lib/dotnet/System.Security.AccessControl.dll +0 -0
  145. ext_lib/dotnet/System.Security.AccessControl.xml +2043 -0
  146. ext_lib/dotnet/System.Security.Principal.Windows.dll +0 -0
  147. ext_lib/dotnet/System.Security.Principal.Windows.xml +1011 -0
  148. ext_lib/dotnet/ThermoFisher.CommonCore.BackgroundSubtraction.dll +0 -0
  149. ext_lib/dotnet/ThermoFisher.CommonCore.BackgroundSubtraction.xml +2307 -0
  150. ext_lib/dotnet/ThermoFisher.CommonCore.Data.dll +0 -0
  151. ext_lib/dotnet/ThermoFisher.CommonCore.Data.xml +29148 -0
  152. ext_lib/dotnet/ThermoFisher.CommonCore.MassPrecisionEstimator.dll +0 -0
  153. ext_lib/dotnet/ThermoFisher.CommonCore.MassPrecisionEstimator.xml +241 -0
  154. ext_lib/dotnet/ThermoFisher.CommonCore.RawFileReader.dll +0 -0
  155. ext_lib/dotnet/ThermoFisher.CommonCore.RawFileReader.xml +31492 -0
  156. ext_lib/version +18 -0
  157. support_code/atom_parsers/AtomsDescription.py +359 -0
  158. support_code/atom_parsers/CreateAtomsDescription.py +56 -0
  159. support_code/nmdc/filefinder.py +90 -0
  160. support_code/nmdc/lipidomics/lipidomics_workflow.py +748 -0
  161. support_code/nmdc/lipidomics/manifest_examples.py +49 -0
  162. support_code/nmdc/metabolomics/gcms_workflow.py +158 -0
  163. support_code/nmdc/metabolomics/lcms_metabolomics_targeted_search.py +59 -0
  164. support_code/nmdc/metabolomics/lcms_metabolomics_workflow.py +248 -0
  165. support_code/nmdc/metabolomics/metabolomics_collection.py +628 -0
  166. support_code/nmdc/metadata/dms_api.py +42 -0
  167. support_code/nmdc/nom/archived_scripts/nmdc_metadata_gen.py +288 -0
  168. support_code/nmdc/nom/archived_scripts/nom_grow_workflow.py +209 -0
  169. support_code/nmdc/nom/nom_workflow.py +312 -0
  170. support_code/windows_only_importers/BrukerCompassXtract.py +180 -0
  171. support_code/windows_only_importers/ThermoMSFileReader.py +405 -0
@@ -0,0 +1,650 @@
1
+ __author__ = "Yuri E. Corilo"
2
+ __date__ = "Feb 12, 2020"
3
+
4
+ import os
5
+ from dataclasses import dataclass
6
+ from typing import Optional
7
+
8
+ from numpy import array, frombuffer
9
+ from sqlalchemy import (
10
+ Column,
11
+ Float,
12
+ ForeignKey,
13
+ Integer,
14
+ LargeBinary,
15
+ String,
16
+ create_engine,
17
+ )
18
+ from sqlalchemy.exc import SQLAlchemyError
19
+ from sqlalchemy.orm import declarative_base
20
+ from sqlalchemy.orm import relationship, sessionmaker
21
+ from sqlalchemy.pool import QueuePool
22
+
23
+ Base = declarative_base()
24
+
25
+
26
+ class Metadatar(Base):
27
+ """This class is used to store the metadata of the compounds in the database
28
+
29
+ Attributes
30
+ -----------
31
+ id : int
32
+ The id of the compound.
33
+ cas : str
34
+ The CAS number of the compound.
35
+ inchikey : str
36
+ The InChiKey of the compound.
37
+ inchi : str
38
+ The InChi of the compound.
39
+ chebi : str
40
+ The ChEBI ID of the compound.
41
+ smiles : str
42
+ The SMILES of the compound.
43
+ kegg : str
44
+ The KEGG ID of the compound.
45
+ iupac_name : str
46
+ The IUPAC name of the compound.
47
+ traditional_name : str
48
+ The traditional name of the compound.
49
+ common_name : str
50
+ The common name of the compound.
51
+ data_id : int
52
+ The id of the compound in the molecularData table.
53
+ data : LowResolutionEICompound
54
+ The compound object.
55
+ """
56
+
57
+ __tablename__ = "metaDataR"
58
+
59
+ id = Column(Integer, primary_key=True)
60
+ cas = Column(String, nullable=True)
61
+ inchikey = Column(String, nullable=False)
62
+ inchi = Column(String, nullable=False)
63
+ chebi = Column(String, nullable=True)
64
+ smiles = Column(String, nullable=True)
65
+ kegg = Column(String, nullable=True)
66
+ iupac_name = Column(String, nullable=True)
67
+ traditional_name = Column(String, nullable=True)
68
+ common_name = Column(String, nullable=True)
69
+
70
+ data_id = Column(Integer, ForeignKey("molecularData.id"))
71
+ data = relationship("LowResolutionEICompound", back_populates="metadatar")
72
+
73
+
74
+ class LowResolutionEICompound(Base):
75
+ """This class is used to store the molecular and spectral data of the compounds in the low res EI database
76
+
77
+ Attributes
78
+ -----------
79
+ id : int
80
+ The id of the compound.
81
+ name : str
82
+ The name of the compound.
83
+ classify : str
84
+ The classification of the compound.
85
+ formula : str
86
+ The formula of the compound.
87
+ ri : float
88
+ The retention index of the compound.
89
+ retention_time : float
90
+ The retention time of the compound.
91
+ source : str
92
+ The source of the compound.
93
+ casno : str
94
+ The CAS number of the compound.
95
+ comment : str
96
+ The comment of the compound.
97
+ source_temp_c : float
98
+ The source temperature of the spectra.
99
+ ev : float
100
+ The electron volts of the spectra.
101
+ peaks_count : int
102
+ The number of peaks in the spectra.
103
+ mz : numpy.ndarray
104
+ The m/z values of the spectra.
105
+ abundance : numpy.ndarray
106
+ The abundance values of the spectra.
107
+ metadatar : Metadatar
108
+ The metadata object.
109
+ """
110
+
111
+ __tablename__ = "molecularData"
112
+
113
+ id = Column(Integer, primary_key=True)
114
+
115
+ name = Column(String, nullable=False)
116
+ classify = Column(String, nullable=True)
117
+ formula = Column(String, nullable=True)
118
+ ri = Column(Float, nullable=False)
119
+ retention_time = Column(Float, nullable=False)
120
+
121
+ source = Column(String, nullable=True)
122
+ casno = Column(String, nullable=False)
123
+ comment = Column(String, nullable=True)
124
+
125
+ derivativenum = Column(String, nullable=True)
126
+ derivatization = Column(String, nullable=True)
127
+
128
+ source_temp_c = Column(Float, nullable=True)
129
+ ev = Column(Float, nullable=True)
130
+
131
+ peaks_count = Column(Integer, nullable=False)
132
+
133
+ mz = Column(LargeBinary, nullable=False)
134
+ abundance = Column(LargeBinary, nullable=False)
135
+
136
+ metadatar = relationship("Metadatar", uselist=False, back_populates="data")
137
+
138
+ # metadatar = relationship('Metadatar', backref='smile', lazy='dynamic')
139
+
140
+ def __init__(self, **dict_data):
141
+ self.id = dict_data.get("id")
142
+
143
+ self.name = dict_data.get("NAME")
144
+ self.classify = dict_data.get("classify")
145
+ self.formula = dict_data.get("FORM")
146
+ self.ri = dict_data.get("RI")
147
+ self.retention_time = dict_data.get("RT")
148
+
149
+ self.source = dict_data.get("SOURCE")
150
+ self.casno = dict_data.get("CASNO")
151
+ self.comment = dict_data.get("COMMENT")
152
+
153
+ self.derivativenum = dict_data.get("derivativenum")
154
+ self.derivatization = dict_data.get("derivatization")
155
+
156
+ self.peaks_count = dict_data.get("NUM PEAKS")
157
+
158
+ # mz and abun are numpy arrays of 64 bits integer
159
+ # when using postgres array might be a better option
160
+
161
+ self.mz = array(dict_data.get("mz"), dtype="int32").tobytes()
162
+ self.abundance = array(dict_data.get("abundance"), dtype="int32").tobytes()
163
+
164
+ self.metadatar = dict_data.get("metadatar", None)
165
+
166
+ def __repr__(self):
167
+ return (
168
+ "<LowResolutionEICompound(name= %s , cas number = %s, formula = %s, Retention index= %.1f, Retention time= %.1f comment='%s')>"
169
+ % (
170
+ self.name,
171
+ self.casno,
172
+ self.formula,
173
+ self.ri,
174
+ self.retention_time,
175
+ self.comment,
176
+ )
177
+ )
178
+
179
+
180
+ @dataclass
181
+ class MetaboliteMetadata:
182
+ """Dataclass for the Metabolite Metadata
183
+
184
+ Attributes
185
+ -----------
186
+ id : int
187
+ The id of the compound.
188
+ cas : str
189
+ The CAS number of the compound.
190
+ inchikey : str
191
+ The InChiKey of the compound.
192
+ inchi : str
193
+ The InChi of the compound.
194
+ chebi : str
195
+ The ChEBI ID of the compound.
196
+ smiles : str
197
+ The SMILES of the compound.
198
+ kegg : str
199
+ The KEGG ID of the compound.
200
+ iupac_name : str
201
+ The IUPAC name of the compound.
202
+ traditional_name : str
203
+ The traditional name of the compound.
204
+ common_name : str
205
+ The common name of the compound, preferrably the RefMet name.
206
+ data_id : int
207
+ The id of the compound in the molecularData table.
208
+ name : Optional[str]
209
+ The name of the compound, preferably the same name as in PubChem,
210
+ Or if a lipid, name as in LipidMaps
211
+ formula : Optional[str]
212
+ The formula of the compound.
213
+ pubchem_id : Optional[str]
214
+ The PubChem ID of the compound.
215
+ refmet_id : Optional[str]
216
+ The RefMet ID of the compound.
217
+ """
218
+
219
+ id: int
220
+ cas: str
221
+ inchikey: str
222
+ inchi: str
223
+ chebi: str
224
+ smiles: str
225
+ kegg: str
226
+ data_id: int
227
+ iupac_name: str
228
+ traditional_name: str
229
+ common_name: str
230
+ name: Optional[str]=None
231
+ formula: Optional[str]=None
232
+ pubchem_id: Optional[str]=None
233
+ refmet_id: Optional[str]=None
234
+
235
+
236
+ @dataclass
237
+ class LowResCompoundRef:
238
+ """Dataclass for the Low Resolution Compound Reference
239
+
240
+ This class is used to store the molecular and spectral data of the compounds in the low res EI database
241
+
242
+ Parameters
243
+ -----------
244
+ compounds_dict : dict
245
+ A dictionary representing the compound.
246
+
247
+ Attributes
248
+ -----------
249
+ id : int
250
+ The id of the compound.
251
+ name : str
252
+ The name of the compound.
253
+ ri : str
254
+ The retention index of the compound.
255
+ retention_time : str
256
+ The retention time of the compound.
257
+ casno : str
258
+ The CAS number of the compound.
259
+ comment : str
260
+ The comment of the compound.
261
+ peaks_count : int
262
+ The number of peaks in the spectra.
263
+ classify : str
264
+ The classification of the compound.
265
+ derivativenum : str
266
+ The derivative number of the compound.
267
+ derivatization : str
268
+ The derivatization applied to the compound.
269
+ mz : numpy.ndarray
270
+ The m/z values of the spectra.
271
+ abundance : numpy.ndarray
272
+ The abundance values of the spectra.
273
+ source_temp_c : float
274
+ The source temperature of the spectra.
275
+ ev : float
276
+ The electron volts of the spectra.
277
+ formula : str
278
+ The formula of the compound.
279
+ source : str
280
+ The source of the spectra data.
281
+ classify : str
282
+ The classification of the compound.
283
+ metadata : MetaboliteMetadata
284
+ The metadata object.
285
+ similarity_score : float
286
+ The similarity score of the compound.
287
+ ri_score : float
288
+ The RI score of the compound.
289
+ spectral_similarity_score : float
290
+ The spectral similarity score of the compound.
291
+ spectral_similarity_scores : dict
292
+ The spectral similarity scores of the compound.
293
+
294
+ """
295
+
296
+ # this class is use to store the results inside the GCPeak class
297
+ def __init__(self, compounds_dict):
298
+ self.id = compounds_dict.get("id")
299
+ self.name = compounds_dict.get("name")
300
+ self.ri = compounds_dict.get("ri")
301
+ self.retention_time = compounds_dict.get("rt")
302
+ self.casno = compounds_dict.get("casno")
303
+ self.comment = compounds_dict.get("comment")
304
+ self.peaks_count = compounds_dict.get("peaks_count")
305
+
306
+ self.classify = compounds_dict.get("classify")
307
+ self.derivativenum = compounds_dict.get("derivativenum")
308
+ self.derivatization = compounds_dict.get("derivatization")
309
+
310
+ self.mz = compounds_dict.get("mz")
311
+ self.abundance = compounds_dict.get("abundance")
312
+
313
+ self.source_temp_c = compounds_dict.get("source_temp_c")
314
+ self.ev = compounds_dict.get("ev")
315
+ self.formula = compounds_dict.get("formula")
316
+ self.source = compounds_dict.get("source")
317
+
318
+ self.classify = compounds_dict.get("classify")
319
+
320
+ if compounds_dict.get("metadata"):
321
+ self.metadata = MetaboliteMetadata(**compounds_dict.get("metadata"))
322
+
323
+ else:
324
+ self.metadata = None
325
+
326
+ self.similarity_score = None
327
+ self.ri_score = None
328
+ self.spectral_similarity_score = None
329
+ self.spectral_similarity_scores = {}
330
+
331
+
332
+ class EI_LowRes_SQLite:
333
+ """
334
+ A class for interacting with a SQLite database for low-resolution EI compounds.
335
+
336
+ Parameters
337
+ -----------
338
+ url : str, optional
339
+ The URL of the SQLite database. Default is 'sqlite://'.
340
+
341
+ Attributes
342
+ -----------
343
+ engine : sqlalchemy.engine.Engine
344
+ The SQLAlchemy engine for connecting to the database.
345
+ session : sqlalchemy.orm.Session
346
+ The SQLAlchemy session for executing database operations.
347
+
348
+ Methods
349
+ --------
350
+ * __init__(self, url='sqlite://').
351
+ Initializes the EI_LowRes_SQLite object.
352
+ * __exit__(self, exc_type, exc_val, exc_tb).
353
+ Closes the database connection.
354
+ * init_engine(self, url).
355
+ Initializes the SQLAlchemy engine.
356
+ * __enter__(self).
357
+ Returns the EI_LowRes_SQLite object.
358
+ * add_compound_list(self, data_dict_list).
359
+ Adds a list of compounds to the database.
360
+ * add_compound(self, data_dict).
361
+ Adds a single compound to the database.
362
+ * commit(self).
363
+ Commits the changes to the database.
364
+ * row_to_dict(self, row).
365
+ Converts a database row to a dictionary.
366
+ * get_all(self).
367
+ Retrieves all compounds from the database.
368
+ * query_min_max_rt(self, min_max_rt).
369
+ Queries compounds based on retention time range.
370
+ * query_min_max_ri(self, min_max_ri).
371
+ Queries compounds based on RI range.
372
+ * query_names_and_rt(self, min_max_rt, compound_names).
373
+ Queries compounds based on compound names and retention time range.
374
+ * query_min_max_ri_and_rt(self, min_max_ri, min_max_rt).
375
+ Queries compounds based on RI range and retention time range.
376
+ * delete_compound(self, compound).
377
+ Deletes a compound from the database.
378
+ * purge(self).
379
+ Deletes all compounds from the database table.
380
+ * clear_data(self).
381
+ Clears all tables in the database.
382
+ """
383
+
384
+ def __init__(self, url="sqlite://"):
385
+ self.engine = self.init_engine(url)
386
+
387
+ Base.metadata.create_all(self.engine)
388
+
389
+ Session = sessionmaker(bind=self.engine)
390
+
391
+ self.session = Session()
392
+
393
+ def __exit__(self, exc_type, exc_val, exc_tb):
394
+ """Closes the database connection."""
395
+ self.commit()
396
+ self.session.close()
397
+ self.engine.dispose()
398
+
399
+ def init_engine(self, url):
400
+ """Initializes the SQLAlchemy engine.
401
+
402
+ Parameters
403
+ -----------
404
+ url : str
405
+ The URL of the SQLite database.
406
+
407
+ Returns
408
+ --------
409
+ sqlalchemy.engine.Engine
410
+ The SQLAlchemy engine for connecting to the database.
411
+ """
412
+ directory = os.getcwd()
413
+ if not url:
414
+ if not os.path.isdir(directory + "/db"):
415
+ os.mkdir(directory + "/db")
416
+ url = "sqlite:///{DB}/db/pnnl_lowres_gcms_compounds.sqlite".format(
417
+ DB=directory
418
+ )
419
+ return create_engine(url, poolclass=QueuePool)
420
+
421
+ def __enter__(self):
422
+ """Returns the EI_LowRes_SQLite object."""
423
+ return self
424
+
425
+ def add_compound_list(self, data_dict_list):
426
+ """Adds a list of compounds to the database.
427
+
428
+ Parameters
429
+ -----------
430
+ data_dict_list : list of dict
431
+ A list of dictionaries representing the compounds.
432
+ """
433
+ for data_dict in data_dict_list:
434
+ # print(data_dict.get('NUM PEAKS'))
435
+ if not data_dict.get("NUM PEAKS"):
436
+ data_dict["NUM PEAKS"] = len(data_dict.get("mz"))
437
+ if not data_dict.get("CASNO"):
438
+ data_dict["CASNO"] = data_dict.get("CAS")
439
+
440
+ self.session.add_all(
441
+ [LowResolutionEICompound(**data_dict) for data_dict in data_dict_list]
442
+ )
443
+
444
+ def add_compound(self, data_dict):
445
+ """Adds a single compound to the database.
446
+
447
+ Parameters
448
+ -----------
449
+ data_dict : dict
450
+ A dictionary representing the compound.
451
+
452
+ """
453
+ one_compound = LowResolutionEICompound(**data_dict)
454
+ self.session.add(one_compound)
455
+ self.commit()
456
+
457
+ def commit(self):
458
+ """Commits the changes to the database."""
459
+ try:
460
+ self.session.commit()
461
+ except SQLAlchemyError as e:
462
+ self.session.rollback()
463
+ print(str(e))
464
+
465
+ def row_to_dict(self, row):
466
+ """Converts a database row to a dictionary.
467
+
468
+ Parameters
469
+ -----------
470
+ row : sqlalchemy.engine.row.Row
471
+ A row from the database.
472
+
473
+ Returns
474
+ --------
475
+ dict
476
+ A dictionary representing the compound.
477
+ """
478
+ data_dict = {c.name: getattr(row, c.name) for c in row.__table__.columns}
479
+
480
+ data_dict["mz"] = frombuffer(data_dict.get("mz"), dtype="int32")
481
+ data_dict["abundance"] = frombuffer(data_dict.get("abundance"), dtype="int32")
482
+
483
+ if row.metadatar:
484
+ data_dict["metadata"] = {
485
+ c.name: getattr(row.metadatar, c.name)
486
+ for c in row.metadatar.__table__.columns
487
+ }
488
+
489
+ else:
490
+ data_dict["metadata"] = None
491
+
492
+ return data_dict
493
+
494
+ def get_all(
495
+ self,
496
+ ):
497
+ """Retrieves all compounds from the database.
498
+
499
+ Returns
500
+ --------
501
+ list
502
+ A list of dictionaries representing the compounds.
503
+ """
504
+ compounds = self.session.query(LowResolutionEICompound).all()
505
+
506
+ return [self.row_to_dict(compound) for compound in compounds]
507
+
508
+ def query_min_max_rt(
509
+ self,
510
+ min_max_rt,
511
+ ):
512
+ """Queries compounds based on retention time range.
513
+
514
+ Parameters
515
+ -----------
516
+ min_max_rt : tuple
517
+ A tuple containing the minimum and maximum retention time values.
518
+
519
+ Returns
520
+ --------
521
+ list
522
+ A list of dictionaries representing the compounds.
523
+ """
524
+ min_rt, max_rt = min_max_rt
525
+
526
+ compounds = self.session.query(LowResolutionEICompound).filter(
527
+ LowResolutionEICompound.retention_time.between(min_rt, max_rt)
528
+ )
529
+
530
+ return [self.row_to_dict(compound) for compound in compounds]
531
+
532
+ def query_min_max_ri(self, min_max_ri):
533
+ """Queries compounds based on RI range.
534
+
535
+ Parameters
536
+ -----------
537
+ min_max_ri : tuple
538
+ A tuple containing the minimum and maximum RI values.
539
+ """
540
+ min_ri, max_ri = min_max_ri
541
+
542
+ compounds = (
543
+ self.session.query(LowResolutionEICompound)
544
+ .filter(LowResolutionEICompound.ri.between(min_ri, max_ri))
545
+ .all()
546
+ )
547
+
548
+ return [self.row_to_dict(compound) for compound in compounds]
549
+
550
+ def query_names_and_rt(self, min_max_rt, compound_names):
551
+ """Queries compounds based on compound names and retention time range.
552
+
553
+ Parameters
554
+ -----------
555
+ min_max_rt : tuple
556
+ A tuple containing the minimum and maximum retention time values.
557
+ compound_names : list
558
+ A list of compound names.
559
+
560
+ Returns
561
+ --------
562
+ list
563
+ A list of dictionaries representing the compounds.
564
+
565
+ """
566
+ min_rt, max_rt = min_max_rt
567
+
568
+ compounds = (
569
+ self.session.query(LowResolutionEICompound)
570
+ .filter(LowResolutionEICompound.name.in_(compound_names))
571
+ .filter(
572
+ LowResolutionEICompound.retention_time >= min_rt,
573
+ LowResolutionEICompound.retention_time <= max_rt,
574
+ )
575
+ )
576
+
577
+ # self.session.query.select(LowResolutionEICompound).where(between(LowResolutionEICompound.ri, min_ri, max_ri))
578
+ # x = [self.row_to_dict(compound) for compound in compounds]
579
+
580
+ return [self.row_to_dict(compound) for compound in compounds]
581
+
582
+ def query_min_max_ri_and_rt(
583
+ self,
584
+ min_max_ri,
585
+ min_max_rt,
586
+ ):
587
+ """Queries compounds based on RI range and retention time range.
588
+
589
+ Parameters
590
+ -----------
591
+ min_max_ri : tuple
592
+ A tuple containing the minimum and maximum RI values.
593
+ min_max_rt : tuple
594
+ A tuple containing the minimum and maximum retention time values.
595
+
596
+ Returns
597
+ --------
598
+ list
599
+ A list of dictionaries representing the compounds.
600
+
601
+ """
602
+ min_ri, max_ri = min_max_ri
603
+
604
+ min_rt, max_rt = min_max_rt
605
+
606
+ compounds = self.session.query(LowResolutionEICompound).filter(
607
+ LowResolutionEICompound.ri <= max_ri,
608
+ LowResolutionEICompound.ri >= min_ri,
609
+ LowResolutionEICompound.ri >= min_rt,
610
+ LowResolutionEICompound.ri >= max_rt,
611
+ )
612
+
613
+ # self.session.query.select(LowResolutionEICompound).where(between(LowResolutionEICompound.ri, min_ri, max_ri))
614
+
615
+ return [self.row_to_dict(compound) for compound in compounds]
616
+
617
+ def delete_compound(self, compound):
618
+ """Deletes a compound from the database.
619
+
620
+ Parameters
621
+ -----------
622
+ compound : LowResolutionEICompound
623
+ A compound object.
624
+
625
+ """
626
+ try:
627
+ self.session.delete(compound)
628
+ self.session.commit()
629
+
630
+ except SQLAlchemyError as e:
631
+ self.session.rollback()
632
+ print(str(e))
633
+
634
+ def purge(self):
635
+ """Deletes all compounds from the database table.
636
+
637
+ Notes
638
+ ------
639
+ Careful, this will delete the entire database table.
640
+ """
641
+ self.session.query(LowResolutionEICompound).delete()
642
+ self.session.commit()
643
+
644
+ def clear_data(self):
645
+ """Clears all tables in the database."""
646
+ meta = Base.metadata
647
+ for table in reversed(meta.sorted_tables):
648
+ print("Clear table %s" % table)
649
+ self.session.execute(table.delete())
650
+ self.session.commit()