Example #1
0
def in_minutes(x):
    '''Convert a time quantity to minutes

    Parameters
    ----------
    x: unitfloat
        A float representing a quantity of time annotated with a time unit

    Returns
    -------
    unitfloat:
        The time after conversion to minutes
    '''
    try:
        unit = x.unit_info
    except AttributeError:
        return x
    if unit == 'minute':
        return x
    elif unit == 'second':
        y = unitfloat(x / 60., 'minute')
        return y
    elif unit == 'hour':
        y = unitfloat(x * 60, 'minute')
        return y
    else:
        warnings.warn("Time unit %r not recognized" % unit)
    return x
Example #2
0
 def _acquisition_information(self, scan):
     scan_info = {}
     scan_list_struct = scan['scanList']
     combination = "unknown"
     if "no combination" in scan_list_struct:
         combination = "no combination"
     elif "sum of spectra" in scan_list_struct:
         combination = "sum of spectra"
     elif "median of spectra" in scan_list_struct:
         combination = "median of spectra"
     elif "mean of spectra" in scan_list_struct:
         combination = "mean of spectra"
     scan_info['combination'] = combination
     scan_info_scan_list = []
     misplaced_FAIMS_value = scan.get(FAIMS_compensation_voltage.name, None)
     for i, scan_ in enumerate(scan_list_struct.get("scan", [])):
         scan_ = scan_.copy()
         if misplaced_FAIMS_value is not None and i == 0:
             scan[FAIMS_compensation_voltage.name] = misplaced_FAIMS_value
         struct = {}
         struct['start_time'] = scan_.pop('scan start time', unitfloat(0, 'minute'))
         struct['injection_time'] = scan_.pop("ion injection time", unitfloat(0, 'millisecond'))
         windows = []
         for window in scan_.pop("scanWindowList", {}).get("scanWindow", []):
             windows.append(ScanWindow(
                 window['scan window lower limit'],
                 window['scan window upper limit']))
         struct['window_list'] = windows
         scan_.pop("instrumentConfigurationRef", None)
         struct['traits'] = scan_
         scan_info_scan_list.append(ScanEventInformation(**struct))
     scan_info['scan_list'] = scan_info_scan_list
     return ScanAcquisitionInformation(**scan_info)
Example #3
0
def in_minutes(x):
    '''Convert a time quantity to minutes

    Parameters
    ----------
    x: unitfloat
        A float representing a quantity of time annotated with a time unit

    Returns
    -------
    unitfloat:
        The time after conversion to minutes
    '''
    try:
        unit = x.unit_info
    except AttributeError:
        return x
    if unit == 'minute':
        return x
    elif unit == 'second':
        y = unitfloat(x / 60., 'minute')
        return y
    elif unit == 'hour':
        y = unitfloat(x * 60, 'minute')
        return y
    else:
        warnings.warn("Time unit %r not recognized" % unit)
    return x
Example #4
0
def in_minutes(x):
    try:
        unit = x.unit_info
    except AttributeError:
        return x
    if unit == 'minute':
        return x
    elif unit == 'second':
        y = unitfloat(x / 60., 'minute')
        return y
    elif unit == 'hour':
        y = unitfloat(x * 60, 'minute')
        return y
    else:
        warnings.warn("Time unit %r not recognized" % unit)
    return x
Example #5
0
def to_mzml(reader,
            outstream,
            pick_peaks=False,
            ms1_filters=None,
            msn_filters=None,
            default_activation=None):
    if ms1_filters is None:
        ms1_filters = []
    if msn_filters is None:
        msn_filters = []
    reader.make_iterator(grouped=True)
    writer = MzMLSerializer(outstream, deconvoluted=False)
    writer.copy_metadata_from(reader)
    method = data_transformation.ProcessingMethod(software_id='ms_deisotope_1')
    if pick_peaks:
        method.add('MS:1000035')
    method.add('MS:1000544')
    writer.add_data_processing(method)
    if default_activation is not None:
        if isinstance(default_activation, basestring):
            default_activation = activation_module.ActivationInformation(
                default_activation, unitfloat(0, 'electronvolt'))
        elif isinstance(default_activation, dict):
            default_activation = activation_module.ActivationInformation(
                **default_activation)
        else:
            click.secho("Could not convert %r into ActivationInformation" %
                        (default_activation, ),
                        err=1,
                        fg='yellow')
            default_activation = None
    if pick_peaks:
        try:
            writer.remove_file_contents("profile spectrum")
        except KeyError:
            pass
        writer.add_file_contents("centroid spectrum")
    for bunch in reader:
        if bunch.precursor is not None:
            if ms1_filters:
                bunch = bunch._replace(
                    precursor=bunch.precursor.transform(ms1_filters))
            if (pick_peaks or not bunch.precursor.is_profile):
                bunch.precursor.pick_peaks()
        for i, product in enumerate(bunch.products):
            if msn_filters:
                product = bunch.products[i] = product.transform(msn_filters)
            if pick_peaks or not product.is_profile:
                product.pick_peaks()
            if product.activation is None and default_activation is not None:
                product.activation = default_activation
        writer.save_scan_bunch(bunch)
    writer.complete()
    writer.format()
Example #6
0
 def _acquisition_information(self, scan):
     fline = self._filter_string(scan)
     event = self._get_scan_event(scan)
     trailer_extras = self._trailer_values(scan)
     traits = {
         'preset scan configuration': event,
         'filter string': fline,
     }
     cv = fline.get("compensation_voltage")
     if cv is not None:
         traits[FAIMS_compensation_voltage] = cv
     event = ScanEventInformation(self._scan_time(scan),
                                  injection_time=unitfloat(
                                      trailer_extras.get(
                                          'Ion Injection Time (ms)', 0.0),
                                      'millisecond'),
                                  window_list=[
                                      ScanWindow(
                                          fline.get("scan_window")[0],
                                          fline.get("scan_window")[1])
                                  ],
                                  traits=traits)
     return ScanAcquisitionInformation("no combination", [event])
 def _handle_param(self, element, **kwargs):
     """Unpacks cvParam and userParam tags into key-value pairs"""
     types = {'int': unitint, 'float': unitfloat, 'string': unitstr}
     attribs = element.attrib
     unit_info = None
     unit_accesssion = None
     if 'unitCvRef' in attribs or 'unitName' in attribs:
         unit_accesssion = attribs.get('unitAccession')
         unit_name = attribs.get("unitName", unit_accesssion)
         unit_info = unit_name
     accession = attribs.get("accession")
     # value = attribs.get("value", "")
     if 'value' in attribs and attribs['value'] != '':
         try:
             if attribs.get('type') in types:
                 value = types[attribs['type']](attribs['value'], unit_info)
             else:
                 value = unitfloat(attribs['value'], unit_info)
         except ValueError:
             value = unitstr(attribs['value'], unit_info)
         return {cvstr(attribs['name'], accession, unit_accesssion): value}
     else:
         return {'name': cvstr(attribs['name'], accession, unit_accesssion)}
Example #8
0
def to_mzml(reader,
            outstream,
            pick_peaks=False,
            reprofile=False,
            ms1_filters=None,
            msn_filters=None,
            default_activation=None,
            correct_precursor_mz=False,
            write_index=True,
            update_metadata=True):
    """Translate the spectra from `reader` into mzML format written to `outstream`.

    Wraps the process of iterating over `reader`, performing a set of simple data transformations if desired,
    and then converts each :class:`~.Scan` into mzML format. Any data transformations are described in the
    appropriate metadata section. All other metadata from `reader` is copied to into `outstream`.

    Parameters
    ----------
    reader : :class:`~.ScanIterator`
        The source of spectra to iterate over
    outstream : file-like
        The output stream to write mzML to.
    pick_peaks : bool, optional
        Whether to centroid profile spectra (the default is False)
    reprofile: bool, optional
        Whether to reprofile spectra from their centroids (the default is False)
    ms1_filters : list, optional
        An optional list of strings or :class:`~.ScanFilterBase` instances which will be
        used to transform the m/z and intensity arrays of MS1 spectra before they are further
        processed (the default is None, which results in no transformations)
    msn_filters : list, optional
        An optional list of strings or :class:`~.ScanFilterBase` instances which will be
        used to transform the m/z and intennsity arrays of MSn spectra before they are futher
        procssed. (the default is None, which results in no transformations)
    default_activation : :class:`str` or :class:`dict`, optional
        A default activation type to use when `reader` does not contain that information (the default is None)
    correct_precursor_mz : bool, optional
        Whether or not to assign the precursor m/z of each product scan to the nearest peak
        m/z in the precursor's peak list. (the default is False, which results in no correction)

    """
    if ms1_filters is None:
        ms1_filters = []
    if msn_filters is None:
        msn_filters = []
    reader.make_iterator(grouped=True)
    writer = MzMLSerializer(outstream,
                            len(reader),
                            deconvoluted=False,
                            build_extra_index=write_index,
                            include_software_entry=update_metadata)
    writer.copy_metadata_from(reader)
    if update_metadata:
        method = data_transformation.ProcessingMethod(
            software_id='ms_deisotope_1')
        if pick_peaks:
            method.add('MS:1000035')
        if correct_precursor_mz:
            method.add('MS:1000780')
        if reprofile:
            method.add('MS:1000784')
        method.add('MS:1000544')
        writer.add_data_processing(method)
    if default_activation is not None:
        if isinstance(default_activation, basestring):
            default_activation = activation_module.ActivationInformation(
                default_activation, unitfloat(0, 'electronvolt'))
        elif isinstance(default_activation, dict):
            default_activation = activation_module.ActivationInformation(
                **default_activation)
        else:
            click.secho("Could not convert %r into ActivationInformation" %
                        (default_activation, ),
                        err=1,
                        fg='yellow')
            default_activation = None
    if pick_peaks:
        try:
            writer.remove_file_contents("profile spectrum")
        except KeyError:
            pass
        writer.add_file_contents("centroid spectrum")
    n_spectra = len(reader)
    progbar = progress(
        label="Processed Spectra",
        length=n_spectra,
        item_show_func=lambda x: str(x.precursor.id
                                     if x.precursor else x.products[0].id)
        if x else '')
    with progbar:
        for bunch in reader:
            progbar.current_item = bunch
            progbar.update((bunch.precursor is not None) + len(bunch.products))
            discard_peaks = False
            if bunch.precursor is not None:
                if (reprofile):
                    bunch = bunch._replace(
                        precursor=bunch.precursor.reprofile())
                if ms1_filters:
                    bunch = bunch._replace(
                        precursor=bunch.precursor.transform(ms1_filters))
                if (pick_peaks or not bunch.precursor.is_profile):
                    bunch.precursor.pick_peaks()
                if correct_precursor_mz:
                    if not pick_peaks:
                        bunch.precursor.pick_peaks()
                        if bunch.precursor.is_profile:
                            discard_peaks = True

            for i, product in enumerate(bunch.products):
                # if reprofile:
                #     product = bunch.products[i] = product.reprofile()
                if msn_filters:
                    product = bunch.products[i] = product.transform(
                        msn_filters)
                if pick_peaks or not product.is_profile:
                    product.pick_peaks()
                if product.activation is None and default_activation is not None:
                    product.activation = default_activation
                if correct_precursor_mz:
                    product.precursor_information.correct_mz()
            if discard_peaks:
                bunch.precursor.peak_set = None
            writer.save_scan_bunch(bunch)
    writer.complete()
    writer.format()
Example #9
0
def to_mzml(reader, outstream, pick_peaks=False, ms1_filters=None, msn_filters=None, default_activation=None,
            correct_precursor_mz=False):
    """Translate the spectra from `reader` into mzML format written to `outstream`.

    Wraps the process of iterating over `reader`, performing a set of simple data transformations if desired,
    and then converts each :class:`~.Scan` into mzML format. Any data transformations are described in the
    appropriate metadata section. All other metadata from `reader` is copied to into `outstream`.

    Parameters
    ----------
    reader : :class:`~.ScanIterator`
        The source of spectra to iterate over
    outstream : file-like
        The output stream to write mzML to.
    pick_peaks : bool, optional
        Whether to centroid profile spectra (the default is False)
    ms1_filters : list, optional
        An optional list of strings or :class:`~.ScanFilterBase` instances which will be
        used to transform the m/z and intensity arrays of MS1 spectra before they are further
        processed (the default is None, which results in no transformations)
    msn_filters : list, optional
        An optional list of strings or :class:`~.ScanFilterBase` instances which will be
        used to transform the m/z and intennsity arrays of MSn spectra before they are futher
        procssed. (the default is None, which results in no transformations)
    default_activation : :class:`str` or :class:`dict`, optional
        A default activation type to use when `reader` does not contain that information (the default is None)
    correct_precursor_mz : bool, optional
        Whether or not to assign the precursor m/z of each product scan to the nearest peak
        m/z in the precursor's peak list. (the default is False, which results in no correction)

    """
    if ms1_filters is None:
        ms1_filters = []
    if msn_filters is None:
        msn_filters = []
    reader.make_iterator(grouped=True)
    writer = MzMLSerializer(outstream, len(reader), deconvoluted=False)
    writer.copy_metadata_from(reader)
    method = data_transformation.ProcessingMethod(software_id='ms_deisotope_1')
    if pick_peaks:
        method.add('MS:1000035')
    if correct_precursor_mz:
        method.add('MS:1000780')
    method.add('MS:1000544')
    writer.add_data_processing(method)
    if default_activation is not None:
        if isinstance(default_activation, basestring):
            default_activation = activation_module.ActivationInformation(
                default_activation, unitfloat(0, 'electronvolt'))
        elif isinstance(default_activation, dict):
            default_activation = activation_module.ActivationInformation(**default_activation)
        else:
            click.secho("Could not convert %r into ActivationInformation" % (default_activation, ), err=1,
                        fg='yellow')
            default_activation = None
    if pick_peaks:
        try:
            writer.remove_file_contents("profile spectrum")
        except KeyError:
            pass
        writer.add_file_contents("centroid spectrum")
    for bunch in reader:
        discard_peaks = False
        if bunch.precursor is not None:
            if ms1_filters:
                bunch = bunch._replace(precursor=bunch.precursor.transform(ms1_filters))
            if (pick_peaks or not bunch.precursor.is_profile):
                bunch.precursor.pick_peaks()
            if correct_precursor_mz:
                if not pick_peaks:
                    bunch.precursor.pick_peaks()
                    if bunch.precursor.is_profile:
                        discard_peaks = True

        for i, product in enumerate(bunch.products):
            if msn_filters:
                product = bunch.products[i] = product.transform(msn_filters)
            if pick_peaks or not product.is_profile:
                product.pick_peaks()
            if product.activation is None and default_activation is not None:
                product.activation = default_activation
            if correct_precursor_mz:
                product.precursor_information.correct_mz()
        if discard_peaks:
            bunch.precursor.peak_set = None
        writer.save_scan_bunch(bunch)
    writer.complete()
    writer.format()