Code Monkey home page Code Monkey logo

matchms's Introduction

fair-software.nl recommendations:

GitHub Badge License Badge Conda Badge Pypi Badge Research Software Directory Badge Zenodo Badge CII Best Practices Badge

Code quality checks:

Continuous integration workflow Continuous integration workflow Documentation Status Sonarcloud Quality Gate Sonarcloud Coverage

matchms

Matchms is a versatile open-source Python package developed for importing, processing, cleaning, and comparing mass spectrometry data (MS/MS). It facilitates the implementation of straightforward, reproducible workflows, transforming raw data from common mass spectra file formats into pre- and post-processed spectral data, and enabling large-scale spectral similarity comparisons.

The software supports a range of popular spectral data formats, including mzML, mzXML, msp, metabolomics-USI, MGF, and JSON. Matchms offers an array of tools for metadata cleaning and validation, alongside basic peak filtering, to ensure data accuracy and integrity. A key feature of matchms is its ability to apply various pairwise similarity measures for comparing extensive amounts of spectra. This encompasses not only common Cosine-related scores but also molecular fingerprint-based comparisons and other metadata-related assessments.

One of the strengths of matchms is its extensibility, allowing users to integrate custom similarity measures. Notable examples of spectrum similarity measures tailored for Matchms include Spec2Vec and MS2DeepScore. Additionally, Matchms enhances efficiency by using faster similarity measures for initial pre-selection and supports storing results in sparse data formats, enabling the comparison of several hundred thousands of spectra. This combination of features positions Matchms as a comprehensive tool for mass spectrometry data analysis.

If you use matchms in your research, please cite the following software papers:

F Huber, S. Verhoeven, C. Meijer, H. Spreeuw, E. M. Villanueva Castilla, C. Geng, J.J.J. van der Hooft, S. Rogers, A. Belloum, F. Diblen, J.H. Spaaks, (2020). matchms - processing and similarity evaluation of mass spectrometry data. Journal of Open Source Software, 5(52), 2411, https://doi.org/10.21105/joss.02411

de Jonge NF, Hecht H, van der Hooft JJJ, Huber F. (2023). Reproducible MS/MS library cleaning pipeline in matchms. ChemRxiv. Cambridge: Cambridge Open Engage; 2023, https://doi.org/10.26434/chemrxiv-2023-l44cm

Latest changes (matchms >= 0.18.0)

Pipeline class

To make typical matchms workflows (data import, processing, score computations) more accessible to users, matchms now offers a Pipeline class to handle complex workflows. This also allows to create, import, export, or modify workflows using yaml files. See code examples below (and soon: updated tutorial).

Sparse scores array

We realized that many matchms-based workflows aim to compare many-to-many spectra whereby not all pairs and scores are equally important. Often, for instance, it will be about searching similar or related spectra/compounds. This also means that often not all scores need to be stored (or computed). For this reason, we now shifted to a sparse handling of scores in matchms (that means: only storing actually computed, non-null values).

matchms code design

Documentation for users

For more extensive documentation see our readthedocs and our matchms introduction tutorial.

Installation

Prerequisites:

  • Python 3.8 - 3.11, (higher versions should work as well, but are not yet tested systematically)
  • Anaconda (recommended)

We recommend installing matchms in a new virtual environment to avoid dependency clashes

conda create --name matchms python=3.9
conda activate matchms
conda install --channel bioconda --channel conda-forge matchms

Alternatively, matchms can also be installed using pip. In the most basic version matchms will then come without rdkit so that several filter functions related to processing and cleaning chemical metadata will not run. To include rdkit install matchms as matchms[chemistry]:

pip install matchms  # simple install w/o rdkit
pip install matchms[chemistry]  # full install including rdkit

matchms ecosystem -> additional functionalities

Matchms functionalities can be complemented by additional packages. To date, we are aware of:

  • Spec2Vec an alternative machine-learning spectral similarity score that can simply be installed by pip install spec2vec and be imported as from spec2vec import Spec2Vec following the same API as the scores in matchms.similarity.
  • MS2DeepScore a supervised, deep-learning based spectral similarity score that can simply be installed by pip install ms2deepscore and be imported as from ms2deepscore import MS2DeepScore following the same API as the scores in matchms.similarity.
  • matchmsextras which contains additional functions to create networks based on spectral similarities, to run spectrum searchers against PubChem, or additional plotting methods.
  • MS2Query Reliable and fast MS/MS spectral-based analogue search, running on top of matchms.
  • memo a method allowing a Retention Time (RT) agnostic alignment of metabolomics samples using the fragmentation spectra (MS2) of their constituents.
  • RIAssigner a tool for retention index calculation for gas chromatography - mass spectrometry (GC-MS) data.
  • MSMetaEnhancer is a python package to collect mass spectral library metadata using various web services and computational chemistry packages.
  • cudams is a python package for fast similarity calculations, using GPU's to speed up the cosine score calculations by 100-500x compared to the standard matchms implementation.

(if you know of any other packages that are fully compatible with matchms, let us know!)

Introduction

To get started with matchms, we recommend following our matchms introduction tutorial.

Below is an example of using default filter steps for cleaning spectra, followed by calculating the Cosine score between mass Spectrums in the tests/testdata/pesticides.mgf file.

from matchms.Pipeline import Pipeline, create_workflow

workflow = create_workflow(
    yaml_file_name="my_config_file.yaml", # The workflow will be stored in a yaml file, this can be used to rerun your workflow or to share it with others.
    score_computations=[["cosinegreedy", {"tolerance": 1.0}]],
    )
pipeline = Pipeline(workflow)
pipeline.logging_file = "my_pipeline.log"  # for pipeline and logging message
pipeline.run("tests/testdata/pesticides.mgf")

Below is a more advanced code example showing how you can make a specific pipeline for your needs.

import os
from matchms.Pipeline import Pipeline, create_workflow
from matchms.filtering.default_pipelines import DEFAULT_FILTERS, LIBRARY_CLEANING

results_folder = "./results"
os.makedirs(results_folder, exist_ok=True)

workflow = create_workflow(
    yaml_file_name=os.path.join(results_folder, "my_config_file.yaml"),  # The workflow will be stored in a yaml file.
    query_filters=DEFAULT_FILTERS,
    reference_filters=LIBRARY_CLEANING + ["add_fingerprint"],
    score_computations=[["precursormzmatch", {"tolerance": 100.0}],
                        ["cosinegreedy", {"tolerance": 1.0}],
                        ["filter_by_range", {"name": "CosineGreedy_score", "low": 0.2}]],
)
pipeline = Pipeline(workflow)
pipeline.logging_file = os.path.join(results_folder, "my_pipeline.log")  # for pipeline and logging message
pipeline.logging_level = "WARNING"  # To define the verbosety of the logging
pipeline.run("tests/testdata/pesticides.mgf", "my_reference_library.mgf",
             cleaned_query_file=os.path.join(results_folder, "cleaned_query_spectra.mgf"),
             cleaned_reference_file=os.path.join(results_folder,
                                                 "cleaned_library_spectra.mgf"))  # choose your own files

Alternatively, in particular, if you need more room to add custom functions and steps, the individual steps can run without using the matchms Pipeline:

from matchms.importing import load_from_mgf
from matchms.filtering import default_filters, normalize_intensities
from matchms import calculate_scores
from matchms.similarity import CosineGreedy

# Read spectrums from a MGF formatted file, for other formats see https://matchms.readthedocs.io/en/latest/api/matchms.importing.html 
file = load_from_mgf("tests/testdata/pesticides.mgf")

# Apply filters to clean and enhance each spectrum
spectrums = []
for spectrum in file:
    # Apply default filter to standardize ion mode, correct charge and more.
    # Default filter is fully explained at https://matchms.readthedocs.io/en/latest/api/matchms.filtering.html .
    spectrum = default_filters(spectrum)
    # Scale peak intensities to maximum of 1
    spectrum = normalize_intensities(spectrum)
    spectrums.append(spectrum)

# Calculate Cosine similarity scores between all spectrums
# For other similarity score methods see https://matchms.readthedocs.io/en/latest/api/matchms.similarity.html .
scores = calculate_scores(references=spectrums,
                          queries=spectrums,
                          similarity_function=CosineGreedy())

# Matchms allows to get the best matches for any query using scores_by_query
query = spectrums[15]  # just an example
best_matches = scores.scores_by_query(query, 'CosineGreedy_score', sort=True)

# Print the calculated scores for each spectrum pair
for (reference, score) in best_matches[:10]:
    # Ignore scores between same spectra
    if reference is not query:
        print(f"Reference scan id: {reference.metadata['scans']}")
        print(f"Query scan id: {query.metadata['scans']}")
        print(f"Score: {score[0]:.4f}")
        print(f"Number of matching peaks: {score[1]}")
        print("----------------------------")

Different spectrum similarity scores

Matchms comes with numerous different scoring methods in matchms.similarity and can further seamlessly work with Spec2Vec or MS2DeepScore.

Code example:

from matchms.importing import load_from_usi
import matchms.filtering as msfilters
import matchms.similarity as mssim


usi1 = "mzspec:GNPS:GNPS-LIBRARY:accession:CCMSLIB00000424840"
usi2 = "mzspec:MSV000086109:BD5_dil2x_BD5_01_57213:scan:760"

mz_tolerance = 0.1

spectrum1 = load_from_usi(usi1)
spectrum1 = msfilters.select_by_mz(spectrum1, 0, spectrum1.get("precursor_mz"))
spectrum1 = msfilters.remove_peaks_around_precursor_mz(spectrum1,
                                                       mz_tolerance=0.1)

spectrum2 = load_from_usi(usi2)
spectrum2 = msfilters.select_by_mz(spectrum2, 0, spectrum1.get("precursor_mz"))
spectrum2 = msfilters.remove_peaks_around_precursor_mz(spectrum2,
                                                       mz_tolerance=0.1)
# Compute scores:
similarity_cosine = mssim.CosineGreedy(tolerance=mz_tolerance).pair(spectrum1, spectrum2)
similarity_modified_cosine = mssim.ModifiedCosine(tolerance=mz_tolerance).pair(spectrum1, spectrum2)
similarity_neutral_losses = mssim.NeutralLossesCosine(tolerance=mz_tolerance).pair(spectrum1, spectrum2)

print(f"similarity_cosine: {similarity_cosine}")
print(f"similarity_modified_cosine: {similarity_modified_cosine}")
print(f"similarity_neutral_losses: {similarity_neutral_losses}")

spectrum1.plot_against(spectrum2)

Documentation for developers

Installation

To install matchms, do:

git clone https://github.com/matchms/matchms.git
cd matchms
conda create --name matchms-dev python=3.8
conda activate matchms-dev
# Install rdkit using conda, rest of dependencies can be installed with pip
conda install -c conda-forge rdkit
python -m pip install --upgrade pip
pip install --editable .[dev]  # if this won't work try "poetry install"

Run the linter with:

prospector

Automatically fix incorrectly sorted imports:

isort .

Files will be changed in place and need to be committed manually. If you only want to inspect the isort suggestions then simply run:

isort --check-only --diff .

Run tests (including coverage) with:

pytest

Conda package

The conda packaging is handled by a recipe at Bioconda.

Publishing to PyPI will trigger the creation of a pull request on the bioconda recipes repository Once the PR is merged the new version of matchms will appear on https://anaconda.org/bioconda/matchms

Flowchart

Flowchart of matchms workflow. Reference and query spectrums are filtered using the same set of set filters (here: filter A and filter B). Once filtered, every reference spectrum is compared to every query spectrum using the matchms.Scores object.

Flowchart of matchms workflow. Reference and query spectrums are filtered using the same set of set filters (here: filter A and filter B). Once filtered, every reference spectrum is compared to every query spectrum using the matchms.Scores object.

Contributing

If you want to contribute to the development of matchms, have a look at the contribution guidelines.

License

Copyright (c) 2023, Düsseldorf University of Applied Sciences & Netherlands eScience Center

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Credits

This package was created with Cookiecutter and the NLeSC/python-template.

matchms's People

Contributors

adafede avatar alpi314 avatar arfon avatar bernardolk avatar bjonnh avatar cunlianggeng avatar cwmeijer avatar davidwhealey avatar efrain2010 avatar fdiblen avatar florian-huber avatar fossabot avatar hannospreeuw avatar hechth avatar jspaaks avatar kiaashour avatar kozo2 avatar lionel42 avatar maximskorik avatar niekdejonge avatar sdrogers avatar sverhoeven avatar tornikeo avatar tshauck avatar wverastegui avatar zargham-ahmad avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

matchms's Issues

Conflicting metadata fields

Since recently I handle MS data from mgf as well as json files (both coming form GNPS). Unfortunately both formats come with conflicting metadata fields.
To a large extend I think it will be fine to just parse the fields accordingly when loading data (PR matchms/matchms-backup#207).
But this doesn't work for the precursor mass.

  • For the mgf files we use pyteomics which gives us a pepmass field with two values: [mz, intensity].
  • The json files come with a precursor_mz field.

Add import and export for json files

I tried using save_as_mgf on the actual data.
The good part: it seems to work even for large lists of spectrums.
The bad part: it is pretty slow. Writing the entire dataset (147,000 spectra) to a mgf file of about 1GB took >20 minutes. I slightly changed save_as_mgf (#152) but that didn't improve things much, so it is mostly likely due to the way pyteomics writes it to an mgf file.

I ran a quickly made json function for comparison, which was at least 5 times faster.

import json

def save_as_json(spectrums, filename):
    """Save spectrum(s) as json file.

    Args:
    ----
    spectrums: list of Spectrum() objects, Spectrum() object
        Expected input are match.Spectrum.Spectrum() objects.
    filename: str
        Provide filename to save spectrum(s).
    """
    if not isinstance(spectrums, list):
        # Assume that input was single Spectrum
        spectrums = [spectrums]

    # Convert matchms.Spectrum() into dictionaries
    spectrum_dicts = []
    for spectrum in spectrums:
        spec = spectrum.clone()
        spectrum_dict = {"intensities": spec.peaks.intensities.tolist(),
                         "mz": spec.peaks.mz.tolist(),
                         "metadata": spec.metadata}
        spectrum_dicts.append(spectrum_dict)

    # Write to json file
    with open(filename, 'w') as fout:
        json.dump(spectrum_dicts, fout)

Question: Does it make sense to add such a function?
We still need the save_to_mgf function because that is how the data can be shared within the community. But to create safe points, store data during the processing pipeline etc. one could still switch to a different (better?) format.

By the way:
Json was just what first crossed my mind. It could of course be any other suited file format!

Fix and/or add metadata through pubchem lookup

My former pre-processing of the data included a step where I tried to "repair" incorrect Inchis or smiles by finding a matching compound via PubChem.
This is not a very simple task, because one needs to define what a good-enough match is (it used to be a very lengthy function find_pubchem_match which was part of ms_functions.py in the old code.

While I consider this something nice to have, it first should be decided:

  • Should this be part of matchms at all?
  • Should this better be postponed?
    (I think that working on the spec2vec part and the library matching is more 'urgent')

Unclear why isort test is failing

In PR #45 half of the tests fail because of isort complaining about Imports are incorrectly sorted..
Even when running isort on one of the named files (add_fingerprint()) that didn't disappear.

I am now not sure if there is something going wrong with the isort test, or whether import must be in one very particular order and format (in which case that should be specified to avoid unlimited trial&error).

Intensities of losses are in wrong order

The add losses filter creates losses by subtracting peak mz from the precursor-m/z.
When using it on actual data I ran into two issues:

  • loss intensities are in the wrong order (inverse to the loss mz)
  • people using losses restrict them to a much smaller range than mz values, so the function should have a from_mz and to_mz parameters.
    There also should be a default from_mz=0, because some spectra have peaks with m/z larger than the precursor-m/z.

Actual implementation on GNPS

Actual implementation on GNPS as a workflow. GNPS is in Conda and has an API.

  • Check what we need to do for GNPS implementation.

Cosine Greedy and Cosine Hungarian duplicate code

They both define and implement the functions get_peaks_arrays() and get_matching_pairs() and the same line of code to normalize the score at the end of the calculation.
To solve this we could:

  • Create an abstract base class that already implements these 3 blocks of code.
  • Put the shared code blocks in some util file so it can be imported by the two similarity modules
  • ..,. (Other suggestions?)

About parallel execution

The current implementation of calc_scores.calculate is deliberately naive while we are sorting out the refactored skeleton of matchms:

def calculate(self):
for i_ref, reference_spectrum in enumerate(self.reference_spectrums):
for i_simfun, simfun in enumerate(self.similarity_functions):
self.scores[i_ref][i_simfun] = simfun(self.measured_spectrum, reference_spectrum)
return self

However, once we sort that out, we should starting thinking about increasing performance through parallel execution of parts of the code.
There are various ways that can help us, such as:

  • vectorized evaluation
  • multi-threading
  • multi-processing
  • distributed computing
    and there are multiple tools available that can help with each of these.

However, I'd like to emphasize that we should first do a performance analysis (make your suggestions for tools and procedures in the comments below).

Regardless of the type of parallelization, we'll likely need some kind of chunking ability. We could opt to add a property mask to the Scores object, which is exactly equal in size to Scores.scores but of type Boolean. mask could thus be used to slice the larger Scores.score matrix into chunks, which can be sent off to different processes or machines. I think multithreading might not need this as the memory is already shared (needs confirmation).

If we do implement a mask and parallelization, it's probably convenient to also implement Scores.__add__(self) which could then be used to recombine partially evaluated instances of Scores according to their masks (with checks on equality of Scores.reference_spectrums and Scores.measured_spectrums).

Add filter to reduce number of peaks

For the similarity calculation it is crucial to remove excessive amounts of low intensity peaks from spectra. Raw spectra vary widely in their number of peaks (about 6000 of the 147,000 have more than 1,000 peaks, the maximum number of peaks is even >70,000). Main reason why this is a problem:

  • It drastically slows down similarity score calculations. While small intensity values will have little impact on classical scores (cosine, modified cosine) they cause a severe slowing down of the calculations.
  • It will confuse (and slow down) Spec2Vec. Many of the low intensity peaks are simply noise but will still appear as "words" in documents. Spec2Vec works much better when documents have comparable amounts of words and when most small peaks are removed.

In the past, this has been done in different ways.
One of them was to fit an exponential function to the peak intensity distribution. This is already partly implemented in spectrum.plot() but would need adjustments.
Even better in my view, however, is to skip it for now and move to something simpler. Namely, removing low intensity peaks until a desired maximum number of peaks is reached.

Handle different compound name input types and fields

When handling both data from GNPS json files (see matchms/matchms-backup#207), a number of new issues arise.
One of the is that GNPS json files do not have name field, but already provide a (poorly) cleaned compound_name and adduct instead.

The current add_adduct function does not work on the new format. And later lookup operations rely on one specific field to retrieve the compound name (preferably in a cleaned version).

Move lookup related functionality to its own directory

Any function that mentions:

  • library
  • inchikey
  • SMILES
  • pubchem
  • fingerprint
  • rdkit
  • openbabel

is likely part of looking up what is known about a compound, so you can interpret a match with a measured spectrum. This is completely separate from the similarity calculation, and (optionally) happens after. We should therefore move it to a new directory, /lookup to be created in the root of the module.

Add consistent logging

Currently several filters use print statements when they change metadata.
As Stefan mentioned (in PR #34, #34 (comment)), it would probably be cleaner to do this via logging.

  • replace print statements by logging
  • allow logging to file (if you run many filters over a lot of data it would be nice to get a report of the done changes)

normalize_intensities filter should also normalize losses

Currently the filter only normalized peak intensities, but that would give very different results for running

spectrums = [add_losses(s) for s in spectrums]
spectrums = [normalize_intensities(s) for s in spectrums]

than for

spectrums = [normalize_intensities(s) for s in spectrums]
spectrums = [add_losses(s) for s in spectrums]

Nice to have: metadata import/export functions

Within the iOMEGA project I had do the following a few times:

  • Overwrite and/or complete spectrum metadata based on a metadata collection I got (as a json file).
  • Export my cleaned-up metadata as json file.

It would hence be nice to have function like import_metadata() or import_metadata_json().
For instance something like this:

from matchms.importing import import_metadata

import_metadata(spectrums, metadata_json, 
                match_field_original='spectrumid', 
                match_field_json='gnpsid',
                replace_fields=['inchi', 'smiles', 'inchikey'])

And for exporting it could be something like this:

from matchms.exporting import export_metadata

export_metadata(spectrums, metadata_filename,
                fields_to_export=['name', 'spectrumid', 'inchi', 'smiles', 'inchikey'])

Missing logger for word2vec model training

Depending on the number of epochs, the number of documents, and the size of the documents, model training can take a while. In my view, some type of logger is really needed to see that the process is working fine. For now I just used the following:

from gensim.models.callbacks import CallbackAny2Vec


class EpochLogger(CallbackAny2Vec):
    """Callback to log information about training progress.
    Used to keep track of gensim model training"""

    def __init__(self, num_of_epochs):
        self.epoch = 0
        self.num_of_epochs = num_of_epochs
        self.loss = 0

    def on_epoch_end(self, model):
        """Return progress of model training"""
        loss = model.get_latest_training_loss()
        # loss_now = loss - self.loss_to_be_subed
        print('\r',
              ' Epoch ' + str(self.epoch+1) + ' of ' + str(self.num_of_epochs) + '.',
              end="")
        print('Change in loss after epoch {}: {}'.format(self.epoch+1, loss - self.loss))
        self.epoch += 1
        self.loss = loss

Maybe we can add something along those lines to spec2vec such that people could simply import it.

from spec2vec import EpochLogger
...

KNIME workflow

For users who don't like Python we could create KNIME nodes for matchms which can be used in a KNIME workflow.

The workflow can be based on the integration tests.
The first prototype could use Python nodes with code snippets written by us.
Later we could write proper nodes with the archetype

splitting off spec2vec

We should consider splitting off matchms/similarity/spec2vec/* into its own repo. If we choose to do so, we may want to use the same method I used for splitting off notebooks and old-iomega-spec2vec.

Also, we should decide on which repository (if any) should be a fork of iomega/spec2vec.

Docstrings missing

In my code example (#41) I would like to link to documentation of methods. Sadly the docs do not show the methods because they do not have doc strings.

For

  • matchms/similarity/CosineGreedy.py:CosineGreedy
  • matchms/filtering/default_filters.py:default_filters, has docstring but does not explain what it does.
  • matchms/calculate_scores.py:calculate_scores

Missing modified score

So far we implemented the cosine score. The other main score we work with in the iomega project is called "modified cosine score" and in addition takes into account mass-shifts of peaks due to different precursor-m/z.

CosineGreedy has incorrect method signature

The signature of CosineGreedy.call is

def __call__(self, spectrum: SpectrumType, reference_spectrum: SpectrumType) -> float

But it should be

def __call__(self, spectrum: SpectrumType, reference_spectrum: SpectrumType) -> Tuple[float, int]

Current CosineGreedy doesn't scale with large spectra

Actual spectra can have largely varying number of peaks (some with many 1,000s or 10,000s).

The current CosineGreedy implementation is based on numpy vector operations. Unfortunately, that doesn't scale well with high number of peaks. When calculating the cosine similarity between spectrum1 and spectrum2 (with n1 and n2 number of peaks), the current CosineGreedy has to calculate a matrix multiplication of two n1*n2-sized matrices.
For spectra with 1,000s of peaks that seems to explode in terms of compute (and memory).

We should hence shift to the former implementation which was added in PR matchms/matchms-backup#239 .

Here a quick comparison:

import time
from matchms import Spectrum, Scores
from matchms.similarity import CosineGreedy, CosineGreedyNumba


n_peaks = 2000
n_spectrums = 10

test_spectrum = Spectrum(mz=numpy.linspace(10, 1000, n_peaks),
                         intensities=numpy.ones((n_peaks)),
                         metadata={})

# current numpy vector based implementation
cosine_greedy = CosineGreedy(tolerance=0.01)

tstart = time.time()
similarity_matrix = Scores(n_spectrums*[test_spectrum], n_spectrums*[test_spectrum],
                           cosine_greedy).calculate().scores
tend = time.time()
print("execution time:", tend-tstart)


# numba based implementation
cosine_greedy = CosineGreedyNumba(tolerance=0.01)

tstart = time.time()
similarity_matrix = Scores(n_spectrums*[test_spectrum], n_spectrums*[test_spectrum],
                           cosine_greedy).calculate().scores
tend = time.time()
print("execution time:", tend-tstart)

For the above code I got:
execution time: 22.43099617958069
execution time: 0.5635242462158203

spikes[0] returns unexpected

I tried to use the spikes[i], but an unexpected result.

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'})

spectrum.peaks[0]

I expected

(100.0, 0.7)

But I got

[100. 150. 200.]

Missing similarity measure based on molecular fingerprints.

In the spec2vec project we compare different spectral similarities to the similarity between respective molecular fingerprints (as a kind of "ground truth").
Those fingerprints are calculated based on the actual structure of a molecule so they need smiles (or inchi) as input.

There are many different flavors of molecular fingerprints. We implemented some key types using rdkit in the old spec2vec code. That should be refactored and added to matchms I think.

Test and compare different cosine score implementations (profiling)

When it comes to finding bottlenecks regarding memory and compute, I strongly expect that the similarity score calculations will be the most important issue.

The current implementation of the cosine score calculation CosineGreedy is already making use of vectorized numpy calculations. But at least in a quick check I found that a former numba based implementation still seems to be faster (bit more than 2-fold?).

add isort based correcting of imports

Refs matchms/matchms-backup#189

Correction should be such that it passes

run: isort --check-only --diff --conda-env matchms --recursive --wrap-length 79 --lines-after-imports 2 --force-single-line --no-lines-before FUTURE --no-lines-before STDLIB --no-lines-before THIRDPARTY --no-lines-before FIRSTPARTY --no-lines-before LOCALFOLDER matchms/ tests/ integration-tests/

without problems. This may be simply a matter of adding an alias to setup.cfg with the line above in it minus the --check-only and --diff parts.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.