Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def function_timetic(self):
"""
extracts timepoints and tic lists for each function
this function is separate from mzml contents because it would increase load times significantly (~6x)
"""
if self.verbose is True:
prog = Progress(string='Extracting timepoints and total ion current values from mzML', fraction=False)
for function in self.functions: # add timepoint and tic lists
self.functions[function]['timepoints'] = [] # list for timepoints
self.functions[function]['tic'] = [] # list for total ion current values
if 'level' in self.functions[function] and self.functions[function]['level'] > 1:
self.functions[function]['ce'] = [] # list for collision energies
for spectrum in self.tree.getElementsByTagName('spectrum'):
attr = branch_attributes(spectrum)
function, proc, scan = fps(spectrum) # determine function, process, and scan numbers
if self.verbose is True:
prog.write(attr['index'] + 1)
p = branch_cvparams(spectrum) # pull spectrum's cvparameters
self.functions[function]['timepoints'].append(p['MS:1000016'].value) # start scan time
self.functions[function]['tic'].append(p['MS:1000285'].value) # total ion current
if 'MS:1000045' in p:
self.functions[function]['ce'].append(p['MS:1000045'].value) # collision energy
self.ftt = True
comp[element]
])
else: # if it's an isotope
speciso = True
spec = Spectrum( # initiate spectrum object
decpl, # decimal places
start=None, # no minimum mass
end=None, # no maximum mass
empty=True, # whether or not to use emptyspec
filler=0., # fill with zeros, not None
)
if verbose is True:
counter = 0 # create a counter
iterations = int(cpu_list_product([numberofcwr(n, k) for n, k in nk])) # number of iterations
prog = Progress( # create a progress instance
string='Processing isotope combination',
last=iterations
)
for comb in product(*iterators):
if verbose is True:
counter += 1
# remaining = st.progress(counter,iterations,'combinations')
prog.write(counter)
num = 1 # number of combinations counter
x = 0. # mass value
y = 1. # intensity value
for tup in comb: # for each element combination
element = isos[tup[0]] # associate isotope to element
# counts = [tup.count(x) for x in isosets[element]] # count the number of occurances of each isotope
# num *= num_permu(tup,counts) # determine the number of permutations of the set
function = self.associate_to_function()
if self.functions[function]['type'] != 'MS':
raise ValueError(
'The auto_resolution function only operates on mass spectrum functions. '
'Type of specified function %d: %s' % (function, self.functions[function]['type']))
ranges = [] # list of scan intervals
if self.functions[function]['nscans'] <= 20: # if the number of scans is less than 20
ranges = [[1, self.functions[function]['nscans']]]
else:
while len(ranges) < n: # generate 10 pseudo-random intervals to sample
ran = int(random() * self.functions[function]['nscans']) + self.functions[function]['sr'][0]
if ran - 10 >= self.functions[function]['sr'][0] and ran + 10 <= self.functions[function]['sr'][1]:
ranges.append([ran - 10, ran + 10])
if self.verbose is True:
prog = Progress(string='Estimating resolution of the instrument', fraction=False, last=n)
summed = []
for ind, rng in enumerate(ranges):
if self.verbose is True:
prog.write(ind + 1)
summed.append(self.sum_scans(rng[0], rng[1], function, 2, True)) # sum those scans and append output
res = []
for spec in summed: # calculate resolution for each scan range
inds = findsomepeaks(spec[1]) # find some peaks
for ind in inds: # for each of those peaks
res.append(resolution(spec[0], spec[1], ind, threshold=10))
if self.verbose is True:
prog.fin()
res = [y for y in res if y is not None] # removes None values (below S/N)
return sum(res) / len(res) # return average
eleips[element] = isotope_pattern_combinatoric( # calculate the isotope pattern for each element
{element: number},
decpl=decpl,
verbose=verbose,
).trim() # trim the generated spectra to lists
sortlist = []
for element in eleips:
sortlist.append((
len(eleips[element][0]),
element
))
sortlist = sorted(sortlist) # sorted list of elements based on the length of their isotope patterns
sortlist.reverse()
if verbose is True:
prog = Progress(
last=len(sortlist) - 1,
percent=False,
fraction=False,
)
spec = None
for lenlist, element in sortlist:
if verbose is True:
prog.string = f'Adding element {element} to isotope pattern'
prog.write(1)
if spec is None:
spec = Spectrum(
autodec(fwhm), # decimal places
start=None, # minimum mass
end=None, # maximum mass
empty=True, # whether or not to use emptyspec
This is useful for line continuity if the spectrum is to be used for
rendering images.
returns a list with each index corresponding to a scan, with two sublists for x and y data
"""
if function is None: # if not specified, retrieve first function
function = self.associate_to_function()
# find spectrum indicies to extract between
if function not in self.functions:
raise ValueError('The function "%d" is not in this mzml file.' % function)
start = self.scan_index(start, function, bias='greater')
end = self.scan_index(end, function, bias='lesser')
if self.ftt is False: # extract the timepoints and etc from the mzml
self.function_timetic()
if self.verbose is True and mute is False:
prog = Progress(string='Extracting scan data from spectrum', last=self.nscans)
out = []
for spectrum in self.tree.getElementsByTagName('spectrum'): # go through each spectrum
attr = branch_attributes(spectrum)
# func,proc,scan = self.fps(spectrum) # determine function, process, and scan numbers
# p = self.cvparam(spectrum)
if attr['index'] > end:
break
if self.verbose is True and mute is False:
prog.write(attr['index'] + 1)
if start <= attr['index'] <= end: # within the index bounds
x, y = extract_spectrum(spectrum)
if mzstart is not None or mzend is not None:
if mzstart is None:
l = min(x)
else:
l = mzstart
:param npeaks: if the dropmethod is set to 'npeaks', the top n peaks will be kept, with the rest being dropped.
:param consolidate: if the dropmethod is set to 'consolidate', any peaks below the threshold will be consolidated
into adjacent peaks using a weighted average. Any peaks that do not have a neighbour within 10^-`consolidate`
will be dropped entirely.
:return: Returns the isotope pattern with mass defects preserved (referred to as the 'raw'
isotope pattern in this script).
:rtype: Spectrum
"""
spec = None # initial state of spec
if verbose is True:
sys.stdout.write('Generating raw isotope pattern.\n')
for key in comp: # for each element
if key in mass_dict: # if not a single isotope
if verbose is True:
prog = Progress(string=f'Processing element {key}', last=comp[key])
masses = [] # list for masses of each isotope
abunds = [] # list for abundances
for mass in mass_dict[key]:
if mass != 0:
if mass_dict[key][mass][1] > 0: # if abundance is nonzero
masses.append(mass_dict[key][mass][0])
abunds.append(mass_dict[key][mass][1])
for n in range(comp[key]): # for n number of each element
if verbose is True:
prog.write(n + 1)
if spec is None: # if spectrum object has not been defined
spec = Spectrum(
decpl, # decimal places
start=min(masses) - 10 ** -decpl, # minimum mass
end=max(masses) + 10 ** -decpl, # maximum mass
specin=[masses, abunds], # supply masses and abundances as initialization spectrum
def pull_chromatograms(self):
"""
Pulls mzML chromatograms
returns:
dictionary = {'chromatogram 1 id', 'chromatogram 2 id', ...}
dictionary['chromatogram 1 id'] = {
'x': list of x values
'y': list of y values (paired with x)
'xunit': unit of the x values
'yunit': unit of the y values
}
"""
if self.verbose is True:
prog = Progress(string='Extracting chromatogram', last=self.nchroms)
chroms = {} # dictionary of chromatograms
for chromatogram in self.tree.getElementsByTagName('chromatogram'):
attr = branch_attributes(chromatogram) # pull attributes
if self.verbose is True:
prog.write(attr['index'] + 1)
x, y, xunit, yunit = extract_spectrum(chromatogram, True) # extract x list, y list, and units
chroms[attr['id']] = {'x': x, 'y': y, 'xunit': xunit, 'yunit': yunit}
if self.verbose is True:
prog.fin()
return chroms
'are none associated with this file. ')
function = min(self.functions.keys())
elif function not in self.functions: # if fn is not defined
raise KeyError(f'The function {function} is not defined in the mzML object. Available options: '
f'{", ".join([str(key) for key in self.functions.keys()])}')
if self.functions[function]['type'] != 'MS':
raise ValueError(f'The sum_scans function does not have the functionality to sum non-mass spec scans.'
f'The specified function {function} is of type {self.functions[function]["type"]}')
start = self.scan_index(start, function, 'greater')
end = self.scan_index(end, function, 'lesser')
spec = Spectrum(dec, start=self.functions[function]['window'][0],
end=self.functions[function]['window'][1]) # create Spectrum object
if self.verbose is True and mute is False:
prog = Progress(string='Combining spectrum', fraction=False, first=start, last=end)
for spectrum in self.tree.getElementsByTagName('spectrum'): # go through each spectrum
attr = branch_attributes(spectrum) # get attributes
if attr['index'] > end:
break
if self.verbose is True and mute is False:
prog.write(attr['index'] + 1)
if start <= attr['index'] <= end: # if within the specified bounds
x, y = extract_spectrum(spectrum) # pull spectrum
spec.add_spectrum(x, y) # add spectrum to Spectrum object
out = spec.trim()
if self.verbose is True and mute is False:
prog.fin()
return out