Skip to content

Documentation for Common.py

Common

DummyFormula

DummyFormula(mz)

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.

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

Source code in vimms/Common.py
337
338
339
340
341
342
343
def __init__(self, mz):
    """
    Create a DummyFormula object
    Args:
        mz: the m/z value to wrap
    """
    self.mass = mz

Formula

Formula(formula_string)

A class to represent a chemical formula

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

Parameters:

Name Type Description Default
formula_string string

the chemical formula

required
Source code in vimms/Common.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
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

compute_exact_mass()

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

Source code in vimms/Common.py
312
313
314
315
316
317
318
319
320
321
322
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

Precursor(
    precursor_mz, precursor_intensity, precursor_charge, precursor_scan_id
)

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

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
465
466
467
468
469
470
471
472
473
474
475
476
477
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

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.

Create a scan parameter object

Source code in vimms/Common.py
396
397
398
399
400
def __init__(self):
    """
    Create a scan parameter object
    """
    self.params = {}

compute_isolation_windows

compute_isolation_windows()

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

Source code in vimms/Common.py
435
436
437
438
439
440
441
442
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

get(key)

Gets scan parameter value

Parameters:

Name Type Description Default
key

the key to look for

required

Returns: the corresponding value in this ScanParameter

Source code in vimms/Common.py
414
415
416
417
418
419
420
421
422
423
424
425
426
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()

Get all scan parameters Returns: all the scan parameters

Source code in vimms/Common.py
428
429
430
431
432
433
def get_all(self):
    """
    Get all scan parameters
    Returns: all the scan parameters
    """
    return self.params

set

set(key, value)

Set scan parameter value

Parameters:

Name Type Description Default
key

a scan parameter name

required
value

a scan parameter value

required

Returns: None

Source code in vimms/Common.py
402
403
404
405
406
407
408
409
410
411
412
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

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
669
670
671
672
673
674
675
676
677
678
679
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

chromatogramDensityNormalisation(rts, intensities)

Definition to standardise the area under a chromatogram to 1.

Parameters:

Name Type Description Default
rts

the RT values of this chromatogram

required
intensities

the intensity values of this chromatogram

required

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

Source code in vimms/Common.py
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
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

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
493
494
495
496
497
498
499
500
501
502
503
504
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

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
713
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
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

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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
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

find_nearest_index_in_array(array, value)

Finds index in array where the value is the nearest

Parameters:

Name Type Description Default
array

the array to check

required
value

the value to check

required

Returns: index in array where the value is the nearest

Source code in vimms/Common.py
698
699
700
701
702
703
704
705
706
707
708
709
710
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

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:

Name Type Description Default
mz

m/z of precursor peak to fragment

required
intensity

intensity of precursor peak to fragment

required
precursor_scan_id

scan ID of the MS1 scan containing the precursor peak

required
isolation_width

isolation width, in Dalton

required
mz_tol

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

required
rt_tol

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

required
agc_target

AGC (automatic gain control) target

DEFAULT_MS2_AGC_TARGET
max_it

maximum time to collect ion

DEFAULT_MS2_MAXIT
collision_energy

the collision energy to use

DEFAULT_MS2_COLLISION_ENERGY
source_cid_energy

source CID energy

DEFAULT_SOURCE_CID_ENERGY
orbitrap_resolution

resolution of the mass-spec (Orbitrap) instrument

DEFAULT_MS2_ORBITRAP_RESOLUTION
mass_analyser

which mass analyser to use

DEFAULT_MS2_MASS_ANALYSER
activation_type

activation type, either HCD or CID

DEFAULT_MS1_ACTIVATION_TYPE
isolation_mode

isolation mode, either None, or Quadrupole or IonTrap

DEFAULT_MS2_ISOLATION_MODE
polarity

the polarity value, either POSITIVE or NEGATIVE

POSITIVE
metadata

additional metadata to include in this scan

None
scan_id

the scan ID, if specified

None

Returns: the parameters of the MS2 scan to create

Source code in vimms/Common.py
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
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

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:

Name Type Description Default
polarity

the polarity value, either POSITIVE or NEGATIVE

POSITIVE
agc_target

AGC (automatic gain control) target

DEFAULT_MS1_AGC_TARGET
max_it

maximum time to collect ion

DEFAULT_MS1_MAXIT
collision_energy

the collision energy to use

DEFAULT_MS1_COLLISION_ENERGY
source_cid_energy

source CID energy

DEFAULT_SOURCE_CID_ENERGY
orbitrap_resolution

resolution of the mass-spec (Orbitrap) instrument

DEFAULT_MS1_ORBITRAP_RESOLUTION
default_ms1_scan_window

the default MS1 scan window

DEFAULT_MS1_SCAN_WINDOW
mass_analyser

which mass analyser to use

DEFAULT_MS1_MASS_ANALYSER
activation_type

activation type, either HCD or CID

DEFAULT_MS1_ACTIVATION_TYPE
isolation_mode

isolation mode, either None, or Quadrupole or IonTrap

DEFAULT_MS1_ISOLATION_MODE
metadata

additional metadata to include in this scan

None
scan_id

the scan ID, if specified

None

Returns: the parameters of the MS1 scan to create

Source code in vimms/Common.py
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
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

get_rt(spectrum)

Extracts RT value from a pymzml spectrum object

Parameters:

Name Type Description Default
spectrum

a pymzml spectrum object

required

Returns: the retention time (in seconds)

Source code in vimms/Common.py
682
683
684
685
686
687
688
689
690
691
692
693
694
695
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

load_obj(filename)

Load saved object from file

Parameters:

Name Type Description Default
filename

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

required

Returns: the loaded object

Source code in vimms/Common.py
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
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

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:

Name Type Description Default
obj

the Python object to save

required
filename

the output filename to use

required

Returns: None

Source code in vimms/Common.py
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
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

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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
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

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
657
658
659
660
661
662
663
664
665
666
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

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
645
646
647
648
649
650
651
652
653
654
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

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
633
634
635
636
637
638
639
640
641
642
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

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
765
766
767
768
769
770
771
772
773
774
775
776
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)