IsoSpecPy 2.4.0__cp315-cp315-win32.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.
IsoSpecPy/IsoSpecPy.py ADDED
@@ -0,0 +1,924 @@
1
+ # -*- coding: utf-8 -*-
2
+ #
3
+ # Copyright (C) 2015-2020 Mateusz Łącki and Michał Startek.
4
+ #
5
+ # This file is part of IsoSpec.
6
+ #
7
+ # IsoSpec is free software: you can redistribute it and/or modify
8
+ # it under the terms of the Simplified ("2-clause") BSD licence.
9
+ #
10
+ # IsoSpec is distributed in the hope that it will be useful,
11
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
+ #
14
+ # You should have received a copy of the Simplified BSD Licence
15
+ # along with IsoSpec. If not, see <https://opensource.org/licenses/BSD-2-Clause>.
16
+ #
17
+
18
+ from .isoFFI import isoFFI
19
+ import re
20
+ import types
21
+ from . import PeriodicTbl
22
+ from .confs_passthrough import ConfsPassthrough
23
+ from collections import namedtuple, OrderedDict
24
+ import math
25
+
26
+ regex_pattern = re.compile('([A-Z][a-z]?)(-?[0-9]*)')
27
+ ParsedFormula = namedtuple('ParsedFormula', 'atomCounts masses probs elems')
28
+
29
+
30
+
31
+
32
+ def ParseFormula(formula):
33
+ """Parse a chemical formula.
34
+
35
+ Args:
36
+ formula (str): a chemical formula, e.g. "C2H6O1" or "C2H6O"
37
+
38
+ Returns:
39
+ A tuple containing element symbols and atomCounts of elements in the parsed formula.
40
+ """
41
+ global regex_pattern
42
+
43
+ ret = OrderedDict()
44
+
45
+ last = 0
46
+ for match in re.finditer(regex_pattern, formula):
47
+ elem, cnt = match.groups()
48
+ if elem in ret:
49
+ raise ValueError("""Invalid formula: {} (repeating element: "{}")""".format(formula, elem))
50
+ ret[elem] = int(cnt) if cnt != '' else 1
51
+ if last!=match.start():
52
+ raise ValueError("""Invalid formula: {} (garbage inside: "{}")""".format(formula, formula[last:match.start()]))
53
+ if elem not in PeriodicTbl.symbol_to_masses:
54
+ raise ValueError("""Invalid formula: {} (unknown element symbol: "{}")""".format(formula, elem))
55
+ last = match.end()
56
+
57
+ if len(formula) != last:
58
+ raise ValueError('''Invalid formula: {} (trailing garbage: "{}")'''.format(formula, formula[last:]))
59
+
60
+ if len(ret) == 0:
61
+ raise ValueError("Invalid formula (empty)")
62
+
63
+ return ret
64
+
65
+ def ParseFASTA(fasta):
66
+ if isinstance(fasta, str):
67
+ fasta = fasta.encode("ascii")
68
+ fasta_parsing_space = isoFFI.ffi.new("int[6]")
69
+ isoFFI.clib.parse_fasta_c(fasta, fasta_parsing_space)
70
+ elements = list("CHNOS")
71
+ if fasta_parsing_space[5] > 0:
72
+ elements.append("Se")
73
+ od = OrderedDict()
74
+ for i in range(len(elements)):
75
+ od[elements[i]] = fasta_parsing_space[i]
76
+ return od
77
+
78
+
79
+ def IsoParamsFromDict(formula, use_nominal_masses = False):
80
+ """Produces a set of IsoSpec parameters from a chemical formula.
81
+
82
+ Args:
83
+ formula (dict): a parsed chemical formula, e.g. {"C": 2, "H": 6, "O": 1}
84
+ use_nominal_masses (boolean): use masses of elements rounded to integer numbers (nominal masses)
85
+
86
+ Returns:
87
+ ParsedFormula: a tuple containing atomCounts, masses and marginal probabilities of elements in the parsed formula.
88
+ """
89
+
90
+ symbols, atomCounts = [], []
91
+ for symbol, atomCount in formula.items():
92
+ symbols.append(symbol)
93
+ atomCounts.append(atomCount)
94
+
95
+ try:
96
+ if use_nominal_masses:
97
+ masses = [PeriodicTbl.symbol_to_massNo[s] for s in symbols]
98
+ else:
99
+ masses = [PeriodicTbl.symbol_to_masses[s] for s in symbols]
100
+ probs = [PeriodicTbl.symbol_to_probs[s] for s in symbols]
101
+ except KeyError:
102
+ raise ValueError("Invalid formula")
103
+
104
+ return ParsedFormula(atomCounts, masses, probs, symbols)
105
+
106
+
107
+ def IsoParamsFromFormula(formula, use_nominal_masses = False):
108
+ """Produces a set of IsoSpec parameters from a chemical formula.
109
+
110
+ Args:
111
+ formula (str): a chemical formula, e.g. "C2H6O1" or "C2H6O"
112
+ use_nominal_masses (boolean): use masses of elements rounded to integer numbers (nominal masses)
113
+
114
+ Returns:
115
+ ParsedFormula: a tuple containing atomCounts, masses and marginal probabilities of elements in the parsed formula.
116
+ """
117
+ parsed = ParseFormula(formula)
118
+ return IsoParamsFromDict(parsed, use_nominal_masses = use_nominal_masses)
119
+
120
+
121
+ class Iso(object):
122
+ """Virtual class representing an isotopic distribution."""
123
+ def __init__(self, formula="",
124
+ get_confs=False,
125
+ atomCounts=None,
126
+ isotopeMasses=None,
127
+ isotopeProbabilities=None,
128
+ use_nominal_masses = False,
129
+ fasta = "",
130
+ charge = 1.0):
131
+ """Initialize Iso.
132
+
133
+ Args:
134
+ formula (str): a chemical formula, e.g. "C2H6O1" or "C2H6O".
135
+ get_confs (boolean): should we report counts of isotopologues?
136
+ atomCounts (list): a list of atom counts (alternative to 'formula').
137
+ isotopeMasses (list): a list of lists of masses of elements with counts in 'atomCounts'.
138
+ isotopeProbabilities (list): a list of lists of probabilities of elements with counts in 'atomCounts'.
139
+ use_nominal_masses (boolean): should the masses be rounded to the closest integer values.
140
+ charge (float): charge state of the molecule: all masses will be divided by this value to obtain the m/z values.
141
+ """
142
+
143
+ self.iso = None
144
+
145
+ if len(fasta) > 0:
146
+ molecule = ParseFASTA(fasta)
147
+ else:
148
+ molecule = OrderedDict()
149
+
150
+ if len(formula) > 0:
151
+ if isinstance(formula, dict):
152
+ df = formula
153
+ else:
154
+ df = ParseFormula(formula)
155
+ for symbol, count in df.items():
156
+ molecule[symbol] = molecule.get(symbol, 0) + count
157
+
158
+ for sym, cnt in molecule.items():
159
+ if cnt < 0:
160
+ raise Exception("Negative count of element " + sym + ": " + str(cnt))
161
+
162
+ if len(molecule) == 0 and not all([atomCounts, isotopeMasses, isotopeProbabilities]):
163
+ raise Exception("Either formula, fasta or ALL of: atomCounts, isotopeMasses, isotopeProbabilities must not be None")
164
+
165
+ if len(molecule) > 0:
166
+ self.atomCounts, self.isotopeMasses, self.isotopeProbabilities, _ = IsoParamsFromDict(molecule, use_nominal_masses = use_nominal_masses)
167
+ else:
168
+ self.atomCounts, self.isotopeMasses, self.isotopeProbabilities = [], [], []
169
+
170
+ if not (atomCounts is None):
171
+ self.atomCounts.extend(atomCounts)
172
+
173
+ if not (isotopeMasses is None):
174
+ self.isotopeMasses.extend(isotopeMasses)
175
+
176
+ if not (isotopeProbabilities is None):
177
+ self.isotopeProbabilities.extend(isotopeProbabilities)
178
+
179
+ for sublist in self.isotopeProbabilities:
180
+ for prob in sublist:
181
+ if not (0.0 < prob <= 1.0):
182
+ raise ValueError("All isotope probabilities p must fulfill: 0.0 < p <= 1.0")
183
+
184
+ self.isotopeNumbers = tuple(map(len, self.isotopeMasses))
185
+ if self.isotopeNumbers != tuple(map(len, self.isotopeProbabilities)):
186
+ raise ValueError("isotopeMasses and isotopeProbabilities must have the same number of isotopes per element")
187
+ if len(self.atomCounts) != len(self.isotopeNumbers) or len(self.isotopeNumbers) != len(self.isotopeProbabilities):
188
+ raise ValueError("atomCounts, isotopeMasses, and isotopeProbabilities must all have the same length")
189
+
190
+ self.dimNumber = len(self.isotopeNumbers)
191
+
192
+ self.get_confs = get_confs
193
+ self.ffi = isoFFI.clib
194
+
195
+ offsets = []
196
+
197
+ i = 0
198
+ for j in range(self.dimNumber):
199
+ newl = []
200
+ for k in range(self.isotopeNumbers[j]):
201
+ newl.append(i)
202
+ i += 1
203
+ offsets.append(tuple(newl))
204
+ self.offsets = tuple(offsets)
205
+
206
+ # "int[]" (open array) + a separate count keeps this call to a single,
207
+ # fixed type string cached after its first use, instead of parsing a
208
+ # fresh "int[N]" through cffi's C parser on every single Iso() built
209
+ # -- N here varies with the formula and cffi's type cache is keyed on
210
+ # the exact string, so embedding N in it defeats that cache entirely.
211
+ self.conf_space = isoFFI.ffi.new("int[]", sum(self.isotopeNumbers))
212
+
213
+ self.iso = self.ffi.setupIso(self.dimNumber, self.isotopeNumbers,
214
+ self.atomCounts,
215
+ [i/charge for s in self.isotopeMasses for i in s],
216
+ [i for s in self.isotopeProbabilities for i in s])
217
+
218
+ def __del__(self):
219
+ try:
220
+ if self.iso is not None:
221
+ self.ffi.deleteIso(self.iso)
222
+ self.iso = None
223
+ except AttributeError:
224
+ pass
225
+
226
+ def getLightestPeakMass(self):
227
+ """Get the lightest peak in the isotopic distribution."""
228
+ return self.ffi.getLightestPeakMassIso(self.iso)
229
+
230
+ def getLightestPeakLProb(self):
231
+ """Get the log probability of the lightest peak in the isotopic distribution."""
232
+ return self.ffi.getLightestPeakLProbIso(self.iso)
233
+
234
+ def getLightestPeakConf(self):
235
+ """Get the isotopic configuration of the lightest peak in the isotopic distribution."""
236
+ self.ffi.getLightestPeakSignature(self.iso, self.conf_space)
237
+ return self.parse_conf(self.conf_space)
238
+
239
+ def getHeaviestPeakMass(self):
240
+ """Get the heaviest peak in the isotopic distribution."""
241
+ return self.ffi.getHeaviestPeakMassIso(self.iso)
242
+
243
+ def getHeaviestPeakLProb(self):
244
+ """Get the log probability of the heaviest peak in the isotopic distribution."""
245
+ return self.ffi.getHeaviestPeakLProbIso(self.iso)
246
+
247
+ def getHeaviestPeakConf(self):
248
+ """Get the isotopic configuration of the heaviest peak in the isotopic distribution."""
249
+ self.ffi.getHeaviestPeakSignature(self.iso, self.conf_space)
250
+ return self.parse_conf(self.conf_space)
251
+
252
+ def getMonoisotopicPeakMass(self):
253
+ """Get the monoisotopic mass of the peak."""
254
+ return self.ffi.getMonoisotopicPeakMassIso(self.iso)
255
+
256
+ def getMonoisotopicPeakLProb(self):
257
+ """Get the log probability of the monoisotopic peak in the isotopic distribution."""
258
+ return self.ffi.getMonoisotopicPeakLProbIso(self.iso)
259
+
260
+ def getMonoisotopicPeakConf(self):
261
+ """Get the isotopic configuration of the monoisotopic peak in the isotopic distribution."""
262
+ self.ffi.getMonoisotopicPeakSignature(self.iso, self.conf_space)
263
+ return self.parse_conf(self.conf_space)
264
+
265
+ def getModeLProb(self):
266
+ """Get the log probability of the most probable peak(s) in the isotopic distribution."""
267
+ return self.ffi.getModeLProbIso(self.iso)
268
+
269
+ def getModeMass(self):
270
+ """Get the mass of the most probable peak.
271
+
272
+ If there are more, return only the mass of one of them."""
273
+ return self.ffi.getModeMassIso(self.iso)
274
+
275
+ def getTheoreticalAverageMass(self):
276
+ return self.ffi.getTheoreticalAverageMassIso(self.iso)
277
+
278
+ def variance(self):
279
+ return self.ffi.getIsoVariance(self.iso)
280
+
281
+ def stddev(self):
282
+ return self.ffi.getIsoStddev(self.iso)
283
+
284
+ def getMarginalLogSizeEstimates(self, prob):
285
+ cbuf = isoFFI.clib.getMarginalLogSizeEstimates(self.iso, prob)
286
+ # cbuf is already "double *" (cdef'd below): index it directly rather
287
+ # than casting through a fresh "double[N]" string, which would need a
288
+ # full, uncached cffi/pycparser parse for every distinct dimNumber.
289
+ ret = [cbuf[i] for i in range(self.dimNumber)]
290
+ isoFFI.clib.freeReleasedArray(cbuf)
291
+ return ret
292
+
293
+ def parse_conf(self, cptr, starting_with = 0):
294
+ return tuple(tuple(cptr[i+starting_with] for i in o) for o in self.offsets)
295
+
296
+ def _get_parse_conf_fun(self):
297
+ # Can't just use the above function as lambda, as the entire class instance will be in closure
298
+ offsets = self.offsets
299
+ def pc(cptr, starting_with = 0):
300
+ return tuple(tuple(cptr[i+starting_with] for i in o) for o in offsets)
301
+ return pc
302
+
303
+
304
+ class IsoDistribution(object):
305
+ """Isotopoic distribution with precomputed vector of masses and probabilities."""
306
+ def np_masses(self):
307
+ """Return computed masses as a numpy array."""
308
+ try:
309
+ import numpy as np
310
+ except ImportError as e:
311
+ raise Exception(str(e) + "\nThis requires numpy to be installed.")
312
+ return np.frombuffer(isoFFI.ffi.buffer(self.masses))
313
+
314
+ def np_probs(self):
315
+ """Return computed probabilities as a numpy array."""
316
+ try:
317
+ import numpy as np
318
+ except ImportError as e:
319
+ raise Exception(str(e) + "\nThis requires numpy to be installed.")
320
+ return np.frombuffer(isoFFI.ffi.buffer(self.probs))
321
+
322
+ def __iter__(self):
323
+ if hasattr(self, "confs") and self.confs is not None:
324
+ for i in range(self.size):
325
+ yield(self.masses[i], self.probs[i], self.confs[i])
326
+ else:
327
+ for i in range(self.size):
328
+ yield (self.masses[i], self.probs[i])
329
+
330
+ def __getitem__(self, idx):
331
+ try:
332
+ return (self.masses[idx], self.probs[idx], self.confs[idx])
333
+ except (AttributeError, TypeError):
334
+ return (self.masses[idx], self.probs[idx])
335
+
336
+ def __len__(self):
337
+ """Get the number of calculated peaks."""
338
+ return self.size
339
+
340
+ def _get_conf(self, idx):
341
+ return self.parse_conf(self.raw_confs, starting_with = self.sum_isotope_numbers * idx)
342
+
343
+ def __del__(self):
344
+ pass
345
+
346
+ def __init__(self, cobject = None, probs = None, masses = None, get_confs = False, iso = None):
347
+ self.mass_sorted = False
348
+ self.prob_sorted = False
349
+ self._total_prob = float('nan')
350
+
351
+ if cobject is not None:
352
+ self.size = isoFFI.clib.confs_noFixedEnvelope(cobject)
353
+
354
+ # The *WithDeleter getters hand the array over without copying it:
355
+ # the library's own buffers are SIMD-aligned, and a large one is
356
+ # mapped straight from the OS, so plain free() is not necessarily the
357
+ # right way to give them back. Each getter therefore writes out the
358
+ # (size, deleter) pair that releases this particular array, and we
359
+ # bind both into the ffi.gc destructor.
360
+ def wrap(typename, getter, attrname, mult = 1):
361
+ size_out = isoFFI.ffi.new("size_t*")
362
+ deleter_out = isoFFI.ffi.new("IsoSpecArrayDeleter*")
363
+ what = getter(cobject, size_out, deleter_out)
364
+ # Reinterpreting `what` as an array of exactly the right length
365
+ # would normally mean asking cffi to parse "typename[N]" -- but
366
+ # N varies on every call, so cffi's per-string type cache never
367
+ # hits and each call falls through to a full, uncached parse.
368
+ # Route the *length* through a plain byte buffer instead: the
369
+ # "typename *" cast and the "typename[]" open-array type are
370
+ # both fixed strings, parsed (and cached) once for the life of
371
+ # the process, no matter how many distinct N show up here.
372
+ n = self.size * mult
373
+ ptr = isoFFI.ffi.cast(typename + ' *', what)
374
+ if what != isoFFI.ffi.NULL:
375
+ # An empty envelope owns nothing, and has nothing to release.
376
+ # The destructor is attached to the plain pointer, not to
377
+ # the sized array below: cffi's from_buffer() cdata does
378
+ # not support ffi.gc() directly (it corrupts the array's
379
+ # length -- verified separately). Attaching it here
380
+ # instead works because the array keeps its backing
381
+ # buffer alive, and the buffer keeps this pointer alive,
382
+ # so the destructor still fires exactly when the array
383
+ # itself is finally dropped.
384
+ nbytes = size_out[0]
385
+ deleter = deleter_out[0]
386
+ ptr = isoFFI.ffi.gc(ptr, lambda p: isoFFI.clib.freeReleasedArrayWithDeleter(p, nbytes, deleter))
387
+ x = isoFFI.ffi.from_buffer(
388
+ typename + '[]',
389
+ isoFFI.ffi.buffer(ptr, n * isoFFI.ffi.sizeof(typename)))
390
+ setattr(self, attrname, x)
391
+
392
+ wrap("double", isoFFI.clib.massesFixedEnvelopeWithDeleter, "masses")
393
+ wrap("double", isoFFI.clib.probsFixedEnvelopeWithDeleter, "probs")
394
+
395
+ if get_confs:
396
+ # Must also be a subclass of Iso...
397
+ self.sum_isotope_numbers = sum(iso.isotopeNumbers)
398
+ wrap("int", isoFFI.clib.confsFixedEnvelopeWithDeleter, "raw_confs", mult = self.sum_isotope_numbers)
399
+ self.confs = ConfsPassthrough(lambda idx: self._get_conf(idx), self.size)
400
+ self.parse_conf = iso._get_parse_conf_fun()
401
+
402
+ elif probs is not None or masses is not None:
403
+ if probs is None or masses is None:
404
+ raise ValueError("masses and probs must both be provided together")
405
+ if len(probs) != len(masses):
406
+ raise ValueError("masses and probs must have the same length")
407
+ self.size = len(probs)
408
+ # "double[]" (open array) infers its length from the initializer,
409
+ # so this is one fixed, cacheable type string regardless of size
410
+ # -- see the matching note on conf_space above.
411
+ self.probs = isoFFI.ffi.new("double[]", probs)
412
+ self.masses = isoFFI.ffi.new("double[]", masses)
413
+ else:
414
+ raise ValueError("IsoDistribution requires at least one of: cobject, or masses+probs")
415
+
416
+ def _get_cobject(self):
417
+ if hasattr(self, 'raw_confs') and self.raw_confs is not None:
418
+ return isoFFI.clib.setupFixedEnvelopeWithConfs(self.masses, self.probs, self.raw_confs, len(self.masses), self.sum_isotope_numbers, self.mass_sorted, self.prob_sorted, self._total_prob)
419
+ else:
420
+ return isoFFI.clib.setupFixedEnvelope(self.masses, self.probs, len(self.masses), self.mass_sorted, self.prob_sorted, self._total_prob)
421
+
422
+ def copy(self):
423
+ x = self._get_cobject()
424
+ c = isoFFI.clib.copyFixedEnvelope(x)
425
+ isoFFI.clib.deleteFixedEnvelope(x, True)
426
+ ret = IsoDistribution(cobject = c)
427
+ ret._total_prob = self._total_prob
428
+ ret.mass_sorted = self.mass_sorted
429
+ ret.prob_sorted = self.prob_sorted
430
+ isoFFI.clib.deleteFixedEnvelope(c, False)
431
+ return ret
432
+
433
+ def __add__(self, other):
434
+ x = self._get_cobject()
435
+ y = other._get_cobject()
436
+ cobject = isoFFI.clib.addEnvelopes(x, y)
437
+ isoFFI.clib.deleteFixedEnvelope(x, True)
438
+ isoFFI.clib.deleteFixedEnvelope(y, True)
439
+ ret = IsoDistribution(cobject = cobject)
440
+ isoFFI.clib.deleteFixedEnvelope(cobject, False)
441
+ return ret
442
+
443
+ def __mul__(self, other):
444
+ x = self._get_cobject()
445
+ y = other._get_cobject()
446
+ cobject = isoFFI.clib.convolveEnvelopes(x, y)
447
+ isoFFI.clib.deleteFixedEnvelope(x, True)
448
+ isoFFI.clib.deleteFixedEnvelope(y, True)
449
+ ret = IsoDistribution(cobject = cobject)
450
+ isoFFI.clib.deleteFixedEnvelope(cobject, False)
451
+ return ret
452
+
453
+ def total_prob(self):
454
+ if math.isnan(self._total_prob):
455
+ co = self._get_cobject()
456
+ self._total_prob = isoFFI.clib.getTotalProbOfEnvelope(co)
457
+ isoFFI.clib.deleteFixedEnvelope(co, True)
458
+ return self._total_prob
459
+
460
+ def normalize(self):
461
+ co = self._get_cobject()
462
+ isoFFI.clib.normalizeEnvelope(co)
463
+ isoFFI.clib.deleteFixedEnvelope(co, True)
464
+ self._total_prob = 1.0
465
+
466
+ def normalized(self):
467
+ ret = self.copy()
468
+ ret.normalize()
469
+ return ret
470
+
471
+ def add_mass(self, d_mass):
472
+ isoFFI.clib.array_add(self.masses, self.size, d_mass)
473
+
474
+ def mul_mass(self, d_mass):
475
+ isoFFI.clib.array_mul(self.masses, self.size, d_mass)
476
+
477
+ def add_mul_mass(self, add, mul):
478
+ isoFFI.clib.array_fma(self.masses, self.size, mul, add*mul)
479
+
480
+ def mul_add_mass(self, mul, add):
481
+ isoFFI.clib.array_fma(self.masses, self.size, mul, add)
482
+
483
+ def scale(self, factor):
484
+ '''Multiplies the pribabilities of spectrum by factor. Works in place.'''
485
+ co = self._get_cobject()
486
+ isoFFI.clib.scaleEnvelope(co, factor)
487
+ isoFFI.clib.deleteFixedEnvelope(co, True)
488
+ self._total_prob *= factor
489
+
490
+ def scaled(self, factor):
491
+ '''Returns a copy of the spectrum where each probability was multiplied by factor.'''
492
+ ret = self.copy()
493
+ ret.scale(factor)
494
+ return ret
495
+
496
+ def resample(self, ionic_current, beta_bias=1.0):
497
+ co = self._get_cobject()
498
+ isoFFI.clib.resampleEnvelope(co, ionic_current, beta_bias)
499
+ isoFFI.clib.deleteFixedEnvelope(co, True)
500
+ self._total_prob = float(ionic_current)
501
+ self.prob_sorted = False
502
+
503
+ def sort_by_prob(self):
504
+ if not self.prob_sorted:
505
+ co = self._get_cobject()
506
+ isoFFI.clib.sortEnvelopeByProb(co)
507
+ isoFFI.clib.deleteFixedEnvelope(co, True)
508
+ self.mass_sorted = False
509
+ self.prob_sorted = True
510
+
511
+ def sort_by_mass(self):
512
+ if not self.mass_sorted:
513
+ co = self._get_cobject()
514
+ isoFFI.clib.sortEnvelopeByMass(co)
515
+ isoFFI.clib.deleteFixedEnvelope(co, True)
516
+ self.mass_sorted = True
517
+ self.prob_sorted = False
518
+
519
+ def _recalculate_everything(self):
520
+ self._total_prob = float('nan')
521
+ self.mass_sorted = False
522
+ self.prob_sorted = False
523
+
524
+ def empiric_average_mass(self):
525
+ co = self._get_cobject()
526
+ ret = isoFFI.clib.empiricAverageMass(co)
527
+ isoFFI.clib.deleteFixedEnvelope(co, True)
528
+ return ret
529
+
530
+ def empiric_variance(self):
531
+ co = self._get_cobject()
532
+ ret = isoFFI.clib.empiricVariance(co)
533
+ isoFFI.clib.deleteFixedEnvelope(co, True)
534
+ return ret
535
+
536
+ def empiric_stddev(self):
537
+ co = self._get_cobject()
538
+ ret = isoFFI.clib.empiricStddev(co)
539
+ isoFFI.clib.deleteFixedEnvelope(co, True)
540
+ return ret
541
+
542
+ def wassersteinDistance(self, other):
543
+ x = self._get_cobject()
544
+ y = other._get_cobject()
545
+ ret = isoFFI.clib.wassersteinDistance(x, y)
546
+ isoFFI.clib.deleteFixedEnvelope(x, True)
547
+ isoFFI.clib.deleteFixedEnvelope(y, True)
548
+ self.mass_sorted = True
549
+ self.prob_sorted = False
550
+ other.mass_sorted = True
551
+ other.prob_sorted = False
552
+ if math.isnan(ret):
553
+ raise ValueError("Both spectra must be normalized before Wasserstein distance can be computed.")
554
+ return ret
555
+
556
+ def orientedWassersteinDistance(self, other):
557
+ x = self._get_cobject()
558
+ y = other._get_cobject()
559
+ ret = isoFFI.clib.orientedWassersteinDistance(x, y)
560
+ isoFFI.clib.deleteFixedEnvelope(x, True)
561
+ isoFFI.clib.deleteFixedEnvelope(y, True)
562
+ self.mass_sorted = True
563
+ self.prob_sorted = False
564
+ other.mass_sorted = True
565
+ other.prob_sorted = False
566
+ if math.isnan(ret):
567
+ raise ValueError("Both spectra must be normalized before Wasserstein distance can be computed.")
568
+ return ret
569
+
570
+ def abyssalWassersteinDistance(self, other, abyss_depth, other_scale = 1.0):
571
+ x = self._get_cobject()
572
+ y = other._get_cobject()
573
+ ret = isoFFI.clib.abyssalWassersteinDistance(x, y, abyss_depth, other_scale)
574
+ isoFFI.clib.deleteFixedEnvelope(x, True)
575
+ isoFFI.clib.deleteFixedEnvelope(y, True)
576
+ self.mass_sorted = True
577
+ self.prob_sorted = False
578
+ other.mass_sorted = True
579
+ other.prob_sorted = False
580
+ return ret
581
+
582
+ def abyssalWassersteinDistanceGrad(self, others, scales, grad, abyss_depth_exp, abyss_depth_the):
583
+ assert len(others) + 1 == len(scales) == len(grad)
584
+ cobjs = [self._get_cobject()]
585
+ cobjs.extend(other._get_cobject() for other in others)
586
+ ret = isoFFI.clib.abyssalWassersteinDistanceGrad(cobjs, scales, grad, len(others), abyss_depth_exp, abyss_depth_the)
587
+ for cobj in cobjs:
588
+ isoFFI.clib.deleteFixedEnvelope(cobj, True)
589
+ self.mass_sorted = True
590
+ self.prob_sorted = False
591
+ for other in others:
592
+ other.mass_sorted = True
593
+ other.prob_sorted = False
594
+ return ret
595
+
596
+ def wassersteinMatch(self, other, flow_dist, other_scale = 1.0):
597
+ x = self._get_cobject()
598
+ y = other._get_cobject()
599
+ ret = isoFFI.clib.wassersteinMatch(x, y, flow_dist, other_scale)
600
+ isoFFI.clib.deleteFixedEnvelope(x, True)
601
+ isoFFI.clib.deleteFixedEnvelope(y, True)
602
+ self.mass_sorted = True
603
+ self.prob_sorted = False
604
+ other.mass_sorted = True
605
+ other.prob_sorted = False
606
+ return (ret.res1, ret.res2, ret.flow)
607
+
608
+ def binned(self, width = 1.0, middle = 0.0):
609
+ co = self._get_cobject()
610
+ cbo = isoFFI.clib.binnedEnvelope(co, width, middle)
611
+ isoFFI.clib.deleteFixedEnvelope(co, True)
612
+ ret = IsoDistribution(cobject = cbo)
613
+ isoFFI.clib.deleteFixedEnvelope(cbo, False)
614
+ self.mass_sorted = True
615
+ self.prob_sorted = False
616
+ ret.mass_sorted = True
617
+ ret.prob_sorted = False
618
+ return ret
619
+
620
+
621
+ @staticmethod
622
+ def LinearCombination(envelopes, intensities):
623
+ envelope_objs = [x._get_cobject() for x in envelopes]
624
+ if type(intensities) != list:
625
+ intensities = list(intensities)
626
+ cobject = isoFFI.clib.linearCombination(envelope_objs, intensities, len(envelope_objs))
627
+ for x in envelope_objs:
628
+ isoFFI.clib.deleteFixedEnvelope(x, True)
629
+ ret = IsoDistribution(cobject = cobject)
630
+ isoFFI.clib.deleteFixedEnvelope(cobject, False)
631
+ return ret
632
+
633
+
634
+ def plot(self, plot_type = "bars", show = True, **matplotlib_args):
635
+ """Plot the isotopic distribution.
636
+
637
+ Args:
638
+ **matplotlib_args: arguments for matplotlib plot.
639
+ """
640
+ try:
641
+ from matplotlib import pyplot as plt
642
+ except ImportError as e:
643
+ raise ImportError(str(e) + "\nPlotting spectra requires matplotlib to be installed.")
644
+ if plot_type == "bars":
645
+ if "linewidth" not in matplotlib_args:
646
+ matplotlib_args['linewidth'] = 1.0
647
+ plt.vlines(list(self.masses), [0], list(self.probs), **matplotlib_args)
648
+ elif plot_type == "profile":
649
+ self.sort_by_mass()
650
+ plt.plot(list(self.masses), list(self.probs), **matplotlib_args)
651
+ plt.xlabel("Mass (Da)")
652
+ plt.ylabel("Intensity (relative)")
653
+ if show:
654
+ plt.show()
655
+
656
+
657
+
658
+
659
+ def IsoThreshold(threshold,
660
+ formula="",
661
+ absolute=False,
662
+ get_confs=False,
663
+ **kwargs):
664
+ """Initialize the IsoDistribution isotopic distribution by threshold.
665
+
666
+ Args:
667
+ threshold (float): value of the absolute or relative threshold.
668
+ formula (str): a chemical formula, e.g. "C2H6O1" or "C2H6O".
669
+ absolute (boolean): should we report peaks with probabilities above an absolute probability threshold, or above a relative threshold amounting to a given proportion of the most probable peak?
670
+ get_confs (boolean): should we report counts of isotopologues?
671
+ **kwds: named arguments to IsoSpectrum.
672
+ """
673
+ iso = Iso(formula = formula, get_confs = get_confs, **kwargs)
674
+ tabulator = isoFFI.clib.setupThresholdFixedEnvelope(iso.iso, threshold, absolute, get_confs)
675
+ ido = IsoDistribution(cobject = tabulator, get_confs = get_confs, iso = iso)
676
+ isoFFI.clib.deleteFixedEnvelope(tabulator, False)
677
+ return ido
678
+
679
+
680
+ def IsoTotalProb(prob_to_cover,
681
+ formula="",
682
+ get_minimal_pset=True,
683
+ get_confs=False,
684
+ **kwargs):
685
+ """Initialize the IsoDistribution isotopic distribution by total probability.
686
+
687
+ Args:
688
+ prob_to_cover (float): minimal total probability of the reported peaks.
689
+ formula (str): a chemical formula, e.g. "C2H6O1" or "C2H6O".
690
+ get_minimal_pset (boolean): should we trim the last calculated layer of isotopologues so that the reported result is as small as possible?
691
+ get_confs (boolean): should we report the counts of isotopologues?
692
+ **kwargs: named arguments to the superclass.
693
+ """
694
+ iso = Iso(formula=formula, get_confs=get_confs, **kwargs)
695
+ tabulator = isoFFI.clib.setupTotalProbFixedEnvelope(iso.iso, prob_to_cover, get_minimal_pset, get_confs)
696
+ ido = IsoDistribution(cobject = tabulator, get_confs = get_confs, iso = iso)
697
+ isoFFI.clib.deleteFixedEnvelope(tabulator, False)
698
+ return ido
699
+
700
+
701
+ def IsoStochastic(no_molecules,
702
+ formula="",
703
+ precision=0.9999,
704
+ beta_bias=5.0,
705
+ get_confs=False,
706
+ **kwargs):
707
+ """Initialize the isotopic distribution by stochastic sampling, simulating a measured mass spectrum
708
+ with a given number of ions. Each configuration is drawn independently according to its isotopic
709
+ probability, producing integer ion counts rather than exact probabilities.
710
+
711
+ Args:
712
+ no_molecules (uint): number of ions to simulate (ionic current).
713
+ formula (str): a chemical formula, e.g. "C2H6O1" or "C2H6O".
714
+ precision (float): total probability of the envelope used for sampling. Between 0.0 and 1.0.
715
+ beta_bias (float, nonnegative): fiddling with this parameter does not change the result, but might make computations slightly faster (or likely, much, much slower if you screw it up...)
716
+ get_confs (boolean): should we report the counts of isotopologues?
717
+ **kwargs: named arguments to the superclass.
718
+ """
719
+ iso = Iso(formula=formula, get_confs=get_confs, **kwargs)
720
+ tabulator = isoFFI.clib.setupStochasticFixedEnvelope(iso.iso, no_molecules, precision, beta_bias, get_confs)
721
+ ido = IsoDistribution(cobject = tabulator, get_confs = get_confs, iso = iso)
722
+ isoFFI.clib.deleteFixedEnvelope(tabulator, False)
723
+ return ido
724
+
725
+
726
+ def IsoBinned(bin_width,
727
+ formula="",
728
+ target_total_prob=0.9999,
729
+ bin_middle=0.0,
730
+ **kwargs):
731
+ """Initialize the isotopic distribution as a binned (histogram) envelope.
732
+ Configurations are grouped into bins of equal width and their probabilities summed.
733
+
734
+ Args:
735
+ bin_width (float): width of each bin in Da.
736
+ formula (str): a chemical formula, e.g. "C2H6O1" or "C2H6O".
737
+ target_total_prob (float): total probability of configurations to include before binning. Between 0.0 and 1.0.
738
+ bin_middle (float): offset of bin centres from zero.
739
+ **kwargs: named arguments to the superclass.
740
+ """
741
+ iso = Iso(formula=formula, get_confs=False, **kwargs)
742
+ tabulator = isoFFI.clib.setupBinnedFixedEnvelope(iso.iso, target_total_prob, bin_width, bin_middle)
743
+ ido = IsoDistribution(cobject = tabulator, get_confs = False, iso = iso)
744
+ isoFFI.clib.deleteFixedEnvelope(tabulator, False)
745
+ return ido
746
+
747
+
748
+ class IsoGenerator(Iso):
749
+ """Virtual class alowing memory-efficient iteration over the isotopic distribution.
750
+
751
+ This iterator will stop only after enumerating all isotopologues.
752
+ """
753
+ def __init__(self, formula="", get_confs=False, **kwargs):
754
+ """Initialize the IsoGenerator.
755
+
756
+ Args:
757
+ formula (str): a chemical formula, e.g. "C2H6O1" or "C2H6O".
758
+ get_confs (boolean): should we report the counts of isotopologues?
759
+ **kwargs: named arguments to the superclass.
760
+ """
761
+ self.cgen = None
762
+ super(IsoGenerator, self).__init__(formula=formula, get_confs=get_confs, **kwargs)
763
+ self.firstuse = True
764
+
765
+ def __iter__(self):
766
+ if not self.firstuse:
767
+ raise NotImplementedError("Multiple iterations through the same IsoGenerator object are not supported. Either create a new (identical) generator for a second loop-through, or use one of the non-generator classes, which do support being re-used.")
768
+ self.firstuse = False
769
+ cgen = self.cgen
770
+ if self.get_confs:
771
+ while self.advancer(cgen):
772
+ self.conf_getter(cgen, self.conf_space)
773
+ yield (self.mass_getter(cgen), self.xprob_getter(cgen), self.parse_conf(self.conf_space))
774
+ else:
775
+ while self.advancer(cgen):
776
+ yield (self.mass_getter(cgen), self.xprob_getter(cgen))
777
+
778
+ def __del__(self):
779
+ super(IsoGenerator, self).__del__()
780
+
781
+
782
+ class IsoThresholdGenerator(IsoGenerator):
783
+ """Class alowing memory-efficient iteration over the isotopic distribution up till some probability threshold.
784
+
785
+ This iterator will stop only after reaching a probability threshold.
786
+ """
787
+ def __init__(self, threshold, formula="", absolute=False, get_confs=False, reorder_marginals = True, **kwargs):
788
+ """Initialize IsoThresholdGenerator.
789
+
790
+ Args:
791
+ formula (str): a chemical formula, e.g. "C2H6O1" or "C2H6O".
792
+ absolute (boolean): should we report peaks with probabilities above an absolute probability threshold, or above a relative threshold amounting to a given proportion of the most probable peak?
793
+ get_confs (boolean): should we report the counts of isotopologues?
794
+ **kwargs: named arguments to the superclass.
795
+ """
796
+ super(IsoThresholdGenerator, self).__init__(formula=formula, get_confs=get_confs, **kwargs)
797
+ self.threshold = threshold
798
+ self.absolute = absolute
799
+ self.cgen = self.ffi.setupIsoThresholdGenerator(self.iso,
800
+ threshold,
801
+ absolute,
802
+ 1000,
803
+ 1000,
804
+ reorder_marginals)
805
+ self.advancer = self.ffi.advanceToNextConfigurationIsoThresholdGenerator
806
+ self.xprob_getter = self.ffi.probIsoThresholdGenerator
807
+ self.mass_getter = self.ffi.massIsoThresholdGenerator
808
+ self.conf_getter = self.ffi.get_conf_signatureIsoThresholdGenerator
809
+
810
+ def __del__(self):
811
+ """Destructor."""
812
+ try:
813
+ if self.cgen is not None:
814
+ self.ffi.deleteIsoThresholdGenerator(self.cgen)
815
+ self.cgen = None
816
+ except AttributeError:
817
+ pass
818
+ super(IsoThresholdGenerator, self).__del__()
819
+
820
+
821
+ class IsoLayeredGenerator(IsoGenerator):
822
+ """Class alowing memory-efficient iteration over the isotopic distribution up till some joint probability of the reported peaks."""
823
+ def __init__(self, formula="", get_confs=False, reorder_marginals = True, t_prob_hint = 0.99, **kwargs):
824
+ """Initialize IsoLayeredGenerator.
825
+
826
+ Args:
827
+ formula (str): a chemical formula, e.g. "C2H6O1" or "C2H6O".
828
+ get_confs (boolean): should we report the counts of isotopologues?
829
+ reorder_marginals (boolean): should the marginal distributions be reordered for efficiency?
830
+ t_prob_hint (float): hint for the target total probability, used to size internal buffers.
831
+ **kwargs: named arguments to the superclass.
832
+ """
833
+ super(IsoLayeredGenerator, self).__init__(formula=formula, get_confs=get_confs, **kwargs)
834
+ self.cgen = self.ffi.setupIsoLayeredGenerator(self.iso, 1000, 1000, reorder_marginals, t_prob_hint)
835
+ self.advancer = self.ffi.advanceToNextConfigurationIsoLayeredGenerator
836
+ self.xprob_getter = self.ffi.probIsoLayeredGenerator
837
+ self.mass_getter = self.ffi.massIsoLayeredGenerator
838
+ self.conf_getter = self.ffi.get_conf_signatureIsoLayeredGenerator
839
+
840
+ def __del__(self):
841
+ try:
842
+ if self.cgen is not None:
843
+ self.ffi.deleteIsoLayeredGenerator(self.cgen)
844
+ self.cgen = None
845
+ except AttributeError:
846
+ pass
847
+ super(IsoLayeredGenerator, self).__del__()
848
+
849
+ class IsoOrderedGenerator(IsoGenerator):
850
+ """Class representing an isotopic distribution with peaks ordered by descending probability.
851
+
852
+ This generator return probilities ordered with descending probability.
853
+ It it not optimal to do so, but it might be useful.
854
+
855
+ WARNING! This algorithm work in O(N*log(N)) vs O(N) of the threshold and layered algorithms.
856
+ Also, the order of descending probability will most likely not reflect the order of ascending masses.
857
+ """
858
+ def __init__(self, formula="", get_confs=False, **kwargs):
859
+ """Initialize IsoOrderedGenerator.
860
+
861
+ Args:
862
+ formula (str): a chemical formula, e.g. "C2H6O1" or "C2H6O".
863
+ get_confs (boolean): should we report the counts of isotopologues?
864
+ **kwargs: named arguments to the superclass.
865
+ """
866
+ super(IsoOrderedGenerator, self).__init__(formula=formula, get_confs=get_confs, **kwargs)
867
+ self.cgen = self.ffi.setupIsoOrderedGenerator(self.iso, 1000, 1000)
868
+ self.advancer = self.ffi.advanceToNextConfigurationIsoOrderedGenerator
869
+ self.xprob_getter = self.ffi.probIsoOrderedGenerator
870
+ self.mass_getter = self.ffi.massIsoOrderedGenerator
871
+ self.conf_getter = self.ffi.get_conf_signatureIsoOrderedGenerator
872
+
873
+ def __del__(self):
874
+ try:
875
+ if self.cgen is not None:
876
+ self.ffi.deleteIsoOrderedGenerator(self.cgen)
877
+ self.cgen = None
878
+ except AttributeError:
879
+ pass
880
+ super(IsoOrderedGenerator, self).__del__()
881
+
882
+
883
+ class IsoStochasticGenerator(IsoGenerator):
884
+ def __init__(self, no_molecules, formula="", precision=0.9999, beta_bias = 1.0, get_confs=False, **kwargs):
885
+ super(IsoStochasticGenerator, self).__init__(formula=formula, get_confs=get_confs, **kwargs)
886
+ self.threshold = precision
887
+ self.no_molecules = no_molecules
888
+ self.cgen = self.ffi.setupIsoStochasticGenerator(self.iso,
889
+ no_molecules,
890
+ precision,
891
+ beta_bias)
892
+ self.advancer = self.ffi.advanceToNextConfigurationIsoStochasticGenerator
893
+ self.xprob_getter = self.ffi.probIsoStochasticGenerator
894
+ self.mass_getter = self.ffi.massIsoStochasticGenerator
895
+ self.conf_getter = self.ffi.get_conf_signatureIsoStochasticGenerator
896
+
897
+ def __del__(self):
898
+ """Destructor."""
899
+ try:
900
+ if self.cgen is not None:
901
+ self.ffi.deleteIsoStochasticGenerator(self.cgen)
902
+ self.cgen = None
903
+ except AttributeError:
904
+ pass
905
+ super(IsoStochasticGenerator, self).__del__()
906
+
907
+
908
+ def get_simd_level():
909
+ """Report what the bundled C++ library's vectorised kernels are running as.
910
+
911
+ The wheels carry several builds of the inner loops and choose one from the
912
+ CPU at import time, so this is a property of the machine as much as of the
913
+ build. Use it to tell an installation that vectorises from one that silently
914
+ does not -- on Windows, for instance, where the standard library provides no
915
+ <experimental/simd> and everything falls back to the scalar path.
916
+
917
+ Returns:
918
+ str: one of "scalar" (not vectorised at all), "sse2", "avx", "avx2",
919
+ "avx512", "neon", or "simd" for a vector unit the library has no
920
+ name for. New tokens may appear as instruction sets are added, so
921
+ treat an unfamiliar one as "some vector unit" rather than an error.
922
+ """
923
+ return isoFFI.ffi.string(isoFFI.clib.activeSimdLevel()).decode("ascii")
924
+