### Install matchms via Conda Source: https://matchms.readthedocs.io/en/latest/_sources/index.rst.txt Recommended installation method using a dedicated Conda environment. ```bash conda create -n matchms python=3.12 conda activate matchms conda install -c conda-forge -c bioconda matchms ``` -------------------------------- ### Build an ANN index Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/BaseEmbeddingSimilarity.html Constructs an ANN index for reference spectra using the pynndescent backend. Requires pynndescent to be installed. ```python def build_ann_index( self, reference_spectra: Optional[Iterable[SpectrumType]] = None, embeddings_path: Optional[Union[str, Path]] = None, k: int = 100, index_backend: str = "pynndescent", **index_kwargs) -> Any: """Build an ANN index for the reference spectra. Parameters ---------- reference_spectra : Optional[Iterable[SpectrumType]] List of reference spectra to build the ANN index for. embeddings_path : Optional[Union[str, Path]] If embeddings are already computed, provide the path to the numpy file. k : int, optional Number of nearest neighbors to use for the ANN index. index_backend : str, optional Backend to use for ANN index. Currently only "pynndescent" is supported. **index_kwargs Additional keyword arguments passed to the index constructor. Returns ------- Any The constructed ANN index. Raises ------ ImportError If pynndescent is not installed. ValueError If an unsupported index_backend is specified. """ # Compute reference embeddings embs_ref = self.get_embeddings(reference_spectra, embeddings_path) if index_backend == "pynndescent": if not pynndescent: raise ImportError("pynndescent is not installed. Please install it with `pip install pynndescent`.") self.index_backend = index_backend self.index_k = k self.index_kwargs = index_kwargs # Build ANN index index = pynndescent.NNDescent(embs_ref, metric=self.similarity, n_neighbors=k, **index_kwargs) else: raise ValueError(f"Only pynndescent is supported for now. Got {index_backend}.") # Keep index in memory self.index = index return self.index ``` -------------------------------- ### Load MSP file with matchms Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/importing/load_from_msp.html Demonstrates how to import the load_from_msp function and convert an MSP file into a list of Spectrum objects. ```python from matchms.importing import load_from_msp # Download msp file from MassBank of North America repository at https://mona.fiehnlab.ucdavis.edu/ file_msp = "MoNA-export-GC-MS-first10.msp" spectra = list(load_from_msp(file_msp)) ``` -------------------------------- ### get(key, default=None) Source: https://matchms.readthedocs.io/en/latest/api/matchms.Metadata.html Retrieves a value from the metadata dictionary by key. ```APIDOC ## get(key, default=None) ### Description Retrieves the value associated with the provided key from the metadata dictionary. ### Parameters - **key** (str) - Required - The key to retrieve. - **default** (any) - Optional - The value to return if the key is not found. ``` -------------------------------- ### Pipeline.__init__(workflow, progress_bar=True, logging_level='WARNING', logging_file=None) Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Pipeline.html Initializes a new Pipeline instance with a defined workflow configuration. ```APIDOC ### Constructor #### Description Initializes the pipeline with a workflow configuration, which can be generated using `create_workflow`. #### Parameters - **workflow** (OrderedDict) - Required - The workflow settings containing query_filters, reference_filters, and score_computations. - **progress_bar** (bool) - Optional - Whether to display a progress bar. Defaults to True. - **logging_level** (str) - Optional - The logging level (e.g., 'WARNING'). Defaults to 'WARNING'. - **logging_file** (str) - Optional - Path to a file for logging output. ``` -------------------------------- ### get(key, default=None) Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Spectrum.html Retrieves a value from the spectrum metadata dictionary. ```APIDOC ### Method `spectrum.get(key, default=None)` ### Description Retrieve a value from the internal metadata dictionary using the specified key. ### Parameters - **key** (str) - Required - The key to look up in the metadata. - **default** (any) - Optional - The value to return if the key is not found (default: None). ``` -------------------------------- ### FlashSimilarity.__init__ Source: https://matchms.readthedocs.io/en/latest/api/matchms.similarity.FlashSimilarity.html Initializes the FlashSimilarity object with configuration for spectral entropy or cosine similarity calculations. ```APIDOC ## class matchms.similarity.FlashSimilarity.FlashSimilarity ### Description Initializes the similarity calculator with specific parameters for entropy weighting, noise removal, and matching modes. ### Parameters - **score_type** (str) - Optional - Score type: 'spectral_entropy' (default) or 'cosine'. - **matching_mode** (str) - Optional - Matching mode: 'fragment', 'neutral_loss', or 'hybrid'. - **tolerance** (float) - Optional - Matching tolerance in Da or ppm. Default is 0.02. - **use_ppm** (bool) - Optional - If True, interpret tolerance as ppm. Default is False. - **remove_precursor** (bool) - Optional - If True, remove precursor peak and peaks within precursor_window. - **precursor_window** (float) - Optional - Window size around precursor m/z if remove_precursor is True. Default is 1.6. - **noise_cutoff** (float) - Optional - Remove peaks below this fraction of max intensity. Default is 0.01. - **normalize_to_half** (bool) - Optional - Normalize intensities to sum to 0.5. Default is True. - **merge_within** (float) - Optional - Merge peaks within this distance in Da. Default is 0. - **identity_precursor_tolerance** (float) - Optional - Enforce identity search by requiring precursor m/z match within this tolerance. - **identity_use_ppm** (bool) - Optional - Interpret identity_precursor_tolerance as ppm. Default is False. - **dtype** (dtype) - Optional - Data type for output scores. Default is np.float64. ``` -------------------------------- ### Get Adduct Charge Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/filtering/filter_utils/interpret_unknown_adduct.html Determines the charge state of an adduct string. ```python def get_charge_of_adduct(adduct) -> Optional[int]: """Returns the charge of an adduct ``` -------------------------------- ### Initialize and Access Spectrum Data Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Spectrum.html Demonstrates creating a Spectrum object with m/z values, intensities, and metadata, and accessing its attributes. ```python import numpy as np from matchms import Scores, Spectrum from matchms.similarity import CosineGreedy spectrum = Spectrum(mz=np.array([100, 150, 200.]), intensities=np.array([0.7, 0.2, 0.1]), metadata={"id": 'spectrum1', "precursor_mz": 222.333, "peak_comments": {200.: "the peak at 200 m/z"}}) print(spectrum) print(spectrum.peaks.mz[0]) print(spectrum.peaks.intensities[0]) print(spectrum.get('id')) print(spectrum.peak_comments.get(200)) ``` -------------------------------- ### Convert Molecular Representations Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/filtering/filter_utils/smile_inchi_inchikey_conversions.html Functions to convert between SMILES, InChI, and InChIKey formats. These require RDKit to be installed. ```python def convert_smiles_to_inchi(smiles: str) -> Optional[str]: """Convert smiles to inchi using rdkit.""" return mol_converter(smiles, "smiles", "inchi") ``` ```python def convert_inchi_to_smiles(inchi: str) -> Optional[str]: """Convert inchi to smiles using rdkit.""" return mol_converter(inchi, "inchi", "smiles") ``` ```python def convert_inchi_to_inchikey(inchi: str) -> Optional[str]: """Convert inchi to inchikey using rdkit.""" return mol_converter(inchi, "inchi", "inchikey") ``` ```python def mol_converter(mol_input: str, input_type: str, output_type: str) -> Optional[str]: """Convert molecular representations using rdkit. Convert from "smiles" or "inchi" to "inchi", "smiles", or "inchikey". Requires conda package *rdkit* to be installed. Parameters ---------- mol_input Input data in "inchi" or "smiles" molecular representation. input_type Define input type: "smiles" for smiles and "inchi" for inchi. output_type Define output type: "smiles", "inchi", or "inchikey". Returns: -------- Mol string in output type or None when conversion failure occurs. """ if not _has_rdkit: raise ImportError(rdkit_missing_message) input_function = {"inchi": Chem.MolFromInchi, "smiles": Chem.MolFromSmiles} output_function = {"inchi": Chem.MolToInchi, "smiles": Chem.MolToSmiles, "inchikey": Chem.MolToInchiKey} mol = input_function[input_type](mol_input.strip('"')) if mol is None: return None output = output_function[output_type](mol) if output: return output return None ``` -------------------------------- ### Calculate CosineLinear similarity Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/CosineLinear.html Example usage of the CosineLinear class to compute the similarity score between two spectra. ```python import numpy as np from matchms import Spectrum from matchms.similarity import CosineLinear reference = Spectrum(mz=np.array([100, 150, 200.]), intensities=np.array([0.7, 0.2, 0.1])) query = Spectrum(mz=np.array([100, 140, 190.]), intensities=np.array([0.4, 0.2, 0.1])) cosine_linear = CosineLinear(tolerance=0.2) score = cosine_linear.pair(reference, query) print(f"CosineLinear score is {score['score']:.2f} with {score['matches']} matched peaks") ``` -------------------------------- ### matchms.similarity.__init__ Source: https://matchms.readthedocs.io/en/latest/api/matchms.similarity.html Initializes the similarity calculator with specific scoring parameters and preprocessing options. ```APIDOC ## Constructor: matchms.similarity.__init__ ### Description Initializes the similarity calculator with configuration for scoring types, matching modes, and spectral preprocessing steps. ### Parameters - **score_type** (str) - Optional - 'spectral_entropy' (default) or 'cosine'. - **matching_mode** (str) - Optional - 'fragment', 'neutral_loss', or 'hybrid' (default 'fragment'). - **tolerance** (float) - Optional - Matching tolerance in Da or ppm. Default 0.02. - **use_ppm** (bool) - Optional - If True, interpret tolerance as ppm. Default False. - **remove_precursor** (bool) - Optional - If True, remove precursor peak. Default False. - **precursor_window** (float) - Optional - Window size for precursor removal. Default 1.6. - **noise_cutoff** (float) - Optional - Intensity fraction threshold for noise removal. Default 0.01. - **normalize_to_half** (bool) - Optional - If True, normalize sum of intensities to 0.5. Default True. - **merge_within** (float) - Optional - Distance to merge peaks. Default 0. - **identity_precursor_tolerance** (float) - Optional - Tolerance for identity search behavior. - **identity_use_ppm** (bool) - Optional - If True, interpret identity_precursor_tolerance as ppm. Default False. - **dtype** (dtype) - Optional - Output data type. Default np.float64. ``` -------------------------------- ### SpectrumProcessor.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/filtering/SpectrumProcessor.html Initializes the SpectrumProcessor with a list of filter functions. ```APIDOC ## SpectrumProcessor(filters) ### Description Initializes a new instance of the SpectrumProcessor class with a specified list of filters. ### Parameters - **filters** (Iterable[Union[str, Callable, FunctionWithParametersType]]) - Required - A list of filter functions or descriptions to be applied to spectra. ``` -------------------------------- ### Get common keys Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/utils.html Identifies common elements between two lists, performing case-insensitive matching for the first list. ```python def get_common_keys(first: List[str], second: List[str]) -> List[str]: """Get common elements of two sets of strings in a case insensitive way. Args: first (List[str]): First list of strings. second (List[str]): List of strings to search for matches. Returns: List[str]: List of common elements without regarding case of first list. """ return [value for value in first if value in second or value.lower() in second] ``` -------------------------------- ### Get RDKit molecule from spectrum Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Fingerprints.html Attempts to generate an RDKit molecule object from either SMILES or InChI metadata. ```python def _get_mol(spectrum: SpectrumType) -> Optional[Mol]: """ Get the molecule either from smiles or inchi. Parameter: ---------- spectrum: SpectrumType Spectrum to get the mol from. Return: -------------- Optional[Mol] RDKit Mol object or None if smiles and inchi missing or generation failed. """ mol = None if spectrum.get("smiles"): return Chem.MolFromSmiles(spectrum.get("smiles")) if spectrum.get("inchi"): return Chem.MolFromInchi(spectrum.get("inchi")) return mol ``` -------------------------------- ### Execute a Pipeline using a YAML configuration Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Pipeline.html Load a workflow from a YAML file and execute the pipeline on a spectrum file. ```python from matchms.Pipeline import Pipeline, load_workflow_from_yaml_file workflow = load_workflow_from_yaml_file("my_config_file.yaml") pipeline = Pipeline(workflow) # Optional steps pipeline.logging_file = "my_pipeline.log" pipeline.logging_level = "ERROR" pipeline.run("my_spectra.mgf") ``` -------------------------------- ### FlashSimilarity.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/FlashSimilarity.html Initializes the FlashSimilarity object with configuration for matching modes, tolerances, and data preprocessing. ```APIDOC ## FlashSimilarity.__init__ ### Description Initializes a new instance of the FlashSimilarity class. This class implements the Flash entropy similarity method (Li & Fiehn, 2023). ### Parameters - **score_type** (str) - Optional - 'spectral_entropy' (default) or 'cosine'. - **matching_mode** (str) - Optional - 'fragment', 'neutral_loss', or 'hybrid' (default is 'fragment'). - **tolerance** (float) - Optional - Matching tolerance in Da or ppm. Default is 0.02. - **use_ppm** (bool) - Optional - If True, interpret tolerance as ppm. Default is False. - **remove_precursor** (bool) - Optional - If True, remove precursor peak and peaks within precursor_window. Default is False. - **precursor_window** (float) - Optional - Window size for precursor removal. Default is 1.6 Da. - **noise_cutoff** (float) - Optional - Intensity threshold for noise removal. Default is 0.01. - **normalize_to_half** (bool) - Optional - If True, normalize intensities to sum to 0.5. Default is True. - **merge_within** (float) - Optional - Distance in Da to merge peaks. Default is 0. - **identity_precursor_tolerance** (float) - Optional - Tolerance for identity search behavior. - **identity_use_ppm** (bool) - Optional - If True, interpret identity_precursor_tolerance as ppm. Default is False. - **dtype** (np.dtype) - Optional - Output data type. Default is np.float64. ``` -------------------------------- ### Initialize and access Fragments Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Fragments.html Demonstrates creating a Fragments object with numpy arrays and accessing specific peaks. ```python import numpy as np from matchms import Fragments mz = np.array([10, 20, 30], dtype="float") intensities = np.array([100, 20, 300], dtype="float") peaks = Fragments(mz=mz, intensities=intensities) print(peaks[2]) ``` -------------------------------- ### Calculate monoisotopic mass of a formula Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/filtering/filter_utils/interpret_unknown_adduct.html Calculates the monoisotopic mass of a given chemical formula string. Requires RDKit to be installed. ```python def get_mass_of_formula(formula): """Calculates the monoisotopic mass of an formula e.g. "C" returns 12.011 and "CH2" returns 15.035. This can be used to calculate the mass difference of adducts Was adapted from: https://bioinformatics.stackexchange.com/questions/6852/ """ if not _has_rdkit: raise ImportError(rdkit_missing_message) parts = re.findall("[A-Z][a-z]?|[0-9]+", formula) mass = 0 for i, part in enumerate(parts): if part.isnumeric(): continue periodic_table = Chem.GetPeriodicTable() try: atom_mass = periodic_table.GetMostCommonIsotopeMass(part) except RuntimeError: logger.warning("The atom: %s in the formula %s is not known", part, formula) return None multiplier = int(parts[i + 1]) if len(parts) > i + 1 and parts[i + 1].isnumeric() else 1 mass += atom_mass * multiplier return mass ``` -------------------------------- ### Metadata.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Metadata.html Initializes a new Metadata object with optional dictionary data and key harmonization settings. ```APIDOC ## Metadata(metadata: dict = None, matchms_key_style: bool = True) ### Description Initializes the Metadata object. If `matchms_key_style` is True (default), keys are automatically harmonized to lower-case and standardized formats. ### Parameters - **metadata** (dict) - Optional - Spectrum metadata as a dictionary. - **matchms_key_style** (bool) - Optional - Set to False if metadata harmonization to default keys is not desired. ``` -------------------------------- ### Calculate Neutral Mass from SMILES Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/filtering/filter_utils/get_neutral_mass_from_smiles.html Functions to compute molecular mass from SMILES strings. Requires RDKit to be installed in the environment. ```python import logging from typing import Optional from matchms.constants import PROTON_MASS logger = logging.getLogger("matchms") try: # rdkit is not included in pip package from rdkit import Chem from rdkit.Chem import Descriptors except ImportError: _has_rdkit = False from collections import UserString class ChemMock(UserString): def __call__(self, *args, **kwargs): return self def __getattr__(self, key): return self Chem = AllChem = ChemMock("") else: _has_rdkit = True rdkit_missing_message = "Conda package 'rdkit' is required for this functionality." [docs] def get_monoisotopic_neutral_mass(smiles: str) -> float: """Get the monoisotopic neutral mass from a SMILES string chemical identifier for the described molecule. Args: smiles (str): SMILES string defining the structure of the molecule. Raises: ImportError: If RDkit chem is not installed. Returns: float: Computed monoisotopic mass. """ return _get_neutral_mass(smiles, True) [docs] def get_molecular_weight_neutral_mass(smiles: str) -> float: """Get the (average) molecular weight for the isotopic distribution of the SMILES code. Args: smiles (str): SMILES string describing the structure of the molecule. Raises: ImportError: Raises import error if RDKitChem is not found. Returns: float: Average molecular mass. """ return _get_neutral_mass(smiles, False) def _get_neutral_mass(smiles: str, monoisotopic: bool) -> Optional[float]: """Get neutral mass of molecule, either average or most abundant monoisotopic mass. Args: smiles (str): SMILES describing the molecule. monoisotopic (bool): whether to compute the monoisotopic mass or average. Raises: ImportError: If RDKit Chem is not found Returns: float: Neutral mass. """ if not _has_rdkit: raise ImportError(rdkit_missing_message) if smiles is None: return None mol = Chem.MolFromSmiles(smiles) if mol is None: logger.warning("No mass could be calculated for smiles: %s, since it is not a valid smiles.", smiles) return None mass = Descriptors.ExactMolWt(mol) if monoisotopic else Descriptors.MolWt(mol) charge = sum(atom.GetFormalCharge() for atom in mol.GetAtoms()) neutral_mass = mass + -charge * PROTON_MASS return neutral_mass ``` -------------------------------- ### BlinkCosine.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/BlinkCosine.html Initializes the BlinkCosine similarity calculator with parameters for tolerance, binning, weighting, and pre-filtering. ```APIDOC ## BlinkCosine(tolerance=0.01, bin_width=0.001, mz_power=0.0, intensity_power=1.0, clip_to_one=True, use_numba=True, prefilter=True, min_relative_intensity=0.01, crop_above_precursor=True, remove_zero_intensities=True, top_k=None, batch_size=1024, sparse_score_min=0.0) ### Description Initializes a new instance of the BlinkCosine similarity calculator. This class prepares the configuration for computing approximate cosine similarity between mass spectra. ### Parameters - **tolerance** (float) - Optional - True m/z tolerance (Da). Peaks within +/- tolerance are considered matches. Default 0.01. - **bin_width** (float) - Optional - Discretization width (Da). Default 0.001. - **mz_power** (float) - Optional - Power for mz weighting. Default 0.0. - **intensity_power** (float) - Optional - Power for intensity weighting. Default 1.0. - **clip_to_one** (bool) - Optional - Clip score to [0,1]. Default True. - **use_numba** (bool) - Optional - Use numba-accelerated pairwise kernel. Default True. - **prefilter** (bool) - Optional - Apply BLINK-like pre-filtering. Default True. - **min_relative_intensity** (float) - Optional - Relative base-peak threshold for prefilter. Default 0.01. - **crop_above_precursor** (bool) - Optional - Drop fragments > precursor m/z. Default True. - **remove_zero_intensities** (bool) - Optional - Remove peaks with intensity <= 0. Default True. - **top_k** (int) - Optional - Keep only top-K most intense fragments. Default None. - **batch_size** (int) - Optional - Number of query spectra per batch in .matrix(). Default 1024. - **sparse_score_min** (float) - Optional - Drop scores < sparse_score_min when array_type='sparse'. Default 0.0. ``` -------------------------------- ### Convert Scores to Numpy Array Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Scores.html Example demonstrating how to calculate similarity scores and convert the resulting Scores object into a numpy array. ```python import numpy as np from matchms import calculate_scores, Scores, Spectrum from matchms.similarity import IntersectMz spectrum_1 = Spectrum(mz=np.array([100, 150, 200.]), intensities=np.array([0.7, 0.2, 0.1])) spectrum_2 = Spectrum(mz=np.array([100, 140, 190.]), intensities=np.array([0.4, 0.2, 0.1])) spectra = [spectrum_1, spectrum_2] scores = calculate_scores(spectra, spectra, IntersectMz()).to_array() print(scores.shape) print(scores.tolist()) ``` -------------------------------- ### Fingerprints.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Fingerprints.html Initializes the Fingerprints generator with specific algorithm and configuration settings. ```APIDOC ## Fingerprints.__init__(fingerprint_algorithm='daylight', fingerprint_method='bit', nbits=2048, ignore_stereochemistry=False, **kwargs) ### Description Initializes the Fingerprints object to configure how molecular fingerprints are generated from spectrum data. ### Parameters - **fingerprint_algorithm** (str) - Optional - The algorithm to use. Options: 'daylight', 'morgan1', 'morgan2', 'morgan3'. Defaults to 'daylight'. - **fingerprint_method** (str) - Optional - The method to use. Options: 'bit', 'sparse_bit', 'count', 'sparse_count'. Defaults to 'bit'. - **nbits** (int) - Optional - The number of bits or fingerprint size. Defaults to 2048. - **ignore_stereochemistry** (bool) - Optional - If True, uses the first 14 characters of the InChIKey. Defaults to False. ``` -------------------------------- ### Initialize a Pipeline via Python script Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Pipeline.html Import the necessary components to define a pipeline programmatically. ```python from matchms.Pipeline import Pipeline, create_workflow ``` -------------------------------- ### CosineGreedy.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/CosineGreedy.html Initializes the CosineGreedy similarity calculator with specific tolerance and power parameters. ```APIDOC ## CosineGreedy.__init__(tolerance=0.1, mz_power=0.0, intensity_power=1.0) ### Description Initializes the similarity calculator. Peaks are considered a match if they are within the specified tolerance. ### Parameters - **tolerance** (float) - Optional - Peaks will be considered a match when <= tolerance apart. Default is 0.1. - **mz_power** (float) - Optional - The power to raise m/z to in the cosine function. Default is 0. - **intensity_power** (float) - Optional - The power to raise intensity to in the cosine function. Default is 1. ``` -------------------------------- ### Load a spectrum from a USI Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/importing/load_from_usi.html Demonstrates how to import and use the load_from_usi function to retrieve a spectrum by its USI string. ```python from matchms.importing import load_from_usi spectrum = load_from_usi("mzspec:MASSBANK::accession:SM858102") print(f"Found spectrum with precursor m/z of {spectrum.get('precursor_mz'):.2f}.") ``` -------------------------------- ### FingerprintSimilarity.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/FingerprintSimilarity.html Initializes the FingerprintSimilarity object with a specified similarity measure. ```APIDOC ## FingerprintSimilarity(similarity_measure="jaccard", set_empty_scores="nan") ### Description Initializes the similarity measure instance. ### Parameters - **similarity_measure** (str) - Optional - The similarity measure to use: "cosine", "dice", or "jaccard". Defaults to "jaccard". - **set_empty_scores** (Union[float, int, str]) - Optional - Value to return when fingerprints are missing. Defaults to "nan". ``` -------------------------------- ### Load spectra from an mzXML file Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/importing/load_from_mzxml.html Demonstrates the basic usage of load_from_mzxml to import spectra from a specified file. ```python from matchms.importing import load_from_mzxml file_mzxml = "testdata.mzxml" spectra = list(load_from_mzml(file_mzxml)) ``` -------------------------------- ### Loading MGF files with load_from_mgf Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/importing/load_from_mgf.html Demonstrates loading spectra from a file path or a file-like object. ```python from matchms.importing import load_from_mgf file_mgf = "pesticides.mgf" spectra_from_path = list(load_from_mgf(file_mgf)) # Or you can read the file in your application with open(file_mgf, "r") as spectra_file: spectra_from_file = list(load_from_mgf(spectra_file)) ``` -------------------------------- ### Configure logging for Pipeline Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Pipeline.html Sets up the matchms logger to output to a specified file if configured. ```python def set_logging(self): """Set the matchms logger to write messages to file (if defined).""" reset_matchms_logger() set_matchms_logger_level(self.logging_level) if self.logging_file is not None: add_logging_to_file(self.logging_file, loglevel=self.logging_level, remove_stream_handlers=True) else: logger.warning("No logging file was defined.Logging messages will not be written to file.") ``` -------------------------------- ### BinnedEmbeddingSimilarity.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/BinnedEmbeddingSimilarity.html Initializes the BinnedEmbeddingSimilarity object with configuration for binning parameters and similarity metrics. ```APIDOC ## BinnedEmbeddingSimilarity(similarity="cosine", max_mz=1005, bin_width=1, intensity_power=1) ### Description Initializes the similarity measure that bins spectra into a fixed number of bins and uses the binned intensities as embedding features. ### Parameters - **similarity** (str) - Optional - The similarity measure to use for comparing embeddings. Options are "cosine" or "euclidean". Default is "cosine". - **max_mz** (float) - Optional - The maximum m/z value to consider when binning. Default is 1005. - **bin_width** (float) - Optional - The width of each bin in m/z units. Default is 1. - **intensity_power** (float) - Optional - The power to raise the peak intensities. Default is 1. ``` -------------------------------- ### Pipeline.run(query_files, reference_files=None, cleaned_query_file=None, cleaned_reference_file=None, create_report=True) Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Pipeline.html Executes the defined pipeline workflow on the provided spectrum files. ```APIDOC ### Method: run #### Description Executes the defined Pipeline workflow on the provided query and reference spectrum files. #### Parameters - **query_files** (str/list) - Required - Path(s) to the query spectrum files. - **reference_files** (str/list) - Optional - Path(s) to the reference spectrum files. - **cleaned_query_file** (str) - Optional - Path to save cleaned query spectra. - **cleaned_reference_file** (str) - Optional - Path to save cleaned reference spectra. - **create_report** (bool) - Optional - Whether to generate a report. Defaults to True. ``` -------------------------------- ### Define and run a pipeline workflow Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Pipeline.html Create a workflow using a YAML configuration file and execute it on query and reference spectra files. ```python workflow = create_workflow( yaml_file_name="my_config_file.yaml", # The workflow will be stored in a yaml file. query_filters=[ ["add_parent_mass"], ["normalize_intensities"], ["select_by_relative_intensity", {"intensity_from": 0.0, "intensity_to": 1.0}], ["select_by_mz", {"mz_from": 0, "mz_to": 1000}], ["require_minimum_number_of_peaks", {"n_required": 5}], ], reference_filters=["add_fingerprint"], score_computations=[ ["precursormzmatch", {"tolerance": 120.0}], ["cosinegreedy", {"tolerance": 1.0}], ["filter_by_range", {"name": "CosineGreedy_score", "low": 0.3}], ["modifiedcosinegreedy", {"tolerance": 1.0}], ["filter_by_range", {"name": "ModifiedCosineGreedy_score", "low": 0.3}], ], ) pipeline = Pipeline(workflow) pipeline.logging_file = "my_pipeline.log" pipeline.logging_level = "WARNING" pipeline.run("my_query_spectra.mgf", "my_reference_spectra.mgf") ``` -------------------------------- ### Retrieve processing steps Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/filtering/SpectrumProcessor.html Returns a list of filter names and their parameter settings currently configured in the processor. ```python @property def processing_steps(self): filter_list = [] for filter_step in self.filters: parameter_settings = get_parameter_settings(filter_step) if parameter_settings is not None: filter_list.append((filter_step.__name__, parameter_settings)) else: filter_list.append(filter_step.__name__) return filter_list ``` -------------------------------- ### Load spectra from an mzML file Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/importing/load_from_mzml.html Demonstrates the basic usage of load_from_mzml to read spectra from a specified file path. ```python from matchms.importing import load_from_mzml file_mzml = "testdata.mzml" spectra = list(load_from_mzml(file_mzml)) ``` -------------------------------- ### NeutralLossesCosine.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/NeutralLossesCosine.html Initializes the NeutralLossesCosine similarity calculator with specific parameters for peak matching and scoring. ```APIDOC ## NeutralLossesCosine(tolerance=0.1, mz_power=0.0, intensity_power=1.0, ignore_peaks_above_precursor=True) ### Description Initializes the similarity calculator. The score is calculated by finding best matches between peaks of two spectra after applying a mass shift based on the precursor m/z difference. ### Parameters - **tolerance** (float) - Optional - Peaks are considered a match when <= tolerance apart. Default is 0.1. - **mz_power** (float) - Optional - The power to raise m/z to in the cosine function. Default is 0. - **intensity_power** (float) - Optional - The power to raise intensity to in the cosine function. Default is 1. - **ignore_peaks_above_precursor** (bool) - Optional - If True, peaks with m/z values larger than the precursor-m/z are ignored. Default is True. ``` -------------------------------- ### CosineLinear.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/CosineLinear.html Initializes the CosineLinear similarity calculator with specified tolerance and power parameters. ```APIDOC ## CosineLinear.__init__(tolerance=0.1, mz_power=0.0, intensity_power=1.0) ### Description Initializes the similarity calculator. Peaks are merged if they are closer than 2 * tolerance. ### Parameters - **tolerance** (float) - Optional - Peaks are considered a match when <= tolerance apart. Default is 0.1. - **mz_power** (float) - Optional - The power to raise m/z to in the cosine function. Default is 0.0. - **intensity_power** (float) - Optional - The power to raise intensity to in the cosine function. Default is 1.0. ``` -------------------------------- ### Compute and retrieve fingerprints Source: https://matchms.readthedocs.io/en/latest/api/matchms.Fingerprints.html Demonstrates initializing the Fingerprints generator, computing fingerprints for a list of spectra, and retrieving them by inchikey. ```python from matchms import Fingerprints from matchms import Spectrum import numpy as np spectrum_1 = Spectrum(mz=np.array([100, 150, 200.]), intensities=np.array([0.7, 0.2, 0.1]), metadata={"inchikey": "OTMSDBZUPAUEDD-UHFFFAOYSA-N", "smiles":"CC", "precursor_mz": 150.0}) spectrum_2 = Spectrum(mz=np.array([100, 150, 200.]), intensities=np.array([0.7, 0.2, 0.1]), metadata={"inchikey": "UGFAIRIUMAVXCW-UHFFFAOYSA-N", "smiles": "[C-]#[O+]", "precursor_mz": 150.0}) spectra = [spectrum_1, spectrum_2] fpgen = Fingerprints() fpgen.compute_fingerprints(spectra) print(fpgen.fingerprint_count) print(type(fpgen.get_fingerprint_by_inchikey('OTMSDBZUPAUEDD-UHFFFAOYSA-N'))) ``` ```text 2 ``` -------------------------------- ### matchms.importing.load_from_pickle Source: https://matchms.readthedocs.io/en/latest/api/matchms.importing.html Loads spectra stored in a pickle file. ```APIDOC ## matchms.importing.load_from_pickle(filename, metadata_harmonization) ### Description Loads spectra stored in a pickle file. ### Parameters - **filename** (str) - Required - Pickled file with spectra. - **metadata_harmonization** (bool) - Required - Flag to determine if metadata harmonization is applied. ### Returns - **List[Spectrum]** - A list of unpickled Spectrum objects. ``` -------------------------------- ### MetadataMatch.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/MetadataMatch.html Initializes the MetadataMatch similarity object with the field to compare and the matching strategy. ```APIDOC ## MetadataMatch(field: str, matching_type: str = "equal_match", tolerance: float = 0.1) ### Description Initializes a new instance of the MetadataMatch class to compare metadata fields between spectra. ### Parameters - **field** (str) - Required - The metadata key to compare. - **matching_type** (str) - Optional - Strategy for matching: "equal_match" (default) or "difference". - **tolerance** (float) - Optional - Numerical tolerance for the "difference" matching type. ``` -------------------------------- ### Compute Fingerprints for Spectra Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Fingerprints.html Demonstrates initializing the Fingerprints class and computing fingerprints for a list of Spectrum objects. ```python from matchms import Fingerprints from matchms import Spectrum import numpy as np spectrum_1 = Spectrum(mz=np.array([100, 150, 200.]), intensities=np.array([0.7, 0.2, 0.1]), metadata={"inchikey": "OTMSDBZUPAUEDD-UHFFFAOYSA-N", "smiles":"CC", "precursor_mz": 150.0}) spectrum_2 = Spectrum(mz=np.array([100, 150, 200.]), intensities=np.array([0.7, 0.2, 0.1]), metadata={"inchikey": "UGFAIRIUMAVXCW-UHFFFAOYSA-N", "smiles": "[C-]#[O+]", "precursor_mz": 150.0}) spectra = [spectrum_1, spectrum_2] fpgen = Fingerprints() fpgen.compute_fingerprints(spectra) print(fpgen.fingerprint_count) print(type(fpgen.get_fingerprint_by_inchikey('OTMSDBZUPAUEDD-UHFFFAOYSA-N'))) ``` -------------------------------- ### PrecursorMzMatch.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/PrecursorMzMatch.html Initializes the PrecursorMzMatch similarity object with a specified tolerance and tolerance type. ```APIDOC ## __init__(tolerance: float = 0.1, tolerance_type: str = "Dalton") ### Description Initializes the similarity measure. The tolerance defines the threshold for a match, and the tolerance_type determines if the threshold is absolute (Dalton) or relative (ppm). ### Parameters - **tolerance** (float) - Optional - Specify tolerance below which two m/z are counted as match. - **tolerance_type** (str) - Optional - Choose between fixed tolerance in Dalton ("Dalton") or a relative difference in ppm ("ppm"). ``` -------------------------------- ### Calculate ParentMassMatch scores Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/ParentMassMatch.html Demonstrates how to initialize ParentMassMatch with a tolerance and calculate scores between reference and query spectra. ```python import numpy as np from matchms import calculate_scores from matchms import Spectrum from matchms.similarity import ParentMassMatch spectrum_1 = Spectrum(mz=np.array([]), intensities=np.array([]), metadata={"id": "1", "parent_mass": 100}) spectrum_2 = Spectrum(mz=np.array([]), intensities=np.array([]), metadata={"id": "2", "parent_mass": 110}) spectrum_3 = Spectrum(mz=np.array([]), intensities=np.array([]), metadata={"id": "3", "parent_mass": 103}) spectrum_4 = Spectrum(mz=np.array([]), intensities=np.array([]), metadata={"id": "4", "parent_mass": 111}) references = [spectrum_1, spectrum_2] queries = [spectrum_3, spectrum_4] similarity_score = ParentMassMatch(tolerance=5.0) scores = calculate_scores(references, queries, similarity_score) for (reference, query, score) in scores: print(f"Parentmass match between {reference.get('id')} and {query.get('id')}" + f" is {bool(score[0])}") ``` -------------------------------- ### Import spectra into Pipeline Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/Pipeline.html Methods for loading query and reference spectra from files, including a deprecated wrapper. ```python @deprecated(version="0.26.5", reason="This method is deprecated and will be removed in the future. Use import_spectra() instead.") def import_spectrums(self, query_files: Union[List[str], str], reference_files: Optional[Union[List[str], str]] = None): """Wrapper method for import_spectra() Parameters ---------- query_files List of files, or single filename, containing the query spectra. reference_files List of files, or single filename, containing the reference spectra. If set to None (default) then all query spectra will be compared to each other. """ return self.import_spectra(query_files, reference_files) ``` ```python def import_spectra(self, query_files: Union[List[str], str], reference_files: Optional[Union[List[str], str]] = None): """Import spectra from file(s). Parameters ---------- query_files List of files, or single filename, containing the query spectra. reference_files List of files, or single filename, containing the reference spectra. If set to None (default) then all query spectra will be compared to each other. """ # import query spectra self.write_to_logfile("--- Importing data ---") self._spectra_queries = load_list_of_spectrum_files(query_files) self.write_to_logfile(f"Loaded query spectra from {query_files}") # import reference spectra if reference_files is None: self.is_symmetric = True self._spectra_references = self._spectra_queries self.write_to_logfile("Reference spectra are equal to the query spectra (is_symmetric = True)") else: self._spectra_references = load_list_of_spectrum_files(reference_files) self.write_to_logfile(f"Loaded reference spectra from {reference_files}") ``` -------------------------------- ### MetadataMatch.__init__ Source: https://matchms.readthedocs.io/en/latest/api/matchms.similarity.html Initializes a new MetadataMatch instance to compare metadata fields between spectra. ```APIDOC ## MetadataMatch(field, matching_type='equal_match', tolerance=0.1) ### Description Initializes the similarity measure to compare metadata entries of a specified field between two spectra. ### Parameters - **field** (str) - Required - The metadata field name to compare. - **matching_type** (str) - Optional - Comparison method: 'equal_match' (default) or 'difference'. - **tolerance** (float) - Optional - Numerical tolerance for 'difference' matching type. ``` -------------------------------- ### SimilarityNetwork.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/networking/SimilarityNetwork.html Initializes the SimilarityNetwork object with configuration parameters for network construction. ```APIDOC ## SimilarityNetwork(identifier_key='spectrum_id', top_n=20, max_links=10, score_cutoff=0.7, link_method='single', keep_unconnected_nodes=True) ### Description Initializes the network builder with specific criteria for edge creation and node management. ### Parameters - **identifier_key** (str) - Optional - Metadata key for unique identifier for each spectrum. Default is 'spectrum_id'. - **top_n** (int) - Optional - Number of top hits to consider for link creation. Default is 20. - **max_links** (int) - Optional - Maximum number of links to add per node. Default is 10. - **score_cutoff** (float) - Optional - Similarity threshold for creating an edge. Default is 0.7. - **link_method** (str) - Optional - Method for linking nodes: 'single' or 'mutual'. Default is 'single'. - **keep_unconnected_nodes** (bool) - Optional - Whether to retain nodes without edges. Default is True. ``` -------------------------------- ### matchms.Pipeline.Pipeline Source: https://matchms.readthedocs.io/en/latest/api/matchms.Pipeline.html Initializes a new Pipeline instance to manage the execution of mass spectrometry analysis workflows. ```APIDOC ## class matchms.Pipeline.Pipeline ### Description Initializes the central pipeline class for running extensive analysis pipelines. ### Parameters - **workflow** (OrderedDict) - Required - Contains the workflow settings, typically created using create_workflow. - **progress_bar** (bool) - Optional - Default is True. Set to False to disable the progress bar. - **logging_level** (str) - Optional - Default is 'WARNING'. - **logging_file** (str | None) - Optional - Path to a log file. ``` -------------------------------- ### Create a spectral network Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/networking/SimilarityNetwork.html Demonstrates initializing a SimilarityNetwork and generating a graph from calculated similarity scores. ```python import numpy as np from matchms import Spectrum, calculate_scores from matchms.similarity import ModifiedCosineGreedy from matchms.networking import SimilarityNetwork spectrum_1 = Spectrum(mz=np.array([100, 150, 200.]), intensities=np.array([0.7, 0.2, 0.1]), metadata={"precursor_mz": 100.0, "test_id": "one"}) spectrum_2 = Spectrum(mz=np.array([104.9, 140, 190.]), intensities=np.array([0.4, 0.2, 0.1]), metadata={"precursor_mz": 105.0, "test_id": "two"}) # Use factory to construct a similarity function modified_cosine = ModifiedCosineGreedy(tolerance=0.2) spectra = [spectrum_1, spectrum_2] scores = calculate_scores(spectra, spectra, modified_cosine) ms_network = SimilarityNetwork(identifier_key="test_id") ms_network.create_network(scores, score_name="ModifiedCosineGreedy_score") nodes = list(ms_network.graph.nodes()) nodes.sort() print(nodes) ``` -------------------------------- ### ParentMassMatch.__init__ Source: https://matchms.readthedocs.io/en/latest/_modules/matchms/similarity/ParentMassMatch.html Initializes the ParentMassMatch similarity calculator with a specified mass tolerance. ```APIDOC ### Constructor #### __init__(tolerance: float = 0.1) - **tolerance** (float) - Optional - Specify tolerance below which two masses are counted as match. ```