Documentation for Common.py

DummyFormula

A dummy wrapper to store an mz as a vimms.Common.Formula. This is convenient as it allows us to treat an m/z value like an (unknown) formula.

Source code in vimms/Common.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
class DummyFormula:
    """
    A dummy wrapper to store an mz as a [vimms.Common.Formula][].
    This is convenient as it allows us to treat an m/z value like an (unknown) formula.
    """

    def __init__(self, mz):
        """
        Create a DummyFormula object
        Args:
            mz: the m/z value to wrap
        """
        self.mass = mz

    def compute_exact_mass(self):
        return self.mass

__init__(mz)

Create a DummyFormula object Args: mz: the m/z value to wrap

Source code in vimms/Common.py
272
273
274
275
276
277
278
def __init__(self, mz):
    """
    Create a DummyFormula object
    Args:
        mz: the m/z value to wrap
    """
    self.mass = mz

Formula

A class to represent a chemical formula

Source code in vimms/Common.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
class Formula:
    """
    A class to represent a chemical formula
    """

    def __init__(self, formula_string):
        """
        Creates a Formula object. Formulae can be sampled to generate [vimms.Chemicals.Chemical][]
        objects.

        Args:
            formula_string (string): the chemical formula
        """
        self.formula_string = formula_string
        self.atom_names = ATOM_NAMES
        self.atoms = {}
        for atom in self.atom_names:
            self.atoms[atom] = self._get_n_element(atom)
        self.mass = self._get_mz()

    def _get_mz(self):
        """
        Computes the m/z value of this formula
        Returns: the m/z value

        """
        # Assume no charge
        return self.compute_exact_mass()

    def _get_n_element(self, atom_name):
        """
        Computes how many elements of an atom is present in the formula
        Args:
            atom_name: the atom to check

        Returns: the total number of atoms present in the formula

        """
        # Do some regex matching to find the numbers of the important atoms
        ex = atom_name + "(?![a-z])" + "\\d*"
        m = re.search(ex, self.formula_string)
        if m is None:
            return 0
        else:
            ex = atom_name + "(?![a-z])" + "(\\d*)"
            m2 = re.findall(ex, self.formula_string)
            total = 0
            for a in m2:
                if len(a) == 0:
                    total += 1
                else:
                    total += int(a)
            return total

    def compute_exact_mass(self):
        """
        Computes the exact mass of this formula
        Returns: the exact mass

        """
        masses = ATOM_MASSES
        exact_mass = 0.0
        for a in self.atoms:
            exact_mass += masses[a] * self.atoms[a]
        return exact_mass

    def __repr__(self):
        return self.formula_string

    def __str__(self):
        return self.formula_string

__init__(formula_string)

Creates a Formula object. Formulae can be sampled to generate vimms.Chemicals.Chemical objects.

Parameters:
  • formula_string (string) –

    the chemical formula

Source code in vimms/Common.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def __init__(self, formula_string):
    """
    Creates a Formula object. Formulae can be sampled to generate [vimms.Chemicals.Chemical][]
    objects.

    Args:
        formula_string (string): the chemical formula
    """
    self.formula_string = formula_string
    self.atom_names = ATOM_NAMES
    self.atoms = {}
    for atom in self.atom_names:
        self.atoms[atom] = self._get_n_element(atom)
    self.mass = self._get_mz()

compute_exact_mass()

Computes the exact mass of this formula Returns: the exact mass

Source code in vimms/Common.py
247
248
249
250
251
252
253
254
255
256
257
def compute_exact_mass(self):
    """
    Computes the exact mass of this formula
    Returns: the exact mass

    """
    masses = ATOM_MASSES
    exact_mass = 0.0
    for a in self.atoms:
        exact_mass += masses[a] * self.atoms[a]
    return exact_mass

Precursor

A class to store precursor peak information when writing an MS2 scan.

Source code in vimms/Common.py
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
class Precursor:
    """
    A class to store precursor peak information when writing an MS2 scan.
    """

    def __init__(self, precursor_mz, precursor_intensity, precursor_charge, precursor_scan_id):
        """
        Create a Precursor object.
        Args:
            precursor_mz: the m/z value of this precursor peak.
            precursor_intensity: the intensity value of this precursor peak.
            precursor_charge: the charge of this precursor peak
            precursor_scan_id: the assocated MS1 scan ID that contains this precursor peak
        """
        self.precursor_mz = precursor_mz
        self.precursor_intensity = precursor_intensity
        self.precursor_charge = precursor_charge
        self.precursor_scan_id = precursor_scan_id

    def __repr__(self):
        return "Precursor mz %f intensity %f charge %d scan_id %d" % (
            self.precursor_mz,
            self.precursor_intensity,
            self.precursor_charge,
            self.precursor_scan_id,
        )

__init__(precursor_mz, precursor_intensity, precursor_charge, precursor_scan_id)

Create a Precursor object. Args: precursor_mz: the m/z value of this precursor peak. precursor_intensity: the intensity value of this precursor peak. precursor_charge: the charge of this precursor peak precursor_scan_id: the assocated MS1 scan ID that contains this precursor peak

Source code in vimms/Common.py
400
401
402
403
404
405
406
407
408
409
410
411
412
def __init__(self, precursor_mz, precursor_intensity, precursor_charge, precursor_scan_id):
    """
    Create a Precursor object.
    Args:
        precursor_mz: the m/z value of this precursor peak.
        precursor_intensity: the intensity value of this precursor peak.
        precursor_charge: the charge of this precursor peak
        precursor_scan_id: the assocated MS1 scan ID that contains this precursor peak
    """
    self.precursor_mz = precursor_mz
    self.precursor_intensity = precursor_intensity
    self.precursor_charge = precursor_charge
    self.precursor_scan_id = precursor_scan_id

ScanParameters

A class to store parameters used to instruct the mass spec how to generate a scan. This object is usually created by the controller. It is used by the controller to instruct the mass spec what actions (scans) to perform next.

Source code in vimms/Common.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
class ScanParameters:
    """
    A class to store parameters used to instruct the mass spec how to
    generate a scan. This object is usually created by the controller.
    It is used by the controller to instruct the mass spec what actions (scans)
    to perform next.
    """

    MS_LEVEL = "ms_level"
    COLLISION_ENERGY = "collision_energy"
    POLARITY = "polarity"
    FIRST_MASS = "first_mass"
    LAST_MASS = "last_mass"
    ORBITRAP_RESOLUTION = "orbitrap_resolution"
    AGC_TARGET = "agc_target"
    MAX_IT = "max_it"
    MASS_ANALYSER = "analyzer"
    ACTIVATION_TYPE = "activation_type"
    ISOLATION_MODE = "isolation_mode"
    SOURCE_CID_ENERGY = "source_cid_energy"
    METADATA = "metadata"
    UNIQUENESS_TOKEN = "uniqueness_token"

    # this is used for DIA-based controllers to specify which windows to
    # fragment
    ISOLATION_WINDOWS = "isolation_windows"

    # precursor m/z and isolation width have to be specified together for
    # DDA-based controllers
    PRECURSOR_MZ = "precursor_mz"
    ISOLATION_WIDTH = "isolation_width"

    # used in Top-N, hybrid and ROI controllers to perform dynamic exclusion
    DYNAMIC_EXCLUSION_MZ_TOL = "dew_mz_tol"
    DYNAMIC_EXCLUSION_RT_TOL = "dew_rt_tol"

    # only used by the hybrid controller for now, since its Top-N may change
    # depending on time for other DDA controllers it's always the same
    # throughout the whole run, so we don't send this parameter
    CURRENT_TOP_N = "current_top_N"

    # if the scan id is specified, then it should be used by the mass spec
    # useful for pre-scheduled controllers where we want the controller
    # to know the scan ids of MS1, MS2
    # and also the precursor ids of those MS2 scans in advance.
    SCAN_ID = "scan_id"

    def __init__(self):
        """
        Create a scan parameter object
        """
        self.params = {}

    def set(self, key, value):
        """
        Set scan parameter value

        Args:
            key: a scan parameter name
            value: a scan parameter value

        Returns: None
        """
        self.params[key] = value

    def get(self, key):
        """
        Gets scan parameter value

        Args:
            key: the key to look for

        Returns: the corresponding value in this ScanParameter
        """
        if key in self.params:
            return self.params[key]
        else:
            return None

    def get_all(self):
        """
        Get all scan parameters
        Returns: all the scan parameters
        """
        return self.params

    def compute_isolation_windows(self):
        """
        Gets the full-width (DDA) isolation window around a precursor m/z
        """
        precursor_list = self.get(ScanParameters.PRECURSOR_MZ)
        precursor_mz_list = [precursor.precursor_mz for precursor in precursor_list]
        isolation_width_list = self.get(ScanParameters.ISOLATION_WIDTH)
        return compute_isolation_windows(isolation_width_list, precursor_mz_list)

    def __repr__(self):
        return "ScanParameters %s" % (self.params)

__init__()

Create a scan parameter object

Source code in vimms/Common.py
331
332
333
334
335
def __init__(self):
    """
    Create a scan parameter object
    """
    self.params = {}

compute_isolation_windows()

Gets the full-width (DDA) isolation window around a precursor m/z

Source code in vimms/Common.py
370
371
372
373
374
375
376
377
def compute_isolation_windows(self):
    """
    Gets the full-width (DDA) isolation window around a precursor m/z
    """
    precursor_list = self.get(ScanParameters.PRECURSOR_MZ)
    precursor_mz_list = [precursor.precursor_mz for precursor in precursor_list]
    isolation_width_list = self.get(ScanParameters.ISOLATION_WIDTH)
    return compute_isolation_windows(isolation_width_list, precursor_mz_list)

get(key)

Gets scan parameter value

Parameters:
  • key

    the key to look for

Returns: the corresponding value in this ScanParameter

Source code in vimms/Common.py
349
350
351
352
353
354
355
356
357
358
359
360
361
def get(self, key):
    """
    Gets scan parameter value

    Args:
        key: the key to look for

    Returns: the corresponding value in this ScanParameter
    """
    if key in self.params:
        return self.params[key]
    else:
        return None

get_all()

Get all scan parameters Returns: all the scan parameters

Source code in vimms/Common.py
363
364
365
366
367
368
def get_all(self):
    """
    Get all scan parameters
    Returns: all the scan parameters
    """
    return self.params

set(key, value)

Set scan parameter value

Parameters:
  • key

    a scan parameter name

  • value

    a scan parameter value

Returns: None

Source code in vimms/Common.py
337
338
339
340
341
342
343
344
345
346
347
def set(self, key, value):
    """
    Set scan parameter value

    Args:
        key: a scan parameter name
        value: a scan parameter value

    Returns: None
    """
    self.params[key] = value

add_log_file(log_path, level)

Add path to log file Args: log_path: filename to output the logging to level: the log level

Returns: None

Source code in vimms/Common.py
604
605
606
607
608
609
610
611
612
613
614
def add_log_file(log_path, level):
    """
    Add path to log file
    Args:
        log_path: filename to output the logging to
        level: the log level

    Returns: None

    """
    logger.add(log_path, level=level)

chromatogramDensityNormalisation(rts, intensities)

Definition to standardise the area under a chromatogram to 1.

Parameters:
  • rts

    the RT values of this chromatogram

  • intensities

    the intensity values of this chromatogram

Returns: updated intensities that have been standardised so the area is 1.

Source code in vimms/Common.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
def chromatogramDensityNormalisation(rts, intensities):
    """
    Definition to standardise the area under a chromatogram to 1.

    Args:
        rts: the RT values of this chromatogram
        intensities: the intensity values of this chromatogram

    Returns: updated intensities that have been standardised so the area is 1.

    """
    assert len(rts) == len(intensities)
    area = 0.0
    for rt_index in range(len(rts) - 1):
        area += ((intensities[rt_index] + intensities[rt_index + 1]) / 2) / (
            rts[rt_index + 1] - rts[rt_index]
        )
    new_intensities = [x * (1 / area) for x in intensities]
    return new_intensities

create_if_not_exist(out_dir)

Creates a directory if it doesn't already exist Args: out_dir: the directory to create, if it doesn't exist

Returns: None.

Source code in vimms/Common.py
428
429
430
431
432
433
434
435
436
437
438
439
def create_if_not_exist(out_dir):
    """
    Creates a directory if it doesn't already exist
    Args:
        out_dir: the directory to create, if it doesn't exist

    Returns: None.

    """
    if not pathlib.Path(out_dir).exists():
        logger.info("Created %s" % out_dir)
        pathlib.Path(out_dir).mkdir(parents=True, exist_ok=True)

download_file(url, out_file=None)

Download a file from the given URL Args: url: URL to download out_file: filename of output file to save to

Returns: filename of the out_file

Source code in vimms/Common.py
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
def download_file(url, out_file=None):
    """
    Download a file from the given URL
    Args:
        url: URL to download
        out_file: filename of output file to save to

    Returns: filename of the out_file

    """
    r = requests.get(url, stream=True)
    total_size = int(r.headers.get("content-length", 0))
    block_size = 1024
    current_size = 0

    if out_file is None:
        out_file = url.rsplit("/", 1)[-1]  # get the last part in url
    logger.info("Downloading %s" % out_file)

    with open(out_file, "wb") as f:
        for data in tqdm(
            r.iter_content(block_size),
            total=math.ceil(total_size // block_size),
            unit="KB",
            unit_scale=True,
        ):
            current_size += len(data)
            f.write(data)
    assert current_size == total_size
    return out_file

extract_zip_file(in_file, delete=True)

Extract a zip file Args: in_file: the input zip file delete: whether to delete the input zip file after extracting

Returns: None

Source code in vimms/Common.py
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
def extract_zip_file(in_file, delete=True):
    """
    Extract a zip file
    Args:
        in_file: the input zip file
        delete: whether to delete the input zip file after extracting

    Returns: None

    """
    logger.info("Extracting %s" % in_file)
    with zipfile.ZipFile(file=in_file) as zip_file:
        for file in tqdm(iterable=zip_file.namelist(), total=len(zip_file.namelist())):
            zip_file.extract(member=file)

    if delete:
        logger.info("Deleting %s" % in_file)
        os.remove(in_file)

find_nearest_index_in_array(array, value)

Finds index in array where the value is the nearest

Parameters:
  • array

    the array to check

  • value

    the value to check

Returns: index in array where the value is the nearest

Source code in vimms/Common.py
633
634
635
636
637
638
639
640
641
642
643
644
645
def find_nearest_index_in_array(array, value):
    """
    Finds index in array where the value is the nearest

    Args:
        array: the array to check
        value: the value to check

    Returns: index in array where the value is the nearest

    """
    idx = (np.abs(array - value)).argmin()
    return idx

get_dda_scan_param(mz, intensity, precursor_scan_id, isolation_width, mz_tol, rt_tol, agc_target=DEFAULT_MS2_AGC_TARGET, max_it=DEFAULT_MS2_MAXIT, collision_energy=DEFAULT_MS2_COLLISION_ENERGY, source_cid_energy=DEFAULT_SOURCE_CID_ENERGY, orbitrap_resolution=DEFAULT_MS2_ORBITRAP_RESOLUTION, mass_analyser=DEFAULT_MS2_MASS_ANALYSER, activation_type=DEFAULT_MS1_ACTIVATION_TYPE, isolation_mode=DEFAULT_MS2_ISOLATION_MODE, polarity=POSITIVE, metadata=None, scan_id=None)

Generate the default MS2 scan parameters.

Parameters:
  • mz

    m/z of precursor peak to fragment

  • intensity

    intensity of precursor peak to fragment

  • precursor_scan_id

    scan ID of the MS1 scan containing the precursor peak

  • isolation_width

    isolation width, in Dalton

  • mz_tol

    m/z tolerance for dynamic exclusion # FIXME: this shouldn't be here

  • rt_tol

    RT tolerance for dynamic exclusion # FIXME: this shouldn't be here

  • agc_target

    AGC (automatic gain control) target

  • max_it

    maximum time to collect ion

  • collision_energy

    the collision energy to use

  • source_cid_energy

    source CID energy

  • orbitrap_resolution

    resolution of the mass-spec (Orbitrap) instrument

  • mass_analyser

    which mass analyser to use

  • activation_type

    activation type, either HCD or CID

  • isolation_mode

    isolation mode, either None, or Quadrupole or IonTrap

  • polarity

    the polarity value, either POSITIVE or NEGATIVE

  • metadata

    additional metadata to include in this scan

  • scan_id

    the scan ID, if specified

Returns: the parameters of the MS2 scan to create

Source code in vimms/Common.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
def get_dda_scan_param(
    mz,
    intensity,
    precursor_scan_id,
    isolation_width,
    mz_tol,
    rt_tol,
    agc_target=DEFAULT_MS2_AGC_TARGET,
    max_it=DEFAULT_MS2_MAXIT,
    collision_energy=DEFAULT_MS2_COLLISION_ENERGY,
    source_cid_energy=DEFAULT_SOURCE_CID_ENERGY,
    orbitrap_resolution=DEFAULT_MS2_ORBITRAP_RESOLUTION,
    mass_analyser=DEFAULT_MS2_MASS_ANALYSER,
    activation_type=DEFAULT_MS1_ACTIVATION_TYPE,
    isolation_mode=DEFAULT_MS2_ISOLATION_MODE,
    polarity=POSITIVE,
    metadata=None,
    scan_id=None,
):
    """
    Generate the default MS2 scan parameters.

    Args:
        mz: m/z of precursor peak to fragment
        intensity: intensity of precursor peak to fragment
        precursor_scan_id: scan ID of the MS1 scan containing the precursor peak
        isolation_width: isolation width, in Dalton
        mz_tol: m/z tolerance for dynamic exclusion # FIXME: this shouldn't be here
        rt_tol: RT tolerance for dynamic exclusion # FIXME: this shouldn't be here
        agc_target: AGC (automatic gain control) target
        max_it: maximum time to collect ion
        collision_energy: the collision energy to use
        source_cid_energy: source CID energy
        orbitrap_resolution: resolution of the mass-spec (Orbitrap) instrument
        mass_analyser: which mass analyser to use
        activation_type: activation type, either HCD or CID
        isolation_mode: isolation mode, either None, or Quadrupole or IonTrap
        polarity: the polarity value, either POSITIVE or NEGATIVE
        metadata: additional metadata to include in this scan
        scan_id: the scan ID, if specified

    Returns: the parameters of the MS2 scan to create

    """

    dda_scan_params = ScanParameters()
    dda_scan_params.set(ScanParameters.MS_LEVEL, 2)

    assert isinstance(mz, list) == isinstance(intensity, list)

    # create precursor object, assume it's all singly charged
    precursor_charge = +1 if (polarity == POSITIVE) else -1
    if isinstance(mz, list):
        precursor_list = []
        for i, m in enumerate(mz):
            precursor_list.append(
                Precursor(
                    precursor_mz=m,
                    precursor_intensity=intensity[i],
                    precursor_charge=precursor_charge,
                    precursor_scan_id=precursor_scan_id,
                )
            )
        dda_scan_params.set(ScanParameters.PRECURSOR_MZ, precursor_list)

        if isinstance(isolation_width, list):
            assert len(isolation_width) == len(precursor_list)
        else:
            isolation_width = [isolation_width for m in mz]
        dda_scan_params.set(ScanParameters.ISOLATION_WIDTH, isolation_width)

    else:
        precursor = Precursor(
            precursor_mz=mz,
            precursor_intensity=intensity,
            precursor_charge=precursor_charge,
            precursor_scan_id=precursor_scan_id,
        )
        precursor_list = [precursor]
        dda_scan_params.set(ScanParameters.PRECURSOR_MZ, precursor_list)

        # set the full-width isolation width, in Da
        # if mz is not a list, neither should isolation_width be
        assert not isinstance(isolation_width, list)
        isolation_width = [isolation_width]
        dda_scan_params.set(ScanParameters.ISOLATION_WIDTH, isolation_width)

    # define dynamic exclusion parameters
    dda_scan_params.set(ScanParameters.DYNAMIC_EXCLUSION_MZ_TOL, mz_tol)
    dda_scan_params.set(ScanParameters.DYNAMIC_EXCLUSION_RT_TOL, rt_tol)

    # define other fragmentation parameters
    dda_scan_params.set(ScanParameters.COLLISION_ENERGY, collision_energy)
    dda_scan_params.set(ScanParameters.ORBITRAP_RESOLUTION, orbitrap_resolution)
    dda_scan_params.set(ScanParameters.ACTIVATION_TYPE, activation_type)
    dda_scan_params.set(ScanParameters.MASS_ANALYSER, mass_analyser)
    dda_scan_params.set(ScanParameters.ISOLATION_MODE, isolation_mode)
    dda_scan_params.set(ScanParameters.AGC_TARGET, agc_target)
    dda_scan_params.set(ScanParameters.MAX_IT, max_it)
    dda_scan_params.set(ScanParameters.SOURCE_CID_ENERGY, source_cid_energy)
    dda_scan_params.set(ScanParameters.POLARITY, polarity)
    dda_scan_params.set(ScanParameters.FIRST_MASS, DEFAULT_MSN_SCAN_WINDOW[0])
    dda_scan_params.set(ScanParameters.METADATA, metadata)
    dda_scan_params.set(ScanParameters.SCAN_ID, scan_id)

    # dynamically scale the upper mass
    charge = 1
    wiggle_room = 1.1
    max_precursor_mz = max(
        [(p.precursor_mz + isol / 2) for (p, isol) in zip(precursor_list, isolation_width)]
    )
    last_mass = max_precursor_mz * charge * wiggle_room
    dda_scan_params.set(ScanParameters.LAST_MASS, last_mass)
    return dda_scan_params

get_default_scan_params(polarity=POSITIVE, agc_target=DEFAULT_MS1_AGC_TARGET, max_it=DEFAULT_MS1_MAXIT, collision_energy=DEFAULT_MS1_COLLISION_ENERGY, source_cid_energy=DEFAULT_SOURCE_CID_ENERGY, orbitrap_resolution=DEFAULT_MS1_ORBITRAP_RESOLUTION, default_ms1_scan_window=DEFAULT_MS1_SCAN_WINDOW, mass_analyser=DEFAULT_MS1_MASS_ANALYSER, activation_type=DEFAULT_MS1_ACTIVATION_TYPE, isolation_mode=DEFAULT_MS1_ISOLATION_MODE, metadata=None, scan_id=None)

Generate the default MS1 scan parameters.

Parameters:
  • polarity

    the polarity value, either POSITIVE or NEGATIVE

  • agc_target

    AGC (automatic gain control) target

  • max_it

    maximum time to collect ion

  • collision_energy

    the collision energy to use

  • source_cid_energy

    source CID energy

  • orbitrap_resolution

    resolution of the mass-spec (Orbitrap) instrument

  • default_ms1_scan_window

    the default MS1 scan window

  • mass_analyser

    which mass analyser to use

  • activation_type

    activation type, either HCD or CID

  • isolation_mode

    isolation mode, either None, or Quadrupole or IonTrap

  • metadata

    additional metadata to include in this scan

  • scan_id

    the scan ID, if specified

Returns: the parameters of the MS1 scan to create

Source code in vimms/Common.py
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
def get_default_scan_params(
    polarity=POSITIVE,
    agc_target=DEFAULT_MS1_AGC_TARGET,
    max_it=DEFAULT_MS1_MAXIT,
    collision_energy=DEFAULT_MS1_COLLISION_ENERGY,
    source_cid_energy=DEFAULT_SOURCE_CID_ENERGY,
    orbitrap_resolution=DEFAULT_MS1_ORBITRAP_RESOLUTION,
    default_ms1_scan_window=DEFAULT_MS1_SCAN_WINDOW,
    mass_analyser=DEFAULT_MS1_MASS_ANALYSER,
    activation_type=DEFAULT_MS1_ACTIVATION_TYPE,
    isolation_mode=DEFAULT_MS1_ISOLATION_MODE,
    metadata=None,
    scan_id=None,
):
    """
    Generate the default MS1 scan parameters.

    Args:
        polarity: the polarity value, either POSITIVE or NEGATIVE
        agc_target: AGC (automatic gain control) target
        max_it: maximum time to collect ion
        collision_energy: the collision energy to use
        source_cid_energy: source CID energy
        orbitrap_resolution: resolution of the mass-spec (Orbitrap) instrument
        default_ms1_scan_window: the default MS1 scan window
        mass_analyser: which mass analyser to use
        activation_type: activation type, either HCD or CID
        isolation_mode: isolation mode, either None, or Quadrupole or IonTrap
        metadata: additional metadata to include in this scan
        scan_id: the scan ID, if specified

    Returns: the parameters of the MS1 scan to create

    """
    default_scan_params = ScanParameters()
    default_scan_params.set(ScanParameters.MS_LEVEL, 1)
    default_scan_params.set(ScanParameters.ISOLATION_WINDOWS, [[default_ms1_scan_window]])
    default_scan_params.set(ScanParameters.ISOLATION_WIDTH, DEFAULT_ISOLATION_WIDTH)
    default_scan_params.set(ScanParameters.COLLISION_ENERGY, collision_energy)
    default_scan_params.set(ScanParameters.ORBITRAP_RESOLUTION, orbitrap_resolution)
    default_scan_params.set(ScanParameters.ACTIVATION_TYPE, activation_type)
    default_scan_params.set(ScanParameters.MASS_ANALYSER, mass_analyser)
    default_scan_params.set(ScanParameters.ISOLATION_MODE, isolation_mode)
    default_scan_params.set(ScanParameters.AGC_TARGET, agc_target)
    default_scan_params.set(ScanParameters.MAX_IT, max_it)
    default_scan_params.set(ScanParameters.SOURCE_CID_ENERGY, source_cid_energy)
    default_scan_params.set(ScanParameters.POLARITY, polarity)
    default_scan_params.set(ScanParameters.FIRST_MASS, default_ms1_scan_window[0])
    default_scan_params.set(ScanParameters.LAST_MASS, default_ms1_scan_window[1])
    default_scan_params.set(ScanParameters.METADATA, metadata)
    default_scan_params.set(ScanParameters.SCAN_ID, scan_id)
    return default_scan_params

get_rt(spectrum)

Extracts RT value from a pymzml spectrum object

Parameters:
  • spectrum

    a pymzml spectrum object

Returns: the retention time (in seconds)

Source code in vimms/Common.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
def get_rt(spectrum):
    """
    Extracts RT value from a pymzml spectrum object

    Args:
        spectrum: a pymzml spectrum object

    Returns: the retention time (in seconds)

    """
    rt, units = spectrum.scan_time
    if units == "minute":
        rt *= 60.0
    return rt

load_obj(filename)

Load saved object from file

Parameters:
  • filename

    The filename to load. Should be saved using the save_obj method.

Returns: the loaded object

Source code in vimms/Common.py
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def load_obj(filename):
    """
    Load saved object from file

    Args:
        filename: The filename to load. Should be saved using the `save_obj` method.

    Returns: the loaded object

    """
    try:
        with gzip.GzipFile(filename, "rb") as f:
            return pickle.load(f)
    except OSError:
        logger.warning(
            "Old, invalid or missing pickle in %s. " "Please regenerate this file." % filename
        )
        raise

save_obj(obj, filename)

Save object to file. This is useful for storing simulation results and other objects.

If the directory containing the specified filename doesn't exist, it will be created first. The object will be saved using gzip + pickle (highest protocol).

Parameters:
  • obj

    the Python object to save

  • filename

    the output filename to use

Returns: None

Source code in vimms/Common.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def save_obj(obj, filename):
    """
    Save object to file. This is useful for storing simulation results and other objects.

    If the directory containing the specified filename doesn't exist, it will be created first.
    The object will be saved using gzip + pickle (highest protocol).

    Args:
        obj: the Python object to save
        filename: the output filename to use

    Returns: None
    """

    # workaround for
    # TypeError: can't pickle _thread.lock objects
    # when trying to pickle a progress bar
    if hasattr(obj, "bar"):
        obj.bar = None

    out_dir = os.path.dirname(filename)
    create_if_not_exist(out_dir)
    logger.info("Saving %s to %s" % (type(obj), filename))
    with gzip.GzipFile(filename, "w") as f:
        pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL)

set_log_level(level, remove_id=None)

Set the logging level of the default logger Args: level: the new level to set remove_id: ID of previous log handler to be removed

Returns: the new log handler after setting the log level

Source code in vimms/Common.py
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
def set_log_level(level, remove_id=None):
    """
    Set the logging level of the default logger
    Args:
        level: the new level to set
        remove_id: ID of previous log handler to be removed

    Returns: the new log handler after setting the log level

    """
    if remove_id is None:
        logger.remove()  # remove all previously set handlers
    else:
        try:
            logger.remove(remove_id)  # remove previously set handler by id
        except ValueError:  # can't find the handler
            pass

    # add new handler at the desired log level
    new_handler_id = logger.add(sys.stderr, level=level)
    return new_handler_id

set_log_level_debug(remove_id=None)

Set log level to DEBUG Args: remove_id: ID of previous log handler to be removed

Returns: None

Source code in vimms/Common.py
592
593
594
595
596
597
598
599
600
601
def set_log_level_debug(remove_id=None):
    """
    Set log level to DEBUG
    Args:
        remove_id: ID of previous log handler to be removed

    Returns: None

    """
    return set_log_level(logging.DEBUG, remove_id=remove_id)

set_log_level_info(remove_id=None)

Set log level to INFO Args: remove_id: ID of previous log handler to be removed

Returns: None

Source code in vimms/Common.py
580
581
582
583
584
585
586
587
588
589
def set_log_level_info(remove_id=None):
    """
    Set log level to INFO
    Args:
        remove_id: ID of previous log handler to be removed

    Returns: None

    """
    return set_log_level(logging.INFO, remove_id=remove_id)

set_log_level_warning(remove_id=None)

Set log level to WARNING Args: remove_id: ID of previous log handler to be removed

Returns: None

Source code in vimms/Common.py
568
569
570
571
572
573
574
575
576
577
def set_log_level_warning(remove_id=None):
    """
    Set log level to WARNING
    Args:
        remove_id: ID of previous log handler to be removed

    Returns: None

    """
    return set_log_level(logging.WARNING, remove_id=remove_id)

uniform_list(N, min_val, max_val)

Generates a list of N uniformly random values from min_val to max_val Args: N: the number of items to generate min_val: the minimum range max_val: the maximum range

Returns: a list of N values

Source code in vimms/Common.py
700
701
702
703
704
705
706
707
708
709
710
711
def uniform_list(N, min_val, max_val):
    """
    Generates a list of N uniformly random values from min_val to max_val
    Args:
        N: the number of items to generate
        min_val: the minimum range
        max_val: the maximum range

    Returns: a list of N values

    """
    return list(np.random.rand(N) * (max_val - min_val) + min_val)