diff --git "a/data/dataset_Glycomics.csv" "b/data/dataset_Glycomics.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Glycomics.csv" @@ -0,0 +1,75840 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Glycomics","mobiusklein/glycresoft","setup.py",".py","14081","365","import sys +import traceback +import os +from setuptools import setup, Extension, find_packages + +from distutils.command.build_ext import build_ext +from distutils.errors import (CCompilerError, DistutilsExecError, + DistutilsPlatformError) + + +def has_option(name): + try: + sys.argv.remove('--%s' % name) + return True + except ValueError: + pass + # allow passing all cmd line options also as environment variables + env_val = os.getenv(name.upper().replace('-', '_'), 'false').lower() + if env_val == ""true"": + return True + return False + + +include_diagnostics = has_option(""include-diagnostics"") +force_cythonize = has_option(""force-cythonize"") + + +def make_extensions(): + is_ci = bool(os.getenv(""CI"", """")) + try: + import numpy + except ImportError: + print(""Installation requires `numpy`"") + raise + macros = [] + try: + from Cython.Build import cythonize + cython_directives = { + 'embedsignature': True, + ""profile"": include_diagnostics + } + if include_diagnostics: + macros.append((""CYTHON_TRACE_NOGIL"", ""1"")) + if is_ci and include_diagnostics: + cython_directives['linetrace'] = True + extensions = cythonize( + [ + Extension( + name=""glycresoft._c.structure.fragment_match_map"", + sources=[""src/glycresoft/_c/structure/fragment_match_map.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.structure.intervals"", + sources=[""src/glycresoft/_c/structure/intervals.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.scoring.shape_fitter"", + sources=[""src/glycresoft/_c/scoring/shape_fitter.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.chromatogram_tree.mass_shift"", + sources=[""src/glycresoft/_c/chromatogram_tree/mass_shift.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.chromatogram_tree.index"", + sources=[""src/glycresoft/_c/chromatogram_tree/index.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.tandem.core_search"", + sources=[""src/glycresoft/_c/tandem/core_search.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.database.mass_collection"", + sources=[""src/glycresoft/_c/database/mass_collection.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.tandem.tandem_scoring_helpers"", + libraries=[""npymath""], + library_dirs=[os.path.join(os.path.dirname(numpy.get_include()), ""lib"")], + sources=[""src/glycresoft/_c/tandem/tandem_scoring_helpers.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.tandem.spectrum_match"", + sources=[""src/glycresoft/_c/tandem/spectrum_match.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.composition_network.graph"", + sources=[""src/glycresoft/_c/composition_network/graph.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.composition_distribution_model.utils"", + sources=[""src/glycresoft/_c/composition_distribution_model/utils.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.structure.lru"", sources=[""src/glycresoft/_c/structure/lru.pyx""] + ), + Extension( + name=""glycresoft._c.tandem.target_decoy"", + sources=[""src/glycresoft/_c/tandem/target_decoy.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.structure.structure_loader"", + sources=[""src/glycresoft/_c/structure/structure_loader.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.tandem.oxonium_ions"", + sources=[""src/glycresoft/_c/tandem/oxonium_ions.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.structure.probability"", + sources=[""src/glycresoft/_c/structure/probability.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.tandem.peptide_graph"", + sources=[""src/glycresoft/_c/tandem/peptide_graph.pyx""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.scoring.elution_time_grouping"", + sources=[""src/glycresoft/_c/scoring/elution_time_grouping.pyx""], + include_dirs=[numpy.get_include()], + ), + ], + compiler_directives=cython_directives, + force=force_cythonize, + ) + except ImportError as err: + print(err) + extensions = [ + Extension( + name=""glycresoft._c.structure.fragment_match_map"", + sources=[""src/glycresoft/_c/structure/fragment_match_map.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.structure.intervals"", + sources=[""src/glycresoft/_c/structure/intervals.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.scoring.shape_fitter"", + sources=[""src/glycresoft/_c/scoring/shape_fitter.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.chromatogram_tree.mass_shift"", + sources=[""src/glycresoft/_c/chromatogram_tree/mass_shift.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.chromatogram_tree.index"", + sources=[""src/glycresoft/_c/chromatogram_tree/index.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.tandem.core_search"", + sources=[""src/glycresoft/_c/tandem/core_search.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.database.mass_collection"", + sources=[""src/glycresoft/_c/database/mass_collection.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.tandem.tandem_scoring_helpers"", + libraries=[""npymath""], + library_dirs=[os.path.join(os.path.dirname(numpy.get_include()), ""lib"")], + sources=[""src/glycresoft/_c/tandem/tandem_scoring_helpers.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.tandem.spectrum_match"", + sources=[""src/glycresoft/_c/tandem/spectrum_match.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.composition_network.graph"", + sources=[""src/glycresoft/_c/composition_network/graph.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.composition_distribution_model.utils"", + sources=[""src/glycresoft/_c/composition_distribution_model/utils.c""], + include_dirs=[numpy.get_include()], + ), + Extension(name=""glycresoft._c.structure.lru"", sources=[""src/glycresoft/_c/structure/lru.c""]), + Extension( + name=""glycresoft._c.tandem.target_decoy"", + sources=[""src/glycresoft/_c/tandem/target_decoy.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.structure.structure_loader"", + sources=[""src/glycresoft/_c/structure/structure_loader.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.tandem.oxonium_ions"", + sources=[""src/glycresoft/_c/tandem/oxonium_ions.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.structure.probability"", + sources=[""src/glycresoft/_c/structure/probability.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.tandem.peptide_graph"", + sources=[""src/glycresoft/_c/tandem/peptide_graph.c""], + include_dirs=[numpy.get_include()], + ), + Extension( + name=""glycresoft._c.scoring.elution_time_grouping"", + sources=[""src/glycresoft/_c/scoring/elution_time_grouping.c""], + include_dirs=[numpy.get_include()], + ), + ] + return extensions + + +ext_errors = (CCompilerError, DistutilsExecError, DistutilsPlatformError) +if sys.platform == 'win32': + # 2.6's distutils.msvc9compiler can raise an IOError when failing to + # find the compiler + ext_errors += (IOError,) + + +class BuildFailed(Exception): + + def __init__(self): + self.cause = sys.exc_info()[1] # work around py 2/3 different syntax + + def __str__(self): + return str(self.cause) + + +class ve_build_ext(build_ext): + # This class allows C extension building to fail. + + def run(self): + try: + build_ext.run(self) + except DistutilsPlatformError: + traceback.print_exc() + raise BuildFailed() + + def build_extension(self, ext): + try: + build_ext.build_extension(self, ext) + except ext_errors: + traceback.print_exc() + raise BuildFailed() + except ValueError: + # this can happen on Windows 64 bit, see Python issue 7511 + traceback.print_exc() + if ""'path'"" in str(sys.exc_info()[1]): # works with both py 2/3 + raise BuildFailed() + raise + + +cmdclass = {} + +cmdclass['build_ext'] = ve_build_ext + + +def status_msgs(*msgs): + print('*' * 75) + for msg in msgs: + print(msg) + print('*' * 75) + + +with open(""src/glycresoft/version.py"") as version_file: + version = None + for line in version_file.readlines(): + if ""version = "" in line: + version = line.split("" = "")[1].replace(""\"""", """").strip() + print(""Version is: %r"" % (version,)) + break + else: + print(""Cannot determine version"") + + +requirements = [] +with open(""requirements.txt"") as requirements_file: + requirements.extend(requirements_file.readlines()) + +try: + with open(""README.md"") as readme_file: + long_description = readme_file.read() +except Exception as e: + print(e) + long_description = """" + + +def run_setup(include_cext=True): + + setup( + name=""glycresoft"", + version=version, + packages=find_packages(where=""src""), + package_dir={"""": ""src""}, + include_package_data=True, + author="", "".join([""Joshua Klein""]), + author_email=""jaklein@bu.edu"", + description=""Glycan and Glycopeptide Mass Spectrometry Database Search Tool"", + long_description=long_description, + long_description_content_type=""text/markdown"", + entry_points={ + ""console_scripts"": [""glycresoft = glycresoft.cli.__main__:main""], + }, + extras_require={""fragmentation-modeling"": [""glycopeptide-feature-learning""]}, + package_data={ + ""glycresoft.models"": [""src/glycresoft/models/data/*""], + ""glycresoft.database.prebuilt"": [""src/glycresoft/database/prebuilt/data/*""], + ""glycresoft.output.report.glycan_lcms"": [""src/glycresoft/output/report/glycan_lcms/*""], + ""glycresoft.output.report.glycopeptide_lcmsms"": [""src/glycresoft/output/report/glycopeptide_lcmsms/*""], + }, + ext_modules=make_extensions() if include_cext else None, + cmdclass=cmdclass, + install_requires=requirements, + classifiers=[ + ""Development Status :: 3 - Alpha"", + ""Intended Audience :: Science/Research"", + ""License :: OSI Approved :: Apache Software License"", + ""Topic :: Scientific/Engineering :: Bio-Informatics"", + ], + zip_safe=False, + python_requires="">3.8"", + project_urls={ + ""Documentation"": ""https://mobiusklein.github.io/glycresoft"", + ""Source Code"": ""https://github.com/mobiusklein/glycresoft"", + ""Issue Tracker"": ""https://github.com/mobiusklein/glycresoft/issues"", + }, + ) + + +try: + run_setup(True) +except Exception as exc: + print(exc) + run_setup(False) + + status_msgs( + ""WARNING: The C extension could not be compiled, "" + + ""speedups are not enabled."", + ""Plain-Python build succeeded."" + ) +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/make-pyinstaller.sh",".sh","576","15","#!/bin/bash + +# NOTE: New versions of PyInstaller bundle more and more hooks, and throw +# errors if there are duplicate hooks. Mangle the names of hooks that have +# been superceded. + +# NOTE: PyInstaller and newer versions of Anaconda-specific NumPy are incompatible. +# Even if you're using a conda environment, you must install NumPy with pip in order +# for the executable to work after deactivating the environment or moving it to another +# computer. + +rm -rf ./build/ ./dist/ +echo ""Beginning build"" +python -m PyInstaller ./glycresoft-cli.spec --workpath build --distpath dist +","Shell" +"Glycomics","mobiusklein/glycresoft","pyinstaller/install-from-git.py",".py","493","20","from os import path as ospath +import sys +import os +import shutil + +repos = [ + ""https://github.com/mobiusklein/glypy"", + ""https://github.com/mobiusklein/glycopeptidepy"", + ""https://github.com/mobiusklein/ms_deisotope"", +] + +clone_dir = ospath.join(ospath.dirname(__file__), ""gitsrc"") + +origin_path = os.getcwd() +os.system(""rm -rf %s"" % clone_dir) + +for repo in repos: + repopath = ospath.join(clone_dir, ospath.splitext(ospath.basename(repo))[0]) + os.system(""pip install git+%s"" % repo) +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/glycresoft-cli.py",".py","1522","55","import matplotlib +import os +import sys +import click +import platform +import multiprocessing + +if platform.system().lower() != 'windows': + os.environ[""NOWAL""] = ""1"" +else: + # while click.echo works when run under normal conditions, + # it has started failing when packaged with PyInstaller. The + # implementation of click's _winterm module seems to replicate + # a lot of logic found in win_unicode_console.streams, but using + # win_unicode_console seems to fix the problem, (found after tracing + # why importing ipdb which imported IPython which called this fixed + # the problem) + import win_unicode_console + # win_unicode_console.enable() +app_dir = click.get_app_dir(""glycresoft"") +_mpl_cache_dir = os.path.join(app_dir, 'mpl') + +if not os.path.exists(_mpl_cache_dir): + os.makedirs(_mpl_cache_dir) + +os.environ[""MPLCONFIGDIR""] = _mpl_cache_dir + +try: + matplotlib.use(""agg"") +except Exception: + pass + +from rdflib.plugins import stores +from rdflib.plugins.stores import sparqlstore + +from glycresoft.cli.__main__ import main + +# import the fallback name +import glycan_profiling + +try: + from glycopeptide_feature_learning import (peak_relations, multinomial_regression, scoring) + from glycopeptide_feature_learning._c import (amino_acid_classification, approximation, model_types, peak_relations) +except ImportError: + pass + + +from glycresoft.cli.validators import strip_site_root + +sys.excepthook = strip_site_root + +if __name__ == '__main__': + multiprocessing.freeze_support() + main() +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/hooks/hook-glycopeptide_feature_learning.py",".py","278","7","from PyInstaller.utils.hooks import collect_submodules, collect_data_files + +hiddenimports = collect_submodules( + ""glycopeptide_feature_learning._c"") + collect_submodules(""glycopeptide_feature_learning.scoring._c"") + +datas = collect_data_files('glycopeptide_feature_learning') +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/hooks/hook-psims.py",".py","92","4","from PyInstaller.utils.hooks import collect_data_files + +datas = collect_data_files(""psims"") +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/hooks/hook-glycresoft.py",".py","314","8"," +from PyInstaller.utils.hooks import collect_submodules, collect_data_files + +hiddenimports = collect_submodules(""glycresoft._c"") + +datas = list(filter(lambda x: ""test_data"" not in x[1] and not x[0].endswith( + '.c') and not x[0].endswith('.html') and not x[0].endswith('.pyx'), collect_data_files(""glycresoft""))) +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/hooks/_hook-rdflib.py",".py","110","5"," +from PyInstaller.utils.hooks import collect_submodules + +hiddenimports = collect_submodules(""rdflib.plugins"") +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/hooks/hook-sklearn.py",".py","108","4","from PyInstaller.utils.hooks import collect_submodules + +hiddenimports = collect_submodules(""sklearn.utils"") +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/hooks/hook-ms_deisotope.py",".py","318","8"," +from PyInstaller.utils.hooks import collect_submodules, collect_data_files + +hiddenimports = collect_submodules(""ms_deisotope._c"") + +datas = list(filter(lambda x: ""test_data"" not in x[1] and not x[0].endswith( + '.c') and not x[0].endswith('.html') and not x[0].endswith('.pyx'), collect_data_files(""ms_deisotope""))) +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/hooks/hook-glypy.py",".py","305","9"," +from PyInstaller.utils.hooks import collect_submodules, collect_data_files + +hiddenimports = collect_submodules(""glypy._c"") + + +datas = list(filter(lambda x: ""test_data"" not in x[1] and not x[0].endswith( + '.c') and not x[0].endswith('.html') and not x[0].endswith('.pyx'), collect_data_files(""glypy""))) +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/hooks/hook-brainpy.py",".py","104","3","from PyInstaller.utils.hooks import collect_submodules +hiddenimports = collect_submodules(""brainpy._c"") +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/hooks/hook-ms_peak_picker.py",".py","113","5"," +from PyInstaller.utils.hooks import collect_submodules + +hiddenimports = collect_submodules(""ms_peak_picker._c"") +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/hooks/hook-glycresoft_app.py",".py","171","5"," +from PyInstaller.utils.hooks import collect_submodules, collect_data_files + +datas = list(filter(lambda x: ""test_data"" not in x[1], collect_data_files(""glycresoft_app""))) +","Python" +"Glycomics","mobiusklein/glycresoft","pyinstaller/hooks/hook-glycopeptidepy.py",".py","322","8"," +from PyInstaller.utils.hooks import collect_submodules, collect_data_files + +hiddenimports = collect_submodules(""glycopeptidepy._c"") + +datas = list(filter(lambda x: ""test_data"" not in x[1] and not x[0].endswith( + '.c') and not x[0].endswith('.html') and not x[0].endswith('.pyx'), collect_data_files(""glycopeptidepy""))) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/task.py",".py","20110","694","from __future__ import print_function +import os +import logging +import pprint +import time +import traceback +import multiprocessing +import threading + +from typing import Any, Generic, List, Optional, TypeVar, Union +from logging.handlers import QueueHandler, QueueListener +from multiprocessing.managers import SyncManager +from datetime import datetime + +from queue import Empty +import warnings + +import six + +from glycresoft.version import version + + + +logger = logging.getLogger(""glycresoft.task"") + +T = TypeVar(""T"") + + +def display_version(print_fn): + msg = ""glycresoft: version %s"" % version + print_fn(msg) + + +def ensure_text(obj): + if six.PY2: + return six.text_type(obj) + else: + return str(obj) + + +def fmt_msg(*message): + return u""%s %s"" % (ensure_text(datetime.now().isoformat(' ')), u', '.join(map(ensure_text, message))) + + +def printer(obj, *message, stacklevel=None): + print(fmt_msg(*message)) + + +def debug_printer(obj, *message, stacklevel=None): + if obj.in_debug_mode(): + print(u""DEBUG:"" + fmt_msg(*message)) + + +class CallInterval(object): + """"""Call a function every `interval` seconds from + a separate thread. + + Attributes + ---------- + stopped: threading.Event + A semaphore lock that controls when to run `call_target` + call_target: callable + The thing to call every `interval` seconds + args: iterable + Arguments for `call_target` + interval: number + Time between calls to `call_target` + """""" + + def __init__(self, interval, call_target, *args): + self.stopped = threading.Event() + self.interval = interval + self.call_target = call_target + self.args = args + self.thread = threading.Thread(target=self.mainloop) + self.thread.daemon = True + + def mainloop(self): + while not self.stopped.wait(self.interval): + try: + self.call_target(*self.args) + except Exception as e: + logger.exception(""An error occurred in %r"", self, exc_info=e) + + def start(self): + self.thread.start() + + def stop(self): + self.stopped.set() + + +class IPCLoggingManager: + queue: multiprocessing.Queue + listener: QueueListener + + def __init__(self, queue=None, *handlers): + if queue is None: + queue = multiprocessing.Queue() + if not handlers: + logger = logging.getLogger() + handlers = logger.handlers + + self.queue = queue + self.listener = QueueListener( + queue, *handlers, respect_handler_level=True) + self.listener.start() + + def sender(self, logger_name=""glycresoft""): + return LoggingHandlerToken(self.queue, logger_name) + + def start(self): + self.listener.start() + + def stop(self): + try: + self.listener.stop() + except AttributeError: + pass + + +class LoggingHandlerToken: + queue: multiprocessing.Queue + name: str + configured: bool + + def __init__(self, queue: multiprocessing.Queue, name: str): + self.queue = queue + self.name = name + self.configured = False + + def get_logger(self) -> logging.Logger: + logger = logging.getLogger(self.name) + return logger + + def clear_handlers(self, logger: logging.Logger): + for handler in list(logger.handlers): + logger.removeHandler(handler) + if logger.parent is not None and logger.parent is not logger: + self.clear_handlers(logger.parent) + + def log(self, *args, **kwargs): + kwargs.setdefault('stacklevel', 2) + self.get_logger().info(*args, **kwargs) + + def __call__(self, *args, **kwargs): + kwargs.setdefault('stacklevel', 3) + self.log(*args, **kwargs) + + def add_handler(self): + if self.configured: + return + logger = self.get_logger() + self.clear_handlers(logger) + handler = QueueHandler(self.queue) + handler.setLevel(logging.INFO) + logger.addHandler(handler) + logger.setLevel(logging.INFO) + LoggingMixin.log_with_logger(logger) + TaskBase.log_with_logger(logger) + self.configured = True + + def __getstate__(self): + return { + ""queue"": self.queue, + ""name"": self.name + } + + def __setstate__(self, state): + self.queue = state['queue'] + self.name = state['name'] + self.configured = False + if multiprocessing.current_process().name == ""MainProcess"": + return + self.add_handler() + + +class MessageSpooler(object): + """"""An IPC-based logging helper + + Attributes + ---------- + halting : bool + Whether the object is attempting to + stop, so that the internal thread can + tell when it should stop and tell other + objects using it it is trying to stop + handler : Callable + A Callable object which can be used to do + the actual logging + message_queue : multiprocessing.Queue + The Inter-Process Communication queue + thread : threading.Thread + The internal listener thread that will consume + message_queue work items + """""" + def __init__(self, handler): + self.handler = handler + self.message_queue = multiprocessing.Queue() + self.halting = False + self.thread = threading.Thread(target=self.run) + self.thread.start() + + def run(self): + while not self.halting: + try: + message = self.message_queue.get(True, 2) + self.handler(*message) + except Exception: + continue + + def stop(self): + self.halting = True + self.thread.join() + + def sender(self): + return MessageSender(self.message_queue) + + +class MessageSender(object): + """"""A simple callable for pushing objects into an IPC + queue. + + Attributes + ---------- + queue : multiprocessing.Queue + The Inter-Process Communication queue + """""" + def __init__(self, queue): + self.queue = queue + + def __call__(self, *message): + self.send(*message) + + def send(self, *message): + self.queue.put(message) + + +def humanize_class_name(name): + parts = [] + i = 0 + last = 0 + while i < len(name): + c = name[i] + if c.isupper() and i != last: + if i + 1 < len(name): + if name[i + 1].islower(): + part = name[last:i] + parts.append(part) + last = i + i += 1 + parts.append(name[last:i]) + return ' '.join(parts) + + +class LoggingMixin(object): + logger_state = None + print_fn = printer + debug_print_fn = debug_printer + error_print_fn = printer + warn_print_fn = warnings.warn + + _debug_enabled = None + + @classmethod + def log_with_logger(cls, logger): + cls.logger_state = logger + cls.print_fn = logger.info + cls.debug_print_fn = logger.debug + cls.error_print_fn = logger.error + cls.warn_print_fn = logger.warning + + def instance_log_with_logger(self, logger): + self.logger_state = logger + self.print_fn = logger.info + self.debug_print_fn = logger.debug + self.error_print_fn = logger.error + self.warn_print_fn = logger.warning + + @classmethod + def log_to_stdout(cls): + cls.logger_state = None + cls.print_fn = printer + cls.debug_print_fn = debug_printer + cls.error_print_fn = printer + cls.warn_print_fn = warnings.warn + + def log(self, *message): + self.print_fn(u', '.join(map(ensure_text, message)), stacklevel=2) + + def debug(self, *message): + self.debug_print_fn(u', '.join(map(ensure_text, message)), stacklevel=2) + + def error(self, *message, **kwargs): + exception = kwargs.get(""exception"") + self.error_print_fn(u', '.join( + map(ensure_text, message)), stacklevel=2) + if exception is not None: + self.error_print_fn(traceback.format_exc()) + + def warn(self, *message, **kwargs): + self.warn_print_fn(u', '.join(map(ensure_text, message)), stacklevel=2) + + def ipc_logger(self, handler=None): + return IPCLoggingManager() + + def in_debug_mode(self): + if self._debug_enabled is None: + logger_state = self.logger_state + if logger_state is not None: + self._debug_enabled = logger_state.isEnabledFor(""DEBUG"") + return bool(self._debug_enabled) + + +class TaskBase(LoggingMixin): + """"""A base class for a discrete, named step in a pipeline that + executes in sequence. + + Attributes + ---------- + debug_print_fn : Callable + The function called to print debug messages + display_fields : bool + Whether to display fields at the start of execution + end_time : datetime.datetime + The time when the task ended + error_print_fn : Callable + The function called to print error messages + logger_state : logging.Logger + The Logger bound to this task + print_fn : Callable + The function called to print status messages + start_time : datetime.datetime + The time when the task began + status : str + The state of the executing task + """""" + + status = ""new"" + + display_fields = True + + _display_name = None + + @property + def display_name(self): + if self._display_name is None: + return humanize_class_name(self.__class__.__name__) + else: + return self._display_name + + def in_debug_mode(self): + if self._debug_enabled is None: + logger_state = self.logger_state + if logger_state is not None: + self._debug_enabled = logger_state.isEnabledFor(logging.DEBUG) + return bool(self._debug_enabled) + + def _format_fields(self): + if self.display_fields: + return '\n' + pprint.pformat( + {k: v for k, v in self.__dict__.items() + if not (k.startswith(""_"") or v is None)}) + else: + return '' + + def display_header(self): + display_version(self.log) + + def try_set_process_name(self, name=None): + """""" + This helper method may be used to try to change a process's name + in order to make discriminating which role a particular process is + fulfilling. This uses a third-party utility library that may not behave + the same way on all platforms, and therefore this is done for convenience + only. + + Parameters + ---------- + name : str, optional + A name to set. If not provided, will check the attribute ``process_name`` + for a non-null value, or else have no effect. + """""" + if name is None: + name = getattr(self, 'process_name', None) + if name is None: + return + _name_process(name) + + def _begin(self, verbose=True, *args, **kwargs): + self.on_begin() + self.start_time = datetime.now() + self.status = ""started"" + if verbose: + self.log( + ""Begin %s%s"" % ( + self.display_name, + self._format_fields())) + + def _end(self, verbose=True, *args, **kwargs): + self.on_end() + self.end_time = datetime.now() + if verbose: + self.log(""End %s"" % self.display_name) + self.log(self.summarize()) + + def on_begin(self): + pass + + def on_end(self): + pass + + def summarize(self): + chunks = [ + ""Started at %s."" % self.start_time, + ""Ended at %s."" % self.end_time, + ""Total time elapsed: %s"" % (self.end_time - self.start_time), + ""%s completed successfully."" % self.__class__.__name__ if self.status == 'completed' else + ""%s failed with error message %r"" % (self.__class__.__name__, self.status), + '' + ] + return '\n'.join(chunks) + + def start(self, *args, **kwargs): + self._begin(*args, **kwargs) + try: + out = self.run() + except (KeyboardInterrupt) as e: + logger.exception(""An error occurred: %r"", e, exc_info=e) + self.status = e + out = e + raise e + else: + self.status = 'completed' + self._end(*args, **kwargs) + return out + + def interact(self, **kwargs): + from IPython.terminal.embed import InteractiveShellEmbed, load_default_config + import sys + config = kwargs.get('config') + header = kwargs.pop('header', u'') + compile_flags = kwargs.pop('compile_flags', None) + if config is None: + config = load_default_config() + config.InteractiveShellEmbed = config.TerminalInteractiveShell + kwargs['config'] = config + frame = sys._getframe(1) + shell = InteractiveShellEmbed.instance( + _init_location_id='%s:%s' % ( + frame.f_code.co_filename, frame.f_lineno), **kwargs) + shell(header=header, stack_depth=2, compile_flags=compile_flags, + _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno)) + InteractiveShellEmbed.clear_instance() + + +log_handle = TaskBase() + + +class TaskExecutionSequence(TaskBase, Generic[T]): + """"""A task unit that executes in a separate thread or process."""""" + + def __call__(self) -> T: + result = None + try: + if self._running_in_process: + self.log(""%s running on PID %r"" % (self, multiprocessing.current_process().pid)) + if os.getenv(""GLYCRESOFTPROFILING""): + import cProfile + profiler = cProfile.Profile() + result = profiler.runcall(self.run, standalone_mode=False) + profiler.dump_stats('glycresoft_performance.profile') + else: + result = self.run() + self.debug(""%r Done"" % self) + except Exception as err: + self.error(""An error occurred while executing %s"" % + self, exception=err) + result = None + self.set_error_occurred() + try: + self.done_event.set() + except AttributeError: + pass + finally: + return result + + def run(self) -> T: + raise NotImplementedError() + + def _get_repr_details(self): + return '' + + _thread: Optional[Union[threading.Thread, multiprocessing.Process]] = None + _running_in_process: bool = False + _error_flag: Optional[threading.Event] = None + + def error_occurred(self) -> bool: + if self._error_flag is None: + return False + else: + return self._error_flag.is_set() + + def set_error_occurred(self): + if self._error_flag is None: + return False + else: + return self._error_flag.set() + + def __repr__(self): + template = ""{self.__class__.__name__}({details})"" + return template.format(self=self, details=self._get_repr_details()) + + def _make_event(self, provider=None) -> Union[threading.Event, multiprocessing.Event]: + if provider is None: + provider = threading + return provider.Event() + + def _name_for_execution_sequence(self): + return (""%s-%r"" % (self.__class__.__name__, id(self))) + + def start(self, process: bool=False, daemon: bool=False): + if self._thread is not None: + return self._thread + if process: + self._running_in_process = True + self._error_flag = self._make_event(multiprocessing) + t = multiprocessing.Process( + target=self, name=self._name_for_execution_sequence()) + if daemon: + t.daemon = daemon + else: + self._error_flag = self._make_event(threading) + t = threading.Thread( + target=self, name=self._name_for_execution_sequence()) + if daemon: + t.daemon = daemon + t.start() + self._thread = t + return t + + def join(self, timeout: Optional[float]=None) -> bool: + if self.error_occurred(): + return True + try: + return self._thread.join(timeout) + except KeyboardInterrupt: + self.set_error_occurred() + return True + + def is_alive(self): + if self.error_occurred(): + return False + return self._thread.is_alive() + + def stop(self): + if self.is_alive(): + self.set_error_occurred() + + def kill_process(self): + if self._running_in_process: + if self.is_alive(): + self._thread.terminate() + else: + self.log(""Cannot kill a process running in a thread"") + + +class Pipeline(TaskExecutionSequence): + tasks: List[TaskExecutionSequence] + error_polling_rate: float + + def __init__(self, tasks, error_polling_rate=1.0): + self.tasks = tasks + self.error_polling_rate = error_polling_rate + + def start(self, *args, **kwargs): + for task in self: + task.start(*args, **kwargs) + + def join(self, timeout: Optional[float]=None): + if timeout is not None: + for task in self: + task.join(timeout) + else: + timeout = self.error_polling_rate + while True: + has_error = self.error_occurred() + if has_error: + self.log(""... Detected an error flag. Stopping!"") + self.stop() + break + alive = 0 + for task in self: + task.join(0.01) + is_alive = task.is_alive() + alive += is_alive + if alive == 0: + break + time.sleep(timeout) + + def is_alive(self): + alive = 0 + for task in self: + alive += task.is_alive() + return alive + + def error_occurred(self) -> int: + errors = 0 + for task in self.tasks: + errors += task.error_occurred() + return errors + + def stop(self): + for task in self.tasks: + task.stop() + + def __iter__(self): + return iter(self.tasks) + + def __len__(self): + return len(self.tasks) + + def __getitem__(self, i: Union[int, slice]): + return self.tasks[i] + + def add(self, task): + self.tasks.append(task) + return self + + +class SinkTask(TaskExecutionSequence): + def __init__(self, in_queue, in_done_event): + self.in_queue = in_queue + self.in_done_event = in_done_event + self.done_event = self._make_event() + + def handle_item(self, task): + pass + + def process(self): + has_work = True + while has_work and not self.error_occurred(): + try: + item = self.in_queue.get(True, 10) + self.handle_item(item) + except Empty: + if self.in_done_event.is_set(): + has_work = False + break + self.done_event.set() + + +def make_shared_memory_manager(): + manager = SyncManager() + manager.start(_name_process, (""glycresoft-shm"", )) + return manager + + +def _name_process(name): + try: + import setproctitle + setproctitle.setproctitle(name) + except (ImportError, AttributeError): + pass + + +def elapsed(seconds): + '''Convert a second count into a human readable duration + + Parameters + ---------- + seconds : :class:`int` + The number of seconds elapsed + + Returns + ------- + :class:`str` : + A formatted, comma separated list of units of duration in days, hours, minutes, and seconds + ''' + periods = [ + ('day', 60 * 60 * 24), + ('hour', 60 * 60), + ('minute', 60), + ('second', 1) + ] + + tokens = [] + for period_name, period_seconds in periods: + if seconds > period_seconds: + period_value, seconds = divmod(seconds, period_seconds) + has_s = 's' if period_value > 1 else '' + tokens.append(""%s %s%s"" % (period_value, period_name, has_s)) + + return "", "".join(tokens) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/profiler.py",".py","81355","1772","''' +High level analytical pipeline implementations. + +Each class is designed to encapsulate a single broad task, i.e. +LC-MS/MS deconvolution or structure identification +''' +import os +import platform + +from collections import defaultdict +from typing import Any, DefaultDict, Dict, List, Optional, Tuple, Type, Sequence +from glycresoft.chromatogram_tree.mass_shift import MassShiftBase +from glycresoft.tandem.glycopeptide.dynamic_generation.journal import SolutionSetGrouper + +import numpy as np + +from ms_deisotope.output import ProcessedMSFileLoader +from ms_deisotope.data_source import ProcessedRandomAccessScanSource +from ms_deisotope.tools.deisotoper.workflow import SampleConsumer as _SampleConsumer + +import glypy +from glypy.utils import Enum + +from glycopeptidepy.utils.collectiontools import descending_combination_counter +from glycopeptidepy.structure.modification import rule_string_to_specialized_rule + +from glycresoft.database.disk_backed_database import ( + DiskBackedStructureDatabaseBase, + GlycanCompositionDiskBackedStructureDatabase, + GlycopeptideDiskBackedStructureDatabase) + +from glycresoft.database.analysis import ( + GlycanCompositionChromatogramAnalysisSerializer, + DynamicGlycopeptideMSMSAnalysisSerializer, + GlycopeptideMSMSAnalysisSerializer) + +from glycresoft.serialize import ( + DatabaseScanDeserializer, AnalysisSerializer, + AnalysisTypeEnum, object_session) + +from glycresoft.scoring import ( + ChromatogramSolution) +from glycresoft.tandem.target_decoy.base import TargetDecoyAnalyzer + +from glycresoft.trace import ( + ChromatogramExtractor, + LogitSumChromatogramProcessor, + LaplacianRegularizedChromatogramProcessor, + ChromatogramEvaluator) + + +from glycresoft.chromatogram_tree import ChromatogramFilter, SimpleChromatogram, Unmodified + +from glycresoft.models import GeneralScorer, get_feature + +from glycresoft.scoring.elution_time_grouping import ( + GlycopeptideChromatogramProxy, GlycoformAggregator, + GlycopeptideElutionTimeModelBuildingPipeline, + PeptideYUtilizationPreservingRevisionValidator, + OxoniumIonRequiringUtilizationRevisionValidator, + CompoundRevisionValidator, ModelEnsemble as GlycopeptideElutionTimeModelEnsemble) + +from glycresoft.structure import ScanStub, ScanInformation + +from glycresoft.piped_deconvolve import ScanGenerator + +from glycresoft.tandem.chromatogram_mapping import ( + SpectrumMatchUpdater, + AnnotatedChromatogramAggregator, + TandemAnnotatedChromatogram, + TandemSolutionsWithoutChromatogram, + MS2RevisionValidator, + SignalUtilizationMS2RevisionValidator, + RevisionSummary +) + +from glycresoft.tandem import chromatogram_mapping +from glycresoft.tandem.target_decoy import TargetDecoySet +from glycresoft.tandem.temp_store import TempFileManager +from glycresoft.tandem.workflow import SearchEngineBase + +from glycresoft.tandem.spectrum_match.spectrum_match import MultiScoreSpectrumMatch, SpectrumMatch +from glycresoft.tandem.spectrum_match.solution_set import QValueRetentionStrategy, SpectrumSolutionSet + +from glycresoft.tandem.glycopeptide.scoring import ( + LogIntensityScorer, + CoverageWeightedBinomialScorer, + CoverageWeightedBinomialModelTree) + +from glycresoft.tandem.glycopeptide.glycopeptide_matcher import ( + GlycopeptideDatabaseSearchIdentifier, + ExclusiveGlycopeptideDatabaseSearchComparer) + +from glycresoft.tandem.glycopeptide.dynamic_generation import ( + MultipartGlycopeptideIdentifier, GlycopeptideFDREstimationStrategy, IdKeyMaker) + +from glycresoft.tandem.glycopeptide import ( + identified_structure as identified_glycopeptide) + +from glycresoft.tandem.glycopeptide.identified_structure import IdentifiedGlycopeptide + +from glycresoft.tandem.glycan.composition_matching import SignatureIonMapper +from glycresoft.tandem.glycan.scoring.signature_ion_scoring import SignatureIonScorer + +from glycresoft.tandem.localize import EvaluatedSolutionBins, ScanLoadingModificationLocalizationSearcher + +from glycresoft.task import TaskBase +from glycresoft import serialize + +from glycresoft.tandem.coelute import CoElutionAdductFinder + + +debug_mode = bool(os.environ.get('GLYCRESOFTDEBUG', False)) + + +class SampleConsumer(TaskBase, _SampleConsumer): + scan_generator_cls = ScanGenerator + + +class ChromatogramSummarizer(TaskBase): + """""" + Implement the simple diagnostic chromatogram extraction pipeline. + + Given a deconvoluted mzML file produced by :class:`SampleConsumer` this will build + aggregated extracted ion chromatograms for each distinct mass over time. + + Unlike most of the pipelines here, this task does not currently save its own output, + instead returning it to the caller of it's :meth:`run` method. + """""" + + def __init__(self, mzml_path, threshold_percentile=90, minimum_mass=300.0, extract_signatures=True, evaluate=False, + chromatogram_scoring_model=None): + if chromatogram_scoring_model is None: + chromatogram_scoring_model = GeneralScorer + self.mzml_path = mzml_path + self.threshold_percentile = threshold_percentile + self.minimum_mass = minimum_mass + self.extract_signatures = extract_signatures + self.intensity_threshold = 0.0 + self.chromatogram_scoring_model = chromatogram_scoring_model + self.should_evaluate = evaluate + + def make_scan_loader(self): + """"""Create a reader for the deconvoluted LC-MS data file."""""" + scan_loader = ProcessedMSFileLoader(self.mzml_path) + return scan_loader + + def estimate_intensity_threshold(self, scan_loader): + """"""Build the MS1 peak intensity distribution to estimate the global intensity threshold. + + This threshold is then used when extracting chromatograms. + """""" + acc = [] + for scan_id in scan_loader.extended_index.ms1_ids: + header = scan_loader.get_scan_header_by_id(scan_id) + acc.extend(header.arrays.intensity) + self.intensity_threshold = np.percentile(acc, self.threshold_percentile) + return self.intensity_threshold + + def extract_chromatograms(self, scan_loader): + """"""Perform the chromatogram extraction process."""""" + extractor = ChromatogramExtractor( + scan_loader, minimum_intensity=self.intensity_threshold, + minimum_mass=self.minimum_mass) + chroma = extractor.run() + return chroma, extractor.total_ion_chromatogram, extractor.base_peak_chromatogram + + def extract_signature_ion_traces(self, scan_loader): + """"""Skim the MSn spectra to look for oxonium ion signatures over time."""""" + from glycresoft.tandem.oxonium_ions import standard_oxonium_ions + window_width = 0.01 + ox_time = [] + ox_current = [] + for scan_id in scan_loader.extended_index.msn_ids: + try: + scan = scan_loader.get_scan_header_by_id(scan_id) + except AttributeError: + self.log(""Unable to resolve scan id %r"" % scan_id) + total = 0 + for ion in standard_oxonium_ions: + mid = ion.mass() + 1.007 + lo = mid - window_width + hi = mid + window_width + sig_slice = scan.arrays.between_mz(lo, hi) + total += sig_slice.intensity.sum() + ox_time.append(scan.scan_time) + ox_current.append(total) + oxonium_ion_chromatogram = SimpleChromatogram(zip(ox_time, ox_current)) + return oxonium_ion_chromatogram + + def evaluate_chromatograms(self, chromatograms): + evaluator = ChromatogramEvaluator(self.chromatogram_scoring_model) + solutions = evaluator.score(chromatograms) + return solutions + + def run(self): + scan_loader = self.make_scan_loader() + self.log(""... Estimating Intensity Threshold"") + self.estimate_intensity_threshold(scan_loader) + chroma, total_ion_chromatogram, base_peak_chromatogram = self.extract_chromatograms( + scan_loader) + oxonium_ion_chromatogram = None + if self.extract_signatures: + oxonium_ion_chromatogram = self.extract_signature_ion_traces(scan_loader) + if self.should_evaluate: + chroma = self.evaluate_chromatograms(chroma) + return chroma, (total_ion_chromatogram, base_peak_chromatogram, oxonium_ion_chromatogram) + + +class GlycanChromatogramAnalyzer(TaskBase): + """"""Analyze glycan LC-MS profiling data, assigning glycan compositions to extracted chromatograms. + + The base implementation targets the legacy deconvoluted spectrum + database format. See :class:`MzMLGlycanChromatogramAnalyzer` for the + newer implementation targeting the mzML file produced by :class:`SampleConsumer`. + """""" + + @staticmethod + def expand_mass_shifts(mass_shift_counts, crossproduct=True, limit=None): + if limit is None: + limit = float('inf') + combinations = [] + if crossproduct: + counts = descending_combination_counter(mass_shift_counts) + for combo in counts: + scaled = [] + if sum(combo.values()) > limit: + continue + for k, v in combo.items(): + if v == 0: + continue + scaled.append(k * v) + if scaled: + base = scaled[0] + for ad in scaled[1:]: + base += ad + combinations.append(base) + else: + for k, total in mass_shift_counts.items(): + for t in range(1, total + 1): + combinations.append(k * t) + return combinations + + def __init__(self, database_connection, hypothesis_id, sample_run_id, mass_shifts=None, + mass_error_tolerance=1e-5, grouping_error_tolerance=1.5e-5, + scoring_model=GeneralScorer, minimum_mass=500., regularize=None, + regularization_model=None, network=None, analysis_name=None, + delta_rt=0.5, require_msms_signature=0, msn_mass_error_tolerance=2e-5, + n_processes=4): + + if mass_shifts is None: + mass_shifts = [] + + self.database_connection = database_connection + self.hypothesis_id = hypothesis_id + self.sample_run_id = sample_run_id + + self.mass_error_tolerance = mass_error_tolerance + self.grouping_error_tolerance = grouping_error_tolerance + self.msn_mass_error_tolerance = msn_mass_error_tolerance + + self.scoring_model = scoring_model + self.regularize = regularize + + self.network = network + self.regularization_model = regularization_model + + self.minimum_mass = minimum_mass + self.delta_rt = delta_rt + self.mass_shifts = mass_shifts + + self.require_msms_signature = require_msms_signature + + self.analysis_name = analysis_name + self.analysis = None + self.n_processes = n_processes + + def save_solutions(self, solutions, extractor, database, evaluator): + if self.analysis_name is None: + return + self.log('Saving solutions') + analysis_saver = AnalysisSerializer( + self.database_connection, self.sample_run_id, self.analysis_name) + analysis_saver.set_peak_lookup_table(extractor.peak_mapping) + analysis_saver.set_analysis_type(AnalysisTypeEnum.glycan_lc_ms.name) + + param_dict = { + ""hypothesis_id"": self.hypothesis_id, + ""sample_run_id"": self.sample_run_id, + ""mass_error_tolerance"": self.mass_error_tolerance, + ""grouping_error_tolerance"": self.grouping_error_tolerance, + ""mass_shifts"": [mass_shift.name for mass_shift in self.mass_shifts], + ""minimum_mass"": self.minimum_mass, + ""require_msms_signature"": self.require_msms_signature, + ""msn_mass_error_tolerance"": self.msn_mass_error_tolerance + } + + evaluator.update_parameters(param_dict) + + analysis_saver.set_parameters(param_dict) + + n = len(solutions) + i = 0 + for chroma in solutions: + i += 1 + if i % 100 == 0: + self.log(""%0.2f%% of Chromatograms Saved (%d/%d)"" % (i * 100. / n, i, n)) + if chroma.composition: + analysis_saver.save_glycan_composition_chromatogram_solution(chroma) + else: + analysis_saver.save_unidentified_chromatogram_solution(chroma) + + self.analysis = analysis_saver.analysis + analysis_saver.commit() + + def make_peak_loader(self): + peak_loader = DatabaseScanDeserializer( + self.database_connection, sample_run_id=self.sample_run_id) + return peak_loader + + def load_msms(self, peak_loader): + prec_info = peak_loader.precursor_information() + msms_scans = [ + o.product for o in prec_info if o.neutral_mass is not None] + return msms_scans + + def make_database(self): + combn_size = len(self.mass_shifts) + database = GlycanCompositionDiskBackedStructureDatabase( + self.database_connection, self.hypothesis_id, cache_size=combn_size) + return database + + def make_chromatogram_extractor(self, peak_loader): + extractor = ChromatogramExtractor( + peak_loader, grouping_tolerance=self.grouping_error_tolerance, + minimum_mass=self.minimum_mass, delta_rt=self.delta_rt) + return extractor + + def make_chromatogram_processor(self, extractor, database): + if self.regularize is not None or self.regularization_model is not None: + proc = LaplacianRegularizedChromatogramProcessor( + extractor, database, network=self.network, + mass_error_tolerance=self.mass_error_tolerance, + mass_shifts=self.mass_shifts, scoring_model=self.scoring_model, + delta_rt=self.delta_rt, smoothing_factor=self.regularize, + regularization_model=self.regularization_model, + peak_loader=extractor.peak_loader) + else: + proc = LogitSumChromatogramProcessor( + extractor, database, mass_error_tolerance=self.mass_error_tolerance, + mass_shifts=self.mass_shifts, scoring_model=self.scoring_model, + delta_rt=self.delta_rt, + peak_loader=extractor.peak_loader) + return proc + + def make_mapper(self, chromatograms, peak_loader, msms_scans=None, default_glycan_composition=None, + scorer_type=SignatureIonScorer): + mapper = SignatureIonMapper( + msms_scans, chromatograms, peak_loader.convert_scan_id_to_retention_time, + self.mass_shifts, self.minimum_mass, batch_size=1000, + default_glycan_composition=default_glycan_composition, + scorer_type=scorer_type, n_processes=self.n_processes) + return mapper + + def annotate_matches_with_msms(self, chromatograms, peak_loader, msms_scans, database): + """"""Map MSn scans to chromatograms matched by precursor mass, and evaluate each glycan compostion-spectrum match. + + Parameters + ---------- + chromatograms : ChromatogramFilter + Description + peak_loader : RandomAccessScanIterator + Description + msms_scans : list + Description + database : SearchableMassCollection + Description + + Returns + ------- + ChromatogramFilter + The chromatograms with matched and scored MSn scans attached to them + """""" + default_glycan_composition = glypy.GlycanComposition( + database.hypothesis.monosaccharide_bounds()) + mapper = self.make_mapper( + chromatograms, peak_loader, msms_scans, default_glycan_composition) + self.log(""Mapping MS/MS"") + mapped_matches = mapper.map_to_chromatograms(self.mass_error_tolerance) + self.log(""Evaluating MS/MS"") + annotate_matches = mapper.score_mapped_tandem( + mapped_matches, error_tolerance=self.msn_mass_error_tolerance, include_compound=True) + return annotate_matches + + def process_chromatograms(self, processor, peak_loader, database): + """"""Extract, match and evaluate chromatograms against the glycan database. + + If MSn are available and required, then MSn scan will be extracted + and mapped onto chromatograms, and search each MSn scan with the + pseudo-fragments of the glycans matching the chromatograms they + map to. + + Parameters + ---------- + processor : ChromatgramProcessor + The container responsible for carrying out the matching + and evaluating of chromatograms + peak_loader : RandomAccessScanIterator + An object which can be used iterate over MS scans + database : SearchableMassCollection + The database of glycan compositions to serch against + """""" + if self.require_msms_signature > 0: + self.log(""Extracting MS/MS"") + msms_scans = self.load_msms(peak_loader) + if len(msms_scans) == 0: + self.log(""No MS/MS scans present. Ignoring requirement."") + processor.run() + else: + matches = processor.match_compositions() + annotated_matches = self.annotate_matches_with_msms( + matches, peak_loader, msms_scans, database) + # filter out those matches which do not have sufficient signature ion signal + # from MS2 to include. As the MS1 scoring procedure will not preserve the + # MS2 mapping, we must keep a mapping from Chromatogram Key to mapped tandem + # matches to re-align later + kept_annotated_matches = [] + key_to_tandem = defaultdict(list) + for match in annotated_matches: + accepted = False + best_score = 0 + key_to_tandem[match.key].extend(match.tandem_solutions) + for gsm in match.tandem_solutions: + if gsm.score > best_score: + best_score = gsm.score + if gsm.score > self.require_msms_signature: + accepted = True + break + if accepted: + kept_annotated_matches.append(match) + else: + self.debug( + ""%s was discarded with insufficient MS/MS evidence %f"" % ( + match, best_score)) + kept_annotated_matches = ChromatogramFilter(kept_annotated_matches) + processor.evaluate_chromatograms(kept_annotated_matches) + for solution in processor.solutions: + mapped = [] + try: + gsms = key_to_tandem[solution.key] + for gsm in gsms: + if solution.spans_time_point(gsm.scan_time): + mapped.append(gsm) + solution.tandem_solutions = mapped + except KeyError: + solution.tandem_solutions = [] + continue + processor.solutions = ChromatogramFilter([ + solution for solution in processor.solutions + if len(solution.tandem_solutions) > 0 + ]) + processor.accepted_solutions = ChromatogramFilter([ + solution for solution in processor.accepted_solutions + if len(solution.tandem_solutions) > 0 + ]) + else: + processor.run() + + def run(self): + peak_loader = self.make_peak_loader() + database = self.make_database() + smallest_database_mass = database.lowest_mass + minimum_mass_shift = min([m.mass for m in self.mass_shifts]) if self.mass_shifts else 0 + if minimum_mass_shift < 0: + smallest_database_mass = smallest_database_mass + minimum_mass_shift + if smallest_database_mass > self.minimum_mass: + self.log(""The smallest possible database mass is %f, raising the minimum mass to extract."" % ( + smallest_database_mass)) + self.minimum_mass = smallest_database_mass + + extractor = self.make_chromatogram_extractor(peak_loader) + proc = self.make_chromatogram_processor(extractor, database) + self.processor = proc + self.process_chromatograms(proc, peak_loader, database) + self.save_solutions(proc.solutions, extractor, database, proc.evaluator) + return proc + + +class MzMLGlycanChromatogramAnalyzer(GlycanChromatogramAnalyzer): + def __init__(self, database_connection, hypothesis_id, sample_path, output_path, + mass_shifts=None, mass_error_tolerance=1e-5, grouping_error_tolerance=1.5e-5, + scoring_model=None, minimum_mass=500., regularize=None, + regularization_model=None, network=None, analysis_name=None, delta_rt=0.5, + require_msms_signature=0, msn_mass_error_tolerance=2e-5, + n_processes=4): + super(MzMLGlycanChromatogramAnalyzer, self).__init__( + database_connection, hypothesis_id, -1, mass_shifts, + mass_error_tolerance, grouping_error_tolerance, + scoring_model, minimum_mass, regularize, regularization_model, network, + analysis_name, delta_rt, require_msms_signature, msn_mass_error_tolerance, + n_processes) + self.sample_path = sample_path + self.output_path = output_path + + def make_peak_loader(self): + peak_loader = ProcessedMSFileLoader(self.sample_path) + if peak_loader.extended_index is None: + if not peak_loader.has_index_file(): + self.log(""Index file missing. Rebuilding."") + peak_loader.build_extended_index() + else: + peak_loader.read_index_file() + if peak_loader.extended_index is None or len(peak_loader.extended_index.ms1_ids) < 1: + raise ValueError(""Sample Data Invalid: Could not validate MS Index"") + + return peak_loader + + def load_msms(self, peak_loader): + prec_info = peak_loader.precursor_information() + msms_scans = [ScanStub(o, peak_loader) + for o in prec_info if o.neutral_mass is not None] + return msms_scans + + def save_solutions(self, solutions, extractor, database, evaluator): + if self.analysis_name is None or self.output_path is None: + return + self.log('Saving solutions') + + exporter = GlycanCompositionChromatogramAnalysisSerializer( + self.output_path, self.analysis_name, extractor.peak_loader.sample_run, + solutions, database, extractor) + + param_dict = { + ""hypothesis_id"": self.hypothesis_id, + ""sample_run_id"": self.sample_path, + ""sample_path"": os.path.abspath(self.sample_path), + ""sample_name"": extractor.peak_loader.sample_run.name, + ""sample_uuid"": extractor.peak_loader.sample_run.uuid, + ""mass_error_tolerance"": self.mass_error_tolerance, + ""grouping_error_tolerance"": self.grouping_error_tolerance, + ""mass_shifts"": [mass_shift.name for mass_shift in self.mass_shifts], + ""minimum_mass"": self.minimum_mass, + ""require_msms_signature"": self.require_msms_signature, + ""msn_mass_error_tolerance"": self.msn_mass_error_tolerance + } + + evaluator.update_parameters(param_dict) + + exporter.run() + exporter.set_parameters(param_dict) + self.analysis = exporter.analysis + self.analysis_id = exporter.analysis.id + + +class GlycopeptideSearchStrategy(Enum): + target_internal_decoy_competition = ""target-internal-decoy-competition"" + target_decoy_competition = ""target-decoy-competition"" + multipart_target_decoy_competition = ""multipart-target-decoy-competition"" + + +class GlycopeptideLCMSMSAnalyzer(TaskBase): + def __init__(self, database_connection, hypothesis_id, sample_run_id, + analysis_name=None, grouping_error_tolerance=1.5e-5, mass_error_tolerance=1e-5, + msn_mass_error_tolerance=2e-5, psm_fdr_threshold=0.05, peak_shape_scoring_model=None, + tandem_scoring_model=None, minimum_mass=1000., save_unidentified=False, + oxonium_threshold=0.05, scan_transformer=None, mass_shifts=None, n_processes=5, + spectrum_batch_size=1000, use_peptide_mass_filter=False, maximum_mass=float('inf'), + probing_range_for_missing_precursors=3, trust_precursor_fits=True, + permute_decoy_glycans=False, rare_signatures=False, model_retention_time=False, + evaluation_kwargs=None): + if evaluation_kwargs is None: + evaluation_kwargs = {} + if tandem_scoring_model is None: + tandem_scoring_model = CoverageWeightedBinomialScorer + if peak_shape_scoring_model is None: + peak_shape_scoring_model = GeneralScorer.clone() + peak_shape_scoring_model.add_feature(get_feature(""null_charge"")) + if scan_transformer is None: + def scan_transformer(x): # pylint: disable=function-redefined + return x + if mass_shifts is None: + mass_shifts = [] + if Unmodified not in mass_shifts: + mass_shifts = [Unmodified] + list(mass_shifts) + + self.database_connection = database_connection + self.hypothesis_id = hypothesis_id + self.sample_run_id = sample_run_id + + self.analysis_name = analysis_name + self.analysis = None + self.analysis_id = None + + self.mass_error_tolerance = mass_error_tolerance + self.msn_mass_error_tolerance = msn_mass_error_tolerance + self.grouping_error_tolerance = grouping_error_tolerance + self.probing_range_for_missing_precursors = probing_range_for_missing_precursors + self.trust_precursor_fits = trust_precursor_fits + self.minimum_mass = minimum_mass + self.maximum_mass = maximum_mass + self.minimum_oxonium_ratio = oxonium_threshold + self.use_peptide_mass_filter = use_peptide_mass_filter + + self.peak_shape_scoring_model = peak_shape_scoring_model + self.psm_fdr_threshold = psm_fdr_threshold + self.tandem_scoring_model = tandem_scoring_model + self.fdr_estimator = None + self.extra_msn_evaluation_kwargs = evaluation_kwargs + self.retention_time_model = None + + self.mass_shifts = mass_shifts + + self.rare_signatures = rare_signatures + self.model_retention_time = model_retention_time + self.permute_decoy_glycans = permute_decoy_glycans + self.save_unidentified = save_unidentified + self.spectrum_batch_size = spectrum_batch_size + self.scan_transformer = scan_transformer + + self.n_processes = n_processes + self.file_manager = TempFileManager() + self.analysis_metadata = { + ""host_uname"": platform.uname()._asdict() + } + + def make_peak_loader(self): + peak_loader = DatabaseScanDeserializer( + self.database_connection, sample_run_id=self.sample_run_id) + return peak_loader + + def make_database(self): + database = GlycopeptideDiskBackedStructureDatabase( + self.database_connection, self.hypothesis_id) + return database + + def make_chromatogram_extractor(self, peak_loader): + extractor = ChromatogramExtractor( + peak_loader, grouping_tolerance=self.grouping_error_tolerance, + minimum_mass=self.minimum_mass) + return extractor + + def prepare_cache_seeds(self, database): + seeds = {} + return seeds + + def load_msms(self, peak_loader: ProcessedRandomAccessScanSource): + prec_info = peak_loader.precursor_information() + msms_scans = [o.product for o in prec_info if o.neutral_mass is not None] + return msms_scans + + def make_msn_evaluation_kwargs(self): + evaluation_kwargs = { + ""rare_signatures"": self.rare_signatures, + } + evaluation_kwargs.update(self.extra_msn_evaluation_kwargs) + return evaluation_kwargs + + def make_search_engine(self, msms_scans: List[ScanStub], + database, + peak_loader: ProcessedRandomAccessScanSource) -> SearchEngineBase: + searcher = GlycopeptideDatabaseSearchIdentifier( + [scan for scan in msms_scans + if scan.precursor_information.neutral_mass < self.maximum_mass], + self.tandem_scoring_model, database, + peak_loader.convert_scan_id_to_retention_time, + minimum_oxonium_ratio=self.minimum_oxonium_ratio, + scan_transformer=self.scan_transformer, + n_processes=self.n_processes, + mass_shifts=self.mass_shifts, + use_peptide_mass_filter=self.use_peptide_mass_filter, + file_manager=self.file_manager, + probing_range_for_missing_precursors=self.probing_range_for_missing_precursors, + trust_precursor_fits=self.trust_precursor_fits, + permute_decoy_glycans=self.permute_decoy_glycans) + return searcher + + def do_search(self, searcher: SearchEngineBase) -> TargetDecoySet: + kwargs = self.make_msn_evaluation_kwargs() + assigned_spectra = searcher.search( + precursor_error_tolerance=self.mass_error_tolerance, + error_tolerance=self.msn_mass_error_tolerance, + batch_size=self.spectrum_batch_size, + **kwargs) + return assigned_spectra + + def estimate_fdr(self, searcher: SearchEngineBase, target_decoy_set: TargetDecoySet) -> TargetDecoySet: + return searcher.estimate_fdr(*target_decoy_set, decoy_pseudocount=0.0) + + def map_chromatograms(self, + searcher: SearchEngineBase, + extractor: ChromatogramExtractor, + target_hits: List[SpectrumSolutionSet], + revision_validator_type: Optional[Type[MS2RevisionValidator]]=None) -> Tuple[ + ChromatogramFilter, + Sequence[TandemSolutionsWithoutChromatogram] + ]: + """""" + Map identified spectrum matches onto extracted chromatogram groups. + + It selects the best overall structure for each chromatogram group and merging disjoint + chromatograms which are assigned the same structure. + + The structure assigned to a chromatogram group is not necessarily the only structure that + is reasonable and there may be ambiguity. When the same exact structure with different source + information (duplicate peptide sequences, common subsequence between proteins) is assigned to + a chromatogram group, every alternative structure is included as well. + + Parameters + ---------- + searcher : object + The search algorithm implementation providing a `map_to_chromatograms` method + extractor : :class:`~.ChromatogramExtractor` or Iterable of :class:`Chromatogram` + The chromatograms to map to + target_hits : list + The list of target spectrum matches + revision_validator_type : Type[MS2RevisionValidator] + A type derived from :class:`~.MS2RevisionValidator` that + + Returns + ------- + merged: :class:`~.ChromatogramFilter` + The chromatograms after all structure assignment, aggregation and merging + is complete. + orphans: list + The set of spectrum matches which were not assigned to a chromatogram. + """""" + + def threshold_fn(x): + return x.q_value <= self.psm_fdr_threshold + + if revision_validator_type is None: + revision_validator_type = MS2RevisionValidator + + chromatograms = tuple(extractor) + + identified_spectrum_ids = {sset.scan.id for sset in target_hits} + + chroma_with_sols, orphans = searcher.map_to_chromatograms( + chromatograms, + target_hits, + self.mass_error_tolerance, + threshold_fn=threshold_fn + ) + + mapped_spectrum_ids = {sset.scan.id for chrom in chroma_with_sols for sset in chrom.tandem_solutions} + orphan_spectrum_ids = {sset.scan.id for orph in orphans for sset in orph.tandem_solutions} + + mapping_lost_spectrum_ids = identified_spectrum_ids - (mapped_spectrum_ids | orphan_spectrum_ids) + + mapping_leaked_ssets = [ + sset for sset in target_hits + if sset.scan.id in mapping_lost_spectrum_ids and + threshold_fn(sset.best_solution()) + ] + + if mapping_leaked_ssets: + self.log(f""Leaked {len(mapping_leaked_ssets)} spectra after mapping"") + if debug_mode: + breakpoint() + + # Detect leaked spectrum matches between here and after aggregate_by_assigned_entity + + self.log(""Aggregating Assigned Entities"") + merged = chromatogram_mapping.aggregate_by_assigned_entity( + chroma_with_sols, + threshold_fn=threshold_fn, + revision_validator=revision_validator_type(threshold_fn), + ) + + aggregated_spectrum_ids = {sset.scan.id for chrom in merged for sset in chrom.tandem_solutions} + aggregated_lost_spectrum_ids = identified_spectrum_ids - (aggregated_spectrum_ids | orphan_spectrum_ids) + + aggregated_leaked_ssets = [ + sset for sset in target_hits + if sset.scan.id in aggregated_lost_spectrum_ids and + threshold_fn(sset.best_solution()) + ] + + if aggregated_leaked_ssets: + self.log( + f""Leaked {len(aggregated_leaked_ssets)} spectra after aggregating"") + if debug_mode: + breakpoint() + + return merged, orphans + + def score_chromatograms(self, merged: ChromatogramFilter): + """"""Calculate the MS1 score for each chromatogram. + + Parameters + ---------- + merged : Iterable of :class:`Chromatogram` + The chromatograms to score + + Returns + ------- + list: + The scored chromatograms + """""" + chroma_scoring_model = self.peak_shape_scoring_model + scored_merged = [] + n = len(merged) + i = 0 + for c in merged: + i += 1 + if i % 500 == 0: + self.log(""%0.2f%% chromatograms evaluated (%d/%d) %r"" % (i * 100. / n, i, n, c)) + try: + chrom_score = chroma_scoring_model.logitscore(c) + scored_merged.append(ChromatogramSolution( + c, scorer=chroma_scoring_model, score=chrom_score)) + except (IndexError, ValueError) as e: + self.log(""Could not score chromatogram %r due to %s"" % (c, e)) + scored_merged.append(ChromatogramSolution(c, score=0.0)) + return scored_merged + + def assign_consensus(self, scored_merged: ChromatogramFilter, + orphans: Sequence[TandemSolutionsWithoutChromatogram]) -> Tuple[List[IdentifiedGlycopeptide], + List[ChromatogramSolution]]: + self.log(""Assigning consensus glycopeptides to spectrum clusters"") + assigned_list = list(scored_merged) + assigned_list.extend(orphans) + gps, unassigned = identified_glycopeptide.extract_identified_structures( + assigned_list, lambda x: x.q_value <= self.psm_fdr_threshold) + return gps, unassigned + + def rank_target_hits(self, searcher: SearchEngineBase, + target_decoy_set: TargetDecoySet) -> List[SpectrumSolutionSet]: + """"""Estimate the FDR using the searcher's method. + + Also count the number of acceptable target matches. Return + the full set of target matches for downstream use. + + Parameters + ---------- + searcher: object + The search algorithm implementation, providing an `estimate_fdr` method + target_decoy_set: TargetDecoySet + + Returns + ------- + Iterable of SpectrumMatch-like objects + """""" + self.log(""Estimating FDR"") + tda: TargetDecoyAnalyzer = self.estimate_fdr(searcher, target_decoy_set) + if tda is not None: + tda.pack() + self.fdr_estimator = tda + target_hits = target_decoy_set.target_matches + n_below = 0 + n_below_1 = 0 + n_below_5 = 0 + for target in target_hits: + if target.q_value <= self.psm_fdr_threshold: + n_below += 1 + if target.q_value <= 0.05: + n_below_5 += 1 + if target.q_value <= 0.01: + n_below_1 += 1 + self.log(""%d spectrum matches accepted"" % (n_below,)) + if self.psm_fdr_threshold != 0.05: + self.log(""%d spectra matched passing 5%% FDR"" % n_below_5) + if self.psm_fdr_threshold != 0.01: + self.log(""%d spectra matched passing 1%% FDR"" % n_below_1) + return target_hits + + def localize_modifications(self, + solution_sets: List[SpectrumSolutionSet], + scan_loader: ProcessedRandomAccessScanSource, + database: DiskBackedStructureDatabaseBase): + pass + + def finalize_solutions(self, identifications: List[IdentifiedGlycopeptide]): + pass + + def handle_adducts(self, + peak_loader: ProcessedRandomAccessScanSource, + identifications: List[IdentifiedGlycopeptide], + chromatograms: ChromatogramFilter, + mass_shifts: Optional[List[MassShiftBase]]=None) -> List[IdentifiedGlycopeptide]: + if not mass_shifts: + return identifications + augmented_chromatograms = list(chromatograms) + augmented_chromatograms.extend(identifications) + augmented_chromatograms = ChromatogramFilter(augmented_chromatograms) + + msn_evaluation_kwargs = {""error_tolerance"": self.msn_mass_error_tolerance} + msn_evaluation_kwargs.update(self.extra_msn_evaluation_kwargs) + + scan_id_to_solution_set = {} + for ident in identifications: + for sset in ident.tandem_solutions: + scan_id_to_solution_set[sset.scan.scan_id] = sset + + adduct_finder = CoElutionAdductFinder( + scan_loader=peak_loader, + chromatograms=augmented_chromatograms, + msn_scoring_model=self.tandem_scoring_model, + msn_evaluation_args=msn_evaluation_kwargs, + fdr_estimator=self.fdr_estimator, + scan_id_to_solution_set=scan_id_to_solution_set, + threshold_fn=lambda x: x.q_value <= self.psm_fdr_threshold + ) + + for adduct in mass_shifts: + self.log(f""... Handling {adduct.name}"") + identifications = adduct_finder.handle_adduct( + identifications, adduct, self.mass_error_tolerance) + + return identifications + + def run(self): + peak_loader = self.make_peak_loader() + database = self.make_database() + extractor = self.make_chromatogram_extractor(peak_loader) + + self.log(""Loading MS/MS"") + + msms_scans = self.load_msms(peak_loader) + + # Traditional LC-MS/MS Database Search + searcher = self.make_search_engine(msms_scans, database, peak_loader) + target_decoy_set = self.do_search(searcher) + + self.target_hit_count = target_decoy_set.target_count() + self.decoy_hit_count = target_decoy_set.decoy_count() + + if target_decoy_set.target_count() == 0: + self.log(""No target matches were found."") + self.save_solutions([], [], extractor, database) + return [], [], TargetDecoySet([], []) + + target_hits = self.rank_target_hits(searcher, target_decoy_set) + + self.localize_modifications(target_hits, peak_loader, database) + + # Map MS/MS solutions to chromatograms. + self.log(""Building and Mapping Chromatograms"") + merged, orphans = self.map_chromatograms(searcher, extractor, target_hits) + + if not self.save_unidentified: + merged = [chroma for chroma in merged if chroma.composition is not None] + + # Score chromatograms, both matched and unmatched + self.log(""Scoring chromatograms"") + scored_merged = self.score_chromatograms(merged) + + if self.model_retention_time and len(scored_merged) > 0: + scored_merged, orphans = self.apply_retention_time_model( + scored_merged, orphans, database, peak_loader) + + gps, unassigned = self.assign_consensus(scored_merged, orphans) + + self.finalize_solutions(gps) + + self.log(""Saving solutions (%d identified glycopeptides)"" % (len(gps),)) + self.save_solutions(gps, unassigned, extractor, database) + return gps, unassigned, target_decoy_set + + def _get_glycan_compositions_from_database(self, database): + glycan_query = database.query( + serialize.GlycanCombination).join( + serialize.GlycanCombination.components).join( + serialize.GlycanComposition.structure_classes).group_by(serialize.GlycanCombination.id) + + glycan_compositions = [ + c.convert() for c in glycan_query.all()] + return glycan_compositions + + def _split_chromatograms_by_observation_priority(self, scored_chromatograms: List[TandemAnnotatedChromatogram], + minimum_ms1_score: float) -> Tuple[ + GlycoformAggregator, + List[GlycopeptideChromatogramProxy] + ]: + proxies = [ + GlycopeptideChromatogramProxy.from_chromatogram(chrom) + for chrom in scored_chromatograms + ] + + by_structure: DefaultDict[Any, List[GlycopeptideChromatogramProxy]] = defaultdict(list) + for proxy in proxies: + by_structure[proxy.structure].append(proxy) + + best_instances: List[GlycopeptideChromatogramProxy] = [] + secondary_observations: List[GlycopeptideChromatogramProxy] = [] + for key, group in by_structure.items(): + group.sort(key=lambda x: x.total_signal, reverse=True) + i = 0 + for i, member in enumerate(group): + if member.source.score > minimum_ms1_score: + best_instances.append(member) + secondary_observations.extend(group[i + 1:]) + break + else: + secondary_observations.append(member) + + glycoform_agg = GlycoformAggregator(best_instances) + return glycoform_agg, secondary_observations + + def _apply_revisions(self, + pipeline: GlycopeptideElutionTimeModelBuildingPipeline, + rt_model: GlycopeptideElutionTimeModelEnsemble, + revisions: List[GlycopeptideChromatogramProxy], + secondary_observations: List[GlycopeptideChromatogramProxy], + orphans: List[TandemSolutionsWithoutChromatogram], + updater: SpectrumMatchUpdater): + was_updated: List[GlycopeptideChromatogramProxy] = [] + to_affirm: List[GlycopeptideChromatogramProxy] = [] + for rev in revisions: + if rev.revised_from and rev.structure != rev.source.structure: + was_updated.append(rev) + else: + to_affirm.append(rev) + + self.log(""... Revising Secondary Occurrences"") + for rev in pipeline.revise_with(rt_model, secondary_observations): + if rev.revised_from and rev.structure != rev.source.structure: + was_updated.append(rev) + else: + to_affirm.append(rev) + + orphan_proxies = [] + for orphan in orphans: + gpsm = orphan.best_match_for(orphan.structure) + if not hasattr(gpsm.scan, ""scan_time""): + gpsm.scan = ScanInformation.from_scan( + updater.scan_loader.get_scan_by_id( + gpsm.scan.id)) + p = GlycopeptideChromatogramProxy.from_spectrum_match( + gpsm, orphan) + orphan_proxies.append(p) + orphan_proxies = list(GlycoformAggregator(orphan_proxies).tag()) + + self.log(""... Revising Orphans"") + orphan_proxies: List[GlycopeptideChromatogramProxy] = pipeline.revise_with( + rt_model, orphan_proxies) + + was_updated_orphans: List[GlycopeptideChromatogramProxy] = [] + to_affirm_orphans: List[GlycopeptideChromatogramProxy] = [] + for rev in orphan_proxies: + if rev.revised_from and rev.structure != rev.source.structure: + was_updated_orphans.append(rev) + else: + to_affirm_orphans.append(rev) + + self.log(""... Updating best match assignments"") + + revisions_accepted: List[RevisionSummary] = [] + # Use side-effects to update the source chromatogram + for revision in was_updated: + revisions_accepted.append(updater(revision)[1]) + + # Use side-effects to update the source not-chromatogram + for revised_orphan in was_updated_orphans: + revisions.append(updater(revised_orphan)[1]) + + self.log(""... Affirming best match assignments with RT model"") + affirmed_results: List[RevisionSummary] = [] + for af in to_affirm: + affirmed_results.append(updater.affirm_solution(af.source)[1]) + + accepted_revisions = sum(rev.accepted for rev in revisions_accepted) + affirmations_accepted = sum(rev.accepted for rev in affirmed_results) + self.log( + f""... Accepted {accepted_revisions}/{len(revisions_accepted)} "" + f""({accepted_revisions * 100.0 / (len(revisions_accepted) or 1):0.2f}%) revisions and "" + f""affirmed {affirmations_accepted}/{len(affirmed_results)} "" + f""({affirmations_accepted * 100.0 / (len(affirmed_results) or 1):0.2f}%) existing results"") + + self.analysis_metadata['retention_time_revisions'] = { + 'accepted_revisions': accepted_revisions, + 'revisions_proposed': len(revisions_accepted), + 'accepted_affirmations': affirmations_accepted, + 'affirmations_proposed': len(affirmed_results) + } + + + def apply_retention_time_model(self, scored_chromatograms: Sequence[ChromatogramSolution], + orphans: List[TandemSolutionsWithoutChromatogram], + database, scan_loader: ProcessedRandomAccessScanSource, + minimum_ms1_score: float=6.0) -> Tuple[ + List[ChromatogramSolution], + List[TandemSolutionsWithoutChromatogram] + ]: + + glycan_compositions = self._get_glycan_compositions_from_database(database) + + glycoform_agg, secondary_observations = self._split_chromatograms_by_observation_priority( + scored_chromatograms, minimum_ms1_score=minimum_ms1_score) + + if not glycoform_agg.has_relative_pairs(): + self.log(""... Insufficient identifications for Retention Time Modeling"") + return scored_chromatograms, orphans + + def threshold_fn(x): + return x.q_value <= self.psm_fdr_threshold + + msn_match_args = self.make_msn_evaluation_kwargs() + msn_match_args['error_tolerance'] = self.msn_mass_error_tolerance + + updater = SpectrumMatchUpdater( + scan_loader, + self.tandem_scoring_model, + spectrum_match_cls=SpectrumMatch, + id_maker=database.make_key_maker(), + threshold_fn=threshold_fn, + match_args=msn_match_args, + fdr_estimator=self.fdr_estimator) + + revision_validator = CompoundRevisionValidator([ + PeptideYUtilizationPreservingRevisionValidator( + spectrum_match_builder=updater), + OxoniumIonRequiringUtilizationRevisionValidator( + spectrum_match_builder=updater), + ]) + + self.log(""... Begin Retention Time Modeling"") + + pipeline = GlycopeptideElutionTimeModelBuildingPipeline( + glycoform_agg, valid_glycans=glycan_compositions, + revision_validator=revision_validator, + n_workers=self.n_processes) + + rt_model, revisions = pipeline.run() + if rt_model is None: + self.retention_time_model = None + return scored_chromatograms, orphans + + self.retention_time_model = rt_model + rt_model.drop_chromatograms() + updater.retention_time_model = rt_model + + self._apply_revisions( + pipeline, + rt_model, + revisions, + secondary_observations, + orphans, + updater) + + self.log(""... Re-running chromatogram merge"") + merger = AnnotatedChromatogramAggregator( + scored_chromatograms, + require_unmodified=False, + threshold_fn=threshold_fn) + + remerged_chromatograms = merger.run() + + out = [] + for chrom in remerged_chromatograms: + if isinstance(chrom, ChromatogramSolution): + chrom = chrom.chromatogram + out.append(chrom) + scored_chromatograms = self.score_chromatograms(out) + + return scored_chromatograms, orphans + + def _filter_out_poor_matches_before_saving(self, + identified_glycopeptides: Sequence[IdentifiedGlycopeptide]) -> Sequence[ + IdentifiedGlycopeptide + ]: + filt = QValueRetentionStrategy(max(0.75, self.psm_fdr_threshold * 10.)) + for idgp in identified_glycopeptides: + for gpsm_set in idgp.tandem_solutions: + gpsm_set.select_top(filt) + return identified_glycopeptides + + def _build_analysis_saved_parameters(self, identified_glycopeptides: Sequence[IdentifiedGlycopeptide], + unassigned_chromatograms: ChromatogramFilter, + chromatogram_extractor: ChromatogramExtractor, + database): + state = { + ""hypothesis_id"": self.hypothesis_id, + ""sample_run_id"": self.sample_run_id, + ""mass_error_tolerance"": self.mass_error_tolerance, + ""fragment_error_tolerance"": self.msn_mass_error_tolerance, + ""grouping_error_tolerance"": self.grouping_error_tolerance, + ""psm_fdr_threshold"": self.psm_fdr_threshold, + ""minimum_mass"": self.minimum_mass, + ""use_peptide_mass_filter"": self.use_peptide_mass_filter, + ""mass_shifts"": self.mass_shifts, + ""maximum_mass"": self.maximum_mass, + ""fdr_estimator"": self.fdr_estimator, + ""permute_decoy_glycans"": self.permute_decoy_glycans, + ""rare_signatures"": self.rare_signatures, + ""model_retention_time"": self.model_retention_time, + ""retention_time_model"": self.retention_time_model, + ""extra_evaluation_kwargs"": self.extra_msn_evaluation_kwargs, + } + state['additional_metadata'] = self.analysis_metadata + return state + + + def _add_files_to_analysis(self): + for path in self.file_manager.dir(): + if os.path.isdir(path): + continue + self.analysis.add_file(path, compress=True) + self.log(""Cleaning up temporary files"") + self.file_manager.clear() + + def save_solutions(self, identified_glycopeptides: List[IdentifiedGlycopeptide], + unassigned_chromatograms: ChromatogramFilter, + chromatogram_extractor: ChromatogramExtractor, + database): + if self.analysis_name is None: + return + self.log(""Saving Results To \""%s\"""" % (self.database_connection,)) + analysis_saver = AnalysisSerializer(self.database_connection, self.sample_run_id, self.analysis_name) + analysis_saver.set_peak_lookup_table(chromatogram_extractor.peak_mapping if chromatogram_extractor else {}) + analysis_saver.set_analysis_type(AnalysisTypeEnum.glycopeptide_lc_msms.name) + analysis_saver.set_parameters( + self._build_analysis_saved_parameters( + identified_glycopeptides, unassigned_chromatograms, + chromatogram_extractor, database)) + + analysis_saver.save_glycopeptide_identification_set( + self._filter_out_poor_matches_before_saving(identified_glycopeptides)) + if self.save_unidentified: + i = 0 + last = 0 + interval = 100 + n = len(unassigned_chromatograms) + for chroma in unassigned_chromatograms: + i += 1 + if (i - last > interval): + self.log(""Saving Unidentified Chromatogram %d/%d (%0.2f%%)"" % (i, n, (i * 100. / n))) + last = i + analysis_saver.save_unidentified_chromatogram_solution(chroma) + + analysis_saver.commit() + self.analysis = analysis_saver.analysis + self.analysis_id = analysis_saver.analysis_id + self._add_files_to_analysis() + analysis_saver.session.add(self.analysis) + analysis_saver.commit() + + +class MzMLGlycopeptideLCMSMSAnalyzer(GlycopeptideLCMSMSAnalyzer): + def __init__(self, database_connection, hypothesis_id, sample_path, output_path, + analysis_name=None, grouping_error_tolerance=1.5e-5, mass_error_tolerance=1e-5, + msn_mass_error_tolerance=2e-5, psm_fdr_threshold=0.05, peak_shape_scoring_model=None, + tandem_scoring_model=None, minimum_mass=1000., save_unidentified=False, + oxonium_threshold=0.05, scan_transformer=None, mass_shifts=None, + n_processes=5, spectrum_batch_size=1000, use_peptide_mass_filter=False, + maximum_mass=float('inf'), probing_range_for_missing_precursors=3, + trust_precursor_fits=True, permute_decoy_glycans=False, rare_signatures=False, + model_retention_time=True, evaluation_kwargs=None): + super(MzMLGlycopeptideLCMSMSAnalyzer, self).__init__( + database_connection, + hypothesis_id, -1, + analysis_name, grouping_error_tolerance, + mass_error_tolerance, msn_mass_error_tolerance, + psm_fdr_threshold, peak_shape_scoring_model, + tandem_scoring_model, minimum_mass, + save_unidentified, oxonium_threshold, + scan_transformer, mass_shifts, n_processes, spectrum_batch_size, + use_peptide_mass_filter, maximum_mass, + probing_range_for_missing_precursors=probing_range_for_missing_precursors, + trust_precursor_fits=trust_precursor_fits, permute_decoy_glycans=permute_decoy_glycans, + rare_signatures=rare_signatures, + model_retention_time=model_retention_time, + evaluation_kwargs=evaluation_kwargs) + self.sample_path = sample_path + self.output_path = output_path + + def make_peak_loader(self) -> ProcessedRandomAccessScanSource: + peak_loader = ProcessedMSFileLoader(self.sample_path) + if peak_loader.extended_index is None: + if not peak_loader.has_index_file(): + self.log(""Index file missing. Rebuilding."") + peak_loader.build_extended_index() + else: + peak_loader.read_index_file() + if peak_loader.extended_index is None or len(peak_loader.extended_index.msn_ids) < 1: + raise ValueError(""Sample Data Invalid: Could not validate MS/MS Index"") + return peak_loader + + def load_msms(self, peak_loader: ProcessedRandomAccessScanSource) -> List[ScanStub]: + prec_info = peak_loader.precursor_information() + msms_scans = [ScanStub(o, peak_loader) for o in prec_info if o.neutral_mass is not None] + return msms_scans + + def _build_analysis_saved_parameters(self, + identified_glycopeptides: List[IdentifiedGlycopeptide], + unassigned_chromatograms: ChromatogramFilter, + chromatogram_extractor: ChromatogramExtractor, + database): + state = { + ""hypothesis_id"": self.hypothesis_id, + ""sample_run_id"": self.sample_run_id, + ""sample_path"": os.path.abspath(self.sample_path), + ""sample_name"": chromatogram_extractor.peak_loader.sample_run.name, + ""sample_uuid"": chromatogram_extractor.peak_loader.sample_run.uuid, + ""mass_error_tolerance"": self.mass_error_tolerance, + ""fragment_error_tolerance"": self.msn_mass_error_tolerance, + ""grouping_error_tolerance"": self.grouping_error_tolerance, + ""psm_fdr_threshold"": self.psm_fdr_threshold, + ""minimum_mass"": self.minimum_mass, + ""maximum_mass"": self.maximum_mass, + ""mass_shifts"": self.mass_shifts, + ""use_peptide_mass_filter"": self.use_peptide_mass_filter, + ""database"": str(self.database_connection), + ""search_strategy"": GlycopeptideSearchStrategy.target_internal_decoy_competition.value, + ""trust_precursor_fits"": self.trust_precursor_fits, + ""probing_range_for_missing_precursors"": self.probing_range_for_missing_precursors, + ""scoring_model"": self.peak_shape_scoring_model, + ""fdr_estimator"": self.fdr_estimator, + ""permute_decoy_glycans"": self.permute_decoy_glycans, + ""tandem_scoring_model"": self.tandem_scoring_model, + ""rare_signatures"": self.rare_signatures, + ""model_retention_time"": self.model_retention_time, + ""retention_time_model"": self.retention_time_model, + ""extra_evaluation_kwargs"": self.extra_msn_evaluation_kwargs, + } + state['additional_metadata'] = self.analysis_metadata + return state + + def make_analysis_serializer(self, output_path, analysis_name: str, + sample_run, + identified_glycopeptides: List[IdentifiedGlycopeptide], + unassigned_chromatograms: ChromatogramFilter, + database, + chromatogram_extractor: ChromatogramExtractor): + return GlycopeptideMSMSAnalysisSerializer( + output_path, analysis_name, sample_run, identified_glycopeptides, + unassigned_chromatograms, database, chromatogram_extractor) + + def save_solutions(self, identified_glycopeptides: List[IdentifiedGlycopeptide], + unassigned_chromatograms: ChromatogramFilter, + chromatogram_extractor: ChromatogramExtractor, + database): + if self.analysis_name is None: + return + self.log(""Saving Results To \""%s\"""" % (self.output_path,)) + exporter = self.make_analysis_serializer( + self.output_path, + self.analysis_name, + chromatogram_extractor.peak_loader.sample_run, + self._filter_out_poor_matches_before_saving(identified_glycopeptides), + unassigned_chromatograms, + database, + chromatogram_extractor) + + exporter.run() + + exporter.set_parameters( + self._build_analysis_saved_parameters( + identified_glycopeptides, unassigned_chromatograms, + chromatogram_extractor, database)) + + self.analysis = exporter.analysis + self.analysis_id = exporter.analysis.id + self._add_files_to_analysis() + session = object_session(self.analysis) + session.add(self.analysis) + session.commit() + self.log(""Final Results Written To %s"" % (self.output_path, )) + + +class MzMLComparisonGlycopeptideLCMSMSAnalyzer(MzMLGlycopeptideLCMSMSAnalyzer): + def __init__(self, database_connection, decoy_database_connection, hypothesis_id, + sample_path, output_path, + analysis_name=None, grouping_error_tolerance=1.5e-5, mass_error_tolerance=1e-5, + msn_mass_error_tolerance=2e-5, psm_fdr_threshold=0.05, peak_shape_scoring_model=None, + tandem_scoring_model=None, minimum_mass=1000., save_unidentified=False, + oxonium_threshold=0.05, scan_transformer=None, mass_shifts=None, + n_processes=5, spectrum_batch_size=1000, use_peptide_mass_filter=False, + maximum_mass=float('inf'), use_decoy_correction_threshold=None, + probing_range_for_missing_precursors=3, trust_precursor_fits=True, + permute_decoy_glycans=False, rare_signatures=False, + model_retention_time=True, evaluation_kwargs=None): + if use_decoy_correction_threshold is None: + use_decoy_correction_threshold = 0.33 + if tandem_scoring_model == CoverageWeightedBinomialScorer: + tandem_scoring_model = CoverageWeightedBinomialModelTree + super(MzMLComparisonGlycopeptideLCMSMSAnalyzer, self).__init__( + database_connection, hypothesis_id, sample_path, output_path, + analysis_name, grouping_error_tolerance, mass_error_tolerance, + msn_mass_error_tolerance, psm_fdr_threshold, peak_shape_scoring_model, + tandem_scoring_model, minimum_mass, save_unidentified, + oxonium_threshold, scan_transformer, mass_shifts, + n_processes, spectrum_batch_size, use_peptide_mass_filter, + maximum_mass, probing_range_for_missing_precursors, + trust_precursor_fits, permute_decoy_glycans=permute_decoy_glycans, + rare_signatures=rare_signatures, model_retention_time=model_retention_time, + evaluation_kwargs=evaluation_kwargs) + self.decoy_database_connection = decoy_database_connection + self.use_decoy_correction_threshold = use_decoy_correction_threshold + + def make_search_engine(self, msms_scans: List[ScanStub], + database, + peak_loader: ProcessedRandomAccessScanSource): + searcher = ExclusiveGlycopeptideDatabaseSearchComparer( + [scan for scan in msms_scans + if scan.precursor_information.neutral_mass < self.maximum_mass], + self.tandem_scoring_model, database, self.make_decoy_database(), + peak_loader.convert_scan_id_to_retention_time, + minimum_oxonium_ratio=self.minimum_oxonium_ratio, + scan_transformer=self.scan_transformer, + n_processes=self.n_processes, + mass_shifts=self.mass_shifts, + use_peptide_mass_filter=self.use_peptide_mass_filter, + file_manager=self.file_manager, + probing_range_for_missing_precursors=self.probing_range_for_missing_precursors, + trust_precursor_fits=self.trust_precursor_fits, + permute_decoy_glycans=self.permute_decoy_glycans) + return searcher + + def make_decoy_database(self): + database = GlycopeptideDiskBackedStructureDatabase( + self.decoy_database_connection, self.hypothesis_id) + return database + + def _build_analysis_saved_parameters(self, identified_glycopeptides, + unassigned_chromatograms, + chromatogram_extractor, + database): + result = super(MzMLComparisonGlycopeptideLCMSMSAnalyzer, self)._build_analysis_saved_parameters( + identified_glycopeptides, unassigned_chromatograms, + chromatogram_extractor, database) + target_database = database + decoy_database = self.make_decoy_database() + result.update({ + ""target_database"": str(self.database_connection), + ""target_database_size"": len(target_database), + ""decoy_database_size"": len(decoy_database), + ""decoy_database"": str(self.decoy_database_connection), + ""decoy_correction_threshold"": self.use_decoy_correction_threshold, + ""search_strategy"": GlycopeptideSearchStrategy.target_decoy_competition.value + }) + return result + + def estimate_fdr(self, searcher: SearchEngineBase, target_decoy_set: TargetDecoySet): + if target_decoy_set.decoy_count() / float( + target_decoy_set.target_count()) < self.use_decoy_correction_threshold: + targets_per_decoy = 0.5 + decoy_correction = 1 + else: + targets_per_decoy = 1.0 + decoy_correction = 0 + return searcher.estimate_fdr( + *target_decoy_set, decoy_correction=decoy_correction, + target_weight=targets_per_decoy) + + +class MultipartGlycopeptideLCMSMSAnalyzer(MzMLGlycopeptideLCMSMSAnalyzer): + def __init__(self, database_connection, decoy_database_connection, target_hypothesis_id, + decoy_hypothesis_id, sample_path, output_path, analysis_name=None, + grouping_error_tolerance=1.5e-5, mass_error_tolerance=1e-5, + msn_mass_error_tolerance=2e-5, psm_fdr_threshold=0.05, + peak_shape_scoring_model=None, tandem_scoring_model=LogIntensityScorer, + minimum_mass=1000., save_unidentified=False, + glycan_score_threshold=1.0, mass_shifts=None, + n_processes=5, spectrum_batch_size=100, + maximum_mass=float('inf'), probing_range_for_missing_precursors=3, + trust_precursor_fits=True, use_memory_database=True, + fdr_estimation_strategy=None, glycosylation_site_models_path=None, + permute_decoy_glycans=False, fragile_fucose=False, rare_signatures=False, + extended_glycan_search=True, model_retention_time=True, + evaluation_kwargs=None, + oxonium_threshold=0.05, + peptide_masses_per_scan=60): + if tandem_scoring_model == CoverageWeightedBinomialScorer: + tandem_scoring_model = CoverageWeightedBinomialModelTree + if fdr_estimation_strategy is None: + fdr_estimation_strategy = GlycopeptideFDREstimationStrategy.multipart_gamma_gaussian_mixture + super(MultipartGlycopeptideLCMSMSAnalyzer, self).__init__( + database_connection, target_hypothesis_id, sample_path, output_path, + analysis_name, grouping_error_tolerance, mass_error_tolerance, + msn_mass_error_tolerance, psm_fdr_threshold, peak_shape_scoring_model, + tandem_scoring_model, minimum_mass, save_unidentified, + oxonium_threshold, None, mass_shifts, + n_processes, + spectrum_batch_size=spectrum_batch_size, + use_peptide_mass_filter=True, + maximum_mass=maximum_mass, + probing_range_for_missing_precursors=probing_range_for_missing_precursors, + trust_precursor_fits=trust_precursor_fits, + # The multipart scoring algorithm automatically implies permute_decoy_glycan + # fragment masses. + permute_decoy_glycans=True, + model_retention_time=model_retention_time, + evaluation_kwargs=evaluation_kwargs) + + self.peptide_masses_per_scan = peptide_masses_per_scan + self.fragile_fucose = fragile_fucose + self.rare_signatures = rare_signatures + self.extended_glycan_search = extended_glycan_search + self.glycan_score_threshold = glycan_score_threshold + self.decoy_database_connection = decoy_database_connection + self.use_memory_database = use_memory_database + self.decoy_hypothesis_id = decoy_hypothesis_id + self.fdr_estimation_strategy = fdr_estimation_strategy + self.glycosylation_site_models_path = glycosylation_site_models_path + self.fdr_estimator = None + self.retention_time_model = None + self.precursor_mass_error_distribution = None + self.localization_model = None + + @property + def target_hypothesis_id(self): + return self.hypothesis_id + + @target_hypothesis_id.setter + def target_hypothesis_id(self, value): + self.hypothesis_id = value + + def make_database(self): + if self.use_memory_database: + database = MultipartGlycopeptideIdentifier.build_default_memory_backed_db_wrapper( + self.database_connection, hypothesis_id=self.target_hypothesis_id) + else: + database = MultipartGlycopeptideIdentifier.build_default_disk_backed_db_wrapper( + self.database_connection, hypothesis_id=self.target_hypothesis_id) + return database + + def make_decoy_database(self): + if self.use_memory_database: + database = MultipartGlycopeptideIdentifier.build_default_memory_backed_db_wrapper( + self.decoy_database_connection, hypothesis_id=self.decoy_hypothesis_id) + else: + database = MultipartGlycopeptideIdentifier.build_default_disk_backed_db_wrapper( + self.decoy_database_connection, hypothesis_id=self.decoy_hypothesis_id) + return database + + def make_msn_evaluation_kwargs(self): + kwargs = { + ""fragile_fucose"": self.fragile_fucose, + ""rare_signatures"": self.rare_signatures, + ""extended_glycan_search"": self.extended_glycan_search, + } + kwargs.update(self.extra_msn_evaluation_kwargs) + return kwargs + + def make_search_engine(self, msms_scans: List[ScanStub], + database, + peak_loader: ProcessedRandomAccessScanSource): + cache_seeds = self.prepare_cache_seeds( + serialize.DatabaseBoundOperation(self.database_connection)) + searcher = MultipartGlycopeptideIdentifier( + [scan for scan in msms_scans + if scan.precursor_information.neutral_mass < self.maximum_mass], + self.tandem_scoring_model, database, self.make_decoy_database(), + peak_loader, + mass_shifts=self.mass_shifts, + glycan_score_threshold=self.glycan_score_threshold, + n_processes=self.n_processes, + file_manager=self.file_manager, + probing_range_for_missing_precursors=self.probing_range_for_missing_precursors, + trust_precursor_fits=self.trust_precursor_fits, + fdr_estimation_strategy=self.fdr_estimation_strategy, + glycosylation_site_models_path=self.glycosylation_site_models_path, + cache_seeds=cache_seeds, evaluation_kwargs=self.make_msn_evaluation_kwargs(), + oxonium_threshold=self.minimum_oxonium_ratio, + peptide_masses_per_scan=self.peptide_masses_per_scan) + return searcher + + def estimate_fdr(self, searcher: SearchEngineBase, target_decoy_set: SolutionSetGrouper): + return searcher.estimate_fdr(target_decoy_set) + + def localize_modifications(self, + solution_sets: List[SpectrumSolutionSet], + scan_loader: ProcessedRandomAccessScanSource, + database: DiskBackedStructureDatabaseBase): + + hyp_parameters: Dict[str, Any] = database.hypothesis.parameters + rules_by_name = {} + table = None + + for rule in hyp_parameters.get('constant_modifications', []): + if isinstance(rule, str): + rule = rule_string_to_specialized_rule(rule) + rules_by_name[rule.name] = rule + for rule in hyp_parameters.get('variable_modifications', []): + if table is not None: + rule = table[rule] + rules_by_name[rule.name] = rule + + self.log(""Begin Modifications Localization"") + task = ScanLoadingModificationLocalizationSearcher( + scan_loader, + threshold_fn=lambda x: x.q_value <= self.psm_fdr_threshold, + error_tolerance=self.msn_mass_error_tolerance, + restricted_modifications=rules_by_name + ) + + solution_bins: List[EvaluatedSolutionBins] = [] + for i, sset in enumerate(solution_sets): + if i % 1000 == 0 and i: + self.log(f""... Processed {i} solution sets"") + solution_bin_set = task.process_solution_set(sset) + solution_bins.append(solution_bin_set) + + training_examples = task.get_training_instances(solution_bins) + self.log(f""{len(training_examples)} training examples for localization"") + + ptm_prophet = task.train_ptm_prophet(training_examples) + self.localization_model = task + + self.log(""Scoring Site Localizations"") + task.select_top_isoforms(solution_bins, ptm_prophet) + + def apply_retention_time_model(self, scored_chromatograms: List[ChromatogramSolution], + orphans: List[TandemSolutionsWithoutChromatogram], + database, + scan_loader: ProcessedRandomAccessScanSource, + minimum_ms1_score=6.0): + glycan_compositions = self._get_glycan_compositions_from_database( + database) + + glycoform_agg, secondary_observations = self._split_chromatograms_by_observation_priority( + scored_chromatograms, minimum_ms1_score=minimum_ms1_score) + + if not glycoform_agg.has_relative_pairs(): + self.log(""... Insufficient identifications for Retention Time Modeling"") + return scored_chromatograms, orphans + + def threshold_fn(x): + return x.q_value <= self.psm_fdr_threshold + + msn_match_args = self.make_msn_evaluation_kwargs() + msn_match_args['error_tolerance'] = self.msn_mass_error_tolerance + + updater = SpectrumMatchUpdater( + scan_loader, + self.tandem_scoring_model, + spectrum_match_cls=MultiScoreSpectrumMatch, + id_maker=IdKeyMaker(glycan_compositions), + threshold_fn=threshold_fn, + match_args=msn_match_args, + fdr_estimator=self.fdr_estimator) + + revision_validator = CompoundRevisionValidator([ + PeptideYUtilizationPreservingRevisionValidator(spectrum_match_builder=updater), + OxoniumIonRequiringUtilizationRevisionValidator(spectrum_match_builder=updater), + ]) + + self.log(""Begin Retention Time Modeling"") + + pipeline = GlycopeptideElutionTimeModelBuildingPipeline( + glycoform_agg, valid_glycans=glycan_compositions, + revision_validator=revision_validator, + n_workers=self.n_processes) + + rt_model, revisions = pipeline.run() + if rt_model is None: + self.retention_time_model = None + return scored_chromatograms, orphans + + self.retention_time_model = rt_model + rt_model.drop_chromatograms() + updater.retention_time_model = rt_model + + self._apply_revisions( + pipeline, + rt_model, + revisions, + secondary_observations, + orphans, + updater) + + self.log(""... Re-running chromatogram merge"") + merger = AnnotatedChromatogramAggregator( + scored_chromatograms, + require_unmodified=False, + threshold_fn=threshold_fn) + + remerged_chromatograms = merger.run() + + out = [] + for chrom in remerged_chromatograms: + if isinstance(chrom, ChromatogramSolution): + chrom = chrom.chromatogram + out.append(chrom) + scored_chromatograms = self.score_chromatograms(out) + + return scored_chromatograms, orphans + + def finalize_solutions(self, identifications: List[identified_glycopeptide.IdentifiedGlycopeptide]): + self.log(""Back-filling localization information"") + k = 0 + for idgp in identifications: + if not idgp.localizations: + for sset in idgp.tandem_solutions: + k += 1 + bins = self.localization_model.process_solution_set(sset) + self.localization_model.select_top_isoforms([bins]) + if k: + self.log(f'Back-filled {k} spectra') + + def rank_target_hits(self, searcher: SearchEngineBase, target_decoy_set: TargetDecoySet): + '''Estimate the FDR using the searcher's method, and + count the number of acceptable target matches. Return + the full set of target matches for downstream use. + + Parameters + ---------- + searcher: object + The search algorithm implementation, providing an `estimate_fdr` method + target_decoy_set: TargetDecoySet + + Returns + ------- + Iterable of SpectrumMatch-like objects + ''' + self.log(""Estimating FDR"") + _groups, fdr_estimator = self.estimate_fdr(searcher, target_decoy_set) + self.fdr_estimator = fdr_estimator + if self.fdr_estimator is not None: + self.fdr_estimator.pack() + target_hits = target_decoy_set.target_matches + n_below = 0 + n_below_1 = 0 + n_below_5 = 0 + for target in target_hits: + if target.q_value <= self.psm_fdr_threshold: + n_below += 1 + if target.q_value <= 0.05: + n_below_5 += 1 + if target.q_value <= 0.01: + n_below_1 += 1 + self.log(""%d spectrum matches accepted"" % (n_below,)) + if self.psm_fdr_threshold != 0.05: + self.log(""%d spectra matched passing 5%% FDR"" % n_below_5) + if self.psm_fdr_threshold != 0.01: + self.log(""%d spectra matched passing 1%% FDR"" % n_below_1) + return target_hits + + def make_analysis_serializer(self, output_path, analysis_name, sample_run, identified_glycopeptides, + unassigned_chromatograms, database, chromatogram_extractor): + return DynamicGlycopeptideMSMSAnalysisSerializer( + output_path, analysis_name, sample_run, + identified_glycopeptides, + unassigned_chromatograms, database, chromatogram_extractor) + + def map_chromatograms(self, searcher: SearchEngineBase, + extractor: ChromatogramExtractor, + target_hits: List[SpectrumSolutionSet], + revision_validator_type: Optional[Type[MS2RevisionValidator]] = None) -> Tuple[ + ChromatogramFilter, TandemSolutionsWithoutChromatogram]: + if revision_validator_type is None: + revision_validator_type = SignalUtilizationMS2RevisionValidator + return super().map_chromatograms( + searcher, + extractor, + target_hits, + revision_validator_type=revision_validator_type) + + def _build_analysis_saved_parameters(self, identified_glycopeptides, unassigned_chromatograms, + chromatogram_extractor, database): + database = GlycopeptideDiskBackedStructureDatabase(self.database_connection) + result = super(MultipartGlycopeptideLCMSMSAnalyzer, self)._build_analysis_saved_parameters( + identified_glycopeptides, unassigned_chromatograms, + chromatogram_extractor, database) + result.update({ + ""target_database"": str(self.database_connection), + ""decoy_database"": str(self.decoy_database_connection), + ""search_strategy"": GlycopeptideSearchStrategy.multipart_target_decoy_competition.value, + ""fdr_estimation_strategy"": self.fdr_estimation_strategy, + ""fdr_estimator"": self.fdr_estimator, + ""fragile_fucose"": self.fragile_fucose, + ""rare_signatures"": self.rare_signatures, + ""extended_glycan_search"": self.extended_glycan_search, + ""glycosylation_site_models_path"": self.glycosylation_site_models_path, + ""retention_time_model"": self.retention_time_model, + ""localization_model"": (self.localization_model.simplify() + if self.localization_model is not None else None), + ""peptide_masses_per_scan"": self.peptide_masses_per_scan, + }) + return result +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/version.py",".py","18","1","version = ""0.4.25""","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/__init__.py",".py","2035","65","# Copyright (c) 2018, Joshua Klein +# +# 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. + +import dill as _dill +import warnings +from sqlalchemy import exc as sa_exc + +try: + warnings.simplefilter(""ignore"", category=sa_exc.SAWarning) + warnings.filterwarnings(action=""ignore"", module=""SPARQLWrapper"") + warnings.filterwarnings( + action=""ignore"", + category=DeprecationWarning, + module=""pysqlite2.dbapi2"") +finally: + pass + +from glycresoft import serialize + +from glycresoft.piped_deconvolve import ( + ScanGenerator +) + +from glycresoft.chromatogram_tree import ( + MassShift, CompoundMassShift, Chromatogram, ChromatogramTreeList, + ChromatogramTreeNode, ChromatogramInterface, ChromatogramFilter, + mass_shift) + + +from glycresoft.trace import ( + ChromatogramExtractor, ChromatogramProcessor) + +from glycresoft import database +from glycresoft.database import ( + NeutralMassDatabase, GlycopeptideDiskBackedStructureDatabase, + GlycanCompositionDiskBackedStructureDatabase) + +from glycresoft import profiler + +from glycresoft.config.config_file import get_configuration + +get_configuration() + +__all__ = [ + ""ScanGenerator"", + ""MassShift"", ""CompoundMassShift"", ""Chromatogram"", + ""ChromatogramTreeNode"", ""ChromatogramTreeList"", + ""ChromatogramInterface"", ""ChromatogramFilter"", + ""mass_shift"", ""ChromatogramExtractor"", ""ChromatogramProcessor"", + ""NeutralMassDatabase"", ""GlycopeptideDiskBackedStructureDatabase"", + ""GlycanCompositionDiskBackedStructureDatabase"", ""serialize"", + ""profiler"", ""plotting"" +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/piped_deconvolve.py",".py","392","19","'''Implements a multiprocessing deconvolution algorithm +''' + +from ms_deisotope.tools.deisotoper.scan_generator import ScanGenerator as _ScanGenerator + +from glycresoft.task import ( + TaskBase, +) + +from glycresoft.config import get_configuration + + +user_config = get_configuration() +huge_tree = user_config.get(""xml_huge_tree"", False) + + +class ScanGenerator(TaskBase, _ScanGenerator): + pass +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/symbolic_expression.py",".py","30312","1145","''' +Provides a simple symbolic algebra engine for expressing relationships between +symbols representing counts in terms of the arithmetic operators addition, +subtraction, multiplication, and division, and conditional operators greater +than, less than equality, as well as compound & and | relationships. +''' +import re + +from numbers import Number + +from six import string_types as basestring, PY3 + +from glypy.composition import composition_transform +from glypy.structure import glycan_composition + + +_FMR = glycan_composition.FrozenMonosaccharideResidue +_MR = glycan_composition.MonosaccharideResidue +_SR = glycan_composition.SubstituentResidue +_MC = glycan_composition.MolecularComposition + +_is_numeric = re.compile(r""^\d+(?:\.\d+)?$"") + +def is_numeric(x): + return _is_numeric.match(x) is not None + +def numerical(x): + try: + return int(x) + except (TypeError, ValueError): + try: + return float(x) + except (TypeError, ValueError): + pass + raise ValueError(""Cannot coerce {} to numerical type"".format(x)) + + +def ensuretext(x): + if isinstance(x, str): + return x + elif PY3: + try: + return x.decode(""utf8"") + except AttributeError: + return str(x) + else: + return str(x) + + +class ExpressionBase(object): + @staticmethod + def _coerce(v): + if isinstance(v, ExpressionBase): + return v + elif isinstance(v, basestring): + return SymbolNode.parse(ensuretext(v)) + elif isinstance(v, Number): + return ValueNode(v) + + def _as_compound(self, op, other): + return ExpressionNode(self, op, self._coerce(other)) + + def __add__(self, other): + return self._as_compound(Operator.get(""+""), other) + + def __sub__(self, other): + return self._as_compound(Operator.get(""-""), other) + + def __mul__(self, other): + return self._as_compound(Operator.get(""*""), other) + + def __div__(self, other): + return self._as_compound(Operator.get(""/""), other) + + def __gt__(self, other): + return self._as_compound(Operator.get("">""), other) + + def __ge__(self, other): + return self._as_compound(Operator.get("">=""), other) + + def __lt__(self, other): + return self._as_compound(Operator.get(""<""), other) + + def __le__(self, other): + return self._as_compound(Operator.get(""<=""), other) + + def __eq__(self, other): + return self._as_compound(Operator.get(""==""), other) + + def __ne__(self, other): + return self._as_compound(Operator.get(""!=""), other) + + def __and__(self, other): + return self._as_compound(Operator.get(""and""), other) + + def __or__(self, other): + return self._as_compound(Operator.get(""or""), other) + + def __call__(self, other): + return self._as_compound(Operator.get(""call""), other) + + def get_symbols(self): + return [] + + def evaluate(self, context): + raise NotImplementedError() + + def itersymbols(self): + for i in []: + yield i + + +class ConstraintExpression(ExpressionBase): + """""" + A wrapper around an ExpressionNode that is callable + to test for satisfaction. + + Attributes + ---------- + expression : ExpressionNode + The symbolic expression that a composition must + satisfy in order to be retained. + """""" + @classmethod + def parse(cls, string): + return ConstraintExpression(ExpressionNode.parse(string)) + + @classmethod + def from_list(cls, sym_list): + return cls.parse(' '.join(sym_list)) + + def __init__(self, expression): + self.expression = expression + + def __repr__(self): + return ""{}"".format(self.expression) + + def evaluate(self, context): + """""" + Test for satisfaction of :attr:`expression` + + Parameters + ---------- + context : Solution + Context to evaluate :attr:`expression` in + + Returns + ------- + bool + """""" + return context[self.expression] + + def __call__(self, context): + return self.evaluate(context) + + def __and__(self, other): + """""" + Construct an :class:`AndCompoundConstraint` from + `self` and `other` + + Parameters + ---------- + other : ConstraintExpression + + Returns + ------- + AndCompoundConstraint + """""" + return AndCompoundConstraint(self, other) + + def __or__(self, other): + """""" + Construct an :class:`OrCompoundConstraint` from + `self` and `other` + + Parameters + ---------- + other : ConstraintExpression + + Returns + ------- + OrCompoundConstraint + """""" + return OrCompoundConstraint(self, other) + + def __eq__(self, other): + return self.expression == other.expression + + def __ne__(self, other): + return self.expression != other.expression + + def get_symbols(self): + return self.expression.get_symbols() + + +class SymbolNode(ExpressionBase): + """""" + A node representing a single symbol or variable with a scalar multiplication + coefficient. When evaluated in the context of a :class:`Solution`, it's value + will be substituted for the value hashed there. + + A SymbolNode is equal to its symbol string and hashes the same way. + + Attributes + ---------- + coefficient : int + Multiplicative coefficient to scale the value by + symbol : str + A name + """""" + @classmethod + def parse(cls, string): + coef = [] + i = 0 + while i < len(string) and (string[i].isdigit() or string[i] in '-+'): + coef.append(string[i]) + i += 1 + coef_val = int(''.join(coef) or 1) + residue_sym = string[i:] + if residue_sym == """": + residue_sym = None + elif string[i] == ""("" and string[-1] == "")"": + residue_sym = residue_sym[1:-1] + return cls(residue_sym, coef_val) + + def __init__(self, symbol, coefficient=1): + self.symbol = symbol + self.coefficient = coefficient + + def __hash__(self): + return hash(self.symbol) + + def __eq__(self, other): + if isinstance(other, basestring): + return self.symbol == ensuretext(other) + else: + return self.symbol == other.symbol and self.coefficient == other.coefficient + + def __ne__(self, other): + return not self == other + + def evaluate(self, context): + return context[self] * self.coefficient + + def __repr__(self): + if self.symbol is not None: + if self.coefficient != 1: + return ""{} * ({})"".format(self.coefficient, self.symbol) + else: + return ""({})"".format(self.symbol) + else: + return ""{}"".format(self.coefficient) + + def get_symbols(self): + return [self.symbol] + + def itersymbols(self): + yield self + + +class ValueNode(ExpressionBase): + """""" + Represent a single numeric value in an ExpressionNode + + Attributes + ---------- + value : int + The value of this node + """""" + coefficient = 1 + + @classmethod + def parse(cls, string): + try: + value = int(string.replace("" "", """")) + except ValueError: + value = float(string.replace("" "", """")) + return cls(value) + + def __init__(self, value): + self.value = value + + def __hash__(self): + return hash(self.value) + + def __eq__(self, other): + if isinstance(other, basestring): + return str(self.value) == ensuretext(other) + else: + return self.value == other.value + + def evaluate(self, context): + return self.value + + def __ne__(self, other): + return not self == other + + def __repr__(self): + return str(self.value) + + +def typify(node): + """"""Convert the input into the appropriate + type of ExpressionBase-derived Node. Will + apply pattern matching to determine if a + passed string looks like a numerical constant + or if the input is a numerical constant, return + the appropriate node type. + + Parameters + ---------- + node : object + The object to be converted. + + Returns + ------- + ExpressionBase + """""" + if isinstance(node, basestring): + if re.match(r""^(\d+(.\d+)?)$"", ensuretext(node).strip()): + return ValueNode.parse(node) + else: + return SymbolNode.parse(node) + elif isinstance(node, Number): + return ValueNode(node) + else: + return node + + +def parse_expression(string: str): + """"""Parses a str argument into a :class:`ExpressionNode` instance + containing arbitrarily complex expressions. + + Parameters + ---------- + string : str + The text to be parsed + + Returns + ------- + ExpressionNode + + Raises + ------ + SyntaxError + If there are unresolved parentheses leftover after resolving the parse + stack + """""" + i = 0 + size = len(string) + paren_level = 0 + current_symbol = '' + expression_stack = [] + resolver_stack = [] + current_function = '' + function_stack = [] + + while i < size: + c = string[i] + if c == "" "": + if current_symbol != """": + if current_symbol.endswith("","") and current_symbol != ',': + expression_stack.append(current_symbol[:-1]) + expression_stack.append("","") + else: + expression_stack.append(current_symbol) + current_symbol = """" + elif c == ""("": + paren_level += 1 + if current_symbol != """": + if current_function != '': + function_stack.append(current_function) + current_function = current_symbol + else: + if current_function != '': + function_stack.append(current_function) + current_function = '' + current_symbol = """" + resolver_stack.append(expression_stack) + expression_stack = [] + elif c == "")"": + paren_level -= 1 + if current_symbol != """": + if current_symbol.endswith("",""): + current_symbol = current_symbol[:-1] + expression_stack.append(current_symbol) + current_symbol = """" + term = collapse_expression_sequence(expression_stack) + expression_stack = resolver_stack.pop() + if current_function != """": + if is_numeric(current_function): + coef = numerical(current_function) + term = EnclosedExpression(term, coef) + else: + fn = SymbolNode(current_function) + term = FunctionCallNode(fn, Operator.get(""call""), term) + if function_stack: + current_function = function_stack.pop() + else: + current_function = '' + else: + term = EnclosedExpression(term) + if function_stack: + current_function = function_stack.pop() + else: + current_function = '' + expression_stack.append(term) + else: + current_symbol += c + i += 1 + + if current_symbol != """": + expression_stack.append(current_symbol) + + if len(resolver_stack) > 0: + raise ValueError(""Unpaired parenthesis"") + return collapse_expression_sequence(expression_stack) + + +def is_operator(symbol): + return symbol in operator_map + + +def collapse_expression_sequence(expression_sequence): + stack = [] + i = 0 + size = len(expression_sequence) + if size == 1: + return typify(expression_sequence[0]) + + while i < size: + next_term = expression_sequence[i] + stack.append(next_term) + if len(stack) == 3: + node = ExpressionNode(*stack) # pylint: disable=no-value-for-parameter + if hasattr(node.left, 'op'): + if node.left.op.precedence < node.op.precedence: + node = ExpressionNode( + left=node.left.left, op=node.left.op, right=ExpressionNode( + left=node.left.right, op=node.op, right=node.right)) + stack = [node] + i += 1 + if len(stack) != 1: + raise ValueError(""Incomplete Expression: %s"" % + ' '.join(expression_sequence)) + return stack[0] + + +class ExpressionNode(ExpressionBase): + """""" + A compound node representing two terms joined by a binary operator + + Attributes + ---------- + left : ExpressionBase + The term to the left of the binary operator + op : Operator or str + The binary operator being applied. If passed as a str + the Operator type will be looked up using the registered + operator map. + right : ExpressionBase + The term to the right of the binary operator + """""" + + #: Expressions have an implicit constant multiplier of 1 + coefficient = 1 + + #: Parses a string-like argument into an ExpressionNode instance + parse = staticmethod(parse_expression) + + def __init__(self, left, op, right): + self.left = typify(left) + try: + self.op = operator_map[op] + except KeyError: + if isinstance(op, Operator): + self.op = op + else: + raise TypeError(""Could not determine operator type from %r"" % op) + self.right = typify(right) + + def __repr__(self): + return ""{} {} {}"".format(self.left, self.op, self.right) + + def evaluate(self, context): + """""" + Execute :attr:`op` on :attr:`left` and :attr:`right` in `context` + + Parameters + ---------- + context : Solution + + Returns + ------- + bool or int + """""" + if not isinstance(context, SymbolContext): + context = SymbolContext(context) + try: + return self.op(self.left, self.right, context) + except KeyError: + if isinstance(self.left, ValueNode) and self.left.value == 0: + return True + elif isinstance(self.right, ValueNode) and self.right.value == 0: + return True + else: + return False + + def get_symbols(self): + return self.left.get_symbols() + self.right.get_symbols() + + def itersymbols(self): + for symbol in self.left.itersymbols(): + yield symbol + for symbol in self.right.itersymbols(): + yield symbol + + +class EnclosedExpression(ExpressionBase): + def __init__(self, expr, coefficient=1): + self.expr = expr + self.coefficient = coefficient + self._simplify() + + def _simplify(self): + while self.coefficient == 1: + if isinstance(self.expr, EnclosedExpression): + inner = self.expr + self.expr = inner.expr + self.coefficient = inner.coefficient + return True + else: + break + return False + + def evaluate(self, context): + return self.expr.evaluate(context) * self.coefficient + + def get_symbols(self): + return self.expr.get_symbols() + + def __repr__(self): + if self.coefficient != 1: + return ""%r(%r)"" % (self.coefficient, self.expr) + return ""(%r)"" % (self.expr, ) + + def itersymbols(self): + return self.expr.itersymbols() + + +class FunctionCallNode(ExpressionNode): + def __repr__(self): + return ""{}({})"".format(re.sub(r""\)|\("", '', str(self.left)), self.right) + + +class SymbolSpace(object): + """"""Represent an abstract collection of symbols. Provides a + notion of definedness for Symbols, without associating an + explicit value for them. + + Attributes + ---------- + context : dict + Internal storage of defined symbols + """""" + def __init__(self, context=None): + if context is None: + context = dict() + self.context = self._format_iterable(context) + + @staticmethod + def _format_iterable(iterable): + space = dict() + for key in iterable: + if isinstance(key, SymbolNode): + key = key.symbol + else: + key = str(key) + space[key] = 1 + return space + + def _test_symbols_defined(self, symbols, partial=False): + if not partial: + for symbol in symbols: + if not self.defined(symbol): + return False + return True + else: + for symbol in symbols: + if self.defined(symbol): + return True + return False + + def defined(self, expr, partial=False): + if isinstance(expr, (list, tuple, set, frozenset)): + return self._test_symbols_defined(expr, partial) + if not isinstance(expr, ExpressionBase): + expr = str(expr) + if isinstance(expr, basestring): + expr = parse_expression(expr) + if isinstance(expr, SymbolNode): + return expr.symbol in self.context + if isinstance(expr, ValueNode): + return True + if isinstance(expr, (ExpressionNode, EnclosedExpression)): + symbols = expr.get_symbols() + return self._test_symbols_defined(symbols, partial) + + def partially_defined(self, expr): + return self.defined(expr, True) + + def __contains__(self, expr): + return self.defined(expr) + + def __repr__(self): + return ""{%s}"" % ', '.join(""%s"" % c for c in self.context) + + def __iter__(self): + return iter(self.context) + + def keys(self): + return self.context.keys() + + def _ipython_key_completions_(self): + return list(self.keys()) + + +class SymbolContext(SymbolSpace): + """""" + Expands the notion of :class:`SymbolSpace` to bind values + to Symbols + + Attributes + ---------- + context : dict + Mapping from Symbol to Value + """""" + + def __init__(self, context=None): + if context is None: + context = dict() + self.context = self._format_map(context) + + def _normalize(self, symbol): + try: + symbol = _FMR.from_iupac_lite(symbol) + return str(symbol) + except Exception: + return symbol + + @staticmethod + def _format_map(mapping): + store = dict() + for key, value in mapping.items(): + if isinstance(key, SymbolNode): + key = key.symbol + else: + key = str(key) + store[key] = value + return store + + def __getitem__(self, node): + """""" + Summary + + Parameters + ---------- + node : ExpressionBase + + Returns + ------- + name : Number + """""" + if not isinstance(node, ExpressionBase): + node = str(node) + + if isinstance(node, basestring): + node = parse_expression(node) + + if isinstance(node, SymbolNode): + if node.symbol is None: + return 1 + else: + try: + return self.context[node] * node.coefficient + except KeyError: + normalized = self._normalize(node.symbol) + if normalized != node.symbol: + if normalized in self.context: + return self.context[normalized] * node.coefficient + return 0 + elif isinstance(node, ValueNode): + return node.value + elif isinstance(node, (ExpressionNode, EnclosedExpression)): + return node.evaluate(self) + else: + raise TypeError(""Don't know how to evaluate %r of type %s"" % (node, node.__class__)) + + def __contains__(self, expr): + if not isinstance(expr, ExpressionBase): + expr = str(expr) + if isinstance(expr, basestring): + expr = parse_expression(expr) + if isinstance(expr, SymbolNode): + return expr.symbol in self.context + elif isinstance(expr, ValueNode): + return True + elif isinstance(expr, (ExpressionNode, EnclosedExpression)): + return expr.evaluate(self) > 0 + + def __repr__(self): + return ""SymbolContext(%r)"" % self.context + + def items(self): + return self.context.items() + + def keys(self): + return self.context.keys() + + def values(self): + return self.context.values() + + +_glycosymbol_map = {} + + +class GlycanSymbolContext(SymbolContext): + @staticmethod + def _format_map(mapping): + store = dict() + for key, value in dict(mapping).items(): + if isinstance(key, SymbolNode): + key = key.symbol + elif isinstance(key, (str, _MR, _SR)): + text_key = str(key) + try: + key = _glycosymbol_map[text_key] + except KeyError: + key = _FMR.from_iupac_lite(text_key) + is_derivatized = composition_transform.has_derivatization(key) + if is_derivatized: + key = str( + glycan_composition.from_iupac_lite.strip_derivatization(text_key)) + else: + key = text_key + _glycosymbol_map[text_key] = key + elif isinstance(key, _MC): + key = str(key) + store[key] = value + return store + + def serialize(self): + form = ""{%s}"" % '; '.join(""{}:{}"".format(str(k), v) for k, v in sorted( + self.items(), key=lambda x: _monosaccharide_symbol_orderer(x[0])) if v != 0) + return form + + @staticmethod + def normalize_key(composition): + key_obj = composition.clone() + key_obj = composition_transform.strip_derivatization(key_obj) + return str(key_obj) + + +class _monosaccharide_symbol_orderer_cache(dict): + + def __missing__(self, key): + value = _FMR.from_iupac_lite(key) + self[key] = value + return value + + def __call__(self, key): + key = str(key) + return self[key].mass(), key + + +_monosaccharide_symbol_orderer = _monosaccharide_symbol_orderer_cache() + + +Solution = SymbolContext + +operator_map = {} + + +def register_operator(cls): + """""" + Summary + + Returns + ------- + name : TYPE + Description + """""" + inst = cls() + operator_map[cls.symbol] = inst + for alias in getattr(cls, ""aliases"", []): + operator_map[alias] = inst + return cls + + +@register_operator +class Operator(object): + """""" + A base class for defining binary arithmetic + operators over expressions. Subclasses should + provide a :meth:`__call__` method to handle + a left and right :class:`ExpressionBase` objects + and a :class:`SymbolContext` instance in which + to resolve them. + + Attributes + ---------- + precedence : int + The operator's precedence, which influences + the order in which they are applied + symbol : str + The textual encoding of the operator + aliases : list + A list of alternative symbols for the operator + """""" + symbol = ""NoOp"" + precedence = 0 + + def __init__(self, symbol=None): + """""" + Summary + + Parameters + ---------- + symbol : TYPE, optional + Description + """""" + if symbol is not None: + self.symbol = symbol + + def __call__(self, left, right, context): + """""" + Summary + + Parameters + ---------- + left : TYPE + Description + right : TYPE + Description + context : TYPE + Description + + Returns + ------- + name : TYPE + Description + """""" + return NotImplemented + + def __repr__(self): + return self.symbol + + def __eq__(self, other): + """""" + Summary + + Parameters + ---------- + other : TYPE + Description + + Returns + ------- + name : TYPE + Description + """""" + try: + return self.symbol == other.symbol + except AttributeError: + return self.symbol == other + + def __hash__(self): + return hash(self.symbol) + + operator_map = operator_map + + @classmethod + def get(cls, symbol): + return cls.operator_map[symbol] + + +@register_operator +class LessThan(Operator): + symbol = ""<"" + + def __call__(self, left, right, context): + left_val = context[left] * left.coefficient + right_val = context[right] * right.coefficient + return left_val < right_val + + +@register_operator +class LessThanOrEqual(Operator): + symbol = ""<="" + + def __call__(self, left, right, context): + left_val = context[left] * left.coefficient + right_val = context[right] * right.coefficient + return left_val <= right_val + + +@register_operator +class GreaterThan(Operator): + symbol = "">"" + + def __call__(self, left, right, context): + left_val = context[left] * left.coefficient + right_val = context[right] * right.coefficient + return left_val > right_val + + +@register_operator +class GreaterThanOrEqual(Operator): + symbol = "">="" + + def __call__(self, left, right, context): + left_val = context[left] * left.coefficient + right_val = context[right] * right.coefficient + return left_val >= right_val + + +@register_operator +class Equal(Operator): + symbol = ""="" + precedence = 10 + aliases = [""==""] + + def __call__(self, left, right, context): + left_val = context[left] * left.coefficient + right_val = context[right] * right.coefficient + return left_val == right_val + + +@register_operator +class Unequal(Operator): + symbol = ""!="" + precedence = 10 + + def __call__(self, left, right, context): + left_val = context[left] * left.coefficient + right_val = context[right] * right.coefficient + return left_val != right_val + + +@register_operator +class Subtraction(Operator): + """""" + Summary + + Attributes + ---------- + precedence : int + Description + symbol : str + Description + """""" + symbol = ""-"" + precedence = 1 + + def __call__(self, left, right, context): + left_val = context[left] + right_val = context[right] + return left_val - right_val + + +@register_operator +class Addition(Operator): + symbol = ""+"" + precedence = 1 + + def __call__(self, left, right, context): + left_val = context[left] + right_val = context[right] + return left_val + right_val + + +@register_operator +class Multplication(Operator): + symbol = '*' + precedence = 2 + + def __call__(self, left, right, context): + left_val = context[left] + right_val = context[right] + return left_val * right_val + + +@register_operator +class Division(Operator): + symbol = '/' + precedence = 2 + + def __call__(self, left, right, context): + left_val = context[left] + right_val = context[right] + return left_val / right_val + + +@register_operator +class Or(Operator): + symbol = 'or' + aliases = ['|', ""||""] + + def __call__(self, left, right, context): + return context[left] or context[right] + + +@register_operator +class And(Operator): + symbol = ""and"" + aliases = [""&"", ""&&""] + + def __call__(self, left, right, context): + return context[left] and context[right] + + +@register_operator +class Append(Operator): + symbol = ',' + + def __call__(self, left, right, context): + lval = context[left] + rval = context[right] + if not isinstance(lval, tuple): + lval = (lval,) + if not isinstance(rval, tuple): + rval = (rval,) + return lval + rval + + +@register_operator +class Call(Operator): + symbol = ""call"" + + def __call__(self, left, right, context): + try: + fn = function_table[left] + return fn(right, context) + except KeyError: + raise UnknownFunctionError(left) + + +class UnknownFunctionError(KeyError): + pass + + +def symbolic_sum(terms, context): + value = 0 + try: + for term in context[terms]: + value += context[term] + return value + except TypeError: + return context[terms] + + +def symbolic_abs(terms, context): + return abs(context[terms]) + + +def symbolic_max(terms, context): + args = terms.evaluate(context) + return max(args) + + +def symbolic_min(terms, context): + args = terms.evaluate(context) + return min(args) + + +def ifelse(terms, context): + if len(terms) != 3: + raise ValueError(""ifelse takes three arguments, given %d"" % (len(terms), )) + condition = terms[0] + if_true = terms[1] + if_false = terms[2] + if condition.evaluate(context): + return if_true.evaluate(context) + else: + return if_false.evaluate(context) + + +function_table = { + ""sum"": symbolic_sum, + ""abs"": symbolic_abs, + ""max"": symbolic_max, + ""min"": symbolic_min, + ""ifelse"": ifelse +} + + +class OrCompoundConstraint(ConstraintExpression): + """""" + A combination of ConstraintExpression instances which + is satisfied if either of its components are satisfied. + + Attributes + ---------- + left : ConstraintExpression + right : ConstraintExpression + """""" + + def __init__(self, left, right): + self.left = left + self.right = right + + def __call__(self, context): + return self.left(context) or self.right(context) + + def __repr__(self): + return ""(({}) or ({}))"".format(self.left, self.right) + + def get_symbols(self): + return self.left.get_symbols() + self.right.get_symbols() + + +class AndCompoundConstraint(ConstraintExpression): + """""" + A combination of ConstraintExpression instances which + is only satisfied if both of its components are satisfied. + + Attributes + ---------- + left : ConstraintExpression + right : ConstraintExpression + """""" + + def __init__(self, left=None, right=None): + self.left = left + self.right = right + + def __call__(self, context): + return self.left(context) and self.right(context) + + def __repr__(self): + return ""(({}) and ({}))"".format(self.left, self.right) + + def get_symbols(self): + return self.left.get_symbols() + self.right.get_symbols() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scan_cache.py",".py","405","17","from ms_deisotope.tools.deisotoper.output import ( + ThreadedMzMLbScanStorageHandler, + ThreadedMzMLScanStorageHandler, + ThreadedMGFScanStorageHandler, + NullScanStorageHandler, + ScanStorageHandlerBase +) + + +__all__ = [ + ""ThreadedMzMLbScanStorageHandler"", + ""ThreadedMzMLScanStorageHandler"", + ""ThreadedMGFScanStorageHandler"", + ""NullScanStorageHandler"", + ""ScanStorageHandlerBase"" +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/cli/analyze.py",".py","48943","964","import os +from uuid import uuid4 + +import dill as pickle + +import click + +from ms_deisotope.data_source.metadata.sample import Sample + +from glycresoft import serialize +from glycresoft.cli.export import analysis_identifier_arg + +from glycresoft.serialize import ( + DatabaseBoundOperation, + GlycanHypothesis, + GlycopeptideHypothesis, + Analysis) + +from glycresoft.profiler import ( + MzMLGlycopeptideLCMSMSAnalyzer, + MzMLComparisonGlycopeptideLCMSMSAnalyzer, + MultipartGlycopeptideLCMSMSAnalyzer, + GlycopeptideFDREstimationStrategy, + MzMLGlycanChromatogramAnalyzer, + LaplacianRegularizedChromatogramProcessor, + ProcessedMSFileLoader, + ChromatogramSummarizer) + +from glycresoft.composition_distribution_model import site_model +from glycresoft.scoring.elution_time_grouping import GlycopeptideChromatogramProxy, GlycopeptideElutionTimeModeler +from glycresoft.serialize.analysis import AnalysisTypeEnum +from glycresoft.tandem.glycopeptide.scoring import CoverageWeightedBinomialScorer +from glycresoft.composition_distribution_model import GridPointSolution +from glycresoft.database.composition_network import GraphReader + +from glycresoft.models import GeneralScorer +from glycresoft.task import fmt_msg + +from .base import ( + cli, HiddenOption, processes_option) + +from .validators import ( + validate_analysis_name, + validate_mass_shift, validate_glycopeptide_tandem_scoring_function, + glycopeptide_tandem_scoring_functions, + get_by_name_or_id, + validate_ms1_feature_name, + ms1_model_features, + RelativeMassErrorParam, + DatabaseConnectionParam, + SmallSampleFDRCorrectionParam, ChoiceOrURI) + + +def make_analysis_output_path(prefix): + output_path_pattern = prefix + ""_analysis_%d.db"" + i = 1 + while os.path.exists(output_path_pattern % i) and i < (2 ** 16): + i += 1 + if i >= (2 ** 16): + return output_path_pattern % (uuid4().int,) + else: + return output_path_pattern % (i,) + + +@cli.group(short_help='Identify structures in preprocessed data') +def analyze(): + pass + + +def database_connection_arg(arg_name='database-connection'): + def database_connection_arg(fn): + arg = click.argument( + arg_name, + type=DatabaseConnectionParam(exists=True), + doc_help=( + ""A connection URI for a database, or a path on the file system"")) + return arg(fn) + return database_connection_arg + + +def hypothesis_identifier_arg(hypothesis_type, arg_name='hypothesis-identifier'): + def wrapper(fn): + arg = click.argument(arg_name, doc_help=( + ""The ID number or name of the %s hypothesis to use"" % (hypothesis_type,))) + return arg(fn) + return wrapper + + +def hypothesis_identifier_arg_option(hypothesis_type, *args, **kwargs): + def wrapper(fn): + arg = click.option(*args, help=( + ""The ID number or name of the %s hypothesis to use"" % (hypothesis_type,)), **kwargs) + return arg(fn) + return wrapper + + +def sample_path_arg(fn): + arg = click.argument( + ""sample-path"", + type=click.Path(exists=True, dir_okay=False, file_okay=True), + doc_help=( + ""The path to the deconvoluted sample file"")) + return arg(fn) + + +@analyze.command(""search-glycopeptide"", short_help='Search preprocessed data for glycopeptide sequences') +@click.pass_context +@database_connection_arg() +@sample_path_arg +@hypothesis_identifier_arg(""glycopeptide"") +@click.option(""-m"", ""--mass-error-tolerance"", type=RelativeMassErrorParam(), default=1e-5, + help=""Mass accuracy constraint, in parts-per-million error, for matching MS^1 ions."") +@click.option(""-mn"", ""--msn-mass-error-tolerance"", type=RelativeMassErrorParam(), default=2e-5, + help=""Mass accuracy constraint, in parts-per-million error, for matching MS^n ions."") +@click.option(""-g"", ""--grouping-error-tolerance"", type=RelativeMassErrorParam(), default=1.5e-5, + help=""Mass accuracy constraint, in parts-per-million error, for grouping chromatograms."") +@click.option(""-n"", ""--analysis-name"", default=None, help='Name for analysis to be performed.') +@click.option(""-q"", ""--psm-fdr-threshold"", default=0.05, type=float, + help='Minimum FDR Threshold to use for filtering GPSMs when selecting identified glycopeptides') +@click.option(""-s"", ""--tandem-scoring-model"", default='coverage_weighted_binomial', + type=ChoiceOrURI(glycopeptide_tandem_scoring_functions.keys()), + help=""Select a scoring function to use for evaluating glycopeptide-spectrum matches"") +@click.option(""-x"", ""--oxonium-threshold"", default=0.05, type=float, + help=('Minimum HexNAc-derived oxonium ion abundance ' + 'ratio to filter MS/MS scans. Defaults to 0.05.')) +@click.option(""-a"", ""--adduct"", 'mass_shifts', multiple=True, nargs=2, + help=(""Adducts to consider. Specify name or formula, and a"" + "" multiplicity."")) +@click.option(""-f"", ""--use-peptide-mass-filter"", is_flag=True, help=( + ""Filter putative spectrum matches by estimating the peptide backbone mass "" + ""from the precursor mass and stub glycopeptide signature ions"")) +@processes_option +@click.option(""--export"", type=click.Choice(['csv', 'html', 'psm-csv']), multiple=True, + help=""export command to after search is complete"") +@click.option(""-o"", ""--output-path"", default=None, type=click.Path(writable=True), + help=(""Path to write resulting analysis to.""), required=True) +@click.option(""-w"", ""--workload-size"", default=500, type=int, help=""Number of spectra to process at once"") +@click.option(""--save-intermediate-results"", default=None, type=click.Path(), required=False, + help='Save intermediate spectrum matches to a file') +@click.option(""--maximum-mass"", default=float('inf'), type=float) +@click.option(""-D"", ""--decoy-database-connection"", default=None, help=( + ""Provide an alternative hypothesis to draw decoy glycopeptides from instead of the simpler reversed-peptide "" + ""decoy. This is especially necessary when the stub peptide+Y ions account for a large fraction of MS2 signal."")) +@click.option(""-G"", ""--permute-decoy-glycan-fragments"", is_flag=True, default=False, help=( + ""Whether or not to permute decoy glycopeptides' peptide+Y ions. The intact mass, peptide, "" + ""and peptide+Y1 ions are unchanged."")) +@click.option(""--fdr-correction"", default='auto', type=SmallSampleFDRCorrectionParam(), + help=(""Whether to attempt to correct for small sample size for target-decoy analysis.""), + cls=HiddenOption) +@click.option(""--isotope-probing-range"", type=int, default=3, help=( + ""The maximum number of isotopic peak errors to allow when searching for untrusted precursor masses"")) +@click.option(""-R"", ""--rare-signatures"", is_flag=True, default=False, + help=""Look for rare signature ions when scoring glycan oxonium signature"") +@click.option(""--retention-time-modeling/--no-retention-time-modeling"", is_flag=True, default=True, + help=(""Whether or not to model relative retention time to correct for common glycan"" + "" composition errors."")) +def search_glycopeptide(context, database_connection, sample_path, hypothesis_identifier, + analysis_name, output_path=None, grouping_error_tolerance=1.5e-5, mass_error_tolerance=1e-5, + msn_mass_error_tolerance=2e-5, psm_fdr_threshold=0.05, peak_shape_scoring_model=None, + tandem_scoring_model=None, oxonium_threshold=0.15, save_intermediate_results=None, + processes=4, workload_size=500, mass_shifts=None, export=None, + use_peptide_mass_filter=False, maximum_mass=float('inf'), + decoy_database_connection=None, fdr_correction='auto', + isotope_probing_range=3, + permute_decoy_glycan_fragments=False, + rare_signatures=False, + retention_time_modeling=True): + """"""Identify glycopeptide sequences from processed LC-MS/MS data. This algorithm requires a fully materialized + cross-product database (the default), and uses a reverse-peptide decoy by default, evaluated on the total score. + + For a search algorithm that applies separate FDR control on the peptide and the glycan, see + :ref:`search-glycopeptide-multipart` + """""" + if tandem_scoring_model is None: + tandem_scoring_model = CoverageWeightedBinomialScorer + if os.path.exists(output_path): + click.secho(""Output path '%s' exists, removing..."" % output_path, fg='yellow') + os.remove(output_path) + database_connection = DatabaseBoundOperation(database_connection) + ms_data = ProcessedMSFileLoader(sample_path, use_index=False) + try: + sample_run = ms_data.sample_run + except StopIteration: + sample_run = Sample(name=os.path.basename(sample_path).split('.')[0], id=str(uuid4())) + + try: + hypothesis = get_by_name_or_id( + database_connection, GlycopeptideHypothesis, hypothesis_identifier) + except Exception: + click.secho(""Could not locate a Glycopeptide Hypothesis with identifier %r"" % + hypothesis_identifier, fg='yellow') + raise click.Abort() + + tandem_scoring_model, evaluation_kwargs = validate_glycopeptide_tandem_scoring_function( + context, tandem_scoring_model) + + mass_shifts = [validate_mass_shift(mass_shift, multiplicity) + for mass_shift, multiplicity in mass_shifts] + expanded = [] + expanded = MzMLGlycanChromatogramAnalyzer.expand_mass_shifts( + dict(mass_shifts), crossproduct=False) + mass_shifts = expanded + + if analysis_name is None: + analysis_name = ""%s @ %s"" % (sample_run.name, hypothesis.name) + + analysis_name = validate_analysis_name( + context, database_connection.session, analysis_name) + + click.secho(""Preparing analysis of %s by %s"" % ( + sample_run.name, hypothesis.name), fg='cyan') + + if decoy_database_connection is None: + analyzer = MzMLGlycopeptideLCMSMSAnalyzer( + database_connection._original_connection, + sample_path=sample_path, + hypothesis_id=hypothesis.id, + analysis_name=analysis_name, + output_path=output_path, + grouping_error_tolerance=grouping_error_tolerance, + mass_error_tolerance=mass_error_tolerance, + msn_mass_error_tolerance=msn_mass_error_tolerance, + psm_fdr_threshold=psm_fdr_threshold, + peak_shape_scoring_model=peak_shape_scoring_model, + tandem_scoring_model=tandem_scoring_model, + oxonium_threshold=oxonium_threshold, + n_processes=processes, + spectrum_batch_size=workload_size, + mass_shifts=mass_shifts, + use_peptide_mass_filter=use_peptide_mass_filter, + maximum_mass=maximum_mass, + probing_range_for_missing_precursors=isotope_probing_range, + permute_decoy_glycans=permute_decoy_glycan_fragments, + rare_signatures=rare_signatures, + model_retention_time=retention_time_modeling, + evaluation_kwargs=evaluation_kwargs + ) + else: + analyzer = MzMLComparisonGlycopeptideLCMSMSAnalyzer( + database_connection._original_connection, + decoy_database_connection, + sample_path=sample_path, + hypothesis_id=hypothesis.id, + analysis_name=analysis_name, + output_path=output_path, + grouping_error_tolerance=grouping_error_tolerance, + mass_error_tolerance=mass_error_tolerance, + msn_mass_error_tolerance=msn_mass_error_tolerance, + psm_fdr_threshold=psm_fdr_threshold, + peak_shape_scoring_model=peak_shape_scoring_model, + tandem_scoring_model=tandem_scoring_model, + oxonium_threshold=oxonium_threshold, + n_processes=processes, + spectrum_batch_size=workload_size, + mass_shifts=mass_shifts, + use_peptide_mass_filter=use_peptide_mass_filter, + maximum_mass=maximum_mass, + use_decoy_correction_threshold=fdr_correction, + probing_range_for_missing_precursors=isotope_probing_range, + permute_decoy_glycans=permute_decoy_glycan_fragments, + rare_signatures=rare_signatures, + model_retention_time=retention_time_modeling, + evaluation_kwargs=evaluation_kwargs + ) + analyzer.display_header() + result = analyzer.start() + gps, unassigned, target_decoy_set = result[:3] + if save_intermediate_results is not None: + analyzer.log(""Saving Intermediate Results"") + with open(save_intermediate_results, 'wb') as handle: + pickle.dump((target_decoy_set, gps), handle) + del gps + del unassigned + del target_decoy_set + if export: + for export_type in set(export): + click.echo(fmt_msg(""Handling Export: %s"" % (export_type,))) + if export_type == 'csv': + from glycresoft.cli.export import glycopeptide_identification + base = os.path.splitext(output_path)[0] + export_path = ""%s-glycopeptides.csv"" % (base,) + context.invoke( + glycopeptide_identification, + database_connection=output_path, + analysis_identifier=analyzer.analysis_id, + output_path=export_path) + elif export_type == 'psm-csv': + from glycresoft.cli.export import glycopeptide_spectrum_matches + base = os.path.splitext(output_path)[0] + export_path = ""%s-glycopeptide-spectrum-matches.csv"" % (base,) + context.invoke( + glycopeptide_spectrum_matches, + database_connection=output_path, + analysis_identifier=analyzer.analysis_id, + output_path=export_path) + elif export_type == 'html': + from glycresoft.cli.export import glycopeptide_identification + base = os.path.splitext(output_path)[0] + export_path = ""%s-report.html"" % (base,) + context.invoke( + glycopeptide_identification, + database_connection=output_path, + analysis_identifier=analyzer.analysis_id, + output_path=export_path, + report=True) + + +@analyze.command(""search-glycopeptide-multipart"", short_help=( + 'Search preprocessed data for glycopeptide sequences scored for both peptide and glycan components')) +@click.pass_context +@database_connection_arg(""database-connection"") +@database_connection_arg(""decoy-database-connection"") +@sample_path_arg +@hypothesis_identifier_arg_option(""glycopeptide"", '-T', '--target-hypothesis-identifier', default=1) +@hypothesis_identifier_arg_option(""glycopeptide"", '-D', ""--decoy-hypothesis-identifier"", default=1) +@click.option(""-M"", ""--memory-database-index"", is_flag=True, + help=(""Whether to load the entire peptide database into memory during spectrum mapping. "" + ""Uses more memory but substantially accelerates the process""), default=False) +@click.option(""-m"", ""--mass-error-tolerance"", type=RelativeMassErrorParam(), default=1e-5, + help=""Mass accuracy constraint, in parts-per-million error, for matching MS^1 ions."") +@click.option(""-mn"", ""--msn-mass-error-tolerance"", type=RelativeMassErrorParam(), default=2e-5, + help=""Mass accuracy constraint, in parts-per-million error, for matching MS^n ions."") +@click.option(""-g"", ""--grouping-error-tolerance"", type=RelativeMassErrorParam(), default=1.5e-5, + help=""Mass accuracy constraint, in parts-per-million error, for grouping chromatograms."") +@click.option(""-n"", ""--analysis-name"", default=None, help='Name for analysis to be performed.') +@click.option(""-q"", ""--psm-fdr-threshold"", default=0.05, type=float, + help='Minimum FDR Threshold to use for filtering GPSMs when selecting identified glycopeptides') +@click.option(""-f"", ""--fdr-estimation-strategy"", type=click.Choice(['joint', 'peptide', 'glycan', 'any']), + default='joint', + help=(""The FDR estimation strategy to use. The joint estimate uses both peptide and glycan scores, "" + ""peptide uses only peptide scores, glycan uses only glycan scores, and any uses the smallest "" + ""FDR of the joint, peptide, and glycan estiamtes."")) +@click.option(""-s"", ""--tandem-scoring-model"", default='log_intensity', + type=ChoiceOrURI([""log_intensity"", + ""simple"", + ""penalized_log_intensty"", + ""log_intensity_v3""]), + help=""Select a scoring function to use for evaluating glycopeptide-spectrum matches"") +@click.option(""-y"", ""--glycan-score-threshold"", default=1.0, type=float, + help=""The minimum glycan score required to consider a peptide mass"") +@click.option(""-a"", ""--adduct"", 'mass_shifts', multiple=True, nargs=2, + help=(""Adducts to consider. Specify name or formula, and a"" + "" multiplicity."")) +@processes_option +@click.option(""--export"", type=click.Choice(['csv', 'html', 'psm-csv']), multiple=True, + help=""export command to after search is complete"") +@click.option(""-o"", ""--output-path"", default=None, type=click.Path(writable=True), + help=(""Path to write resulting analysis to.""), required=True) +@click.option(""-w"", ""--workload-size"", default=100, type=int, help=""Number of spectra to process at once"") +@click.option(""-R"", ""--rare-signatures"", is_flag=True, default=False, + help=""Look for rare signature ions when scoring glycan oxonium signature"") +@click.option(""--retention-time-modeling/--no-retention-time-modeling"", is_flag=True, default=True, + help=(""Whether or not to model relative retention time to correct for common glycan"" + "" composition errors."")) +@click.option(""--save-intermediate-results"", default=None, type=click.Path(), required=False, + help='Save intermediate spectrum matches to a file', cls=HiddenOption) +@click.option(""--maximum-mass"", default=float('inf'), type=float, cls=HiddenOption) +@click.option(""--isotope-probing-range"", type=int, default=3, help=( + ""The maximum number of isotopic peak errors to allow when searching for untrusted precursor masses"")) +@click.option(""-S"", ""--glycoproteome-smoothing-model"", type=click.Path(readable=True), help=( + ""Path to a glycoproteome site-specific glycome model""), default=None) +@click.option(""-x"", ""--oxonium-threshold"", default=0.05, type=float, + help=('Minimum HexNAc-derived oxonium ion abundance ' + 'ratio to filter MS/MS scans. Defaults to 0.05.')) +@click.option(""-P"", ""--peptide-masses-per-scan"", type=int, default=60, + help=""The maximum number of peptide masses to consider per scan"") +def search_glycopeptide_multipart(context, database_connection, + decoy_database_connection, + sample_path, + target_hypothesis_identifier=1, + decoy_hypothesis_identifier=1, + analysis_name=None, + output_path=None, + grouping_error_tolerance=1.5e-5, + mass_error_tolerance=1e-5, + msn_mass_error_tolerance=2e-5, + psm_fdr_threshold=0.05, + peak_shape_scoring_model=None, + tandem_scoring_model=None, + glycan_score_threshold=1.0, + memory_database_index=False, + save_intermediate_results=None, + processes=4, + workload_size=100, + mass_shifts=None, + export=None, + maximum_mass=float('inf'), + isotope_probing_range=3, + fdr_estimation_strategy=None, + glycoproteome_smoothing_model=None, + rare_signatures=False, + retention_time_modeling=True, + oxonium_threshold: float=0.05, + peptide_masses_per_scan: int=60): + """""" + Search preprocessed data for glycopeptide sequences scored for both peptide and glycan components. + + This search strategy requires an explicit decoy database, like one created with the `--reverse` + flag from `glycopeptide-fa`. + """""" + if fdr_estimation_strategy is None: + fdr_estimation_strategy = GlycopeptideFDREstimationStrategy.multipart_gamma_gaussian_mixture + else: + fdr_estimation_strategy = GlycopeptideFDREstimationStrategy[fdr_estimation_strategy] + if tandem_scoring_model is None: + tandem_scoring_model = ""log_intensity"" + if os.path.exists(output_path): + click.secho(""Output path '%s' exists, removing..."" % output_path, fg='yellow') + os.remove(output_path) + database_connection = DatabaseBoundOperation(database_connection) + decoy_database_connection = DatabaseBoundOperation(decoy_database_connection) + ms_data = ProcessedMSFileLoader(sample_path, use_index=False) + try: + sample_run = ms_data.sample_run + except StopIteration: + sample_run = Sample(name=os.path.basename(sample_path).split(""."")[0], id=str(uuid4())) + + try: + target_hypothesis = get_by_name_or_id( + database_connection, GlycopeptideHypothesis, target_hypothesis_identifier) + except Exception: + click.secho(""Could not locate Target Glycopeptide Hypothesis with identifier %r"" % + target_hypothesis_identifier, fg='yellow') + raise click.Abort() + + try: + decoy_hypothesis = get_by_name_or_id( + decoy_database_connection, GlycopeptideHypothesis, decoy_hypothesis_identifier) + except Exception: + click.secho(""Could not locate Decoy Glycopeptide Hypothesis with identifier %r"" % + decoy_hypothesis_identifier, fg='yellow') + raise click.Abort() + + tandem_scoring_model, evaluation_kwargs = validate_glycopeptide_tandem_scoring_function( + context, tandem_scoring_model) + + mass_shifts = [validate_mass_shift(mass_shift, multiplicity) + for mass_shift, multiplicity in mass_shifts] + expanded = [] + expanded = MzMLGlycanChromatogramAnalyzer.expand_mass_shifts( + dict(mass_shifts), crossproduct=False) + mass_shifts = expanded + + if analysis_name is None: + analysis_name = ""%s @ %s"" % (sample_run.name, target_hypothesis.name) + + analysis_name = validate_analysis_name( + context, database_connection.session, analysis_name) + + click.secho(""Preparing analysis of %s by %s"" % ( + sample_run.name, target_hypothesis.name), fg='cyan') + analyzer = MultipartGlycopeptideLCMSMSAnalyzer( + database_connection._original_connection, + decoy_database_connection._original_connection, + target_hypothesis.id, + decoy_hypothesis.id, + sample_path, + output_path, + analysis_name=analysis_name, + grouping_error_tolerance=grouping_error_tolerance, + mass_error_tolerance=mass_error_tolerance, + msn_mass_error_tolerance=msn_mass_error_tolerance, + psm_fdr_threshold=psm_fdr_threshold, + tandem_scoring_model=tandem_scoring_model, + glycan_score_threshold=glycan_score_threshold, + mass_shifts=mass_shifts, + n_processes=processes, + spectrum_batch_size=workload_size, + maximum_mass=maximum_mass, + probing_range_for_missing_precursors=isotope_probing_range, + use_memory_database=memory_database_index, + fdr_estimation_strategy=fdr_estimation_strategy, + glycosylation_site_models_path=glycoproteome_smoothing_model, + fragile_fucose=False, + rare_signatures=rare_signatures, + evaluation_kwargs=evaluation_kwargs, + model_retention_time=retention_time_modeling, + oxonium_threshold=oxonium_threshold, + peptide_masses_per_scan=peptide_masses_per_scan + ) + analyzer.display_header() + result = analyzer.start() + gps, unassigned, target_decoy_set = result[:3] + if save_intermediate_results is not None: + analyzer.log(""Saving Intermediate Results"") + with open(save_intermediate_results, 'wb') as handle: + pickle.dump((target_decoy_set, gps), handle) + del gps + del unassigned + del target_decoy_set + if export: + for export_type in set(export): + click.echo(fmt_msg(""Handling Export: %s"" % (export_type,))) + if export_type == 'csv': + from glycresoft.cli.export import glycopeptide_identification + base = os.path.splitext(output_path)[0] + export_path = ""%s-glycopeptides.csv"" % (base,) + context.invoke( + glycopeptide_identification, + database_connection=output_path, + analysis_identifier=analyzer.analysis_id, + output_path=export_path) + elif export_type == 'psm-csv': + from glycresoft.cli.export import glycopeptide_spectrum_matches + base = os.path.splitext(output_path)[0] + export_path = ""%s-glycopeptide-spectrum-matches.csv"" % (base,) + context.invoke( + glycopeptide_spectrum_matches, + database_connection=output_path, + analysis_identifier=analyzer.analysis_id, + output_path=export_path) + elif export_type == 'html': + from glycresoft.cli.export import glycopeptide_identification + base = os.path.splitext(output_path)[0] + export_path = ""%s-report.html"" % (base,) + context.invoke( + glycopeptide_identification, + database_connection=output_path, + analysis_identifier=analyzer.analysis_id, + output_path=export_path, + report=True) + + + +@analyze.command(""fit-glycoproteome-smoothing-model"", short_help=( + ""Fit a site-specific glycome network smoothing model for each site in the glycoproteome"")) +@click.pass_context +@processes_option +@click.option(""-i"", ""--analysis-path"", nargs=2, multiple=True, required=True) +@click.option(""-o"", ""--output-path"", type=click.Path(writable=True), required=True) +@click.option('-q', '--fdr-threshold', type=float, default=0.05, + help=""The FDR threshold to apply when selecting identified glycopeptides"") +@click.option(""-P"", ""--glycopeptide-hypothesis"", type=(DatabaseConnectionParam(exists=True), str)) +@click.option(""-g"", ""--glycan-hypothesis"", type=(DatabaseConnectionParam(exists=True), str)) +@click.option(""-u"", ""--unobserved-penalty-scale"", type=float, default=1.0, required=False, + help=""A penalty to scale unobserved-but-suggested glycans by. Defaults to 1.0, no penalty."") +@click.option(""-a"", ""--smoothing-limit"", type=float, default=0.2, + help=""An upper bound on the network smoothness to use when estimating the posterior probability."") +@click.option(""-r"", ""--require-multiple-observations/--no-require-multiple-observations"", is_flag=True, default=False, + help=( + ""Require a glycan/glycosite combination be observed in multiple samples to treat it as real."" + "" Defaults to False."")) +@click.option(""-w"", ""--network-path"", type=click.Path(exists=True, file_okay=True, dir_okay=False), required=False, + default=None, + help=(""The path to a text file defining the glycan network and its neighborhoods, as produced by "" + ""`glycresfoft build-hypothesis glycan-network`, otherwise the default human N-glycan network "" + ""will be used with the glycans defined in `-g`."")) +@click.option(""-D / -ND"", ""--include-decoys / --exclude-decoys"", is_flag=True, default=True, + help=""Include decoy glycans in the network."", cls=HiddenOption) +def fit_glycoproteome_model(context, analysis_path, output_path, glycopeptide_hypothesis, glycan_hypothesis, + processes=4, unobserved_penalty_scale=None, smoothing_limit=0.2, + require_multiple_observations=True, fdr_threshold=0.05, + network_path=None, include_decoys=True): + analysis_path_set = analysis_path + analysis_path_set_transformed = [] + if require_multiple_observations and len(analysis_path_set) == 1: + click.secho(""Requested multiple observations required but only one analysis provided"" + "" discarding multiple observation requirement."", fg='yellow') + click.echo(f""Collecting {len(analysis_path_set)} analyses"") + for analysis_path, analysis_id in analysis_path_set: + database_connection = DatabaseBoundOperation(analysis_path) + try: + click.echo(""Checking analysis %s:%s"" % + (analysis_path, analysis_id)) + _analysis = get_by_name_or_id(database_connection, Analysis, analysis_id) + except Exception: + click.secho(""Could not locate an Analysis in %r with identifier %r"" % + (analysis_path, analysis_id), fg='yellow') + raise click.Abort() + # analysis_path_set_transformed.append((analysis_path, analysis.id)) + analysis_path_set_transformed.append((analysis_path, int(analysis_id))) + analysis_path_set = analysis_path_set_transformed + + if network_path is not None: + click.echo(""Loading graph from \""%s\"""" % (network_path, )) + with open(network_path, 'r') as netfile: + network = GraphReader(netfile).network + else: + network = None + + glycopeptide_database_connection_path, hypothesis_identifier = glycopeptide_hypothesis + glycopeptide_database_connection = DatabaseBoundOperation(glycopeptide_database_connection_path) + try: + glycopeptide_hypothesis = get_by_name_or_id( + glycopeptide_database_connection, GlycopeptideHypothesis, hypothesis_identifier) + except Exception: + click.secho(""Could not locate a Glycopeptide Hypothesis with identifier %r"" % + hypothesis_identifier, fg='yellow') + raise click.Abort() + + glycan_database_connection_path, hypothesis_identifier = glycan_hypothesis + glycan_database_connection = DatabaseBoundOperation( + glycan_database_connection_path) + try: + glycan_hypothesis = get_by_name_or_id( + glycan_database_connection, GlycanHypothesis, hypothesis_identifier) + except Exception: + click.secho(""Could not locate a Glycopeptide Hypothesis with identifier %r"" % + hypothesis_identifier, fg='yellow') + raise click.Abort() + workflow = site_model.GlycoproteinSiteModelBuildingWorkflow.from_paths( + analysis_path_set, glycopeptide_database_connection_path, glycopeptide_hypothesis.id, + glycan_database_connection_path, glycan_hypothesis.id, unobserved_penalty_scale, smoothing_limit, + require_multiple_observations, output_path=output_path, n_threads=processes, + q_value_threshold=fdr_threshold, network=network, include_decoy_glycans=False) + workflow.start() + + +class RegularizationParameterType(click.ParamType): + name = ""\""grid\"" or NUMBER > 0 or [grid|NUMBER]/NUMBER"" + seperator = '/' + + def convert(self, value, param, ctx): + sep_count = value.count(self.seperator) + if sep_count > 1: + self.fail(""regularization parameter split \""%s\"" cannot be "" + ""used more than once"" % self.seperator) + elif sep_count == 1: + parts = value.split(self.seperator) + parts = (self.convert(parts[0], param, ctx), + self.convert(parts[1], param, ctx)) + if parts[1] == 'grid': + self.fail(""The second regularization parameter cannot be \""grid\"""") + return parts + + value = value.strip().lower() + if value == 'grid': + return LaplacianRegularizedChromatogramProcessor.GRID_SEARCH + else: + try: + value = float(value) + if value < 0: + self.fail(""regularization parameter must be either \""grid\"" or"" + "" a non-negative number between 0 and 1"") + return value + except ValueError: + self.fail(""regularization parameter must be either \""grid\"" or"" + "" a number between 0 and 1"") + + +@analyze.command(""search-glycan"", short_help=('Search processed data for' + ' glycan compositions')) +@click.pass_context +@database_connection_arg() +@sample_path_arg +@hypothesis_identifier_arg(""glycan"") +@click.option(""-m"", ""--mass-error-tolerance"", type=RelativeMassErrorParam(), default=1e-5, + help=(""Mass accuracy constraint, in parts-per-million "" + ""error, for matching."")) +@click.option(""-mn"", ""--msn-mass-error-tolerance"", type=RelativeMassErrorParam(), default=2e-5, + help=""Mass accuracy constraint, in parts-per-million error, for matching MS^n ions."") +@click.option(""-g"", ""--grouping-error-tolerance"", type=RelativeMassErrorParam(), default=1.5e-5, + help=(""Mass accuracy constraint, in parts-per-million error, for"" + "" grouping chromatograms."")) +@click.option(""-n"", ""--analysis-name"", default=None, + help='Name for analysis to be performed.') +@click.option(""-a"", ""--mass_shift"", 'mass_shifts', multiple=True, nargs=2, + help=(""Adducts to consider. Specify name or formula, and a"" + "" multiplicity."")) +@click.option(""--mass_shift-combination-limit"", type=int, default=8, help=( + ""Maximum number of mass_shift combinations to consider"")) +@click.option(""-d"", ""--minimum-mass"", default=500., type=float, + help=""The minimum mass to consider signal at."") +@click.option(""-o"", ""--output-path"", default=None, help=(""Path to write resulting analysis to.""), + required=True) +@click.option(""--interact"", is_flag=True, cls=HiddenOption) +@click.option(""-f"", ""--ms1-scoring-feature"", ""scoring_model_features"", multiple=True, + type=click.Choice(ms1_model_features.keys(lambda x: x.replace(""_"", ""-""))), + help=""Additional features to include in evaluating chromatograms"") +@click.option(""-r"", ""--regularize"", type=RegularizationParameterType(), + help=(""Apply Laplacian regularization with either a"" + "" specified weight or \""grid\"" to grid search, or a pair of values"" + "" separated by a / to specify a weight or grid search "" + "" for model fitting and a separate weight for scoring"")) +@click.option(""-w"", ""--regularization-model-path"", type=click.Path(exists=True), + default=None, + help=""Path to a file containing a neighborhood model for regularization"") +@click.option(""-k"", ""--network-path"", type=click.Path(exists=True), default=None, + help=(""Path to a file containing the glycan composition network"" + "" and neighborhood rules"")) +@click.option(""-t"", ""--delta-rt"", default=0.5, type=float, + help='The maximum time between observed data points before splitting features') +@click.option(""--export"", type=click.Choice(['csv', 'glycan-list', 'html', ""model""]), multiple=True, + help=""export command to after search is complete"") +@click.option('-s', '--require-msms-signature', type=float, default=0.0, + help=""Minimum oxonium ion signature required in MS/MS scans to include."") +@processes_option +def search_glycan(context, database_connection, sample_path, + hypothesis_identifier, + analysis_name, mass_shifts, grouping_error_tolerance=1.5e-5, + mass_error_tolerance=1e-5, minimum_mass=500., + scoring_model=None, regularize=None, regularization_model_path=None, + network_path=None, + output_path=None, scoring_model_features=None, + delta_rt=0.5, export=None, interact=False, + require_msms_signature=0.0, msn_mass_error_tolerance=2e-5, + mass_shift_combination_limit=None, + processes=4): + """"""Identify glycan compositions from preprocessed LC-MS data, stored in mzML + format. + """""" + if os.path.exists(output_path): + click.secho(""Output path '%s' exists, removing..."" % output_path, fg='yellow') + os.remove(output_path) + + if scoring_model is None: + scoring_model = GeneralScorer + + if mass_shift_combination_limit is None: + mass_shift_combination_limit = 8 + + if scoring_model_features: + for feature in scoring_model_features: + scoring_model.add_feature(validate_ms1_feature_name(feature)) + + if regularization_model_path is not None: + with open(regularization_model_path, 'r') as mod_file: + regularization_model = GridPointSolution.load(mod_file) + else: + regularization_model = None + + if network_path is not None: + with open(network_path, 'r') as netfile: + network = GraphReader(netfile).network + else: + network = None + + database_connection = DatabaseBoundOperation(database_connection) + ms_data = ProcessedMSFileLoader(sample_path, use_index=False) + try: + sample_run = ms_data.sample_run + except StopIteration: + sample_run = Sample(name=os.path.basename(sample_path).split(""."")[0], id=str(uuid4())) + + try: + hypothesis = get_by_name_or_id( + database_connection, GlycanHypothesis, hypothesis_identifier) + except Exception: + click.secho(""Could not locate a Glycan Hypothesis with identifier %r"" % + hypothesis_identifier, fg='yellow') + raise click.Abort() + + if analysis_name is None: + analysis_name = ""%s @ %s"" % (sample_run.name, hypothesis.name) + + analysis_name = validate_analysis_name( + context, database_connection.session, analysis_name) + + mass_shifts = [validate_mass_shift(mass_shift, multiplicity) + for mass_shift, multiplicity in mass_shifts] + expanded = [] + expanded = MzMLGlycanChromatogramAnalyzer.expand_mass_shifts(dict(mass_shifts), limit=mass_shift_combination_limit) + mass_shifts = expanded + + click.secho(""Preparing analysis of %s by %s"" % + (sample_run.name, hypothesis.name), fg='cyan') + + analyzer = MzMLGlycanChromatogramAnalyzer( + database_connection._original_connection, hypothesis.id, + sample_path=sample_path, output_path=output_path, mass_shifts=mass_shifts, + mass_error_tolerance=mass_error_tolerance, + msn_mass_error_tolerance=msn_mass_error_tolerance, + grouping_error_tolerance=grouping_error_tolerance, + scoring_model=scoring_model, + minimum_mass=minimum_mass, + regularize=regularize, + regularization_model=regularization_model, + network=network, + analysis_name=analysis_name, + delta_rt=delta_rt, + require_msms_signature=require_msms_signature, + n_processes=processes) + analyzer.display_header() + analyzer.start() + if interact: + try: + import IPython + click.secho(fmt_msg(""Beginning Interactive Session...""), fg='cyan') + IPython.embed() + except ImportError: + click.secho(fmt_msg(""Interactive Session Not Supported""), fg='red') + if export: + for export_type in set(export): + click.echo(fmt_msg(""Handling Export: %s"" % (export_type,))) + if export_type == 'csv': + from glycresoft.cli.export import glycan_composition_identification + base = os.path.splitext(output_path)[0] + export_path = ""%s-glycan-chromatograms.csv"" % (base,) + context.invoke( + glycan_composition_identification, + database_connection=output_path, + analysis_identifier=analyzer.analysis_id, + output_path=export_path) + elif export_type == 'html': + from glycresoft.cli.export import glycan_composition_identification + base = os.path.splitext(output_path)[0] + export_path = ""%s-report.html"" % (base,) + context.invoke( + glycan_composition_identification, + database_connection=output_path, + analysis_identifier=analyzer.analysis_id, + output_path=export_path, + report=True) + elif export_type == 'glycan-list': + from glycresoft.cli.export import glycan_hypothesis + base = os.path.splitext(output_path)[0] + export_path = ""%s-glycan-chromatograms.csv"" % (base,) + context.invoke( + glycan_hypothesis, + database_connection=output_path, + hypothesis_identifier=analyzer.hypothesis_id, + output_path=export_path, + importable=True) + elif export_type == ""model"": + base = os.path.splitext(output_path)[0] + export_path = ""%s-regularization-parameters.txt"" % (base,) + params = analyzer.analysis.parameters.get(""network_parameters"") + if params is None: + click.secho(""No parameters were fitted, skipping \""model\"""", fg='red') + else: + with open(export_path, 'w') as fp: + params.dump(fp) + else: + click.secho(""Unrecognized Export: %s"" % (export_type,), fg='yellow') + + +@analyze.command(""summarize-chromatograms"", + short_help=""Simply summarize coherent chromatograms by mass and signal with time boundaries"") +@click.pass_context +@sample_path_arg +@click.option(""-o"", ""--output-path"", default=None, type=click.Path(writable=True), + help=(""Path to write resulting analysis to as a CSV"")) +@click.option(""-e"", ""--evaluate"", is_flag=True, + help=(""Should all chromatograms be evaluated. Can greatly increase runtime."")) +def summarize_chromatograms(context, sample_path, output_path, evaluate=False): + task = ChromatogramSummarizer(sample_path, evaluate=evaluate) + chromatograms, summary_chromatograms = task.start() + if output_path is None: + output_path = os.path.splitext(sample_path)[0] + '.chromatograms.csv' + from glycresoft.output import ( + SimpleChromatogramCSVSerializer, SimpleScoredChromatogramCSVSerializer) + click.echo(""Writing chromatogram summaries to %s"" % (output_path, )) + with open(output_path, 'wb') as fh: + if evaluate: + writer = SimpleScoredChromatogramCSVSerializer(fh, chromatograms) + else: + writer = SimpleChromatogramCSVSerializer(fh, chromatograms) + writer.run() + + + +@analyze.group(short_help=""Model and predict the retention time of glycopeptides"") +def retention_time(): + pass + + +@retention_time.command(""fit-glycopeptide-retention-time"", short_help=""Model the retention time of glycopeptides"") +@click.pass_context +@click.argument(""chromatogram-csv-path"", type=click.Path(readable=True)) +@click.argument(""output-path"", type=click.Path(writable=True)) +@click.option(""-t"", ""--test-chromatogram-csv-path"", type=click.Path(readable=True), + help=(""Path to glycopeptide CSV chromatograms to evaluate with the model, but not fit on"")) +@click.option(""-p"", ""--prefer-joint-model"", is_flag=True, + help=""Prefer the joint model over the peptide-specific ones"") +@click.option('-m', '--minimum-observations-for-specific-model', type=int, default=20, + help=""The minimum number of observations required to fit a peptide sequence-specific model"") +@click.option('-r', '--use-retention-time-normalization', is_flag=True) +def glycopeptide_retention_time_fit(context, chromatogram_csv_path, output_path=None, + test_chromatogram_csv_path=None, prefer_joint_model=False, + minimum_observations_for_specific_model=20, use_retention_time_normalization=False): + '''Fit a retention time model to glycopeptide chromatogram observations, and evaluate the chromatographic apex + retention of each glycopeptide based upon the model fit. For large enough groups, try to fit a model to just + that group. + ''' + with open(chromatogram_csv_path, 'rt') as fh: + chromatograms = GlycopeptideChromatogramProxy.from_csv(fh) + if test_chromatogram_csv_path is not None: + with open(test_chromatogram_csv_path, 'rt') as fh: + test_chromatograms = GlycopeptideChromatogramProxy.from_csv(fh) + else: + test_chromatograms = None + modeler = GlycopeptideElutionTimeModeler( + chromatograms, test_chromatograms=test_chromatograms, + prefer_joint_model=prefer_joint_model, + use_retention_time_normalization=use_retention_time_normalization, + minimum_observations_for_specific_model=minimum_observations_for_specific_model) + modeler.run() + if output_path: + modeler.write(output_path) + + +@retention_time.command( + ""evaluate-glycopeptide-retention-time"", + short_help=""Predict and score the retention time of glycopeptides using an existing model"") +@click.pass_context +@click.argument(""model-path"", type=click.Path(readable=True)) +@click.argument(""chromatogram-csv-path"", type=click.Path(readable=True)) +@click.argument(""output-path"", type=click.Path(writable=True)) +def glycopeptide_retention_time_predict(context, model_path, chromatogram_csv_path, output_path): + """"""Predict and evaluate the retention time of glycopeptides using an existing model. + + The model file should have the extension .pkl and have been produced by the same version of GlycReSoft. + """""" + with open(model_path, 'rb') as fh: + modeler = pickle.load(fh) + with open(chromatogram_csv_path, 'rt') as fh: + chromatograms = GlycopeptideChromatogramProxy.from_csv(fh) + modeler.evaluate(chromatograms) + with open(output_path, 'wt') as fh: + GlycopeptideChromatogramProxy.to_csv(chromatograms, fh) + + +@analyze.command(""summarize-analysis"", short_help=""Briefly summarize the results of an analysis output file"") +@click.pass_context +@database_connection_arg() +@analysis_identifier_arg(""glycopeptide"") +def summarize_analysis(context: click.Context, database_connection, analysis_identifier, verbose=False): + database_connection = DatabaseBoundOperation(database_connection) + session = database_connection.session() # pylint: disable=not-callable + + analysis = get_by_name_or_id(session, Analysis, analysis_identifier) + if not analysis.analysis_type == AnalysisTypeEnum.glycopeptide_lc_msms: + click.secho(""Analysis %r is of type %r."" % ( + str(analysis.name), str(analysis.analysis_type)), fg='red', err=True) + context.abort() + + ads = serialize.AnalysisDeserializer(database_connection._original_connection, analysis_id=analysis.id) + + idgps = ads.query(serialize.IdentifiedGlycopeptide).all() + idgp_05 = 0 + idgp_01 = 0 + + for idgp in idgps: + q = idgp.q_value + if q <= 0.05: + idgp_05 += 1 + if q <= 0.01: + idgp_01 += 1 + + gpsms = ads.get_glycopeptide_spectrum_matches(0.05).all() + gpsm_05 = 0 + gpsm_01 = 0 + + seen_spectrum_05 = set() + seen_spectrum_01 = set() + for gpsm in gpsms: + scan_id = gpsm.scan.scan_id + q = gpsm.q_value + if q <= 0.05: + if scan_id not in seen_spectrum_05: + seen_spectrum_05.add(scan_id) + gpsm_05 += 1 + if q <= 0.01: + if scan_id not in seen_spectrum_01: + seen_spectrum_01.add(scan_id) + gpsm_01 += 1 + + click.echo(f""Name: {ads.analysis.name}"") + click.echo(f""Identified Glycopeptides @ 5% FDR: {idgp_05}"") + click.echo(f""Identified Glycopeptides @ 1% FDR: {idgp_01}"") + + click.echo(f""Identified GPSMs @ 5% FDR: {gpsm_05}"") + click.echo(f""Identified GPSMs @ 1% FDR: {gpsm_01}"") +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/cli/logger_config.py",".py","11425","363","import os +import re +import sys +import uuid +import codecs +import logging +import warnings +import multiprocessing + +from typing import Dict +from logging import FileHandler, LogRecord +from multiprocessing import current_process + +from stat import S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IROTH, S_IWOTH + +from ms_deisotope.task.log_utils import LogUtilsMixin as _LogUtilsMixin + +from glycresoft import task +from glycresoft.config import config_file + +logging_levels = { + 'CRITICAL': 50, + 'DEBUG': 10, + 'ERROR': 40, + 'INFO': 20, + 'NOTSET': 0, + 'WARN': 30, + 'WARNING': 30 +} + +LOG_FILE_NAME = ""glycresoft-log"" +LOG_FILE_MODE = 'w' +LOG_LEVEL = 'INFO' + +user_config_data = config_file.get_configuration() +try: + LOG_FILE_NAME = user_config_data['environment']['log_file_name'] +except KeyError: + pass +try: + LOG_FILE_MODE = user_config_data['environment']['log_file_mode'] +except KeyError: + pass +try: + LOG_LEVEL = user_config_data['environment']['log_level'] + LOG_LEVEL = str(LOG_LEVEL).upper() +except KeyError: + pass + + +LOG_FILE_NAME = os.environ.get(""GLYCRESOFT_LOG_FILE_NAME"", LOG_FILE_NAME) +LOG_FILE_MODE = os.environ.get(""GLYCRESOFT_LOG_FILE_MODE"", LOG_FILE_MODE) +LOG_LEVEL = str(os.environ.get(""GLYCRESOFT_LOG_LEVEL"", LOG_LEVEL)).upper() + + +log_multiprocessing = False +try: + log_multiprocessing = bool(user_config_data['environment']['log_multiprocessing']) +except KeyError: + pass + + +log_multiprocessing = bool(int(os.environ.get( + ""GLYCRESOFT_LOG_MULTIPROCESSING"", log_multiprocessing))) + + +LOGGING_CONFIGURED = False + + +class ProcessAwareFormatter(logging.Formatter): + def format(self, record: logging.LogRecord) -> str: + d: Dict[str, str] = record.__dict__ + try: + d['filename'] = d['filename'].replace("".py"", '').ljust(13)[:13] + except KeyError: + d['filename'] = '' + try: + if d['processName'] == ""MainProcess"": + d['maybeproc'] = '' + else: + d['maybeproc'] = ""| %s "" % d['processName'].replace( + ""Process"", '') + except KeyError: + d['maybeproc'] = '' + return super(ProcessAwareFormatter, self).format(record) + + +class LevelAwareColoredLogFormatter(ProcessAwareFormatter): + try: + from colorama import Fore, Style, init + init() + GREY = Fore.WHITE + BLUE = Fore.BLUE + GREEN = Fore.GREEN + YELLOW = Fore.YELLOW + RED = Fore.RED + BRIGHT = Style.BRIGHT + DIM = Style.DIM + BOLD_RED = Fore.RED + Style.BRIGHT + RESET = Style.RESET_ALL + except ImportError: + GREY = '' + BLUE = '' + GREEN = '' + YELLOW = '' + RED = '' + BRIGHT = '' + DIM = '' + BOLD_RED = '' + RESET = '' + + def _colorize_field(self, fmt: str, field: str, color: str) -> str: + return re.sub(""("" + field + "")"", color + r""\1"" + self.RESET, fmt) + + def _patch_fmt(self, fmt: str, level_color: str) -> str: + fmt = self._colorize_field(fmt, r""%\(asctime\)s"", self.GREEN) + fmt = self._colorize_field(fmt, r""%\(name\).*?s"", self.BLUE) + # fmt = self._colorize_field(fmt, r""%\(message\).*?s"", self.GREY) + if level_color: + fmt = self._colorize_field(fmt, r""%\(levelname\).*?s"", level_color) + return fmt + + def __init__(self, fmt, level_color=None, **kwargs): + fmt = self._patch_fmt(fmt, level_color=level_color) + super().__init__(fmt, **kwargs) + + +class ColoringFormatter(logging.Formatter): + level_to_color = { + logging.INFO: LevelAwareColoredLogFormatter.GREEN, + logging.DEBUG: LevelAwareColoredLogFormatter.GREY + LevelAwareColoredLogFormatter.DIM, + logging.WARN: LevelAwareColoredLogFormatter.YELLOW + LevelAwareColoredLogFormatter.BRIGHT, + logging.ERROR: LevelAwareColoredLogFormatter.BOLD_RED, + logging.CRITICAL: LevelAwareColoredLogFormatter.BOLD_RED, + logging.FATAL: LevelAwareColoredLogFormatter.RED + LevelAwareColoredLogFormatter.DIM, + } + + _formatters: Dict[int, LevelAwareColoredLogFormatter] + + def __init__(self, fmt: str, **kwargs): + self._formatters = {} + for level, style in self.level_to_color.items(): + self._formatters[level] = LevelAwareColoredLogFormatter( + fmt, level_color=style, **kwargs) + + def format(self, record: logging.LogRecord) -> str: + fmtr = self._formatters[record.levelno] + return fmtr.format(record) + + +DATE_FMT = ""%H:%M:%S"" + + +class _LogFilter(logging.Filter): + """"""Filter out log messages from redundant logger helpers"""""" + + def filter(self, record: LogRecord) -> bool: + if record.module == 'log_utils': + return False + return super().filter(record) + + +def get_status_formatter(): + status_terminal_format_string = '[%(asctime)s] %(levelname).1s | %(name)s | %(message)s' + # status_terminal_format_string = ""%(asctime)s %(name)s:%(levelname).1s - %(message)s"" + + if sys.stderr.isatty(): + terminal_formatter = ColoringFormatter( + status_terminal_format_string, datefmt=DATE_FMT) + else: + terminal_formatter = logging.Formatter( + status_terminal_format_string, datefmt=DATE_FMT) + return terminal_formatter + + +def make_status_logger(name=""glycresoft.status""): + status_logger = logging.getLogger(name) + status_logger.propagate = False + + terminal_formatter = get_status_formatter() + handler = logging.StreamHandler(sys.stderr) + handler.setFormatter(terminal_formatter) + status_logger.addHandler(handler) + return status_logger + + +def get_main_process_formatter(): + terminal_format_string = ( + ""[%(asctime)s] %(levelname).1s | %(name)s | %(filename)s:%(lineno)-4d%(maybeproc)s| %(message)s"" + ) + if sys.stderr.isatty(): + fmt = ColoringFormatter( + terminal_format_string, datefmt=DATE_FMT) + else: + fmt = ProcessAwareFormatter( + terminal_format_string, datefmt=DATE_FMT) + return fmt + + +def make_main_process_logger(name=None, level=""INFO""): + fmt = get_main_process_formatter() + handler = logging.StreamHandler() + handler.setFormatter(fmt) + handler.setLevel(level) + logging.getLogger(name=name).addHandler(handler) + + +def make_log_file_logger(log_file_name, log_file_mode, name=None, level=""INFO""): + file_fmter = ProcessAwareFormatter( + ""[%(asctime)s] %(levelname).1s | %(name)s | %(filename)s:%(lineno)-4d%(maybeproc)s | %(message)s"", + DATE_FMT) + flex_handler = FlexibleFileHandler(log_file_name, mode=log_file_mode) + flex_handler.setFormatter(file_fmter) + flex_handler.setLevel(level) + logger = logging.getLogger(name=name) + for handler in list(logger.handlers): + if isinstance(handler, FlexibleFileHandler): + logger.removeHandler(handler) + logger.addHandler(flex_handler) + + +def configure_logging(level=None, log_file_name=None, log_file_mode=None): + global LOGGING_CONFIGURED + root_logger = logging.getLogger() + LOGGING_CONFIGURED = getattr(root_logger, ""_glycresoft_logging_configured"", False) + # If we've already called this, don't repeat it + if LOGGING_CONFIGURED: + return + else: + root_logger._glycresoft_logging_configured = True + LOGGING_CONFIGURED = True + if level is None: + level = logging_levels.get(LOG_LEVEL, ""INFO"") + if log_file_name is None: + log_file_name = LOG_FILE_NAME + if log_file_mode is None: + log_file_mode = LOG_FILE_MODE + + if log_file_mode not in (""w"", ""a""): + warnings.warn(""File Logger configured with mode %r not applicable, using \""w\"" instead"" % ( + log_file_mode,)) + log_file_mode = ""w"" + logging.getLogger().setLevel(level) + + log_filter = _LogFilter() + + logger_to_silence = logging.getLogger(""ms_deisotope"") + logger_to_silence.setLevel(logging.INFO) + logger_to_silence.addFilter(log_filter) + logging.captureWarnings(True) + + logger = logging.getLogger(""glycresoft"") + # We probably only need to register the base class but let's play it safe + _LogUtilsMixin.log_with_logger(logger) + task.LoggingMixin.log_with_logger(logger) + task.TaskBase.log_with_logger(logger) + + make_status_logger() + + if current_process().name == ""MainProcess"": + make_main_process_logger(level=level) + + if log_multiprocessing: + fmt = get_main_process_formatter() + multilogger = multiprocessing.get_logger() + handler = logging.StreamHandler() + handler.setFormatter(fmt) + handler.setLevel(level) + multilogger.addHandler(handler) + + if log_file_name: + make_log_file_logger(log_file_name, log_file_mode, name='glycresoft', level=level) + + warner = logging.getLogger('py.warnings') + warner.setLevel(""CRITICAL"") + + +permission_mask = S_IRUSR & S_IWUSR & S_IXUSR & S_IRGRP & S_IWGRP & S_IROTH & S_IWOTH + + +class FlexibleFileHandler(FileHandler): + def _get_available_file(self): + basename = current_name = self.baseFilename + suffix = 0 + while suffix < 2 ** 16: + if not os.path.exists(current_name): + break + elif os.access(current_name, os.W_OK): + break + else: + suffix += 1 + current_name = ""%s.%s"" % (basename, suffix) + if suffix < 2 ** 16: + return current_name + else: + return ""%s.%s"" % (basename, uuid.uuid4().hex) + + def _open(self): + """""" + Open the current base file with the (original) mode and encoding. + Return the resulting stream. + """""" + stream = LazyFile(self.baseFilename, self.mode, self.encoding) + return stream + + +class LazyFile(object): + def __init__(self, name, mode='r', encoding=None): + self.name = name + self.mode = mode + self.encoding = encoding + self._file = None + + def _open(self): + file_name = self._get_available_file() + if self.encoding is None: + stream = open(file_name, self.mode) + else: + try: + stream = codecs.open(file_name, self.mode, self.encoding) + except LookupError: + print(f""!! Failed to look up encoding {self.encoding}, falling back to UTF-8"") + stream = open(file_name, self.mode, encoding='utf8') + self.name = file_name + self._file = stream + return self._file + + def read(self, n=None): + if self._file is None: + self._open() + return self._file.read(n) + + def write(self, t): + if self._file is None: + self._open() + return self._file.write(t) + + def close(self): + if self._file is not None: + self._file.close() + return None + + def flush(self): + if self._file is None: + return + return self._file.flush() + + def _get_available_file(self): + basename = current_name = self.name + suffix = 0 + while suffix < 2 ** 16: + if not os.path.exists(current_name): + break + elif os.access(current_name, os.W_OK): + break + else: + suffix += 1 + current_name = ""%s.%s"" % (basename, suffix) + if suffix < 2 ** 16: + return current_name + else: + return ""%s.%s"" % (basename, uuid.uuid4().hex) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/cli/validators.py",".py","17283","474","import os +import re +import traceback + +from typing import Mapping, TypeVar, Type, Union + + +import pickle + +from functools import partial + +import click + +from sqlalchemy.exc import OperationalError, ArgumentError +from sqlalchemy.engine.url import _parse_rfc1738_args as parse_engine_uri + +from glycresoft.serialize import ( + DatabaseBoundOperation, GlycanHypothesis, GlycopeptideHypothesis, + SampleRun, Analysis, AnalysisTypeEnum) + +from glycresoft.database.builder.glycan import ( + GlycanCompositionHypothesisMerger, + named_reductions, named_derivatizations) + +from glycresoft.database.builder.glycan.synthesis import synthesis_register +from glycresoft.database.builder.glycopeptide.proteomics import mzid_proteome +from glycresoft.chromatogram_tree import ( + MassShift, Formate, Ammonium, + Sodium, Potassium) + +from glycresoft.tandem.glycopeptide.scoring import ( + binomial_score, simple_score, coverage_weighted_binomial, intensity_scorer, + SpectrumMatcherBase) + +from glycresoft.models import ms1_model_features + +from glycopeptidepy.utils.collectiontools import decoratordict +from glycopeptidepy.structure.modification import ModificationTable + +from glypy import Substituent, Composition + +glycan_source_validators = decoratordict() + +T = TypeVar('T') + + +class ModificationValidator(object): + """"""Determines whether a provided command line argument can be mapped to a + valid peptide modification in a default contructed + :class:`glycopeptidepy.structure.modification.ModificationTable` + + Attributes + ---------- + table : glycopeptidepy.structure.modification.ModificationTable + The modification database to look up modifications by name. + """""" + def __init__(self): + self.table = ModificationTable() + + def validate(self, modification_string): + try: + return self.table[modification_string] + except KeyError: + return False + + +class GlycanSourceValidatorBase(DatabaseBoundOperation): + def __init__(self, database_connection, source, source_type, source_identifier=None): + DatabaseBoundOperation.__init__(self, database_connection) + self.source = source + self.source_type = source_type + self.source_identifier = source_identifier + + def validate(self): + raise NotImplementedError() + + +@glycan_source_validators('text') +@glycan_source_validators('combinatorial') +class TextGlycanSourceValidator(GlycanSourceValidatorBase): + def __init__(self, database_connection, source, source_type, source_identifier=None): + super(TextGlycanSourceValidator, self).__init__( + database_connection, source, source_type, source_identifier) + + def validate(self): + return os.path.exists(self.source) + + +@glycan_source_validators(""hypothesis"") +class HypothesisGlycanSourceValidator(GlycanSourceValidatorBase): + def __init__(self, database_connection, source, source_type, source_identifier=None): + super(HypothesisGlycanSourceValidator, self).__init__( + database_connection, source, source_type, source_identifier) + self.handle = DatabaseBoundOperation(source) + + def validate(self): + if self.source_identifier is None: + click.secho(""No value passed through --glycan-source-identifier."", fg='magenta') + return False + try: + hypothesis_id = int(self.source_identifier) + inst = self.handle.query(GlycanHypothesis).get(hypothesis_id) + return inst is not None + except TypeError: + hypothesis_name = self.source + inst = self.handle.query(GlycanHypothesis).filter(GlycanHypothesis.name == hypothesis_name).first() + return inst is not None + + +@glycan_source_validators(""analysis"") +class GlycanAnalysisGlycanSourceValidator(GlycanSourceValidatorBase): + def __init__(self, database_connection, source, source_type, source_identifier=None): + super(GlycanAnalysisGlycanSourceValidator, self).__init__( + database_connection, source, source_type, source_identifier) + self.handle = DatabaseBoundOperation(source) + + def validate(self): + if self.source_identifier is None: + click.secho(""No value passed through --glycan-source-identifier."", fg='magenta') + return False + try: + analysis_id = int(self.source_identifier) + inst = self.handle.query(Analysis).filter( + Analysis.id == analysis_id, + Analysis.analysis_type == AnalysisTypeEnum.glycan_lc_ms.name) + return inst is not None + except TypeError: + hypothesis_name = self.source + inst = self.handle.query(Analysis).filter( + Analysis.name == hypothesis_name, + Analysis.analysis_type == AnalysisTypeEnum.glycan_lc_ms.name).first() + return inst is not None + + +class GlycanHypothesisCopier(GlycanCompositionHypothesisMerger): + pass + + +def validate_glycan_source(context, database_connection, source, source_type, source_identifier=None): + glycan_source_validator_type = glycan_source_validators[source_type] + glycan_validator = glycan_source_validator_type(database_connection, source, source_type, source_identifier) + if not glycan_validator.validate(): + click.secho(""Could not validate glycan source %s of type %s"" % ( + source, source_type), fg='yellow') + raise click.Abort() + + +def validate_modifications(context, modifications): + mod_validator = ModificationValidator() + for mod in modifications: + if not mod_validator.validate(mod): + click.secho(""Invalid modification '%s'"" % mod, fg='yellow') + raise click.Abort() + + +def validate_unique_name(context, database_connection, name, klass): + handle = DatabaseBoundOperation(database_connection) + obj = handle.query(klass).filter( + klass.name == name).first() + if obj is not None: + return klass.make_unique_name(handle.session, name) + else: + return name + + +validate_glycopeptide_hypothesis_name = partial(validate_unique_name, klass=GlycopeptideHypothesis) +validate_glycan_hypothesis_name = partial(validate_unique_name, klass=GlycanHypothesis) +validate_sample_run_name = partial(validate_unique_name, klass=SampleRun) +validate_analysis_name = partial(validate_unique_name, klass=Analysis) + + +def _resolve_protein_name_list(context, args): + result = [] + for arg in args: + if isinstance(arg, str): + if os.path.exists(arg) and os.path.isfile(arg): + with open(arg) as fh: + for line in fh: + cleaned = line.strip() + if cleaned: + result.append(cleaned) + else: + result.append(arg) + else: + if isinstance(arg, (list, tuple)): + result.extend(arg) + else: + result.append(arg) + return result + + +def validate_mzid_proteins(context, mzid_file, target_proteins=tuple(), target_proteins_re=tuple()): + all_proteins = set(mzid_proteome.protein_names(mzid_file)) + accepted_target_proteins = set() + target_proteins = _resolve_protein_name_list(context, target_proteins) + target_proteins_re = _resolve_protein_name_list(context, target_proteins_re) + for prot in target_proteins: + if prot in all_proteins: + accepted_target_proteins.add(prot) + else: + click.secho(""Could not find protein '%s'"" % prot, fg='yellow') + for prot_re in target_proteins_re: + pat = re.compile(prot_re) + hits = 0 + for prot in all_proteins: + if pat.search(prot): + accepted_target_proteins.add(prot) + hits += 1 + + if hits == 0: + click.secho(""Pattern '%s' did not match any proteins"" % prot_re, fg='yellow') + if len(accepted_target_proteins) == 0: + click.secho(""Using all proteins"", fg='yellow') + return list(accepted_target_proteins) + + +def validate_reduction(context, reduction_string): + if reduction_string is None: + return None + try: + if str(reduction_string).lower() in named_reductions: + return named_reductions[str(reduction_string).lower()] + else: + if len(Composition(str(reduction_string))) > 0: + return str(reduction_string) + else: + raise Exception(""Invalid"") + except Exception: + click.secho(""Could not validate reduction '%s'"" % reduction_string) + raise click.Abort(""Could not validate reduction '%s'"" % reduction_string) + + +def validate_derivatization(context, derivatization_string): + if derivatization_string is None: + return derivatization_string + if derivatization_string in named_derivatizations: + return named_derivatizations[derivatization_string] + subst = Substituent(derivatization_string) + if len(subst.composition) == 0: + click.secho(""Could not validate derivatization '%s'"" % derivatization_string) + raise click.Abort(""Could not validate derivatization '%s'"" % derivatization_string) + else: + return derivatization_string + + +class SubstituentParamType(click.types.StringParamType): + name = ""SUBSTITUENT"" + + def convert(self, value, param, ctx): + t = Substituent(value) + if not t.composition: + raise ValueError(""%s is not a recognized substituent"" % value) + return t + + +mass_shifts = { + ""ammonium"": Ammonium, + ""formate"": Formate, + ""sodium"": Sodium, + ""potassium"": Potassium, +} + + +def validate_mass_shift(mass_shift_string, multiplicity=1): + multiplicity = int(multiplicity) + if mass_shift_string.lower() in mass_shifts: + return (mass_shifts[mass_shift_string.lower()], multiplicity) + else: + try: + mass_shift_string = str(mass_shift_string) + composition = Composition(mass_shift_string) + shift = MassShift(mass_shift_string, composition) + return (shift, multiplicity) + except Exception as e: + click.secho(""%r"" % (e,)) + click.secho(""Could not validate mass_shift %r"" % (mass_shift_string,), fg='yellow') + raise click.Abort(""Could not validate mass_shift %r"" % (mass_shift_string,)) + + +glycopeptide_tandem_scoring_functions = { + ""binomial"": binomial_score.BinomialSpectrumMatcher, + ""simple"": simple_score.SimpleCoverageScorer, + ""coverage_weighted_binomial"": coverage_weighted_binomial.CoverageWeightedBinomialScorer, + ""log_intensity"": intensity_scorer.LogIntensityScorer, + ""penalized_log_intensty"": intensity_scorer.FullSignaturePenalizedLogIntensityScorer, + ""peptide_only_cw_binomial"": coverage_weighted_binomial.StubIgnoringCoverageWeightedBinomialScorer, + ""log_intensity_v3"": (intensity_scorer.LogIntensityScorerReweighted, {}), + ""log_intensity_reweighted"": (intensity_scorer.LogIntensityScorerReweighted, {}), +} + + +def validate_glycopeptide_tandem_scoring_function(context, name): + if isinstance(name, SpectrumMatcherBase): + return name, {} + try: + scorer = glycopeptide_tandem_scoring_functions[name] + if not isinstance(scorer, (tuple, list)): + return scorer, {} + return scorer + except KeyError: + # Custom scorer loading + if name.startswith(""model://""): + path = name[8:] + if not os.path.exists(path): + raise click.Abort(""Model file at \""%s\"" does not exist."" % (path, )) + with open(path, 'rb') as fh: + scorer = pickle.load(fh) + if not isinstance(scorer, (tuple, list)): + return scorer, {} + else: + if len(scorer) == 2 and isinstance(scorer[1], Mapping): + return scorer + else: + raise TypeError( + ""Unpickled scorer contained a tuple, but the second value was not a dictionary!"") + else: + raise click.Abort(""Could not recognize scoring function by name %r"" % (name,)) + + +class ChoiceOrURI(click.Choice): + def get_metavar(self, param): + return ""[%s|model://path]"" % ('|'.join(self.choices), ) + + def get_missing_message(self, param): + choice_str = "",\n\t"".join(self.choices) + return ""Choose from:\n\t%s\nor specify a model://path"" % choice_str + + def convert(self, value, param, ctx): + # Match through normalization and case sensitivity + # first do token_normalize_func, then lowercase + # preserve original `value` to produce an accurate message in + # `self.fail` + normed_value = value + normed_choices = {choice: choice for choice in self.choices} + + if ctx is not None and ctx.token_normalize_func is not None: + normed_value = ctx.token_normalize_func(value) + normed_choices = { + ctx.token_normalize_func(normed_choice): original + for normed_choice, original in normed_choices.items() + } + + if not self.case_sensitive: + normed_value = normed_value.casefold() + normed_choices = { + normed_choice.casefold(): original + for normed_choice, original in normed_choices.items() + } + + if normed_value in normed_choices: + return normed_choices[normed_value] + + if value.startswith(""model://""): + return value + + self.fail( + ""invalid value: {value}. (choose from {choices} or specify a \""model://path\"")"".format( + value=value, choices=', '.join(self.choices)), + param, + ctx, + ) + + +def get_by_name_or_id(session, model_type: Type[T], name_or_id: Union[str, int]) -> T: + try: + object_id = int(name_or_id) + inst = session.query(model_type).get(object_id) + if inst is None: + raise ValueError(""No instance of type %s with id %r"" % + (model_type, name_or_id)) + return inst + except ValueError: + try: + inst = session.query(model_type).filter( + model_type.name == name_or_id).one() + return inst + except Exception: + raise click.BadParameter(""Could not locate an instance of %r with identifier %r"" % ( + model_type.__name__, name_or_id)) + + +def validate_database_unlocked(database_connection): + try: + db = DatabaseBoundOperation(database_connection) + db.session.add(GlycanHypothesis(name=""_____not_real_do_not_use______"")) + db.session.rollback() + return True + except OperationalError: + return False + + +def validate_ms1_feature_name(feature_name): + try: + return ms1_model_features[feature_name] + except KeyError: + raise click.Abort( + ""Could not recognize scoring feature by name %r"" % ( + feature_name,)) + + +def strip_site_root(type, value, tb): + msg = traceback.format_exception(type, value, tb) + sanitized = [] + for i, line in enumerate(msg): + if 'site-packages' in line: + sanitized.append(line.split(""site-packages"")[1]) + else: + sanitized.append(line) + print(''.join(sanitized)) + + +class RelativeMassErrorParam(click.types.FloatParamType): + name = 'PPM MASS ERR' + + def convert(self, value, param, ctx): + value = super(RelativeMassErrorParam, self).convert(value, param, ctx) + if value > 1e-3: + click.secho( + f""Translating {value} PPM -> {value / 1e-6}"", + fg='yellow' + ) + value /= 1e-6 + if value <= 0: + self.fail(""mass error value must be greater than 0."") + return value + + +class DatabaseConnectionParam(click.types.StringParamType): + name = ""CONN"" + + def __init__(self, exists=False): + self.exists = exists + + def convert(self, value, param, ctx): + value = super(DatabaseConnectionParam, self).convert(value, param, ctx) + try: + parse_engine_uri(value) + return value + except ArgumentError: + # not a uri + if self.exists: + if not os.path.exists(value): + raise self.fail( + ""Database file {} does not exist."".format(value), param, ctx) + return value + + +class SmallSampleFDRCorrectionParam(click.ParamType): + name = '0-1.0/on/off/auto' + + error_message_template = ( + ""%s is not a valid option for FDR strategy selection. "" + ""If numerical, it must be between 0 and 1.0, otherwise it must "" + ""be one of auto, on, or off."" + ) + + def convert(self, value, param, ctx): + value = value.lower() + try: + threshold = float(value) + if threshold > 1 or threshold < 0: + self.fail(self.error_message_template % value, param, ctx) + except ValueError: + value = value.strip() + if value == 'auto': + threshold = 0.5 + elif value == 'off': + threshold = 0.0 + elif value == 'on': + threshold = 1.0 + else: + self.fail(self.error_message_template % value, param, ctx) + return threshold +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/cli/build_db.py",".py","34910","721","import sys +import multiprocessing +import click +import textwrap + +from glycresoft.cli.base import cli, HiddenOption + +from glycresoft.cli.validators import ( + glycan_source_validators, + validate_modifications, + validate_glycan_source, + validate_glycopeptide_hypothesis_name, + validate_glycan_hypothesis_name, + get_by_name_or_id, + validate_reduction, + validate_derivatization, + validate_mzid_proteins, + GlycanHypothesisCopier, + DatabaseConnectionParam, + SubstituentParamType) + +from glycresoft.cli.utils import ctxstream + +from glycresoft.serialize import ( + DatabaseBoundOperation, + GlycanHypothesis, + Analysis, + AnalysisTypeEnum) + +from glycresoft.database.builder.glycopeptide.naive_glycopeptide import ( + MultipleProcessFastaGlycopeptideHypothesisSerializer, + ReversingMultipleProcessFastaGlycopeptideHypothesisSerializer, + NonSavingMultipleProcessFastaGlycopeptideHypothesisSerializer) + +from glycresoft.database.builder.glycopeptide.informed_glycopeptide import ( + MultipleProcessMzIdentMLGlycopeptideHypothesisSerializer, + ReversingMultipleProcessMzIdentMLGlycopeptideHypothesisSerializer) + +from glycresoft.database.builder.glycan import ( + TextFileGlycanHypothesisSerializer, + CombinatorialGlycanHypothesisSerializer, + GlycanCompositionHypothesisMerger, + NGlycanGlyspaceHypothesisSerializer, + OGlycanGlyspaceHypothesisSerializer, + TaxonomyFilter, + GlycanAnalysisHypothesisSerializer, + GlycopeptideAnalysisGlycanCompositionExtractionHypothesisSerializer, + SynthesisGlycanHypothesisSerializer) + +from glycresoft.database.prebuilt import hypothesis_register as prebuilt_hypothesis_register + +from glycresoft.database.disk_backed_database import GlycanCompositionDiskBackedStructureDatabase +from glycresoft.database.composition_network import ( + CompositionGraph, GraphWriter, GraphReader, + CompositionRangeRule, + CompositionRatioRule, + CompositionRuleClassifier, + CompositionExpressionRule, + make_n_glycan_neighborhoods, + make_adjacency_neighborhoods, + make_mammalian_n_glycan_neighborhoods) + +from glycresoft.database.builder.glycan.synthesis import synthesis_register + +from glycopeptidepy.enzyme import enzyme_rules +from glycopeptidepy.utils.collectiontools import decoratordict +from glycopeptidepy.structure.modification import RestrictedModificationTable + + +@cli.group('build-hypothesis', short_help='Build search spaces for glycans and glycopeptides') +def build_hypothesis(): + pass + + +command_group = build_hypothesis + + +def database_connection(fn): + arg = click.argument(""database-connection"", doc_help=( + ""A connection URI for a database, or a path on the file system"")) + return arg(fn) + + +_glycan_hypothesis_builders = decoratordict() + + +@_glycan_hypothesis_builders('text') +def _build_glycan_composition_hypothesis_from_text(database_connection, text_file, hypothesis_name, + identifier=None): + if hypothesis_name is not None: + hypothesis_name = hypothesis_name + '-Glycans' + builder = TextFileGlycanHypothesisSerializer( + text_file, database_connection, hypothesis_name=hypothesis_name) + builder.run() + return builder.hypothesis_id + + +@_glycan_hypothesis_builders(""combinatorial"") +def _build_glycan_composition_hypothesis_from_combinatorial(database_connection, text_file, hypothesis_name, + identifier=None): + if hypothesis_name is not None: + hypothesis_name = hypothesis_name + '-Glycans' + builder = CombinatorialGlycanHypothesisSerializer( + text_file, database_connection, hypothesis_name=hypothesis_name) + builder.run() + return builder.hypothesis_id + + +@_glycan_hypothesis_builders(""hypothesis"") +def _copy_hypothesis_across_file_boundaries(database_connection, source, hypothesis_name, + identifier=None): + source_handle = DatabaseBoundOperation(source) + source_hypothesis_id = None + source_hypothesis_name = None + + try: + hypothesis_id = int(identifier) + inst = source_handle.query(GlycanHypothesis).get(hypothesis_id) + if inst is not None: + source_hypothesis_id = hypothesis_id + source_hypothesis_name = inst.name + + except TypeError: + hypothesis_name = identifier + inst = source_handle.query(GlycanHypothesis).filter( + GlycanHypothesis.name == hypothesis_name).first() + if inst is not None: + source_hypothesis_id = inst.id + source_hypothesis_name = inst.name + + if source == database_connection: + return source_hypothesis_id + + mover = GlycanHypothesisCopier( + database_connection, [(source, source_hypothesis_id)], + hypothesis_name=source_hypothesis_name) + mover.run() + return mover.hypothesis_id + + +@_glycan_hypothesis_builders(""analysis"") +def _copy_analysis_across_file_boundaries(database_connection, source, hypothesis_name, + identifier=None): + source_handle = DatabaseBoundOperation(source) + source_analysis_id = None + source_analysis_name = None + try: + hypothesis_id = int(identifier) + inst = source_handle.query(Analysis).get(hypothesis_id) + if inst is not None: + source_analysis_id = hypothesis_id + source_analysis_name = inst.name + + except TypeError: + hypothesis_name = identifier + inst = source_handle.query(Analysis).filter( + Analysis.name == hypothesis_name).first() + if inst is not None: + source_analysis_id = inst.id + source_analysis_name = inst.name + if hypothesis_name is None: + hypothesis_name = source_analysis_name + mover = GlycanAnalysisHypothesisSerializer( + source, source_analysis_id, hypothesis_name, + database_connection) + mover.run() + return mover.hypothesis_id + + +def _validate_glycan_source_identifier(ctx, param, value): + try: + if ctx.params['glycan_source_type'] not in (""hypothesis"", ""analysis"") and value: + width = click.get_terminal_size()[0] + click.secho('\n'.join( + textwrap.wrap( + ""Warning: --glycan-source-identifier specified when "" + ""--glycan-source is neither \""hypothesis\"" nor \""analysis\""."" + "" Its value will be ignored."", width=int(width * 0.6))), fg='yellow') + return None + else: + return value + except KeyError: + click.secho(""Specify --glycan-source before --glycan-source-identifier."", fg='yellow') + + +def glycopeptide_hypothesis_common_options(cmd): + options = [ + click.option(""-u"", ""--occupied-glycosites"", type=int, default=1, + help=(""The number of occupied glycosylation sites permitted."")), + click.option(""-n"", ""--name"", default=None, help=""The name for the hypothesis to be created""), + click.option(""-p"", ""--processes"", 'processes', type=click.IntRange(1, multiprocessing.cpu_count()), + default=min(multiprocessing.cpu_count(), 4), + help=('Number of worker processes to use. Defaults to 4 ' + 'or the number of CPUs, whichever is lower')), + click.option(""-G"", ""--glycan-source-identifier"", required=False, default=None, + help=(""The name or id number of the hypothesis or analysis to"" + "" be used when using those glycan source types.""), + callback=_validate_glycan_source_identifier), + click.option(""-s"", ""--glycan-source-type"", default='text', type=click.Choice( + list(glycan_source_validators.keys())), + help=""The type of glycan information source to use""), + click.option(""-g"", ""--glycan-source"", required=True, + help=""The path, identity, or other specifier for the glycan source""), + click.option(""-z"", ""--peptide-length-range"", type=(int, int), default=(5, 60), + help=""The minimum and maximum peptide length to consider"") + ] + for opt in options: + cmd = opt(cmd) + return cmd + + +@build_hypothesis.command(""glycopeptide-fa"", + short_help=""Build glycopeptide search spaces with a FASTA file of proteins"") +@click.pass_context +@glycopeptide_hypothesis_common_options +@click.argument(""fasta-file"", type=click.Path(exists=True), doc_help=( + ""A file containing protein sequences in FASTA format"")) +@database_connection +@click.option(""-e"", ""--enzyme"", default=['trypsin'], multiple=True, + help=( + 'The proteolytic enzyme to use during digestion. May be specified multiple' + ' times, generating a co-digestion. May specify an enzyme name or a regular' + ' expression describing the cleavage pattern. Recognized enzyme names are: ' + + ', '.join(sorted(enzyme_rules)))) +@click.option(""-m"", ""--missed-cleavages"", type=int, default=1, + help=""The number of missed proteolytic cleavage sites permitted"") +@click.option(""-c"", ""--constant-modification"", multiple=True, + help='Peptide modification rule which will be applied constantly') +@click.option(""-v"", ""--variable-modification"", multiple=True, + help='Peptide modification rule which will be applied variablely') +@click.option(""-V"", ""--max-variable-modifications"", type=int, default=4, required=False, + help=(""The maximum number of variable modifications that can be applied to a single peptide"")) +@click.option(""-y"", ""--semispecific-digest"", is_flag=True, help=( + ""Apply a semispecific enzyme digest permitting one peptide terminal to be non-specific"")) +@click.option(""-R"", ""--reverse"", default=False, is_flag=True, help='Reverse protein sequences') +@click.option(""--dry-run"", default=False, is_flag=True, help=""Do not save glycopeptides"", cls=HiddenOption) +@click.option(""-F"", ""--not-full-crossproduct"", is_flag=True, help=( + ""Do not produce full crossproduct. For when the search space is too large to enumerate, store, and load."")) +@click.option(""--retain-all-peptides"", is_flag=True, default=False, + help=(""Do not require a glycosylation site when saving base peptides"")) +@click.option(""-C"", ""--include-n-x-c-glycosylation"", ""include_cysteine_n_glycosylation"", default=False, is_flag=True, + help=""Whether to support N-x-C in the N-glycosylation sequon"") +@click.option(""-a"", ""--annotation-path"", type=click.Path(exists=True, allow_dash=True), required=False, + default=None, help=""The path to an annotation XML file from UniProt, or '-' to suppress annotations."") +def glycopeptide_fa(context, fasta_file, database_connection, enzyme, missed_cleavages, occupied_glycosites, name, + constant_modification, variable_modification, processes, glycan_source, glycan_source_type, + glycan_source_identifier=None, semispecific_digest=False, reverse=False, dry_run=False, + peptide_length_range=(5, 60), not_full_crossproduct=False, max_variable_modifications=4, + retain_all_peptides=False, include_cysteine_n_glycosylation: bool=False, annotation_path=None): + '''Constructs a glycopeptide hypothesis from a FASTA file of proteins and a + collection of glycans. + ''' + if reverse: + task_type = ReversingMultipleProcessFastaGlycopeptideHypothesisSerializer + click.secho(""Using ReversingMultipleProcessFastaGlycopeptideHypothesisSerializer"", fg='yellow') + elif dry_run: + task_type = NonSavingMultipleProcessFastaGlycopeptideHypothesisSerializer + click.secho(""Using NonSavingMultipleProcessFastaGlycopeptideHypothesisSerializer"", fg='yellow') + else: + task_type = MultipleProcessFastaGlycopeptideHypothesisSerializer + + validate_modifications( + context, constant_modification + variable_modification) + validate_glycan_source(context, database_connection, + glycan_source, glycan_source_type, + glycan_source_identifier) + + processes = min(multiprocessing.cpu_count(), processes) + + if name is not None: + name = validate_glycopeptide_hypothesis_name( + context, database_connection, name) + click.secho(""Building Glycopeptide Hypothesis %s"" % name, fg='cyan') + mt = RestrictedModificationTable( + None, constant_modification, variable_modification) + constant_modification = [mt[c] for c in constant_modification] + variable_modification = [mt[c] for c in variable_modification] + + glycan_hypothesis_id = _glycan_hypothesis_builders[ + glycan_source_type](database_connection, glycan_source, name, glycan_source_identifier) + + builder = task_type( + fasta_file, database_connection, + glycan_hypothesis_id=glycan_hypothesis_id, + protease=enzyme, + constant_modifications=constant_modification, + variable_modifications=variable_modification, + max_missed_cleavages=missed_cleavages, + max_glycosylation_events=occupied_glycosites, + hypothesis_name=name, + semispecific=semispecific_digest, + n_processes=processes, + full_cross_product=not not_full_crossproduct, + max_variable_modifications=max_variable_modifications, + peptide_length_range=peptide_length_range, + require_glycosylation_sites=not retain_all_peptides, + include_cysteine_n_glycosylation=include_cysteine_n_glycosylation, + uniprot_source_file=annotation_path) + builder.display_header() + builder.start() + return builder.hypothesis_id + + +@build_hypothesis.command(""glycopeptide-mzid"", + short_help=""Build a glycopeptide search space with an mzIdentML file"") +@click.pass_context +@click.argument(""mzid-file"", type=click.Path(exists=True)) +@database_connection +@glycopeptide_hypothesis_common_options +@click.option(""-t"", ""--target-protein"", multiple=True, + help='Specifies the name of a protein to include in the hypothesis, or a file containing such' + ', one per line. May be used many times.') +@click.option('-r', '--target-protein-re', multiple=True, + help=('Specifies a regular expression to select proteins' + ' to be included by name. May be used many times.')) +@click.option(""--reference-fasta"", default=None, required=False, + help=(""When the full sequence for each protein is not embedded in the mzIdentML file and "" + ""the FASTA file used is not local."")) +@click.option(""-a"", ""--annotation-path"", type=click.Path(exists=True, allow_dash=True), required=False, + default=None, help=""The path to an annotation XML file from UniProt or '-' to suppress loading annotations"") +@click.option(""-R"", ""--reverse"", default=False, is_flag=True, help='Reverse protein sequences') +@click.option(""-F"", ""--not-full-crossproduct"", is_flag=True, help=( + ""Do not produce full crossproduct. For when the search space is too large to enumerate, store, and load."")) +def glycopeptide_mzid(context, mzid_file, database_connection, name, occupied_glycosites, target_protein, + target_protein_re, processes, glycan_source, glycan_source_type, glycan_source_identifier, + reference_fasta, peptide_length_range=(5, 60), annotation_path=None, reverse=False, + not_full_crossproduct=False): + """""" + Constructs a glycopeptide hypothesis from a MzIdentML file of proteins and a + collection of glycans. + """""" + proteins = validate_mzid_proteins( + context, mzid_file, target_protein, target_protein_re) + validate_glycan_source(context, database_connection, + glycan_source, glycan_source_type, + glycan_source_identifier) + + processes = min(multiprocessing.cpu_count(), processes) + + if name is not None: + name = validate_glycopeptide_hypothesis_name( + context, database_connection, name) + click.secho(""Building Glycopeptide Hypothesis %s"" % name, fg='cyan') + + glycan_hypothesis_id = _glycan_hypothesis_builders[ + glycan_source_type](database_connection, glycan_source, name, glycan_source_identifier) + + job_cls = MultipleProcessMzIdentMLGlycopeptideHypothesisSerializer + if reverse: + job_cls = ReversingMultipleProcessMzIdentMLGlycopeptideHypothesisSerializer + + builder = job_cls( + mzid_file, database_connection, + glycan_hypothesis_id=glycan_hypothesis_id, + hypothesis_name=name, + target_proteins=proteins, + max_glycosylation_events=occupied_glycosites, + reference_fasta=reference_fasta, + n_processes=processes, + peptide_length_range=peptide_length_range, + uniprot_source_file=annotation_path, + full_cross_product=not not_full_crossproduct + ) + builder.display_header() + builder.start() + return builder.hypothesis_id + + +@build_hypothesis.command(""glycan-text"", + short_help='Build a glycan search space with a text file of glycan compositions') +@click.pass_context +@click.argument(""text-file"", type=click.Path(exists=True)) +@database_connection +@click.option(""-r"", ""--reduction"", default=None, help='Reducing end modification') +@click.option(""-d"", ""--derivatization"", default=None, help='Chemical derivatization to apply') +@click.option(""-n"", ""--name"", default=None, help=""The name for the hypothesis to be created"") +def glycan_text(context, text_file, database_connection, reduction, derivatization, name): + if name is not None: + name = validate_glycan_hypothesis_name(context, database_connection, name) + click.secho(""Building Glycan Hypothesis %s"" % name, fg='cyan') + reduction = validate_reduction(context, reduction) + derivatization = validate_derivatization(context, derivatization) + builder = TextFileGlycanHypothesisSerializer( + text_file, database_connection, reduction=reduction, derivatization=derivatization, + hypothesis_name=name) + builder.display_header() + builder.start() + + +@build_hypothesis.command(""glycan-combinatorial"", short_help=('Build a glycan search space with a text file' + ' containing algebraic combination rules')) +@click.pass_context +@click.argument(""rule-file"", type=click.Path(exists=True)) +@database_connection +@click.option(""-r"", ""--reduction"", default=None, help='Reducing end modification') +@click.option(""-d"", ""--derivatization"", default=None, help='Chemical derivatization to apply') +@click.option(""-n"", ""--name"", default=None, help=""The name for the hypothesis to be created"") +@click.option(""-c"", ""--glycan-type"", default=None, required=False, + type=click.Choice(['n-glycan', 'o-glycan', 'gag-linker'], case_sensitive=False), + help=""The glycan classification to apply to all generated glycan compositions."" + "" If not set, a heuristic will be used to guess if a composition in an N-glycan."" + "" This is only relevant when building a glycopeptide hypothesis."") +def glycan_combinatorial(context, rule_file, database_connection, reduction, derivatization, name, + glycan_type=None): + if name is not None: + name = validate_glycan_hypothesis_name(context, database_connection, name) + click.secho(""Building Glycan Hypothesis %s"" % name, fg='cyan') + reduction = validate_reduction(context, reduction) + derivatization = validate_derivatization(context, derivatization) + builder = CombinatorialGlycanHypothesisSerializer( + rule_file, database_connection, reduction=reduction, derivatization=derivatization, + hypothesis_name=name, glycan_type=glycan_type) + builder.display_header() + builder.start() + + +@build_hypothesis.command(""merge-glycan"", short_help=(""Combine two or more glycan search spaces to create a "" + ""new one containing unique entries from all constituents"")) +@click.pass_context +@database_connection +@click.option(""-n"", ""--name"", default=None, help=""The name for the hypothesis to be created"") +@click.option( + ""-i"", ""--hypothesis-specification"", multiple=True, + nargs=2, help=(""The location and identity for the hypothesis to"" + "" include. May be specified many times"")) +def merge_glycan_hypotheses(context, database_connection, hypothesis_specification, name): + database_connection = DatabaseBoundOperation(database_connection) + hypothesis_ids = [] + for connection, ident in hypothesis_specification: + hypothesis = get_by_name_or_id(DatabaseBoundOperation(connection), GlycanHypothesis, ident) + hypothesis_ids.append((connection, hypothesis.id)) + + if name is not None: + name = validate_glycan_hypothesis_name(context, database_connection._original_connection, name) + click.secho(""Building Glycan Hypothesis %s"" % name, fg='cyan') + + task = GlycanCompositionHypothesisMerger( + database_connection._original_connection, hypothesis_ids, name) + task.display_header() + task.start() + + +@build_hypothesis.command(""glycan-glyspace"", short_help=(""Construct a glycan hypothesis from GlySpace"")) +@click.pass_context +@database_connection +@click.option(""-r"", ""--reduction"", default=None, help='Reducing end modification') +@click.option(""-d"", ""--derivatization"", default=None, help='Chemical derivatization to apply') +@click.option(""-n"", ""--name"", default=None, help=""The name for the hypothesis to be created"") +@click.option(""-m"", ""--motif-class"", type=click.Choice([""n-linked"", ""o-linked""]), default=None, + help=""Specify a glycan structure family to search for"") +@click.option(""-t"", ""--target-taxon"", default=None, help=""Only select structures annotated with this taxonomy"") +@click.option(""-i"", ""--include-children"", default=False, is_flag=True, + help=""Include child taxa of --target-taxon. No effect otherwise."") +@click.option(""-s"", ""--detatch-substituent"", multiple=True, type=SubstituentParamType(), + help='Substituent type to detatch from all monosaccharides') +def glyspace_glycan_hypothesis(context, database_connection, motif_class, reduction, derivatization, name, + target_taxon=None, include_children=False, detatch_substituent=None): + database_connection = DatabaseBoundOperation(database_connection) + if name is not None: + name = validate_glycan_hypothesis_name(context, database_connection._original_connection, name) + click.secho(""Building Glycan Hypothesis %s"" % name, fg='cyan') + filter_funcs = [] + + if target_taxon is not None: + filter_funcs.append(TaxonomyFilter(target_taxon, include_children)) + + serializer_type = None + if motif_class == ""n-linked"": + serializer_type = NGlycanGlyspaceHypothesisSerializer + elif motif_class == ""o-linked"": + serializer_type = OGlycanGlyspaceHypothesisSerializer + + reduction = validate_reduction(context, reduction) + derivatization = validate_derivatization(context, derivatization) + job = serializer_type( + database_connection._original_connection, name, reduction, derivatization, filter_funcs, + simplify=True, substituents_to_detatch=detatch_substituent) + job.display_header() + job.start() + + +@build_hypothesis.command(""glycan-from-analysis"", short_help=(""Construct a glycan hypothesis from a matched analysis"")) +@click.pass_context +@database_connection +@click.argument(""analysis-connection"", type=DatabaseConnectionParam(exists=True)) +@click.argument(""analysis-identifier"") +@click.option(""-r"", ""--reduction"", default=None, help='Reducing end modification') +@click.option(""-d"", ""--derivatization"", default=None, help='Chemical derivatization to apply') +@click.option(""-n"", ""--name"", default=None, help=""The name for the hypothesis to be created"") +def from_analysis(context, database_connection, analysis_connection, analysis_identifier, + reduction, derivatization, name): + database_connection = DatabaseBoundOperation(database_connection) + if name is not None: + name = validate_glycan_hypothesis_name(context, database_connection._original_connection, name) + click.secho(""Building Glycan Hypothesis %s"" % name, fg='cyan') + reduction = validate_reduction(context, reduction) + derivatization = validate_derivatization(context, derivatization) + + analysis_connection = DatabaseBoundOperation(analysis_connection) + analysis = get_by_name_or_id(analysis_connection.session, Analysis, analysis_identifier) + if analysis.analysis_type == AnalysisTypeEnum.glycan_lc_ms: + job = GlycanAnalysisHypothesisSerializer( + analysis_connection._original_connection, analysis.id, name, + output_connection=database_connection._original_connection) + job.display_header() + job.start() + elif analysis.analysis_type == AnalysisTypeEnum.glycopeptide_lc_msms: + job = GlycopeptideAnalysisGlycanCompositionExtractionHypothesisSerializer( + analysis_connection._original_connection, analysis.id, name, + output_connection=database_connection._original_connection) + job.display_header() + job.start() + else: + click.secho(""Analysis Type %r could not be converted"" % ( + analysis.analysis_type.name,), fg='red') + + +@build_hypothesis.command(""prebuilt-glycan"", short_help=( + 'Construct a glycan hypothesis from a list of pre-made recipes')) +@click.pass_context +@database_connection +@click.option(""-p"", ""--recipe-name"", type=click.Choice(prebuilt_hypothesis_register.keys()), required=True) +@click.option(""-n"", ""--name"", default=None, help=""The name for the hypothesis to be created"") +@click.option(""-r"", ""--reduction"", default=None, help='Reducing end modification') +@click.option(""-d"", ""--derivatization"", default=None, help='Chemical derivatization to apply') +def prebuilt_glycan(context, database_connection, recipe_name, name, reduction, derivatization): + database_connection = DatabaseBoundOperation(database_connection) + reduction = validate_reduction(context, reduction) + derivatization = validate_derivatization(context, derivatization) + if name is not None: + name = validate_glycan_hypothesis_name( + context, database_connection._original_connection, name) + recipe = prebuilt_hypothesis_register[recipe_name]() + recipe(database_connection._original_connection, + hypothesis_name=name, reduction=reduction, + derivatization=derivatization) + + +@build_hypothesis.command( + ""glycan-synthesis"", + short_help='Construct a glycan hypothesis from a set of biosynthetic pathways') +@click.pass_context +@database_connection +@click.option(""-n"", ""--name"", default=None, help=""The name for the hypothesis to be created"") +@click.option(""-r"", ""--reduction"", default=None, help='Reducing end modification') +@click.option(""-d"", ""--derivatization"", default=None, help='Chemical derivatization to apply') +@click.option(""-w"", ""--pathway-type"", default='human-n-glycan', type=click.Choice([ + 'mammalian-n-glycan', 'human-n-glycan', + 'human-o-glycan', 'mammalian-o-glycan']), help=( + 'The default pathway template to use, and the glycan class annotation type.')) +@click.option('-m', '--maximum-size', default=26, type=int, + help='The maximum number of residues to allow in a single glycan') +@click.option('-e', ""--remove-enzyme"", ""removed_enzymes"", multiple=True) +@click.option('-a', ""--add-enzyme"", ""added_enzymes"", multiple=True) +@click.option(""-p"", ""--processes"", 'processes', type=click.IntRange(1, multiprocessing.cpu_count()), + default=min(multiprocessing.cpu_count(), 4), + help=('Number of worker processes to use. Defaults to 4 ' + 'or the number of CPUs, whichever is lower')) +def glycan_synthesis(context, database_connection, name, pathway_type, removed_enzymes, added_enzymes, + maximum_size, reduction, derivatization, processes): + pathway = synthesis_register[pathway_type](n_processes=processes) + pathway.add_limit(pathway.size_limiter_type(maximum_size)) + for enzyme_to_remove in removed_enzymes: + pathway.remove_enzyme(enzyme_to_remove) + for enzyme_to_add in added_enzymes: + click.echo(""Adding enzymes is unsupported at this time"") + task = SynthesisGlycanHypothesisSerializer( + pathway, database_connection, + hypothesis_name=name, reduction=reduction, derivatization=derivatization) + task.start() + + +@build_hypothesis.group(""glycan-network"", short_help='Build and manipulate glycan network definitions') +def glycan_network_tools(): + pass + + +@glycan_network_tools.command(""build-network"", short_help=( + ""Build a glycan network for an existing glycan hypothesis"")) +@click.pass_context +@database_connection +@click.argument(""hypothesis-identifier"", doc_help=( + ""The ID number or name of the glycan hypothesis to use"")) +@click.option(""-o"", ""--output-path"", type=click.Path( + file_okay=True, dir_okay=False, writable=True), default=None, + help='Path to write to instead of stdout') +@click.option(""-e"", ""--edge-strategy"", type=click.Choice([""manhattan"", ]), default='manhattan', + help=""Strategy to use to decide when two nodes are connected by an edge"") +def glycan_network(context, database_connection, hypothesis_identifier, edge_strategy, output_path): + conn = DatabaseBoundOperation(database_connection) + hypothesis = get_by_name_or_id(conn, GlycanHypothesis, hypothesis_identifier) + if output_path is None: + output_stream = ctxstream(sys.stdout) + else: + output_stream = open(output_path, 'w') + with output_stream: + db = GlycanCompositionDiskBackedStructureDatabase( + database_connection, hypothesis.id) + glycans = list(db) + graph = CompositionGraph(glycans) + if edge_strategy == 'manhattan': + graph.create_edges(1) + else: + raise click.ClickException( + ""Could not find edge strategy %r"" % (edge_strategy,)) + GraphWriter(graph, output_stream) + + +@glycan_network_tools.command(""add-prebuilt-neighborhoods"", short_help=( + ""Add a set of neighborhoods with built-in rules"")) +@click.pass_context +@click.option(""-i"", ""--input-path"", type=click.Path(dir_okay=False), default=None) +@click.option(""-o"", ""--output-path"", type=click.Path(dir_okay=False, writable=True), + default=None) +@click.option(""-n"", ""--name"", help='Set the neighborhood name', type=click.Choice( + [""n-glycan"", ""mammalian-n-glycan"", ]), required=True) +def add_prebuild_neighborhoods_to_network(context, input_path, output_path, name): + if input_path is None: + input_stream = ctxstream(sys.stdin) + else: + input_stream = open(input_path, 'r') + with input_stream: + graph = GraphReader(input_stream).network + if name == 'n-glycan': + neighborhoods = make_n_glycan_neighborhoods() + elif name == 'mammalian-n-glycan': + neighborhoods = make_mammalian_n_glycan_neighborhoods() + else: + raise LookupError(name) + for n in neighborhoods: + graph.neighborhoods.add(n) + if output_path is None: + output_stream = ctxstream(sys.stdout) + else: + output_stream = open(output_path, 'w') + with output_stream: + GraphWriter(graph, output_stream) + + +@glycan_network_tools.command(""add-neighborhood"", short_help=( + 'Add a neighborhood definition to a glycan network')) +@click.pass_context +@click.option(""-i"", ""--input-path"", type=click.Path(dir_okay=False), default=None) +@click.option(""-o"", ""--output-path"", type=click.Path(dir_okay=False, writable=True), + default=None) +@click.option(""-n"", ""--name"", help='Set the neighborhood name', required=True) +@click.option(""-r"", ""--range-rule"", nargs=4, multiple=True, help=( + ""Format: "" +)) +@click.option(""-e"", ""--expression-rule"", nargs=2, multiple=True, help=( + ""Format: "" +)) +@click.option(""-a"", ""--ratio-rule"", nargs=4, multiple=True, help=( + ""Format: "" +)) +def add_neighborhood_to_network(context, input_path, output_path, name, range_rule, expression_rule, ratio_rule): + if input_path is None: + input_stream = ctxstream(sys.stdin) + else: + input_stream = open(input_path, 'r') + with input_stream: + graph = GraphReader(input_stream).network + if name in graph.neighborhoods: + click.secho( + ""This network already has a neighborhood called %s, overwriting"" % name, + fg='yellow', err=True) + rules = [] + for rule in range_rule: + expr, lo, hi, req = rule + lo = int(lo) + hi = int(hi) + req = req.lower().strip() in ('true', 'yes', '1') + rules.append(CompositionRangeRule(expr, lo, hi, req)) + for rule in expression_rule: + expr, req = rule + req = req.lower().strip() in ('true', 'yes', '1') + rules.append(CompositionExpressionRule(expr, req)) + for rule in ratio_rule: + numer, denom, threshold, req = rule + threshold = float(threshold) + req = req.lower().strip() in ('true', 'yes', '1') + rules.append(CompositionRatioRule(numer, denom, threshold, req)) + graph.neighborhoods.add(CompositionRuleClassifier(name, rules)) + if output_path is None: + output_stream = ctxstream(sys.stdout) + else: + output_stream = open(output_path, 'w') + with output_stream: + GraphWriter(graph, output_stream) + + +@glycan_network_tools.command(""remove-neighborhood"", short_help=( + 'Remove a neighborhood definition to a glycan network')) +@click.pass_context +@click.option(""-i"", ""--input-path"", type=click.Path(dir_okay=False), default=None) +@click.option(""-o"", ""--output-path"", type=click.Path(dir_okay=False, writable=True), + default=None) +@click.option(""-n"", ""--name"", help='Set the neighborhood name', required=True) +def remove_neighborhood(context, input_path, output_path, name): + if input_path is None: + input_stream = ctxstream(sys.stdin) + else: + input_stream = open(input_path, 'r') + with input_stream: + graph = GraphReader(input_stream).network + try: + graph.neighborhoods.remove(name) + except KeyError: + click.secho( + ""No neighborhood with name %r was found"" % name, err=True, fg='yellow') + if output_path is None: + output_stream = ctxstream(sys.stdout) + else: + output_stream = open(output_path, 'w') + with output_stream: + GraphWriter(graph, output_stream) + + +if __name__ == '__main__': + cli.main() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/cli/tools.py",".py","20713","598","import sys +import cmd +import csv +import threading +import code +import pprint + +from queue import Queue, Empty + +import click +import pkg_resources + +from glypy.structure.glycan_composition import HashableGlycanComposition +from glycopeptidepy.io import fasta, uniprot +from glycopeptidepy.structure.residue import UnknownAminoAcidException + +from .base import cli +from .validators import RelativeMassErrorParam, get_by_name_or_id + +from glycresoft.serialize import ( + DatabaseBoundOperation, GlycanHypothesis, GlycopeptideHypothesis, + SampleRun, Analysis, Protein, Peptide, Glycopeptide, GlycanClass, + GlycanComposition, func, FileBlob) + +from glycresoft.database import ( + GlycopeptideDiskBackedStructureDatabase, + GlycanCompositionDiskBackedStructureDatabase) + +from glycresoft.database.builder.glycopeptide.proteomics import mzid_proteome +from glycresoft.database.builder.glycopeptide.proteomics.uniprot import UniprotProteinDownloader + + +@cli.group(""tools"", short_help=""Odds and ends to help inspect data and diagnose issues"") +def tools(): + pass + + +def database_connection(fn): + arg = click.argument(""database-connection"", doc_help=( + ""A connection URI for a database, or a path on the file system""), + type=DatabaseBoundOperation) + return arg(fn) + + +def hypothesis_identifier(hypothesis_type): + def wrapper(fn): + arg = click.argument(""hypothesis-identifier"", doc_help=( + ""The ID number or name of the %s hypothesis to use"" % (hypothesis_type,))) + return arg(fn) + return wrapper + + +def analysis_identifier(fn): + arg = click.argument(""analysis-identifier"", doc_help=( + ""The ID number or name of the analysis to use"")) + return arg(fn) + + +@tools.command(""list"", short_help='List names and ids of collections in the database') +@click.pass_context +@database_connection +def list_contents(context, database_connection): + click.echo(""Glycan Hypothesis"") + for hypothesis in database_connection.query(GlycanHypothesis): + click.echo(""\t%d\t%s\t%s"" % (hypothesis.id, hypothesis.name, hypothesis.uuid)) + + click.echo(""\nGlycopeptide Hypothesis"") + for hypothesis in database_connection.query(GlycopeptideHypothesis): + click.echo(""\t%d\t%s\t%s\t%d"" % (hypothesis.id, hypothesis.name, hypothesis.uuid, + hypothesis.glycan_hypothesis.id)) + + click.echo(""\nSample Run"") + for run in database_connection.query(SampleRun): + click.echo(""\t%d\t%s\t%s"" % (run.id, run.name, run.uuid)) + + click.echo(""\nAnalysis"") + for analysis in database_connection.query(Analysis): + click.echo(""\t%d\t%s\t%s"" % (analysis.id, analysis.name, analysis.sample_run.name)) + + click.echo(""\nFile Blobs"") + for blob in database_connection.query(FileBlob): + click.echo(""\t%d\t%s"" % (blob.id, blob.name)) + + +@tools.command('mzid-proteins', short_help='Extract proteins from mzIdentML files') +@click.argument(""mzid-file"") +def list_protein_names(mzid_file): + for name in mzid_proteome.protein_names(mzid_file): + click.echo(name) + + +class SQLShellInterpreter(cmd.Cmd): + prompt = '[sql-shell] ' + + def __init__(self, session, *args, **kwargs): + self.session = session + cmd.Cmd.__init__(self, *args, **kwargs) + + def postcmd(self, stop, line): + if line == ""quit"": + return True + return False + + def precmd(self, line): + tokens = line.split("" "") + tokens[0] = tokens[0].lower() + return ' '.join(tokens) + + def _print_table(self, result): + rows = list(result) + if len(rows) == 0: + return + sizes = [0] * len(rows[0]) + titles = rows[0].keys() + str_rows = [] + for row in rows: + str_row = [] + for i, col in enumerate(row): + col = repr(col) + col_len = len(col) + if sizes[i] < col_len: + sizes[i] = col_len + str_row.append(col) + str_rows.append(str_row) + print("" | "".join(titles)) + for row in str_rows: + print(' | '.join(row)) + + def _to_csv(self, rows, fh): + titles = rows[0].keys() + writer = csv.writer(fh) + writer.writerow(titles) + writer.writerows(rows) + + def do_export(self, line): + try: + fname, line = line.rsplit("";"", 1) + if len(fname.strip()) == 0 or len(line.strip()) == 0: + raise ValueError() + try: + result = self.session.execute(""select "" + line) + except Exception as e: + print(str(e)) + self.session.rollback() + return + try: + rows = list(result) + print(""%d rows selected; Writing to %r"" % (len(rows), fname)) + with open(fname, 'wb') as handle: + self._to_csv(rows, handle) + except Exception as e: + print(str(e)) + + except ValueError: + print(""Could not determine the file name to export to."") + print(""Usage: export ; "") + + def do_execsql(self, line): + try: + result = self.session.execute(line) + self._print_table(result) + + except Exception as e: + print(str(e)) + self.session.rollback() + return False + + def do_explain(self, line): + try: + result = self.session.execute(""explain "" + line) + self._print_table(result) + + except Exception as e: + print(str(e)) + self.session.rollback() + return False + + def do_select(self, line): + try: + result = self.session.execute(""select "" + line) + self._print_table(result) + + except Exception as e: + print(str(e)) + self.session.rollback() + return False + + def do_quit(self, line): + return True + + +@tools.command(""sql-shell"", + short_help=(""A minimal SQL command shell for running "" + ""diagnostics and exporting arbitrary data."")) +@click.argument(""database-connection"") +@click.option(""-s"", ""--script"", default=None) +def sql_shell(database_connection, script=None): + db = DatabaseBoundOperation(database_connection) + session = db.session() # pylint: disable=not-callable + interpreter = SQLShellInterpreter(session) + if script is None: + interpreter.cmdloop() + else: + result = session.execute(script) + interpreter._to_csv(list(result), sys.stdout) + + +@tools.command(""validate-fasta"", short_help=""Validates a FASTA file, checking a few errors."") +@click.argument(""path"") +def validate_fasta(path): + with open(path, ""r"") as handle: + n_deflines = 0 + for line in handle: + if line.startswith("">""): + n_deflines += 1 + with open(path, 'r') as handle: + n_entries = 0 + for entry in fasta.FastaFileParser(handle): + n_entries += 1 + if n_entries != n_deflines: + click.secho(""%d\"">\"" prefixed lines found, but %d entries parsed"" % (n_deflines, n_entries)) + else: + click.echo(""%d Protein Sequences"" % (n_entries, )) + n_glycoprots = 0 + o_glycoprots = 0 + with open(path, 'r') as handle: + invalid_sequences = [] + for entry in fasta.FastaFileParser(handle): + try: + seq = fasta.ProteinSequence(entry['name'], entry['sequence']) + n_glycoprots += bool(seq.n_glycan_sequon_sites) + o_glycoprots += bool(seq.o_glycan_sequon_sites) + except UnknownAminoAcidException as e: + invalid_sequences.append((entry['name'], e)) + click.echo(""Proteins with N-Glycosites: %d"" % n_glycoprots) + for name, error in invalid_sequences: + click.secho(""%s had %s"" % (name, error), fg='yellow') + + +@tools.command(""validate-glycan-text"", short_help=""Validates a text file of glycan compositions"") +@click.argument(""path"") +def validate_glycan_text(path): + from glycresoft.database.builder.glycan.glycan_source import TextFileGlycanCompositionLoader + with open(path, 'r') as handle: + loader = TextFileGlycanCompositionLoader(handle) + n = 0 + glycan_classes = set() + residues = set() + unresolved = set() + for line in loader: + n += 1 + glycan_classes.update(line[1]) + glycan_composition = HashableGlycanComposition.parse(line[0]) + for residue in glycan_composition.keys(): + if residue.mass() == 0: + unresolved.add(residue) + residues.add(residue) + click.secho(""%d glycan compositions"" % (n,)) + click.secho(""Residues:"") + for residue in residues: + click.secho(""\t%s - %f"" % (str(residue), residue.mass())) + if unresolved: + click.secho(""Unresolved Residues:"", fg='yellow') + click.secho(""\n"".join(str(r) for r in unresolved), fg='yellow') + + +def has_known_glycosylation(accession): + try: + prot = uniprot.get(accession) + if ""Glycoprotein"" in prot.keywords: + return True + else: + # for feature in prot.features: + # if isinstance(feature, uniprot.GlycosylationSite): + # return True + pass + return False + except Exception: + return False + + +@tools.command(""known-glycoproteins"", short_help=( + 'Checks UniProt to see if a list of proteins contains any known glycoproteins')) +@click.option(""-i"", ""--file-path"", help=""Read input from a file instead of STDIN"") +@click.option(""-f"", ""--fasta-format"", is_flag=True, help=""Indicate input is in FASTA format"") +@click.option(""-o"", ""--output-path"", help=""Write output to a file instead of STDOUT"") +def known_uniprot_glycoprotein(file_path=None, output_path=None, fasta_format=False): + if file_path is not None: + handle = open(file_path) + else: + handle = sys.stdin + + if fasta_format: + reader = fasta.ProteinFastaFileParser(handle) + + def name_getter(x): + return x.name.accession + else: + reader = handle + + def name_getter(x): + header = fasta.default_parser(x) + try: + return header.accession + except Exception: + return header[0] + + if output_path is None: + outhandle = sys.stdout + else: + outhandle = open(output_path, 'w') + + def checker_task(inqueue, outqueue, no_more_event): + has_work = True + while has_work: + try: + protein = inqueue.get(True, 1) + except Empty: + if no_more_event.is_set(): + has_work = False + continue + try: + if has_known_glycosylation(name_getter(protein)): + outqueue.put(protein) + except Exception as e: + click.secho(""%r occurred for %s"" % (e, protein), err=True, fg='yellow') + + def consumer_task(outqueue, no_more_event): + has_work = True + if fasta_format: + writer = fasta.ProteinFastaFileWriter(outhandle) + write_fn = writer.write + else: + def write_fn(payload): + outhandle.write(str(payload).strip() + '\n') + while has_work: + try: + protein = outqueue.get(True, 1) + except Empty: + if no_more_event.is_set(): + has_work = False + continue + write_fn(protein) + outhandle.close() + + producer_done = threading.Event() + checker_done = threading.Event() + + inqueue = Queue() + outqueue = Queue() + + n_threads = 10 + checkers = [threading.Thread( + target=checker_task, args=(inqueue, outqueue, producer_done)) for i in range(n_threads)] + for check in checkers: + check.start() + + consumer = threading.Thread(target=consumer_task, args=(outqueue, checker_done)) + consumer.start() + + for protein in reader: + inqueue.put(protein) + + producer_done.set() + + for checker in checkers: + checker.join() + checker_done.set() + consumer.join() + + +@tools.command(""download-uniprot"", short_help=( + ""Downloads a list of proteins from UniProt"")) +@click.option(""-i"", ""--name-file-path"", help=""Read input from a file instead of STDIN"") +@click.option(""-o"", ""--output-path"", help=""Write output to a file instead of STDOUT"") +def download_uniprot(name_file_path=None, output_path=None): + if name_file_path is not None: + handle = open(name_file_path) + else: + handle = sys.stdin + + def name_getter(x): + header = fasta.default_parser(x) + try: + return header.accession + except Exception: + return header[0] + + accession_list = [] + for line in handle: + accession_list.append(name_getter(line)) + if output_path is None: + outhandle = click.get_binary_stream('stdout') + else: + outhandle = open(output_path, 'wb') + writer = fasta.FastaFileWriter(outhandle) + downloader = UniprotProteinDownloader(accession_list, 10) + downloader.start() + has_work = True + + def make_protein(accession, uniprot_protein): + sequence = uniprot_protein.sequence + name = ""sp|{accession}|{gene_name} {description}"".format( + accession=accession, gene_name=uniprot_protein.gene_name, + description=uniprot_protein.recommended_name) + return name, sequence + + while has_work: + try: + accession, value = downloader.get(True, 3) + if isinstance(value, Exception): + click.echo(""Could not retrieve %s - %r"" % (accession, value), err=True) + else: + writer.write(*make_protein(accession, value)) + + except Empty: + # If we haven't completed the download process, block + # now and wait for the threads to join, then continue + # trying to fetch results + if not downloader.done_event.is_set(): + downloader.join() + continue + # Otherwise we've already waited for all the results to + # arrive and we can stop iterating + else: + has_work = False + + +@tools.command(""mass-search"") +@click.option(""-p"", ""--glycopeptide"", is_flag=True) +@click.option(""-m"", ""--error-tolerance"", type=RelativeMassErrorParam(), default=1e-5) +@click.argument(""database-connection"") +@click.argument(""hypothesis-identifier"") +@click.argument(""target-mass"", type=float) +def mass_search(database_connection, hypothesis_identifier, target_mass, glycopeptide=False, error_tolerance=1e-5): + if glycopeptide: + handle = GlycopeptideDiskBackedStructureDatabase(database_connection, int(hypothesis_identifier)) + else: + handle = GlycanCompositionDiskBackedStructureDatabase(database_connection, int(hypothesis_identifier)) + width = (target_mass * error_tolerance) + click.secho(""Mass Window: %f-%f"" % (target_mass - width, target_mass + width), fg='yellow') + hits = list(handle.search_mass_ppm(target_mass, error_tolerance)) + if not hits: + click.secho(""No Matches"", fg='red') + for hit in hits: + click.echo(""\t"".join(map(str, hit))) + + +@tools.command(""version-check"") +def version_check(): + packages = [ + ""glycresoft"", + ""glycresoft_app"", + ""glypy"", + ""glycopeptidepy"", + ""ms_peak_picker"", + ""brain-isotopic-distribution"", + ""ms_deisotope"", + ""pyteomics"", + ""lxml"", + ""numpy"", + ""scipy"", + ""matplotlib"" + ] + click.secho(""Library Versions"", fg='yellow') + for dep in packages: + try: + rev = pkg_resources.require(dep) + click.echo(str(rev[0])) + except Exception: + try: + module = __import__(dep) + except ImportError: + continue + version = getattr(module, ""__version__"", None) + if version is None: + version = getattr(module, ""version"", None) + if version is None: + try: + module = __import__(""%s.version"" % dep).version + version = module.version + except ImportError: + continue + if version: + click.echo(""%s %s"" % (dep, version)) + + +@tools.command(""interactive-shell"") +@click.option(""-s"", ""--script"", default=None) +@click.argument(""script_args"", nargs=-1) +def interactive_shell(script_args, script): + if script: + with open(script, 'rt') as fh: + script = fh.read() + exec(script) + code.interact(local=locals()) + + +@tools.command(""update-analysis-parameters"") +@database_connection +@analysis_identifier +@click.option(""-p"", ""--parameter"", nargs=2, multiple=True, required=False) +def update_analysis_parameters(database_connection, analysis_identifier, parameter): + session = database_connection.session + analysis = get_by_name_or_id(session, Analysis, analysis_identifier) + click.echo(""Current Parameters:"") + pprint.pprint(analysis.parameters) + for name, value in parameter: + analysis.parameters[name] = value + session.add(analysis) + session.commit() + + +@tools.command(""summarize-glycopeptide-hypothesis"", + short_help=""Show summary information about a glycopeptide hypothesis"") +@database_connection +@hypothesis_identifier(GlycopeptideHypothesis) +def summarize_glycopeptide_hypothesis(database_connection, hypothesis_identifier): + session = database_connection.session + hypothesis = get_by_name_or_id(session, GlycopeptideHypothesis, hypothesis_identifier) + gp_counts = session.query(Protein, func.count(Glycopeptide.id)).join( + Glycopeptide).group_by(Protein.id).filter( + Protein.hypothesis_id == hypothesis.id).order_by( + Protein.id).all() + pept_counts = session.query(Protein, func.count(Peptide.id)).join( + Peptide).group_by(Protein.id).filter( + Protein.hypothesis_id == hypothesis.id).order_by( + Protein.id).all() + + gc_count = session.query(GlycanClass.name, func.count(GlycanClass.id)).join( + GlycanComposition.structure_classes).filter(GlycanComposition.hypothesis_id == hypothesis.id).group_by( + GlycanClass.id).order_by(GlycanClass.name).all() + + counts = {} + for prot, c in gp_counts: + counts[prot.id] = [prot, 0, c] + for prot, c in pept_counts: + try: + counts[prot.id][1] = c + except KeyError: + counts[prot.id] = [prot, c, 0] + + counts = sorted(counts.values(), key=lambda x: x[::-1][:-1], reverse=1) + pept_total = 0 + gp_total = 0 + for protein, pept_count, gp_count in counts: + click.echo(""%s: %d"" % (protein.name, pept_count)) + pept_total += pept_count + gp_total += gp_count + + click.echo(""Total Peptides: %d"" % (pept_total, )) + click.echo(""Total Glycopeptides: %d"" % (gp_total, )) + for cls_name, count in gc_count: + click.echo(""%s Glycan Compositions: %d"" % (cls_name, count)) + click.echo(pprint.pformat(hypothesis.parameters)) + + +@tools.command(""extract-blob"") +@database_connection +@click.argument(""blob-identifier"") +@click.option(""-o"", ""--output-path"", type=click.File(mode='wb')) +def extract_file_blob(database_connection, blob_identifier, output_path=None): + if output_path is None: + output_path = click.get_binary_stream('stdout') + session = database_connection.session + blob = get_by_name_or_id(session, FileBlob, blob_identifier) + with blob.open() as fh: + chunk_size = 2 ** 16 + chunk = fh.read(chunk_size) + while chunk: + output_path.write(chunk) + chunk = fh.read(chunk_size) + + +@tools.command(""csv-concat"") +@click.argument(""csv-paths"", type=click.File(mode='rt'), nargs=-1) +@click.option(""-o"", ""--output-path"", type=click.Path(writable=True), help=""Path to write output to"") +def csv_concat(csv_paths, output_path=None): + if output_path is None: + output_path = '-' + import csv + headers = None + with click.open_file(output_path, mode='wt') as outfh: + writer = csv.writer(outfh) + for infh in csv_paths: + reader = csv.reader(infh) + _header_line = next(reader) + if headers is None: + headers = _header_line + writer.writerow(headers) + elif _header_line != headers: + raise click.ClickException(""File %s did not have matching headers (%s != %s)"" % ( + infh.name, _header_line, headers)) + for row in reader: + writer.writerow(row) + infh.close() + outfh.flush() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/cli/__init__.py",".py","66","4","from .logger_config import configure_logging + +configure_logging() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/cli/export.py",".py","27762","618","import os +import sys +import time +import logging + +import click + +from glycresoft.cli.base import cli +from glycresoft.cli.validators import get_by_name_or_id, DatabaseConnectionParam + +from glycresoft import serialize +from glycresoft.serialize import ( + DatabaseBoundOperation, GlycanHypothesis, GlycopeptideHypothesis, + Analysis, + AnalysisTypeEnum, + GlycanCompositionChromatogram, + Protein, + Glycopeptide, + IdentifiedGlycopeptide, + GlycopeptideSpectrumMatch, + AnalysisDeserializer, + GlycanComposition, + GlycanCombination, + GlycanCombinationGlycanComposition, + UnidentifiedChromatogram) + +from glycresoft.output import ( + GlycanHypothesisCSVSerializer, ImportableGlycanHypothesisCSVSerializer, + GlycopeptideHypothesisCSVSerializer, GlycanLCMSAnalysisCSVSerializer, + GlycopeptideLCMSMSAnalysisCSVSerializer, + GlycopeptideSpectrumMatchAnalysisCSVSerializer, + MultiScoreGlycopeptideLCMSMSAnalysisCSVSerializer, + MultiScoreGlycopeptideSpectrumMatchAnalysisCSVSerializer, + MzIdentMLSerializer, + GlycanChromatogramReportCreator, + GlycopeptideDatabaseSearchReportCreator, + TrainingMGFExporter, + SpectrumAnnotatorExport, + CSVSpectrumAnnotatorExport) + +from glycresoft.output.csv_format import csv_stream + +from glycresoft.cli.utils import ctxstream + + +status_logger = logging.getLogger('glycresoft.status') + + +def database_connection_arg(fn): + arg = click.argument( + ""database-connection"", + type=DatabaseConnectionParam(exists=True), + doc_help=( + ""A connection URI for a database, or a path on the file system"")) + return arg(fn) + + +def analysis_identifier_arg(analysis_type): + def wrapper(fn): + arg = click.argument(""analysis-identifier"", doc_help=( + ""The ID number or name of the %s analysis to use"" % (analysis_type,))) + return arg(fn) + return wrapper + + +def hypothesis_identifier_arg(hypothesis_type): + def wrapper(fn): + arg = click.argument(""hypothesis-identifier"", doc_help=( + ""The ID number or name of the %s hypothesis to use"" % (hypothesis_type,))) + return arg(fn) + return wrapper + + +@cli.group(short_help='Write Data Collections To Text Files') +def export(): + pass + + +@export.command(""glycan-hypothesis"", + short_help=""Export theoretical glycan composition database to CSV"") +@database_connection_arg +@hypothesis_identifier_arg(""glycan"") +@click.option(""-o"", ""--output-path"", type=click.Path(), default=None, help='Path to write to instead of stdout') +@click.option(""-i"", ""--importable"", is_flag=True, + help=""Make the file importable for later re-use, with less information."") +def glycan_hypothesis(database_connection, hypothesis_identifier, output_path=None, importable=False): + """"""Write each theoretical glycan composition in CSV format"""""" + database_connection = DatabaseBoundOperation(database_connection) + hypothesis = get_by_name_or_id(database_connection, GlycanHypothesis, hypothesis_identifier) + if importable: + task_type = ImportableGlycanHypothesisCSVSerializer + else: + task_type = GlycanHypothesisCSVSerializer + if output_path is None or output_path == '-': + output_stream = ctxstream(sys.stdout) + else: + output_stream = open(output_path, 'wb') + with output_stream: + job = task_type(output_stream, hypothesis.glycans) + job.run() + + +@export.command(""glycopeptide-hypothesis"", + short_help='Export theoretical glycopeptide database to CSV') +@database_connection_arg +@hypothesis_identifier_arg(""glycopeptide"") +@click.option(""-o"", ""--output-path"", type=click.Path(), default=None, help='Path to write to instead of stdout') +def glycopeptide_hypothesis(database_connection, hypothesis_identifier, output_path, multifasta=False): + """"""Write each theoretical glycopeptide in CSV format"""""" + database_connection = DatabaseBoundOperation(database_connection) + session = database_connection.session() # pylint: disable=not-callable + hypothesis = get_by_name_or_id(session, GlycopeptideHypothesis, hypothesis_identifier) + + def generate(): + interval = 100000 + i = 0 + while True: + session.expire_all() + chunk = hypothesis.glycopeptides.slice(i, i + interval).all() + if len(chunk) == 0: + break + for glycopeptide in chunk: + yield glycopeptide + i += interval + if output_path is None or output_path == '-': + output_stream = ctxstream(sys.stdout) + else: + output_stream = open(output_path, 'wb') + with output_stream: + job = GlycopeptideHypothesisCSVSerializer(output_stream, generate()) + job.run() + + +@export.command(""glycan-identification"", + short_help=""Exports assigned LC-MS features of Glycan Compositions to CSV or HTML"") +@database_connection_arg +@analysis_identifier_arg(""glycan"") +@click.option(""-o"", ""--output-path"", type=click.Path(), default=None, help='Path to write to instead of stdout') +@click.option(""-r"", ""--report"", is_flag=True, help=""Export an HTML report instead of a CSV"") +@click.option(""-t"", ""--threshold"", type=float, default=0, help=""Minimum score threshold to include"") +def glycan_composition_identification(database_connection, analysis_identifier, output_path=None, + threshold=0, report=False): + """"""Write each glycan chromatogram in CSV format"""""" + database_connection = DatabaseBoundOperation(database_connection) + session = database_connection.session() # pylint: disable=not-callable + analysis = get_by_name_or_id(session, Analysis, analysis_identifier) + if not analysis.analysis_type == AnalysisTypeEnum.glycan_lc_ms: + click.secho(""Analysis %r is of type %r."" % ( + str(analysis.name), str(analysis.analysis_type)), fg='red', err=True) + raise click.Abort() + analysis_id = analysis.id + if output_path is None or output_path == '-': + output_stream = ctxstream(sys.stdout) + else: + output_stream = open(output_path, 'wb') + + if report: + with output_stream: + job = GlycanChromatogramReportCreator( + database_connection._original_connection, + analysis_id, output_stream, threshold=threshold) + job.run() + else: + def generate(): + i = 0 + interval = 100 + query = session.query(GlycanCompositionChromatogram).filter( + GlycanCompositionChromatogram.analysis_id == analysis_id, + GlycanCompositionChromatogram.score > threshold) + + while True: + session.expire_all() + chunk = query.slice(i, i + interval).all() + if len(chunk) == 0: + break + for gcs in chunk: + yield gcs.convert() + i += interval + + i = 0 + query = session.query(UnidentifiedChromatogram).filter( + UnidentifiedChromatogram.analysis_id == analysis_id, + UnidentifiedChromatogram.score > threshold) + + while True: + session.expire_all() + chunk = query.slice(i, i + interval).all() + if len(chunk) == 0: + break + for gcs in chunk: + yield gcs.convert() + i += interval + + with output_stream: + job = GlycanLCMSAnalysisCSVSerializer(output_stream, generate()) + job.run() + + +@export.command(""glycopeptide-identification"", + short_help=""Exports assigned LC-MS/MS features of Glycopeptides to CSV or HTML"") +@database_connection_arg +@analysis_identifier_arg(""glycopeptide"") +@click.option(""-o"", ""--output-path"", type=click.Path(), default=None, help='Path to write to instead of stdout') +@click.option(""-r"", ""--report"", is_flag=True, help=""Export an HTML report instead of a CSV"") +@click.option(""-m"", ""--mzml-path"", type=click.Path(exists=True), default=None, help=( + ""Path to read processed spectra from instead of the path embedded in the analysis metadata"")) +@click.option(""-t"", ""--threshold"", type=float, default=0, help='The minimum MS2 score threshold (larger is better)') +@click.option(""-f"", ""--fdr-threshold"", type=float, default=1, help='The maximum FDR threshold (smaller is better)') +def glycopeptide_identification(database_connection, analysis_identifier, output_path=None, + report=False, mzml_path=None, threshold=0, fdr_threshold=1): + """"""Write each distinct identified glycopeptide in CSV format"""""" + # logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO) + database_connection = DatabaseBoundOperation(database_connection) + session = database_connection.session() # pylint: disable=not-callable + analysis = get_by_name_or_id(session, Analysis, analysis_identifier) + if not analysis.analysis_type == AnalysisTypeEnum.glycopeptide_lc_msms: + click.secho(""Analysis %r is of type %r."" % ( + str(analysis.name), str(analysis.analysis_type)), fg='red', err=True) + raise click.Abort() + analysis_id = analysis.id + is_multiscore = analysis.is_multiscore + if output_path is None or output_path == '-': + output_stream = ctxstream(click.get_binary_stream('stdout')) + else: + output_stream = open(output_path, 'wb') + if report: + with output_stream: + if mzml_path is None: + mzml_path = analysis.parameters['sample_path'] + if not os.path.exists(mzml_path): + raise click.ClickException( + (""Sample path {} not found. Pass the path to"" + "" this file as `-m/--mzml-path` for this command."").format( + mzml_path)) + job = GlycopeptideDatabaseSearchReportCreator( + database_connection._original_connection, analysis_id, + stream=output_stream, + threshold=threshold, + fdr_threshold=fdr_threshold, + mzml_path=mzml_path) + job.run() + else: + query = session.query(Protein.id, Protein.name).join(Protein.glycopeptides).join( + IdentifiedGlycopeptide).filter( + IdentifiedGlycopeptide.analysis_id == analysis.id) + protein_index = dict(query) + + if is_multiscore: + job_type = MultiScoreGlycopeptideLCMSMSAnalysisCSVSerializer + else: + job_type = GlycopeptideLCMSMSAnalysisCSVSerializer + + protein_site_track_cache = {} + + def generate(): + i = 0 + interval = 100 + query = session.query(IdentifiedGlycopeptide).filter( + IdentifiedGlycopeptide.analysis_id == analysis_id) + if threshold != 0: + query = query.filter(IdentifiedGlycopeptide.ms2_score >= threshold) + if fdr_threshold < 1: + query = query.filter(IdentifiedGlycopeptide.q_value <= fdr_threshold) + while True: + session.expunge_all() + chunk = query.slice(i, i + interval).all() + if len(chunk) == 0: + break + new_proteins = {x.structure.protein_relation.protein_id for x in chunk} - set(protein_site_track_cache) + protein_site_track_cache.update(Protein.build_site_cache(session, list(new_proteins))) + # chunk = IdentifiedGlycopeptide.bulk_convert(chunk) + for glycopeptide in chunk: + yield glycopeptide + + i += interval + with output_stream: + job = job_type( + output_stream, generate(), + protein_index, + analysis, + site_track_cache=protein_site_track_cache, + ) + job.run() + + +@export.command(""glycopeptide-spectrum-matches"", + short_help=""Exports individual MS/MS assignments of Glycopeptides to CSV"") +@database_connection_arg +@analysis_identifier_arg(""glycopeptide"") +@click.option(""-o"", ""--output-path"", type=click.Path(), default=None, help='Path to write to instead of stdout') +@click.option(""-t"", ""--threshold"", type=float, default=0, help='The minimum MS2 score threshold (larger is better)') +@click.option(""-f"", ""--fdr-threshold"", type=float, default=1, help='The maximum FDR threshold (smaller is better)') +def glycopeptide_spectrum_matches(database_connection, analysis_identifier, output_path=None, threshold=0, + fdr_threshold=1.0): + """"""Write each matched glycopeptide spectrum in CSV format"""""" + database_connection = DatabaseBoundOperation(database_connection) + session = database_connection.session() # pylint: disable=not-callable + analysis = get_by_name_or_id(session, Analysis, analysis_identifier) + if not analysis.analysis_type == AnalysisTypeEnum.glycopeptide_lc_msms: + click.secho(""Analysis %r is of type %r."" % ( + str(analysis.name), str(analysis.analysis_type)), fg='red', err=True) + raise click.Abort() + analysis_id = analysis.id + hypothesis_id = analysis.hypothesis_id + is_multiscore = analysis.is_multiscore + start = time.monotonic() + + status_logger.info(""Loading protein index"") + protein_query = session.query(Protein.id, Protein.name).join( + Protein.glycopeptides + ).join( + GlycopeptideSpectrumMatch + ).filter( + Protein.hypothesis_id == hypothesis_id, + GlycopeptideSpectrumMatch.analysis_id == analysis.id + ) + protein_index = dict(protein_query.all()) + + # This could concievably use a lot of RAM and need an analysis constraint like `protein_index`, but + # the value is an integer, much smaller than the strings a name might be + missed_cleavage_cache = dict( + session.query( + serialize.Glycopeptide.id, + serialize.Peptide.count_missed_cleavages + ).join(serialize.Peptide).filter( + serialize.Peptide.count_missed_cleavages > 0, + serialize.Peptide.hypothesis_id == hypothesis_id + ).all() + ) + + protein_site_track_cache = {} + + def generate(): + i = 0 + interval = 100000 + gpsm_query = session.query(GlycopeptideSpectrumMatch.id).filter( + GlycopeptideSpectrumMatch.analysis_id == analysis_id).order_by( + GlycopeptideSpectrumMatch.scan_id) + if threshold != 0: + gpsm_query = gpsm_query.filter(GlycopeptideSpectrumMatch.score >= threshold) + if fdr_threshold < 1: + gpsm_query = gpsm_query.filter(GlycopeptideSpectrumMatch.q_value <= fdr_threshold) + + mass_shift_cache = { + m.id: m.convert() + for m in session.query(serialize.CompoundMassShift).all() + } + scan_cache = {} + structure_cache = {} + peptide_relation_cache = {} + + status_logger.info(""Reading spectrum matches"") + j = 0 + while True: + session.expire_all() + chunk = gpsm_query.slice(i, i + interval).all() + chunk = [x[0] for x in chunk] + chunk = GlycopeptideSpectrumMatch.bulk_load( + session, + chunk, + mass_shift_cache=mass_shift_cache, + scan_cache=scan_cache, + structure_cache=structure_cache, + peptide_relation_cache=peptide_relation_cache + ) + if not chunk: + break + chunk = [x[1] for x in sorted(chunk.items())] + new_proteins = {x.target.protein_relation.protein_id for x in chunk} - set(protein_site_track_cache) + protein_site_track_cache.update(Protein.build_site_cache(session, list(new_proteins))) + for glycopeptide in chunk: + j += 1 + yield glycopeptide + i += interval + + if is_multiscore: + job_type = MultiScoreGlycopeptideSpectrumMatchAnalysisCSVSerializer + else: + job_type = GlycopeptideSpectrumMatchAnalysisCSVSerializer + + if output_path is None or output_path == '-': + output_stream = ctxstream(click.get_binary_stream('stdout')) + else: + output_stream = open(output_path, 'wb') + + with output_stream: + job = job_type( + output_stream, + generate(), + protein_index, + analysis, + site_track_cache=protein_site_track_cache, + missed_cleavage_cache=missed_cleavage_cache, + ) + job.run() + + end = time.monotonic() + elapsed = end - start + status_logger.info(f""{elapsed:0.2f} seconds elapsed"") + + +@export.command(""mzid"", short_help=""Export a Glycopeptide Analysis as MzIdentML"") +@database_connection_arg +@analysis_identifier_arg(""glycopeptide"") +@click.argument(""output-path"") +@click.option(""--embed-protein-sequences/--exclude-protein-sequences"", is_flag=True, default=True, + help=""Include protein sequences in the output file"") +@click.option(""-m"", '--mzml-path', type=click.Path(exists=True), default=None, + help=""Alternative path to find the source mzML file"") +def glycopeptide_mzidentml(database_connection, analysis_identifier, output_path=None, + mzml_path=None, embed_protein_sequences=True): + """""" + Write identified glycopeptides as mzIdentML file, and associated MSn spectra + to a paired mzML file if the matched data are available. If an mzML file is written + it will also contain the extracted ion chromatograms for each glycopeptide with an + extracted elution profile. + """""" + database_connection = DatabaseBoundOperation(database_connection) + session = database_connection.session() # pylint: disable=not-callable + analysis = get_by_name_or_id(session, Analysis, analysis_identifier) + if not analysis.analysis_type == AnalysisTypeEnum.glycopeptide_lc_msms: + click.secho(""Analysis %r is of type %r."" % ( + str(analysis.name), str(analysis.analysis_type)), fg='red', err=True) + raise click.Abort() + loader = AnalysisDeserializer( + database_connection._original_connection, analysis_id=analysis.id) + click.echo(""Loading Identifications"") + # glycopeptides = loader.load_identified_glycopeptides() + glycopeptides = loader.query(IdentifiedGlycopeptide).filter( + IdentifiedGlycopeptide.analysis_id == analysis_identifier).all() + with open(output_path, 'wb') as outfile: + writer = MzIdentMLSerializer( + outfile, glycopeptides, analysis, loader, + source_mzml_path=mzml_path, + embed_protein_sequences=embed_protein_sequences) + writer.run() + + +@export.command(""glycopeptide-training-mgf"", short_help=(""Export identified MS2 spectra as MGF with"" + "" matched glycopeptide as metadata"")) +@database_connection_arg +@analysis_identifier_arg(""glycopeptide"") +@click.option(""-o"", ""--output-path"", type=click.Path(), default=None, help='Path to write to instead of stdout') +@click.option(""-m"", '--mzml-path', type=click.Path(exists=True), default=None, + help=""Alternative path to find the source mzML file"") +@click.option(""-t"", ""--threshold"", type=float, default=None, help='Minimum MS2 score to export') +def glycopeptide_training_mgf(database_connection, analysis_identifier, output_path=None, + mzml_path=None, threshold=None): + """""" + Export identified glycopeptide spectrum matches for model training as + an annotated MGF file. + """""" + database_connection = DatabaseBoundOperation(database_connection) + session = database_connection.session() # pylint: disable=not-callable + analysis = get_by_name_or_id(session, Analysis, analysis_identifier) + if not analysis.analysis_type == AnalysisTypeEnum.glycopeptide_lc_msms: + click.secho(""Analysis %r is of type %r."" % ( + str(analysis.name), str(analysis.analysis_type)), fg='red', err=True) + raise click.Abort() + if output_path is None or output_path == '-': + output_stream = ctxstream(click.get_binary_stream('stdout')) + else: + output_stream = open(output_path, 'wb') + with output_stream: + TrainingMGFExporter.from_analysis( + database_connection, analysis.id, output_stream, mzml_path, threshold).run() + + +@export.command(""identified-glycans-from-glycopeptides"", short_help=""Export glycans on identified glycopeptides"") +@database_connection_arg +@analysis_identifier_arg(""glycopeptide"") +@click.option(""-o"", ""--output-path"", type=click.Path(), default=None, help='Path to write to instead of stdout') +def export_identified_glycans_from_glycopeptides(database_connection, analysis_identifier, output_path): + """""" + Export the glycans attached to any identified glycopeptides. + + The files are written in an importable format to be used to create a new glycan hypothesis. + """""" + database_connection = DatabaseBoundOperation(database_connection) + session = database_connection.session() # pylint: disable=not-callable + analysis = get_by_name_or_id(session, Analysis, analysis_identifier) + if not analysis.analysis_type == AnalysisTypeEnum.glycopeptide_lc_msms: + click.secho(""Analysis %r is of type %r."" % ( + str(analysis.name), str(analysis.analysis_type)), fg='red', err=True) + raise click.Abort() + glycans = session.query(GlycanComposition).join( + GlycanCombinationGlycanComposition).join(GlycanCombination).join( + Glycopeptide, + Glycopeptide.glycan_combination_id == GlycanCombination.id).join( + IdentifiedGlycopeptide, + IdentifiedGlycopeptide.structure_id == Glycopeptide.id).filter( + IdentifiedGlycopeptide.analysis_id == analysis.id).all() + if output_path is None: + output_stream = ctxstream(click.get_binary_stream('stdout')) + else: + output_stream = open(output_path, 'wb') + with output_stream: + job = ImportableGlycanHypothesisCSVSerializer(output_stream, glycans) + job.run() + + +@export.command(""annotate-matched-spectra"", + short_help=""Exports graphical renderings of individual MS/MS assignments of glycopeptides to PDF"") +@database_connection_arg +@analysis_identifier_arg(""glycopeptide"") +@click.option(""-o"", ""--output-path"", type=click.Path(), default=None, help='Path to write to instead of stdout') +@click.option(""-m"", '--mzml-path', type=click.Path(exists=True), default=None, + help=""Alternative path to find the source mzML file"") +def annotate_matched_spectra(database_connection, analysis_identifier, output_path, mzml_path=None): + """""" + Export graphical renderings of individual MS/MS assignments of glycopeptides to PDF. + + The output file will contain one spectrum per PDF page. + """""" + database_connection = DatabaseBoundOperation(database_connection) + session = database_connection.session() # pylint: disable=not-callable + analysis = get_by_name_or_id(session, Analysis, analysis_identifier) + if not analysis.analysis_type == AnalysisTypeEnum.glycopeptide_lc_msms: + click.secho(""Analysis %r is of type %r."" % ( + str(analysis.name), str(analysis.analysis_type)), fg='red', err=True) + raise click.Abort() + if output_path is None: + output_path = os.path.dirname(database_connection._original_connection) + + task = SpectrumAnnotatorExport( + database_connection._original_connection, analysis.id, output_path, + mzml_path) + task.display_header() + task.start() + + +@export.command(""write-csv-spectrum-library"", short_help=""Exports individual MS/MS assignments of glycopeptides to CSV"") +@database_connection_arg +@analysis_identifier_arg(""glycopeptide"") +@click.option(""-o"", ""--output-path"", type=click.Path(), default=None, help='Path to write to instead of stdout') +@click.option(""-m"", '--mzml-path', type=click.Path(exists=True), default=None, + help=""Alternative path to find the source mzML file"") +@click.option(""-t"", ""--fdr-threshold"", type=float, default=0.05) +def write_spectrum_library(database_connection, analysis_identifier, output_path, mzml_path=None, fdr_threshold=0.05): + """""" + Export individual MS/MS assignments of glycopeptides to CSV. + + Each row corresponds to a single product ion match, partitioned by + scan ID. Unmatched peaks are ignored. + """""" + database_connection = DatabaseBoundOperation(database_connection) + session = database_connection.session() # pylint: disable=not-callable + analysis = get_by_name_or_id(session, Analysis, analysis_identifier) + if not analysis.analysis_type == AnalysisTypeEnum.glycopeptide_lc_msms: + click.secho(""Analysis %r is of type %r."" % ( + str(analysis.name), str(analysis.analysis_type)), fg='red', err=True) + raise click.Abort() + if output_path is None: + output_stream = ctxstream(click.get_binary_stream('stdout')) + else: + output_stream = open(output_path, 'wb') + + with output_stream: + task = CSVSpectrumAnnotatorExport( + database_connection._original_connection, analysis.id, output_stream, + mzml_path, fdr_threshold) + task.run() + + +@export.command(""glycopeptide-chromatogram-records"") +@database_connection_arg +@analysis_identifier_arg(""glycopeptide"") +@click.option(""-o"", ""--output-path"", type=click.Path(), default=None, help='Path to write to instead of stdout') +@click.option('-r', '--apex-time-range', type=(float, float), default=(0, float('inf')), + help='The range of apex times to include') +@click.option(""-t"", ""--fdr-threshold"", type=float, default=0.05) +def glycopeptide_chromatogram_records( + database_connection, analysis_identifier, output_path, apex_time_range=None, fdr_threshold=0.05): + """""" + Export a simplified table of glycopeptide chromatographic features, formatted for retention time + modeling. + """""" + if apex_time_range is None: + apex_time_range = (0, float('inf')) + database_connection = DatabaseBoundOperation(database_connection) + session = database_connection.session() # pylint: disable=not-callable + analysis = get_by_name_or_id(session, Analysis, analysis_identifier) + if not analysis.analysis_type == AnalysisTypeEnum.glycopeptide_lc_msms: + click.secho(""Analysis %r is of type %r."" % ( + str(analysis.name), str(analysis.analysis_type)), fg='red', err=True) + raise click.Abort() + if output_path is None: + fh = click.get_binary_stream('stdout') + else: + fh = open(output_path, 'wb') + idgps = session.query( + IdentifiedGlycopeptide).filter( + IdentifiedGlycopeptide.analysis_id == analysis.id).all() + n = len(idgps) + from glycresoft.scoring.elution_time_grouping import GlycopeptideChromatogramProxy + cases = [] + analysis_name = analysis.name + start_time, stop_time = apex_time_range + for i, idgp in enumerate(idgps): + if i % 50 == 0: + click.echo(""%d/%d Records Processed"" % (i, n), err=True) + if idgp.chromatogram is None: + continue + if idgp.ms1_score < 0: + continue + if idgp.q_value > fdr_threshold: + continue + obj = GlycopeptideChromatogramProxy.from_chromatogram( + idgp, ms1_score=idgp.ms1_score, ms2_score=idgp.ms2_score, + q_value=idgp.q_value, analysis_name=analysis_name, + mass_shifts=idgp.chromatogram.mass_shifts) + if obj.apex_time < start_time or obj.apex_time > stop_time: + continue + cases.append(obj) + click.echo(""Writing %d Records"" % (len(cases), ), err=True) + with fh: + GlycopeptideChromatogramProxy.to_csv(cases, csv_stream(fh)) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/cli/utils.py",".py","424","20","class ctxstream(object): + def __init__(self, stream): + self.stream = stream + + def write(self, string): + self.stream.write(string) + + def flush(self): + self.stream.flush() + + def __getattr__(self, attrib: str): + attr = getattr(self.stream, attrib) + return attr + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + return False +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/cli/config.py",".py","3338","86","import click + +from glycresoft.cli.base import cli +from glycresoft.config.config_file import ( + add_user_modification_rule as add_user_peptide_modification_rule, + add_user_substituent_rule, delete_config_dir) + +from glypy.composition import formula, Composition +from glypy import Substituent + +from glycopeptidepy.structure.modification import ( + extract_targets_from_string, ModificationRule, + Modification) + + +@cli.group(short_help='Set persistent configuration options') +def config(): + pass + + +def parse_peptide_modification_target_spec(context, spec_string_list): + out = [] + for spec_string in spec_string_list: + try: + spec = extract_targets_from_string(spec_string) + out.append(spec) + except Exception as e: + raise ValueError(str(e)) + return out + + +@config.command(""add-peptide-modification"") +@click.option(""-n"", '--name', required=True, help='Modification name') +@click.option(""-c"", ""--composition"", required=True, help='The chemical formula for this modification') +@click.option(""-t"", ""--target"", required=True, multiple=True, + help=""Target specification string of the form residue[@n-term|c-term]"", + callback=parse_peptide_modification_target_spec) +def peptide_modification(name, composition, target, categories=None): + composition = Composition(str(composition)) + rule = ModificationRule(target, name, None, composition.mass, composition) + add_user_peptide_modification_rule(rule) + click.echo(""Added %r to modification registry"" % (rule,)) + + +@config.command(""get-peptide-modification"") +@click.argument(""name"") +def display_peptide_modification(name): + mod = Modification(name) + click.echo(""name: %s"" % mod.name) + click.echo(""mass: %f"" % mod.mass) + click.echo(""formula: %s"" % formula(mod.composition)) + for target in mod.rule.targets: + click.echo(""target: %s"" % target.serialize()) + + +@config.command(""add-substituent"") +@click.option(""-n"", ""--name"", required=True, help='Substituent name') +@click.option(""-c"", ""--composition"", required=True, help='The chemical formula for this substituent') +@click.option(""-s"", ""--is-nh-derivatizable"", is_flag=True, + help=""Can this substituent be derivatized as at an N-H bond?"") +@click.option(""-d"", ""--can-nh-derivatize"", is_flag=True, + help=""Will this substituent derivatize other substituents at sites like an N-H bond?"") +@click.option(""-a"", ""--attachment-loss"", default=""H"", + help=""The composition lost by the parent molecule when this substituent is added. Defaults to \""H\"""") +def substituent(name, composition, is_nh_derivatizable, can_nh_derivatize, attachment_loss): + click.echo(""name: %s"" % (name,)) + click.echo(""composition: %s"" % (composition,)) + click.echo(""is_nh_derivatizable: %s"" % (is_nh_derivatizable,)) + click.echo(""can_nh_derivatize: %s"" % (can_nh_derivatize,)) + click.echo(""attachment_loss: %s"" % (attachment_loss,)) + + rule = Substituent( + name, + composition=Composition(composition), + can_nh_derivatize=can_nh_derivatize, + attachment_composition=Composition(attachment_loss), + ) + + add_user_substituent_rule(rule) + + +@config.command(""clear-configuration"") +def clear_config(): + click.secho(""Deleting Configuration Directory"", fg='red') + delete_config_dir() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/cli/mzml.py",".py","4451","118","import os +import functools + +from collections import defaultdict + +import click + +import ms_deisotope +import glypy + +from ms_deisotope import MSFileLoader +from ms_deisotope.output import ProcessedMSFileLoader +from ms_deisotope.feature_map import quick_index +from ms_deisotope.tools.deisotoper import deisotope + +from glycresoft.cli.base import cli + +from glycresoft.profiler import SampleConsumer + + +@cli.group('mzml', short_help='Inspect and preprocess mzML files') +def mzml_cli(): + pass + + +preprocess = click.Command( + ""preprocess"", + context_settings=deisotope.context_settings, + callback=functools.partial(deisotope.callback, workflow_cls=SampleConsumer, configure_logging=False), + params=deisotope.params, + help=deisotope.help, + epilog=deisotope.epilog, +) + +mzml_cli.add_command(preprocess, ""preprocess"") + + +@mzml_cli.command('rt-to-id', short_help=""Look up the retention time for a given scan id"") +@click.argument(""ms-file"", type=click.Path(exists=True)) +@click.argument(""rt"", type=float) +def rt_to_id(ms_file, rt): + loader = MSFileLoader(ms_file) + id = loader._locate_ms1_scan(loader.get_scan_by_time(rt)).id + click.echo(id) + + +@mzml_cli.command(""info"", short_help='Summary information describing a processed mzML file') +@click.argument(""ms-file"", type=click.Path(exists=True, file_okay=True, dir_okay=False)) +def msfile_info(ms_file): + reader = ProcessedMSFileLoader(ms_file) + if not reader.has_index_file(): + index, intervals = quick_index.index(ms_deisotope.MSFileLoader(ms_file)) + reader.extended_index = index + with open(reader._index_file_name, 'w') as handle: + index.serialize(handle) + click.echo(""Name: %s"" % (os.path.basename(ms_file),)) + click.echo(""MS1 Scans: %d"" % (len(reader.extended_index.ms1_ids),)) + click.echo(""MSn Scans: %d"" % (len(reader.extended_index.msn_ids),)) + + n_defaulted = 0 + n_orphan = 0 + + charges = defaultdict(int) + first_msn = float('inf') + last_msn = 0 + for scan_info in reader.extended_index.msn_ids.values(): + n_defaulted += scan_info.get('defaulted', False) + n_orphan += scan_info.get('orphan', False) + charges[scan_info['charge']] += 1 + rt = scan_info['scan_time'] + if rt < first_msn: + first_msn = rt + if rt > last_msn: + last_msn = rt + + click.echo(""First MSn Scan: %0.2f Minutes"" % (first_msn,)) + click.echo(""Last MSn Scan: %0.2f Minutes"" % (last_msn,)) + + for charge, count in sorted(charges.items()): + if not isinstance(charge, int): + continue + click.echo(""Precursors with Charge State %d: %d"" % (charge, count)) + + click.echo(""Defaulted MSn Scans: %d"" % (n_defaulted,)) + click.echo(""Orphan MSn Scans: %d"" % (n_orphan,)) + + +@mzml_cli.command(""oxonium-signature"", short_help=( + 'Report Oxonium Ion Signature Score (G-Score) and Glycan Structure Signature Score' + ' for each MSn scan in a processed mzML file')) +@click.argument(""ms-file"", type=click.Path(exists=True, file_okay=True, dir_okay=False)) +@click.option(""-g"", ""--g-score-threshold"", type=float, default=0.05, help=""Minimum G-Score to report"") +def oxonium_signature(ms_file, g_score_threshold=0.05): + reader = ProcessedMSFileLoader(ms_file) + if not reader.has_index_file(): + click.secho(""Building temporary index..."", fg='yellow') + index, intervals = quick_index.index(ms_deisotope.MSFileLoader(ms_file)) + reader.extended_index = index + with open(reader._index_file_name, 'w') as handle: + index.serialize(handle) + + from glycresoft.tandem.glycan.scoring.signature_ion_scoring import SignatureIonScorer + from glycresoft.tandem.oxonium_ions import gscore_scanner + + refcomp = glypy.GlycanComposition.parse(""{Fuc:1; Hex:5; HexNAc:4; Neu5Ac:1; NeuGc:1}"") + headers = [""scan_id"", ""precursor_mass"", ""precursor_charge"", ""g_score"", ""signature_score""] + click.echo(""\t"".join(headers)) + for scan_id in reader.extended_index.msn_ids.keys(): + scan = reader.get_scan_by_id(scan_id) + gscore = gscore_scanner(scan.deconvoluted_peak_set) + if gscore >= g_score_threshold: + signature_match = SignatureIonScorer.evaluate( + scan, refcomp, use_oxonium=False) + click.echo(""%s\t%f\t%r\t%f\t%f"" % ( + scan_id, scan.precursor_information.neutral_mass, + scan.precursor_information.charge, gscore, + signature_match.score)) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/cli/base.py",".py","2183","80","import logging +import multiprocessing + +import click + +from glycresoft import version +from glycresoft.cli.logger_config import make_log_file_logger, LOG_FILE_MODE, LOG_LEVEL + +CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) + +logger = logging.getLogger(""glycresoft"") + + +@click.group(context_settings=CONTEXT_SETTINGS) +@click.version_option(version.version) +@click.option(""-l"", ""--log-file"", type=click.Path(writable=True), required=False, + default=None, help=""Path to write the log file to."") +def cli(log_file=None): + if log_file is not None: + click.echo(f""Logging to {log_file}"") + make_log_file_logger(log_file_name=log_file, log_file_mode=LOG_FILE_MODE, + level=LOG_LEVEL, name='glycresoft') + + +class HiddenOption(click.Option): + """""" + HiddenOption -- absent from Help text. + + Supported in latest and greatest version of Click, but not old versions, so + use generic 'cls=HiddenOption' to get the desired behavior. + """""" + + @property + def hidden(self): + return True + + @hidden.setter + def hidden(self, value): + return + + def get_help_record(self, ctx): + """""" + Has ""None"" as its help record. All that is needed. + """""" + return + + +class DocumentableArgument(click.Argument): + def __init__(self, *args, **kwargs): + doc_help = kwargs.pop(""doc_help"", """") + super(DocumentableArgument, self).__init__(*args, **kwargs) + self.doc_help = doc_help + + +_option = click.option +_argument = click.argument + + +def option(*args, **kwargs): + kwargs.setdefault(""show_default"", True) + return _option(*args, **kwargs) + + +def argument(*args, **kwargs): + kwargs['cls'] = DocumentableArgument + a = _argument(*args, **kwargs) + return a + + +click.option = option +click.argument = argument + + +processes_option = click.option( + ""-p"", ""--processes"", 'processes', type=click.IntRange(1, multiprocessing.cpu_count()), + default=min(multiprocessing.cpu_count(), 4), help=('Number of worker processes to use. Defaults to 4 ' + 'or the number of CPUs, whichever is lower'), + # show_default=True +) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/cli/__main__.py",".py","1623","64","import os +import sys +import traceback +import platform +import logging + +from multiprocessing import freeze_support, set_start_method + +import click + +from glycresoft.cli import ( + base, build_db, tools, mzml, analyze, config, + export) + +try: + from glycresoft_app.cli import server +except ImportError: + pass + + +def info(type, value, tb): + if not sys.stderr.isatty(): + click.secho(""Running interactively, not starting debugger"", fg='yellow') + sys.__excepthook__(type, value, tb) + else: + import pdb + traceback.print_exception(type, value, tb) + pdb.post_mortem(tb) + + +def set_breakpoint_hook(): + try: + import ipdb + sys.breakpointhook = ipdb.set_trace + except ImportError: + pass + + +def main(): + freeze_support() + try: + if platform.system() == 'Windows' or platform.system() == ""Darwin"": + set_start_method(""spawn"") + else: + set_start_method(""forkserver"") + except Exception as err: + logging.getLogger().error(""Failed to set multiprocessing start method: %s"", err, exc_info=True) + + if os.getenv(""GLYCRESOFTDEBUG""): + sys.excepthook = info + click.secho(""Running glycresoft with debugger"", fg='yellow') + if os.getenv(""GLYCRESOFTPROFILING""): + import cProfile + click.secho(""Running glycresoft with profiler"", fg='yellow') + profiler = cProfile.Profile() + profiler.runcall(base.cli.main, standalone_mode=False) + profiler.dump_stats('glycresoft_performance.profile') + else: + base.cli.main(standalone_mode=True) + + +if __name__ == '__main__': + main() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/diagnostics.py",".py","579","13","from matplotlib import pyplot as plt +import numpy as np + + +def target_decoy_score_separation(target_hits, decoy_hits, binwidth=5, ax=None): + if ax is None: + fig, ax = plt.subplots(1) + bins = np.arange(min([s.score for s in target_hits]), max([s.score for s in target_hits]) + binwidth, binwidth) + ax.hist([s.score for s in target_hits], bins=bins, alpha=0.4, lw=0.5, ec='white', label='Target PSMs') + ax.hist([s.score for s in decoy_hits], bins=bins, alpha=0.4, lw=0.5, ec='white', label='Decoy PSMs') + ax.legend().get_frame().set_linewidth(0) + return ax +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/lcms_surface.py",".py","2939","100","from matplotlib import pyplot as plt +from mpl_toolkits.mplot3d import Axes3D +from matplotlib import cm +from scipy.ndimage import gaussian_filter1d +import numpy as np + + +from ..scoring import total_intensity + + +class LCMSSurfaceArtist(object): + def __init__(self, chromatograms): + self.chromatograms = chromatograms + self.times = [] + self.masses = [] + self.heights = [] + + def build_map(self): + self.times = [] + self.masses = [] + self.heights = [] + + for chroma in self.chromatograms: + x, z = chroma.as_arrays() + y = chroma.neutral_mass + self.times.append(x) + self.masses.append(y) + + rt = set() + map(rt.update, self.times) + rt = np.array(list(rt)) + rt.sort() + self.times = rt + + self.heights = list(map(self.make_z_array, self.chromatograms)) + scaler = max(map(max, self.heights)) / 100. + for height in self.heights: + height /= scaler + + def make_z_array(self, chroma): + z = [] + next_time_i = 0 + next_time = chroma.retention_times[next_time_i] + + for i in self.times: + if np.allclose(i, next_time): + z.append(total_intensity(chroma.peaks[next_time_i])) + next_time_i += 1 + if next_time_i == len(chroma): + break + next_time = chroma.retention_times[next_time_i] + else: + z.append(0) + z = gaussian_filter1d(np.concatenate((z, np.zeros(len(self.times) - len(z)))), 1) + return z + + def make_sparse(self, width=0.05): + i = 0 + masses = [] + heights = [] + + flat = self.heights[0] * 0 + + masses.append(self.masses[0] - 200) + heights.append(flat) + + while i < len(self.masses): + mass = self.masses[i] + masses.append(mass - width) + heights.append(flat) + masses.append(mass) + heights.append(self.heights[i]) + masses.append(mass + width) + heights.append(flat) + i += 1 + + self.masses = masses + self.heights = heights + + def draw(self, alpha=0.8, **kwargs): + fig = plt.figure() + ax = fig.gca(projection='3d') + self.ax = ax + + self.build_map() + self.make_sparse() + + X, Y = np.meshgrid(self.times, self.masses) + ax.plot_surface(X, Y, self.heights, rstride=1, cstride=1, + linewidth=0, antialiased=False, shade=True, + alpha=alpha) + ax.view_init() + ax.azim += 20 + ax.set_xlim3d(self.times.min(), self.times.max()) + ax.set_ylim3d(min(self.masses) - 100, max(self.masses)) + ax.set_xlabel(""Retention Time (Min)"", fontsize=18) + ax.set_ylabel(""Neutral Mass"", fontsize=18) + ax.set_zlabel(""Relative Abundance (%)"", fontsize=18) + return self +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/entity_bar_chart.py",".py","4841","149","from collections import Counter + +import numpy as np +from matplotlib import pyplot as plt + +from glypy.structure.glycan_composition import HashableGlycanComposition + +from .glycan_visual_classification import ( + NGlycanCompositionColorizer, + NGlycanCompositionOrderer, + GlycanLabelTransformer) +from .chromatogram_artist import ArtistBase + + +class EntitySummaryBarChartArtist(ArtistBase): + bar_width = 0.5 + alpha = 0.5 + y_label = """" + plot_title = """" + + def __init__(self, chromatograms, ax=None, colorizer=None, orderer=None): + if ax is None: + fig, ax = plt.subplots(1) + if colorizer is None: + colorizer = NGlycanCompositionColorizer + if orderer is None: + orderer = NGlycanCompositionOrderer + self.ax = ax + self.colorizer = colorizer + self.orderer = orderer + self.chromatograms = [c for c in chromatograms if c.glycan_composition is not None] + + def sort_items(self): + return self.orderer.sort(self.chromatograms, key=lambda x: x.glycan_composition) + + def get_heights(self, items, **kwargs): + raise NotImplementedError() + + def configure_axes(self): + self.ax.axes.spines['right'].set_visible(False) + self.ax.axes.spines['top'].set_visible(False) + self.ax.yaxis.tick_left() + self.ax.xaxis.set_ticks_position('none') + self.ax.xaxis.set_ticks_position('none') + self.ax.set_title(self.plot_title, fontsize=24) + self.ax.set_ylabel(self.y_label, fontsize=18) + + def __len__(self): + return len(self.sort_items()) + + def prepare_x_args(self): + items = self.sort_items() + keys = [c.glycan_composition for c in items] + include_classes = set(map(self.colorizer.classify, keys)) + xtick_labeler = GlycanLabelTransformer(keys, self.orderer) + color = list(map(self.colorizer, keys)) + self.indices = indices = np.arange(len(items)) + + self.xtick_labeler = xtick_labeler + self.keys = keys + self.color = color + self.include_classes = include_classes + self.items = items + + return items, keys, include_classes, xtick_labeler, color, indices + + def configure_x_axis(self): + ax = self.ax + ax.set_xticks(self.indices + (self.bar_width)) + n = len(self.indices) + if not n: + n = 1 + font_size = min( + max( + (150. / (n / 2.)), + 3), + 24) + + ax.set_xlabel(self.xtick_labeler.label_key, fontsize=14) + ax.set_xticklabels(tuple(self.xtick_labeler), rotation=90, ha='center', size=font_size) + if len(self.indices) == 1: + lo, hi = ax.get_xlim() + hi *= 2 + ax.set_xlim(lo, hi) + + def draw(self, logscale=False): + items, keys, include_classes, xtick_labeler, color, indices = self.prepare_x_args() + heights = self.get_heights(items, logscale) + + self.bars = self.ax.bar( + indices + self.bar_width, heights, + width=self.bar_width, color=color, alpha=self.alpha, lw=0) + + self.configure_x_axis() + + handles = NGlycanCompositionColorizer.make_legend( + include_classes, alpha=self.alpha) + if handles: + self.ax.legend(handles=handles, bbox_to_anchor=(1.20, 1.0)) + + self.configure_axes() + + return self + + +class BundledGlycanComposition(object): + def __init__(self, glycan_composition, total_signal): + self.glycan_composition = HashableGlycanComposition.parse(str(glycan_composition)) + self.total_signal = float(total_signal) + + def __hash__(self): + return hash(self.glycan_composition) + + def __str__(self): + return str(self.glycan_composition) + + def __eq__(self, other): + return self.glycan_composition == other + + def __repr__(self): + return ""BundledGlycanComposition(%s, %e)"" % (self.glycan_composition, self.total_signal) + + @classmethod + def aggregate(cls, observations): + signals = Counter() + for obs in observations: + signals[obs.glycan_composition] += obs.total_signal + return [cls(k, v) for k, v in signals.items() if v > 0] + + +class AggregatedAbundanceArtist(EntitySummaryBarChartArtist): + y_label = ""Relative Intensity"" + plot_title = ""Glycan Composition\nTotal Abundances"" + + def get_heights(self, items, logscale=False, *args, **kwargs): + heights = [c.total_signal for c in items] + if logscale: + heights = np.log2(heights) + return heights + + +class ScoreBarArtist(EntitySummaryBarChartArtist): + y_label = ""Composition Score"" + plot_title = ""Glycan Composition Scores"" + + def get_heights(self, items, *args, **kwargs): + heights = [c.score for c in items] + return heights +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/map_glycan_network.py",".py","3709","111","import numpy as np +from matplotlib import pyplot as plt +from glycresoft.composition_distribution_model import laplacian_matrix + + +def _spectral_layout(network): + eigvals, eigvects = np.linalg.eig(laplacian_matrix(network)) + index = np.argsort(eigvects)[2:3] + coords = (eigvects[:, index[0][0]], eigvects[:, index[0][1]]) + return coords + + +def draw_network(network, ax=None, layout='spectral'): + if ax is None: + fig, ax = plt.subplots(1) + font_args = {""ha"": ""center"", 'va': 'center', ""fontdict"": {""family"": ""monospace""}} + + # Spectral Layout Algorithm + if layout == 'spectral': + coords = _spectral_layout(network) + elif layout == 'spring': + coords = _spring_layout(network) + + seen_edges = set() + for node in network.nodes: + xc, yc = coords[0][node.index], coords[1][node.index] + ax.scatter(xc, yc, s=250, alpha=0.5) + label = str(node) + label = '\n'.join([t.replace("":"", """") for t in label[1:-1].split(""; "")]) + ax.text(xc, yc, label, size=10, **font_args) + for e in node.edges: + if e in seen_edges: + continue + else: + seen_edges.add(e) + neighbor = e[node] + neigh_xc, neigh_yc = coords[0][neighbor.index], coords[1][neighbor.index] + ax.plot((xc, neigh_xc), (yc, neigh_yc), color='grey', alpha=0.5) + center_xc = (xc + neigh_xc) / 2. + center_yc = (yc + neigh_yc) / 2. + ax.text(center_xc, center_yc, ""%0.2f"" % (1. / e.order), size=7, **font_args) + ax.axis(""off"") + return ax + + +class VertexWrapper(object): + def __init__(self, node, position, dispersion): + self.node = node + self.position = position + self.dispersion = dispersion + + def __eq__(self, other): + return self.node == other.node + + def __ne__(self, other): + return self.node != other.node + + +def _spring_layout(network, width=None, height=None, maxiter=3): + if width is None: + width = 50.0 + if height is None: + height = 50.0 + area = width * height + area = float(area) + vertices = [] + X, Y = np.random.random(len(network)), np.random.random(len(network)) + temperature = 100.0 + iters = 0 + while iters < maxiter: + for i, node in enumerate(network.nodes): + vert = VertexWrapper(node, np.array((X[i], Y[i])), 0) + vertices.append(vert) + k = np.sqrt(area / i) + + def attract(x): + return (x * x) / k + + def repel(x): + return (k * k) / x + + for v in vertices: + v.dispersion = 0 + for u in vertices: + if v == u: + continue + delta = v.position - u.position + magdelta = len(delta) + v.dispersion = v.dispersion + (delta / magdelta) * repel(magdelta) + + for edge in network.edges: + v = vertices[edge.node1.index] + u = vertices[edge.node2.index] + delta = v.position - u.position + magdelta = len(delta) + attract_magdelta = attract(magdelta) + delta_magdelta_ratio = (delta / magdelta) + dispersion_shift = delta_magdelta_ratio * attract_magdelta + + v.dispersion = v.dispersion - dispersion_shift + u.dispersion = u.dispersion + dispersion_shift + + for v in vertices: + v.position = v.position + (v.dispersion / len(v.dispersion)) * temperature + v.position /= 1e4 + temperature = max(temperature / 2., 1) + iters += 1 + X = (np.array([v.position[0] for v in vertices]) + 5) * 10 + Y = (np.array([v.position[1] for v in vertices]) + 5) * 10 + return X, Y +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/__init__.py",".py","1607","43","from .base import ArtistBase + +from .chromatogram_artist import ( + ChromatogramArtist, SmoothingChromatogramArtist, + ChargeSeparatingChromatogramArtist, ChargeSeparatingSmoothingChromatogramArtist, + NGlycanChromatogramColorizer, LabelProducer, NGlycanLabelProducer, n_glycan_labeler, + AbundantLabeler, n_glycan_colorizer) + +from .entity_bar_chart import ( + EntitySummaryBarChartArtist, AggregatedAbundanceArtist, + BundledGlycanComposition, ScoreBarArtist) + +from .colors import ( + ColorMapper) + +from .glycan_visual_classification import ( + GlycanCompositionOrderer, GlycanCompositionClassifierColorizer, + NGlycanCompositionColorizer, NGlycanCompositionOrderer, + GlycanLabelTransformer) + +from .plot_glycoforms import GlycoformLayout + +from . import sequence_fragment_logo +from .sequence_fragment_logo import glycopeptide_match_logo + +from .utils import figax, figure + + +__all__ = [ + ""ChromatogramArtist"", ""SmoothingChromatogramArtist"", + ""ChargeSeparatingChromatogramArtist"", ""ChargeSeparatingSmoothingChromatogramArtist"", + ""NGlycanChromatogramColorizer"", ""LabelProducer"", ""NGlycanLabelProducer"", ""n_glycan_labeler"", + ""AbundantLabeler"", ""ArtistBase"", + ""n_glycan_colorizer"", ""ColorMapper"", + ""EntitySummaryBarChartArtist"", ""AggregatedAbundanceArtist"", + ""BundledGlycanComposition"", ""ScoreBarArtist"", + ""GlycanCompositionOrderer"", ""GlycanCompositionClassifierColorizer"", + ""NGlycanCompositionColorizer"", ""NGlycanCompositionOrderer"", + ""GlycanLabelTransformer"", ""GlycoformLayout"", + ""sequence_fragment_logo"", ""glycopeptide_match_logo"", + ""figax"", ""figure"", +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/summaries.py",".py","4154","122","from collections import OrderedDict +from matplotlib import pyplot as plt + +from .chromatogram_artist import ( + SmoothingChromatogramArtist, AbundantLabeler, + NGlycanLabelProducer, n_glycan_colorizer) + +from .entity_bar_chart import AggregatedAbundanceArtist, BundledGlycanComposition +from .utils import figax + + +class GlycanChromatographySummaryGraphBuilder(object): + def __init__(self, solutions): + self.solutions = solutions + + def chromatograms(self, min_score=0.4, min_signal=0.2, colorizer=None, total_ion_chromatogram=None, + base_peak_chromatogram=None, ax=None): + if ax is None: + ax = figax() + monosaccharides = set() + + for sol in self.solutions: + if sol.glycan_composition: + monosaccharides.update(map(str, sol.glycan_composition)) + + label_abundant = AbundantLabeler( + NGlycanLabelProducer(monosaccharides), + max(sol.total_signal for sol in self.solutions if sol.score > min_score) * min_signal) + + if colorizer is None: + colorizer = n_glycan_colorizer + + results = [sol for sol in self.solutions if sol.score > min_score and not sol.used_as_mass_shift] + chrom = SmoothingChromatogramArtist( + results, ax=ax, colorizer=colorizer).draw(label_function=label_abundant) + + if total_ion_chromatogram is not None: + rt, intens = total_ion_chromatogram.as_arrays() + chrom.draw_generic_chromatogram( + ""TIC"", rt, intens, 'blue') + chrom.ax.set_ylim(0, max(intens) * 1.1) + + if base_peak_chromatogram is not None: + rt, intens = base_peak_chromatogram.as_arrays() + chrom.draw_generic_chromatogram( + ""BPC"", rt, intens, 'green') + return chrom + + def aggregated_abundance(self, min_score=0.4, ax=None): + if ax is None: + ax = figax() + agg = AggregatedAbundanceArtist( + BundledGlycanComposition.aggregate([ + sol for sol in self.solutions if (sol.score > min_score and + sol.glycan_composition is not None and + not sol.used_as_mass_shift)]), + ax=ax) + if len(agg) == 0: + ax = agg.ax + ax.text(0.5, 0.5, ""No Entities Matched"", ha='center') + ax.set_axis_off() + else: + agg.draw() + return agg + + def draw(self, min_score=0.4, min_signal=0.2, colorizer=None, total_ion_chromatogram=None, + base_peak_chromatogram=None): + chrom = self.chromatograms(min_score, min_signal, colorizer, + total_ion_chromatogram, base_peak_chromatogram) + agg = self.aggregated_abundance(min_score) + return chrom, agg + + +def breaklines(cases): + counts = OrderedDict() + counter = 0 + ms2_score = 0 + cases = sorted(cases, key=lambda x: x.ms2_score, reverse=True) + i = 0 + for case in cases: + i += 1 + if case.ms2_score == ms2_score: + counter += 1 + else: + counts[ms2_score] = counter + ms2_score = case.ms2_score + counter += 1 + if counts[0] == 0: + counts.pop(0) + return counts + + +def plot_tapering(cases, threshold=0.05, ax=None, **kwargs): + plot_kwargs = { + ""alpha"": 0.5, + ""lw"": 2 + } + plot_kwargs.update(kwargs) + counts = breaklines(cases) + if ax is None: + fig, ax = plt.subplots(1) + + score_at_threshold = float('inf') + for t in cases: + if t.q_value < 0.05: + if t.score < score_at_threshold: + score_at_threshold = t.score + + ax.spines['top'].set_visible(False) + ax.spines['right'].set_visible(False) + ax.xaxis.tick_bottom() + ax.yaxis.tick_left() + ax.plot(*zip(*counts.items()), **plot_kwargs) + ax.set_xlim(*(ax.get_xlim()[::-1])) + + xlim = ax.get_xlim() + ax.hlines(counts[score_at_threshold], max(xlim), 0, linestyles='--') + + ax.set_xlabel(""PSM Score Threshold"", fontsize=18) + ax.set_ylabel(""# of PSMS < Threshold"", fontsize=18) + return ax +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/svg_utils.py",".py","1192","44","# try: # pragma: no cover +# from cStringIO import StringIO +# except: # pragma: no cover +# try: +# from StringIO import StringIO +# except: +# from io import StringIO +# from io import StringIO +from io import BytesIO +try: # pragma: no cover + from lxml import etree as ET +except ImportError: # pragma: no cover + try: + from xml.etree import cElementTree as ET + except ImportError: + from xml.etree import ElementTree as ET + + +class IDMapper(dict): + ''' + A dictionary-like container which uses a format-string + key pattern to generate unique identifiers for each entry + + Key Pattern: '-%d' + + Associates each generated id with a dictionary of metadata and + sets the `gid` of the passed `matplotlib.Artist` to the generated + id. Only the id and metadata are stored. + + Used to preserve a mapping of metadata to artists for later SVG + serialization. + ''' + + def __init__(self): + dict.__init__(self) + self.counter = 0 + + def add(self, key, value, meta): + label = key % self.counter + value.set_gid(label) + self[label] = meta + self.counter += 1 + return label +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/glycan_visual_classification.py",".py","7732","217","from collections import OrderedDict + +from six import string_types as basestring + +from matplotlib import patches as mpatches + +from glypy.structure.glycan_composition import FrozenGlycanComposition, FrozenMonosaccharideResidue +from glycopeptidepy.utils import simple_repr + +from glycresoft.database.composition_network import ( + CompositionRangeRule, + CompositionRuleClassifier, + CompositionRatioRule, + normalize_composition) + + +def _degree_monosaccharide_alteration(x): + try: + if not isinstance(x, FrozenMonosaccharideResidue): + x = FrozenMonosaccharideResidue.from_iupac_lite(str(x)) + return (len(x.modifications), len(x.substituent_links)) + except Exception: + return (float('inf'), float('inf')) + + +class GlycanCompositionOrderer(object): + def __init__(self, priority_residues=None, sorter=None): + self.priority_residues = priority_residues or [] + self.sorter = sorter or _degree_monosaccharide_alteration + + self.priority_residues = [ + residue if isinstance( + residue, FrozenMonosaccharideResidue) else FrozenMonosaccharideResidue.from_iupac_lite( + residue) + for residue in self.priority_residues + ] + + outer = self + + class _ComparableProxy(object): + def __init__(self, composition, obj=None): + if isinstance(composition, basestring): + composition = FrozenGlycanComposition.parse(composition) + if obj is None: + obj = composition + self.composition = composition + self.obj = obj + + def __iter__(self): + return iter(self.composition) + + def __getitem__(self, key): + return self.composition[key] + + def __lt__(self, other): + return outer(self, other) < 0 + + def __gt__(self, other): + return outer(self, other) > 0 + + def __eq__(self, other): + return outer(self, other) == 0 + + def __le__(self, other): + return outer(self, other) <= 0 + + def __ge__(self, other): + return outer(self, other) >= 0 + + def __ne__(self, other): + return outer(self, other) != 0 + + self._comparable_proxy = _ComparableProxy + + def sort(self, compositions, key=None, reverse=False): + if key is None: + + def key(x): # pylint: disable=function-redefined + return x + + proxies = [self._comparable_proxy(key(c), c) for c in compositions] + proxies = sorted(proxies, reverse=reverse) + out = [p.obj for p in proxies] + return out + + def key_order(self, keys): + keys = list(keys) + for r in reversed(self.priority_residues): + try: + i = keys.index(r) + keys.pop(i) + keys = [r] + keys + except ValueError: + pass + return keys + + def __call__(self, a, b): + if isinstance(a, basestring): + a = normalize_composition(a) + b = normalize_composition(b) + keys = self.key_order(sorted(set(a) | set(b), key=self.sorter)) + + for key in keys: + if a[key] < b[key]: + return -1 + elif a[key] > b[key]: + return 1 + else: + continue + return 0 + + __repr__ = simple_repr + + +class allset(frozenset): + def __contains__(self, k): + return True + + +class GlycanCompositionClassifierColorizer(object): + def __init__(self, rule_color_map=None, default=None): + self.rule_color_map = rule_color_map or {} + self.default = default + + def __call__(self, obj): + obj = normalize_composition(obj) + for rule, color in self.rule_color_map.items(): + if rule(obj): + return color + if self.default: + return self.default + raise ValueError(""Could not classify %r"" % obj) + + def classify(self, obj): + for rule, color in self.rule_color_map.items(): + if rule(obj): + return rule.name + return None + + __repr__ = simple_repr + + def make_legend(self, included=allset(), alpha=0.5): + return [ + mpatches.Patch( + label=rule.name, color=color, alpha=alpha) for rule, color in self.rule_color_map.items() + if rule.name in included + ] + + +NGlycanCompositionColorizer = GlycanCompositionClassifierColorizer(OrderedDict([ + (CompositionRuleClassifier(""Sulfated Hybrid"", [ + CompositionRangeRule(""HexNAc"", 3, 3) & CompositionRangeRule(""@sulfate"", 1)]), 'yellow'), + (CompositionRuleClassifier(""Sulfated Bi-Antennary"", + [CompositionRangeRule(""HexNAc"", 4, 4) & CompositionRangeRule(""@sulfate"", 1)]), 'teal'), + (CompositionRuleClassifier(""Sulfated Tri-Antennary"", + [CompositionRangeRule(""HexNAc"", 5, 5) & CompositionRangeRule(""@sulfate"", 1)]), 'rosybrown'), + (CompositionRuleClassifier(""Sulfated Tetra-Antennary"", + [CompositionRangeRule(""HexNAc"", 6, 6) & CompositionRangeRule(""@sulfate"", 1)]), 'magenta'), + (CompositionRuleClassifier(""Paucimannose"", [ + CompositionRangeRule(""HexNAc"", 2, 2) & CompositionRangeRule(""Hex"", 0, 4)]), ""#f05af0""), + (CompositionRuleClassifier(""High Mannose"", [ + CompositionRangeRule(""HexNAc"", 2, 2)]), '#1f77b4'), + (CompositionRuleClassifier(""Hybrid"", [ + CompositionRangeRule(""HexNAc"", 3, 3)]), '#ff7f0e'), + (CompositionRuleClassifier(""Bi-Antennary"", + [CompositionRangeRule(""HexNAc"", 4, 4)]), '#2ca02c'), + (CompositionRuleClassifier(""Tri-Antennary"", + [CompositionRangeRule(""HexNAc"", 5, 5)]), '#d62728'), + (CompositionRuleClassifier(""Tetra-Antennary"", + [CompositionRangeRule(""HexNAc"", 6, 6)]), '#9467bd'), + (CompositionRuleClassifier(""Penta-Antennary"", + [CompositionRangeRule(""HexNAc"", 7, 7)]), '#8c564b'), + (CompositionRuleClassifier(""Supra-Penta-Antennary"", + [CompositionRangeRule(""HexNAc"", 8)]), 'brown'), + (CompositionRuleClassifier(""Low Sulfate GAG"", [ + CompositionRatioRule(""HexN"", ""@sulfate"", (0, 2))]), ""#2aaaaa""), + (CompositionRuleClassifier(""High Sulfate GAG"", [ + CompositionRatioRule(""HexN"", ""@sulfate"", (2, 4))]), ""#88faaa"") +]), default=""slateblue"") + +NGlycanCompositionOrderer = GlycanCompositionOrderer([""HexNAc"", ""Hex"", ""Fuc"", ""NeuAc""]) + +_null_color_chooser = GlycanCompositionClassifierColorizer({}, default='blue') + + +class GlycanLabelTransformer(object): + def __init__(self, label_series, order_chooser): + self._input_series = label_series + self.order_chooser = order_chooser + self.residues = None + self._infer_compositions() + + def _infer_compositions(self): + residues = set() + for item in self._input_series: + if isinstance(item, basestring): + item = normalize_composition(item) + residues.update(item) + + residues = sorted(residues, key=_degree_monosaccharide_alteration) + self.residues = self.order_chooser.key_order(residues) + + def transform(self): + for item in self._input_series: + if isinstance(item, basestring): + item = normalize_composition(item) + counts = [str(item[r]) for r in self.residues] + yield '[%s]' % '; '.join(counts) + + __iter__ = transform + + __repr__ = simple_repr + + @property + def label_key(self): + return ""Key: [%s]"" % '; '.join(map(str, self.residues)) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/colors.py",".py","5003","131","from itertools import cycle +from matplotlib.colors import cnames, hex2color, rgb_to_hsv, hsv_to_rgb +from matplotlib import patches as mpatches + + +def lighten(rgb, factor=0.25): + '''Given a triplet of rgb values, lighten the color by `factor`%''' + factor += 1 + return [min(c * factor, 1) for c in rgb] + + +def darken(rgb, factor=0.25): + '''Given a triplet of rgb values, darken the color by `factor`%''' + factor = 1 - factor + return [(c * factor) for c in rgb] + + +def deepen(rgb, factor=0.25): + hsv = rgb_to_hsv(rgb) + hsv[1] = min(hsv[1] * (1 + factor), 1) + return hsv_to_rgb(hsv) + + +colors = cycle([hex2color(cnames[name]) for name in ( + ""red"", ""blue"", ""yellow"", ""purple"", ""navy"", ""grey"", ""coral"", ""forestgreen"", ""limegreen"", ""maroon"", ""aqua"", + ""lavender"", ""lightcoral"", ""mediumorchid"")]) + + +class ColorMapper(object): + colors = [hex2color(cnames[name]) for name in ( + ""red"", ""blue"", ""yellow"", ""purple"", ""navy"", ""grey"", ""coral"", ""forestgreen"", ""limegreen"", ""maroon"", ""aqua"", + ""lavender"", ""lightcoral"", ""mediumorchid"")] + + def __init__(self): + self.color_name_map = { + ""HexNAc"": hex2color(cnames[""mediumseagreen""]), + ""N-Glycosylation"": hex2color(cnames[""mediumseagreen""]), + ""O-Glycosylation"": hex2color(cnames[""cadetblue""]), + ""GAG-Linker"": hex2color(cnames['burlywood']), + ""Xyl"": hex2color(cnames['darkorange']), + ""a,enHex"": hex2color(cnames['lightskyblue']), + ""aHex"": hex2color(cnames['plum']), + ""Hex"": hex2color(cnames['steelblue']), + ""Neu5Ac"": hex2color(cnames['blueviolet']), + ""Neu5Gc"": hex2color(cnames['lightsteelblue']), + ""Fuc"": hex2color(cnames['crimson']) + } + self.color_generator = cycle(self.colors) + + def get_color(self, name): + """"""Given a name, find the color mapped to that name, or + select the next color from the `colors` generator and assign + it to the name and return the new color. + + Parameters + ---------- + name : object + Any hashable object, usually a string + + Returns + ------- + tuple: RGB triplet + """""" + try: + return self.color_name_map[name] + except KeyError: + o = self.color_name_map[name] = next(self.color_generator) + return o + + __getitem__ = get_color + + def __setitem__(self, name, color): + self.color_name_map[name] = color + + def __repr__(self): + return repr(self.color_name_map) + + darken = staticmethod(darken) + lighten = staticmethod(lighten) + + def keys(self): + return self.color_name_map.keys() + + def items(self): + return self.color_name_map.items() + + def proxy_artists(self, subset=None): + proxy_artists = [] + if subset is not None: + for name, color in self.items(): + if name in subset: + artist = mpatches.Rectangle((0, 0), 1, 1, fc=color, label=name) + proxy_artists.append((name, artist)) + else: + for name, color in self.items(): + artist = mpatches.Rectangle((0, 0), 1, 1, fc=color, label=name) + proxy_artists.append((name, artist)) + return proxy_artists + + +_color_mapper = ColorMapper() + +color_name_map = _color_mapper.color_name_map +get_color = _color_mapper.get_color +proxy_artists = _color_mapper.proxy_artists + + +def color_dict(): + return {str(k): v for k, v in _color_mapper.items()} + + +material_palette = [(0.9568627450980393, 0.2627450980392157, 0.21176470588235294), + (0.24705882352941178, 0.3176470588235294, 0.7098039215686275), + (0.2980392156862745, 0.6862745098039216, 0.3137254901960784), + (1.0, 0.596078431372549, 0.0), + (0.9137254901960784, 0.11764705882352941, 0.38823529411764707), + (0.12941176470588237, 0.5882352941176471, 0.9529411764705882), + (0.5450980392156862, 0.7647058823529411, 0.2901960784313726), + (1.0, 0.3411764705882353, 0.13333333333333333), + (0.011764705882352941, 0.6627450980392157, 0.9568627450980393), + (0.803921568627451, 0.8627450980392157, 0.2235294117647059), + (0.4745098039215686, 0.3333333333333333, 0.2823529411764706), + (0.611764705882353, 0.15294117647058825, 0.6901960784313725), + (0.0, 0.7372549019607844, 0.8313725490196079), + (1.0, 0.9215686274509803, 0.23137254901960785), + (0.6196078431372549, 0.6196078431372549, 0.6196078431372549), + (0.403921568627451, 0.22745098039215686, 0.7176470588235294), + (0.0, 0.5882352941176471, 0.5333333333333333), + (1.0, 0.7568627450980392, 0.027450980392156862), + (0.3764705882352941, 0.49019607843137253, 0.5450980392156862)] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/lcms_map.py",".py","4886","164","from collections import defaultdict + +import numpy as np +import matplotlib +from matplotlib import pyplot as plt + + +def _make_color_map(): + # Derived from the seaborn.cubehelix_palette function + start = .5 + rot = - .75 + gamma = 1.0 + hue = 0.8 + light = 0.85 + dark = 0.15 + cdict = matplotlib._cm.cubehelix(gamma, start, rot, hue) + cmap = matplotlib.colors.LinearSegmentedColormap(""cubehelix"", cdict) + x_256 = np.linspace(light, dark, 256) + pal_256 = cmap(x_256) + cmap = matplotlib.colors.ListedColormap(pal_256) + return cmap + + +_color_map = _make_color_map() + + +def extract_intensity_array(peaks): + mzs = [] + intensities = [] + rts = [] + current_mzs = [] + current_intensities = [] + last_time = None + for peak, time in peaks: + if time != last_time: + if last_time is not None: + mzs.append(current_mzs) + intensities.append(current_intensities) + rts.append(time) + last_time = time + current_mzs = [] + current_intensities = [] + current_mzs.append(peak.mz) + current_intensities.append(peak.intensity) + mzs.append(current_mzs) + intensities.append(current_intensities) + rts.append(time) + return mzs, intensities, rts + + +def binner(x): + return np.floor(np.array(x) / 10.) * 10 + + +def make_map(mzs, intensities): + binned_mzs = [ + binner(mz_row) for mz_row in mzs + ] + unique_mzs = set() + map(unique_mzs.update, binned_mzs) + unique_mzs = np.array(sorted(unique_mzs)) + assigned_bins = [] + j = 0 + for mz, inten in zip(mzs, intensities): + j += 1 + mz = binner(mz) + bin_row = defaultdict(float) + for i in range(len(mz)): + k = mz[i] + v = inten[i] + bin_row[k] += v + array_row = np.array([bin_row[m] for m in unique_mzs]) + assigned_bins.append(array_row) + + assigned_bins = np.vstack(assigned_bins) + assigned_bins[assigned_bins == 0] = 1 + return assigned_bins, unique_mzs + + +def render_map(assigned_bins, rts, unique_mzs, ax=None, color_map=None, scaler=np.sqrt): + if ax is None: + fig, ax = plt.subplots(1) + if color_map is None: + color_map = _color_map + ax.pcolormesh(np.array(scaler(assigned_bins.T)), cmap=color_map) + + xticks = ax.get_xticks() + newticks = xticks + newlabels = np.array(ax.get_xticklabels())[np.arange(0, len(xticks))] + n = len(newlabels) + step = len(rts) / n + interp = [rts[i * step] for i in range(n)] + + for i, label in enumerate(newlabels): + num = round(interp[i], 1) + label.set_rotation(90) + label.set_text(str((num))) + + ax.set_xticks(newticks) + ax.set_xticklabels(newlabels) + + yticks = ax.get_yticks() + n = len(yticks) + + newticks = yticks[np.arange(0, len(yticks))] + newlabels = np.array(ax.get_yticklabels())[np.arange(0, len(yticks))] + va = unique_mzs + n = len(newlabels) + step = len(va) / n + interp = [va[i * step] for i in range(n)] + for i, label in enumerate(newlabels): + num = interp[i] + label.set_text(str((num))) + ax.set_yticks(newticks) + ax.set_yticklabels(newlabels) + + ax.set_xlabel(""Retention Time"") + ax.set_ylabel(""m/z"") + return ax + + +def get_peak_time_pairs(peak_loader, threshold=None): + if threshold is None: + acc = [] + for scan_id in peak_loader.extended_index.ms1_ids: + header = peak_loader.get_scan_header_by_id(scan_id) + acc.extend(header.arrays[1]) + threshold = np.percentile(acc, 90) + peaks = [] + for scan_id in peak_loader.extended_index.ms1_ids: + scan = peak_loader.get_scan_by_id(scan_id) + for peak in scan.deconvoluted_peak_set: + if peak.intensity > threshold: + peaks.append((peak, scan.scan_time)) + return peaks + + +class LCMSMapArtist(object): + + def __init__(self, peak_time_pairs, ax=None): + if ax is None: + fig, ax = plt.subplots(1) + self.peak_time_pairs = peak_time_pairs + self.ax = ax + + def format_axes(self, axis_font_size=12): + self.ax.axes.spines['right'].set_visible(False) + self.ax.axes.spines['top'].set_visible(False) + self.ax.yaxis.tick_left() + self.ax.xaxis.tick_bottom() + [t.set(fontsize=axis_font_size) for t in self.ax.get_xticklabels()] + [t.set(fontsize=axis_font_size) for t in self.ax.get_yticklabels()] + + def draw(self): + mzs, intensities, rts = extract_intensity_array(self.peak_time_pairs) + binned_intensities, unique_mzs = make_map(mzs, intensities) + render_map(binned_intensities, rts, unique_mzs, self.ax) + self.format_axes() + return self + + @classmethod + def from_peak_loader(cls, peak_loader, threshold=None, ax=None): + return cls(get_peak_time_pairs(peak_loader, threshold=threshold), ax=ax) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/plot_glycoforms.py",".py","26652","686","import operator + +import matplotlib +from matplotlib import font_manager +from matplotlib import pyplot as plt +from matplotlib import patches as mpatches +from matplotlib.textpath import TextPath +from matplotlib.transforms import IdentityTransform, Affine2D + +import numpy as np + +from .svg_utils import ET, BytesIO, IDMapper +from .colors import lighten, darken, get_color + +from glycopeptidepy import PeptideSequence, enzyme + + +font_options = font_manager.FontProperties(family='monospace') + + +def span_overlap(a, b): + if a.end_position == b.start_position or b.end_position == a.start_position: + return False + return (a.spans(b.start_position + 1) or a.spans(b.end_position) or + b.spans(a.start_position + 1) or b.spans(a.end_position)) + + +def layout_layers(gpms, sort_key=operator.attrgetter(""ms2_score"")): + ''' + Produce a non-overlapping stacked layout of individual peptide-like + identifications across a protein sequence. + ''' + layers = [[]] + gpms.sort(key=sort_key, reverse=True) + for gpm in gpms: + placed = False + for layer in layers: + collision = False + for member in layer: + if span_overlap(gpm, member): + collision = True + break + if not collision: + layer.append(gpm) + placed = True + break + if not placed: + layers.append([gpm]) + # import IPython + # IPython.embed() + return layers + + +def ndigits(x): + digits = 0 + while x > 0: + x //= 10 + digits += 1 + return digits + + +class GlycoformLayout(object): + def __init__(self, protein, glycopeptides, scale_factor=1.0, ax=None, row_width=50, + sort_key=operator.attrgetter('ms2_score'), **kwargs): + if ax is None: + figure, ax = plt.subplots(1, 1) + self.protein = protein + self.sort_key = sort_key + layers = self.layout_layers(glycopeptides) + for layer in layers: + layer.sort(key=lambda x: x.start_position) + self.layers = layers + self.id_mapper = IDMapper() + self.ax = ax + self.row_width = min(row_width, len(protein)) + self.options = kwargs + self.layer_height = 0.56 * scale_factor + self.y_step = (self.layer_height + 0.15) * -scale_factor + + self.cur_y = -3 + self.cur_position = 0 + + self.mod_text_x_offset = 0.50 * scale_factor + self.sequence_font_size = 6. * scale_factor + self.mod_font_size = 2.08 * scale_factor + self.mod_text_y_offset = 0.1 * scale_factor + self.mod_width = 0.5 * scale_factor + self.mod_x_offset = 0.60 * scale_factor + self.total_length = len(protein.protein_sequence or '') + self.protein_pad = -0.365 * scale_factor + self.peptide_pad = self.protein_pad * (1.2) + self.peptide_end_pad = 0.35 * scale_factor + + self.glycosites = set(protein.n_glycan_sequon_sites) + + def layout_layers(self, glycopeptides): + layers = [[]] + glycopeptides = list(glycopeptides) + glycopeptides.sort(key=self.sort_key, reverse=True) + for gpm in glycopeptides: + placed = False + for layer in layers: + collision = False + for member in layer: + if span_overlap(gpm, member): + collision = True + break + if not collision: + layer.append(gpm) + placed = True + break + if not placed: + layers.append([gpm]) + return layers + + def draw_protein_main_sequence(self, current_position): + next_row = current_position + self.row_width + i = -1 + offset = current_position + 1 + digits = ndigits(offset) + i -= (digits - 1) * 0.5 + text_path = TextPath( + (self.protein_pad + i, self.layer_height + .2 + self.cur_y), + str(current_position + 1), size=self.sequence_font_size / 7.5, + prop=font_options) + patch = mpatches.PathPatch(text_path, facecolor='grey', edgecolor='grey', lw=0.04) + self.ax.add_patch(patch) + + i = self.row_width + text_path = TextPath( + (self.protein_pad + i, self.layer_height + .2 + self.cur_y), + str(next_row), size=self.sequence_font_size / 7.5, + prop=font_options) + patch = mpatches.PathPatch(text_path, facecolor='grey', edgecolor='grey', lw=0.04) + self.ax.add_patch(patch) + self._draw_main_sequence(current_position, next_row) + + def _draw_main_sequence(self, start, end): + for i, aa in enumerate(self.protein.protein_sequence[start:end]): + text_path = TextPath( + (self.protein_pad + i, self.layer_height + .2 + self.cur_y), + aa, size=self.sequence_font_size / 7.5, prop=font_options) + color = 'red' if any( + (((i + start) in self.glycosites), + ((i + start - 1) in self.glycosites), + ((i + start - 2) in self.glycosites)) + ) else 'black' + patch = mpatches.PathPatch(text_path, facecolor=color, edgecolor=color, lw=0.04) + self.ax.add_patch(patch) + + def next_row(self): + if self.cur_position > len(self.protein): + return False + self.cur_y += self.y_step * 3 + self.cur_position += self.row_width + if self.cur_position >= len(self.protein): + return False + return True + + def _pack_sequence_metadata(self, rect, gpm): + self.id_mapper.add(""glycopeptide-%d"", rect, { + ""sequence"": str(gpm.structure), + ""start-position"": gpm.start_position, + ""end-position"": gpm.end_position, + ""ms2-score"": gpm.ms2_score, + ""q-value"": gpm.q_value, + ""record-id"": gpm.id if hasattr(gpm, 'id') else None, + ""calculated-mass"": gpm.structure.total_mass, + ""spectra-count"": len(gpm.spectrum_matches) + }) + + def _get_sequence(self, gpm): + try: + return gpm.structure + except AttributeError: + return PeptideSequence(str(gpm)) + + def draw_peptide_block(self, gpm, current_position, next_row): + color, alpha = self._compute_sequence_color(gpm) + + interval_start = max(gpm.start_position - current_position, 0) + interval_end = min( + len(self._get_sequence(gpm)) + gpm.start_position - current_position, + self.row_width) + + rect = mpatches.Rectangle( + (interval_start + self.peptide_pad, self.cur_y), + width=(interval_end - interval_start) - self.peptide_end_pad, + height=self.layer_height, + facecolor=color, edgecolor='none', + alpha=alpha) + self._pack_sequence_metadata(rect, gpm) + + self.ax.add_patch(rect) + return interval_start, interval_end + + def _compute_sequence_indices(self, gpm, current_position): + # Compute offsets into the peptide sequence to select + # PTMs to draw for this row + if (current_position) > gpm.start_position: + start_index = current_position - gpm.start_position + if gpm.end_position - start_index > self.row_width: + end_index = min( + self.row_width, + len(self._get_sequence(gpm))) + else: + end_index = gpm.end_position - start_index + else: + start_index = min(0, gpm.start_position - current_position) + end_index = min( + gpm.end_position - current_position, + self.row_width - (gpm.start_position - current_position)) + return start_index, end_index + + def _compute_sequence_color(self, gpm): + color = ""lightblue"" + alpha = min(max(self.sort_key(gpm) * 2, 0.2), 0.8) + return color, alpha + + def _compute_modification_color(self, gpm, modification): + color = get_color(modification.name) + return color + + def draw_modification_chips(self, gpm, current_position): + start_index, end_index = self._compute_sequence_indices(gpm, current_position) + + # Extract PTMs from the peptide sequence to draw over the + # peptide rectangle + seq = self._get_sequence(gpm) + + for i, pos in enumerate(seq[start_index:end_index]): + if pos.modifications: + modification = pos.modifications[0] + color = self._compute_modification_color(gpm, modification) + facecolor, edgecolor = lighten( + color), darken(color, 0.6) + + mod_patch = mpatches.Rectangle( + (gpm.start_position - current_position + + i - self.mod_x_offset + 0.3 + start_index, self.cur_y), + width=self.mod_width, height=self.layer_height, alpha=0.4, + facecolor=facecolor, edgecolor=edgecolor, linewidth=0.5, + ) + + self.id_mapper.add( + ""modification-%d"", mod_patch, + { + ""modification-type"": str(modification), + ""parent"": gpm.id + }) + self.ax.add_patch(mod_patch) + modification_string = str(modification) + modification_symbol = modification_string[0] + if modification_symbol == '@': + modification_symbol = modification_string[1] + text_path = TextPath( + (gpm.start_position - current_position + i - + self.mod_text_x_offset + 0.3 + start_index, + self.cur_y + self.mod_text_y_offset), + modification_symbol, size=self.mod_font_size / 4.5, prop=font_options) + patch = mpatches.PathPatch( + text_path, facecolor='black', lw=0.04) + self.ax.add_patch(patch) + + def draw_peptidoform(self, gpm, current_position, next_row): + self.draw_peptide_block(gpm, current_position, next_row) + self.draw_modification_chips(gpm, current_position) + + def draw_current_row(self, current_position): + next_row = current_position + self.row_width + for layer in self.layers: + c = 0 + for gpm in layer: + if gpm.start_position < current_position and gpm.end_position < current_position: + continue + elif gpm.start_position >= next_row: + break + c += 1 + self.draw_peptidoform(gpm, current_position, next_row) + + if c > 0: + self.cur_y += self.y_step + + def finalize_axes(self, ax=None, remove_axes=True): + if ax is None: + ax = self.ax + ax.set_ylim(self.cur_y - 5, 0.2) + ax.set_xlim(-3., self.row_width + 1) + if remove_axes: + ax.axis('off') + + def draw(self): + self.draw_protein_main_sequence(self.cur_position) + self.draw_current_row(self.cur_position) + while self.next_row(): + self.draw_protein_main_sequence(self.cur_position) + self.draw_current_row(self.cur_position) + self.finalize_axes() + return self + + def to_svg(self, scale=1.5, height_padding_scale=1.2): + ax = self.ax + xlim = ax.get_xlim() + ylim = ax.get_ylim() + ax.autoscale() + + x_size = sum(map(abs, xlim)) + y_size = sum(map(abs, ylim)) + + aspect_ratio = x_size / y_size + canvas_x = 8. + canvas_y = canvas_x / aspect_ratio + + fig = ax.get_figure() + fig.tight_layout(pad=0) + fig.patch.set_visible(False) + fig.set_figwidth(canvas_x) + fig.set_figheight(canvas_y) + + ax.patch.set_visible(False) + buff = BytesIO() + fig.savefig(buff, format='svg') + parser = ET.XMLParser(huge_tree=True) + root, ids = ET.XMLID(buff.getvalue(), parser=parser) + root.attrib['class'] = 'plot-glycoforms-svg' + for id, attributes in self.id_mapper.items(): + element = ids[id] + element.attrib.update({(""data-"" + k): str(v) + for k, v in attributes.items()}) + element.attrib['class'] = id.rsplit('-')[0] + width = float(root.attrib[""width""][:-2]) * 1.75 + root.attrib['width'] = '%fpt' % width + root.attrib.pop(""viewBox"") + + height = width / (aspect_ratio) + + root.attrib[""height""] = ""%dpt"" % (height * height_padding_scale) + root.attrib[""preserveAspectRatio""] = ""xMinYMin meet"" + figure_group = root.find(""./{http://www.w3.org/2000/svg}g/[@id='figure_1']"") + figure_group.attrib[""transform""] = ""scale(%f)"" % scale + svg = ET.tostring(root) + return svg + + +class CompressedPileupLayout(GlycoformLayout): + + default_protein_bar_color = 'black' + n_glycosite_bar_color = 'red' + + def __init__(self, protein, glycopeptides, scale_factor=1.0, ax=None, row_width=50, compression=8, **kwargs): + super(CompressedPileupLayout, self).__init__( + protein, glycopeptides, scale_factor, ax, row_width, **kwargs) + self.compress(compression) + + def compress(self, scale): + self.layer_height /= scale + self.y_step /= scale + + def layout_layers(self, matches): + layers = [[]] + matches = list(matches) + matches.sort(key=lambda x: getattr(x, ""ms2_score"", float('inf')), reverse=True) + for gpm in matches: + placed = False + for layer in layers: + collision = False + for member in layer: + if span_overlap(gpm, member): + collision = True + break + if not collision: + layer.append(gpm) + placed = True + break + if not placed: + layers.append([gpm]) + return layers + + def _make_text_scaler(self): + transform = Affine2D() + transform.scale(self.row_width / 75., 0.5) + return transform + + def draw_protein_main_sequence(self, current_position): + next_row = current_position + self.row_width + transform = self._make_text_scaler() + for i, aa in enumerate(self.protein.protein_sequence[current_position:next_row]): + color = self.n_glycosite_bar_color if (i + current_position) in self.glycosites\ + else self.default_protein_bar_color + rect = mpatches.Rectangle( + (self.protein_pad + i, self.layer_height + .05 + self.cur_y), + width=self.sequence_font_size / 4.5, + height=self.sequence_font_size / 30., + facecolor=color) + self.ax.add_patch(rect) + if i % 100 == 0 and i != 0: + xy = np.array((self.protein_pad + i, self.layer_height + .35 + self.cur_y)) + text_path = TextPath( + xy, + str(current_position + i), size=self.sequence_font_size / 7.5, + prop=font_options) + text_path = text_path.transformed(transform) + new_center = transform.transform(xy) + delta = xy - new_center - (1, 0) + text_path = text_path.transformed(Affine2D().translate(*delta)) + patch = mpatches.PathPatch(text_path, facecolor='grey', lw=0.04) + self.ax.add_patch(patch) + + def _pack_sequence_metadata(self, rect, gpm): + pass + + def _get_sequence(self, gpm): + try: + glycopeptide = gpm.structure + glycopeptide = PeptideSequence(str(glycopeptide)) + return glycopeptide + except AttributeError: + return PeptideSequence(str(gpm)) + + def _compute_sequence_color(self, gpm): + try: + glycopeptide = gpm.structure + glycopeptide = PeptideSequence(str(glycopeptide)) + if ""N-Glycosylation"" in glycopeptide.modification_index: + return 'forestgreen', 0.5 + elif 'O-Glycosylation' in glycopeptide.modification_index: + return 'aquamarine', 0.5 + elif 'GAG-Linker' in glycopeptide.modification_index: + return 'orange', 0.5 + else: + raise ValueError(glycopeptide) + except AttributeError: + return 'red', 0.5 + + def draw_modification_chips(self, gpm, current_position): + return + + def finalize_axes(self, ax=None, remove_axes=True): + super(CompressedPileupLayout, self).finalize_axes(ax, remove_axes) + self.ax.set_xlim(1., self.row_width + 2) + + +class DigestLayout(GlycoformLayout): + def __init__(self, *args, **kwargs): + super(DigestLayout, self).__init__(*args, **kwargs) + protease = enzyme.Protease(kwargs.get(""enzyme"", ""trypsin"")) + self.cleavage_sites = set(i for c in protease.cleave(str(self.protein)) for i in c[1:3] if i != 0) + + def _draw_main_sequence(self, start, end): + for i, aa in enumerate(self.protein.protein_sequence[start:end]): + text_path = TextPath( + (self.protein_pad + i, self.layer_height + .2 + self.cur_y), + aa, size=self.sequence_font_size / 7.5, prop=font_options) + color = 'red' if any( + (((i + start) in self.glycosites), + ((i + start - 1) in self.glycosites), + ((i + start - 2) in self.glycosites)) + ) else 'black' + patch = mpatches.PathPatch(text_path, facecolor=color, edgecolor=color, lw=0.04) + self.ax.add_patch(patch) + if i + start in self.cleavage_sites: + rect = mpatches.Rectangle( + (self.protein_pad + i - 0.33, + self.layer_height + self.cur_y - 0.25), 0.15, 1.5, fc='black') + self.ax.add_patch(rect) + + +def draw_layers(layers, protein, scale_factor=1.0, ax=None, row_width=50, **kwargs): + ''' + Render fixed-width stacked peptide identifications across + a protein. Each shape is rendered with a unique identifier. + ''' + if ax is None: + figure, ax = plt.subplots(1, 1) + id_mapper = IDMapper() + i = 0 + + layer_height = 0.56 * scale_factor + y_step = (layer_height + 0.15) * -scale_factor + cur_y = -3 + + cur_position = 0 + + mod_text_x_offset = 0.50 * scale_factor + sequence_font_size = 6. * scale_factor + mod_font_size = 2.08 * scale_factor + mod_text_y_offset = 0.1 * scale_factor + mod_width = 0.5 * scale_factor + mod_x_offset = 0.60 * scale_factor + total_length = len(protein.protein_sequence or '') + protein_pad = -0.365 * scale_factor + peptide_pad = protein_pad * (1.2) + peptide_end_pad = 0.35 * scale_factor + + glycosites = set(protein.n_glycan_sequon_sites) + for layer in layers: + layer.sort(key=lambda x: x.start_position) + + while cur_position < total_length: + next_row = cur_position + row_width + i = -2 + text_path = TextPath( + (protein_pad + i, layer_height + .2 + cur_y), + str(cur_position + 1), size=sequence_font_size / 7.5, prop=font_options, stretch=1000) + patch = mpatches.PathPatch(text_path, facecolor='grey', lw=0.04) + ax.add_patch(patch) + + i = row_width + 2 + text_path = TextPath( + (protein_pad + i, layer_height + .2 + cur_y), + str(next_row), size=sequence_font_size / 7.5, prop=font_options, stretch=1000) + patch = mpatches.PathPatch(text_path, facecolor='grey', lw=0.04) + ax.add_patch(patch) + + for i, aa in enumerate(protein.protein_sequence[cur_position:next_row]): + text_path = TextPath( + (protein_pad + i, layer_height + .2 + cur_y), + aa, size=sequence_font_size / 7.5, prop=font_options, stretch=1000) + color = 'red' if any( + (((i + cur_position) in glycosites), + ((i + cur_position - 1) in glycosites), + ((i + cur_position - 2) in glycosites)) + ) else 'black' + patch = mpatches.PathPatch(text_path, facecolor=color, lw=0.04) + ax.add_patch(patch) + + for layer in layers: + c = 0 + for gpm in layer: + if gpm.start_position < cur_position and gpm.end_position < cur_position: + continue + elif gpm.start_position >= next_row: + break + c += 1 + + color = ""lightblue"" + alpha = min(max(gpm.ms2_score * 2, 0.2), 0.8) + + interval_start = max( + gpm.start_position - cur_position, + 0) + interval_end = min( + len(gpm.structure) + gpm.start_position - cur_position, + row_width) + + rect = mpatches.Rectangle( + (interval_start + peptide_pad, cur_y), + width=(interval_end - interval_start) - peptide_end_pad, + height=layer_height, + facecolor=color, edgecolor='none', + alpha=alpha) + + id_mapper.add(""glycopeptide-%d"", rect, { + ""sequence"": str(gpm.structure), + ""start-position"": gpm.start_position, + ""end-position"": gpm.end_position, + ""ms2-score"": gpm.ms2_score, + ""q-value"": gpm.q_value, + ""record-id"": gpm.id if hasattr(gpm, 'id') else None, + ""calculated-mass"": gpm.structure.total_mass, + ""spectra-count"": len(gpm.spectrum_matches) + }) + ax.add_patch(rect) + + # Compute offsets into the peptide sequence to select + # PTMs to draw for this row + if (cur_position) > gpm.start_position: + start_index = cur_position - gpm.start_position + if gpm.end_position - start_index > row_width: + end_index = min( + row_width, + len(gpm.structure)) + else: + end_index = gpm.end_position - start_index + else: + start_index = min(0, gpm.start_position - cur_position) + end_index = min( + gpm.end_position - cur_position, + row_width - (gpm.start_position - cur_position)) + + # Extract PTMs from the peptide sequence to draw over the + # peptide rectangle + seq = gpm.structure + + for i, pos in enumerate(seq[start_index:end_index]): + if len(pos[1]) > 0: + color = get_color(pos[1][0].name) + facecolor, edgecolor = lighten( + color), darken(color, 0.6) + + mod_patch = mpatches.Rectangle( + (gpm.start_position - cur_position + + i - mod_x_offset + 0.3 + start_index, cur_y), + width=mod_width, height=layer_height, alpha=0.4, + facecolor=facecolor, edgecolor=edgecolor, linewidth=0.5, + ) + + id_mapper.add( + ""modification-%d"", mod_patch, + { + ""modification-type"": pos[1][0].name, + ""parent"": gpm.id + }) + ax.add_patch(mod_patch) + text_path = TextPath( + (gpm.start_position - cur_position + i - + mod_text_x_offset + 0.3 + start_index, cur_y + mod_text_y_offset), + str(pos[1][0])[0], size=mod_font_size / 4.5, prop=font_options) + patch = mpatches.PathPatch( + text_path, facecolor='black', lw=0.04) + ax.add_patch(patch) + if c > 0: + cur_y += y_step + cur_y += y_step * 3 + cur_position = next_row + + ax.set_ylim(cur_y - 5, 5) + ax.set_xlim(-5, row_width + 5) + ax.axis('off') + return ax, id_mapper + + +def plot_glycoforms(protein, identifications, **kwargs): + layout = GlycoformLayout(protein, identifications, **kwargs) + layout.draw() + return layout.ax, layout.id_mapper + + +def plot_glycoforms_svg(protein, identifications, scale=1.5, ax=None, + margin_left=80, margin_top=0, height_padding_scale=1.2, + **kwargs): + ''' + A specialization of :func:`plot_glycoforms` which adds additional features to SVG images, such as + adding shape metadata to XML tags and properly configuring the viewport and canvas for the figure's + dimensions. + + TODO: replace uses of this function with :meth:`GlycoformLayout.to_svg` + ''' + ax, id_mapper = plot_glycoforms(protein, identifications, ax=ax, **kwargs) + xlim = ax.get_xlim() + ylim = ax.get_ylim() + ax.autoscale() + + x_size = sum(map(abs, xlim)) + y_size = sum(map(abs, ylim)) + + aspect_ratio = x_size / y_size + canvas_x = 8. + canvas_y = canvas_x / aspect_ratio + + fig = ax.get_figure() + # fig.tight_layout(pad=0.2) + fig.tight_layout(pad=0) + fig.patch.set_visible(False) + fig.set_figwidth(canvas_x) + fig.set_figheight(canvas_y) + + ax.patch.set_visible(False) + buff = BytesIO() + fig.savefig(buff, format='svg') + root, ids = ET.XMLID(buff.getvalue()) + root.attrib['class'] = 'plot-glycoforms-svg' + for id, attributes in id_mapper.items(): + element = ids[id] + element.attrib.update({(""data-"" + k): str(v) + for k, v in attributes.items()}) + element.attrib['class'] = id.rsplit('-')[0] + min_x, min_y, max_x, max_y = map(float, root.attrib[""viewBox""].split("" "")) + min_x += margin_left + min_y += margin_top + max_x += 200 + view_box = ' '.join(map(str, (min_x, min_y, max_x, max_y))) + root.attrib[""viewBox""] = view_box + width = float(root.attrib[""width""][:-2]) * 1.75 + root.attrib[""width""] = ""100%"" + + height = width / (aspect_ratio) + + root.attrib[""height""] = ""%dpt"" % (height * height_padding_scale) + root.attrib[""preserveAspectRatio""] = ""xMinYMin meet"" + root[1].attrib[""transform""] = ""scale(%f)"" % scale + svg = ET.tostring(root) + plt.close() + + return svg +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/utils.py",".py","345","15","from matplotlib.figure import Figure +from matplotlib.backends.backend_agg import FigureCanvasAgg + + +def figax(*args, **kwargs): + fig = Figure(*args, **kwargs) + canvas = FigureCanvasAgg(fig) + return fig.add_subplot(1, 1, 1) + + +def figure(*args, **kwargs): + fig = Figure(*args, **kwargs) + canvas = FigureCanvasAgg(fig) + return fig +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/chromatogram_artist.py",".py","15751","447","from itertools import cycle +from typing import List + +from scipy.ndimage import gaussian_filter1d +import numpy as np +from matplotlib import pyplot as plt + +import glypy + +from .glycan_visual_classification import NGlycanCompositionColorizer, NGlycanCompositionOrderer, GlycanLabelTransformer + +from .base import ArtistBase +from ..chromatogram_tree import get_chromatogram, Chromatogram, ChromatogramInterface + + +def split_charge_states(chromatogram): + charge_states = chromatogram.charge_states + versions = {} + last = chromatogram + for charge_state in charge_states: + a, b = last.bisect_charge(charge_state) + if len(a): + versions[charge_state] = a + last = b + return versions + + +def label_include_charges(chromatogram, *args, **kwargs): + return ""%s-%r"" % (default_label_extractor(chromatogram, **kwargs), tuple(chromatogram.charge_states)) + + +def default_label_extractor(chromatogram, **kwargs): + if chromatogram.composition: + return str(chromatogram.composition) + else: + return ""%0.3f %r"" % (chromatogram.neutral_mass, tuple(chromatogram.charge_states)) + + +def binsearch(array: np.ndarray, x: float) -> int: + lo = 0 + hi = len(array) + + while hi != lo: + mid = (hi + lo) // 2 + y = array[mid] + err = y - x + if abs(err) < 1e-6: + return mid + elif (hi - 1) == lo: + return mid + elif err > 0: + hi = mid + else: + lo = mid + return 0 + + +class ColorCycler(object): + def __init__(self, colors=None): + if colors is None: + colors = [""red"", ""green"", ""blue"", ""yellow"", ""purple"", ""grey"", ""black"", ""orange""] + self.color_cycler = cycle(colors) + + def __call__(self, *args, **kwargs): + return next(self.color_cycler) + + +class NGlycanChromatogramColorizer(object): + def __call__(self, chromatogram, default_color=""black""): + if chromatogram.composition is None: + return default_color + else: + try: + return NGlycanCompositionColorizer(chromatogram.glycan_composition) + except Exception: + return default_color + + +n_glycan_colorizer = NGlycanChromatogramColorizer() + + +class LabelProducer(object): + def __init__(self, *args, **kwargs): + pass + + def __call__(self, chromatogram, *args, **kwargs): + return default_label_extractor(chromatogram) + + +class NGlycanLabelProducer(LabelProducer): + """"""Create a square-brace enclosed tuplet of digits denoting the count + of of a specific set of glycan composition components common to N-Glycans. + + Relies on :class:`GlycanLabelTransformer` + + """""" + + def __init__(self, monosaccharides=(""HexNAc"", ""Hex"", ""Fuc"", ""NeuAc"")): + super(NGlycanLabelProducer, self).__init__() + self.monosaccharides = monosaccharides + self.stub = glypy.GlycanComposition() + for x in monosaccharides: + self.stub[x] = -99 + self.label_key = GlycanLabelTransformer([self.stub], NGlycanCompositionOrderer).label_key + + def __call__(self, chromatogram, *args, **kwargs): + if chromatogram.composition is not None: + return list( + GlycanLabelTransformer([chromatogram.glycan_composition, self.stub], NGlycanCompositionOrderer) + )[0] + else: + return ""%0.3f (%s)"" % (chromatogram.neutral_mass, "", "".join(map(str, chromatogram.charge_states))) + + +n_glycan_labeler = NGlycanLabelProducer() + + +class AbundantLabeler(LabelProducer): + def __init__(self, labeler, threshold): + self.labeler = labeler + self.threshold = threshold + + def __call__(self, chromatogram, *args, **kwargs): + if chromatogram.total_signal > self.threshold: + return self.labeler(chromatogram, *args, **kwargs), True + else: + return self.labeler(chromatogram, *args, **kwargs), False + + +class ChromatogramArtist(ArtistBase): + default_label_function = staticmethod(default_label_extractor) + include_points: bool = True + + def __init__( + self, + chromatograms, + ax=None, + colorizer=None, + label_peaks: bool = True, + clip_labels: bool = True, + should_draw_tandem_points: bool = True, + ): + if colorizer is None: + colorizer = ColorCycler() + if ax is None: + fig, ax = plt.subplots(1) + + if len(chromatograms) > 0: + chromatograms = self._resolve_chromatograms_from_argument(chromatograms) + chromatograms = [get_chromatogram(c) for c in chromatograms] + else: + chromatograms = [] + self.max_points = float(""inf"") + if chromatograms: + self.max_points = max([len(c) for c in chromatograms]) + self.chromatograms = chromatograms + self.minimum_ident_time = float(""inf"") + self.maximum_ident_time = 0 + self.maximum_intensity = 0 + self.ax = ax + self.default_colorizer = colorizer + self.legend = None + self.label_peaks = label_peaks + self.clip_labels = clip_labels + self.should_draw_tandem_points = should_draw_tandem_points + + def __iter__(self): + return iter(self.chromatograms) + + def __getitem__(self, i): + return self.chromatograms[i] + + def __len__(self): + return len(self.chromatograms) + + def _resolve_chromatograms_from_argument(self, chromatograms: List[ChromatogramInterface]) -> List[Chromatogram]: + try: + # if not hasattr(chromatograms[0], ""get_chromatogram""): + if not get_chromatogram(chromatograms[0]): + chromatograms = [chromatograms] + except TypeError: + chromatograms = [chromatograms] + return chromatograms + + def draw_generic_chromatogram( + self, label, rt: np.ndarray, heights: np.ndarray, color: str, fill: bool = False, label_font_size: int = 10 + ): + if fill: + s = self.ax.fill_between(rt, heights, alpha=0.25, color=color, label=label) + + else: + s = self.ax.plot(rt, heights, color=color, label=label, alpha=0.5)[0] + + s.set_gid(str(label) + ""-area"") + if self.include_points: + s = self.ax.scatter(rt, heights, color=color, s=1) + s.set_gid(str(label) + ""-points"") + apex = max(heights) + apex_ind = heights.index(apex) + rt_apex = rt[apex_ind] + + if label is not None: + self.ax.text(rt_apex, apex + 1200, label, ha=""center"", fontsize=label_font_size, clip_on=self.clip_labels) + + def draw_group( + self, + label: str, + rt: np.ndarray, + heights: np.ndarray, + color: str, + label_peak: bool = True, + chromatogram: Chromatogram = None, + label_font_size: int = 10, + ): + if chromatogram is not None: + try: + key = str(chromatogram.id) + except AttributeError: + key = str(id(chromatogram)) + else: + key = str(label) + + s = self.ax.fill_between(rt, heights, alpha=0.25, color=color, label=label) + s.set_gid(key + ""-area"") + if self.include_points: + s = self.ax.scatter(rt, heights, color=color, s=1) + s.set_gid(key + ""-points"") + apex = max(heights) + heights = np.array(heights) + maximum_height_mask = heights > apex * 0.95 + apex_indices = np.where(maximum_height_mask)[0] + apex_ind = apex_indices[apex_indices.shape[0] // 2] + rt_apex = rt[apex_ind] + + if label is not None and label_peak: + self.ax.text( + rt_apex, + min(apex * 1.1, apex + 1200), + label, + ha=""center"", + fontsize=label_font_size, + clip_on=self.clip_labels, + ) + + def transform_group(self, rt, heights): + return rt, heights + + def draw_tandem_points(self, rt: np.ndarray, heights: np.ndarray, tandem_solutions: list, color: str): + xs = [] + ys = [] + for tandem in tandem_solutions: + try: + x = tandem.scan_time + except AttributeError: + # we're dealing with a reference or a stub + continue + i = binsearch(rt, x) + x0 = rt[i] + y0 = heights[i] + y1 = 0 + if x0 < x: + if i < len(rt) - 1: + x1 = rt[i + 1] + y1 = heights[i + 1] + else: + x1 = rt[i] + y1 = heights[i] + else: + x1 = x0 + y1 = y0 + if i > 0: + x0 = rt[i - 1] + y0 = heights[i - 1] + else: + x0 = rt[i] + y0 = heights[i] + # interpolate the height at the time coordinate + den = x1 - x0 + if den == 0: + y = (y1 + y0) / 2 + else: + y = (y0 * (x1 - x) + y1 * (x - x0)) / (x1 - x0) + xs.append(x) + ys.append(y) + self.ax.scatter(xs, ys, marker=""X"", s=35, color=color) + + def process_group(self, composition, chromatogram: Chromatogram, label_function=None, **kwargs): + if label_function is None: + label_function = self.default_label_function + + color = self.default_colorizer(chromatogram) + + rt, heights = self.transform_group(*chromatogram.as_arrays()) + + self.maximum_ident_time = max(max(rt), self.maximum_ident_time) + self.minimum_ident_time = min(min(rt), self.minimum_ident_time) + + self.maximum_intensity = max(max(heights), self.maximum_intensity) + + label = label_function(chromatogram, rt=rt, heights=heights, peaks=None) + if isinstance(label, (str, glypy.GlycanComposition)): + label = label + label_peak = True + else: + label, label_peak = label + label_peak = label_peak & self.label_peaks + + self.draw_group(label, rt, heights, color, label_peak, chromatogram, **kwargs) + + try: + tandem_solutions = chromatogram.tandem_solutions + except AttributeError: + tandem_solutions = [] + + if self.should_draw_tandem_points: + self.draw_tandem_points(rt, heights, tandem_solutions, color) + + def _interpolate_xticks(self, xlo, xhi): + self.ax.set_xlim(xlo - 0.01, xhi + 0.01) + tick_values = np.linspace(xlo, xhi, min(5, self.max_points)) + self.ax.set_xticks(tick_values) + self.ax.set_xticklabels([""%0.2f"" % v for v in tick_values]) + + def layout_axes( + self, legend: bool = True, axis_font_size: int = 18, axis_label_font_size: int = 16, legend_cols: int = 2 + ): + self._interpolate_xticks(self.minimum_ident_time, self.maximum_ident_time) + self.ax.set_ylim(0, self.maximum_intensity * 1.25) + if legend: + try: + self.legend = self.ax.legend(bbox_to_anchor=(1.2, 1.0), ncol=legend_cols, fontsize=10) + except ValueError: + # matplotlib 2.1.1 bug compares array-like colors using == and expects a + # scalar boolean, triggering a ValueError. When this happens, we can't + # render a legend. + self.legend = None + self.ax.axes.spines[""right""].set_visible(False) + self.ax.axes.spines[""top""].set_visible(False) + self.ax.yaxis.tick_left() + self.ax.xaxis.tick_bottom() + self.ax.set_xlabel(""Retention Time"", fontsize=axis_label_font_size) + self.ax.set_ylabel(""Relative Abundance"", fontsize=axis_label_font_size) + self.ax.ticklabel_format(axis=""y"", style=""scientific"", scilimits=(0, 0)) + [t.set(fontsize=axis_font_size) for t in self.ax.get_xticklabels()] + [t.set(fontsize=axis_font_size) for t in self.ax.get_yticklabels()] + + def draw( + self, + label_function=None, + legend: bool = True, + label_font_size: int = 10, + axis_label_font_size: int = 16, + axis_font_size: int = 18, + legend_cols: int = 2, + ): + if label_function is None: + label_function = self.default_label_function + for chroma in self.chromatograms: + composition = chroma.composition + self.process_group(composition, chroma, label_function, label_font_size=label_font_size) + self.layout_axes( + legend=legend, + axis_label_font_size=axis_label_font_size, + axis_font_size=axis_font_size, + legend_cols=legend_cols, + ) + return self + + +class SmoothingChromatogramArtist(ChromatogramArtist): + def __init__( + self, + chromatograms, + ax=None, + colorizer=None, + smoothing_factor=1.0, + label_peaks=True, + clip_labels=True, + should_draw_tandem_points: bool = True, + ): + super(SmoothingChromatogramArtist, self).__init__( + chromatograms, + ax=ax, + colorizer=colorizer, + label_peaks=label_peaks, + clip_labels=clip_labels, + should_draw_tandem_points=should_draw_tandem_points, + ) + self.smoothing_factor = smoothing_factor + + def transform_group(self, rt, heights): + heights = gaussian_filter1d(heights, self.smoothing_factor) + return rt, heights + + def draw_generic_chromatogram(self, label, rt, heights, color, fill=False, label_font_size=10): + heights = gaussian_filter1d(heights, self.smoothing_factor) + if fill: + s = self.ax.fill_between(rt, heights, alpha=0.25, color=color, label=label) + + else: + s = self.ax.plot(rt, heights, color=color, label=label, alpha=0.5)[0] + + s.set_gid(str(label) + ""-area"") + s = self.ax.scatter(rt, heights, color=color, s=1) + s.set_gid(str(label) + ""-points"") + apex = max(heights) + apex_ind = np.argmax(heights) + rt_apex = rt[apex_ind] + + if label is not None: + self.ax.text(rt_apex, apex + 1200, label, ha=""center"", fontsize=label_font_size, clip_on=self.clip_labels) + + +class ChargeSeparatingChromatogramArtist(ChromatogramArtist): + default_label_function = staticmethod(label_include_charges) + + def process_group(self, composition, chroma, label_function=None, **kwargs): + if label_function is None: + label_function = self.default_label_function + charge_state_map = split_charge_states(chroma) + for charge_state, component in charge_state_map.items(): + super(ChargeSeparatingChromatogramArtist, self).process_group( + composition, component, label_function=label_function, **kwargs + ) + + +class ChargeSeparatingSmoothingChromatogramArtist(ChargeSeparatingChromatogramArtist, SmoothingChromatogramArtist): + pass + + +def mass_shift_separating_chromatogram(chroma, ax=None, **kwargs): + mass_shifts = list(chroma.mass_shifts) + labels = {} + for mass_shift in mass_shifts: + with_mass_shift, _ = chroma.bisect_mass_shift(mass_shift) + if len(with_mass_shift): + labels[mass_shift] = with_mass_shift + mass_shift_plot = SmoothingChromatogramArtist(list(labels.values()), colorizer=lambda *a, **k: ""green"", ax=ax).draw( + label_function=lambda *a, **k: tuple(a[0].mass_shifts)[0].name, legend=False, **kwargs + ) + rt, intens = chroma.as_arrays() + mass_shift_plot.draw_generic_chromatogram(""Total"", rt, intens, color=""steelblue"") + ymin = mass_shift_plot.ax.get_ylim()[0] + mass_shift_plot.ax.set_ylim(ymin, intens.max() * 1.01) + mass_shift_plot.ax.set_title(""Mass Shift-Separated\nExtracted Ion Chromatogram"", fontsize=20) + return mass_shift_plot.ax +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/base.py",".py","414","20","from .utils import figax, figure + + +class ArtistBase(object): + + def __init__(self, ax=None): + self.ax = ax + + def create_axes(self): + self.ax = figax() + + def __repr__(self): + return ""{self.__class__.__name__}()"".format(self=self) + + def _repr_html_(self): + if self.ax is None: + return repr(self) + fig = (self.ax.get_figure()) + return fig._repr_html_() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/sequence_fragment_logo.py",".py","53938","1562","from collections import Counter, defaultdict +from typing import Any, Dict, List, Tuple, NamedTuple, Optional + +import glypy + +import glycopeptidepy +from glycopeptidepy.structure import sequence, modification, SequencePosition +from glycopeptidepy.structure.modification import GlycanFragment, Modification +from glycopeptidepy.structure.fragment import IonSeries, OxoniumIon, StubFragment, PeptideFragment +from glycopeptidepy.utils import simple_repr +from glycopeptidepy.utils.collectiontools import CountTable + +from glypy.plot import plot as draw_tree, SNFGNomenclature +from glypy.plot.common import MonosaccharidePatch + +from .colors import darken, cnames, hex2color, get_color + +import numpy as np + +from matplotlib import ( + patheffects, + pyplot as plt, + patches as mpatch, + textpath, + font_manager, + path as mpath, + transforms as mtransform, + collections as mcollection, +) + + +def flatten(x): + return [xj for xi in x for xj in ([xi] if not isinstance(xi, (tuple, list)) else flatten(xi))] + + +def centroid(path): + point = np.zeros_like(path.vertices[0]) + c = 0.0 + for p in path.vertices: + point += p + c += 1 + return point / c + + +# def apply_transform(t, ax, scale=(1, 1), translate=(0, 0)): +# cent = centroid(t.get_path()) +# trans = mtransform.Affine2D().scale(*scale) +# new_cent = centroid(t.get_path().transformed(trans)) +# shift = cent - new_cent +# trans.translate(*(shift + translate)) +# trans += ax.transData +# t.set_transform(trans) +def apply_transform(t: mpatch.PathPatch, ax, scale=(1, 1), translate=(0, 0), rotate_deg=None): + cent = centroid(t.get_path()) + trans = mtransform.Affine2D() + if rotate_deg is not None: + trans.translate(*(-cent)) + trans.rotate_deg(rotate_deg) + trans.translate(*(cent)) + trans.scale(*scale) + new_cent = centroid(t.get_path().transformed(trans)) + shift = cent - new_cent + trans.translate(*(shift + translate)) + t.set_path(t.get_path().transformed(trans)) + + +font_options = font_manager.FontProperties(family=""monospace"") +glycan_symbol_grammar = SNFGNomenclature() + + +class BBox(NamedTuple): + xmin: float + ymin: float + xmax: float + ymax: float + + def expand(self, xmin, ymin, xmax, ymax) -> ""BBox"": + return self.__class__( + min(xmin, self.xmin), + min(ymin, self.ymin), + max(xmax, self.xmax), + max(ymax, self.ymax), + ) + + @classmethod + def from_axes(cls, ax: plt.Axes): + xlim = ax.get_xlim() + ylim = ax.get_ylim() + return BBox(xlim[0], ylim[0], xlim[1], ylim[1]) + + @classmethod + def from_path(cls, path: mpath.Path): + return bbox_path(path) + + def relative_to_point(self, x, y): + return BBox(self.xmin - x, self.ymin - y, self.xmax - x, self.ymax - y) + + def as_array(self): + return np.array(self).reshape((-1, 2)) + + +def bbox_path(path): + nodes = path.vertices + if nodes.size == 0: + return BBox(0, 0, 0, 0) + xmin = nodes[:, 0].min() + xmax = nodes[:, 0].max() + ymin = nodes[:, 1].min() + ymax = nodes[:, 1].max() + return BBox(xmin, ymin, xmax, ymax) + + +class SequencePositionGlyph(object): + position: SequencePosition + index: int + _ax: plt.Axes + x: float + y: float + options: Dict[str, Any] + + def __init__(self, position, index, x, y, patch=None, ax=None, **kwargs): + self.position = position + self.index = index + self.x = x + self.y = y + self._patch = patch + self._ax = ax + self.options = kwargs + + __repr__ = simple_repr + + def render(self, ax=None): + if ax is None: + ax = self._ax + else: + self._ax = ax + + symbol = self.position.amino_acid.symbol + + color = self.options.get(""color"", ""black"") + if self.position.modifications: + color = darken(get_color(self.position.modifications[0])) + label = self.position.modifications[0].name + else: + label = None + + tpath = textpath.TextPath((self.x, self.y), symbol, size=self.options.get(""size""), prop=font_options) + tpatch = mpatch.PathPatch(tpath, color=color, lw=self.options.get(""lw"", 0), label=label) + self._patch = tpatch + ax.add_patch(tpatch) + return ax + + def set_transform(self, transform): + self._patch.set_transform(transform) + + def centroid(self): + path = self._patch.get_path() + return centroid(path) + + def bbox(self): + return bbox_path(self._patch.get_path()) + + +class GlycanCompositionGlyphs(object): + glycan_composition: glypy.GlycanComposition + ax: plt.Axes + x: float + xend: float + y: float + spacing: float + options: Dict[str, Any] + + patches: List[MonosaccharidePatch] + layers: List[List[mpatch.PathPatch]] + + def __init__(self, glycan_composition, x, y, ax, vertical=False, spacing: float = 1.0, **kwargs): + self.glycan_composition = glycan_composition + self.ax = ax + self.x = x + self.xend = x + self.y = y + self.yend = y + self.vertical = vertical + self.options = kwargs + self.patches = [] + self.layers = [] + self.spacing = spacing + + def render(self): + x = self.x + y = self.y + glyphs = [] + layers = [] + for mono, count in self.glycan_composition.items(): + layer = [] + glyph = glycan_symbol_grammar.draw(mono, x, y, ax=self.ax, scale=(0.4, 0.4)) + x += 0.6 * self.spacing + layer.extend(flatten(glyph.shape_patches)) + glyph = glycan_symbol_grammar.draw_text( + self.ax, x, y - 0.17, r""$\times %d$"" % count, center=False, fontsize=22, zorder=100, lw=0 + ) + if isinstance(glyph, tuple): + for g in glyph: + g.set_lw(0) + else: + glyph.set_lw(0) + if self.vertical: + y += 1.0 * self.spacing + x -= 0.6 * self.spacing + else: + x += 1.75 + layer.extend(glyph) + layers.append(layer) + glyphs.extend(layer) + if self.vertical: + x += 0.95 + (0.6 * self.spacing) + self.xend = x + self.yend = y + self.patches = glyphs + self.layers = layers + + def set_transform(self, transform): + for patch in self.patches: + patch.set_transform(transform) + + def bbox(self): + if not self.patches: + return self.x, self.y, self.xend, self.y + + flat_patch_iter = ( + p for patch in self.patches for p in ([patch] if not isinstance(patch, (tuple, list)) else patch) + ) + first = next(flat_patch_iter) + bbox = bbox_path(first.get_path()) + for patch in flat_patch_iter: + bbox = bbox.expand(*bbox_path(patch.get_path())) + return bbox + + +class GlycanCompositionGlyphsOverlaid(GlycanCompositionGlyphs): + def render(self): + x = self.x + y = self.y + glyphs = [] + layers = [] + for mono, count in self.glycan_composition.items(): + layer = [] + glyph = glycan_symbol_grammar.draw(mono, x, y, ax=self.ax, scale=(0.4, 0.4)) + # x += 0.6 * self.spacing + layer.extend(flatten(glyph.shape_patches)) + glyph = glycan_symbol_grammar.draw_text( + self.ax, x - 0.15, y - 0.17, r""$%d$"" % count, center=False, fontsize=22, zorder=100, lw=0 + ) + if isinstance(glyph, tuple): + for g in glyph: + g.set_lw(0) + else: + glyph.set_lw(0) + if self.vertical: + y += 1.0 * self.spacing + # x -= 0.6 * self.spacing + else: + x += 1.75 + layer.extend(glyph) + layers.append(layer) + glyphs.extend(layer) + if self.vertical: + x += 0.95 + (0.6 * self.spacing) + self.xend = x + self.yend = y + self.patches = glyphs + self.layers = layers + + +class MonosaccharideSequence(object): + monosaccharides: List[glypy.MonosaccharideResidue] + ax: plt.Axes + x: float + xend: float + y: float + spacing: float + options: Dict[str, Any] + + patches: List[MonosaccharidePatch] + layers: List[List[mpatch.PathPatch]] + + def __init__(self, monosaccharides, x, y, ax, spacing: float = 1.0, **kwargs): + self.monosaccharides = monosaccharides + self.ax = ax + self.x = x + self.xend = x + self.y = y + self.yend = y + self.options = kwargs + self.patches = [] + self.layers = [] + self.spacing = spacing + + def render(self): + x = self.x + y = self.y + layers = [] + for mono in self.monosaccharides: + layer = [] + glyph = glycan_symbol_grammar.draw(mono, x, y, ax=self.ax, scale=(0.4, 0.4), zorder=100) + y += 1.0 * self.spacing + layer.extend(flatten(glyph.shape_patches)) + layers.append(layer) + self.layers = layers + self.patches = [o for layer in layers for o in layer] + + def set_transform(self, transform): + for patch in self.patches: + patch.set_transform(transform) + + def bbox(self): + if not self.patches: + return self.x, self.y, self.xend, self.y + + flat_patch_iter = ( + p for patch in self.patches for p in ([patch] if not isinstance(patch, (tuple, list)) else patch) + ) + first = next(flat_patch_iter) + bbox = bbox_path(first.get_path()) + for patch in flat_patch_iter: + bbox = bbox.expand(*bbox_path(patch.get_path())) + return bbox + + +class IonAnnotationGlyphBase: + xaspect: float = 32 + yaspect: float = 24 + + x: float + y: float + ax: plt.Axes + + xscale: float + yscale: float + charge: int + + peptide_patch: mpatch.PathPatch + charge_patch: mpatch.PathPatch + patches: List[mpatch.PathPatch] + glycan_patch_layers: List[List[mpatch.PathPatch]] + + size: int + + base_size: int = 22 + + def __init__(self, x: float, y: float, ax: plt.Axes, xscale: float, yscale: float, charge: int, size: int = 22): + self.x = x + self.y = y + self.ax = ax + self.charge = charge + self.xscale = xscale + self.yscale = yscale + self.patches = [] + self.glycan_patch_layers = [] + self.peptide_patch = None + self.charge_patch = None + self.size = size + + def __repr__(self): + return f""{self.__class__.__name__}({self.x}, {self.y}, {self.fragment.name})"" + + def draw_charge_patch(self): + y = 0 + for patch in [self.peptide_patch] + self.patches: + y = max(bbox_path(patch.get_path()).ymax, y) + if abs(self.charge) == 1: + return + if self.charge > 0: + label = f""+{self.charge}"" + else: + label = str(self.charge) + + (glyph,) = glycan_symbol_grammar.draw_text( + self.ax, -0.45, y + 0.15, label, center=False, fontsize=16, zorder=100, lw=0 + ) + p = glyph.get_path() + center = centroid(p) + p = ( + p.transformed(mtransform.Affine2D().translate(*-center)) + .transformed(mtransform.Affine2D().scale((self.size + 4) / self.base_size)) + .transformed(mtransform.Affine2D().translate(*center)) + ) + lower = bbox_path(p).ymin + upshift = y - lower + if upshift > 0: + upshift *= 2 + p = p.transformed(mtransform.Affine2D().translate(0, upshift)) + glyph.set_path(p) + self.charge_patch = glyph + + def get_glycan_composition(self): + frag = self.fragment + + if frag.glycosylation: + return frag.glycosylation + elif hasattr(frag, ""modification_dict""): + mods = CountTable() + for mod, v in frag.modification_dict.items(): + if isinstance(mod, GlycanFragment): + mods += mod.fragment.glycan_composition + elif ( + isinstance(mod, Modification) + and glycopeptidepy.ModificationCategory.glycosylation in mod.rule.categories + ) or glycopeptidepy.ModificationCategory.glycosylation in mod.categories: + mods[glypy.MonosaccharideResidue.from_iupac_lite(mod.name)] += v + mods = glypy.GlycanComposition(mods) + return mods + else: + return glypy.GlycanComposition() + + def render(self): + raise NotImplementedError() + + def bbox(self): + patches = self.get_all_patches() + + flat_patch_iter = iter(patches) + first = next(flat_patch_iter) + bbox = bbox_path(first.get_path()) + for patch in flat_patch_iter: + bbox = bbox.expand(*bbox_path(patch.get_path())) + return bbox + + def get_all_patches(self) -> List[mpatch.PathPatch]: + patches = list(self.patches) + if self.peptide_patch: + patches = [self.peptide_patch] + patches + if self.charge_patch: + patches.append(self.charge_patch) + return patches + + def translate(self, x, y): + self.x += x + self.y += y + for patch in self.get_all_patches(): + patch.set_path(patch.get_path().transformed(mtransform.Affine2D().translate(x, y))) + + +class GlycopeptideStubFragmentGlyph(IonAnnotationGlyphBase): + fragment: StubFragment + + def __init__( + self, + x: float, + y: float, + ax: plt.Axes, + fragment: StubFragment, + xscale: float, + yscale: float, + charge: int, + size: int = 22, + ): + super().__init__(x, y, ax, xscale, yscale, charge, size) + self.fragment = fragment + + def draw_peptide_text(self): + x = 0 + y = 0 + if self.get_glycan_composition(): + label = ""pep+"" + else: + label = ""pep"" + glyph = glycan_symbol_grammar.draw_text( + self.ax, x, y, label, center=False, fontsize=self.base_size, zorder=100, lw=0 + ) + glyph = glyph[0] + path = glyph.get_path() + glyph.set_path( + path.transformed(mtransform.Affine2D().scale(self.size / self.base_size)) + .transformed(mtransform.Affine2D().rotate_deg(90)) + .transformed(mtransform.Affine2D().translate(0, 0)) + ) + self.peptide_patch = glyph + + def draw_glycan_composition(self): + y = bbox_path(self.peptide_patch.get_path()).ymax + art = GlycanCompositionGlyphsOverlaid( + self.get_glycan_composition(), + 0 - 0.30, + y + (0.5 * self.size / self.base_size), + self.ax, + spacing=self.size / self.base_size, + vertical=True, + ) + art.render() + ytop = y + for layer in art.layers: + ybottom = None + for patch in layer: + p: mpath.Path = patch.get_path() + center = centroid(p) + p: mpath.Path = ( + p.transformed(mtransform.Affine2D().translate(*-center)) + .transformed(mtransform.Affine2D().scale(self.size / self.base_size)) + .transformed(mtransform.Affine2D().translate(*center)) + .transformed(mtransform.Affine2D().scale(0.65, 1.0)) + ) + bb_next = bbox_path(p) + if ybottom is None: + ybottom = bb_next.ymin + elif ybottom > bb_next.ymin: + ybottom = bb_next.ymin + patch.set_path(p) + + if ybottom <= ytop: + for patch in layer: + p: mpath.Path = patch.get_path() + p = p.transformed(mtransform.Affine2D().translate(0, (ytop - ybottom) + 0.01 * self.yscale)) + patch.set_path(p) + for patch in layer: + p: mpath.Path = patch.get_path() + bb_next = bbox_path(p) + ytop = max(ytop, bb_next.ymax) + patch.set_path(p) + self.patches = art.patches + self.glycan_patch_layers = art.layers + + def render(self): + self.draw_peptide_text() + self.draw_glycan_composition() + self.draw_charge_patch() + + patches = [self.peptide_patch] + self.patches + if self.charge_patch: + patches.append(self.charge_patch) + + for glyph in patches: + glyph.set_path( + glyph.get_path() + .transformed(mtransform.Affine2D().scale(self.xscale / self.xaspect, self.yscale / self.yaspect)) + .transformed(mtransform.Affine2D().translate(self.x + 0.15 * self.xscale / self.xaspect, self.y)) + ) + glyph.set_path_effects( + [ + patheffects.Stroke(linewidth=0.5, foreground=""white""), + patheffects.Normal(), + ] + ) + + +class OxoniumIonGlyph(IonAnnotationGlyphBase): + fragment: OxoniumIon + loss_patch: mpatch.PathPatch + + def __init__( + self, + x: float, + y: float, + ax: plt.Axes, + fragment: OxoniumIon, + xscale: float, + yscale: float, + charge: int, + size: int = 22, + ): + super().__init__(x, y, ax, xscale, yscale, charge, size) + self.fragment = fragment + self.loss_patch = None + + def get_glycan_composition(self): + return glypy.GlycanComposition(Counter(self.fragment.monosaccharides)) + + def draw_glycan_composition(self): + y = 0 + if len(self.fragment.monosaccharides) > 3: + art = GlycanCompositionGlyphsOverlaid( + self.get_glycan_composition(), + -0.2, + y + (0.5 * self.size / self.base_size), + self.ax, + spacing=self.size / self.base_size, + vertical=True, + ) + else: + art = MonosaccharideSequence( + self.fragment.monosaccharides, + -0.2, + y + (0.5 * self.size / self.base_size), + self.ax, + spacing=self.size / self.base_size, + vertical=True, + ) + art.render() + ytop = y + for layer in art.layers: + ybottom = None + for patch in layer: + p: mpath.Path = patch.get_path() + center = centroid(p) + p: mpath.Path = ( + p.transformed(mtransform.Affine2D().translate(*-center)) + .transformed(mtransform.Affine2D().scale(self.size / self.base_size)) + .transformed(mtransform.Affine2D().translate(*center)) + .transformed(mtransform.Affine2D().scale(0.65, 1.0)) + ) + bb_next = bbox_path(p) + if ybottom is None: + ybottom = bb_next.ymin + elif ybottom > bb_next.ymin: + ybottom = bb_next.ymin + patch.set_path(p) + + if ybottom <= ytop: + for patch in layer: + p: mpath.Path = patch.get_path() + p = p.transformed(mtransform.Affine2D().translate(0, (ytop - ybottom) + 0.01 * self.yscale)) + patch.set_path(p) + for patch in layer: + p: mpath.Path = patch.get_path() + bb_next = bbox_path(p) + ytop = max(ytop, bb_next.ymax) + patch.set_path(p) + self.patches = art.patches + self.glycan_patch_layers = art.layers + + def draw_loss(self): + y = 0 + xs = [] + for patch in self.patches: + y = max(bbox_path(patch.get_path()).ymax, y) + x = centroid(patch.get_path())[0] + xs.append(x) + if xs: + x = np.mean(x) + else: + x = 0.0 + if self.fragment.chemical_shift is None: + return + + label = self.fragment.chemical_shift.name + glyph = glycan_symbol_grammar.draw_text( + self.ax, x, y, label, center=False, fontsize=self.base_size, zorder=100, lw=0 + ) + glyph = glyph[0] + path = glyph.get_path() + glyph.set_path( + path.transformed(mtransform.Affine2D().scale(self.size / self.base_size)).transformed( + mtransform.Affine2D().rotate_deg_around(x, y, 90.0) + ) + ) + self.loss_patch = glyph + + def render(self): + self.draw_glycan_composition() + self.draw_loss() + + patches = self.patches + + for glyph in patches: + glyph.set_path( + glyph.get_path() + .transformed(mtransform.Affine2D().scale(self.xscale / self.xaspect, self.yscale / self.yaspect)) + .transformed(mtransform.Affine2D().translate(self.x + 0.15 * self.xscale / self.xaspect, self.y)) + ) + glyph.set_path_effects( + [ + patheffects.Stroke(linewidth=0.5, foreground=""white""), + patheffects.Normal(), + ] + ) + + if self.loss_patch is not None: + xs = [] + for patch in patches: + x = centroid(patch.get_path())[0] + xs.append(x) + if xs: + x = np.mean(x) + else: + x = 0.0 + + glyph = self.loss_patch + + # Center x at 0.0 + glyph.set_path( + glyph.get_path().transformed(mtransform.Affine2D().translate(-centroid(glyph.get_path())[0], 0.0)) + ) + + glyph.set_path( + # Scale paths + glyph.get_path() + .transformed(mtransform.Affine2D().scale(self.xscale / self.xaspect, self.yscale / self.yaspect)) + .transformed( + # Move to expected position + mtransform.Affine2D().translate(x, self.y) + ) + ) + + def get_all_patches(self) -> List[mpatch.PathPatch]: + patches = list(self.patches) + if self.loss_patch and self.loss_patch not in patches: + patches.append(self.loss_patch) + return patches + + def bbox(self): + patches = self.get_all_patches() + flat_patch_iter = iter(patches) + first = next(flat_patch_iter) + bbox = bbox_path(first.get_path()) + for patch in flat_patch_iter: + bbox = bbox.expand(*bbox_path(patch.get_path())) + return bbox + + +class PeptideFragmentGlyph(IonAnnotationGlyphBase): + fragment: PeptideFragment + + def __init__( + self, + x: float, + y: float, + ax: plt.Axes, + fragment: glycopeptidepy.PeptideFragment, + xscale: float, + yscale: float, + charge: int, + size: int = 22, + ): + super().__init__(x, y, ax, xscale, yscale, charge, size) + self.fragment = fragment + + def draw_peptide_text(self): + x = 0 + y = 0 + label = self.fragment.base_name() + glyph = glycan_symbol_grammar.draw_text( + self.ax, x, y, label, center=False, fontsize=self.base_size, zorder=100, lw=0 + ) + glyph = glyph[0] + path = glyph.get_path() + bbox = bbox_path(path) + xc = (bbox.xmin + bbox.xmax) / 2 + yc = (bbox.ymin + bbox.ymax) / 2 + glyph.set_path( + path.transformed(mtransform.Affine2D().scale(self.size / self.base_size)).transformed( + mtransform.Affine2D().translate(-xc, yc) + ) + ) + self.peptide_patch = glyph + + def draw_glycan_composition(self): + gc = self.get_glycan_composition() + bb = bbox_path(self.peptide_patch.get_path()) + y = bb.ymax + art = GlycanCompositionGlyphsOverlaid( + gc, + 0 - 0.1, + y + (0.5 * self.size / self.base_size), + self.ax, + vertical=True, + spacing=self.size / self.base_size, + ) + art.render() + ytop = y + for layer in art.layers: + ybottom = None + for patch in layer: + p: mpath.Path = patch.get_path() + center = centroid(p) + p: mpath.Path = ( + p.transformed(mtransform.Affine2D().translate(*-center)) + .transformed(mtransform.Affine2D().scale(self.size / self.base_size)) + .transformed(mtransform.Affine2D().translate(*center)) + .transformed(mtransform.Affine2D().scale(0.65, 1)) + ) + bb_next = bbox_path(p) + if ybottom is None: + ybottom = bb_next.ymin + elif ybottom > bb_next.ymin: + ybottom = bb_next.ymin + patch.set_path(p) + + if ybottom <= ytop: + for patch in layer: + p: mpath.Path = patch.get_path() + p = p.transformed(mtransform.Affine2D().translate(0, ytop - ybottom)) + patch.set_path(p) + for patch in layer: + p: mpath.Path = patch.get_path() + bb_next = bbox_path(p) + ytop = max(ytop, bb_next.ymax) + patch.set_path(p) + self.patches = art.patches + self.glycan_path_layers = art.layers + + def draw_charge_patch(self): + y = 0 + for patch in [self.peptide_patch] + self.patches: + y = max(bbox_path(patch.get_path()).ymax, y) + if abs(self.charge) == 1: + return + if self.charge > 0: + label = f""+{self.charge}"" + else: + label = str(self.charge) + + (glyph,) = glycan_symbol_grammar.draw_text(self.ax, -0.2, y + 0.1, label, center=False, fontsize=16, lw=0) + p = glyph.get_path() + center = centroid(p) + p = ( + p.transformed(mtransform.Affine2D().translate(*-center)) + .transformed(mtransform.Affine2D().scale((self.size + 4) / self.base_size)) + .transformed(mtransform.Affine2D().translate(*center)) + ) + lower = bbox_path(p).ymin + upshift = y - lower + if upshift > 0: + upshift *= 2 + p = p.transformed(mtransform.Affine2D().translate(0, upshift)) + glyph.set_path(p) + self.charge_patch = glyph + + def render(self): + self.draw_peptide_text() + self.draw_glycan_composition() + self.draw_charge_patch() + + patches = [self.peptide_patch] + self.patches + if self.charge_patch: + patches.append(self.charge_patch) + + for i, glyph in enumerate(patches): + p = glyph.get_path() + p = p.transformed( + mtransform.Affine2D().scale(self.xscale / self.xaspect, self.yscale / self.yaspect) + ).transformed(mtransform.Affine2D().translate(self.x + 0.25 * self.xscale / self.xaspect, self.y)) + if i == 0: + bbox = bbox_path(p) + shift = (bbox.xmin - self.x) / 2 + p = p.transformed(mtransform.Affine2D().translate(shift, 0)) + glyph.set_path(p) + glyph.set_path_effects( + [ + patheffects.Stroke(linewidth=0.5, foreground=""white""), + patheffects.Normal(), + ] + ) + cent = centroid(self.peptide_patch.get_path()) + centx = cent[0] + xoffset = self.x - centx + for glyph in patches: + p = glyph.get_path() + p = p.transformed(mtransform.Affine2D().translate(xoffset, 0)) + glyph.set_path(p) + + +class FragmentStroke: + index: int + + linewidth: float + x: float + top: float + bottom: float + + n_length: float + c_length: float + + v_step: float + stroke_slope: float + + c_labels: List[str] + n_labels: List[str] + + main_color: str + c_colors: List[str] + n_colors: List[str] + + main_stroke: mpatch.PathPatch + c_strokes: List[mpatch.PathPatch] + n_strokes: List[mpatch.PathPatch] + + use_collection: bool = True + _collection: mcollection.PatchCollection + ax: plt.Axes + options: Dict[str, Any] + + def __init__( + self, + index: int, + x: float, + top: float, + bottom: float, + n_labels=None, + c_labels=None, + main_color=None, + n_colors=None, + c_colors=None, + ax=None, + v_step: float = 0.2, + stroke_slope: float = 0.2, + n_length: float = 0.8, + c_length: float = 0.8, + options: Dict[str, Any] = None, + **kwargs, + ): + if options is None: + options = {} + options.update(kwargs) + + self.index = index + self.x = x + self.top = top + self.bottom = bottom + + self.v_step = v_step + self.stroke_slope = stroke_slope + + self.c_length = c_length + self.n_length = n_length + + self.c_labels = c_labels or [] + self.n_labels = n_labels or [] + self.main_color = main_color or ""black"" + self.c_colors = c_colors or [""black""] * len(self.c_labels) + self.n_colors = n_colors or [""black""] * len(self.n_labels) + + self.main_stroke = None + self.c_strokes = [] + self.n_strokes = [] + + self.ax = ax + self.options = options + self.options.setdefault(""lw"", 2) + self._collection = None + + def has_annotations(self): + return self.has_n_annotations() or self.has_c_annotations() + + def has_n_annotations(self): + return bool(self.n_labels) + + def has_c_annotations(self): + return bool(self.c_labels) + + def add_n_label(self, label: str, color=""black""): + self.n_labels.append(label) + self.n_colors.append(color) + + def add_c_label(self, label: str, color=""black""): + self.c_labels.append(label) + self.c_colors.append(color) + + def draw_main_stroke(self): + p = mpath.Path( + [[self.x, self.top], [self.x, self.bottom], [self.x, self.bottom]], + [mpath.Path.MOVETO, mpath.Path.LINETO, mpath.Path.STOP], + ) + + pp = mpatch.PathPatch( + p, + facecolor=self.main_color, + edgecolor=self.main_color, + lw=self.options[""lw""], + capstyle=""round"" if self.stroke_slope != 0 else ""projecting"", + ) + if not self.use_collection: + self.ax.add_patch(pp) + self.main_stroke = pp + + def draw_c_strokes(self): + v_step = self.v_step + stroke_slope = self.stroke_slope + for i, (c_label, color) in enumerate(zip(self.c_labels, self.c_colors), 1): + if color is None or color == ""none"": + continue + p = mpath.Path( + [ + [self.x, self.top + v_step * (i - 1)], + [self.x + self.c_length, self.top + v_step * (i - 1) + stroke_slope], + [self.x + self.c_length, self.top + v_step * (i - 1) + stroke_slope], + ], + [mpath.Path.MOVETO, mpath.Path.LINETO, mpath.Path.STOP], + ) + pp = mpatch.PathPatch( + p, + facecolor=color, + edgecolor=color, + lw=self.options[""lw""], + capstyle=""round"" if self.stroke_slope != 0 else ""projecting"", + ) + if not self.use_collection: + self.ax.add_patch(pp) + self.c_strokes.append(pp) + + def draw_n_strokes(self): + v_step = self.v_step + for i, (n_label, color) in enumerate(zip(self.n_labels, self.n_colors), 1): + if color is None or color == ""none"": + continue + p = mpath.Path( + [ + [self.x, self.bottom - v_step * (i - 1)], + [self.x - self.n_length, self.bottom - v_step * (i - 1) - self.stroke_slope], + [self.x - self.n_length, self.bottom - v_step * (i - 1) - self.stroke_slope], + ], + [mpath.Path.MOVETO, mpath.Path.LINETO, mpath.Path.STOP], + ) + pp = mpatch.PathPatch( + p, + facecolor=color, + edgecolor=color, + lw=self.options[""lw""], + capstyle=""round"" if self.stroke_slope != 0 else ""projecting"", + ) + if not self.use_collection: + self.ax.add_patch(pp) + self.n_strokes.append(pp) + + def draw(self): + self.draw_main_stroke() + self.draw_c_strokes() + self.draw_n_strokes() + if self.c_labels: + self.draw_c_label() + if self.n_labels: + self.draw_n_label() + if self.use_collection: + collect = self.as_patch_collection() + self.ax.add_collection(collect) + self._collection = collect + + def draw_c_label(self): + if self.c_strokes: + p = self.c_strokes[-1] + base = bbox_path(p.get_path()).ymax + label_y = base + 0.2 + else: + i = len(self.c_strokes) + label_y = self.top + (0.2) * i + skipped = 0 + seen = set() + for j, text in enumerate(self.c_labels): + text = str(text) + if text in seen or not text: + skipped += 1 + continue + seen.add(text) + tpath = textpath.TextPath( + (self.x, label_y + (j - skipped) * (self.v_step or 0.2)), + text, + size=0.45, + prop=font_options, + ) + # bbox = bbox_path(tpath) + # dy = (bbox.ymax - bbox.ymin) / 2 + 0.2 * (j - skipped) + dy = (0.2) * (j - skipped) + tpath = tpath.transformed(mtransform.Affine2D().translate(0, dy)) + tpatch = mpatch.PathPatch(tpath, color=""black"", lw=0) + if not self.use_collection: + self.ax.add_patch(tpatch) + self.c_strokes.append(tpatch) + + def draw_n_label(self): + if self.n_strokes: + p = self.n_strokes[-1] + base = bbox_path(p.get_path()).ymin + label_y = base - 0.1 + else: + i = len(self.n_strokes) + label_y = self.bottom - (self.v_step or 0.2) * i + skipped = 0 + seen = set() + for j, text in enumerate(self.n_labels): + text = str(text) + if text in seen or not text: + skipped += 1 + continue + seen.add(text) + tpath = textpath.TextPath( + (self.x - self.c_length, label_y - (j - skipped) * (self.v_step or 0.2)), + text, + size=0.45, + prop=font_options, + ) + bbox = bbox_path(tpath) + dy = (bbox.ymax - bbox.ymin) + 0.16 * (j - skipped) + tpath = tpath.transformed(mtransform.Affine2D().translate(0, -dy)) + + tpatch = mpatch.PathPatch(tpath, color=""black"", lw=0) + if not self.use_collection: + self.ax.add_patch(tpatch) + self.n_strokes.append(tpatch) + + def bbox(self): + bbox = bbox_path(self.main_stroke.get_path()) + for stroke in self.n_strokes + self.c_strokes: + bbox = bbox.expand(*bbox_path(stroke.get_path())) + return bbox + + def as_patch_collection(self): + strokes = [self.main_stroke] + self.n_strokes + self.c_strokes + collect = mcollection.PatchCollection( + strokes, match_original=True, capstyle=""round"" if self.stroke_slope != 0 else ""projecting"" + ) + return collect + + def set_transform(self, transform: mtransform.Affine2D): + if self.main_stroke: + self.main_stroke.set_transform(transform) + for stroke in self.c_strokes + self.n_strokes: + stroke.set_transform(transform) + if self._collection is not None: + self._collection.set_transform(transform) + + +class SequenceGlyph(object): + sequence: glycopeptidepy.PeptideSequence + sequence_position_glyphs: List[SequencePositionGlyph] + glycan_composition_glyphs: Optional[GlycanCompositionGlyphs] + + step_coefficient: float + x: float + y: float + size: float + draw_glycan: bool + + ax: plt.Axes + + # Old and possibly unused + multi_tier_annotation: bool + label_fragments: bool + + def __init__( + self, peptide, ax=None, size=1, step_coefficient=1.0, draw_glycan=False, label_fragments=True, **kwargs + ): + if not isinstance(peptide, sequence.PeptideSequenceBase): + peptide = sequence.PeptideSequence(peptide) + self.sequence = peptide + self._fragment_index = None + self.ax = ax + self.size = size + self.step_coefficient = step_coefficient + self.sequence_position_glyphs = [] + self.annotations = [] + self.x = kwargs.get(""x"", 1) + self.y = kwargs.get(""y"", 1) + self.options = kwargs + self.next_at_height = dict(c_term=defaultdict(float), n_term=defaultdict(float)) + self.label_fragments = label_fragments + self.multi_tier_annotation = False + self.draw_glycan = draw_glycan + self.glycan_composition_glyphs = None + self.render() + + def transform(self, transform): + for glyph in self.sequence_position_glyphs: + glyph.set_transform(transform + self.ax.transData) + for annot in self.annotations: + annot.set_transform(transform + self.ax.transData) + if self.draw_glycan: + self.glycan_composition_glyphs.set_transform(transform + self.ax.transData) + return self + + def make_position_glyph(self, position, i, x, y, size, lw=0): + glyph = SequencePositionGlyph(position, i, x, y, size=size, lw=lw) + return glyph + + def render(self): + ax = self.ax + if ax is None: + fig, ax = plt.subplots(1) + self.ax = ax + else: + ax = self.ax + + size = self.size + x = self.x + y = self.y + glyphs = self.sequence_position_glyphs = [] + i = 0 + for position in self.sequence: + glyph = self.make_position_glyph(position, i, x, y, size=size, lw=self.options.get(""lw"", 0)) + glyph.render(ax) + glyphs.append(glyph) + x += size * self.step_coefficient + i += 1 + if self.draw_glycan: + self.glycan_composition_glyphs = GlycanCompositionGlyphs( + self.sequence.glycan_composition, x + size * self.step_coefficient, y + 0.35, ax + ) + self.glycan_composition_glyphs.render() + return ax + + def __getitem__(self, i): + return self.sequence_position_glyphs[i] + + def __len__(self): + return len(self.sequence_position_glyphs) + + def next_between(self, index): + for i, position in enumerate(self.sequence_position_glyphs, 1): + if i == index: + break + mid_point_offset = (self.step_coefficient * self.size) / 1.3 + return position.x + mid_point_offset + + def draw_bar_at(self, index, height=0.25, color=""red"", **kwargs): + x = self.next_between(index) + y = self.y + rect = mpatch.Rectangle((x, y - height), 0.05, 1 + height, color=color, **kwargs) + self.ax.add_patch(rect) + self.annotations.append(rect) + + def draw_n_term_label(self, index, label, height=0.25, length=0.75, size=0.45, color=""black"", **kwargs): + kwargs.setdefault(""lw"", self.options.get(""lw"", 0)) + x = self.next_between(index) + y = self.y - height - size + length *= self.step_coefficient + label_x = x - length * 0.9 + label_y = y + + if self.next_at_height[""n_term""][index] != 0: + label_y = self.next_at_height[""n_term""][index] - 0.4 + self.multi_tier_annotation = True + else: + label_y = y + + if self.label_fragments: + tpath = textpath.TextPath((label_x, label_y), label, size=size, prop=font_options) + tpatch = mpatch.PathPatch(tpath, color=color, lw=kwargs.get(""lw"")) + self.ax.add_patch(tpatch) + self.annotations.append(tpatch) + self.next_at_height[""n_term""][index] = tpath.vertices[:, 1].min() + + def draw_n_term_annotation(self, index, height=0.25, length=0.75, color=""red"", **kwargs): + x = self.next_between(index) + y = self.y - height + length *= self.step_coefficient + rect = mpatch.Rectangle((x - length, y), length, 0.07, color=color, **kwargs) + self.ax.add_patch(rect) + self.annotations.append(rect) + + def draw_c_term_label(self, index, label, height=0.25, length=0.75, size=0.45, color=""black"", **kwargs): + kwargs.setdefault(""lw"", self.options.get(""lw"", 0)) + x = self.next_between(index) + y = (self.y * 2) + height + length *= self.step_coefficient + label_x = x + length / 10.0 + if self.next_at_height[""c_term""][index] != 0: + label_y = self.next_at_height[""c_term""][index] + self.multi_tier_annotation = True + else: + label_y = y + 0.2 + + if self.label_fragments: + tpath = textpath.TextPath((label_x, label_y), label, size=size, prop=font_options) + tpatch = mpatch.PathPatch(tpath, color=color, lw=kwargs.get(""lw"")) + self.ax.add_patch(tpatch) + self.annotations.append(tpatch) + self.next_at_height[""c_term""][index] = tpath.vertices[:, 1].max() + 0.1 + + def draw_c_term_annotation(self, index, height=0.0, length=0.75, color=""red"", **kwargs): + x = self.next_between(index) + y = (self.y * 2) + height + length *= self.step_coefficient + rect = mpatch.Rectangle((x, y), length, 0.07, color=color, **kwargs) + self.ax.add_patch(rect) + self.annotations.append(rect) + + def bbox(self) -> BBox: + bbox: BBox = None + for glyph in self.sequence_position_glyphs: + if bbox is None: + bbox = glyph.bbox() + else: + bbox = bbox.expand(*glyph.bbox()) + if self.glycan_composition_glyphs is not None: + if bbox is None: + bbox = self.glycan_composition_glyphs.bbox() + else: + bbox = bbox.expand(*self.glycan_composition_glyphs.bbox()) + for glyph in self.annotations: + if bbox is None: + bbox = glyph.bbox() + else: + bbox = bbox.expand(*glyph.bbox()) + return bbox + + def layout(self): + ax = self.ax + # xmax = self.x + self.size * self.step_coefficient * len(self.sequence) + 1 + # if self.draw_glycan: + # xmax += self.glycan_composition_glyphs.xend - self.glycan_composition_glyphs.x + 1 + # ax.set_xlim(self.x - 1, xmax) + # ax.set_ylim(self.y - 1, self.y + 2) + # if self.multi_tier_annotation: + # ax.set_ylim(self.y - 2, self.y + 3) + bbox = self.bbox() + ax.set_xlim(bbox.xmin - 0.5, bbox.xmax + 0.5) + ax.set_ylim(bbox.ymin - 0.5, bbox.ymax + 0.5) + ax.axis(""off"") + + def draw(self): + self.layout() + + def break_at(self, idx): + if self._fragment_index is None: + self._build_fragment_index() + return self._fragment_index[idx] + + def _build_fragment_index(self, types=tuple(""bycz"")): + self._fragment_index = [[] for i in range(len(self) + 1)] + for series in types: + series = IonSeries(series) + if series.direction > 0: + g = self.sequence.get_fragments(series) + for frags in g: + position = self._fragment_index[frags[0].position] + position.append(frags) + else: + g = self.sequence.get_fragments(series) + for frags in g: + position = self._fragment_index[len(self) - frags[0].position] + position.append(frags) + + def build_annotations( + self, fragments: List[glycopeptidepy.PeptideFragment] + ) -> Tuple[List[Tuple[glycopeptidepy.PeptideFragment, bool, str]]]: + index = {} + for i in range(1, len(self.sequence)): + for series in self.break_at(i): + for f in series: + index[f.name] = i + n_annotations = [] + c_annotations = [] + + for fragment in fragments: + if hasattr(fragment, ""base_name""): + key = fragment.base_name() + else: + key = fragment.name + if key in index: + is_glycosylated = fragment.is_glycosylated + if key.startswith(""b"") or key.startswith(""c""): + n_annotations.append((index[key], is_glycosylated, key)) + elif key.startswith(""y"") or key.startswith(""z""): + c_annotations.append((index[key], is_glycosylated, key)) + return n_annotations, c_annotations + + def annotate_from_fragments_stroke(self, fragments: List[glycopeptidepy.PeptideFragment], **kwargs): + n = len(self.sequence) + kwargs.setdefault(""lw"", 2) + kwargs.setdefault(""color"", ""red"") + kwargs.setdefault(""glycosylated_color"", ""green"") + kwargs.setdefault(""v_step"", 0.3) + kwargs.setdefault(""stroke_slope"", 0) + kwargs.setdefault(""stroke_length"", 0.8) + kwargs.setdefault(""glyph_padding"", 0.2) + + lw = kwargs[""lw""] + color = kwargs[""color""] + glycosylated_color = kwargs[""glycosylated_color""] + v_step = kwargs[""v_step""] + stroke_slope = kwargs[""stroke_slope""] + stroke_length = kwargs[""stroke_length""] + glyph_padding = kwargs[""glyph_padding""] + + annotations = [ + FragmentStroke( + i, + self.next_between(i), + self.y + 0.8 + glyph_padding, + self.y - 0.1 - glyph_padding, + n_length=stroke_length, + c_length=stroke_length, + v_step=v_step, + stroke_slope=stroke_slope, + ax=self.ax, + main_color=color, + lw=lw, + ) + for i in range(1, n) + ] + + for frag in sorted(fragments, key=lambda x: x.mass): + if frag.series.includes_peptide and frag.series.direction: + if frag.series.direction > 0: + stroke = annotations[frag.position - 1] + if frag.is_glycosylated: + if not stroke.has_n_annotations(): + stroke.add_n_label("""", ""none"") + stroke.add_n_label(frag.base_name(), glycosylated_color) + else: + stroke.add_n_label(frag.base_name(), color) + else: + stroke = annotations[n - (frag.position + 1)] + if frag.is_glycosylated: + if not stroke.has_c_annotations(): + stroke.add_c_label("""", ""none"") + stroke.add_c_label(frag.base_name(), glycosylated_color) + else: + stroke.add_c_label(frag.base_name(), color) + + annotations = [annot for annot in annotations if annot.has_annotations()] + for annot in annotations: + annot.draw() + self.annotations.extend(annotations) + return annotations + + def annotate_from_fragments(self, fragments: List[glycopeptidepy.PeptideFragment], **kwargs): + n_annotations, c_annotations = self.build_annotations(fragments) + + kwargs.setdefault(""height"", 0.25) + kwargs_with_greater_height = kwargs.copy() + kwargs_with_greater_height[""height""] = kwargs[""height""] * 2 + kwargs.setdefault(""color"", ""red"") + + try: + kwargs.pop(""glycosylated_color"") + kwargs_with_greater_height[""color""] = kwargs_with_greater_height[""glycosylated_color""] + kwargs_with_greater_height.pop(""glycosylated_color"") + except KeyError: + color = kwargs.get(""color"", ""red"") + try: + color = cnames.get(color, color) + rgb = hex2color(color) + except Exception: + rgb = color + kwargs_with_greater_height[""color""] = darken(rgb) + + heights_at = defaultdict(float) + + for n_annot, is_glycosylated, key in n_annotations: + self.draw_bar_at(n_annot, color=kwargs[""color""]) + if is_glycosylated: + self.draw_n_term_annotation(n_annot, **kwargs_with_greater_height) + if heights_at[n_annot] < kwargs_with_greater_height[""height""]: + heights_at[n_annot] = kwargs_with_greater_height[""height""] + else: + self.draw_n_term_annotation(n_annot, label=key, **kwargs) + if heights_at[n_annot] < kwargs[""height""]: + heights_at[n_annot] = kwargs[""height""] + + labeled = set() + for n_annot, is_glycosylated, key in n_annotations: + label = key.split(""+"")[0] + if label not in labeled: + self.draw_n_term_label(n_annot, label=label, height=heights_at[n_annot]) + labeled.add(label) + + kwargs_with_greater_height[""height""] = kwargs.get(""height"", 0.25) + kwargs[""height""] = 0 + + heights_at = defaultdict(float) + + for c_annot, is_glycosylated, key in c_annotations: + self.draw_bar_at(c_annot, color=kwargs[""color""]) + if is_glycosylated: + self.draw_c_term_annotation(c_annot, **kwargs_with_greater_height) + if heights_at[c_annot] < kwargs_with_greater_height[""height""]: + heights_at[c_annot] = kwargs_with_greater_height[""height""] + else: + self.draw_c_term_annotation(c_annot, label=key, **kwargs) + if heights_at[c_annot] < kwargs[""height""]: + heights_at[c_annot] = kwargs[""height""] + + labeled = set() + for c_annot, is_glycosylated, key in c_annotations: + label = key.split(""+"")[0] + if label not in labeled: + self.draw_c_term_label(c_annot, label=label, height=heights_at[c_annot]) + labeled.add(label) + + @classmethod + def from_spectrum_match( + cls, spectrum_match, ax=None, set_layout=True, color=""red"", glycosylated_color=""forestgreen"", **kwargs + ): + annotation_options = kwargs.get(""annotation_options"", {}) + annotation_options[""color""] = color + annotation_options[""glycosylated_color""] = glycosylated_color + kwargs[""annotation_options""] = annotation_options + inst = cls(spectrum_match.target, ax=ax, **kwargs) + fragments = [f for f in spectrum_match.solution_map.fragments()] + # inst.annotate_from_fragments(fragments, **annotation_options) + inst.annotate_from_fragments_stroke(fragments, **annotation_options) + if set_layout: + inst.layout() + return inst + + +def glycopeptide_match_logo( + glycopeptide_match, + ax=None, + color=""red"", + glycosylated_color=""forestgreen"", + return_artist: bool = True, + annotation_options: Optional[dict] = None, + **kwargs, +): + if annotation_options is None: + annotation_options = {} + annotation_options[""color""] = color + annotation_options[""glycosylated_color""] = glycosylated_color + kwargs[""annotation_options""] = annotation_options + inst = SequenceGlyph.from_spectrum_match( + glycopeptide_match, color=color, glycosylated_color=glycosylated_color, ax=ax, **kwargs + ) + if return_artist: + return inst + return inst.ax + + +class ProteoformDisplay(object): + def __init__(self, proteoform, ax=None, width=60): + self.proteoform = proteoform + self.glyph_rows = [] + self.peptide_rows = [] + self.width = width + self.x = 1 + self.y = 1 + + +def draw_proteoform(proteoform, width=60): + """"""Draw a sequence logo for a proteoform"""""" + fig, ax = plt.subplots(1) + i = 0 + n = len(proteoform) + y = 1 + x = 1 + rows = [] + if width > n: + width = n + 1 + # partion the protein sequence into chunks of width positions + while i < n: + rows.append(glycopeptidepy.PeptideSequence.from_iterable(proteoform[i : i + width])) + i += width + # draw each row, starting from the last row and going up + # so that if the current row has a glycan on it, we can + # compute its height and start drawing the next row further + # up the plot + for row in rows[::-1]: + sg = SequenceGlyph(row, x=x, y=y, ax=ax) + sg.layout() + drawn_trees = [] + for position in sg.sequence_position_glyphs: + # check for glycosylation at each position + if position.position[1] and position.position[1][0].is_a(modification.ModificationCategory.glycosylation): + mod = position.position[1][0] + dtree, ax = draw_tree( + mod.rule._original, at=(position.x, position.y + 1), orientation=""vertical"", ax=sg.ax, center=False + ) + # re-center tree because draw_tree's layout only sets the starting + # coordinates of the tree root, and later transforms move it around. + # this sequence of translates will re-center it above the residue + dtree.transform.translate(-dtree.x, 0).translate(0.3, 0) + drawn_trees.append(dtree) + # get the height of the tallest glycan + if drawn_trees: + tree_height = max(dtree.extrema()[3] for dtree in drawn_trees) + 0.5 + else: + tree_height = 0 + ymax = tree_height + 1 + y += ymax + ax.set_xlim(0, width + 1) + ax.set_ylim(-1, y + 1) + return ax +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/plotting/spectral_annotation.py",".py","16845","480","from typing import TYPE_CHECKING, List, Optional + +import numpy as np + +from matplotlib import pyplot as plt, font_manager, axes +from matplotlib import patheffects as path_effects + + +from six import PY3 + +from ms_peak_picker.utils import draw_peaklist + +from ms_deisotope.data_source.scan.base import ChargeNotProvided +from ms_deisotope.data_source import ProcessedScan + +from .sequence_fragment_logo import IonAnnotationGlyphBase, glycopeptide_match_logo, GlycopeptideStubFragmentGlyph, PeptideFragmentGlyph, OxoniumIonGlyph + +if TYPE_CHECKING: + from glycresoft.tandem.spectrum_match.spectrum_match import SpectrumMatcherBase + + +default_ion_series_to_color = { + ""y"": ""red"", + ""z"": ""maroon"", + ""b"": ""blue"", + ""c"": ""navy"", + ""B"": ""blue"", + ""Y"": ""red"", + ""oxonium_ion"": ""green"", + ""stub_glycopeptide"": ""goldenrod"", + ""precursor"": ""orange"", +} + + +monosaccharide_to_symbol = { + ""Hex"": ""\u25CB"", + ""HexNAc"": ""\u25A1"", + ""Fuc"": ""\u25B3"", + ""dHex"": ""\u25B3"", + ""HexN"": ""\u25E9"", + ""NeuAc"": ""\u25C6"", + ""NeuGc"": ""\u25C7"", +} + + +def format_stub_annotation(frag): + """""" + An amusing diversion with unicode, but impractical for + narrow spectrum plots. + """""" + stack = [] + base = [""Hex"", ""HexNAc""] + for k in sorted(frag.glycosylation, key=lambda x: x.mass(), reverse=True): + if k not in base: + base.append(k) + for k in base: + v = frag.glycosylation[k] + if not v: + continue + stack.append(f"" {monosaccharide_to_symbol[k]}{v}"") + stack.append(""Pep"") + return ""\n"".join(stack) + + +if PY3: + font_options = font_manager.FontProperties(family=""sans serif"") + font_options.set_math_fontfamily(""dejavusans"") +else: + font_options = font_manager.FontProperties(family=""sans serif"") + + +unicode_superscript = { + ""0"": ""\u2070"", + ""1"": ""\u00B9"", + ""2"": ""\u00B2"", + ""3"": ""\u00B3"", + ""4"": ""\u2074"", + ""5"": ""\u2075"", + ""6"": ""\u2076"", + ""7"": ""\u2077"", + ""8"": ""\u2078"", + ""9"": ""\u2079"", + ""+"": ""\u207A"", + ""-"": ""\u207B"", +} + + +def encode_superscript(number: int) -> str: + return """".join([unicode_superscript[c] for c in str(number)]) + + +class SpectrumMatchAnnotator(object): + usemathtext: bool + spectrum_match: ""SpectrumMatcherBase"" + ax: axes.Axes + clip_labels: bool + upper: float + upshift: float + peak_labels: List[plt.Text] + intensity_scale: float + use_glyphs: bool + + def __init__( + self, + spectrum_match: ""SpectrumMatcherBase"", + ax: Optional[axes.Axes] = None, + clip_labels: bool = True, + usemathtext: bool = False, + normalize: bool = False, + use_glyphs=False, + ): + if ax is None: + _, ax = plt.subplots(1) + self.spectrum_match = spectrum_match + self.ax = ax + self.clip_labels = clip_labels + self.upper = max(spectrum_match.spectrum, key=lambda x: x.intensity).intensity * 1.35 + self.peak_labels = [] + self.upshift = 10 + self.sequence_logo = None + self.usemathtext = usemathtext + self.normalize = normalize + self.intensity_scale = 1.0 + self.use_glyphs = use_glyphs + if self.use_glyphs: + self.upper = max(spectrum_match.spectrum, key=lambda x: x.intensity).intensity * 1.0 + if self.normalize: + self.intensity_scale = max(spectrum_match.spectrum, key=lambda x: x.intensity).intensity + self.compute_scale() + + def compute_scale(self): + peaks = self.spectrum_match.deconvoluted_peak_set + mzs = [p.mz for p in peaks] + if not mzs: + self.xscale = 1.0 + else: + self.xscale = max(mzs) - min(mzs) + self.yscale = self.upper + + def draw_all_peaks(self, color=""grey"", **kwargs): + draw_peaklist(self.spectrum_match.deconvoluted_peak_set, alpha=0.3, color=color, ax=self.ax, **kwargs) + try: + draw_peaklist(self.spectrum_match._sanitized_spectrum, color=color, ax=self.ax, alpha=0.5, **kwargs) + except AttributeError: + pass + + def add_summary_labels(self, x=0.95, y=0.9): + prec_purity = self.spectrum_match.scan.annotations.get(""precursor purity"") + if prec_purity is not None: + prec_purity = ""%0.2f"" % prec_purity + else: + prec_purity = ""-"" + + prec_z = self.spectrum_match.precursor_information.charge + if prec_z is None or prec_z == ChargeNotProvided: + prec_z = ""-"" + else: + prec_z = str(prec_z) + + self.ax.text( + x, + y, + ""Isolation Purity: %s\nPrec. Z: %s"" % (prec_purity, prec_z), + transform=self.ax.transAxes, + ha=""right"", + color=""darkslategrey"", + ) + + def label_peak(self, fragment, peak, fontsize=12, rotation=90, **kw): + label = f""{fragment.name}"" + if peak.charge > 1: + if self.usemathtext: + label += f""$^{peak.charge}$"" + else: + label += encode_superscript(peak.charge) + y = peak.intensity + upshift = self.upshift + if self.use_glyphs: + y = y + upshift + else: + y = min(y + upshift, self.upper * 0.9) + + kw.setdefault(""clip_on"", self.clip_labels) + clip_on = kw[""clip_on""] + + if self.use_glyphs and fragment.series == ""stub_glycopeptide"": + art = GlycopeptideStubFragmentGlyph( + peak.mz, + y if not self.normalize else y / self.intensity_scale, + self.ax, + fragment, + self.xscale, + self.yscale, + peak.charge, + size=fontsize * 2, + ) + art.render() + self.peak_labels.append(art) + return art + elif self.use_glyphs and fragment.series in (""b"", ""y"", ""c"", ""z""): + art = PeptideFragmentGlyph( + peak.mz, + y if not self.normalize else y / self.intensity_scale, + self.ax, + fragment, + self.xscale, + self.yscale, + peak.charge, + size=fontsize * 2, + ) + art.render() + self.peak_labels.append(art) + return art + elif self.use_glyphs and fragment.series == ""oxonium_ion"": + art = OxoniumIonGlyph( + peak.mz, + y if not self.normalize else y / self.intensity_scale, + self.ax, + fragment, + self.xscale, + self.yscale, + peak.charge, + size=fontsize * 2 + ) + art.render() + self.peak_labels.append(art) + return art + else: + text = self.ax.text( + peak.mz, + y if not self.normalize else y / self.intensity_scale, + label, + rotation=rotation, + va=""bottom"", + ha=""center"", + fontsize=fontsize, + fontproperties=font_options, + clip_on=clip_on, + parse_math=self.usemathtext, + ) + self.peak_labels.append(text) + return text + + def format_axes(self): + draw_peaklist([], self.ax, pretty=True) + bboxes = list(map(lambda x: x.bbox().ymax, filter(lambda x: isinstance(x, IonAnnotationGlyphBase), self.peak_labels))) + if bboxes: + upper = max(max(bboxes), self.upper) + else: + upper = self.upper + + self.ax.set_ylim(0, upper) + + def draw_matched_peaks(self, color=""red"", alpha=0.8, fontsize=12, ion_series_to_color=None, **kwargs): + if ion_series_to_color is None: + ion_series_to_color = {} + try: + solution_map = self.spectrum_match.solution_map + except AttributeError: + return + for peak, fragment in solution_map: + try: + peak_color = ion_series_to_color.get(fragment.series, color) + except AttributeError: + peak_color = ion_series_to_color.get(fragment.kind, color) + if self.normalize: + peak = peak.clone() + peak.intensity / self.intensity_scale + # peak = (peak.mz, peak.intensity / self.intensity_scale) + draw_peaklist([peak], alpha=alpha, ax=self.ax, color=peak_color) + self.label_peak(fragment, peak, fontsize=fontsize, **kwargs) + + def draw_spectrum_graph(self, color=""red"", alpha=0.8, fontsize=12, **kwargs): + try: + graph = self.spectrum_match.spectrum_graph + except AttributeError: + return + + paths = graph.longest_paths(limit=100) + + for path in paths: + for edge in path: + self.draw_peak_pair((edge.start, edge.end), color, alpha, fontsize, label=edge.annotation, **kwargs) + + def draw_peak_pair(self, pair, color=""red"", alpha=0.8, fontsize=12, label=None, rotation=45, **kwargs): + p1, p2 = pair + self.ax.plot((p1.mz, p2.mz), (p1.intensity, p2.intensity), color=color, alpha=alpha, **kwargs) + kwargs.setdefault(""clip_on"", self.clip_labels) + clip_on = kwargs[""clip_on""] + draw_peaklist(pair, ax=self.ax, alpha=0.4, color=""orange"") + if label: + # pylint: disable=assignment-from-no-return + midx = (p1.mz + p2.mz) / 2 + # interpolate the midpoint's height + midy = (p1.intensity * (p2.mz - midx) + p2.intensity * (midx - p1.mz)) / (p2.mz - p1.mz) + + # find the angle of the line connecting the two peaks + xlo = min(p1.mz, p2.mz) + xhi = max(p1.mz, p2.mz) + adj = xhi - xlo + ylo = min(p1.intensity, p2.intensity) + yhi = max(p1.intensity, p2.intensity) + opp = yhi - ylo + hypot = np.hypot(adj, opp) + rotation = np.arccos(adj / hypot) + + if isinstance(label, (list, tuple)): + label = ""-"".join(map(str, label)) + else: + label = str(label) + text = self.ax.text( + midx, midy, label, fontsize=fontsize, ha=""center"", va=""bottom"", rotation=rotation, clip_on=clip_on + ) + text.set_path_effects( + [ + path_effects.Stroke(linewidth=0.5, foreground=""white""), + path_effects.Normal(), + ] + ) + + def draw(self, **kwargs): + fontsize = kwargs.pop(""fontsize"", 9) + rotation = kwargs.pop(""rotation"", 90) + clip_labels = kwargs.pop(""clip_labels"", self.clip_labels) + self.clip_labels = clip_labels + ion_series_to_color = kwargs.pop(""ion_series_to_color"", default_ion_series_to_color) + self.draw_all_peaks(**kwargs) + self.draw_matched_peaks(fontsize=fontsize, ion_series_to_color=ion_series_to_color, rotation=rotation, **kwargs) + self.draw_spectrum_graph(fontsize=fontsize, rotation=rotation / 2) + self.format_axes() + return self + + def add_logo_plot(self, xrel=0.15, yrel=0.8, width=0.67, height=0.13, **kwargs): + figure = self.ax.figure + iax = figure.add_axes([xrel, yrel, width, height]) + logo = glycopeptide_match_logo(self.spectrum_match, ax=iax, **kwargs) + self.sequence_logo = logo + return logo + + def _draw_mass_accuracy_plot(self, ax, error_tolerance=2e-5, **kwargs): + ion_series_to_color = kwargs.pop(""ion_series_to_color"", default_ion_series_to_color) + match = self.spectrum_match + ax.scatter( + *zip(*[(pp.peak.mz, pp.mass_accuracy()) for pp in match.solution_map]), + alpha=0.5, + edgecolor=""black"", + color=[ion_series_to_color[pp.fragment.series] for pp in match.solution_map], + ) + limits = error_tolerance + ax.set_ylim(-limits, limits) + xlim = 0, max(match.deconvoluted_peak_set, key=lambda x: x.mz).mz + 100 + ax.hlines(0, *xlim, linestyle=""--"", color=""black"", lw=0.75) + ax.hlines(limits / 2, *xlim, linestyle=""--"", lw=0.5, color=""black"") + ax.hlines(-limits / 2, *xlim, linestyle=""--"", lw=0.5, color=""black"") + ax.set_xlim(*xlim) + labels = ax.get_yticks() + labels = [""%0.2g"" % (label * 1e6) for label in labels] + ax.set_yticklabels(labels) + ax.set_xlabel(""m/z"", fontsize=10) + ax.set_ylabel(""Mass Accuracy (PPM)"", fontsize=10) + return ax + + def __repr__(self): + return f""{self.__class__.__name__}({self.spectrum_match})"" + + +class TidySpectrumMatchAnnotator(SpectrumMatchAnnotator): + def label_peak(self, fragment, peak, fontsize=12, rotation=90, **kw): + min_intensity = 0.02 * (self.upper / 1.35) + if fragment.series == ""oxonium_ion"": + if peak.intensity < min_intensity: + return + super(TidySpectrumMatchAnnotator, self).label_peak(fragment, peak, fontsize, rotation, **kw) + + +def normalize_scan(scan: ProcessedScan, factor=None): + scan = scan.copy() + scan.annotations.pop(""peak_label_map"", None) + scan.deconvoluted_peak_set = scan.deconvoluted_peak_set.__class__(p.clone() for p in scan.deconvoluted_peak_set) + bp = scan.base_peak() + if factor is None: + factor = bp.intensity / 1000 + for peak in scan: + peak.intensity /= factor + return scan + + +class MirrorSpectrumAnnotatorFacet(TidySpectrumMatchAnnotator): + def draw_all_peaks(self, color=""black"", alpha=0.5, mirror=False, **kwargs): + draw_peaklist( + self.spectrum_match.deconvoluted_peak_set + if not mirror + else [[p.mz, -p.intensity] for p in self.spectrum_match.deconvoluted_peak_set], + alpha=0.3, + color=""grey"", + ax=self.ax, + lw=0.75, + **kwargs, + ) + + def draw_matched_peaks(self, color=""red"", alpha=0.8, fontsize=12, ion_series_to_color=None, mirror=False, **kwargs): + if ion_series_to_color is None: + ion_series_to_color = {} + try: + solution_map = self.spectrum_match.solution_map + except AttributeError: + return + for peak, fragment in solution_map: + try: + peak_color = ion_series_to_color.get(fragment.series, color) + except AttributeError: + peak_color = ion_series_to_color.get(fragment.kind, color) + draw_peaklist( + [peak] if not mirror else [(peak.mz, -peak.intensity)], alpha=alpha, ax=self.ax, color=peak_color + ) + self.label_peak(fragment, peak, fontsize=fontsize, mirror=mirror, **kwargs) + + def base_peak_factor(self): + return self.spectrum_match.scan.base_peak().intensity / 100 + + def label_peak(self, fragment, peak, fontsize=12, rotation=90, mirror=False, **kw): + label = ""%s"" % fragment.name + if fragment.series == ""oxonium_ion"": + return """" + if peak.charge > 1: + if self.usemathtext: + label += f""$^{peak.charge}$"" + else: + label += encode_superscript(peak.charge) + y = peak.intensity + upshift = 2 + sign = 1 if y > 0 else -1 + y = min(y + sign * upshift, self.upper * 0.9) + + if mirror: + y = -y + + kw.setdefault(""clip_on"", self.clip_labels) + clip_on = kw[""clip_on""] + + text = self.ax.text( + peak.mz, + y, + label, + rotation=rotation, + va=""bottom"" if not mirror else ""top"", + ha=""center"", + fontsize=fontsize, + fontproperties=font_options, + clip_on=clip_on, + ) + self.peak_labels.append(text) + return text + + def draw(self, mirror=False, **kwargs): + fontsize = kwargs.pop(""fontsize"", 9) + rotation = kwargs.pop(""rotation"", 90) + clip_labels = kwargs.pop(""clip_labels"", self.clip_labels) + self.clip_labels = clip_labels + ion_series_to_color = kwargs.pop(""ion_series_to_color"", default_ion_series_to_color) + self.draw_all_peaks(mirror=mirror, **kwargs) + self.draw_matched_peaks( + fontsize=fontsize, ion_series_to_color=ion_series_to_color, rotation=rotation, mirror=mirror, **kwargs + ) + self.draw_spectrum_graph(fontsize=fontsize, rotation=rotation / 2) + self.format_axes() + return self + + +def mirror_spectra(psm_a, psm_b): + art = MirrorSpectrumAnnotatorFacet(psm_a) + art.draw() + reflect = MirrorSpectrumAnnotatorFacet(psm_b, ax=art.ax) + reflect.draw(mirror=True) + reflect.ax.set_ylim(-1500, 1200) + ax = art.ax + ax.set_yticks(np.arange(-1000, 1000 + 250, 250)) + ax.set_yticklabels(map(lambda x: str(x) + ""%"", list(range(100, -25, -25)) + list(range(25, 125, 25)))) + return art.ax, art, reflect +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/trace/extract.py",".py","5055","137","from collections import defaultdict +from contextlib import contextmanager +from typing import Dict, Optional, Tuple, Union +from ms_deisotope import DeconvolutedPeak + +import numpy as np + +from ms_deisotope.data_source import ProcessedRandomAccessScanSource +from ms_deisotope.output.common import LCMSMSQueryInterfaceMixin + +from glycresoft.task import TaskBase +from glycresoft.chromatogram_tree import ( + ChromatogramForest, + SimpleChromatogram, + find_truncation_points, + ChromatogramFilter) + + +class ChromatogramExtractor(TaskBase): + peak_loader: Union[ProcessedRandomAccessScanSource, LCMSMSQueryInterfaceMixin] + truncate: bool + + minimum_mass: float + minimum_intensity: float + + grouping_tolerance: float + min_points: int + delta_rt: float + + peak_mapping: Optional[Dict[Tuple, DeconvolutedPeak]] + chromatograms: Optional[ChromatogramForest] + base_peak_chromatogram: Optional[SimpleChromatogram] + total_ion_chromatogram: Optional[SimpleChromatogram] + + def __init__(self, peak_loader, truncate=False, minimum_mass=500, grouping_tolerance=1.5e-5, + minimum_intensity=250., min_points=3, delta_rt=0.25): + self.peak_loader = peak_loader + self.truncate = truncate + self.minimum_mass = minimum_mass + self.minimum_intensity = minimum_intensity + self.grouping_tolerance = grouping_tolerance + + self.min_points = min_points + self.delta_rt = delta_rt + + # self.accumulated = None + # self.annotated_peaks = None + self.peak_mapping = None + + self.chromatograms = None + self.base_peak_chromatogram = None + self.total_ion_chromatogram = None + + def get_scan_by_id(self, scan_id: str): + return self.peak_loader.get_scan_by_id(scan_id) + + def get_scan_header_by_id(self, scan_id: str): + return self.peak_loader.get_scan_header_by_id(scan_id) + + def get_index_information_by_scan_id(self, scan_id: str) -> dict: + return self.peak_loader.get_index_information_by_scan_id(scan_id) + + def scan_id_to_rt(self, scan_id: str) -> float: + return self.peak_loader.convert_scan_id_to_retention_time(scan_id) + + @contextmanager + def toggle_peak_loading(self): + if hasattr(self.peak_loader, 'toggle_peak_loading'): + with self.peak_loader.toggle_peak_loading(): + yield + else: + yield + + def load_peaks(self): + accumulated = self.peak_loader.ms1_peaks_above(min(500.0, self.minimum_mass), self.minimum_intensity) + annotated_peaks = [x[:2] for x in accumulated] + self.peak_mapping = {x[:2]: x[2] for x in accumulated} + if len(accumulated) > 0: + self.minimum_intensity = np.percentile([p[1].intensity for p in accumulated], 5) + return annotated_peaks + + def aggregate_chromatograms(self, annotated_peaks): + forest = ChromatogramForest([], self.grouping_tolerance, self.scan_id_to_rt) + forest.aggregate_peaks(annotated_peaks, self.minimum_mass, self.minimum_intensity) + chroma = list(forest) + self.log(""...... %d Chromatograms Extracted."" % (len(chroma),)) + self.chromatograms = ChromatogramFilter.process( + chroma, min_points=self.min_points, delta_rt=self.delta_rt) + + def summary_chromatograms(self, annotated_peaks): + mapping = defaultdict(list) + for scan_id, peak in annotated_peaks: + mapping[scan_id].append(peak.intensity) + bpc = SimpleChromatogram() + tic = SimpleChromatogram() + collection = sorted(mapping.items(), key=lambda b: self.scan_id_to_rt(b[0])) + for scan_id, intensities in collection: + rt = self.scan_id_to_rt(scan_id) + bpc[rt] = max(intensities) + tic[rt] = sum(intensities) + self.base_peak_chromatogram = bpc + self.total_ion_chromatogram = tic + + def run(self): + self.log(""... Begin Extracting Chromatograms"") + annotated_peaks = self.load_peaks() + self.log(""...... Aggregating Chromatograms"") + self.aggregate_chromatograms(annotated_peaks) + self.summary_chromatograms(annotated_peaks) + # Ensure chromatograms are wrapped and sorted. + if self.truncate: + self.chromatograms = ChromatogramFilter( + self.truncate_chromatograms(self.chromatograms)) + else: + self.chromatograms = ChromatogramFilter(self.chromatograms) + return self.chromatograms + + def truncate_chromatograms(self, chromatograms): + start, stop = find_truncation_points(*self.total_ion_chromatogram.as_arrays()) + out = [] + for c in chromatograms: + if len(c) == 0: + continue + c.truncate_before(start) + if len(c) == 0: + continue + c.truncate_after(stop) + if len(c) == 0: + continue + out.append(c) + return out + + def __iter__(self): + if self.chromatograms is None: + self.run() + return iter(self.chromatograms) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/trace/__init__.py",".py","1082","38","from glycresoft.trace.sink import ScanSink + +from glycresoft.trace.match import ( + ChromatogramMatcher, + GlycanChromatogramMatcher, + GlycopeptideChromatogramMatcher) + +from glycresoft.trace.extract import ChromatogramExtractor + +from glycresoft.trace.evaluate import ( + ChromatogramEvaluator, + LogitSumChromatogramEvaluator, + LaplacianRegularizedChromatogramEvaluator) + +from glycresoft.trace.process import ( + ChromatogramProcessor, + LogitSumChromatogramProcessor, + LaplacianRegularizedChromatogramProcessor, + GlycopeptideChromatogramProcessor, + NonSplittingChromatogramProcessor) + + +__all__ = [ + ""ScanSink"", + ""ChromatogramMatcher"", + ""GlycanChromatogramMatcher"", + ""GlycopeptideChromatogramMatcher"", + ""ChromatogramExtractor"", + ""ChromatogramEvaluator"", + ""LogitSumChromatogramEvaluator"", + ""LaplacianRegularizedChromatogramEvaluator"", + ""ChromatogramProcessor"", + ""LogitSumChromatogramProcessor"", + ""LaplacianRegularizedChromatogramProcessor"", + ""GlycopeptideChromatogramProcessor"", + ""NonSplittingChromatogramProcessor"" +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/trace/process.py",".py","5163","137","from glycresoft.task import TaskBase + +from .match import ( + GlycanChromatogramMatcher, + GlycopeptideChromatogramMatcher, + NonSplittingChromatogramMatcher) + +from .evaluate import ( + ChromatogramEvaluator, + LogitSumChromatogramEvaluator, + LaplacianRegularizedChromatogramEvaluator) + + +class ChromatogramProcessor(TaskBase): + matcher_type = GlycanChromatogramMatcher + + def __init__(self, chromatograms, database, mass_shifts=None, mass_error_tolerance=1e-5, + scoring_model=None, smooth_overlap_rt=True, acceptance_threshold=0.4, + delta_rt=0.25, peak_loader=None): + if mass_shifts is None: + mass_shifts = [] + self._chromatograms = chromatograms + self.database = database + self.mass_shifts = mass_shifts + self.mass_error_tolerance = mass_error_tolerance + self.peak_loader = peak_loader + + self.scoring_model = scoring_model + + self.smooth_overlap_rt = smooth_overlap_rt + self.acceptance_threshold = acceptance_threshold + self.delta_rt = delta_rt + + self.solutions = None + self.accepted_solutions = None + + def make_matcher(self): + matcher = self.matcher_type(self.database) + return matcher + + def _match_compositions(self): + matcher = self.make_matcher() + matches = matcher.process( + self._chromatograms, self.mass_shifts, self.mass_error_tolerance, + delta_rt=(self.delta_rt * 4 if self.smooth_overlap_rt else 0)) + return matches + + def make_evaluator(self): + evaluator = ChromatogramEvaluator(self.scoring_model) + return evaluator + + def match_compositions(self): + self.log(""Begin Matching Chromatograms"") + matches = self._match_compositions() + self.log(""End Matching Chromatograms"") + self.log(""%d Chromatogram Candidates Found"" % (len(matches),)) + return matches + + def evaluate_chromatograms(self, matches): + self.log(""Begin Evaluating Chromatograms"") + self.evaluator = self.make_evaluator() + self.evaluator.configure({ + ""peak_loader"": self.peak_loader, + ""mass_shifts"": self.mass_shifts, + ""delta_rt"": self.delta_rt, + ""mass_error_tolerance"": self.mass_error_tolerance, + ""matches"": matches + }) + self.solutions = self.evaluator.score( + matches, smooth_overlap_rt=self.smooth_overlap_rt, + mass_shifts=self.mass_shifts, delta_rt=self.delta_rt) + self.accepted_solutions = self.evaluator.acceptance_filter(self.solutions) + self.log(""End Evaluating Chromatograms"") + return self.accepted_solutions + + def run(self): + matches = self.match_compositions() + result = self.evaluate_chromatograms(matches) + return result + + def __iter__(self): + if self.accepted_solutions is None: + self.run() + return iter(self.accepted_solutions) + + +class LogitSumChromatogramProcessor(ChromatogramProcessor): + def make_evaluator(self): + evaluator = LogitSumChromatogramEvaluator(self.scoring_model) + return evaluator + + +class LaplacianRegularizedChromatogramProcessor(LogitSumChromatogramProcessor): + GRID_SEARCH = 'grid' + + def __init__(self, chromatograms, database, network=None, mass_shifts=None, mass_error_tolerance=1e-5, + scoring_model=None, smooth_overlap_rt=True, acceptance_threshold=0.4, + delta_rt=0.25, peak_loader=None, smoothing_factor=0.2, grid_smoothing_max=1.0, + regularization_model=None): + super(LaplacianRegularizedChromatogramProcessor, self).__init__( + chromatograms, database, mass_shifts, mass_error_tolerance, + scoring_model, smooth_overlap_rt, acceptance_threshold, + delta_rt, peak_loader) + if grid_smoothing_max is None: + grid_smoothing_max = 1.0 + if network is None: + network = database.glycan_composition_network + self.network = network + self.smoothing_factor = self.prepare_regularization_parameters(smoothing_factor) + self.grid_smoothing_max = grid_smoothing_max + self.regularization_model = regularization_model + + def prepare_regularization_parameters(self, smoothing_factor): + if isinstance(smoothing_factor, tuple): + if smoothing_factor[0] == self.GRID_SEARCH: + smoothing_factor = (None, smoothing_factor[1]) + elif self.GRID_SEARCH == smoothing_factor: + smoothing_factor = None + return smoothing_factor + + def make_evaluator(self): + evaluator = LaplacianRegularizedChromatogramEvaluator( + self.scoring_model, + self.network, + smoothing_factor=self.smoothing_factor, + grid_smoothing_max=self.grid_smoothing_max, + regularization_model=self.regularization_model) + return evaluator + + +class GlycopeptideChromatogramProcessor(ChromatogramProcessor): + matcher_type = GlycopeptideChromatogramMatcher + + +class NonSplittingChromatogramProcessor(ChromatogramProcessor): + matcher_type = NonSplittingChromatogramMatcher +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/trace/match.py",".py","15911","379","from collections import defaultdict + +from glycresoft.database.mass_collection import NeutralMassDatabase + +from glycresoft.chromatogram_tree import ( + Chromatogram, + Unmodified, + DuplicateNodeError, + ChromatogramFilter, + GlycanCompositionChromatogram, + GlycopeptideChromatogram, + ChromatogramGraph) + +from glycresoft.task import TaskBase + + +def span_overlap(reference, target): + """"""test whether two time Chromatogram objects + overlap each other in the time domain + + Parameters + ---------- + reference: Chromatogram + target: Chromatogram + + Returns + ------- + bool + """""" + cond = ((reference.start_time <= target.start_time and reference.end_time >= target.end_time) or ( + reference.start_time >= target.start_time and reference.end_time <= target.end_time) or ( + reference.start_time >= target.start_time and reference.end_time >= target.end_time and + reference.start_time <= target.end_time) or ( + reference.start_time <= target.start_time and reference.end_time >= target.start_time) or ( + reference.start_time <= target.end_time and reference.end_time >= target.end_time)) + return cond + + +class CompositionGroup(object): + def __init__(self, name, members): + self.name = name + self.members = tuple(members) + + def __iter__(self): + return iter(self.members) + + def __repr__(self): + return ""CompositionGroup(%r, %d members)"" % (self.name, len(self.members)) + + def __eq__(self, other): + return self.members == other.members + + +class ChromatogramMatcher(TaskBase): + memory_load_threshold = 1e5 + + def __init__(self, database, chromatogram_type=None, require_unmodified=False, enforce_charges=False): + if chromatogram_type is None: + chromatogram_type = GlycanCompositionChromatogram + self.database = database + self.require_unmodified = require_unmodified + self.enforce_charges = enforce_charges + self._group_bundle = dict() + self.chromatogram_type = chromatogram_type + if len(database) < self.memory_load_threshold: + self._in_memory = True + self.database = NeutralMassDatabase(list(database.get_all_records())) + self._original_convert = database._convert + else: + self._in_memory = False + + def _convert(self, record): + if not self._in_memory: + return self.database._convert(record) + else: + return self._original_convert(record) + + def _match(self, neutral_mass, mass_error_tolerance=1e-5): + return self.database.search_mass_ppm(neutral_mass, mass_error_tolerance) + + def _prepare_group(self, key, matches): + ids = frozenset(m.id for m in matches) + if len(ids) == 0: + return None + try: + bundle = self._group_bundle[ids] + return bundle + except KeyError: + bundle = CompositionGroup(key, [ + self._convert(m) + for m in sorted(matches, key=lambda x: getattr(x, ""calculated_mass"", 0))]) + self._group_bundle[ids] = bundle + return bundle + + def match(self, mass, mass_error_tolerance=1e-5): + hits = self._match(mass, mass_error_tolerance) + bundle = self._prepare_group(mass, hits) + return bundle + + def assign(self, chromatogram, group): + out = [] + if group is None: + return [chromatogram] + for composition in group: + case = chromatogram.clone(self.chromatogram_type) + case.composition = composition + out.append(case) + if len(out) == 0: + return [chromatogram] + return out + + def search(self, chromatogram, mass_error_tolerance=1e-5): + return self.assign(chromatogram, self.match( + chromatogram.weighted_neutral_mass, mass_error_tolerance)) + + def reverse_mass_shift_search(self, chromatograms, mass_shifts, mass_error_tolerance=1e-5): + exclude_compositions = defaultdict(list) + candidate_chromatograms = [] + + new_members = {} + unmatched = [] + + for chroma in chromatograms: + if chroma.composition is not None: + exclude_compositions[chroma.composition].append(chroma) + else: + candidate_chromatograms.append(chroma) + n = len(chromatograms) + i = 0 + self.log(""Begin Reverse Search"") + for chroma in candidate_chromatograms: + i += 1 + if i % 1000 == 0: + self.log(""... %0.2f%% chromatograms searched (%d/%d)"" % (i * 100. / n, i, n)) + candidate_mass = chroma.weighted_neutral_mass + matched = False + exclude = False + for mass_shift in mass_shifts: + matches = self.match(candidate_mass - mass_shift.mass, mass_error_tolerance) + if matches is None: + continue + for match in matches: + name = match + if name in exclude_compositions: + # This chromatogram matches another form of an existing composition + # assignment. If it were assigned during `join_mass_shifted`, then + # it overlapped with that entity and should not be merged. Otherwise + # construct a new match + for hit in exclude_compositions[name]: + if span_overlap(hit, chroma): + exclude = True + break + else: + if name in new_members: + chroma_to_update = new_members[name] + else: + chroma_to_update = self.chromatogram_type(match) + chroma_to_update.created_at = ""reverse_mass_shiftion_search"" + chroma, _ = chroma.bisect_mass_shift(Unmodified) + chroma_to_update = chroma_to_update.merge(chroma, mass_shift) + chroma_to_update.created_at = ""reverse_mass_shiftion_search"" + new_members[name] = chroma_to_update + matched = True + else: + if name in new_members: + chroma_to_update = new_members[name] + else: + chroma_to_update = self.chromatogram_type(match) + chroma_to_update.created_at = ""reverse_mass_shiftion_search"" + chroma, _ = chroma.bisect_mass_shift(Unmodified) + chroma_to_update = chroma_to_update.merge(chroma, mass_shift) + chroma_to_update.created_at = ""reverse_mass_shiftion_search"" + new_members[name] = chroma_to_update + matched = True + if not matched and not exclude: + unmatched.append(chroma) + out = [] + out.extend(s for g in exclude_compositions.values() for s in g) + out.extend(new_members.values()) + out.extend(unmatched) + return ChromatogramFilter(out) + + def join_mass_shifted(self, chromatograms, mass_shifts, mass_error_tolerance=1e-5): + out = [] + i = 0 + n = len(chromatograms) + self.log(""Begin Forward Search"") + for chroma in chromatograms: + i += 1 + if i % 1000 == 0: + self.log(""... %0.2f%% chromatograms searched (%d/%d)"" % (i * 100. / n, i, n)) + add = chroma + for mass_shift in mass_shifts: + query_mass = chroma.weighted_neutral_mass + mass_shift.mass + matches = chromatograms.find_all_by_mass(query_mass, mass_error_tolerance) + for match in matches: + if match and span_overlap(add, match): + try: + match.used_as_mass_shift.append((add.key, mass_shift)) + add = add.merge(match, node_type=mass_shift, skip_duplicate_nodes=True) + add.created_at = ""join_mass_shifted"" + add.mass_shifts.append(mass_shift) + except DuplicateNodeError as e: + e.original = chroma + e.to_add = match + e.accumulated = add + e.mass_shift = mass_shift + raise e + out.append(add) + return ChromatogramFilter(out) + + def join_common_identities(self, chromatograms, delta_rt=0): + chromatograms._build_key_map() + key_map = chromatograms._key_map + out = [] + for _, disjoint_set in key_map.items(): + if len(tuple(disjoint_set)) == 1: + out.extend(disjoint_set) + continue + + accumulated = [] + last = disjoint_set[0] + for case in disjoint_set[1:]: + if last.overlaps_in_time(case) or ((case.start_time - last.end_time) < delta_rt): + merged = last._merge_missing_only(case) + merged.used_as_mass_shift = list(last.used_as_mass_shift) + for ua in case.used_as_mass_shift: + if ua not in merged.used_as_mass_shift: + merged.used_as_mass_shift.append(ua) + last = merged + last.created_at = ""join_common_identities"" + else: + accumulated.append(last) + last = case + accumulated.append(last) + out.extend(accumulated) + return ChromatogramFilter(out) + + def find_related_profiles(self, chromatograms, mass_shifts, mass_error_tolerance=1e-5): + self.log(""Building Connected Components"") + graph = ChromatogramGraph(chromatograms) + graph.find_shared_peaks() + components = graph.connected_components() + + n_components = len(components) + self.log(""Validating %d Components"" % (n_components, )) + for i_components, component in enumerate(components): + if i_components % 1000 == 0 and i_components > 0: + self.log(""... %d Components Validated (%0.2f%%)"" % ( + i_components, + i_components / float(n_components) * 100.)) + if len(component) == 1: + continue + component = ChromatogramFilter([node.chromatogram for node in component]) + + for a in component: + pairs = [] + for mass_shift in mass_shifts: + bs = component.find_all_by_mass( + a.weighted_neutral_mass - mass_shift.mass, mass_error_tolerance) + for b in bs: + if b != a: + pairs.append((mass_shift, b)) + if not pairs: + continue + grouped_pairs = [] + pairs.sort(key=lambda x: (x[1].start_time, x[1].weighted_neutral_mass)) + last = [pairs[0]] + for current in pairs[1:]: + if current[1] is last[0][1]: + last.append(current) + else: + grouped_pairs.append(last) + last = [current] + grouped_pairs.append(last) + unique_pairs = [] + + def minimizer(args): + mass_shift, b = args + return abs(a.weighted_neutral_mass - (b.weighted_neutral_mass + mass_shift.mass)) + + for pair_group in grouped_pairs: + unique_pairs.append(min(pair_group, key=minimizer)) + + for mass_shift, b in unique_pairs: + used_set = set(b.used_as_mass_shift) + used_set.add((a.key, mass_shift)) + b.used_as_mass_shift = list(used_set) + + def search_all(self, chromatograms, mass_error_tolerance=1e-5): + matches = [] + chromatograms = ChromatogramFilter(chromatograms) + self.log(""Matching Chromatograms"") + i = 0 + n = len(chromatograms) + for chro in chromatograms: + i += 1 + if i % 1000 == 0 and i > 0: + self.log(""... %0.2f%% chromatograms searched (%d/%d)"" % (i * 100. / n, i, n)) + matches.extend(self.search(chro, mass_error_tolerance)) + matches = ChromatogramFilter(matches) + return matches + + def strip_only_modified(self, matches): + out = [] + for match in matches: + adducts = match.adducts + if Unmodified in adducts: + out.append(match) + return out + + def enforce_charge_counts(self, matches): + out = [] + for match in matches: + changed = False + for adduct in match.adducts: + if adduct.charge_carrier != 0: + charge_carrier = adduct.charge_carrier + charges = match.charge_states + has_sufficient_charge = [c for c in charges if c >= charge_carrier] + has_insufficient_charge = [c for c in charges if c < charge_carrier] + if has_insufficient_charge: + # TODO: Bisect the chromatogram along the relevant charge states + # and then extract out the disallowed adduction state, then re-combine + # the chromatogram. + pass + if not changed: + out.append(match) + return out + + def process(self, chromatograms, mass_shifts=None, mass_error_tolerance=1e-5, delta_rt=0): + if mass_shifts is None: + mass_shifts = [] + matches = [] + chromatograms = ChromatogramFilter(chromatograms) + matches = self.search_all(chromatograms, mass_error_tolerance) + matches = self.join_common_identities(matches, delta_rt) + if mass_shifts: + self.log(""Handling Mass Shifts"") + matches = self.join_mass_shifted(matches, mass_shifts, mass_error_tolerance) + matches = self.reverse_mass_shift_search(matches, mass_shifts, mass_error_tolerance) + matches = self.join_common_identities(matches, delta_rt) + self.find_related_profiles(matches, mass_shifts, mass_error_tolerance) + if self.require_unmodified: + matches = self.strip_only_modified(matches) + return matches + + +class GlycanChromatogramMatcher(ChromatogramMatcher): + pass + + +class GlycopeptideChromatogramMatcher(ChromatogramMatcher): + def __init__(self, database, chromatogram_type=None, require_unmodified=False, enforce_charges=False): + if chromatogram_type is None: + chromatogram_type = GlycopeptideChromatogram + super(GlycopeptideChromatogramMatcher, self).__init__( + database, chromatogram_type, require_unmodified=require_unmodified, + enforce_charges=enforce_charges) + + +class NonSplittingChromatogramMatcher(ChromatogramMatcher): + def __init__(self, database, chromatogram_type=None, require_unmodified=False, enforce_charges=False): + if chromatogram_type is None: + chromatogram_type = Chromatogram + super(NonSplittingChromatogramMatcher, self).__init__( + database, chromatogram_type, require_unmodified=require_unmodified, + enforce_charges=enforce_charges) + + def assign(self, chromatogram, group): + out = [] + if group is None: + return [chromatogram] + else: + case = chromatogram.clone(self.chromatogram_type) + case.composition = group + out.append(case) + return out +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/trace/sink.py",".py","1769","63","from glycresoft.scan_cache import NullScanStorageHandler + + +class ScanSink(object): + def __init__(self, scan_generator, cache_handler_type=NullScanStorageHandler): + self.scan_generator = scan_generator + self.scan_store = None + self._scan_store_type = cache_handler_type + + @property + def scan_source(self): + try: + return self.scan_generator.scan_source + except AttributeError: + return None + + @property + def sample_run(self): + try: + return self.scan_store.sample_run + except AttributeError: + return None + + def configure_cache(self, storage_path=None, name=None, source=None): + self.scan_store = self._scan_store_type.configure_storage( + storage_path, name, source) + + def configure_iteration(self, *args, **kwargs): + self.scan_generator.configure_iteration(*args, **kwargs) + + def scan_id_to_rt(self, scan_id): + return self.scan_generator.convert_scan_id_to_retention_time(scan_id) + + def store_scan(self, scan): + if self.scan_store is not None: + self.scan_store.accumulate(scan) + + def commit(self): + if self.scan_store is not None: + self.scan_store.commit() + + def complete(self): + if self.scan_store is not None: + self.scan_store.complete() + self.scan_generator.close() + + def next_scan(self): + scan = next(self.scan_generator) + self.store_scan(scan) + while scan.ms_level != 1: + scan = next(self.scan_generator) + self.store_scan(scan) + return scan + + def __iter__(self): + return self + + def __next__(self): + return self.next_scan() + + def next(self): + return self.next_scan() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/trace/evaluate.py",".py","9883","237","import time +from collections import defaultdict + +import numpy as np + +from glycresoft.task import TaskBase + +from glycresoft.chromatogram_tree import ( + Unmodified, + ChromatogramFilter, + ChromatogramOverlapSmoother, + prune_bad_mass_shift_branches) + +from glycresoft.scoring import ( + ChromatogramSolution, + ChromatogramScorer) + +from glycresoft.composition_distribution_model import smooth_network, display_table + + +class ChromatogramEvaluator(TaskBase): + acceptance_threshold = 0.4 + ignore_below = 1e-5 + + def __init__(self, scoring_model=None): + if scoring_model is None: + scoring_model = ChromatogramScorer() + self.scoring_model = scoring_model + + def configure(self, analysis_info): + self.scoring_model.configure(analysis_info) + + def evaluate(self, chromatograms, delta_rt=0.25, min_points=3, smooth_overlap_rt=True, + *args, **kwargs): + filtered = ChromatogramFilter.process( + chromatograms, delta_rt=delta_rt, min_points=min_points) + if smooth_overlap_rt: + filtered = ChromatogramOverlapSmoother(filtered) + solutions = [] + i = 0 + n = len(filtered) + for case in filtered: + start = time.time() + i += 1 + if self.in_debug_mode(): + self.debug(""... Evaluating %r"" % (case, )) + if i % 1000 == 0: + self.log(""... %0.2f%% chromatograms evaluated (%d/%d)"" % (i * 100. / n, i, n)) + try: + sol = self.evaluate_chromatogram(case) + if self.scoring_model.accept(sol): + solutions.append(sol) + else: + if sol.glycan_composition: + self.debug(""... Rejecting %s with score %s %s"" % ( + sol, sol.score, sol.score_components())) + end = time.time() + # Report on anything that took more than 30 seconds to evaluate + if end - start > 30.0: + self.log(""... %r took a long time to evaluated (%0.2fs)"" % (case, end - start)) + except (IndexError, ValueError): + continue + solutions = ChromatogramFilter(solutions) + return solutions + + def evaluate_chromatogram(self, chromatogram): + score_set = self.scoring_model.compute_scores(chromatogram) + score = score_set.product() + return ChromatogramSolution( + chromatogram, score, scorer=self.scoring_model, + score_set=score_set) + + def finalize_matches(self, solutions): + out = [] + for sol in solutions: + if sol.score <= self.ignore_below: + continue + elif (sol.composition is None) and (Unmodified not in sol.mass_shifts): + continue + out.append(sol) + solutions = ChromatogramFilter(out) + return solutions + + def score(self, chromatograms, delta_rt=0.25, min_points=3, smooth_overlap_rt=True, + mass_shifts=None, *args, **kwargs): + + solutions = self.evaluate( + chromatograms, delta_rt, min_points, smooth_overlap_rt, *args, **kwargs) + + if mass_shifts: + self.log(""Pruning mass shift branches"") + hold = self.prune_mass_shifts(solutions) + self.log(""Re-evaluating after mass shift pruning"") + solutions = self.evaluate(hold, delta_rt, min_points, smooth_overlap_rt, + *args, **kwargs) + + solutions = self.finalize_matches(solutions) + return solutions + + def prune_mass_shifts(self, solutions): + return prune_bad_mass_shift_branches(ChromatogramFilter(solutions)) + + def acceptance_filter(self, solutions, threshold=None): + if threshold is None: + threshold = self.acceptance_threshold + return ChromatogramFilter([ + sol for sol in solutions + if sol.score >= threshold and not sol.used_as_mass_shift + ]) + + def update_parameters(self, param_dict): + param_dict['scoring_model'] = self.scoring_model + + +class LogitSumChromatogramEvaluator(ChromatogramEvaluator): + acceptance_threshold = 4 + ignore_below = 2 + update_score_on_merge = True + + def __init__(self, scoring_model): + super(LogitSumChromatogramEvaluator, self).__init__(scoring_model) + + def prune_mass_shifts(self, solutions): + return prune_bad_mass_shift_branches(ChromatogramFilter(solutions), score_margin=2.5) + + def evaluate_chromatogram(self, chromatogram): + score_set = self.scoring_model.compute_scores(chromatogram) + logitsum_score = score_set.logitsum() + return ChromatogramSolution( + chromatogram, logitsum_score, scorer=self.scoring_model, + score_set=score_set) + + def evaluate(self, chromatograms, delta_rt=0.25, min_points=3, smooth_overlap_rt=True, + *args, **kwargs): + solutions = super(LogitSumChromatogramEvaluator, self).evaluate( + chromatograms, delta_rt=delta_rt, min_points=min_points, + smooth_overlap_rt=smooth_overlap_rt, *args, **kwargs) + self.log(""Collapsing Duplicates"") + accumulator = defaultdict(list) + for case in solutions: + accumulator[case.key].append(case) + solutions = [] + n = len(accumulator) + i = 0.0 + for group, members in accumulator.items(): + if i % 1000 == 0 and i > 0: + self.log(""... %d groups collapsed (%0.02f%%)"" % (i, i / n * 100.0)) + members = sorted(members, key=lambda x: x.score, reverse=True) + reference = members[0] + base = reference.clone() + for other in members[1:]: + base = base.merge(other, skip_duplicate_nodes=True) + merged = reference.__class__( + base, reference.score, scorer=reference.scorer, + score_set=reference.score_set) + if self.update_score_on_merge and len(members) > 1: + aggregated = self.evaluate_chromatogram(merged) + if aggregated.score > reference.score: + merged.score_set = aggregated.score_set + merged.score = aggregated.score + solutions.append(merged) + i += 1.0 + return ChromatogramFilter(solutions) + + +class LaplacianRegularizedChromatogramEvaluator(LogitSumChromatogramEvaluator): + def __init__(self, scoring_model, network, smoothing_factor=None, grid_smoothing_max=1.0, + regularization_model=None): + super(LaplacianRegularizedChromatogramEvaluator, + self).__init__(scoring_model) + self.network = network + self.smoothing_factor = smoothing_factor + self.grid_smoothing_max = grid_smoothing_max + self.regularization_model = regularization_model + + def network_smoothing(self, solutions): + is_bipartite = False + if isinstance(self.smoothing_factor, tuple): + smoothing_factor = self.smoothing_factor[0] + is_bipartite = True + else: + smoothing_factor = self.smoothing_factor + updated_network, search, params = smooth_network( + self.network, solutions, lmbda=smoothing_factor, + lambda_max=self.grid_smoothing_max, + model_state=self.regularization_model) + if is_bipartite: + regularization_model = params + updated_network, search, params = smooth_network( + self.network, solutions, lmbda=self.smoothing_factor[1], + lambda_max=self.grid_smoothing_max, + model_state=regularization_model) + return updated_network, search, params + + def evaluate(self, chromatograms, delta_rt=0.25, min_points=3, smooth_overlap_rt=True, + *args, **kwargs): + solutions = super(LaplacianRegularizedChromatogramEvaluator, self).evaluate( + chromatograms, delta_rt=delta_rt, min_points=min_points, + smooth_overlap_rt=smooth_overlap_rt, *args, **kwargs) + self.log(""... Applying Network Smoothing Regularization"") + updated_network, search, params = self.network_smoothing(solutions) + if updated_network is search is params is None: + return solutions + solutions = sorted(solutions, key=lambda x: x.score, reverse=True) + # TODO - Use aggregation across multiple observations for the same glycan composition + # instead of discarding all but the top scoring feature? + seen = dict() + unannotated = [] + for sol in solutions: + if sol.glycan_composition is None: + unannotated.append(sol) + continue + if sol.glycan_composition in seen: + continue + seen[sol.glycan_composition] = sol + node = updated_network[sol.glycan_composition] + if sol.score > self.acceptance_threshold: + sol.score = node.score + else: + # Do not permit network smoothing to boost scores below acceptance_threshold + if node.score < sol.score: + sol.score = node.score + self.network_parameters = params + self.grid_search = search + display_table( + search.model.neighborhood_names, + np.array(params.tau).reshape((-1, 1)), + print_fn=lambda x: self.log(""...... %s"" % (x,))) + self.log(""...... smoothing factor: %0.3f; threshold: %0.3f"" % ( + params.lmbda, params.threshold)) + return ChromatogramFilter(list(seen.values()) + unannotated) + + def update_parameters(self, param_dict): + super(LaplacianRegularizedChromatogramEvaluator, self).update_parameters(param_dict) + param_dict['network_parameters'] = self.network_parameters + param_dict['network_model'] = self.grid_search +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/chromatogram_tree/grouping.py",".py","13310","362","from typing import Callable, List, Optional, Tuple + +from ms_deisotope.peak_set import DeconvolutedPeak +from ms_deisotope.peak_dependency_network.intervals import Interval, IntervalTreeNode + +from glycresoft.task import TaskBase + +from .chromatogram import Chromatogram + + +class ChromatogramForest(TaskBase): + """"""An an algorithm for aggregating chromatograms from peaks of close mass + weighted by intensity. + + This algorithm assumes that mass accuracy is correlated with intensity, so + the most intense peaks should most accurately reflect their true neutral mass. + The expected input is a list of (scan id, peak) pairs. This list is sorted by + descending peak intensity. For each pair, using binary search, locate the nearest + existing chromatogram in :attr:`chromatograms`. If the nearest chromatogram is within + :attr:`error_tolerance` ppm of the peak's neutral mass, add this peak to that + chromatogram, otherwise create a new chromatogram containing this peak and insert + it into :attr:`chromatograms` while preserving the overall sortedness. This algorithm + is carried out by :meth:`aggregate_unmatched_peaks` + + This process may produce chromatograms with large gaps in them, which + may or may not be acceptable. To break gapped chromatograms into separate + entities, the :class:`ChromatogramFilter` type has a method :meth:`split_sparse`. + + Attributes + ---------- + chromatograms : list of Chromatogram + A list of growing Chromatogram objects, ordered by neutral mass + count : int + The number of peaks accumulated + error_tolerance : float + The mass error tolerance between peaks and possible chromatograms (in ppm) + scan_id_to_rt : callable + A callable object to convert scan ids to retention time. + count : int + The number of peaks handled + """""" + chromatograms: List[Chromatogram] + error_tolerance: float + scan_id_to_rt: Callable[[str], float] + count: int + + def __init__(self, chromatograms=None, error_tolerance=1e-5, scan_id_to_rt=lambda x: x): + if chromatograms is None: + chromatograms = [] + self.chromatograms = sorted(chromatograms, key=lambda x: x.neutral_mass) + self.error_tolerance = error_tolerance + self.scan_id_to_rt = scan_id_to_rt + self.count = 0 + + def __len__(self): + return len(self.chromatograms) + + def __iter__(self): + return iter(self.chromatograms) + + def __getitem__(self, i): + if isinstance(i, (int, slice)): + return self.chromatograms[i] + else: + return [self.chromatograms[j] for j in i] + + def find_insertion_point(self, peak: DeconvolutedPeak) -> Tuple[List[int], bool]: + index, matched = binary_search_with_flag( + self.chromatograms, peak.neutral_mass, self.error_tolerance) + return index, matched + + def find_minimizing_index(self, peak: DeconvolutedPeak, indices: List[int]) -> int: + best_index = None + best_error = float('inf') + for index_case in indices: + chroma = self[index_case] + err = abs(chroma.neutral_mass - peak.neutral_mass) / peak.neutral_mass + if err < best_error: + best_index = index_case + best_error = err + return best_index + + def handle_peak(self, scan_id: str, peak: DeconvolutedPeak): + if len(self) == 0: + index = [0] + matched = False + else: + index, matched = self.find_insertion_point(peak) + if matched: + chroma = self.chromatograms[self.find_minimizing_index(peak, index)] + most_abundant_member = chroma.most_abundant_member + chroma.insert(scan_id, peak, self.scan_id_to_rt(scan_id)) + if peak.intensity < most_abundant_member: + chroma.retain_most_abundant_member() + else: + chroma = Chromatogram(None) + chroma.created_at = ""forest"" + chroma.insert(scan_id, peak, self.scan_id_to_rt(scan_id)) + self.insert_chromatogram(chroma, index) + self.count += 1 + + def insert_chromatogram(self, chromatogram: Chromatogram, index: Tuple[int, bool]): + # TODO: Review this index arithmetic, the output isn't sorted. + index = index[0] # index is (index, matched) from binary_search_with_flag + if index != 0: + self.chromatograms.insert(index + 1, chromatogram) + else: + if len(self) == 0: + new_index = index + else: + x = self.chromatograms[index] + if x.neutral_mass < chromatogram.neutral_mass: + new_index = index + 1 + else: + new_index = index + self.chromatograms.insert(new_index, chromatogram) + + def aggregate_unmatched_peaks(self, *args, **kwargs): + import warnings + warnings.warn(""Instead of calling aggregate_unmatched_peaks, call aggregate_peaks"", stacklevel=2) + self.aggregate_peaks(*args, **kwargs) + + def aggregate_peaks(self, scan_id_peaks_list, minimum_mass=300, minimum_intensity=1000.): + unmatched = sorted(scan_id_peaks_list, key=lambda x: x[1].intensity, reverse=True) + for scan_id, peak in unmatched: + if peak.neutral_mass < minimum_mass or peak.intensity < minimum_intensity: + continue + self.handle_peak(scan_id, peak) + + +class ChromatogramMerger(TaskBase): + def __init__(self, chromatograms=None, error_tolerance=1e-5): + if chromatograms is None: + chromatograms = [] + self.chromatograms = sorted(chromatograms, key=lambda x: x.neutral_mass) + self.error_tolerance = error_tolerance + self.count = 0 + self.verbose = False + + def __len__(self): + return len(self.chromatograms) + + def __iter__(self): + return iter(self.chromatograms) + + def __getitem__(self, i): + if isinstance(i, (int, slice)): + return self.chromatograms[i] + else: + return [self.chromatograms[j] for j in i] + + def find_candidates(self, new_chromatogram: Chromatogram) -> Tuple[List[int], bool]: + index, matched = binary_search_with_flag( + self.chromatograms, new_chromatogram.neutral_mass, self.error_tolerance) + return index, matched + + def merge_overlaps(self, new_chromatogram: Chromatogram, chromatogram_range: List[Chromatogram]) -> bool: + has_merged = False + query_mass = new_chromatogram.neutral_mass + for chroma in chromatogram_range: + cond = (chroma.overlaps_in_time(new_chromatogram) and abs( + (chroma.neutral_mass - query_mass) / query_mass) < self.error_tolerance and + not chroma.common_nodes(new_chromatogram)) + if cond: + chroma.merge(new_chromatogram) + has_merged = True + break + return has_merged + + def find_insertion_point(self, new_chromatogram: Chromatogram) -> Optional[int]: + return binary_search_exact( + self.chromatograms, new_chromatogram.neutral_mass) + + def handle_new_chromatogram(self, new_chromatogram: Chromatogram): + if len(self) == 0: + index = [0] + matched = False + else: + index, matched = self.find_candidates(new_chromatogram) + if matched: + + chroma = self[index] + has_merged = self.merge_overlaps(new_chromatogram, chroma) + if not has_merged: + insertion_point = self.find_insertion_point(new_chromatogram) + self.insert_chromatogram(new_chromatogram, [insertion_point]) + else: + self.insert_chromatogram(new_chromatogram, index) + self.count += 1 + + def insert_chromatogram(self, chromatogram: Chromatogram, index: List[int]): + if index[0] != 0: + self.chromatograms.insert(index[0] + 1, chromatogram) + else: + if len(self) == 0: + new_index = index[0] + else: + x = self.chromatograms[index[0]] + if x.neutral_mass < chromatogram.neutral_mass: + new_index = index[0] + 1 + else: + new_index = index[0] + self.chromatograms.insert(new_index, chromatogram) + + def aggregate_chromatograms(self, chromatograms): + unmatched = sorted(chromatograms, key=lambda x: x.total_signal, reverse=True) + for chroma in unmatched: + self.handle_new_chromatogram(chroma) + + +def flatten_tree(tree): + output_queue = [] + input_queue = [tree] + while input_queue: + next_node = input_queue.pop() + output_queue.append(next_node) + + next_right = next_node.right + if next_right is not None: + input_queue.append(next_right) + + next_left = next_node.left + if next_left is not None: + input_queue.append(next_left) + return output_queue[::-1] + + +def layered_traversal(nodes): + return sorted(nodes, key=lambda x: (x.level, x.center), reverse=True) + + +class ChromatogramOverlapSmoother(object): + def __init__(self, chromatograms, error_tolerance=1e-5): + self.retention_interval_tree = build_rt_interval_tree(chromatograms) + self.error_tolerance = error_tolerance + self.solution_map = {None: []} + self.chromatograms = self.smooth() + + def __iter__(self): + return iter(self.chromatograms) + + def __getitem__(self, i): + return self.chromatograms[i] + + def __len__(self): + return len(self.chromatograms) + + def aggregate_interval(self, tree): + chromatograms = [interval[0] for interval in tree.contained] + chromatograms.extend(self.solution_map[tree.left]) + chromatograms.extend(self.solution_map[tree.right]) + merger = ChromatogramMerger(error_tolerance=self.error_tolerance) + merger.aggregate_chromatograms(chromatograms) + self.solution_map[tree] = list(merger) + return merger + + def smooth(self): + nodes = layered_traversal(flatten_tree(self.retention_interval_tree)) + for node in nodes: + self.aggregate_interval(node) + final = self.solution_map[self.retention_interval_tree] + result = ChromatogramMerger() + result.aggregate_chromatograms(final) + return list(result) + + +def binary_search_with_flag(array, mass, error_tolerance=1e-5): + lo = 0 + n = hi = len(array) + while hi != lo: + mid = (hi + lo) // 2 + x = array[mid] + err = (x.neutral_mass - mass) / mass + if abs(err) <= error_tolerance: + i = mid - 1 + # Begin Sweep forward + while i > 0: + x = array[i] + err = (x.neutral_mass - mass) / mass + if abs(err) <= error_tolerance: + i -= 1 + continue + else: + break + low_end = i + i = mid + 1 + + # Begin Sweep backward + while i < n: + x = array[i] + err = (x.neutral_mass - mass) / mass + if abs(err) <= error_tolerance: + i += 1 + continue + else: + break + high_end = i + return list(range(low_end, high_end)), True + elif (hi - lo) == 1: + return [mid], False + elif err > 0: + hi = mid + elif err < 0: + lo = mid + return 0, False + + +def binary_search_exact(array, mass): + lo = 0 + hi = len(array) + while hi != lo: + mid = (hi + lo) // 2 + x = array[mid] + err = (x.neutral_mass - mass) + if err == 0: + return mid + elif (hi - lo) == 1: + return mid + elif err > 0: + hi = mid + else: + lo = mid + + +def smooth_overlaps(chromatogram_list, error_tolerance=1e-5): + chromatogram_list = sorted(chromatogram_list, key=lambda x: x.neutral_mass) + out = [] + last = chromatogram_list[0] + i = 1 + while i < len(chromatogram_list): + current = chromatogram_list[i] + mass_error = abs((last.neutral_mass - current.neutral_mass) / current.neutral_mass) + if mass_error <= error_tolerance: + if last.overlaps_in_time(current): + last = last.merge(current) + last.created_at = ""smooth_overlaps"" + else: + out.append(last) + last = current + else: + out.append(last) + last = current + i += 1 + out.append(last) + return out + + +class ChromatogramRetentionTimeInterval(Interval): + def __init__(self, chromatogram): + super(ChromatogramRetentionTimeInterval, self).__init__( + chromatogram.start_time, chromatogram.end_time, [chromatogram]) + self.neutral_mass = chromatogram.neutral_mass + self.start_time = self.start + self.end_time = self.end + self.data['neutral_mass'] = self.neutral_mass + + +def build_rt_interval_tree(chromatogram_list, interval_tree_type=IntervalTreeNode): + intervals = list(map(ChromatogramRetentionTimeInterval, chromatogram_list)) + interval_tree = interval_tree_type.build(intervals) + return interval_tree +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/chromatogram_tree/relation_graph.py",".py","8875","277","import itertools + +from collections import deque, defaultdict +from typing import List, Set, Optional, Dict, DefaultDict, Type, ClassVar, Generic, TypeVar, Deque, Any + +import numpy as np + +from glypy.structure.glycan_composition import FrozenMonosaccharideResidue +from ms_deisotope.peak_dependency_network.intervals import SpanningMixin + +from .grouping import ChromatogramRetentionTimeInterval, IntervalTreeNode +from .index import ChromatogramFilter +from .chromatogram import Chromatogram + + +_standard_transitions = [ + FrozenMonosaccharideResidue.from_iupac_lite(""HexNAc""), + FrozenMonosaccharideResidue.from_iupac_lite(""Hex""), + FrozenMonosaccharideResidue.from_iupac_lite('NeuAc'), + FrozenMonosaccharideResidue.from_iupac_lite(""Fuc""), + FrozenMonosaccharideResidue.from_iupac_lite(""HexA""), +] + + +class UnknownTransition(object): + def __init__(self, mass): + self._mass = mass + self._hash = hash(mass) + + def __eq__(self, other): + return self.mass() == other.mass() + + def mass(self): + return self._mass + + def __hash__(self): + return self._hash + + def __repr__(self): + return ""{self.__class__.__name__}({mass})"".format(self=self, mass=self.mass()) + + +class TimeQuery(SpanningMixin): + def __init__(self, chromatogram, width=0): + self.start = chromatogram.start_time - width + self.end = chromatogram.end_time + width + + def __repr__(self): + return ""TimeQuery(%f, %f)"" % (self.start, self.end) + + +class ChromatogramGraphNode(ChromatogramRetentionTimeInterval): + chromatogram: Chromatogram + edges: Set['ChromatogramGraphEdge'] + index: int + center: float + + def __init__(self, chromatogram, index, edges=None): + super(ChromatogramGraphNode, self).__init__(chromatogram) + if edges is None: + edges = set() + self.chromatogram = chromatogram + self.index = index + self.edges = edges + + total = 0 + abundance = 0 + for node in self.chromatogram.nodes: + intensity = node.total_intensity() + total += node.retention_time * intensity + abundance += intensity + self.center = total / abundance + + def get_chromatogram(self): + return self.chromatogram + + def __repr__(self): + return ""%s(%s)"" % (self.__class__.__name__, self.chromatogram,) + + def __index__(self): + return self.index + + def __hash__(self): + return hash(self.index) + + def __eq__(self, other): + return self.chromatogram == other.chromatogram + + +class ChromatogramGraphEdge(object): + node_a: ChromatogramGraphNode + node_b: ChromatogramGraphNode + weight: float + mass_error: float + rt_error: float + + def __init__(self, node_a, node_b, transition, weight=1, mass_error=0, rt_error=0): + self.node_a = node_a + self.node_b = node_b + self.transition = transition + self.weight = weight + self.mass_error = mass_error + self.rt_error = rt_error + self.node_a.edges.add(self) + self.node_b.edges.add(self) + + def __repr__(self): + return ""%s(%s, %s, %s)"" % ( + self.__class__.__name__, self.node_a.chromatogram, self.node_b.chromatogram, + self.transition) + + def __hash__(self): + return hash(frozenset((self.node_a.index, self.node_b.index))) + + def __eq__(self, other): + return frozenset((self.node_a.index, self.node_b.index)) == frozenset((other.node_a.index, other.node_b.index)) + + def __ne__(self, other): + return not self == other + + +def explode_node(node): + items = deque() + results = [] + + for edge in node.edges: + items.append(edge.node_a) + items.append(edge.node_b) + + visited = set() + while items: + node = items.popleft() + if node.index in visited: + continue + visited.add(node.index) + results.append(node) + + for edge in node.edges: + if edge.node_a.index not in visited: + items.append(edge.node_a) + if edge.node_b.index not in visited: + items.append(edge.node_b) + return results + + +def chromatograms_from_edge(edge): + return edge.node_a.chromatogram, edge.node_b.chromatogram + + +V = TypeVar(""V"", bound=ChromatogramGraphNode) +E = TypeVar(""E"", bound=ChromatogramGraphEdge) + +class ChromatogramGraph(Generic[V, E]): + node_cls: ClassVar[Type[V]] = ChromatogramGraphNode + edge_cls: ClassVar[Type[E]] = ChromatogramGraphEdge + + chromatograms: List[Chromatogram] + assigned_seed_queue: Deque[V] + assignment_map: Dict[Any, V] + + nodes: List[V] + edges: Set[E] + + rt_tree: IntervalTreeNode + + def __init__(self, chromatograms): + self.chromatograms = chromatograms + self.assigned_seed_queue = deque() + self.assignment_map = {} + self.nodes = self._construct_graph_nodes(self.chromatograms) + self.rt_tree = IntervalTreeNode.build(self.nodes) + self.edges = set() + + def __len__(self): + return len(self.nodes) + + def __iter__(self): + return iter(self.nodes) + + def __getitem__(self, i): + return self.nodes[i] + + def _construct_graph_nodes(self, chromatograms) -> List[V]: + nodes = [] + for i, chroma in enumerate(chromatograms): + node = (self.node_cls(chroma, i)) + nodes.append(node) + if node.chromatogram.composition: + self.enqueue_seed(node) + self.assignment_map[node.chromatogram.composition] = node + return nodes + + def enqueue_seed(self, chromatogram_with_assignment): + self.assigned_seed_queue.append(chromatogram_with_assignment) + + def pop_seed(self): + return self.assigned_seed_queue.popleft() + + def iterseeds(self): + while self.assigned_seed_queue: + yield self.pop_seed() + + def find_edges(self, node: V, query_width: float=2., transitions=None, **kwargs): + if transitions is None: + transitions = _standard_transitions + query = TimeQuery(node.chromatogram, query_width) + nodes = ChromatogramFilter(self.rt_tree.overlaps(query.start, query.end)) + + starting_mass = node.neutral_mass + + for transition in transitions: + added = starting_mass + transition.mass() + match = nodes.find_mass(added) + if match: + ppm_error = (added - match.neutral_mass) / match.neutral_mass + rt_error = (node.center - match.center) + self.edges.add(self.edge_cls(node, match, transition, mass_error=ppm_error, rt_error=rt_error)) + + def find_shared_peaks(self): + peak_map = defaultdict(set) + for chromatogram_node in self.nodes: + for peak_bunch in chromatogram_node.chromatogram.peaks: + for peak in peak_bunch: + peak_map[peak].add(chromatogram_node) + edges = set() + for peak, nodes in peak_map.items(): + for a, b in itertools.combinations(nodes, 2): + edges.add(frozenset((a, b))) + + result = [] + for edge in edges: + start, end = sorted(edge, key=lambda x: x.index) + delta = -(start.neutral_mass - end.neutral_mass) + chromatogram_edge = ChromatogramGraphEdge( + start, end, UnknownTransition(delta), rt_error=start.center - end.center) + result.append(chromatogram_edge) + self.edges.add(chromatogram_edge) + return result + + def build(self, query_width: float=2., transitions=None, **kwargs): + for node in self.iterseeds(): + self.find_edges(node, query_width=query_width, transitions=transitions, **kwargs) + + def adjacency_matrix(self) -> np.ndarray: + adjmat = np.zeros((len(self), len(self))) + nodes = self.nodes + for node in nodes: + for edge in node.edges: + adjmat[edge.node_a.index, edge.node_b.index] = 1 + return adjmat + + def connected_components(self) -> List[List[V]]: + pool = set(self.nodes) + components = [] + + i = 0 + while pool: + i += 1 + current_component = set() + visited = set() + node = pool.pop() + current_component.add(node) + j = 0 + while current_component: + j += 1 + node = current_component.pop() + visited.add(node) + for edge in node.edges: + if edge.node_a not in visited and edge.node_a in pool: + current_component.add(edge.node_a) + pool.remove(edge.node_a) + if edge.node_b not in visited and edge.node_b in pool: + current_component.add(edge.node_b) + pool.remove(edge.node_b) + components.append(list(visited)) + return components +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/chromatogram_tree/__init__.py",".py","1083","40","from . import mass_shift +from .mass_shift import ( + MassShift, CompoundMassShift, Unmodified, Ammonium, + Sodium, Formate, Potassium) + +from . import chromatogram +from .chromatogram import ( + Chromatogram, ChromatogramInterface, ChromatogramTreeNode, + ChromatogramTreeList, EmptyListException, DuplicateNodeError, + mask_subsequence, split_by_charge, group_by, ChromatogramWrapper, + GlycanCompositionChromatogram, GlycopeptideChromatogram, get_chromatogram) + + +from . import grouping +from .grouping import ( + ChromatogramForest, ChromatogramOverlapSmoother, + smooth_overlaps, build_rt_interval_tree) + + +from . import generic +from .generic import ( + SimpleChromatogram, + SimpleEntityChromatogram, + find_truncation_points) + +from . import index +from .index import ChromatogramFilter, DisjointChromatogramSet + + +from . import relation_graph +from .relation_graph import ChromatogramGraph + + +from . import mass_shift_tree +from .mass_shift_tree import (prune_bad_mass_shift_branches, MassShiftTreePruner) + + +from . import utils +from .utils import ArithmeticMapping +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/chromatogram_tree/mass_shift.py",".py","9199","289","from collections import defaultdict +from glypy import Composition + +mass_shift_index = dict() + + +class MassShiftBase(object): + def __eq__(self, other): + try: + return (self.name == other.name and abs( + self.mass - other.mass) < 1e-10) or self.composition == other.composition + except AttributeError: + return False + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash(self.name) + + def _register_name(self): + mass_shift_index[self.name] = self.composition + + @classmethod + def get(cls, name): + return mass_shift_index[name] + +try: + from glycresoft._c.chromatogram_tree.mass_shift import MassShiftBase + mass_shift_index = MassShiftBase._get_name_registry() +except ImportError: + pass + + +class MassShift(MassShiftBase): + def __init__(self, name, composition, tandem_composition=None, charge_carrier=0): + self.name = name + self.composition = composition + self.mass = composition.mass + self.charge_carrier = charge_carrier + if tandem_composition is None: + tandem_composition = self.composition.copy() + self.tandem_composition = tandem_composition + self.tandem_mass = self.tandem_composition.mass + self._register_name() + + def __repr__(self): + return ""MassShift(%s, %s)"" % (self.name, self.composition) + + def __mul__(self, n): + if self.composition == {}: + return self + if isinstance(n, int): + return CompoundMassShift({self: n}) + else: + raise TypeError(""Cannot multiply MassShift by non-integer"") + + def __rmul__(self, n): + if self.composition == {}: + return self + if isinstance(n, int): + return CompoundMassShift({self: n}) + else: + raise TypeError(""Cannot multiply MassShift by non-integer"") + + def __getstate__(self): + return { + ""tandem_composition"": self.tandem_composition, + ""name"": self.name, + ""mass"": self.mass, + ""charge_carrier"": self.charge_carrier, + ""tandem_mass"": self.tandem_mass, + ""composition"": self.composition + } + + def __setstate__(self, state): + if isinstance(state, tuple): + # We're receiving an older Cython pickled state + self._hash = state[0] + self.composition = state[1] + self.mass = state[2] + self.name = state[3] + self.tandem_composition = state[4] + self.tandem_mass = state[5] + self.charge_carrier = state[6].get('charge_carrier', 0) + + else: + self.name = state['name'] + self.charge_carrier = state.get('charge_carrier', 0) + self.mass = state['mass'] + self.composition = state['composition'] + self.tandem_mass = state['tandem_mass'] + self.tandem_composition = state['tandem_composition'] + self._hash = hash(self.name) + + def __add__(self, other): + if self.composition == {}: + return other + elif other.composition == {}: + return self + + if self == other: + return self * 2 + if isinstance(other, CompoundMassShift): + return other + self + return CompoundMassShift({ + self: 1, + other: 1 + }) + + def __sub__(self, other): + if other.composition == {}: + return self + # if self.composition == {}: + # name = ""-(%s)"" % other.name + # composition = -other.composition + # tandem_composition = -other.tandem_composition + # charge_carrier = -other.charge_carrier + if self == other: + return Unmodified + if isinstance(other, CompoundMassShift): + return other - self + else: + return CompoundMassShift({ + self: 1, + other: -1 + }) + + def composed_with(self, other): + return self == other + + +class CompoundMassShift(MassShiftBase): + def __init__(self, counts=None): + if counts is None: + counts = {} + self.counts = defaultdict(int, counts) + self.composition = None + self.tandem_composition = None + self.name = None + self.mass = 0 + self.tandem_mass = 0 + self.charge_carrier = 0 + self._compute_composition() + self._compute_name() + + def __reduce__(self): + return self.__class__, (self.counts, ) + + def _compute_composition(self): + composition = Composition() + tandem_composition = Composition() + charge_carrier = 0 + for k, v in self.counts.items(): + composition += k.composition * v + tandem_composition += k.tandem_composition * v + charge_carrier += k.charge_carrier * v + self.composition = composition + self.mass = composition.mass + self.tandem_composition = tandem_composition + self.tandem_mass = tandem_composition.mass + self.charge_carrier = charge_carrier + + def _compute_name(self): + parts = [] + for k, v in self.counts.items(): + if v == 1: + parts.append(k.name) + else: + parts.append(""%s * %d"" % (k.name, v)) + self.name = "" + "".join(sorted(parts)) + + def composed_with(self, other): + if isinstance(other, MassShift): + return self.counts.get(other, 0) >= 1 + elif isinstance(other, CompoundMassShift): + for key, count in other.counts.items(): + if self.counts.get(key, 0) != count: + return False + return True + + def __add__(self, other): + if other == Unmodified: + return self + elif self == Unmodified: + return other + + if isinstance(other, MassShift): + counts = defaultdict(int, self.counts) + counts[other] += 1 + if counts[other] == 0: + counts.pop(other) + if counts: + return self.__class__(counts) + return Unmodified + elif isinstance(other, CompoundMassShift): + counts = defaultdict(int, self.counts) + for k, v in other.counts.items(): + if v != 0: + counts[k] += v + if counts[k] == 0: + counts.pop(k) + if counts: + return self.__class__(counts) + return Unmodified + else: + return NotImplemented + + def __sub__(self, other): + if other == Unmodified: + return self + if not self.composed_with(other): + raise ValueError( + ""Cannot subtract %r from %r, not part of the compound"" % (other, self)) + + if isinstance(other, MassShift): + counts = defaultdict(int, self.counts) + counts[other] -= 1 + if counts[other] == 0: + counts.pop(other) + if counts: + return self.__class__(counts) + return Unmodified + elif isinstance(other, CompoundMassShift): + counts = defaultdict(int, self.counts) + for k, v in other.counts.items(): + counts[k] -= v + if counts[k] == 0: + counts.pop(k) + if counts: + return self.__class__(counts) + return Unmodified + else: + return NotImplemented + + def __mul__(self, i): + if self.composition == {}: + return self + if isinstance(i, int): + counts = defaultdict(int, self.counts) + for k in counts: + if k == Unmodified: + continue + counts[k] *= i + return self.__class__(counts) + else: + raise TypeError(""Cannot multiply MassShift by non-integer"") + + def __neg__(self): + return self * -1 + + def __repr__(self): + return ""MassShift(%s, %s)"" % (self.name, self.composition) + + +Unmodified = MassShift(""Unmodified"", Composition()) +Formate = MassShift(""Formate"", Composition('HCOOH'), charge_carrier=1) +Ammonium = MassShift(""Ammonium"", Composition(""NH3""), Composition()) +Sodium = MassShift(""Sodium"", Composition(""Na1H-1""), charge_carrier=1) +Potassium = MassShift(""Potassium"", Composition(""K1H-1""), charge_carrier=1) +Deoxy = MassShift(""Deoxy"", Composition(""O-1""), Composition()) + + +class MassShiftCollection(object): + def __init__(self, mass_shifts): + self.mass_shifts = list(mass_shifts) + self.mass_shift_map = {} + self._invalidate() + + def _invalidate(self): + self.mass_shift_map = { + mass_shift.name: mass_shift for mass_shift in self.mass_shifts + } + + def append(self, mass_shift): + self.mass_shifts.append(mass_shift) + self._invalidate() + + def __getitem__(self, i): + try: + return self.mass_shifts[i] + except (IndexError, TypeError): + return self.mass_shift_map[i] + + def __iter__(self): + return iter(self.mass_shifts) + + def __len__(self): + return len(self.mass_shifts)","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/chromatogram_tree/generic.py",".py","5073","182","'''A collection of odds-and-ends that are not heavily used or optimized. +''' + +from collections import OrderedDict + +import numpy as np +from scipy.ndimage import gaussian_filter1d + + +class ChromatogramDeltaNode(object): + '''Represent a sub-region of a chromatogram to determine whether to truncate + the chromatogram or not based upon whether or not they show large gaps in time + or significant change in intensity over time. + ''' + + def __init__(self, retention_times, delta_intensity, start_time, end_time, is_below_threshold=True): + self.retention_times = retention_times + self.delta_intensity = delta_intensity + self.start_time = start_time + self.end_time = end_time + self.mean_change = np.mean(delta_intensity) + self.is_below_threshold = is_below_threshold + + def __repr__(self): + return ""ChromatogramDeltaNode(%f, %f, %f)"" % ( + self.mean_change, self.start_time, self.end_time) + + @classmethod + def partition(cls, rt, delta_smoothed, window_size=.5): + last_rt = rt[1] + last_index = 1 + nodes = [] + i = 0 + for i, rt_i in enumerate(rt[2:]): + if (rt_i - last_rt) >= window_size: + nodes.append( + cls( + rt[last_index:i], + delta_smoothed[last_index:i + 1], + last_rt, rt[i])) + last_index = i + last_rt = rt_i + nodes.append( + cls( + rt[last_index:i], + delta_smoothed[last_index:i + 1], + last_rt, rt[i])) + return nodes + + +def build_chromatogram_nodes(rt, signal, sigma=3): + rt = np.array(rt) + smoothed = gaussian_filter1d(signal, sigma) + delta_smoothed = np.gradient(smoothed, rt) + change = delta_smoothed[:-1] - delta_smoothed[1:] + avg_change = change.mean() + std_change = change.std() + + lo = avg_change - std_change + hi = avg_change + std_change + + nodes = ChromatogramDeltaNode.partition(rt, delta_smoothed) + + for node in nodes: + if lo > node.mean_change or node.mean_change > hi: + node.is_below_threshold = False + + return nodes + + +def find_truncation_points(rt, signal, sigma=3, pad=3): + nodes = build_chromatogram_nodes(rt, signal, sigma=3) + + leading = 0 + ending = len(nodes) + + for node in nodes: + if not node.is_below_threshold: + break + leading += 1 + leading -= 3 + leading = max(leading - pad, 0) + + for node in reversed(nodes): + if not node.is_below_threshold: + break + ending -= 1 + + ending = min(ending + pad, len(nodes) - 1) + if len(nodes) == 1: + return nodes[0].start_time, nodes[0].end_time + elif len(nodes) == 2: + return nodes[0].start_time, nodes[-1].end_time + return nodes[leading].start_time, nodes[ending].end_time + + +class SimpleChromatogram(OrderedDict): + '''A simplified Chromatogram-like object which supports :meth:`as_arrays` + and :meth:`get_chromatogram`, but otherwise acts as a mapping from retention + time to intensity. + ''' + def __init__(self, *args): + super(SimpleChromatogram, self).__init__(*args) + + composition = None + glycan_composition = None + + def as_arrays(self): + return ( + np.array(list(self.keys())), + np.array(list(self.values())) + ) + + def get_chromatogram(self): + return self + + def _new(self): + return self.__class__() + + def slice(self, start, end): + pairs = [] + for t, v in self.items(): + if start <= t <= end: + pairs.append((t, v)) + dup = self._new() + dup.update(pairs) + return dup + + def split_sparse(self, delta_rt=1.): + parts = [] + start = 0 + last = None + for i, t in enumerate(self.keys()): + if last is None: + last = t + start = t + if t - last >= delta_rt: + parts.append(self.slice(start, last)) + start = t + last = t + if last != start: + parts.append(self.slice(start, last)) + return parts + + @property + def start_time(self): + return next(iter(self.keys())) + + @property + def end_time(self): + return list(self.keys())[-1] + + @property + def apex_time(self): + time, intensity = self.as_arrays() + i = np.argmax(intensity) + return time[i] + + +class SimpleEntityChromatogram(SimpleChromatogram): + + def __init__(self, entity=None, glycan_composition=None): + self.entity = entity + self.composition = entity + self.glycan_composition = glycan_composition + super(SimpleEntityChromatogram, self).__init__() + + def _new(self): + return self.__class__(self.entity, self.glycan_composition) + + +class PairedArray(object): + def __init__(self, x, y): + self.x = x + self.y = y + + def as_arrays(self): + return self.x, self.y + + def __len__(self): + return len(self.x) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/chromatogram_tree/utils.py",".py","1147","48","from collections import Counter + + +class ArithmeticMapping(Counter): + def __init__(self, base=None, **kwargs): + if base is not None: + self.update(base) + else: + if kwargs: + self.update(kwargs) + + def __missing__(self, key): + return 0 + + def __add__(self, other): + inst = self.copy() + for key, value in other.items(): + inst[key] += value + return inst + + def __sub__(self, other): + inst = self.copy() + for key, value in other.items(): + inst[key] -= value + return inst + + def __mul__(self, i): + inst = self.copy() + for key, value in self.items(): + inst[key] = value * i + return inst + + def __imul__(self, i): + for key, value in list(self.items()): + self[key] = value * i + return self + + def __div__(self, i): + inst = self.copy() + for key, value in self.items(): + inst[key] = value / i + return inst + + def __idiv__(self, i): + for key, value in list(self.items()): + self[key] = value / i + return self +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/chromatogram_tree/chromatogram.py",".py","37948","1240","from abc import ABCMeta +from collections import defaultdict, Counter +from operator import attrgetter +from typing import Iterable, List, Optional, Set + +from six import add_metaclass + +import numpy as np + +from glypy.utils import uid +from glypy.structure.glycan_composition import HashableGlycanComposition + +from ms_deisotope import DeconvolutedPeak +from ms_deisotope.data_source import ProcessedRandomAccessScanSource + +from .mass_shift import MassShiftBase, Unmodified +from .utils import ArithmeticMapping + + +try: + trapezoid = np.trapz +except AttributeError: + trapezoid = np.trapezoid + +MIN_POINTS_FOR_CHARGE_STATE = 3 +intensity_getter = attrgetter(""intensity"") + + +class EmptyListException(Exception): + pass + + +class DuplicateNodeError(Exception): + pass + + +def group_by(ungrouped_list, key_fn=lambda x: x, transform_fn=lambda x: x): + groups = defaultdict(list) + for item in ungrouped_list: + key_value = key_fn(item) + groups[key_value].append(transform_fn(item)) + return groups + + +def split_by_charge(peaks): + return group_by(peaks, lambda x: x.charge) + + +def count_charge_states(peaks): + peaks = [j for i in peaks for j in i] + return len(split_by_charge(peaks)) + + +class SubsequenceMasker(object): + def __init__(self, target, masker): + self.target = target + self.masker = masker + + self.masking_nodes = [] + + def masking_nodes_from_masker(self): + self.masking_nodes = self.masker.nodes.unspool() + + def masking_nodes_from_peaks(self, peaks): + nodes = [] + for node in self.masker.nodes.unspool_strip_children(): + for peak in node.members: + if peak in peaks: + nodes.append(node) + break + self.masking_nodes = nodes + + def mask(self): + unmasked_nodes = [] + target_nodes = self.target.nodes.unspool_strip_children() + for node in target_nodes: + if node not in self.masking_nodes: + unmasked_nodes.append(node) + + new = self.target.clone() + new.clear() + new.used_as_mass_shift = [] + new.created_at = ""mask_subsequence"" + for node in unmasked_nodes: + new.insert_node(node) + return new + + @classmethod + def mask_subsequence(cls, target, masker, peaks=None): + inst = cls(target, masker) + if peaks is None: + inst.masking_nodes_from_masker() + else: + inst.masking_nodes_from_peaks(peaks) + return inst.mask() + + +mask_subsequence = SubsequenceMasker.mask_subsequence + + +class _TimeIntervalMethods(object): + __slots__ = [] + + def overlaps_in_time(self, interval): + self_start_time = self.start_time + self_end_time = self.end_time + interval_start_time = interval.start_time + interval_end_time = interval.end_time + cond = ((self_start_time <= interval_start_time and self_end_time >= interval_end_time) or ( + self_start_time >= interval_start_time and self_end_time <= interval_end_time) or ( + self_start_time >= interval_start_time and self_end_time >= interval_end_time and + self_start_time <= interval_end_time) or ( + self_start_time <= interval_start_time and self_end_time >= interval_start_time) or ( + self_start_time <= interval_end_time and self_end_time >= interval_end_time)) + return cond + + def spans_time_point(self, point): + return self.start_time <= point <= self.end_time + + +class Chromatogram(_TimeIntervalMethods): + created_at = ""new"" + glycan_composition = None + + nodes: 'ChromatogramTreeList' + mass_shifts: List[MassShiftBase] + used_as_mass_shift: List + + _total_intensity: float + _neutral_mass: float + _weighted_neutral_mass: float + _last_neutral_mass: float + _charge_states: Set[int] + + _start_time: float + _end_time: float + + def __init__(self, composition, nodes=None, mass_shifts=None, used_as_mass_shift=None): + if nodes is None: + nodes = ChromatogramTreeList() + if mass_shifts is None: + mass_shifts = [] + if used_as_mass_shift is None: + used_as_mass_shift = [] + + self.nodes = nodes + self._mass_shifts = mass_shifts + self.used_as_mass_shift = used_as_mass_shift + self._infer_mass_shifts() + self._has_msms = None + + self.composition = composition + self._total_intensity = None + self._neutral_mass = None + self._weighted_neutral_mass = None + self._last_neutral_mass = 0. + self._most_abundant_member = 0. + self._charge_states = None + self._retention_times = None + self._peaks = None + self._scan_ids = None + self._start_time = None + self._end_time = None + + def _invalidate(self): + self._total_intensity = None + self._last_neutral_mass = self._neutral_mass if self._neutral_mass is not None else 0. + self._neutral_mass = None + self._weighted_neutral_mass = None + self._charge_states = None + self._retention_times = None + self._peaks = None + self._scan_ids = None + self._mass_shifts = None + self._has_msms = None + self._start_time = None + self._end_time = None + self._last_most_abundant_member = self._most_abundant_member + self._most_abundant_member = None + + def invalidate(self): + self._invalidate() + + def retain_most_abundant_member(self): + self._neutral_mass = self._last_neutral_mass + self._most_abundant_member = self._last_most_abundant_member + + @property + def has_msms(self): + if self._has_msms is None: + self._has_msms = [node for node in self.nodes if node.has_msms] + return self._has_msms + + @property + def most_abundant_member(self): + if self._most_abundant_member is None: + self._most_abundant_member = max(node.max_intensity() for node in self.nodes) + return self._most_abundant_member + + def _infer_mass_shifts(self): + mass_shifts = set() + for node in self.nodes: + mass_shifts.update(node.node_types()) + if not mass_shifts: + mass_shifts = [Unmodified] + self._mass_shifts = list(mass_shifts) + + def __getitem__(self, i): + return self.nodes[i] + + def __iter__(self): + return iter(self.nodes) + + def total_signal_for(self, node_type=Unmodified): + total = 0. + for node in self.nodes: + node = node._find(node_type) + if node is not None: + total += node._total_intensity_members() + return total + + def mass_shift_signal_fractions(self): + return ArithmeticMapping({ + k: self.total_signal_for(k) for k in self.mass_shifts + }) + + def drop_mass_shifts(self): + for node in self.nodes.unspool(): + node.node_type = Unmodified + return self + + @property + def integrated_abundance(self): + spacing = np.array([ + node.retention_time for node in self.nodes + ]) + values = np.array([ + node.total_intensity() for node in self.nodes + ]) + integrated = trapezoid(values, spacing) + return integrated + + @property + def mass_shifts(self): + if self._mass_shifts is None: + self._infer_mass_shifts() + return self._mass_shifts + + @property + def total_signal(self): + if self._total_intensity is None: + total = 0. + for node in self.nodes: + total += node.total_intensity() + self._total_intensity = total + return self._total_intensity + + @property + def weighted_neutral_mass(self): + if self._weighted_neutral_mass is None: + try: + self._infer_neutral_mass() + except KeyError: + self._infer_neutral_mass(self.mass_shifts[0]) + return self._weighted_neutral_mass + + @property + def theoretical_mass(self): + if self.composition: + return self.composition.total_composition().mass + else: + return self.weighted_neutral_mass + + def _infer_neutral_mass(self, node_type=Unmodified): + prod = 0 + total = 0 + maximum_intensity = 0 + best_neutral_mass = 0 + for node in self.nodes: + intensity = node.max_intensity() + try: + mass = node.neutral_mass_of_type(node_type) + except KeyError: + continue + prod += intensity * mass + total += intensity + if intensity > maximum_intensity: + maximum_intensity = intensity + best_neutral_mass = mass + if total > 0: + self._weighted_neutral_mass = prod / total - node_type.mass + else: + self._weighted_neutral_mass = best_neutral_mass - node_type.mass + self._last_neutral_mass = self._neutral_mass = best_neutral_mass - node_type.mass + if self._neutral_mass == 0: + raise KeyError(node_type) + return best_neutral_mass + + def mzs(self): + return self._average_mz_included() + + def _average_mz_included(self): + peaks = defaultdict(list) + for node in self.nodes.unspool(): + for member in node.members: + peaks[node.node_type, member.charge].append(member) + mzs = dict() + for key, value in peaks.items(): + product = 0 + weight = 0 + for v in value: + product += v.mz * v.intensity + weight += v.intensity + mzs[key] = product / weight + return tuple(mzs.values()) + + @property + def neutral_mass(self): + if self._neutral_mass is None: + try: + self._infer_neutral_mass() + except KeyError: + self._infer_neutral_mass(self.mass_shifts[0]) + return self._neutral_mass + + @property + def charge_states(self): + if self._charge_states is None: + states = Counter() + for node in self.nodes: + states += (Counter(node.charge_states())) + # Require more than `MIN_POINTS_FOR_CHARGE_STATE` data points to accept any + # charge state + collapsed_states = {k for k, v in states.items() if v >= min(MIN_POINTS_FOR_CHARGE_STATE, len(self))} + if not collapsed_states: + collapsed_states = states.keys() + self._charge_states = collapsed_states + return self._charge_states + + @property + def n_charge_states(self): + return len(self.charge_states) + + @property + def key(self): + if self.composition is not None: + return self.composition + else: + return self.neutral_mass + + @property + def retention_times(self): + if self._retention_times is None: + self._retention_times = tuple(node.retention_time for node in self.nodes) + return self._retention_times + + @property + def scan_ids(self): + if self._scan_ids is None: + self._scan_ids = tuple(node.scan_id for node in self.nodes) + return self._scan_ids + + @property + def peaks(self): + if self._peaks is None: + self._peaks = tuple(node.peaks for node in self.nodes) + return self._peaks + + @property + def start_time(self): + if self._start_time is None: + self._start_time = self.nodes[0].retention_time + return self._start_time + + @property + def end_time(self): + if self._end_time is None: + self._end_time = self.nodes[-1].retention_time + return self._end_time + + def as_arrays(self): + rts = np.array([node.retention_time for node in self.nodes], dtype=np.float64) + signal = np.array([node.total_intensity() for node in self.nodes], dtype=np.float64) + return rts, signal + + def __len__(self): + return len(self.nodes) + + def __repr__(self): + return ""Chromatogram(%s, %0.4f)"" % (self.composition, self.weighted_neutral_mass) + + def split_sparse(self, delta_rt: float=1.) -> List['Chromatogram']: + chunks = [] + current_chunk = [] + last_rt = self.nodes[0].retention_time + + for node in self.nodes: + if (node.retention_time - last_rt) > delta_rt: + x = self.__class__(self.composition, ChromatogramTreeList(current_chunk)) + x.used_as_mass_shift = list(self.used_as_mass_shift) + + chunks.append(x) + current_chunk = [] + + last_rt = node.retention_time + current_chunk.append(node) + + x = self.__class__(self.composition, ChromatogramTreeList(current_chunk)) + x.used_as_mass_shift = list(self.used_as_mass_shift) + + chunks.append(x) + for chunk in chunks: + chunk.created_at = self.created_at + + # Sanity check previously done here + # for member in chunks: + # for other in chunks: + # if member == other: + # continue + # assert not member.overlaps_in_time(other) + + return chunks + + def truncate_before(self, time: float): + _, i = self.nodes.find_time(time) + if self.nodes[i].retention_time < time: + i += 1 + self.nodes = ChromatogramTreeList(self.nodes[i:]) + self._invalidate() + + def truncate_after(self, time: float): + _, i = self.nodes.find_time(time) + if self.nodes[i].retention_time < time: + i += 1 + self.nodes = ChromatogramTreeList(self.nodes[:i]) + self._invalidate() + + def clone(self, cls=None): + if cls is None: + cls = self.__class__ + c = cls( + self.composition, self.nodes.clone(), list(self.mass_shifts), list(self.used_as_mass_shift)) + c.created_at = self.created_at + return c + + def insert_node(self, node: 'ChromatogramTreeNode'): + self.nodes.insert_node(node) + self._invalidate() + + def insert(self, scan_id: str, peak: DeconvolutedPeak, retention_time: float): + self.nodes.insert(retention_time, scan_id, [peak]) + self._invalidate() + + def merge(self, other: 'Chromatogram', node_type=Unmodified, skip_duplicate_nodes=False): + if skip_duplicate_nodes: + return self._merge_missing_only(other, node_type=node_type) + new = self.clone() + for node in other.nodes.unspool_strip_children(): + node = node.clone() + node.node_type = node.node_type + node_type + new.insert_node(node) + new.created_at = ""merge"" + return new + + def deduct_node_type(self, node_type: MassShiftBase): + new = self.clone() + for node in new.nodes.unspool(): + if node.node_type == node_type: + node.node_type = Unmodified + else: + node.node_type = node.node_type - node_type + new.invalidate() + return new + + def _merge_missing_only(self, other: 'Chromatogram', node_type: MassShiftBase=Unmodified): + new = self.clone() + ids = set(node.node_id for node in new.nodes.unspool()) + for node in other.nodes.unspool_strip_children(): + if node.node_id in ids: + continue + else: + new_node = node.clone() + new_node.node_type = node.node_type + node_type + new.insert_node(new_node) + new.created_at = ""_merge_missing_only"" + return new + + @classmethod + def from_parts(cls, composition, retention_times, scan_ids, peaks): + nodes = ChromatogramTreeList() + nodes.extend(zip(scan_ids, peaks, retention_times)) + return cls(composition, nodes) + + def slice(self, start: float, end: float): + """""" + Slice the chromatogram along the time dimension. + + Parameters + ---------- + start : float + The time to start from + end : float + The time to end at + + Returns + ------- + Chromatogram + """""" + _, i = self.nodes.find_time(start) + _, j = self.nodes.find_time(end) + new = self.__class__( + self.composition, + ChromatogramTreeList(node.clone() for node in self.nodes[i:j + 1]), + used_as_mass_shift=list(self.used_as_mass_shift)) + return new + + def bisect_mass_shift(self, mass_shift: MassShiftBase): + """""" + Split a chromatogram into two parts, one with the provided mass shift + and one without. + + This method does not try to deal with composite mass shifts, see :meth:`deducte_node_type` + for that behavior. + + Parameters + ---------- + mass_shift : MassShift + The mass shift to split on + + Returns + ------- + new_with_mass_shift : Chromatogram + The portion of the chromatogram that has the mass shift + new_no_mass_shift : Chromatogram + The portion of the chromatogram that did not have the mass shift + + See Also + -------- + :meth:`deduct_node_type` + """""" + new_mass_shift = self.__class__(self.composition) + new_no_mass_shift = self.__class__(self.composition) + for node in self: + for new_node in node._unspool_strip_children(): + if new_node.node_type == mass_shift: + new_mass_shift.insert_node(new_node) + else: + new_no_mass_shift.insert_node(new_node) + return new_mass_shift, new_no_mass_shift + + def bisect_charge(self, charge: int): + new_charge = self.__class__(self.composition) + new_no_charge = self.__class__(self.composition) + for node in self.nodes.unspool(): + node_t = node.node_type + rt = node.retention_time + scan_id = node.scan_id + peaks = node.members + charge_peaks = [] + no_charge_peaks = [] + for peak in peaks: + if peak.charge == charge: + charge_peaks.append(peak) + else: + no_charge_peaks.append(peak) + if len(charge_peaks): + charge_node = ChromatogramTreeNode( + retention_time=rt, scan_id=scan_id, children=None, + members=charge_peaks, node_type=node_t) + new_charge.insert_node(charge_node) + if len(no_charge_peaks): + no_charge_node = ChromatogramTreeNode( + retention_time=rt, scan_id=scan_id, children=None, + members=no_charge_peaks, node_type=node_t) + new_no_charge.insert_node(no_charge_node) + return new_charge, new_no_charge + + def __eq__(self, other): + if other is None: + return False + if self.key != other.key: + return False + else: + return self.peaks == other.peaks + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash((self.neutral_mass, self.start_time, self.end_time)) + + @property + def elemental_composition(self): + return None + + def common_nodes(self, other: 'Chromatogram'): + return self.nodes.common_nodes(other.nodes) + + @property + def apex_time(self): + rt, intensity = self.as_arrays() + return rt[np.argmax(intensity)] + + def extract_components(self): + mass_shifts = list(self.mass_shifts) + labels = {} + rest = self + for mass_shift in mass_shifts: + with_mass_shift, rest = rest.bisect_mass_shift(mass_shift) + labels[mass_shift] = with_mass_shift + + labels[Unmodified] = rest + mass_shift_charge_table = defaultdict(dict) + for mass_shift, component in labels.items(): + charges = list(component.charge_states) + rest = component + for charge in charges: + selected, rest = rest.bisect_charge(charge) + mass_shift_charge_table[mass_shift][charge] = selected + return mass_shift_charge_table + + def clear(self): + self.nodes.clear() + self._invalidate() + + def is_distinct(self, other: 'Chromatogram'): + return not self.nodes.common_peaks(get_chromatogram(other).nodes) + + def integrate(self): + time, intensity = self.as_arrays() + return trapezoid(intensity, time) + + +class ChromatogramTreeList(object): + roots: List['ChromatogramTreeNode'] + + def __init__(self, roots=None): + if roots is None: + roots = [] + self.roots = list(roots) + self._node_id_hash = None + self._peak_hash = None + + def _invalidate(self): + self._node_id_hash = None + self._peak_hash = None + + def find_time(self, retention_time: float): + if len(self.roots) == 0: + raise EmptyListException() + lo = 0 + hi = len(self.roots) + while lo != hi: + i = (lo + hi) // 2 + node = self.roots[i] + if node.retention_time == retention_time: + return node, i + elif (hi - lo) == 1: + return None, i + elif node.retention_time < retention_time: + lo = i + elif node.retention_time > retention_time: + hi = i + + def _build_node_id_hash(self): + node_id_hash = set() + for node in self.unspool(): + node_id_hash.add(node.node_id) + self._node_id_hash = frozenset(node_id_hash) + + def _build_peak_hash(self): + peak_hash = set() + for node in self.unspool(): + peak_hash.update([(node.scan_id, peak) for peak in node.members]) + self._peak_hash = frozenset(peak_hash) + + @property + def node_id_hash(self): + if self._node_id_hash is None: + self._build_node_id_hash() + return self._node_id_hash + + @property + def peak_hash(self): + if self._peak_hash is None: + self._build_peak_hash() + return self._peak_hash + + def insert_node(self, node: 'ChromatogramTreeNode'): + self._invalidate() + try: + root, i = self.find_time(node.retention_time) + if root is None: + if i != 0: + self.roots.insert(i + 1, node) + else: + slot = self.roots[i] + if slot.retention_time < node.retention_time: + i += 1 + self.roots.insert(i, node) + else: + root.add(node) + return i + except EmptyListException: + self.roots.append(node) + return 0 + + def insert(self, retention_time, scan_id, peaks, node_type=Unmodified): + node = ChromatogramTreeNode(retention_time, scan_id, [], peaks, node_type) + return self.insert_node(node) + + def extend(self, iterable: Iterable['ChromatogramTreeNode']): + for scan_id, peaks, retention_time in iterable: + self.insert(retention_time, scan_id, peaks) + + def __getitem__(self, i) -> 'ChromatogramTreeNode': + return self.roots[i] + + def __len__(self): + return len(self.roots) + + def __iter__(self): + return iter(self.roots) + + def __eq__(self, other): + return list(self) == list(other) + + def __ne__(self, other): + return not (self == other) + + def clone(self): + return ChromatogramTreeList(node.clone() for node in self) + + def clear(self): + self.roots = [] + self._invalidate() + + def unspool(self): + out_queue = [] + for root in self: + stack = [root] + while len(stack) != 0: + node = stack.pop() + out_queue.append(node) + stack.extend(node.children) + return out_queue + + def unspool_strip_children(self) -> List['ChromatogramTreeNode']: + out_queue = [] + for root in self: + stack = [root] + while len(stack) != 0: + node = stack.pop() + node_copy = node.clone() + node_copy.children = [] + out_queue.append(node_copy) + stack.extend(node.children) + return out_queue + + def common_nodes(self, other): + return not self.node_id_hash.isdisjoint(other.node_id_hash) + + def common_peaks(self, other): + return not self.peak_hash.isdisjoint(other.peak_hash) + + def __repr__(self): + return ""ChromatogramTreeList(%d nodes, %0.2f-%0.2f)"" % ( + len(self), self[0].retention_time, self[-1].retention_time) + + +class ChromatogramTreeNode(object): + __slots__ = ['retention_time', 'scan_id', 'children', 'members', 'node_type', + '_most_abundant_member', '_neutral_mass', '_charge_states', '_has_msms', + 'node_id', ] + + retention_time: float + scan_id: str + children: List['ChromatogramTreeNode'] + members: List[DeconvolutedPeak] + node_type: MassShiftBase + node_id: int + + _most_abundant_member: Optional[DeconvolutedPeak] + _neutral_mass: float + _charge_states: Set[int] + _has_msms: Optional[bool] + + def __init__(self, retention_time=None, scan_id=None, children=None, members=None, + node_type=Unmodified): + if children is None: + children = [] + if members is None: + members = [] + self.retention_time = retention_time + self.scan_id = scan_id + self.children = children + self.members = members + self.node_type = node_type + self._most_abundant_member = None + self._neutral_mass = 0 + self._charge_states = set() + self._recalculate() + self._has_msms = None + self.node_id = uid() + + def as_ref(self): + return { + ""scan_id"": self.scan_id, + ""node_id"": self.node_id, + ""peak_indices"": [p.index.neutral_mass for p in self.members], + ""node_type"": self.node_type.name, + ""children"": [ + node._as_ref() for node in self.children + ] + } + + @classmethod + def from_ref(cls, ref: dict, scan_reader: ProcessedRandomAccessScanSource): + scan = scan_reader.get_scan_by_id(ref['scan_id']) + rt = scan.scan_time + members = [scan.deconvoluted_peak_set[i] for i in ref['peak_indices']] + node_type = MassShiftBase.get(ref['node_type']) + children = [cls.from_ref(child) for child in ref['children']] + node = cls(rt, ref['scan_id'], children, members, node_type) + node.node_id = ref['node_id'] + return node + + def clone(self): + node = ChromatogramTreeNode( + self.retention_time, self.scan_id, [c.clone() for c in self.children], + list(self.members), node_type=self.node_type) + node.node_id = self.node_id + return node + + def __reduce__(self): + return self.__class__, ( + self.retention_time, self.scan_id, [c for c in self.children], + list(self.members), self.node_type), self.__getstate__() + + def __getstate__(self): + return { + ""node_id"": self.node_id + } + + def __setstate__(self, state): + self.node_id = state['node_id'] + + def _unspool_strip_children(self): + node = ChromatogramTreeNode( + self.retention_time, self.scan_id, [], list(self.members), node_type=self.node_type) + yield node + for child in self.children: + for node in child._unspool_strip_children(): + yield node + + def _calculate_most_abundant_member(self): + if len(self.members) == 1: + self._most_abundant_member = self.members[0] + else: + if len(self.members) == 0: + self._most_abundant_member = None + else: + self._most_abundant_member = max(self.members, key=intensity_getter) + + def _recalculate(self): + self._calculate_most_abundant_member() + self._neutral_mass = self._most_abundant_member.neutral_mass + self._charge_states = None + self._has_msms = None + + @property + def _contained_charge_states(self): + if self._charge_states is None: + self._charge_states = set(split_by_charge(self.members)) + return self._charge_states + + @property + def has_msms(self): + if self._has_msms is None: + self._has_msms = self._has_any_peaks_with_msms() + return self._has_msms + + def _find(self, node_type=Unmodified): + if self.node_type == node_type: + return self + else: + for child in self.children: + match = child._find(node_type) + if match is not None: + return match + + def find(self, node_type=Unmodified): + match = self._find(node_type) + if match is not None: + return match + else: + raise KeyError(node_type) + + @property + def neutral_mass(self): + if self._neutral_mass is None: + if self._most_abundant_member is not None: + self._neutral_mass = self._most_abundant_member.neutral_mass + return self._neutral_mass + + def charge_states(self): + u = set() + u.update(self._contained_charge_states) + for child in self.children: + u.update(child.charge_states()) + return u + + def neutral_mass_of_type(self, node_type=Unmodified): + return self.find(node_type)._neutral_mass + + def add(self, node, recalculate=True): + if self.node_id == node.node_id: + raise DuplicateNodeError(""Duplicate Node %s"" % node) + if node.node_type == self.node_type: + self.members.extend(node.members) + else: + self.children.append(node) + if recalculate: + self._recalculate() + + def _total_intensity_members(self): + total = 0. + for peak in self.members: + total += peak.intensity + return total + + def _total_intensity_children(self): + total = 0. + for child in self.children: + total += child.total_intensity() + return total + + def max_intensity(self): + return self._most_abundant_member.intensity + + def total_intensity(self): + return self._total_intensity_children() + self._total_intensity_members() + + def __eq__(self, other): + if self.scan_id != other.scan_id: + return False + return self.members == other.members + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return hash(self.node_id) + + def _has_any_peaks_with_msms(self): + for peak in self.members: + if peak.chosen_for_msms: + return True + for child in self.children: + if child._has_any_peaks_with_msms(): + return True + return False + + @property + def peaks(self): + peaks = list(self.members) + for child in self.children: + peaks.extend(child.peaks) + return peaks + + def __repr__(self): + return ""ChromatogramTreeNode(%f, %r, %s|%d, %d)"" % ( + self.retention_time, self.scan_id, self.node_type.name, + len(self.members), len(self.children)) + + def node_types(self): + kinds = [self.node_type] + for child in self.children: + kinds.extend(child.node_types()) + return kinds + + +@add_metaclass(ABCMeta) +class ChromatogramInterface(object): + pass + + +ChromatogramInterface.register(Chromatogram) + + +class ChromatogramWrapper(_TimeIntervalMethods): + def __init__(self, chromatogram): + self.chromatogram = chromatogram + + def __iter__(self): + return iter(self.chromatogram) + + def __getitem__(self, i): + return self.chromatogram[i] + + def __len__(self): + return len(self.chromatogram) + + def __hash__(self): + return hash(self.chromatogram) + + def __eq__(self, other): + try: + return self.chromatogram == get_chromatogram(other) + except Exception: + return False + + def has_chromatogram(self): + return self.chromatogram is not None + + @property + def nodes(self): + return self.chromatogram.nodes + + @property + def neutral_mass(self): + return self.chromatogram.neutral_mass + + @property + def weighted_neutral_mass(self): + return self.chromatogram.weighted_neutral_mass + + @property + def theoretical_mass(self): + return self.chromatogram.theoretical_mass + + @property + def n_charge_states(self): + return self.chromatogram.n_charge_states + + @property + def charge_states(self): + return self.chromatogram.charge_states + + @property + def mass_shifts(self): + return self.chromatogram.mass_shifts + + @property + def total_signal(self): + return self.chromatogram.total_signal + + @property + def integrated_abundance(self): + return self.chromatogram.integrated_abundance + + @property + def start_time(self): + return self.chromatogram.start_time + + @property + def end_time(self): + return self.chromatogram.end_time + + def as_arrays(self): + return self.chromatogram.as_arrays() + + def overlaps_in_time(self, interval): + return self.chromatogram.overlaps_in_time(interval) + + @property + def key(self): + return self.chromatogram.key + + @property + def composition(self): + return self.chromatogram.composition + + @property + def peaks(self): + return self.chromatogram.peaks + + @property + def scan_ids(self): + return self.chromatogram.scan_ids + + @property + def retention_times(self): + return self.chromatogram.retention_times + + def __repr__(self): + return ""{self.__class__.__name__}({self.key}, {self.neutral_mass})"".format(self=self) + + @property + def entity(self): + return self.chromatogram.entity + + @entity.setter + def entity(self, value): + self.chromatogram.entity = value + + @property + def glycan_composition(self): + return self.chromatogram.glycan_composition + + @property + def elemental_composition(self): + return self.chromatogram.elemental_composition + + def common_nodes(self, other): + return self.chromatogram.common_nodes(other) + + @property + def apex_time(self): + return self.chromatogram.apex_time + + def __getattr__(self, name): + if name == 'chromatogram': + raise AttributeError(name) + else: + return getattr(self.chromatogram, name) + + def clone(self): + chromatogram = self.chromatogram.clone() + new = self.__class__(chromatogram) + return new + + def clear(self): + self.chromatogram.clear() + + def mzs(self): + return self.chromatogram.mzs() + + def is_distinct(self, other): + return self.chromatogram.is_distinct(get_chromatogram(other)) + + def mass_shift_signal_fractions(self): + return self.chromatogram.mass_shift_signal_fractions() + + def drop_mass_shifts(self): + self.chromatogram.drop_mass_shifts() + return self + + def integrate(self): + return self.chromatogram.integrate() + + +ChromatogramInterface.register(ChromatogramWrapper) + + +class CachedGlycanComposition(HashableGlycanComposition): + _hash = None + + def __hash__(self): + if self._hash is None: + self._hash = hash(str(self)) + return self._hash + + +class EntityChromatogram(Chromatogram): + _entity = None + + @property + def glycan_composition(self): + return self._entity + + def clone(self, cls=None): + if cls is None: + cls = self.__class__ + inst = super(EntityChromatogram, self).clone(cls=cls) + inst.entity = self.entity + return inst + + @property + def entity(self): + if self._entity is None and self.composition is not None: + self.entity = self.composition + return self._entity + + @entity.setter + def entity(self, value): + if isinstance(value, str): + value = self._parse(value) + self._entity = value + if self.composition is None and value is not None: + self.composition = value + + @property + def structure(self): + return self.entity + + @structure.setter + def structure(self, value): + self.entity = value + + @property + def elemental_composition(self): + try: + return self.entity.total_composition() + except AttributeError: + try: + return self._parse(self.composition).total_composition() + except Exception: + return None + + +class GlycanCompositionChromatogram(EntityChromatogram): + @staticmethod + def _parse(string): + return CachedGlycanComposition.parse(string) + + @property + def glycan_composition(self): + if isinstance(self.composition, str): + self.composition = self._parse(self.composition) + return self.composition + + +class GlycopeptideChromatogram(EntityChromatogram): + @staticmethod + def _parse(string): + from glycopeptidepy.structure.sequence import PeptideSequence + return PeptideSequence(string) + + @property + def glycan_composition(self): + if self.entity is None and self.composition is not None: + self.entity = self.composition + return self.entity.glycan_composition + + +def get_chromatogram(instance): + if isinstance(instance, Chromatogram): + return instance + elif isinstance(instance, ChromatogramInterface): + return instance + elif isinstance(instance, ChromatogramWrapper): + return instance.chromatogram + else: + try: + return instance.get_chromatogram() + except AttributeError: + raise TypeError( + ""%s does not contain a chromatogram"" % instance) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/chromatogram_tree/mass_shift_tree.py",".py","4105","83","from glycresoft.task import TaskBase + +from .chromatogram import (get_chromatogram, mask_subsequence) +from .index import ChromatogramFilter + + +class MassShiftTreePruner(TaskBase): + def __init__(self, solutions, score_margin=2.5, ratio_threshold=1.5, trivial_abundance_delta_ratio=0.01): + self.solutions = solutions + self.score_margin = score_margin + self.ratio_threshold = ratio_threshold + self.trivial_abundance_delta_ratio = trivial_abundance_delta_ratio + + self.key_map = self.solutions._build_key_map() + self.updated = set() + + def check_close_score_abundance_ratio(self, case, owner_item): + component_signal = case.total_signal + complement_signal = owner_item.total_signal - component_signal + signal_ratio = complement_signal / component_signal + # The owner is more abundant than used-as-mass_shift-case + return (signal_ratio < self.ratio_threshold) + + def create_masked_chromatogram(self, owner_item, case): + new_masked = mask_subsequence(get_chromatogram(owner_item), get_chromatogram(case)) + new_masked.created_at = ""prune_bad_mass_shift_branches"" + new_masked.score = owner_item.score + return new_masked + + def handle_chromatogram(self, case): + if case.used_as_mass_shift: + keepers = [] + for owning_key, mass_shift in case.used_as_mass_shift: + owner = self.key_map.get(owning_key) + if owner is None: + continue + owner_item = owner.find_overlap(case) + if owner_item is None: + continue + scores_close = abs(case.score - owner_item.score) < self.score_margin + mass_shifted_case_stronger = case.score > owner_item.score + # If the owning group is lower scoring, but the scores are close + if mass_shifted_case_stronger and scores_close: + mass_shifted_case_stronger = self.check_close_score_abundance_ratio(case, owner_item) + # If the scores are close, but the owning group is less abundant, + # e.g. more mass shift groups or mass accuracy prevents propagation + # of mass shifts + elif scores_close and (owner_item.total_signal / case.total_signal) < 1: + mass_shifted_case_stronger = True + independent = owner_item.total_signal - case.total_signal + if (independent / case.total_signal) < self.trivial_abundance_delta_ratio: + mass_shifted_case_stronger = True + if mass_shifted_case_stronger: + new_masked = self.create_masked_chromatogram(owner_item, case) + if len(new_masked) != 0: + owner.replace(owner_item, new_masked) + self.updated.add(owning_key) + else: + keepers.append((owning_key, mass_shift)) + case.chromatogram.used_as_mass_shift = keepers + + def prune_branches(self): + n = len(self.solutions) + for i, case in enumerate(self.solutions): + if len(case.used_as_mass_shift) > 2 ** 6: + self.log(""Pruning %r with %d mass shift branches"" % (case, len(case.used_as_mass_shift))) + if i % 100 == 0 and i > 0: + self.log(""... %d chromatograms reduced (%0.2f%%)"" % (i, i / float(n) * 100.0)) + self.handle_chromatogram(case) + out = [s.chromatogram for k in (set(self.key_map) - self.updated) for s in self.key_map[k]] + out.extend(s for k in self.updated for s in self.key_map[k]) + out = ChromatogramFilter(out) + return out + + @classmethod + def prune_bad_mass_shift_branches(cls, solutions, score_margin=2.5, ratio_threshold=1.5, + trivial_abundance_delta_ratio=0.01): + inst = cls(solutions, score_margin, ratio_threshold, trivial_abundance_delta_ratio) + return inst.prune_branches() + + +prune_bad_mass_shift_branches = MassShiftTreePruner.prune_bad_mass_shift_branches +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/chromatogram_tree/index.py",".py","10536","329","from collections import defaultdict + +from . import (smooth_overlaps, build_rt_interval_tree) + + +def binary_search_with_flag(array, mass, error_tolerance=1e-5): + """"""Binary search an ordered array of objects with :attr:`neutral_mass` + using a PPM error tolerance of `error_toler + + Parameters + ---------- + array : list + An list of objects, sorted over :attr:`neutral_mass` in increasing order + mass : float + The mass to search for + error_tolerance : float, optional + The PPM error tolerance to use when deciding whether a match has been found + + Returns + ------- + int: + The index in `array` of the best match + bool: + Whether or not a match was actually found, used to + signal behavior to the caller. + """""" + lo = 0 + n = hi = len(array) + while hi != lo: + mid = (hi + lo) // 2 + x = array[mid] + err = (x.neutral_mass - mass) / mass + if abs(err) <= error_tolerance: + best_index = mid + best_error = abs(err) + i = mid - 1 + while i >= 0: + x = array[i] + err = abs((x.neutral_mass - mass) / mass) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i -= 1 + + i = mid + 1 + while i < n: + x = array[i] + err = abs((x.neutral_mass - mass) / mass) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i += 1 + return best_index, True + elif (hi - lo) == 1: + return mid, False + elif err > 0: + hi = mid + elif err < 0: + lo = mid + return 0, False + + +class ChromatogramIndex(object): + """"""An ordered collection of Chromatogram-like objects with fast searching + and features. Supports Sequence operations. + + Attributes + ---------- + chromatograms: list of Chromatogram + list of chromatogram-like objects, ordered by neutral mass + """""" + def __init__(self, chromatograms, sort=True): + if sort: + self._sort(chromatograms) + else: + self.chromatograms = list(chromatograms) + + def _sort(self, iterable): + self.chromatograms = sorted([c for c in iterable if len(c)], key=lambda x: (x.neutral_mass, x.start_time)) + + def add(self, chromatogram, sort=True): + self.chromatograms.append(chromatogram) + if sort: + self._sort(self.chromatograms) + + def __iter__(self): + return iter(self.chromatograms) + + def __getitem__(self, i): + return self.chromatograms[i] + + def __len__(self): + return len(self.chromatograms) + + def find_mass(self, mass, ppm_error_tolerance=1e-5): + index, flag = self._binary_search(mass, ppm_error_tolerance) + if flag: + return self[index] + else: + return None + + def find_all_by_mass(self, mass, ppm_error_tolerance=1e-5): + if len(self) == 0: + return self.__class__([], sort=False) + center_index, _ = self._binary_search(mass, ppm_error_tolerance) + low_index = center_index + while low_index > 0: + x = self[low_index - 1] + if abs((mass - x.neutral_mass) / x.neutral_mass) > ppm_error_tolerance: + break + low_index -= 1 + + n = len(self) + high_index = center_index - 1 + while high_index < n - 1: + x = self[high_index + 1] + if abs((mass - x.neutral_mass) / x.neutral_mass) > ppm_error_tolerance: + break + high_index += 1 + if low_index == high_index == center_index: + x = self[center_index] + if abs((mass - x.neutral_mass) / x.neutral_mass) > ppm_error_tolerance: + return self.__class__([], sort=False) + items = self[low_index:high_index + 1] + items = [ + c for c in items if abs( + (c.neutral_mass - mass) / mass) < ppm_error_tolerance + ] + return self.__class__(items, sort=False) + + def mass_between(self, low, high): + n = len(self) + if n == 0: + return self.__class__([]) + low_index, flag = self._binary_search(low, 1e-5) + low_index = max(0, min(low_index, n - 1)) + if self[low_index].neutral_mass < low: + low_index += 1 + high_index, flag = self._binary_search(high, 1e-5) + high_index += 2 + # high_index = min(n - 1, high_index) + if (high_index < n) and (self[high_index].neutral_mass > high): + high_index -= 1 + items = self[low_index:high_index] + items = [c for c in items if low <= c.neutral_mass <= high] + return self.__class__(items, sort=False) + + def _binary_search(self, mass, error_tolerance=1e-5): + return binary_search_with_flag(self, mass, error_tolerance) + + def __repr__(self): + return repr(list(self)) + + def _repr_pretty_(self, p, cycle): + return p.pretty(list(self)) + + def __str__(self): + return str(list(self)) + + +try: + _ChromatogramIndex = ChromatogramIndex + from glycresoft._c.chromatogram_tree.index import ChromatogramIndex +except ImportError: + pass + + +class ChromatogramFilter(ChromatogramIndex): + """"""An ordered collection of Chromatogram-like objects with fast searching + and filtering features. Supports Sequence operations. + + Attributes + ---------- + chromatograms: list of Chromatogram + list of chromatogram-like objects, ordered by neutral mass + key_map: dict + A mapping between values appearing in the :attr:`Chromatogram.key` and :class:`DisjointChromatogramSet` + instances containing all occurrences of that key, ordered by time. + rt_interval_tree: IntervalTreeNode + An interval tree over retention time containing all of the chromatograms in + :attr:`chromatograms` + """""" + def __init__(self, chromatograms, sort=True): + super(ChromatogramFilter, self).__init__(chromatograms, sort=sort) + self._key_map = None + self._intervals = None + + def _invalidate(self): + self._key_map = None + self._intervals = None + + def _build_key_map(self): + self._key_map = defaultdict(list) + for chrom in self: + self._key_map[chrom.key].append(chrom) + for key in tuple(self._key_map.keys()): + self._key_map[key] = DisjointChromatogramSet(self._key_map[key]) + return self._key_map + + def _build_rt_interval_tree(self): + self._intervals = build_rt_interval_tree(self) + + @property + def key_map(self): + if self._key_map is None: + self._build_key_map() + return self._key_map + + @property + def rt_interval_tree(self): + if self._intervals is None: + self._build_rt_interval_tree() + return self._intervals + + def find_all_instances(self, key): + return self.key_map[key] + + def find_key(self, key): + try: + return self.key_map[key][0] + except (KeyError, IndexError): + return None + + def min_points(self, n=3, keep_if_msms=True): + self.chromatograms = [c for c in self if (len(c) >= n) or c.has_msms] + return self + + def split_sparse(self, delta_rt=1.): + self.chromatograms = [ + seg for c in self + for seg in c.split_sparse(delta_rt) + ] + return self + + def spanning(self, rt): + return self.__class__((c for c in self if c.start_time <= rt <= c.end_time), sort=False) + + def contained_in_interval(self, start, end): + return self.__class__( + (c for c in self if ((c.start_time <= start and c.end_time >= start) or ( + c.start_time >= start and c.end_time <= end) or ( + c.start_time >= start and c.end_time >= end and c.start_time <= end) or ( + c.start_time <= start and c.end_time >= start) or ( + c.start_time <= end and c.end_time >= end))), sort=False) + + def after(self, t): + out = [] + for c in self: + c = c.clone() + c.truncate_before(t) + if len(c) > 0: + out.append(c) + return self.__class__(out, sort=False) + + def before(self, t): + out = [] + for c in self: + c = c.clone() + c.truncate_after(t) + if len(c) > 0: + out.append(c) + return self.__class__(out, sort=False) + + def filter(self, filter_fn): + return self.__class__([x for x in self if filter_fn(x)], sort=False) + + @classmethod + def process(cls, chromatograms, min_points=5, percentile=10, delta_rt=1.): + return cls(chromatograms).split_sparse(delta_rt).min_points(min_points) + + def smooth_overlaps(self, mass_error_tolerance=1e-5): + return self.__class__(smooth_overlaps(self, mass_error_tolerance)) + + def extend(self, other): + chroma = [] + chroma.extend(self) + chroma.extend(other) + self.chromatograms = [c for c in sorted([c for c in chroma if len(c)], key=lambda x: ( + x.neutral_mass, x.start_time))] + self._invalidate() + + def __add__(self, other): + inst = self.__class__([]) + inst.extend(self) + inst.extend(other) + return inst + + +class DisjointChromatogramSet(object): + def __init__(self, chromatograms): + self.group = sorted(chromatograms, key=lambda c: c.start_time) + + def linear_search(self, start_time, end_time): + center_time = (start_time + end_time) / 2. + for chrom in self.group: + if chrom.start_time <= center_time <= chrom.end_time: + return chrom + + def find_overlap(self, chromatogram): + return self.linear_search( + chromatogram.start_time, + chromatogram.end_time) + + def replace(self, original, replacement): + i = self.group.index(original) + self.group[i] = replacement + + def __getitem__(self, i): + return self.group[i] + + def __iter__(self): + return iter(self.group) + + def __repr__(self): + return repr(list(self)) + + def _repr_pretty_(self, p, cycle): + return p.pretty(self.group) + + def __str__(self): + return str(list(self)) + + def __len__(self): + return len(self.group) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/output/annotate_spectra.py",".py","7544","195","import os +import logging +import string +import platform +import csv +from io import TextIOWrapper + +from glycresoft import serialize +from glycresoft.serialize import ( + Protein, Glycopeptide, IdentifiedGlycopeptide, + func, MSScan, GlycopeptideSpectrumMatch) + +from glycresoft.task import TaskBase +from glycresoft.serialize import DatabaseBoundOperation + +from glycresoft.chromatogram_tree import Unmodified +from glycresoft.tandem.ref import SpectrumReference +from glycresoft.tandem.glycopeptide.scoring import CoverageWeightedBinomialModelTree + +from glycresoft.plotting import figure +from glycresoft.plotting.sequence_fragment_logo import glycopeptide_match_logo +from glycresoft.plotting.spectral_annotation import TidySpectrumMatchAnnotator + +from ms_deisotope.output import ProcessedMSFileLoader + +from matplotlib import pyplot as plt, style +from matplotlib import rcParams as mpl_params + + +status_logger = logging.getLogger(""glycresoft.status"") + + +def format_filename(s): + """"""Take a string and return a valid filename constructed from the string. + Uses a whitelist approach: any characters not present in valid_chars are + removed. Also spaces are replaced with underscores. + """""" + valid_chars = ""-_.() %s%s"" % (string.ascii_letters, string.digits) + filename = ''.join(c for c in s if c in valid_chars) + filename = filename.replace(' ', '_') + return filename + + +class SpectrumAnnotatorExport(TaskBase, DatabaseBoundOperation): + def __init__(self, database_connection, analysis_id, output_path, mzml_path=None): + DatabaseBoundOperation.__init__(self, database_connection) + self.analysis_id = analysis_id + self.mzml_path = mzml_path + self.output_path = output_path + self.analysis = self.session.query(serialize.Analysis).get(self.analysis_id) + self.scan_loader = None + self._mpl_style = { + 'figure.facecolor': 'white', + 'figure.edgecolor': 'white', + 'font.size': 10, + 'savefig.dpi': 72, + 'figure.subplot.bottom': .125 + } + + def _make_scan_loader(self): + if self.mzml_path is not None: + if not os.path.exists(self.mzml_path): + raise IOError(""No such file {}"".format(self.mzml_path)) + self.scan_loader = ProcessedMSFileLoader(self.mzml_path) + else: + self.mzml_path = self.analysis.parameters['sample_path'] + if not os.path.exists(self.mzml_path): + raise IOError(( + ""No such file {}. If {} was relocated, you may need to explicily pass the"" + "" corrected file path."").format( + self.mzml_path, + self.database_connection._original_connection)) + self.scan_loader = ProcessedMSFileLoader(self.mzml_path) + return self.scan_loader + + def _load_spectrum_matches(self): + query = self.query(GlycopeptideSpectrumMatch).join( + GlycopeptideSpectrumMatch.scan).filter( + GlycopeptideSpectrumMatch.analysis_id == self.analysis_id).order_by( + MSScan.index) + return query.all() + + def run(self): + scan_loader = self._make_scan_loader() + gpsms = self._load_spectrum_matches() + if not os.path.exists(self.output_path): + os.makedirs(self.output_path) + n = len(gpsms) + self.log(""%d Spectrum Matches"" % (n,)) + for i, gpsm in enumerate(gpsms): + scan = scan_loader.get_scan_by_id(gpsm.scan.scan_id) + gpep = gpsm.structure.convert() + if i % 10 == 0: + self.log(""... %0.2f%%: %s @ %s"" % (((i + 1) / float(n) * 100.0), gpep, scan.id)) + with style.context(self._mpl_style): + fig = figure() + grid = plt.GridSpec(nrows=5, ncols=1) + ax1 = fig.add_subplot(grid[1, 0]) + ax2 = fig.add_subplot(grid[2:, 0]) + ax3 = fig.add_subplot(grid[0, 0]) + match = CoverageWeightedBinomialModelTree.evaluate(scan, gpep) + ax3.text(0, 0.5, ( + str(match.target) + '\n' + scan.id + + '\nscore=%0.3f q value=%0.3g' % (gpsm.score, gpsm.q_value)), va='center') + ax3.axis('off') + match.plot(ax=ax2) + glycopeptide_match_logo(match, ax=ax1) + fname = format_filename(""%s_%s.pdf"" % (scan.id, gpep)) + path = os.path.join(self.output_path, fname) + abspath = os.path.abspath(path) + if len(abspath) > 259 and platform.system().lower() == 'windows': + abspath = '\\\\?\\' + abspath + fig.savefig(abspath, bbox_inches='tight') + plt.close(fig) + + +class CSVSpectrumAnnotatorExport(SpectrumAnnotatorExport): + def __init__(self, database_connection, analysis_id, outstream, mzml_path=None, fdr_threshold=0.05): + super(CSVSpectrumAnnotatorExport, self).__init__( + database_connection, analysis_id, None, mzml_path) + self.outstream = outstream + try: + self.is_binary = 'b' in self.outstream.mode + except AttributeError: + self.is_binary = True + if self.is_binary: + try: + self.outstream = TextIOWrapper(outstream, 'utf8', newline="""") + except AttributeError: + # must be Py2 + pass + self.fdr_threshold = fdr_threshold + self.writer = csv.writer(self.outstream, delimiter=',') + + def get_header(self): + return [ + ""glycopeptide"", + ""scan_id"", + ""fragment_name"", + ""peak_mass"", + ""peak_charge"", + ""peak_intensity"", + ""mass_accuracy_ppm"", + ] + + def _load_spectrum_matches(self): + query = self.query(GlycopeptideSpectrumMatch).join( + GlycopeptideSpectrumMatch.scan).filter( + GlycopeptideSpectrumMatch.analysis_id == self.analysis_id, + GlycopeptideSpectrumMatch.is_best_match, + GlycopeptideSpectrumMatch.q_value <= self.fdr_threshold).order_by( + GlycopeptideSpectrumMatch.score.desc(), MSScan.index) + return query.all() + + def convert_object(self, obj): + records = [] + for pfp in sorted(obj.solution_map, key=lambda x: x.fragment.mass): + peak, fragment = pfp + rec = [ + str(obj.target), + str(obj.scan.scan_id), + fragment.name, + peak.neutral_mass, + peak.charge, + peak.intensity, + pfp.mass_accuracy() * 1e6 + ] + records.append(rec) + return records + + def status_update(self, message): + status_logger.info(message) + + def writerows(self, iterable): + self.writer.writerows(iterable) + + def writerow(self, row): + self.writer.writerow(row) + + def run(self): + header = self.get_header() + self.writerow(header) + + scan_loader = self._make_scan_loader() + gpsms = self._load_spectrum_matches() + + n = len(gpsms) + for i, gpsm in enumerate(gpsms): + scan = scan_loader.get_scan_by_id(gpsm.scan.scan_id) + gpep = gpsm.structure.convert() + match = CoverageWeightedBinomialModelTree.evaluate(scan, gpep) + self.writerows(self.convert_object(match)) + if i % 100 == 0 and i: + self.status_update(""%d Spectrum Matches Handled (%0.2f%%)"" % (i, i * 100.0 / n)) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/output/__init__.py",".py","781","25","from .csv_format import ( + CSVSerializerBase, + GlycanHypothesisCSVSerializer, + ImportableGlycanHypothesisCSVSerializer, + GlycopeptideHypothesisCSVSerializer, + GlycanLCMSAnalysisCSVSerializer, + GlycopeptideLCMSMSAnalysisCSVSerializer, + GlycopeptideSpectrumMatchAnalysisCSVSerializer, + SimpleChromatogramCSVSerializer, + SimpleScoredChromatogramCSVSerializer, + MultiScoreGlycopeptideLCMSMSAnalysisCSVSerializer, + MultiScoreGlycopeptideSpectrumMatchAnalysisCSVSerializer) + +from .xml import ( + MzIdentMLSerializer) + +from .report import ( + GlycanChromatogramReportCreator, + GlycopeptideDatabaseSearchReportCreator) + +from .annotate_spectra import SpectrumAnnotatorExport, CSVSpectrumAnnotatorExport + + +from .text_format import TrainingMGFExporter +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/output/xml.py",".py","36236","945","import io +import os +import re +import bisect + +from collections import defaultdict, OrderedDict, namedtuple, deque +from typing import Any, Set, List, Union, Dict, Optional + +from brainpy import mass_charge_ratio + +from glypy.composition import formula +from glypy.io.nomenclature import identity +from glypy.structure.glycan_composition import ( + MonosaccharideResidue, + FrozenMonosaccharideResidue, SubstituentResidue, FrozenGlycanComposition) + +from glycopeptidepy.structure import parser, modification, PeptideSequence + +from psims.mzid import components +from psims.mzid.writer import MzIdentMLWriter +from psims.controlled_vocabulary.controlled_vocabulary import load_gno + +from ms_deisotope.output import mzml, ProcessedMSFileLoader + +from glycresoft import task, serialize, version +from glycresoft.chromatogram_tree import Unmodified +from glycresoft.chromatogram_tree.chromatogram import group_by +from glycresoft.structure import FragmentCachingGlycopeptide + + +GlycopeptideType = Union[PeptideSequence, FragmentCachingGlycopeptide, serialize.Glycopeptide] +Props = Dict[str, Any] + + +class mass_term_pair(namedtuple(""mass_term_pair"", ('mass', 'term'))): + def __lt__(self, other): + return self.mass < float(other) + + def __gt__(self, other): + return self.mass > float(other) + + def __float__(self): + return self.mass + + +valid_monosaccharide_names = [ + ""Hex"", + ""HexNAc"", + ""dHex"", + ""NeuAc"", + ""NeuGc"", + ""Pen"", + ""Fuc"", + # ""HexA"", + # ""HexN"", +] + +valid_monosaccharides = {FrozenMonosaccharideResidue.from_iupac_lite(v): v + for v in valid_monosaccharide_names} + + +def monosaccharide_to_term(monosaccharide): + try: + return valid_monosaccharides[monosaccharide] + except KeyError: + value = str(monosaccharide) + return value + + +substituent_map = { + ""S"": ""sulfate"", + ""P"": ""phosphate"", + # ""Me"": ""methyl"", + # ""Ac"": ""acetyl"", +} + +inverted_substituent_map = { + v: k for k, v in substituent_map.items() +} + +substituent_map['Sulpho'] = ""sulfate"" +substituent_map['Phospho'] = ""phosphate"" + + +def mparam(name, value=None, accession=None, cvRef=""PSI-MS"", **kwargs): + if isinstance(name, dict): + value = name.pop('value', None) + accession = name.pop('accession') + cvRef = name.pop('cvRef', cvRef) + name_ = name.pop(""name"") + kwargs.update(kwargs) + name = name_ + return components.CVParam( + name=name, + value=value, + accession=accession, + cvRef=cvRef, + **kwargs) + + +def parse_glycan_formula(glycan_formula): + gc = FrozenGlycanComposition() + if glycan_formula.startswith(""\""""): + glycan_formula = glycan_formula[1:-1] + for mono, count in re.findall(r""([^0-9]+)\((\d+)\)"", glycan_formula): + count = int(count) + if mono in substituent_map: + parsed = SubstituentResidue(substituent_map[mono]) + elif mono in (""Sia"", ): + continue + elif mono in (""Pent"", ): + mono = ""Pen"" + parsed = FrozenMonosaccharideResidue.from_iupac_lite(mono) + elif mono == 'Xxx': + continue + elif mono == 'X': + continue + else: + parsed = FrozenMonosaccharideResidue.from_iupac_lite(mono) + gc[parsed] += count + return gc + + +class GNOmeResolver(object): + def __init__(self, cv=None): + if cv is None: + cv = load_gno() + self.cv = cv + self.build_mass_search_index() + self.add_glycan_compositions() + + def add_glycan_compositions(self): + formula_key = ""GNO:00000202"" + for term in self.cv.terms.values(): + glycan_formula = term.get(formula_key) + if glycan_formula: + term['glycan_composition'] = parse_glycan_formula(glycan_formula) + + def build_mass_search_index(self): + mass_index = [] + + for term in self.cv.terms.values(): + match = re.search(r""weight of (\d+\.\d+) Da"", term.definition) + if match: + mass = float(match.group(1)) + term['mass'] = mass + mass_index.append(mass_term_pair(mass, term)) + + mass_index.sort() + self.mass_index = mass_index + + def _find_mass_match(self, mass): + i = bisect.bisect_left(self.mass_index, mass) + lo = self.mass_index[i - 1] + lo_err = abs(lo.mass - mass) + hi = self.mass_index[i] + hi_err = abs(hi.mass - mass) + if hi_err < lo_err: + term = hi.term + elif hi_err > lo_err: + term = lo.term + else: + raise ValueError( + ""Ambiguous duplicate masses (%0.2f, %0.2f)"" % (lo.mass, hi.mass)) + return term + + def resolve_gnome(self, glycan_composition): + mass = glycan_composition.mass() + term = self._find_mass_match(mass) + recast = glycan_composition.clone().reinterpret(valid_monosaccharides) + visit_queue = deque(term.children) + while visit_queue: + child = visit_queue.popleft() + gc = child.get(""glycan_composition"") + if gc is None: + visit_queue.extend(child.children) + elif gc == recast: + return child + + def glycan_composition_to_terms(self, glycan_composition): + out = [] + term = self.resolve_gnome(glycan_composition) + if term is not None: + out.append({ + ""accession"": term.id, + ""name"": term.name, + ""cvRef"": term.vocabulary.name + }) + reinterpreted = glycan_composition.clone().reinterpret(valid_monosaccharides) + for mono, count in reinterpreted.items(): + if isinstance(mono, SubstituentResidue): + subst = inverted_substituent_map.get( + mono.name.replace(""@"", """")) + if subst is not None: + out.append({ + ""name"": ""monosaccharide count"", + ""value"": (""%s:%d"" % (subst, count)), + ""accession"": ""MS:XXXXX2"", + ""cvRef"": ""PSI-MS"" + }) + else: + out.append({ + ""name"": ""unknown monosaccharide count"", + ""value"": (""%s:%0.3f:%d"" % (mono.name.replace(""@"", """"), mono.mass(), count)), + ""accession"": ""MS:XXXXX3"", + ""cvRef"": ""PSI-MS"" + }) + elif isinstance(mono, MonosaccharideResidue): + for known in valid_monosaccharides: + if identity.is_a(mono, known): + out.append({ + ""name"": ""monosaccharide count"", + ""value"": (""%s:%d"" % (monosaccharide_to_term(known), count)), + ""accession"": ""MS:XXXXX2"", + ""cvRef"": ""PSI-MS"" + }) + break + else: + out.append({ + ""name"": ""unknown monosaccharide count"", + ""value"": (""%s:%0.3f:%d"" % (monosaccharide_to_term(mono), mono.mass(), count)), + ""accession"": ""MS:XXXXX3"", + ""cvRef"": ""PSI-MS"" + }) + else: + raise TypeError(""Cannot handle unexpected component of type %s"" % (type(mono), )) + return out + + +class SequenceIdTracker(object): + mapping: Dict[str, int] + + def __init__(self): + self.mapping = dict() + + def convert(self, glycopeptide: GlycopeptideType) -> int: + s = str(glycopeptide) + if s in self.mapping: + return self.mapping[s] + else: + self.mapping[s] = glycopeptide.id + return self.mapping[s] + + def __call__(self, glycopeptide: GlycopeptideType) -> int: + return self.convert(glycopeptide) + + def dump(self): + for key, value in self.mapping.items(): + print(value, key) + + +class MzMLExporter(task.TaskBase): + def __init__(self, source, outfile): + self.reader = ProcessedMSFileLoader(source) + self.outfile = outfile + self.writer = None + self.n_spectra = None + + def make_writer(self): + self.writer = mzml.MzMLScanSerializer( + self.outfile, sample_name=self.reader.sample_run.name, + n_spectra=self.n_spectra) + + def aggregate_scan_bunches(self, scan_ids): + scans = defaultdict(list) + for scan_id in scan_ids: + scan = self.reader.get_scan_by_id(scan_id) + scans[scan.precursor_information.precursor_scan_id].append( + scan) + bunches = [] + for precursor_id, products in scans.items(): + products.sort(key=lambda x: x.scan_time) + precursor = self.reader.get_scan_by_id(precursor_id) + bunches.append(mzml.ScanBunch(precursor, products)) + bunches.sort(key=lambda bunch: bunch.precursor.scan_time) + return bunches + + def begin(self, scan_bunches): + self.n_spectra = sum(len(b.products) for b in scan_bunches) + len(scan_bunches) + self.make_writer() + for bunch in scan_bunches: + self.put_scan_bunch(bunch) + + def put_scan_bunch(self, bunch): + self.writer.save_scan_bunch(bunch) + + def extract_chromatograms_from_identified_glycopeptides(self, glycopeptide_list): + by_chromatogram = group_by( + glycopeptide_list, lambda x: ( + x.chromatogram.chromatogram if x.chromatogram is not None else None)) + i = 0 + for chromatogram, members in by_chromatogram.items(): + if chromatogram is None: + continue + self.enqueue_chromatogram(chromatogram, i, params=[ + {""name"": ""GlycReSoft:profile score"", ""value"": members[0].ms1_score}, + {""name"": ""GlycReSoft:assigned entity"", ""value"": str(members[0].structure)} + ]) + i += 1 + + def enqueue_chromatogram(self, chromatogram, chromatogram_id, params=None): + if params is None: + params = [] + chromatogram_data = dict() + rt, signal = chromatogram.as_arrays() + chromatogram_dict = OrderedDict(zip(rt, signal)) + chromatogram_data['chromatogram'] = chromatogram_dict + chromatogram_data['chromatogram_type'] = 'selected ion current chromatogram' + chromatogram_data['id'] = chromatogram_id + chromatogram_data['params'] = params + + self.writer.chromatogram_queue.append(chromatogram_data) + + def complete(self): + self.writer.complete() + self.writer.format() + + +glycosylation_type_to_term_map = { + ""N-Linked"": { + ""name"": ""N-glycan"", + ""accession"": ""MS:XXXXX5"", + ""cvRef"": ""PSI-MS"", + }, + ""O-Linked"": { + ""name"": ""mucin O-glycan"", + ""accession"": ""MS:XXXXX6"", + ""cvRef"": ""PSI-MS"", + }, + ""GAG linker"": { + ""name"": ""glycosaminoglycan"", + ""accession"": ""MS:XXXXX7"", + ""cvRef"": ""PSI-MS"", + }, +} + +glycosylation_type_to_term_map[""N-Glycan""] = glycosylation_type_to_term_map[""N-Linked""] +glycosylation_type_to_term_map[""O-Glycan""] = glycosylation_type_to_term_map[""O-Linked""] + + +def glycosylation_type_to_term(glycosylation_type): + return glycosylation_type_to_term_map[glycosylation_type] + + +class MzIdentMLSerializer(task.TaskBase): + outfile: Union[os.PathLike, io.IOBase] + + analysis: serialize.Analysis + database_handle: serialize.DatabaseBoundOperation + gnome_resolver: GNOmeResolver + + _id_tracker: SequenceIdTracker + _glycopeptide_list: List[serialize.IdentifiedGlycopeptide] + _peptide_evidence: List[Props] + + protein_list: List[serialize.Protein] + glycan_list: List[serialize.GlycanCombination] + + scan_ids: Set[str] + + q_value_threshold: float + ms2_score_threshold: float + + export_mzml: bool + source_mzml_path: Optional[os.PathLike] + output_mzml_path: Optional[os.PathLike] + + embed_protein_sequences: bool + report_top_match_per_glycopeptide: bool + + def __init__(self, outfile: Union[os.PathLike, io.IOBase], + glycopeptide_list: List[serialize.IdentifiedGlycopeptide], + analysis: serialize.Analysis, + database_handle: serialize.DatabaseBoundOperation, + q_value_threshold: float=0.05, + ms2_score_threshold: float=0, + export_mzml: bool=True, + source_mzml_path: Optional[os.PathLike]=None, + output_mzml_path: Optional[os.PathLike]=None, + embed_protein_sequences: bool=True, + report_top_match_per_glycopeptide: bool=True): + + self.outfile = outfile + + self.database_handle = database_handle + self.analysis = analysis + self.gnome_resolver = GNOmeResolver() + + self._glycopeptide_list = glycopeptide_list + self.protein_list = [] + self.glycan_list = [] + self._peptide_evidence = [] + self.scan_ids = set() + self._id_tracker = SequenceIdTracker() + + self.q_value_threshold = q_value_threshold + self.ms2_score_threshold = ms2_score_threshold + + self.export_mzml = export_mzml + self.source_mzml_path = source_mzml_path + self.output_mzml_path = output_mzml_path + + self.report_top_match_per_glycopeptide = report_top_match_per_glycopeptide + self.embed_protein_sequences = embed_protein_sequences + + def _coerce_orm(self, obj): + if isinstance(obj, serialize.Base): + obj = obj.convert() + return obj + + @property + def glycopeptide_list(self): + return self._glycopeptide_list + + def extract_proteins(self): + self.protein_list = self.database_handle.query(serialize.Protein).all() + + def extract_glycans(self): + self.glycan_list = self.database_handle.query(serialize.GlycanCombination).all() + + def convert_to_peptide_dict(self, glycopeptide: GlycopeptideType, id_tracker: SequenceIdTracker) -> Props: + data = { + ""id"": glycopeptide.id, + ""peptide_sequence"": parser.strip_modifications(glycopeptide), + ""modifications"": [] + } + + glycopeptide = self._coerce_orm(glycopeptide) + + i = 0 + # TODO: handle N-terminal and C-terminal modifications + glycosylation_event_count = len(glycopeptide.glycosylation_manager) + glycosylation_events_handled = 0 + for _pos, mods in glycopeptide: + i += 1 + if not mods: + continue + else: + mod = mods[0] + if mod.rule.is_a(""glycosylation""): + glycosylation_events_handled += 1 + is_aggregate_stub = False + mod_params = [ + glycosylation_type_to_term( + str(mod.rule.glycosylation_type)) + ] + if mod.rule.is_core: + + mod_params.extend( + self.gnome_resolver.glycan_composition_to_terms(glycopeptide.glycan_composition.clone())) + + mass = glycopeptide.glycan_composition.mass() + if glycosylation_event_count == 1: + mod_params.append({ + ""name"": ""glycan composition"", + ""cvRef"": ""PSI-MS"", + ""accession"": ""MS:XXXX14"" + }) + else: + mod_params.append({ + ""name"": ""glycan aggregate"", + ""cvRef"": ""PSI-MS"", + ""accession"": ""MS:XXXX15"" + }) + if glycosylation_events_handled > 1: + mass = 0 + is_aggregate_stub = True + + if not is_aggregate_stub: + mod_params.append({ + ""accession"": 'MS:1000864', + ""cvRef"": ""PSI-MS"", + ""name"": ""chemical formula"", + ""value"": formula(glycopeptide.glycan_composition.total_composition()), + }) + + else: + mod_params.append({ + ""accession"": 'MS:1000864', + ""cvRef"": ""PSI-MS"", + ""name"": ""chemical formula"", + ""value"": formula(mod.rule.composition), + }) + if mod.rule.is_composition: + mod_params.extend(self.gnome_resolver.glycan_composition_to_terms(mod.rule.glycan.clone())) + mod_params.append({ + ""name"": ""glycan composition"", + ""cvRef"": ""PSI-MS"", + ""accession"": ""MS:XXXX14"" + }) + else: + mod_params.append({ + ""name"": ""glycan structure"", + ""cvRef"": ""PSI-MS"", + ""accession"": ""MS:XXXXXXX"" + }) + mass = mod.mass + + mod_dict = { + ""monoisotopic_mass_delta"": mass, + ""location"": i, + # ""name"": ""unknown modification"", + ""name"": ""glycosylation modification"", + ""params"": [components.CVParam(**x) for x in mod_params] + } + data['modifications'].append(mod_dict) + else: + mod_dict = { + ""monoisotopic_mass_delta"": mod.mass, + ""location"": i, + ""name"": mod.name, + } + data['modifications'].append(mod_dict) + return data + + def _encode_score_set(self, spectrum_match: serialize.GlycopeptideSpectrumMatch) -> List[Union[Props, components.CVParam]]: + score_params = [ + mparam(""GlycReSoft:peptide score"", + spectrum_match.score_set.peptide_score, ""MS:XXX10C""), + mparam(""GlycReSoft:glycan score"", + spectrum_match.score_set.glycan_score, ""MS:XXX10B""), + mparam(""GlycReSoft:glycan coverage"", + spectrum_match.score_set.glycan_coverage, ""MS:XXX10H""), + mparam(""GlycReSoft:joint q-value"", + spectrum_match.q_value, ""MS:XXX10G""), + mparam(""GlycReSoft:peptide q-value"", + spectrum_match.q_value_set.peptide_q_value, + ""MS:XXX10E""), + mparam(""GlycReSoft:glycan q-value"", + spectrum_match.q_value_set.glycan_q_value, ""MS:XXX10F""), + mparam(""GlycReSoft:glycopeptide q-value"", + spectrum_match.q_value_set.glycopeptide_q_value, ""MS:XXX10D""), + ] + return score_params + + def convert_to_identification_item_dict(self, spectrum_match: serialize.GlycopeptideSpectrumMatch, + seen_targets: Optional[Set[int]] = None, + id_tracker: Optional[SequenceIdTracker] = None) -> Props: + if seen_targets is None: + seen_targets = set() + if spectrum_match.target.id not in seen_targets: + return None + charge = spectrum_match.scan.precursor_information.charge + data = { + ""charge_state"": charge, + ""experimental_mass_to_charge"": mass_charge_ratio( + spectrum_match.scan.precursor_information.neutral_mass, charge), + ""calculated_mass_to_charge"": mass_charge_ratio( + spectrum_match.target.total_mass, charge), + ""peptide_id"": id_tracker(spectrum_match.target), + ""peptide_evidence_id"": spectrum_match.target.id, + ""score"": mparam({ + ""name"": ""GlycReSoft:total score"", + ""value"": spectrum_match.score, + ""accession"": ""MS:XXX10A"", + }), + ""params"": [ + components.CVParam(**{ + ""name"": ""glycan dissociating, peptide preserving"", + ""accession"": ""MS:XXX111"", ""cvRef"": ""PSI-MS""}), + components.CVParam(**{ + ""name"": ""glycan eliminated, peptide dissociating"", + ""accession"": ""MS:XXX114"", ""cvRef"": ""PSI-MS""}), + { + ""name"": ""scan start time"", + ""value"": spectrum_match.scan.scan_time, + ""unit_name"": ""minute"" + } + ], + ""id"": spectrum_match.id + } + if spectrum_match.is_multiscore(): + score_params = self._encode_score_set(spectrum_match) + data['params'].extend(score_params) + else: + data['params'].extend([ + mparam(""GlycReSoft:glycopeptide q-value"", + spectrum_match.q_value, ""MS:XXX10D""), + ]) + if spectrum_match.mass_shift.name != Unmodified.name: + data['params'].append( + mparam(""GlycReSoft:mass shift"", ""%s:%0.3f:%0.3f"" % ( + spectrum_match.mass_shift.name, + spectrum_match.mass_shift.mass, + spectrum_match.mass_shift.tandem_mass), + ""MS:XXX10I"")) + return data + + def convert_to_spectrum_identification_dict(self, spectrum_solution_set: serialize.GlycopeptideSpectrumSolutionSet, + seen_targets: Optional[Set[int]] = None, + id_tracker: Optional[SequenceIdTracker] = None) -> Props: + data = { + ""spectra_data_id"": 1, + ""spectrum_id"": spectrum_solution_set.scan.scan_id, + ""id"": spectrum_solution_set.id + } + idents = [] + for item in spectrum_solution_set: + d = self.convert_to_identification_item_dict( + item, seen_targets=seen_targets, id_tracker=id_tracker) + if d is None: + continue + idents.append(d) + data['identifications'] = idents + return data + + def convert_to_peptide_evidence_dict(self, glycopeptide: GlycopeptideType, id_tracker: SequenceIdTracker) -> Props: + data = { + ""start_position"": glycopeptide.protein_relation.start_position, + ""end_position"": glycopeptide.protein_relation.end_position, + ""peptide_id"": id_tracker(glycopeptide), + ""db_sequence_id"": glycopeptide.protein_relation.protein_id, + ""is_decoy"": False, + ""id"": glycopeptide.id + } + return data + + def convert_to_protein_dict(self, protein: serialize.Protein, include_sequence: bool = True) -> Props: + data = { + ""id"": protein.id, + ""accession"": protein.name, + ""search_database_id"": 1, + } + if include_sequence: + data[""sequence""] = protein.protein_sequence + return data + + def extract_peptides(self): + self.log(""Extracting Proteins"") + self.extract_proteins() + self._peptides = [] + seen = set() + + self.log(""Extracting Peptides"") + for gp in self.glycopeptide_list: + d = self.convert_to_peptide_dict(gp.structure, self._id_tracker) + + if self._id_tracker(gp.structure) == gp.structure.id: + self._peptides.append(d) + seen.add(gp.structure.id) + + self.log(""Extracting PeptideEvidence"") + self._peptide_evidence = [ + self.convert_to_peptide_evidence_dict( + gp.structure, self._id_tracker) for gp in self.glycopeptide_list + ] + + self._proteins = [ + self.convert_to_protein_dict(prot, self.embed_protein_sequences) + for prot in self.protein_list + ] + + def extract_spectrum_identifications(self): + self.log(""Extracting SpectrumIdentificationResults"") + spectrum_identifications = [] + seen_scans = set() + accepted_solution_ids = {gp.structure.id for gp in self.glycopeptide_list} + gp_list = self.glycopeptide_list + n = len(gp_list) + j = 0 + for i, gp in enumerate(gp_list): + if i % 25 == 0: + self.log(""... Processed %d glycopeptide features with %d spectra matched (%0.2f%%)"" % (i, j, i * 100.0 / n)) + if self.report_top_match_per_glycopeptide: + spectrum_matches: List[serialize.GlycopeptideSpectrumSolutionSet] = [ + gp.best_spectrum_match.solution_set] + else: + spectrum_matches: List[serialize.GlycopeptideSpectrumSolutionSet] = gp.spectrum_matches + for solution in spectrum_matches: + j += 1 + if solution.scan.scan_id in seen_scans: + continue + if solution.best_solution().q_value > self.q_value_threshold: + continue + if solution.score < self.ms2_score_threshold: + continue + seen_scans.add(solution.scan.scan_id) + d = self.convert_to_spectrum_identification_dict( + solution, seen_targets=accepted_solution_ids, + id_tracker=self._id_tracker) + if len(d['identifications']): + spectrum_identifications.append(d) + + self.scan_ids = seen_scans + self._spectrum_identification_list = { + ""id"": 1, + ""identification_results"": spectrum_identifications + } + + def software_entry(self) -> List[Props]: + software = { + ""name"": ""GlycReSoft"", + ""version"": version.version, + ""uri"": None + } + return [software] + + def search_database(self) -> Props: + hypothesis = self.analysis.hypothesis + spec = { + ""name"": hypothesis.name, + ""location"": self.database_handle._original_connection, + ""id"": 1 + } + if ""fasta_file"" in hypothesis.parameters: + spec['file_format'] = 'fasta format' + spec['location'] = hypothesis.parameters['fasta_file'] + elif ""mzid_file"" in hypothesis.parameters: + spec['file_format'] = 'mzIdentML format' + return spec + + def source_file(self) -> Props: + spec = { + ""location"": self.database_handle._original_connection, + ""file_format"": ""data stored in database"", + ""id"": 1 + } + return spec + + def spectra_data(self) -> Props: + spec = { + ""location"": self.analysis.parameters['sample_path'], + ""file_format"": 'mzML format', + ""spectrum_id_format"": ""multiple peak list nativeID format"", + ""id"": 1 + } + return spec + + def protocol(self) -> Props: + hypothesis = self.analysis.hypothesis + analysis = self.analysis + mods = [] + + def transform_modification(mod): + if isinstance(mod, str): + mod_inst = modification.Modification(mod) + target = modification.extract_targets_from_rule_string(mod) + new_rule = mod_inst.rule.clone({target}) + return new_rule + return mod + + def pack_modification(mod, fixed=True): + mod_spec = { + ""fixed"": fixed, + ""mass_delta"": mod.mass, + ""residues"": [res.symbol for rule in mod.targets + for res in rule.amino_acid_targets], + ""params"": [ + mod.name + ] + } + return mod_spec + + def pack_glycan_modification(glycan_composition, fixed=False): + params = self.gnome_resolver.glycan_composition_to_terms(self._coerce_orm(glycan_composition)) + glycan_types = sorted({str(b) for a in glycan_composition.component_classes for b in a}) + residues = [] + for gt in glycan_types: + gt = str(gt) + if gt == ""N-Glycan"": + residues.append(""N"") + if gt == ""O-Glycan"": + residues.extend(""ST"") + if gt == 'GAG-Linker': + residues.append(""S"") + params.append(glycosylation_type_to_term(gt)) + if glycan_composition.count == 1: + params.append({ + ""name"": ""glycan composition"", + ""cvRef"": ""PSI-MS"", + ""accession"": ""MS:XXXX14"" + }) + else: + params.append({ + ""name"": ""glycan aggregate"", + ""cvRef"": ""PSI-MS"", + ""accession"": ""MS:XXXX15"" + }) + mod_spec = { + ""fixed"": fixed, + ""mass_delta"": glycan_composition.dehydrated_mass(), + ""name"": ""glycosylation modification"", + # ""accession"": ""MS:XXXXX1"", + ""residues"": residues, + ""params"": [components.CVParam(**x) for x in params] + } + return mod_spec + + + for mod in hypothesis.parameters.get('constant_modifications', []): + mod = transform_modification(mod) + mods.append(pack_modification(mod, True)) + for mod in hypothesis.parameters.get('variable_modifications', []): + mod = transform_modification(mod) + mods.append(pack_modification(mod, False)) + + for gc in sorted(self.glycan_list, key=lambda x: (x.mass(), x.id)): + mods.append(pack_glycan_modification(gc, False)) + + strategy = analysis.parameters.get(""search_strategy"") + if strategy == ""multipart-target-decoy-competition"": + fdr_params = [ + {""name"": ""glycopeptide false discovery rate control strategy"", + ""accession"": ""MS:XXX108"", ""cvRef"": ""PSI-MS""}, + {""name"": ""peptide glycopeptide false discovery rate control strategy"", + ""accession"": ""MS:XXX106"", ""cvRef"": ""PSI-MS""}, + {""name"": ""glycan glycopeptide false discovery rate control strategy"", + ""accession"": ""MS:XXX107"", ""cvRef"": ""PSI-MS""}, + {""name"": ""joint glycopeptide false discovery rate control strategy"", + ""accession"": ""MS:XXX11A"", ""cvRef"": ""PSI-MS""}, + ] + else: + fdr_params = [ + {""name"": ""glycopeptide false discovery rate control strategy"", + ""accession"": ""MS:XXX108"", ""cvRef"": ""PSI-MS""}, + ] + spec = { + ""enzymes"": [ + {""name"": getattr(e, 'name', e), ""missed_cleavages"": hypothesis.parameters.get( + 'max_missed_cleavages', None), ""id"": i} + for i, e in enumerate(hypothesis.parameters.get('enzymes')) + ], + ""fragment_tolerance"": (analysis.parameters['fragment_error_tolerance'] * 1e6, None, ""parts per million""), + ""parent_tolerance"": (analysis.parameters['mass_error_tolerance'] * 1e6, None, ""parts per million""), + ""modification_params"": mods, + ""id"": 1, + ""additional_search_params"": [ + { + ""name"": ""glycopeptide search"", + ""accession"": ""MS:XXXX98"", + ""cvRef"": ""PSI-MS"", + } + ] + fdr_params + [ + { + ""name"": ""param: b ion"", + ""accession"": ""MS:1001118"", + ""cvRef"": ""PSI-MS"", + }, + { + ""name"": ""param: y ion"", + ""accession"": ""MS:1001262"", + ""cvRef"": ""PSI-MS"", + }, + { + ""name"": ""param: peptide + glycan Y ion"", + ""accession"": ""MS:XXXX17"", + ""cvRef"": ""PSI-MS"", + }, + { + ""name"": ""param: oxonium ion"", + ""accession"": ""MS:XXXX22"", + ""cvRef"": ""PSI-MS"", + }, + ] + } + spec['additional_search_params'] = [components.CVParam(**x) for x in spec['additional_search_params']] + return spec + + def run(self): + f = MzIdentMLWriter(self.outfile, vocabularies=[ + components.CV( + id='GNO', uri=""http://purl.obolibrary.org/obo/gno.obo"", full_name='GNO'), + ]) + self.log(""Loading Spectra Data"") + spectra_data = self.spectra_data() + self.log(""Loading Search Database"") + search_database = self.search_database() + self.log(""Building Protocol"") + self.extract_glycans() + protocol = self.protocol() + source_file = self.source_file() + self.extract_peptides() + self.extract_spectrum_identifications() + + had_specified_mzml_path = self.source_mzml_path is None + if self.source_mzml_path is None: + self.source_mzml_path = spectra_data['location'] + + if self.source_mzml_path is None: + did_resolve_mzml_path = False + else: + did_resolve_mzml_path = os.path.exists(self.source_mzml_path) + if not did_resolve_mzml_path: + self.log(""Could not locate source mzML file."") + if not had_specified_mzml_path: + self.log(""If you did not specify an alternative location to "" + ""find the mzML path, please do so."") + + if self.export_mzml and did_resolve_mzml_path: + if self.output_mzml_path is None: + prefix = os.path.splitext(self.outfile.name)[0] + self.output_mzml_path = ""%s.export.mzML"" % (prefix,) + exporter = None + self.log(""Begin Exporting mzML"") + with open(self.output_mzml_path, 'wb') as handle: + exporter = MzMLExporter(self.source_mzml_path, handle) + self.log(""... Aggregating Scan Bunches"") + scan_bunches = exporter.aggregate_scan_bunches(self.scan_ids) + self.log(""... Exporting Spectra"") + exporter.begin(scan_bunches) + self.log(""... Exporting Chromatograms"") + exporter.extract_chromatograms_from_identified_glycopeptides( + self.glycopeptide_list) + self.log(""... Finalizing mzML"") + exporter.complete() + self.log(""mzML Export Finished"") + + analysis = [[spectra_data['id']], [search_database['id']]] + + with f: + f.controlled_vocabularies() + f.providence(software=self.software_entry()) + + f.register(""SpectraData"", spectra_data['id']) + f.register(""SearchDatabase"", search_database['id']) + f.register(""SpectrumIdentificationList"", self._spectrum_identification_list['id']) + + with f.sequence_collection(): + for prot in self._proteins: + f.write_db_sequence(**prot) + for pep in self._peptides: + f.write_peptide(**pep) + for pe in self._peptide_evidence: + f.write_peptide_evidence(**pe) + + with f.analysis_protocol_collection(): + f.spectrum_identification_protocol(**protocol) + + with f.element(""AnalysisCollection""): + f.SpectrumIdentification(*analysis).write(f) + + with f.element(""DataCollection""): + f.inputs(source_file, search_database, spectra_data) + with f.element(""AnalysisData""): + with f.spectrum_identification_list(id=self._spectrum_identification_list['id']): + for result_ in self._spectrum_identification_list['identification_results']: + result = dict(result_) + identifications = result.pop(""identifications"") + result = f.spectrum_identification_result(**result) + with result: + for item in identifications: + f.write_spectrum_identification_item(**item) + + f.outfile.close() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/output/text_format.py",".py","6439","151","from glypy.io import iupac, glycoct +from glypy import Glycan + +from ms_deisotope.output import mgf, mzml, ProcessedMSFileLoader +from ms_deisotope.data_source import ScanBunch + +from sqlalchemy.orm import aliased +from glycresoft import serialize +from glycresoft.task import TaskBase + + +def build_partial_subgraph_n_glycan(composition): + composition = composition.clone() + if composition[""HexNAc""] < 2: + raise ValueError(""Not enough HexNAc present to extract N-glycan core"") + root = iupac.loads(""?-D-Glcp2NAc"").clone(prop_id=False) + composition['HexNAc'] -= 1 + b2 = iupac.loads(""b-D-Glcp2NAc"").clone(prop_id=False) + root.add_monosaccharide(b2, position=4, child_position=1) + composition['HexNAc'] -= 1 + if composition['Hex'] < 3: + raise ValueError(""Not enough Hex present to extract N-glycan core"") + composition['Hex'] -= 3 + b3 = iupac.loads(""b-D-Manp"").clone() + b2.add_monosaccharide(b3, position=4, child_position=1) + b4 = iupac.loads(""a-D-Manp"").clone() + b3.add_monosaccharide(b4, position=3, child_position=1) + b5 = iupac.loads(""a-D-Manp"").clone() + b3.add_monosaccharide(b5, position=6, child_position=1) + subgraph = Glycan(root, index_method=None) + return composition, subgraph + + +def to_glycoct_partial_n_glycan(composition): + a, b = build_partial_subgraph_n_glycan(composition) + writer = glycoct.OrderRespectingGlycoCTWriter(b) + writer.handle_glycan(writer.structure) + writer.add_glycan_composition(a) + return writer.buffer.getvalue() + + +class GlycoCTCompositionListExporter(TaskBase): + def __init__(self, outstream, glycan_composition_iterable): + self.outstream = outstream + self.glycan_composition_iterable = glycan_composition_iterable + + def run(self): + for glycan_composition in self.glycan_composition_iterable: + text = to_glycoct_partial_n_glycan(glycan_composition) + self.outstream.write(text) + self.outstream.write(""\n"") + + +class AnnotatedMGFSerializer(mgf.MGFSerializer): + + def write_header(self, header_dict): + super(AnnotatedMGFSerializer, self).write_header(header_dict) + self.add_parameter(""precursor_defaulted"", header_dict['defaulted']) + self.add_parameter(""activation_method"", header_dict['precursor_activation_method']) + self.add_parameter(""activation_energy"", header_dict['precursor_activation_energy']) + self.add_parameter(""analyzers"", header_dict.get('analyzers')) + self.add_parameter(""scan_id"", header_dict['id']) + self.add_parameter(""precursor_scan_id"", header_dict['precursor_scan_id']) + for key, value in header_dict['annotations'].items(): + self.add_parameter(key, value) + + +class TrainingMGFExporterBase(TaskBase): + def __init__(self, outstream, spectrum_match_iterable): + self.outstream = outstream + self.spectrum_match_iterable = spectrum_match_iterable + + def prepare_scan(self, spectrum_match): + scan = spectrum_match.scan + scan = scan.clone() + scan.annotations['structure'] = spectrum_match.target + # try: + # scan.annotations['protein_name'] = spectrum_match.target.protein.name + # except AttributeError: + # pass + try: + scan.annotations['mass_shift'] = spectrum_match.mass_shift.name + except AttributeError: + pass + scan.annotations['ms2_score'] = spectrum_match.score + try: + scan.annotations['q_value'] = spectrum_match.q_value + except AttributeError: + pass + try: + score_set = spectrum_match.score_set + scan.annotations['ms2_peptide_score'] = score_set.peptide_score + scan.annotations['ms2_glycan_score'] = score_set.glycan_score + scan.annotations['ms2_glycan_coverage'] = score_set.glycan_coverage + q_value_set = spectrum_match.q_value_set + scan.annotations['q_value'] = q_value_set.total_q_value + scan.annotations['glycan_q_value'] = q_value_set.glycan_q_value + scan.annotations['peptide_q_value'] = q_value_set.peptide_q_value + scan.annotations['glycopeptide_q_value'] = q_value_set.glycopeptide_q_value + except AttributeError as err: + print(err) + return scan + + def run(self): + writer = AnnotatedMGFSerializer(self.outstream) + for spectrum_match in self.spectrum_match_iterable: + scan = self.prepare_scan(spectrum_match) + writer.save(ScanBunch(None, [scan])) + writer.complete() + + +class TrainingMGFExporter(TrainingMGFExporterBase): + def __init__(self, outstream, spectrum_match_iterable, mzml_path): + super(TrainingMGFExporter, self).__init__(outstream, spectrum_match_iterable) + self.scan_loader = ProcessedMSFileLoader(mzml_path) + + def prepare_scan(self, spectrum_match): + scan = self.scan_loader.get_scan_by_id(spectrum_match.scan.scan_id) + spectrum_match.scan = scan.clone() + scan = super(TrainingMGFExporter, self).prepare_scan(spectrum_match) + return scan + + @classmethod + def _from_analysis_id_query(cls, database_connection, analysis_id, threshold=0.0): + + A = aliased(serialize.GlycopeptideSpectrumMatch) + q = database_connection.query(A).filter( + A.is_best_match, + A.analysis_id == analysis_id) + # B = aliased(serialize.GlycopeptideSpectrumMatch) + # qinner = database_connection.query( + # B.id.label('inner_id'), serialize.func.max(B.score).label(""inner_score""), + # B.scan_id.label(""inner_scan_id"")).group_by(B.scan_id).selectable + + # q = database_connection.query(A).join( + # qinner, qinner.c.inner_id == A.id and A.score == qinner.inner_score).filter( + # A.analysis_id == analysis_id) + + if threshold is not None: + q = q.filter(A.score >= threshold) + for gsm in q: + yield gsm.convert() + + @classmethod + def from_analysis(cls, database_connection, analysis_id, outstream, scan_loader_path=None, threshold=0.0): + if scan_loader_path is None: + analysis = database_connection.query(serialize.Analysis).get(analysis_id) + scan_loader_path = analysis.parameters['sample_path'] + iterable = cls._from_analysis_id_query(database_connection, analysis_id, threshold=threshold) + return cls(outstream, iterable, scan_loader_path) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/output/csv_format.py",".py","20419","585","import csv +import logging + +from io import TextIOWrapper +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Mapping, TextIO, Tuple, Union + +from six import PY2 + +from glycresoft.task import TaskBase + +from glycresoft.scoring.elution_time_grouping import ( + GlycopeptideChromatogramProxy +) + +from glycopeptidepy import PeptideSequence +from glycresoft.serialize import Glycopeptide +from glycresoft.structure.structure_loader import FragmentCachingGlycopeptide +if TYPE_CHECKING: + from glycresoft.serialize import Analysis + +status_logger = logging.getLogger(""glycresoft.status"") + + +def csv_stream(outstream): + if 'b' in outstream.mode: + if not PY2: + return TextIOWrapper(outstream, 'utf8', newline="""") + else: + return outstream + else: + import warnings + warnings.warn(""Opened CSV stream in text mode!"") + return outstream + + +class CSVSerializerBase(TaskBase): + entity_label: str = ""entities"" + log_interval: int = 100 + outstream: TextIO + writer: csv.writer + delimiter: str + _entities_iterable: Iterable + + def __init__(self, outstream, entities_iterable, delimiter=','): + self.outstream = outstream + try: + self.is_binary = 'b' in self.outstream.mode + except AttributeError: + self.is_binary = True + if self.is_binary: + try: + self.outstream = TextIOWrapper(outstream, 'utf8', newline="""") + except AttributeError: + # must be Py2 + pass + self.writer = csv.writer(self.outstream, delimiter=delimiter) + self._entities_iterable = entities_iterable + + def status_update(self, message: str): + status_logger.info(message) + + def writerows(self, iterable: Iterable[Iterable[str]]): + self.writer.writerows(iterable) + + def writerow(self, row: Iterable[str]): + self.writer.writerow(row) + + def get_header(self) -> List[str]: + raise NotImplementedError() + + def convert_object(self, obj): + raise NotImplementedError() + + @property + def header(self): + return self.get_header() + + def run(self): + if self.header: + header = self.header + self.writerow(header) + entity_label = self.entity_label + log_interval = self.log_interval + gen = (self.convert_object(entity) for entity in self._entities_iterable) + i = 0 + for i, row in enumerate(gen, 1): + if i % log_interval == 0 and i != 0: + self.status_update(f""Handled {i} {entity_label}"") + self.writerow(row) + self.status_update(f""Handled {i} {entity_label}"") + self.outstream.flush() # If the TextIOWrapper is buffering, we need to flush it here + + +class GlycanHypothesisCSVSerializer(CSVSerializerBase): + def __init__(self, outstream, entities_iterable, delimiter=','): + super(GlycanHypothesisCSVSerializer, self).__init__( + outstream, entities_iterable, delimiter) + + def get_header(self): + return [ + ""composition"", + ""calculated_mass"", + ""classes"" + ] + + def convert_object(self, obj): + attribs = [ + obj.composition, + obj.calculated_mass, + "";"".join([sc.name for sc in obj.structure_classes]) + ] + return list(map(str, attribs)) + + +class ImportableGlycanHypothesisCSVSerializer(CSVSerializerBase): + def __init__(self, outstream, entities_iterable): + super(ImportableGlycanHypothesisCSVSerializer, self).__init__( + outstream, entities_iterable, delimiter=""\t"") + + def get_header(self): + return False + + def convert_object(self, obj): + attribs = [ + obj.composition, + # Use list concatenation to ensure that the glycan classes + # are treated as independent entries not containing whitespace + # so that they are not quoted + ] + [sc.name for sc in obj.structure_classes] + return list(map(str, attribs)) + + +class GlycopeptideHypothesisCSVSerializer(CSVSerializerBase): + def __init__(self, outstream, entities_iterable, delimiter=','): + super(GlycopeptideHypothesisCSVSerializer, self).__init__( + outstream, entities_iterable, delimiter) + + def get_header(self): + return [ + ""glycopeptide"", + ""calculated_mass"", + ""start_position"", + ""end_position"", + ""protein"", + ] + + def convert_object(self, obj): + attribs = [ + obj.glycopeptide_sequence, + obj.calculated_mass, + obj.peptide.start_position, + obj.peptide.end_position, + obj.peptide.protein.name + ] + return list(map(str, attribs)) + + +class SimpleChromatogramCSVSerializer(CSVSerializerBase): + def __init__(self, outstream, entities_iterable, delimiter=','): + super(SimpleChromatogramCSVSerializer, self).__init__( + outstream, entities_iterable, delimiter) + + def get_header(self): + return [ + ""neutral_mass"", + ""total_signal"", + ""charge_states"", + ""start_time"", + ""apex_time"", + ""end_time"" + ] + + def convert_object(self, obj): + attribs = [ + obj.weighted_neutral_mass, + obj.total_signal, + ';'.join(map(str, obj.charge_states)), + obj.start_time, + obj.apex_time, + obj.end_time, + ] + return map(str, attribs) + + +class SimpleScoredChromatogramCSVSerializer(SimpleChromatogramCSVSerializer): + + def get_header(self): + headers = super(SimpleScoredChromatogramCSVSerializer, self).get_header() + headers += [ + ""score"", + ""line_score"", + ""isotopic_fit"", + ""spacing_fit"", + ""charge_count"", + ] + return headers + + def convert_object(self, obj): + attribs = super(SimpleScoredChromatogramCSVSerializer, self).convert_object(obj) + scores = obj.score_components() + more_attribs = [ + obj.score, + scores.line_score, + scores.isotopic_fit, + scores.spacing_fit, + scores.charge_count, + ] + attribs = list(attribs) + list(map(str, more_attribs)) + return attribs + + +class GlycanLCMSAnalysisCSVSerializer(CSVSerializerBase): + def __init__(self, outstream, entities_iterable, delimiter=','): + super(GlycanLCMSAnalysisCSVSerializer, self).__init__( + outstream, entities_iterable, delimiter) + + def get_header(self): + return [ + ""composition"", + ""neutral_mass"", + ""mass_accuracy"", + ""score"", + ""total_signal"", + ""start_time"", + ""end_time"", + ""apex_time"", + ""charge_states"", + ""mass_shifts"", + ""line_score"", + ""isotopic_fit"", + ""spacing_fit"", + ""charge_count"", + ""ambiguous_with"", + ""used_as_mass_shift"" + ] + + def convert_object(self, obj): + scores = obj.score_components() + attribs = [ + obj.glycan_composition, + obj.weighted_neutral_mass, + 0 if obj.glycan_composition is None else ( + (obj.glycan_composition.mass() - obj.weighted_neutral_mass + ) / obj.weighted_neutral_mass), + obj.score, + obj.total_signal, + obj.start_time, + obj.end_time, + obj.apex_time, + ';'.join(map(str, obj.charge_states)), + ';'.join([a.name for a in obj.mass_shifts]), + scores.line_score, + scores.isotopic_fit, + scores.spacing_fit, + scores.charge_count, + ';'.join(""%s:%s"" % (p[0], p[1].name) for p in obj.ambiguous_with), + ';'.join(""%s:%s"" % (p[0], p[1].name) for p in obj.used_as_mass_shift) + ] + return list(map(str, attribs)) + + +class GlycositeMixin: + site_track_cache: Mapping[int, Mapping[str, List[Tuple[int, str]]]] = None + + def get_n_glycosites(self, glycopeptide: Union[Glycopeptide, PeptideSequence]): + if isinstance(glycopeptide, Glycopeptide): + glycopeptide = glycopeptide.convert() + start = glycopeptide.protein_relation.start + protein_id = glycopeptide.protein_relation.protein_id + if not self.site_track_cache or protein_id not in self.site_track_cache: + sites = set() + seq = str(glycopeptide.strip_modifications()) + for site, (_, mods) in glycopeptide.modified_residues(): + for mod in mods: + if mod == ""N-Glycosylation"": + sequon = seq[site:site + 3] + i = start + site + v = (i, sequon) + if v not in sites: + sites.add(v) + return sorted(sites) + else: + tracks = self.site_track_cache[protein_id] + sites = tracks.get(""N-Glycosylation"", []) + return [(i, sequon) for i, sequon in sites if i in glycopeptide.protein_relation] + + +class MissedCleavageMixin: + missed_cleavage_cache: Mapping[int, int] = None + + def get_missed_cleavages(self, glycopeptide: Union[Glycopeptide, FragmentCachingGlycopeptide]): + if isinstance(glycopeptide, Glycopeptide): + i = glycopeptide.id + if not self.missed_cleavage_cache or i not in self.missed_cleavage_cache: + return glycopeptide.peptide.count_missed_cleavages + return self.missed_cleavage_cache[i] + else: + try: + i = glycopeptide.id + if not self.missed_cleavage_cache or i not in self.missed_cleavage_cache: + return 0 + return self.missed_cleavage_cache[i] + except Exception as err: + self.error(f""Failed to retrieve missed cleavages: {err}"") + return 0 + + +class GlycopeptideLCMSMSAnalysisCSVSerializer(CSVSerializerBase, GlycositeMixin, MissedCleavageMixin): + analysis: 'Analysis' + protein_name_resolver: Mapping[int, str] + include_group: bool + + def __init__(self, outstream, entities_iterable, protein_name_resolver, analysis, delimiter=',', + include_group: bool=True, site_track_cache=None): + super(GlycopeptideLCMSMSAnalysisCSVSerializer, self).__init__(outstream, entities_iterable, delimiter) + self.protein_name_resolver = protein_name_resolver + self.analysis = analysis + self.retention_time_model = analysis.parameters.get(""retention_time_model"") + self.include_group = include_group + self.site_track_cache = site_track_cache + + def get_header(self): + headers = [ + ""glycopeptide"", + ""analysis"", + ""neutral_mass"", + ""mass_accuracy"", + ""ms1_score"", + ""ms2_score"", + ""q_value"", + ""total_signal"", + ""start_time"", + ""end_time"", + ""apex_time"", + ""charge_states"", + ""msms_count"", + ""peptide_start"", + ""peptide_end"", + ""protein_name"", + ""n_glycosylation_sites"", + ""mass_shifts"", + ""missed_cleavages"", + ] + if self.include_group: + headers.append(""group_id"") + if self.retention_time_model: + headers.extend([ + ""predicted_apex_interval_start"", + ""predicted_apex_interval_end"", + ""retention_time_score"", + ]) + return headers + + def convert_object(self, obj): + has_chrom = obj.has_chromatogram() + if has_chrom: + weighted_neutral_mass = obj.weighted_neutral_mass + charge_states = obj.charge_states + else: + weighted_neutral_mass = obj.tandem_solutions[0].scan.precursor_information.neutral_mass + charge_states = (obj.tandem_solutions[0].scan.precursor_information.charge,) + + missed_cleavages = '' + try: + missed_cleavages = self.get_missed_cleavages(obj.structure) + except Exception as err: + self.error(f""Failed to retrieve missed cleavages: {err}"") + + attribs = [ + str(obj.structure), + self.analysis.name, + weighted_neutral_mass, + (obj.structure.total_mass - weighted_neutral_mass) / weighted_neutral_mass, + obj.ms1_score, + obj.ms2_score, + obj.q_value, + obj.total_signal, + obj.start_time if has_chrom else """", + obj.end_time if has_chrom else """", + obj.apex_time if has_chrom else """", + "";"".join(map(str, charge_states)), + len(obj.spectrum_matches), + obj.protein_relation.start_position, + obj.protein_relation.end_position, + self.protein_name_resolver[obj.protein_relation.protein_id], + "";"".join([':'.join(map(str, i)) for i in self.get_n_glycosites(obj.structure)]), + "";"".join([a.name for a in obj.mass_shifts]), + missed_cleavages, + ] + try: + attribs.append(obj.ambiguous_id) + except AttributeError: + attribs.append(-1) + if self.retention_time_model: + if has_chrom: + proxy = GlycopeptideChromatogramProxy.from_chromatogram(obj) + rt_start, rt_end = self.retention_time_model.predict_interval(proxy, 0.01) + rt_score = self.retention_time_model.score_interval(proxy, 0.01) + attribs.append(rt_start) + attribs.append(rt_end) + attribs.append(rt_score) + else: + attribs.append(""-"") + attribs.append(""-"") + attribs.append(""-"") + return list(map(str, attribs)) + + +class MultiScoreGlycopeptideLCMSMSAnalysisCSVSerializer(GlycopeptideLCMSMSAnalysisCSVSerializer): + def get_header(self): + headers = super(MultiScoreGlycopeptideLCMSMSAnalysisCSVSerializer, self).get_header() + headers.extend([ + ""glycopeptide_score"", + ""peptide_score"", + ""glycan_score"", + ""glycan_coverage"", + ""total_q_value"", + ""peptide_q_value"", + ""glycan_q_value"", + ""glycopeptide_q_value"", + ""localizations"" + ]) + return headers + + def convert_object(self, obj): + fields = super(MultiScoreGlycopeptideLCMSMSAnalysisCSVSerializer, self).convert_object(obj) + score_set = obj.score_set + q_value_set = obj.q_value_set + new_fields = [ + score_set.glycopeptide_score if score_set is not None else ""?"", + score_set.peptide_score if score_set is not None else ""?"", + score_set.glycan_score if score_set is not None else ""?"", + score_set.glycan_coverage if score_set is not None else ""?"", + q_value_set.total_q_value if q_value_set is not None else ""?"", + q_value_set.peptide_q_value if q_value_set is not None else ""?"", + q_value_set.glycan_q_value if q_value_set is not None else ""?"", + q_value_set.glycopeptide_q_value if q_value_set is not None else ""?"", + ';'.join(map(str, obj.localizations)) + ] + fields.extend(map(str, new_fields)) + return fields + + +class GlycopeptideSpectrumMatchAnalysisCSVSerializer(CSVSerializerBase, GlycositeMixin, MissedCleavageMixin): + entity_label = ""glycopeptide spectrum matches"" + log_interval = 5000 + + include_rank: bool + include_group: bool + analysis: 'Analysis' + protein_name_resolver: Dict[int, str] + + def __init__(self, outstream, entities_iterable, protein_name_resolver, analysis, delimiter=',', + include_rank: bool = True, include_group: bool = True, site_track_cache: dict=None, + missed_cleavage_cache: dict=None): + super(GlycopeptideSpectrumMatchAnalysisCSVSerializer, self).__init__(outstream, entities_iterable, delimiter) + self.protein_name_resolver = protein_name_resolver + self.analysis = analysis + self.include_rank = include_rank + self.include_group = include_group + self.site_track_cache = site_track_cache + self.missed_cleavage_cache = missed_cleavage_cache + + def get_header(self): + names = [ + ""glycopeptide"", + ""analysis"", + ""neutral_mass"", + ""mass_accuracy"", + ""mass_shift_name"", + ""scan_id"", + ""scan_time"", + ""charge"", + ""ms2_score"", + ""q_value"", + ""precursor_abundance"", + ""peptide_start"", + ""peptide_end"", + ""protein_name"", + ""n_glycosylation_sites"", + ""is_best_match"", + ""is_precursor_fit"", + ] + if self.include_rank: + names.append(""rank"") + if self.include_group: + names.append(""group_id"") + names.extend([ + ""precursor_scan_id"", + ""precursor_activation"", + ""missed_cleavages"" + ]) + return names + + def convert_object(self, obj): + try: + mass_shift = obj.mass_shift + mass_shift_mass = mass_shift.mass + mass_shift_name = mass_shift.name + except Exception: + mass_shift_name = ""Unmodified"" + mass_shift_mass = 0 + target = obj.target + scan = obj.scan + precursor = scan.precursor_information + precursor_mass = precursor.neutral_mass + precursor_id = '' + try: + precursor_id = precursor.precursor_scan_id + except AttributeError as err: + self.error(f""Failed to resolve precursor id: {err}"") + precursor_activation = '' + try: + precursor_activation = str(scan.activation.method) + except AttributeError as err: + self.error(f""Failed to resolve precursor activation: {err}"") + attribs = [ + str(obj.target), + self.analysis.name, + precursor_mass, + ((target.total_mass + mass_shift_mass) - precursor_mass) / precursor_mass, + mass_shift_name, + scan.scan_id, + scan.scan_time, + scan.precursor_information.extracted_charge, + obj.score, + obj.q_value, + scan.precursor_information.intensity, + target.protein_relation.start_position, + target.protein_relation.end_position, + self.protein_name_resolver[target.protein_relation.protein_id], + "";"".join(["":"".join(map(str, i)) for i in self.get_n_glycosites(obj.target)]), + obj.is_best_match, + not precursor.defaulted, + ] + if self.include_rank: + try: + rank = obj.rank + except AttributeError: + rank = -1 + attribs.append(rank) + if self.include_group: + try: + group = obj.cluster_id + except AttributeError: + group = -1 + attribs.append(group) + attribs.extend([ + precursor_id, + precursor_activation, + self.get_missed_cleavages(target) + ]) + return list(map(str, attribs)) + + +class MultiScoreGlycopeptideSpectrumMatchAnalysisCSVSerializer(GlycopeptideSpectrumMatchAnalysisCSVSerializer): + + def get_header(self): + header = super(MultiScoreGlycopeptideSpectrumMatchAnalysisCSVSerializer, self).get_header() + header.extend([ + ""peptide_score"", + ""glycan_score"", + ""glycan_coverage"", + ""peptide_q_value"", + ""glycan_q_value"", + ""glycopeptide_q_value"", + ""localizations"", + ]) + return header + + def convert_object(self, obj): + fields = super(MultiScoreGlycopeptideSpectrumMatchAnalysisCSVSerializer, self).convert_object(obj) + score_set = obj.score_set + fdr_set = obj.q_value_set + fields.extend([ + score_set.peptide_score, + score_set.glycan_score, + score_set.glycan_coverage, + fdr_set.peptide_q_value, + fdr_set.glycan_q_value, + fdr_set.glycopeptide_q_value, + ';'.join(map(str, obj.localizations)) + ]) + return fields +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/output/report/__init__.py",".py","245","9","from .glycan_lcms.render import GlycanChromatogramReportCreator +from .glycopeptide_lcmsms.render import GlycopeptideDatabaseSearchReportCreator + + +__all__ = [ + ""GlycanChromatogramReportCreator"", + ""GlycopeptideDatabaseSearchReportCreator"" +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/output/report/base.py",".py","9563","295","from typing import Any +import urllib +import logging +import base64 + +try: + from urllib.parse import quote +except ImportError: + from urllib import quote + +from io import BytesIO + +from six import string_types as basestring + +from matplotlib.axes import Axes +from matplotlib import pyplot as plt +from matplotlib import rcParams as mpl_params + +from lxml import etree + +import jinja2 +from markupsafe import escape + +from glypy.structure.glycan_composition import GlycanComposition +from glycopeptidepy import PeptideSequence + +from glycresoft.task import TaskBase +from glycresoft.serialize import DatabaseBoundOperation +from glycresoft.symbolic_expression import GlycanSymbolContext +from glycresoft.plotting import colors + + +mpl_params.update({ + 'figure.facecolor': 'white', + 'figure.edgecolor': 'white', + 'font.size': 10, + 'savefig.dpi': 72, + 'figure.subplot.bottom': .125}) + + +status_logger = logging.getLogger(""glycresoft.status"") + + +def _sanitize_savefig_kwargs(kwargs: dict): + keys = [""patchless"", ""img_width"", ""width"", ""height"", ""svg_width""] + for key in keys: + kwargs.pop(key, None) + return kwargs + + + +def render_plot(figure, **kwargs): + if isinstance(figure, Axes): + figure = figure.get_figure() + if ""height"" in kwargs: + figure.set_figheight(kwargs[""height""]) + if ""width"" in kwargs: + figure.set_figwidth(kwargs['width']) + if kwargs.get(""bbox_inches"") != 'tight' or kwargs.get(""patchless""): + figure.patch.set_alpha(0) + figure.axes[0].patch.set_alpha(0) + data_buffer = BytesIO() + figure.savefig(data_buffer, **_sanitize_savefig_kwargs(kwargs)) + plt.close(figure) + return data_buffer + + +def xmlattrs(**kwargs): + return ' '.join(""%s=\""%s\"""" % kv for kv in kwargs.items()).encode('utf8') + + +def png_plot(figure, img_width=None, img_height=None, xattrs=None, optimize: bool=False, **kwargs): + if xattrs is None: + xattrs = dict() + kwargs.pop(""svg_width"", None) + xml_attributes = dict(xattrs) + if img_width is not None: + xml_attributes['width'] = img_width + if img_height is not None: + xml_attributes['height'] = img_height + data_buffer = render_plot(figure, format='png', ** + _sanitize_savefig_kwargs(kwargs)) + return (b"""" % ( + xmlattrs(**xml_attributes), + base64.b64encode(data_buffer.getvalue()) + )).decode('utf8') + + +def svguri_plot(figure, img_width=None, img_height=None, xattrs=None, optimize: bool=False, **kwargs): + if xattrs is None: + xattrs = dict() + xml_attributes = dict(xattrs) + if img_width is not None: + xml_attributes['width'] = img_width + if img_height is not None: + xml_attributes['height'] = img_height + svg_string = svg_plot(figure, optimize=optimize, **kwargs) + return ("""" % (xmlattrs(**xml_attributes).decode('utf8'), + quote(svg_string))) + + +def _strip_style(root): + style_node = root.find("".//{http://www.w3.org/2000/svg}style"") + style_node.text = """" + return root + + +def svg_plot(figure, svg_width=None, xml_transform=None, optimize: bool=False, **kwargs): + data_buffer = render_plot(figure, format='svg', ** + _sanitize_savefig_kwargs(kwargs)) + if optimize: + root = etree.fromstring(svg_optimizer(data_buffer.getvalue())) + else: + root = etree.fromstring(data_buffer.getvalue()) + root = _strip_style(root) + if svg_width is not None: + root.attrib[""width""] = svg_width + if xml_transform is not None: + root = xml_transform(root) + return etree.tostring(root) + + +def rgbpack(color): + return ""rgba(%d,%d,%d,0.5)"" % tuple(i * 255 for i in color) + + +def formula(composition): + return ''.join(""%s%d"" % (k, v) for k, v in sorted(composition.items())) + + +def modification_specs(modification_rule): + if isinstance(modification_rule, str): + yield modification_rule + else: + yield from modification_rule.as_spec_strings() + + +def glycan_composition_string(composition): + try: + composition = GlycanComposition.parse( + GlycanSymbolContext( + GlycanComposition.parse( + composition)).serialize()) + except ValueError: + return ""%s"" % composition + + parts = [] + template = ("""" + ""%s %d"") + for k, v in sorted(composition.items(), key=lambda x: x[0].mass()): + name = str(k) + color = colors.get_color(str(name)) + parts.append(template % (rgbpack(color), name, v)) + reduced = composition.reducing_end + if reduced: + reducing_end_template = ( + """" + ""%s"") + name = formula(reduced.composition) + color = colors.get_color(str(name)) + parts.append(reducing_end_template % (rgbpack(color), name)) + + return ' '.join(parts) + + +def glycopeptide_string(sequence, long=False, include_glycan=True): + sequence = PeptideSequence(str(sequence)) + parts = [] + template = ""(%s)"" + + n_term_template = template.replace(""("", """").replace("")"", """") + '-' + c_term_template = ""-"" + (template.replace(""("", """").replace("")"", """")) + + def render(mod, template=template): + color = colors.get_color(str(mod)) + letter = escape(mod.name if long else mod.name[0]) + name = escape(mod.name) + parts.append(template % (rgbpack(color), name, name, letter)) + + if sequence.n_term.modification is not None: + render(sequence.n_term.modification, n_term_template) + for res, mods in sequence: + parts.append(res.symbol) + if mods: + for mod in mods: + render(mod) + if sequence.c_term.modification is not None: + render(sequence.c_term.modification, c_term_template) + parts.append(( + ' ' + glycan_composition_string(str(sequence.glycan)) if sequence.glycan is not None else """") + if include_glycan else """") + return ''.join(parts) + + +def highlight_sequence_site(amino_acid_sequence, site_list, site_type_list): + if isinstance(site_type_list, basestring): + site_type_list = [site_type_list for i in site_list] + sequence = list(amino_acid_sequence) + for site, site_type in zip(site_list, site_type_list): + sequence[site] = ""{}"".format(site_type, sequence[site]) + return sequence + + +def n_per_row(sequence, n=60): + row_buffer = [] + i = 0 + while i < len(sequence): + row_buffer.append( + ''.join(sequence[i:(i + n)]) + ) + i += n + return '
'.join(row_buffer) + + +def is_type(x): + return isinstance(x, type) + + +class ReportCreatorBase(TaskBase): + database_connection: DatabaseBoundOperation + env: jinja2.Environment + + def __init__(self, database_connection, analysis_id, stream=None): + self.database_connection = DatabaseBoundOperation(database_connection) + self.analysis_id = analysis_id + self.stream = stream + self.env = jinja2.Environment() + + @property + def session(self): + return self.database_connection.session + + def status_update(self, message): + status_logger.info(message) + + def prepare_environment(self): + self.env.filters['svguri_plot'] = svguri_plot + self.env.filters['png_plot'] = png_plot + self.env.filters['svg_plot'] = svg_plot + self.env.filters[""n_per_row""] = n_per_row + self.env.filters['highlight_sequence_site'] = highlight_sequence_site + self.env.filters['svg_plot'] = svg_plot + self.env.filters['glycopeptide_string'] = glycopeptide_string + self.env.filters['glycan_composition_string'] = glycan_composition_string + self.env.filters[""formula""] = formula + self.env.filters[""modification_specs""] = modification_specs + self.env.tests['is_type'] = is_type + + def set_template_loader(self, path): + self.env.loader = jinja2.FileSystemLoader(path) + + def make_template_stream(self): + raise NotImplementedError() + + def run(self): + self.prepare_environment() + template_stream = self.make_template_stream() + template_stream.dump(self.stream, encoding='utf-8') + +try: + from scour import scour + + class _SVGOptimizer: + def __init__(self, **parameters): + self.parameters = parameters + self.scour_args = scour.generateDefaultOptions() + for k, v in parameters.items(): + setattr(self.scour_args, k, v) + + def __call__(self, xml_string: bytes) -> bytes: + return scour.scourString(xml_string, self.scour_args).encode('utf8') + +except ImportError: + class _SVGOptimizer: + def __init__(self, **parameters) -> None: + self.parameters = parameters + + def __call__(self, xml_string: bytes) -> bytes: + if isinstance(xml_string, str): + return xml_string.encode('utf8') + return xml_string + + +svg_optimizer = _SVGOptimizer( + strip_comments=True, + strip_ids=True, + shorten_ids=True, + remove_metadata=True, + indent_depth=0 +) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/output/report/glycan_lcms/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/output/report/glycan_lcms/render.py",".py","6208","152","import os + +from glycresoft import serialize +from glycresoft.plotting import summaries, figax, SmoothingChromatogramArtist +from glycresoft.plotting.chromatogram_artist import ChargeSeparatingSmoothingChromatogramArtist +from glycresoft.scoring.utils import logit +from glycresoft.chromatogram_tree import ChromatogramFilter + +from jinja2 import Template +from markupsafe import Markup + + +from glycresoft.output.report.base import ( + svguri_plot, ReportCreatorBase) + + +def chromatogram_figures(chroma): + figures = [] + plot = SmoothingChromatogramArtist( + [chroma], colorizer=lambda *a, **k: 'green', ax=figax()).draw( + label_function=lambda *a, **k: """", legend=False).ax + plot.set_title(""Aggregated\nExtracted Ion Chromatogram"", fontsize=24) + chroma_svg = svguri_plot( + plot, bbox_inches='tight', height=5, width=9, svg_width=""100%"") + figures.append(chroma_svg) + if len(chroma.mass_shifts) > 1: + mass_shifts = list(chroma.mass_shifts) + labels = {} + rest = chroma + for mass_shift in mass_shifts: + with_mass_shift, rest = rest.bisect_mass_shift(mass_shift) + labels[mass_shift] = with_mass_shift + mass_shift_plot = SmoothingChromatogramArtist( + labels.values(), + colorizer=lambda *a, **k: 'green', ax=figax()).draw( + label_function=lambda *a, **k: tuple(a[0].mass_shifts)[0].name, + legend=False).ax + mass_shift_plot.set_title( + ""mass_shift-Separated\nExtracted Ion Chromatogram"", fontsize=24) + mass_shift_separation = svguri_plot( + mass_shift_plot, bbox_inches='tight', height=5, width=9, svg_width=""100%"") + figures.append(mass_shift_separation) + if len(chroma.charge_states) > 1: + charge_separating_plot = ChargeSeparatingSmoothingChromatogramArtist( + [chroma], ax=figax()).draw( + label_function=lambda x, *a, **kw: str( + tuple(x.charge_states)[0]), legend=False).ax + charge_separating_plot.set_title( + ""Charge-Separated\nExtracted Ion Chromatogram"", fontsize=24) + charge_separation = svguri_plot( + charge_separating_plot, bbox_inches='tight', height=5, width=9, + svg_width=""100%"") + figures.append(charge_separation) + return figures + + +def chromatogram_link(chromatogram): + id_string = str(chromatogram.id) + return Markup(""{1}"").format(id_string, str(chromatogram.key)) + + +class GlycanChromatogramReportCreator(ReportCreatorBase): + def __init__(self, database_path, analysis_id, stream=None, threshold=5): + super(GlycanChromatogramReportCreator, self).__init__( + database_path, analysis_id, stream) + self.set_template_loader(os.path.dirname(__file__)) + self.threshold = threshold + self.glycan_chromatograms = ChromatogramFilter([]) + self.unidentified_chromatograms = ChromatogramFilter([]) + + def glycan_link(self, key): + match = self.glycan_chromatograms.find_key(key) + if match is not None: + return chromatogram_link(match) + match = self.unidentified_chromatograms.find_key(key) + if match is not None: + return chromatogram_link(match) + return None + + def prepare_environment(self): + super(GlycanChromatogramReportCreator, self).prepare_environment() + self.env.filters[""logit""] = logit + self.env.filters['chromatogram_figures'] = chromatogram_figures + self.env.filters['glycan_link'] = self.glycan_link + + def make_template_stream(self): + template_obj = self.env.get_template(""overview.templ"") + + ads = serialize.AnalysisDeserializer( + self.database_connection._original_connection, + analysis_id=self.analysis_id) + + self.glycan_chromatograms = gcs = ads.load_glycan_composition_chromatograms() + # und = ads.load_unidentified_chromatograms() + self.unidentified_chromatograms = und = ChromatogramFilter( + ads.query(serialize.UnidentifiedChromatogram).filter( + serialize.UnidentifiedChromatogram.analysis_id == self.analysis_id).all()) + + if len(gcs) == 0: + self.log(""No glycan compositions were identified. Skipping report building"") + templ = Template(''' + + + +

No glycan compositions were identified

+ + + ''') + return templ.stream() + + summary_plot = summaries.GlycanChromatographySummaryGraphBuilder( + filter(lambda x: x.score > self.threshold, gcs + und)) + lcms_plot, composition_abundance_plot = summary_plot.draw(min_score=5) + + try: + lcms_plot.ax.legend_.set_visible(False) + except AttributeError: + # The legend may not have been created + pass + lcms_plot.ax.set_title(""Glycan Composition\nLC-MS Aggregated EICs"", fontsize=24) + + fig = lcms_plot.ax.figure + fig.set_figwidth(fig.get_figwidth() * 2.) + fig.set_figheight(fig.get_figheight() * 2.) + + composition_abundance_plot.ax.set_title(""Glycan Composition\nTotal Abundances"", fontsize=24) + composition_abundance_plot.ax.set_xlabel( + composition_abundance_plot.ax.get_xlabel(), fontsize=14) + + def resolve_key(key): + match = gcs.find_key(key) + if match is None: + match = und.find_key(key) + return match + + template_stream = (template_obj.stream( + analysis=ads.analysis, lcms_plot=svguri_plot( + lcms_plot.ax, bbox_inches='tight', patchless=True, + svg_width=""100%""), + composition_abundance_plot=svguri_plot( + composition_abundance_plot.ax, bbox_inches='tight', patchless=True, + svg_width=""100%""), + glycan_chromatograms=gcs, + unidentified_chromatograms=und, + resolve_key=resolve_key + )) + return template_stream +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/output/report/glycopeptide_lcmsms/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/output/report/glycopeptide_lcmsms/render.py",".py","16671","375","import os +import textwrap + +from collections import OrderedDict +from typing import Optional + +from glycopeptidepy.structure.glycan import GlycosylationType + +from glycresoft.tandem.glycopeptide.dynamic_generation.multipart_fdr import (GlycopeptideFDREstimator) +from glycresoft.tandem.target_decoy import GroupwiseTargetDecoyAnalyzer, TargetDecoyAnalyzer + +from glycresoft import serialize +from glycresoft.serialize import ( + Protein, Glycopeptide, IdentifiedGlycopeptide, + func, MSScan, DatabaseBoundOperation) + +from glycresoft.chromatogram_tree import Unmodified +from glycresoft.scoring.elution_time_grouping import ModelEnsemble as RetentionTimeEnsemble + +from glycresoft.plotting.glycan_visual_classification import ( + GlycanCompositionClassifierColorizer, + NGlycanCompositionColorizer) +from glycresoft.plotting import (figax, SmoothingChromatogramArtist) +from glycresoft.plotting.sequence_fragment_logo import glycopeptide_match_logo +from glycresoft.plotting.plot_glycoforms import ( + GlycoformLayout) +from glycresoft.plotting.spectral_annotation import TidySpectrumMatchAnnotator +from glycresoft.tandem.glycopeptide.identified_structure import IdentifiedGlycoprotein +from glycresoft.tandem.glycopeptide.scoring import LogIntensityScorer +from glycresoft.plotting.entity_bar_chart import ( + AggregatedAbundanceArtist, BundledGlycanComposition) +from glycresoft.output.report.base import ( + svguri_plot, png_plot, ReportCreatorBase, svg_plot, svg_optimizer) + +from ms_deisotope.data_source import ProcessedRandomAccessScanSource +from ms_deisotope.output import ProcessedMSFileLoader + + + +glycan_colorizer_type_map = { + GlycosylationType.n_linked: NGlycanCompositionColorizer, + GlycosylationType.glycosaminoglycan: GlycanCompositionClassifierColorizer({}, 'slateblue'), + GlycosylationType.o_linked: GlycanCompositionClassifierColorizer({}, 'slateblue') +} + + +def scale_fix_xml_transform(root): + view_box_str = root.attrib[""viewBox""] + x_start, y_start, x_end, y_end = map(float, view_box_str.split("" "")) + x_start += 0 + updated_view_box_str = "" "".join(map(str, [x_start, y_start, x_end, y_end])) + root.attrib[""viewBox""] = updated_view_box_str + fig_g = root.find("".//{http://www.w3.org/2000/svg}g[@id=\""figure_1\""]"") + fig_g.attrib[""transform""] = ""scale(1.0, 1.0)"" + return root + + +class IdentifiedGlycopeptideDescriberBase(object): + database_connection: DatabaseBoundOperation + analysis_id: int + analysis: serialize.Analysis + mzml_path: str + scan_loader: Optional[ProcessedRandomAccessScanSource] + retention_time_model: Optional[RetentionTimeEnsemble] + + def __init__(self, database_path: str, analysis_id: int, mzml_path: Optional[str]=None): + self.database_connection = DatabaseBoundOperation(database_path) + self.analysis_id = analysis_id + self.analysis = self.session.query(serialize.Analysis).get(self.analysis_id) + self.mzml_path = mzml_path + self.scan_loader = None + self.retention_time_model = None + self._make_scan_loader() + + def chromatogram_plot(self, glycopeptide: serialize.IdentifiedGlycopeptide): + ax = figax(dpi=120, figsize=(6, 3.1)) + try: + SmoothingChromatogramArtist( + glycopeptide, ax=ax, label_peaks=False, + colorizer=lambda x: ""#48afd0"").draw(legend=False, axis_font_size=10) + ax.set_xlabel(""Time (Minutes)"", fontsize=10) + ax.set_ylabel(""Relative Abundance"", fontsize=10) + ax.ticklabel_format(axis='y', scilimits=(1, 3)) + return png_plot(ax, bbox_inches='tight', img_width='100%', width=8, dpi=160) + except ValueError: + return ""
No Chromatogram Found
"" + + def flex_panel(self, content: str): + wrapper = ""
{content}
"" + return wrapper.format(content=content) + + def spectrum_match_info(self, glycopeptide: serialize.IdentifiedGlycopeptide): + spectrum_match_ref = glycopeptide.best_spectrum_match + scan_id = spectrum_match_ref.scan.scan_id + scan = self.scan_loader.get_scan_by_id(scan_id) + try: + mass_shift = spectrum_match_ref.mass_shift + except Exception: + mass_shift = Unmodified + if mass_shift.name != Unmodified.name: + mass_shift = mass_shift.convert() + else: + mass_shift = Unmodified + + match = LogIntensityScorer.evaluate( + scan, + glycopeptide.structure.convert(), + error_tolerance=self.analysis.parameters[""fragment_error_tolerance""], + mass_shift=mass_shift) + specmatch_artist = TidySpectrumMatchAnnotator(match, ax=figax(dpi=160, figsize=(6, 3))) + specmatch_artist.draw(fontsize=8, pretty=True) + specmatch_artist.add_summary_labels() + annotated_match_ax = specmatch_artist.ax + + scan_title = scan.id + if len(scan_title) > 60: + scan_title = '\n'.join(textwrap.wrap(scan_title, 60)) + + annotated_match_ax.set_title(scan_title, fontsize=11, y=1.05) + annotated_match_ax.set_ylabel( + annotated_match_ax.get_ylabel(), fontsize=10) + annotated_match_ax.set_xlabel( + annotated_match_ax.get_xlabel(), fontsize=10) + + sequence_logo_plot = glycopeptide_match_logo( + match, ax=figax(), annotation_options={""lw"": 3, ""v_step"":0.15, ""stroke_slope"": 0.1}) + + spectrum_plot = svguri_plot( + annotated_match_ax, svg_width=""100%"", bbox_inches='tight', height=3 * 1.5, + optimize=True, + width=8 * 1.5, + img_width=""100%"", + patchless=True, dpi=120) + sequence_logo_plot.ax.figure.set_figheight(2.5) + sequence_logo_plot.ax.figure.set_figwidth(8) + logo_plot = svg_plot( + sequence_logo_plot.ax, + svg_width=""100%"", + img_width=""100%"", + # xml_transform=scale_fix_xml_transform, + bbox_inches='tight', + optimize=False, + height=1, width=6, patchless=True).decode('utf8') + match.drop_peaks() + return dict( + spectrum_plot=spectrum_plot, logo_plot=logo_plot, + precursor_mass_accuracy=match.precursor_mass_accuracy(), + spectrum_match=match) + + def format_rt_prediction_interval(self, glycopeptide: serialize.IdentifiedGlycopeptide): + iv = self.retention_time_model.predict_interval(glycopeptide, 0.01) + return self.retention_time_model._truncate_interval(iv) + + def _make_scan_loader(self): + if self.mzml_path is not None: + if not os.path.exists(self.mzml_path): + raise IOError(""No such file {}"".format(self.mzml_path)) + self.scan_loader = ProcessedMSFileLoader(self.mzml_path) + else: + self.mzml_path = self.analysis.parameters['sample_path'] + if not os.path.exists(self.mzml_path): + raise IOError(( + ""No such file {}. If {} was relocated, you may need to explicily pass the"" + "" corrected file path."").format( + self.mzml_path, + self.database_connection._original_connection)) + self.scan_loader = ProcessedMSFileLoader(self.mzml_path) + + def draw_glycoforms(self, glycoprotein: IdentifiedGlycoprotein) -> str: + ax = figax() + layout = GlycoformLayout( + glycoprotein, glycoprotein.identified_glycopeptides, ax=ax) + layout.draw() + svg = layout.to_svg(scale=2.0, height_padding_scale=1.1) + svg = svg_optimizer(svg.decode('utf8')).decode('utf8') + return svg + + +class IdentifiedGlycopeptideDescriberWorker(IdentifiedGlycopeptideDescriberBase): + + def __call__(self, glycopeptide_id: int): + glycopeptide = self._glycopeptide_from_id(glycopeptide_id) + return self.spectrum_match_info(glycopeptide) + + def _glycopeptide_from_id(self, glycopeptide_id: int) -> serialize.IdentifiedGlycopeptide: + return self.database_connection.query( + IdentifiedGlycopeptide).get(glycopeptide_id) + + +class GlycopeptideDatabaseSearchReportCreator(ReportCreatorBase, IdentifiedGlycopeptideDescriberBase): + threshold: float + fdr_threshold: float + use_dynamic_display_mode: int + hypothesis_id: int + + def __init__(self, database_path, analysis_id, stream=None, threshold=5, + fdr_threshold=1, + mzml_path=None): + super(GlycopeptideDatabaseSearchReportCreator, self).__init__( + database_path, analysis_id, stream) + self.set_template_loader(os.path.dirname(__file__)) + self.mzml_path = mzml_path + self.scan_loader = None + self.threshold = threshold + self.fdr_threshold = fdr_threshold + self._total_glycopeptides = None + self.use_dynamic_display_mode = 0 + self.analysis = self.session.query(serialize.Analysis).get(self.analysis_id) + self._resolve_hypothesis_id() + self._build_protein_index() + self._make_scan_loader() + self._glycopeptide_counter = 0 + if len(self.protein_index) > 10: + self.use_dynamic_display_mode = 1 + self.fdr_estimator = self.analysis.parameters.get(""fdr_estimator"") + self.retention_time_model = self.analysis.parameters.get(""retention_time_model"") + + def _spawn(self): + return IdentifiedGlycopeptideDescriberWorker(self.database_connection, self.analysis_id, self.mzml_path) + + def _resolve_hypothesis_id(self): + self.hypothesis_id = self.analysis.hypothesis_id + hypothesis = self.session.query(serialize.GlycopeptideHypothesis).get(self.hypothesis_id) + if hypothesis is None: + self.hypothesis_id = 1 + hypothesis = self.session.query(serialize.GlycopeptideHypothesis).get( + self.hypothesis_id) + if hypothesis is None: + raise ValueError(""Could not resolve Glycopeptide Hypothesis!"") + + def prepare_environment(self): + super(GlycopeptideDatabaseSearchReportCreator, self).prepare_environment() + + def _build_protein_index(self): + hypothesis_id = self.hypothesis_id + theoretical_counts = self.session.query(Protein.name, Protein.id, func.count(Glycopeptide.id)).join( + Glycopeptide).group_by(Protein.id).filter( + Protein.hypothesis_id == hypothesis_id).all() + matched_counts = self.session.query( + Protein.name, Protein.id, func.count(IdentifiedGlycopeptide.id)).join(Protein.glycopeptides).join( + IdentifiedGlycopeptide, IdentifiedGlycopeptide.structure_id == Glycopeptide.id).group_by(Protein.id).filter( + IdentifiedGlycopeptide.ms2_score > self.threshold, + IdentifiedGlycopeptide.q_value < self.fdr_threshold, + IdentifiedGlycopeptide.analysis_id == self.analysis_id).all() + listing = [] + index = {} + for protein_name, protein_id, glycopeptide_count in theoretical_counts: + index[protein_id] = { + ""protein_name"": protein_name, + ""protein_id"": protein_id, + } + total_glycopeptides = 0 + for protein_name, protein_id, glycopeptide_count in matched_counts: + entry = index[protein_id] + entry['identified_glycopeptide_count'] = glycopeptide_count + total_glycopeptides += glycopeptide_count + listing.append(entry) + self._total_glycopeptides = total_glycopeptides + self.protein_index = sorted(listing, key=lambda x: x[""identified_glycopeptide_count""], reverse=True) + for protein_entry in self.protein_index: + protein_entry['protein'] = self.session.query(Protein).get(protein_entry[""protein_id""]) + return self.protein_index + + def iterglycoproteins(self): + n = float(len(self.protein_index)) + + for i, row in enumerate(self.protein_index, 1): + protein = row['protein'] + glycopeptides = self.session.query( + IdentifiedGlycopeptide).join(Glycopeptide).join( + Protein).filter( + IdentifiedGlycopeptide.analysis_id == self.analysis_id, + Glycopeptide.hypothesis_id == self.hypothesis_id, + IdentifiedGlycopeptide.ms2_score > self.threshold, + IdentifiedGlycopeptide.q_value < self.fdr_threshold, + Protein.id == protein.id).all() + glycoprotein = IdentifiedGlycoprotein(protein, glycopeptides) + self.status_update( + ""Processing %s (%d/%d) %0.2f%%"" % ( + protein.name, i, n, (i / n * 100))) + yield i, glycoprotein + + def site_specific_abundance_plots(self, glycoprotein: IdentifiedGlycoprotein): + axes = OrderedDict() + for glyco_type in glycoprotein.glycosylation_types: + for site in sorted(glycoprotein.glycosylation_sites_for(glyco_type)): + spanning_site = glycoprotein.site_map[glyco_type][site] + if len(spanning_site) == 0: + continue + bundle = BundledGlycanComposition.aggregate(spanning_site) + if len(bundle) == 0: + continue + ax = figax() + AggregatedAbundanceArtist( + bundle, ax=ax, colorizer=glycan_colorizer_type_map[glyco_type]).draw() + ax.set_title(""%s Glycans\nat Site %d"" % (glyco_type.name, site + 1,), fontsize=18) + axes[site, glyco_type] = svguri_plot(ax, bbox_inches='tight') + return axes + + + def fdr_estimator_plot(self): + fdr_estimator = self.fdr_estimator + if fdr_estimator is None: + return [self.flex_panel(""No FDR estimation data"")] + if isinstance(fdr_estimator, (GroupwiseTargetDecoyAnalyzer, TargetDecoyAnalyzer)): + ax = figax() + fdr_estimator.plot(ax=ax) + svg_figure = svguri_plot(ax.figure) + return [ + self.flex_panel(svg_figure) + ] + if isinstance(fdr_estimator, GlycopeptideFDREstimator): + ax = figax() + fdr_estimator.glycan_fdr.plot(ax=ax) + ax.set_title(""Glycan FDR"", size=16) + ax.figure.tight_layout() + figures = [ + ""
%s
"" % svguri_plot( + ax.figure) + ] + ax = figax() + fdr_estimator.peptide_fdr.plot(ax=ax) + ax.set_title(""Peptide FDR"", size=16) + ax.figure.tight_layout() + figures.append(""
%s
"" % + svguri_plot(ax.figure)) + return figures + return [""
Could not recognize FDR estimation data
""] + + def retention_time_model_plot(self): + figures = [] + rt_model = self.retention_time_model + if rt_model is None: + figures.append(self.flex_panel(""No retention time model found"")) + else: + ax = figax() + rt_model.plot_factor_coefficients(ax=ax) + figures.append(self.flex_panel(svg_plot(ax.figure).decode('utf8'))) + ax = figax() + rt_model.plot_residuals(ax=ax) + figures.append(self.flex_panel(svg_plot(ax.figure).decode('utf8'))) + + return figures + + def track_entry(self, glycopeptide: serialize.IdentifiedGlycopeptide): + self._glycopeptide_counter += 1 + if self._glycopeptide_counter % 15 == 0: + self.status_update( + f"" ... {self._glycopeptide_counter}/{self._total_glycopeptides} "" + f""({self._glycopeptide_counter / self._total_glycopeptides * 100:0.2f}%) glycopeptides handled"" + ) + return self._glycopeptide_counter + + def make_template_stream(self): + template_obj = self.env.get_template(""overview.templ"") + + ads = serialize.AnalysisDeserializer( + self.database_connection._original_connection, + analysis_id=self.analysis_id) + + hypothesis = ads.analysis.hypothesis + sample_run = ads.analysis.sample_run + if self.use_dynamic_display_mode: + self.status_update(""Using dynamic display mode"") + template_stream = template_obj.stream( + analysis=ads.analysis, + hypothesis=hypothesis, + sample_run=sample_run, + protein_index=self.protein_index, + glycoprotein_iterator=self.iterglycoproteins(), + renderer=self, + use_dynamic_display_mode=self.use_dynamic_display_mode) + + return template_stream +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/spectrum.py",".py","15149","397","from typing import Dict, Optional +from sqlalchemy.orm.session import object_session + +from sqlalchemy import ( + Column, Numeric, Integer, String, ForeignKey, PickleType, + Boolean, select) +from sqlalchemy.orm import relationship, backref, deferred +from sqlalchemy.ext.mutable import MutableDict, MutableList + +import numpy as np + +from ms_peak_picker import FittedPeak as MemoryFittedPeak, PeakIndex, PeakSet +from ms_deisotope import DeconvolutedPeak as MemoryDeconvolutedPeak, DeconvolutedPeakSet +from ms_deisotope.peak_set import Envelope +from ms_deisotope.averagine import ( + mass_charge_ratio) + +from ms_deisotope.data_source.common import ( + ProcessedScan, PrecursorInformation as MemoryPrecursorInformation, ChargeNotProvided) + + +from .base import (Base, Mass, HasUniqueName) +from .utils import chunkiter + + +class SampleRun(Base, HasUniqueName): + __tablename__ = ""SampleRun"" + + id = Column(Integer, primary_key=True, autoincrement=True) + + ms_scans = relationship( + ""MSScan"", backref=backref(""sample_run""), lazy='dynamic') + sample_type = Column(String(128)) + + completed = Column(Boolean(), default=False, nullable=False) + + def __repr__(self): + return ""SampleRun(id=%d, name=%s)"" % (self.id, self.name) + + +class MSScan(Base): + __tablename__ = ""MSScan"" + + id = Column(Integer, primary_key=True, autoincrement=True) + index = Column(Integer, index=True) + ms_level = Column(Integer) + scan_time = Column(Numeric(10, 5, asdecimal=False), index=True) + title = Column(String(512)) + scan_id = Column(String(512), index=True) + sample_run_id = Column(Integer, ForeignKey( + SampleRun.id, ondelete='CASCADE'), index=True) + + peak_set = relationship(""FittedPeak"", backref=""scan"", lazy=""dynamic"") + deconvoluted_peak_set = relationship( + ""DeconvolutedPeak"", backref='scan', lazy='dynamic') + + info = deferred(Column(MutableDict.as_mutable(PickleType))) + + def __repr__(self): + f = ""{}({}, {}, {}, {}"".format( + self.__class__.__name__, self.scan_id, self.ms_level, self.scan_time, + self.deconvoluted_peak_set.count()) + if self.ms_level > 1: + f = ""%s %s"" % (f, self.precursor_information) + f += "")"" + return f + + def convert(self, fitted=False, deconvoluted=True): + precursor_information = self.precursor_information + # if precursor_information is not None: + # precursor_information = precursor_information.convert() + + + session = object_session(self) + conn = session.connection() + + if fitted: + q = conn.execute(select([FittedPeak.__table__]).where( + FittedPeak.__table__.c.scan_id == self.id)).fetchall() + + peak_set_items = list( + map(make_memory_fitted_peak, q)) + + peak_set = PeakSet(peak_set_items) + peak_set._index() + peak_index = PeakIndex(np.array([], dtype=np.float64), np.array( + [], dtype=np.float64), peak_set) + else: + peak_index = PeakIndex(np.array([], dtype=np.float64), np.array( + [], dtype=np.float64), PeakSet([])) + + if deconvoluted: + q = conn.execute(select([DeconvolutedPeak.__table__]).where( + DeconvolutedPeak.__table__.c.scan_id == self.id)).fetchall() + + deconvoluted_peak_set_items = list( + map(make_memory_deconvoluted_peak, q)) + + deconvoluted_peak_set = DeconvolutedPeakSet( + deconvoluted_peak_set_items) + deconvoluted_peak_set.reindex() + else: + deconvoluted_peak_set = DeconvolutedPeakSet([]) + + info = self.info or {} + + (scan_id, scan_title, scan_ms_level, scan_time, scan_index) = session.query( + MSScan.scan_id, MSScan.title, MSScan.ms_level, MSScan.scan_time, MSScan.index).filter( + MSScan.id == self.id).first() + + scan = ProcessedScan( + scan_id, scan_title, precursor_information, int(scan_ms_level), + float(scan_time), scan_index, peak_index, deconvoluted_peak_set, + activation=info.get('activation')) + return scan + + @classmethod + def bulk_load(cls, session, ids, chunk_size: int=512, scan_cache: Optional[Dict]=None): + if scan_cache is None: + scan_cache = {} + out = scan_cache + + for chunk in chunkiter(ids, chunk_size): + id_slice = list(filter(lambda x: x not in scan_cache, + set(chunk))) + res = session.execute(cls.__table__.select().where( + cls.id.in_(id_slice))) + pinfos = PrecursorInformation.bulk_load_from_product_ids( + session, id_slice, chunk_size=chunk_size) + for self in res.fetchall(): + peak_index = None + deconvoluted_peak_set = DeconvolutedPeakSet([]) + scan = ProcessedScan( + self.scan_id, self.scan_id, pinfos.get(self.id), int(self.ms_level), + float(self.scan_time), self.index, peak_index, deconvoluted_peak_set, + activation=self.info.get('activation')) + out[self.id] = scan + return [out[i] for i in ids] + + @classmethod + def _serialize_scan(cls, scan, sample_run_id=None): + db_scan = cls( + index=scan.index, ms_level=scan.ms_level, + scan_time=float(scan.scan_time), title=scan.title, + scan_id=scan.id, sample_run_id=sample_run_id, + info={'activation': scan.activation}) + return db_scan + + @classmethod + def serialize(cls, scan, sample_run_id=None): + db_scan = cls._serialize_scan(scan, sample_run_id) + db_scan.peak_set = map(FittedPeak.serialize, scan.peak_set) + db_scan.deconvoluted_peak_set = map( + DeconvolutedPeak.serialize, scan.deconvoluted_peak_set) + return db_scan + + @classmethod + def serialize_bulk(cls, scan, sample_run_id, session, fitted=True, deconvoluted=True): + db_scan = cls._serialize_scan(scan, sample_run_id) + + session.add(db_scan) + session.flush() + + if fitted: + FittedPeak._serialize_bulk_list(scan.peak_set, db_scan.id, session) + if deconvoluted: + DeconvolutedPeak._serialize_bulk_list( + scan.deconvoluted_peak_set, db_scan.id, session) + return db_scan + + +class PrecursorInformation(Base): + __tablename__ = ""PrecursorInformation"" + + id = Column(Integer, primary_key=True) + sample_run_id = Column(Integer, ForeignKey( + SampleRun.id, ondelete='CASCADE'), index=True) + + precursor_id = Column(Integer, ForeignKey( + MSScan.id, ondelete='CASCADE'), index=True) + precursor = relationship(MSScan, backref=backref(""product_information""), + primaryjoin=""PrecursorInformation.precursor_id == MSScan.id"", + uselist=False) + product_id = Column(Integer, ForeignKey( + MSScan.id, ondelete='CASCADE'), index=True) + product = relationship(MSScan, backref=backref(""precursor_information"", uselist=False), + primaryjoin=""PrecursorInformation.product_id == MSScan.id"", + uselist=False) + neutral_mass = Mass() + charge = Column(Integer) + intensity = Column(Numeric(16, 4, asdecimal=False)) + defaulted = Column(Boolean) + orphan = Column(Boolean) + + @property + def extracted_neutral_mass(self): + return self.neutral_mass + + @property + def extracted_charge(self): + return self.charge + + @property + def extracted_intensity(self): + return self.intensity + + def __repr__(self): + return ""DBPrecursorInformation({}, {}, {})"".format( + self.precursor.scan_id, self.neutral_mass, self.charge) + + def convert(self, data_source=None): + precursor_id = None + if self.precursor is not None: + precursor_id = self.precursor.scan_id + product_id = None + if self.product is not None: + product_id = self.product.scan_id + charge = self.charge + if charge == 0: + charge = ChargeNotProvided + conv = MemoryPrecursorInformation( + mass_charge_ratio(self.neutral_mass, charge), self.intensity, charge, + precursor_id, data_source, self.neutral_mass, charge, + self.intensity, self.defaulted, self.orphan, product_scan_id=product_id) + return conv + + @classmethod + def bulk_load_from_product_ids(cls, session, ids, chunk_size: int=512, data_source=None) -> Dict[int, MemoryPrecursorInformation]: + out = {} + + for chunk in chunkiter(ids, chunk_size): + res = session.execute(cls.__table__.select().where(cls.product_id.in_(chunk))) + for self in res.fetchall(): + precursor_id = None + if self.precursor_id is not None: + precursor_id = session.execute(select([MSScan.scan_id]).where( + MSScan.id == self.precursor_id)).scalar() + + product_id = None + if self.product_id is not None: + product_id = session.execute(select([MSScan.scan_id]).where( + MSScan.id == self.product_id)).scalar() + + charge = self.charge + if charge == 0: + charge = ChargeNotProvided + + conv = MemoryPrecursorInformation( + mass_charge_ratio(self.neutral_mass, charge), self.intensity, charge, + precursor_id, data_source, self.neutral_mass, charge, + self.intensity, self.defaulted, self.orphan, product_scan_id=product_id) + out[self.product_id] = conv + return out + + @classmethod + def serialize(cls, inst, precursor, product, sample_run_id): + charge = inst.extracted_charge + if charge == ChargeNotProvided: + charge = 0 + db_pi = PrecursorInformation( + precursor_id=precursor.id, product_id=product.id, + charge=charge, intensity=inst.extracted_intensity, + neutral_mass=inst.extracted_neutral_mass, sample_run_id=sample_run_id, + defaulted=inst.defaulted, orphan=inst.orphan) + return db_pi + + +class PeakMixin(object): + mz = Mass(False) + intensity = Column(Numeric(16, 4, asdecimal=False)) + full_width_at_half_max = Column(Numeric(7, 6, asdecimal=False)) + signal_to_noise = Column(Numeric(10, 3, asdecimal=False)) + area = Column(Numeric(12, 4, asdecimal=False)) + + @classmethod + def _serialize_bulk_list(cls, peaks, scan_id, session): + out = cls._prepare_serialize_list(peaks, scan_id) + session.bulk_save_objects(out) + + @classmethod + def _prepare_serialize_list(cls, peaks, scan_id): + out = [] + for peak in peaks: + db_peak = cls.serialize(peak) + db_peak.scan_id = scan_id + out.append(db_peak) + return out + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + +def make_memory_fitted_peak(self): + return MemoryFittedPeak( + self.mz, self.intensity, self.signal_to_noise, -1, -1, + self.full_width_at_half_max, (self.area if self.area is not None else 0.)) + + +class FittedPeak(Base, PeakMixin): + __tablename__ = ""FittedPeak"" + + id = Column(Integer, primary_key=True, autoincrement=True) + scan_id = Column(Integer, ForeignKey( + MSScan.id, ondelete='CASCADE'), index=True) + + convert = make_memory_fitted_peak + + @classmethod + def serialize(cls, peak): + return cls( + mz=peak.mz, intensity=peak.intensity, signal_to_noise=peak.signal_to_noise, + full_width_at_half_max=peak.full_width_at_half_max, area=peak.area) + + +def make_memory_deconvoluted_peak(self): + return MemoryDeconvolutedPeak( + self.neutral_mass, self.intensity, self.charge, + self.signal_to_noise, -1, self.full_width_at_half_max, + self.a_to_a2_ratio, self.most_abundant_mass, self.average_mass, + self.score, Envelope( + self.envelope), self.mz, None, self.chosen_for_msms, + (self.area if self.area is not None else 0.)) + + +class DeconvolutedPeak(Base, PeakMixin): + __tablename__ = ""DeconvolutedPeak"" + + id = Column(Integer, primary_key=True, autoincrement=True) + neutral_mass = Mass(False) + average_mass = Mass(False) + most_abundant_mass = Mass(False) + + charge = Column(Integer) + + score = Column(Numeric(12, 6, asdecimal=False)) + scan_id = Column(Integer, ForeignKey( + MSScan.id, ondelete='CASCADE'), index=True) + envelope = Column(MutableList.as_mutable(PickleType)) + a_to_a2_ratio = Column(Numeric(8, 7, asdecimal=False)) + chosen_for_msms = Column(Boolean) + + def __eq__(self, other): + return (abs(self.neutral_mass - other.neutral_mass) < 1e-5) and ( + abs(self.intensity - other.intensity) < 1e-5) + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return hash((self.mz, self.intensity, self.charge)) + + convert = make_memory_deconvoluted_peak + + @classmethod + def serialize(cls, peak): + return cls( + mz=peak.mz, intensity=peak.intensity, signal_to_noise=peak.signal_to_noise, + full_width_at_half_max=peak.full_width_at_half_max, + neutral_mass=peak.neutral_mass, average_mass=peak.average_mass, + most_abundant_mass=peak.most_abundant_mass, charge=peak.charge, score=peak.score, + envelope=list(peak.envelope), a_to_a2_ratio=peak.a_to_a2_ratio, + chosen_for_msms=peak.chosen_for_msms, area=(peak.area if peak.area is not None else 0.)) + + +def serialize_scan_bunch(session, bunch, sample_run_id=None): + precursor = bunch.precursor + db_precursor = MSScan.serialize(precursor, sample_run_id=sample_run_id) + session.add(db_precursor) + db_products = [MSScan.serialize(p, sample_run_id=sample_run_id) + for p in bunch.products] + session.add_all(db_products) + session.flush() + for scan, db_scan in zip(bunch.products, db_products): + pi = scan.precursor_information + db_pi = PrecursorInformation.serialize( + pi, db_precursor, db_scan, sample_run_id) + session.add(db_pi) + session.flush() + return db_precursor, db_products + + +def serialize_scan_bunch_bulk(session, bunch, sample_run_id, ms1_fitted=True, msn_fitted=True): + precursor = bunch.precursor + db_precursor = MSScan.serialize_bulk( + precursor, sample_run_id, session, fitted=ms1_fitted) + db_products = [MSScan.serialize_bulk(p, sample_run_id, session, fitted=msn_fitted) + for p in bunch.products] + for scan, db_scan in zip(bunch.products, db_products): + pi = scan.precursor_information + db_pi = PrecursorInformation( + precursor_id=db_precursor.id, product_id=db_scan.id, + charge=pi.extracted_charge, intensity=pi.extracted_intensity, + neutral_mass=pi.extracted_neutral_mass, sample_run_id=sample_run_id) + session.add(db_pi) + session.flush() + return db_precursor, db_products +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/serializer.py",".py","31080","795","import time + +from collections import defaultdict +from typing import Dict, FrozenSet, Iterable, List, Tuple, TYPE_CHECKING +from uuid import uuid4 + +from sqlalchemy.orm import Query, aliased + +from ms_deisotope.output.common import (ScanDeserializerBase, ScanBunch) + +from glycresoft.task import TaskBase + +from .connection import DatabaseBoundOperation +from .spectrum import ( + MSScan, PrecursorInformation, SampleRun, DeconvolutedPeak) + +from .analysis import Analysis, _AnalysisParametersProps +from .chromatogram import ( + Chromatogram, + MassShiftSerializer, + CompositionGroupSerializer, + ChromatogramSolution, + GlycanCompositionChromatogram, + UnidentifiedChromatogram) + +from .hypothesis import ( + GlycanComposition, + GlycanCombinationGlycanComposition, + GlycanCombination, + Glycopeptide) + +from .tandem import ( + GlycopeptideSpectrumMatch, + GlycopeptideSpectrumSolutionSet, + SpectrumClusterBase, + GlycopeptideSpectrumCluster, + GlycanCompositionSpectrumCluster, + UnidentifiedSpectrumCluster, + GlycanCompositionChromatogramToGlycanCompositionSpectrumCluster, + UnidentifiedChromatogramToUnidentifiedSpectrumCluster) + +from .identification import ( + AmbiguousGlycopeptideGroup, + IdentifiedGlycopeptide, + IdentifiedGlycopeptideSummary) + + +if TYPE_CHECKING: + from glycresoft.tandem.glycopeptide.identified_structure import ( + IdentifiedGlycopeptide as MemoryIdentifiedGlycopeptide + ) + + +class AnalysisSerializer(DatabaseBoundOperation, TaskBase): + _analysis: Analysis + _analysis_id: int + _analysis_name: str + _seed_analysis_name: str + _peak_lookup_table: Dict[Tuple[str, DeconvolutedPeak], int] + _mass_shift_cache: MassShiftSerializer + _composition_cache: CompositionGroupSerializer + _node_peak_map: Dict + _scan_id_map: Dict[str, int] + _chromatogram_solution_id_map: Dict + _tandem_cluster_cache: Dict[FrozenSet, SpectrumClusterBase] + + def __init__(self, connection, sample_run_id, analysis_name, analysis_id=None): + DatabaseBoundOperation.__init__(self, connection) + session = self.session + self.sample_run_id = sample_run_id + + self._analysis = None + self._analysis_id = analysis_id + self._analysis_name = None + self._seed_analysis_name = analysis_name + self._peak_lookup_table = None + self._mass_shift_cache = MassShiftSerializer(session) + self._composition_cache = CompositionGroupSerializer(session) + self._node_peak_map = dict() + self._scan_id_map = self._build_scan_id_map() + self._chromatogram_solution_id_map = dict() + self._tandem_cluster_cache = dict() + + def __repr__(self): + return ""AnalysisSerializer(%s, %d)"" % (self.analysis.name, self.analysis_id) + + def set_peak_lookup_table(self, mapping: Dict[Tuple, DeconvolutedPeak]): + self._peak_lookup_table = mapping + + def build_peak_lookup_table(self, minimum_mass=500): + peak_loader = DatabaseScanDeserializer(self._original_connection, sample_run_id=self.sample_run_id) + accumulated = peak_loader.ms1_peaks_above(minimum_mass) + peak_mapping = {x[:2]: x[2] for x in accumulated} + self.set_peak_lookup_table(peak_mapping) + + def _build_scan_id_map(self) -> Dict[str, int]: + return dict(self.session.query( + MSScan.scan_id, MSScan.id).filter( + MSScan.sample_run_id == self.sample_run_id)) + + @property + def analysis(self): + if self._analysis is None: + self._construct_analysis() + return self._analysis + + @property + def analysis_id(self): + if self._analysis_id is None: + self._construct_analysis() + return self._analysis_id + + @property + def analysis_name(self): + if self._analysis_name is None: + self._construct_analysis() + return self._analysis_name + + def set_analysis_type(self, type_string): + self.analysis.analysis_type = type_string + self.session.add(self.analysis) + self.session.commit() + + def set_parameters(self, parameters: Dict): + self.analysis.parameters = parameters + self.session.add(self.analysis) + self.commit() + + def _retrieve_analysis(self): + self._analysis = self.session.query(Analysis).get(self._analysis_id) + self._analysis_name = self._analysis.name + + def _create_analysis(self): + self._analysis = Analysis( + name=self._seed_analysis_name, sample_run_id=self.sample_run_id, + uuid=str(uuid4())) + self.session.add(self._analysis) + self.session.flush() + self._analysis_id = self._analysis.id + self._analysis_name = self._analysis.name + + def _construct_analysis(self): + if self._analysis_id is not None: + self._retrieve_analysis() + else: + self._create_analysis() + + def save_chromatogram_solution(self, solution, commit=False): + result = ChromatogramSolution.serialize( + solution, self.session, analysis_id=self.analysis_id, + peak_lookup_table=self._peak_lookup_table, + mass_shift_cache=self._mass_shift_cache, + composition_cache=self._composition_cache, + scan_lookup_table=self._scan_id_map, + node_peak_map=self._node_peak_map) + try: + self._chromatogram_solution_id_map[solution.id] = result.id + except AttributeError: + pass + if commit: + self.commit() + return result + + def save_glycan_composition_chromatogram_solution(self, solution, commit=False): + try: + cluster = self.save_glycan_composition_spectrum_cluster(solution) + cluster_id = cluster.id + except AttributeError: + cluster_id = None + result = GlycanCompositionChromatogram.serialize( + solution, self.session, analysis_id=self.analysis_id, + peak_lookup_table=self._peak_lookup_table, + mass_shift_cache=self._mass_shift_cache, + composition_cache=self._composition_cache, + scan_lookup_table=self._scan_id_map, + node_peak_map=self._node_peak_map) + if cluster_id is not None: + self.session.execute( + GlycanCompositionChromatogramToGlycanCompositionSpectrumCluster.insert(), { + ""chromatogram_id"": result.id, + ""cluster_id"": cluster_id + }) + self.session.flush() + try: + self._chromatogram_solution_id_map[solution.id] = result.solution.id + except AttributeError: + pass + + if commit: + self.commit() + return result + + def save_unidentified_chromatogram_solution(self, solution, commit=False): + try: + cluster = self.save_unidentified_spectrum_cluster(solution) + cluster_id = cluster.id + except AttributeError: + cluster_id = None + result = UnidentifiedChromatogram.serialize( + solution, self.session, analysis_id=self.analysis_id, + peak_lookup_table=self._peak_lookup_table, + mass_shift_cache=self._mass_shift_cache, + composition_cache=self._composition_cache, + scan_lookup_table=self._scan_id_map, + node_peak_map=self._node_peak_map) + if cluster_id is not None: + self.session.execute( + UnidentifiedChromatogramToUnidentifiedSpectrumCluster.insert(), { + ""chromatogram_id"": result.id, + ""cluster_id"": cluster_id + }) + self.session.flush() + try: + self._chromatogram_solution_id_map[solution.id] = result.solution.id + except AttributeError: + pass + + if commit: + self.commit() + return result + + def save_glycan_composition_spectrum_cluster(self, glycan_spectrum_cluster, commit=False): + inst = GlycanCompositionSpectrumCluster.serialize( + glycan_spectrum_cluster, + self.session, + self._scan_id_map, + self._mass_shift_cache, + self.analysis_id) + if commit: + self.commit() + return inst + + def save_unidentified_spectrum_cluster(self, unidentified_spectrum_cluster, commit=False): + inst = UnidentifiedSpectrumCluster.serialize( + unidentified_spectrum_cluster, + self.session, + self._scan_id_map, + self._mass_shift_cache, + self.analysis_id) + if commit: + self.commit() + return inst + + def save_glycopeptide_identification(self, identification: 'MemoryIdentifiedGlycopeptide', + commit: bool=False): + _start_time = time.time() + if identification.chromatogram is not None: + chromatogram_solution = self.save_chromatogram_solution( + identification.chromatogram, commit=False) + chromatogram_solution_id = chromatogram_solution.id + else: + chromatogram_solution_id = None + _chromatogram_saving_elapsed = time.time() - _start_time + + # Compute the cluster key to avoid duplicating the storage of duplicate matches + cluster_key = GlycopeptideSpectrumCluster.compute_key(identification.tandem_solutions) + _cluster_key_elapsed = time.time() - (_chromatogram_saving_elapsed + _start_time) + if cluster_key in self._tandem_cluster_cache: + cluster = self._tandem_cluster_cache[cluster_key] + _cluster_serialized_elapsed = 0 + else: + cluster = GlycopeptideSpectrumCluster.serialize( + identification, self.session, self._scan_id_map, self._mass_shift_cache, + analysis_id=self.analysis_id) + self._tandem_cluster_cache[cluster_key] = cluster + _cluster_serialized_elapsed = time.time() - (_cluster_key_elapsed + + _chromatogram_saving_elapsed + _start_time) + + _total_elapsed = (_cluster_serialized_elapsed + _cluster_key_elapsed + _chromatogram_saving_elapsed) + + if _total_elapsed > 5: + _cluster_size = sum(map(len, identification.tandem_solutions)) + _chromatogram_size = len(identification.chromatogram) if identification.chromatogram else 0 + self.log(f""..... Saving {identification} took {_total_elapsed:0.2f} sec "" + f""(chromatogram {_chromatogram_saving_elapsed:0.2f}s of {_chromatogram_size} nodes,"" + f"" key {_cluster_key_elapsed:0.2f}s,"" + f"" cluster {_cluster_serialized_elapsed:0.2f}s of {_cluster_size} entries)"") + + cluster_id = cluster.id + + best_match = identification.best_spectrum_match + + inst = IdentifiedGlycopeptide.serialize( + identification, self.session, chromatogram_solution_id, cluster_id, analysis_id=self.analysis_id) + + if identification.chromatogram is not None: + apex_time = identification.apex_time + total_signal = identification.total_signal + start_time = identification.start_time + end_time = identification.end_time + weighted_neutral_mass = identification.weighted_neutral_mass + + best_spectrum_match_id = None + sset: GlycopeptideSpectrumSolutionSet = self.session.query( + GlycopeptideSpectrumSolutionSet).join(MSScan).filter( + MSScan.scan_id == best_match.scan_id, + GlycopeptideSpectrumSolutionSet.analysis_id == self.analysis_id + ).first() + + if sset is not None: + db_best_match = sset.spectrum_matches.filter( + GlycopeptideSpectrumMatch.structure_id == inst.structure_id + ).first() + if best_match is not None: + if db_best_match is not None: + best_spectrum_match_id = db_best_match.id + + if best_spectrum_match_id is None: + self.log(f""Failed to resolve best spectrum match for {identification} in the database"") + + summary = IdentifiedGlycopeptideSummary( + id=inst.id, + weighted_neutral_mass=weighted_neutral_mass, + apex_time=apex_time, + total_signal=total_signal, + start_time=start_time, + end_time=end_time, + best_spectrum_match_id=best_spectrum_match_id, + ) + self.session.add(summary) + self.session.flush() + if commit: + self.commit() + return inst + + def save_glycopeptide_identification_set(self, identification_set: Iterable['MemoryIdentifiedGlycopeptide'], + commit: bool=False): + cache = defaultdict(list) + no_chromatograms = [] + out = [] + n = len(identification_set) + i = 0 + + chromatogram_node_counter = 0 + gpsms_solution_counter = 0 + spectra_counter = 0 + for case in identification_set: + i += 1 + if i % 100 == 0: + self.log( + f""{i * 100. / n:0.2f}% glycopeptides saved. ({i}/{n}), {case.structure}:"" + f""MS2={case.ms2_score:0.2f}:{case.q_value:0.3f}, MS1={case.ms1_score:0.2f}:{case.total_signal:0.2e}"" + f""({spectra_counter} spectra, {gpsms_solution_counter} solutions, "" + f""{chromatogram_node_counter} XIC points)"" + ) + gpsms_solution_counter += sum(map(len, case.tandem_solutions)) + spectra_counter += len(case.tandem_solutions) + chromatogram_node_counter += len(case.chromatogram) if case.chromatogram is not None else 0 + saved = self.save_glycopeptide_identification(case) + if case.chromatogram is not None: + cache[case.chromatogram].append(saved) + else: + no_chromatograms.append(saved) + out.append(saved) + for chromatogram, members in cache.items(): + AmbiguousGlycopeptideGroup.serialize( + members, self.session, analysis_id=self.analysis_id) + for case in no_chromatograms: + AmbiguousGlycopeptideGroup.serialize( + [case], self.session, analysis_id=self.analysis_id) + if commit: + self.commit() + return out + + def commit(self): + self.session.commit() + + +class AnalysisDeserializer(DatabaseBoundOperation, _AnalysisParametersProps): + def __init__(self, connection: str, analysis_name=None, analysis_id=None): + DatabaseBoundOperation.__init__(self, connection) + + if analysis_name is analysis_id is None: + analysis_id = 1 + + self._analysis = None + self._analysis_id = analysis_id + self._analysis_name = analysis_name + + @property + def name(self): + return self.analysis_name + + @property + def chromatogram_scoring_model(self): + try: + return self.analysis.parameters[""scoring_model""] + except KeyError: + from glycresoft.models import GeneralScorer + return GeneralScorer + + def _retrieve_analysis(self): + if self._analysis_id is not None: + self._analysis = self.session.query(Analysis).get(self._analysis_id) + self._analysis_name = self._analysis.name + elif self._analysis_name is not None: + self._analysis = self.session.query(Analysis).filter(Analysis.name == self._analysis_name).one() + self._analysis_id = self._analysis.id + else: + raise ValueError(""No Analysis identification information provided"") + + @property + def analysis(self) -> Analysis: + if self._analysis is None: + self._retrieve_analysis() + return self._analysis + + @property + def analysis_id(self) -> int: + if self._analysis_id is None: + self._retrieve_analysis() + return self._analysis_id + + @property + def analysis_name(self) -> str: + if self._analysis_name is None: + self._retrieve_analysis() + return self._analysis_name + + @property + def parameters(self): + return self.analysis.parameters + + def load_unidentified_chromatograms(self): + from glycresoft.chromatogram_tree import ChromatogramFilter + node_type_cache = dict() + scan_id_cache = dict() + q = self.query(UnidentifiedChromatogram).filter( + UnidentifiedChromatogram.analysis_id == self.analysis_id).all() + chroma = ChromatogramFilter([c.convert( + chromatogram_scoring_model=self.chromatogram_scoring_model, + node_type_cache=node_type_cache, + scan_id_cache=scan_id_cache) for c in q]) + return chroma + + def load_glycan_composition_chromatograms(self): + from glycresoft.chromatogram_tree import ChromatogramFilter + node_type_cache = dict() + scan_id_cache = dict() + q = self.query(GlycanCompositionChromatogram).filter( + GlycanCompositionChromatogram.analysis_id == self.analysis_id).all() + chroma = ChromatogramFilter([c.convert( + chromatogram_scoring_model=self.chromatogram_scoring_model, + node_type_cache=node_type_cache, + scan_id_cache=scan_id_cache) for c in q]) + return chroma + + def load_identified_glycopeptides_for_protein(self, protein_id): + q = self.query(IdentifiedGlycopeptide).join(Glycopeptide).filter( + IdentifiedGlycopeptide.analysis_id == self.analysis_id, + Glycopeptide.protein_id == protein_id) + gps = [c.convert() for c in q] + return gps + + def load_identified_glycopeptides(self, min_q_value: float=0.2): + q = self.query(IdentifiedGlycopeptide).filter( + IdentifiedGlycopeptide.analysis_id == self.analysis_id).all() + gps = IdentifiedGlycopeptide.bulk_convert(q, min_q_value=min_q_value) + return gps + + def load_glycans_from_identified_glycopeptides(self) -> List[GlycanComposition]: + q = self.query(GlycanComposition).join( + GlycanCombinationGlycanComposition).join(GlycanCombination).join( + Glycopeptide, + Glycopeptide.glycan_combination_id == GlycanCombination.id).join( + IdentifiedGlycopeptide, + IdentifiedGlycopeptide.structure_id == Glycopeptide.id).filter( + IdentifiedGlycopeptide.analysis_id == self.analysis_id) + gcs = [c for c in q] + return gcs + + def get_glycopeptide_by_sequence(self, sequence: str) -> Query: + return self.query(IdentifiedGlycopeptide).join( + IdentifiedGlycopeptide.structure).filter( + Glycopeptide.glycopeptide_sequence == sequence) + + def get_glycopeptide_spectrum_matches(self, q_value_threshold: float=0.05) -> Query: + query = self.query(GlycopeptideSpectrumMatch).join( + GlycopeptideSpectrumSolutionSet).join( + GlycopeptideSpectrumCluster).join( + IdentifiedGlycopeptide).filter( + GlycopeptideSpectrumMatch.is_best_match, + # GlycopeptideSpectrumMatch.structure_id == IdentifiedGlycopeptide.structure_id, + GlycopeptideSpectrumMatch.q_value < q_value_threshold, + GlycopeptideSpectrumMatch.analysis_id == self.analysis_id) + return query + + def _get_glycopeptide_spectrum_matches_not_matching_owning_structure(self, q_value_threshold: float=0.05) -> Query: + GPSM_Glycopeptide = aliased(Glycopeptide) + mixed = self.query(GlycopeptideSpectrumMatch, IdentifiedGlycopeptide).join( + GlycopeptideSpectrumMatch.solution_set).join( + GlycopeptideSpectrumSolutionSet.cluster).join( + GlycopeptideSpectrumCluster.owners).join( + GPSM_Glycopeptide, + GlycopeptideSpectrumMatch.structure_id == GPSM_Glycopeptide.id + ).join( + IdentifiedGlycopeptide.structure + ).filter( + GlycopeptideSpectrumMatch.is_best_match, + GlycopeptideSpectrumMatch.q_value < q_value_threshold, + GPSM_Glycopeptide.glycopeptide_sequence != Glycopeptide.glycopeptide_sequence, + GPSM_Glycopeptide.peptide_id != Glycopeptide.peptide_id, + GlycopeptideSpectrumMatch.analysis_id == self.analysis_id + ) + return mixed + + def __repr__(self): + template = ""{self.__class__.__name__}({self.engine!r}, {self.analysis_name!r})"" + return template.format(self=self) + + +class AnalysisDestroyer(DatabaseBoundOperation): + def __init__(self, database_connection, analysis_id): + DatabaseBoundOperation.__init__(self, database_connection) + self.analysis_id = analysis_id + + def delete_chromatograms(self): + self.session.query(Chromatogram).filter( + Chromatogram.analysis_id == self.analysis_id).delete(synchronize_session=False) + self.session.flush() + + def delete_chromatogram_solutions(self): + self.session.query(ChromatogramSolution).filter( + ChromatogramSolution.analysis_id == self.analysis_id).delete(synchronize_session=False) + self.session.flush() + + def delete_glycan_composition_chromatograms(self): + self.session.query(GlycanCompositionChromatogram).filter( + GlycanCompositionChromatogram.analysis_id == self.analysis_id).delete(synchronize_session=False) + self.session.flush() + + def delete_unidentified_chromatograms(self): + self.session.query(UnidentifiedChromatogram).filter( + UnidentifiedChromatogram.analysis_id == self.analysis_id).delete(synchronize_session=False) + self.session.flush() + + def delete_ambiguous_glycopeptide_groups(self): + self.session.query(AmbiguousGlycopeptideGroup).filter( + AmbiguousGlycopeptideGroup.analysis_id == self.analysis_id).delete(synchronize_session=False) + self.session.flush() + + def delete_identified_glycopeptides(self): + self.session.query(IdentifiedGlycopeptide).filter( + IdentifiedGlycopeptide.analysis_id == self.analysis_id).delete(synchronize_session=False) + self.session.flush() + + def delete_analysis(self): + self.session.query(Analysis).filter(Analysis.id == self.analysis_id).delete(synchronize_session=False) + + def run(self): + self.delete_ambiguous_glycopeptide_groups() + self.delete_identified_glycopeptides() + self.delete_glycan_composition_chromatograms() + self.delete_unidentified_chromatograms() + self.delete_chromatograms() + self.delete_analysis() + self.session.commit() + + +def flatten(iterable): + return [y for x in iterable for y in x] + + +class DatabaseScanDeserializer(ScanDeserializerBase, DatabaseBoundOperation): + + def __init__(self, connection, sample_name=None, sample_run_id=None): + + DatabaseBoundOperation.__init__(self, connection) + + self._sample_run = None + self._sample_name = sample_name + self._sample_run_id = sample_run_id + self._iterator = None + self._scan_id_to_retention_time_cache = None + + def _intialize_scan_id_to_retention_time_cache(self): + self._scan_id_to_retention_time_cache = dict( + self.session.query(MSScan.scan_id, MSScan.scan_time).filter( + MSScan.sample_run_id == self.sample_run_id)) + + def __reduce__(self): + return self.__class__, ( + self._original_connection, self.sample_name, self.sample_run_id) + + # Sample Run Bound Handle API + + @property + def sample_run_id(self): + if self._sample_run_id is None: + self._retrieve_sample_run() + return self._sample_run_id + + @property + def sample_run(self): + if self._sample_run is None: + self._retrieve_sample_run() + return self._sample_run + + @property + def sample_name(self): + if self._sample_name is None: + self._retrieve_sample_run() + return self._sample_name + + def _retrieve_sample_run(self): + session = self.session + if self._sample_name is not None: + sr = session.query(SampleRun).filter( + SampleRun.name == self._sample_name).one() + elif self._sample_run_id is not None: + sr = session.query(SampleRun).filter( + SampleRun.id == self._sample_run_id).one() + else: + sr = session.query(SampleRun).first() + self._sample_run = sr + self._sample_run_id = sr.id + self._sample_name = sr.name + + # Scan Generator Public API + + def get_scan_by_id(self, scan_id): + q = self._get_by_scan_id(scan_id) + if q is None: + raise KeyError(scan_id) + mem = q.convert() + if mem.precursor_information: + mem.precursor_information.source = self + return mem + + def convert_scan_id_to_retention_time(self, scan_id): + if self._scan_id_to_retention_time_cache is None: + self._intialize_scan_id_to_retention_time_cache() + try: + return self._scan_id_to_retention_time_cache[scan_id] + except KeyError: + q = self.session.query(MSScan.scan_time).filter( + MSScan.scan_id == scan_id, MSScan.sample_run_id == self.sample_run_id).scalar() + self._scan_id_to_retention_time_cache[scan_id] = q + return q + + def _select_index(self, require_ms1=True): + indices_q = self.session.query(MSScan.index).filter( + MSScan.sample_run_id == self.sample_run_id).order_by(MSScan.index.asc()) + if require_ms1: + indices_q = indices_q.filter(MSScan.ms_level == 1) + indices = flatten(indices_q.all()) + return indices + + def _iterate_over_index(self, start=0, require_ms1=True): + indices = self._select_index(require_ms1) + try: + i = indices.index(start) + except ValueError: + lo = 0 + hi = len(indices) + + while lo != hi: + mid = (lo + hi) // 2 + x = indices[mid] + if x == start: + i = mid + break + elif lo == (hi - 1): + i = mid + break + elif x > start: + hi = mid + else: + lo = mid + items = indices[i:] + i = 0 + n = len(items) + while i < n: + index = items[i] + scan = self.session.query(MSScan).filter( + MSScan.index == index, + MSScan.sample_run_id == self.sample_run_id).one() + products = [pi.product for pi in scan.product_information] + yield ScanBunch(scan.convert(), [p.convert() for p in products]) + i += 1 + + def __iter__(self): + return self + + def next(self): + if self._iterator is None: + self._iterator = self._iterate_over_index() + return next(self._iterator) + + def _get_by_scan_id(self, scan_id): + q = self.session.query(MSScan).filter( + MSScan.scan_id == scan_id, MSScan.sample_run_id == self.sample_run_id).first() + return q + + def _get_scan_by_time(self, rt, require_ms1=False): + times_q = self.session.query(MSScan.scan_time).filter( + MSScan.sample_run_id == self.sample_run_id).order_by(MSScan.scan_time.asc()) + if require_ms1: + times_q = times_q.filter(MSScan.ms_level == 1) + times = flatten(times_q.all()) + try: + i = times.index(rt) + except ValueError: + lo = 0 + hi = len(times) + + while lo != hi: + mid = (lo + hi) // 2 + x = times[mid] + if x == rt: + i = mid + break + elif lo == (hi - 1): + i = mid + break + elif x > rt: + hi = mid + else: + lo = mid + scan = self.session.query(MSScan).filter( + MSScan.scan_time == times[i], + MSScan.sample_run_id == self.sample_run_id).one() + return scan + + def reset(self): + self._iterator = None + + def get_scan_by_time(self, rt, require_ms1=False): + q = self._get_scan_by_time(rt, require_ms1) + mem = q.convert() + if mem.precursor_information: + mem.precursor_information.source = self + return mem + + def _get_scan_by_index(self, index): + q = self.session.query(MSScan).filter( + MSScan.index == index, MSScan.sample_run_id == self.sample_run_id).one() + return q + + def get_scan_by_index(self, index): + mem = self._get_scan_by_index(index).convert() + if mem.precursor_information: + mem.precursor_information.source = self + return mem + + def _locate_ms1_scan(self, scan): + while scan.ms_level != 1: + scan = self._get_scan_by_index(scan.index - 1) + return scan + + def start_from_scan(self, scan_id=None, rt=None, index=None, require_ms1=True): + if scan_id is None: + if rt is not None: + scan = self._get_scan_by_time(rt) + elif index is not None: + scan = self._get_scan_by_index(index) + else: + scan = self._get_by_scan_id(scan_id) + + # We must start at an MS1 scan, so backtrack until we reach one + if require_ms1: + scan = self._locate_ms1_scan(scan) + self._iterator = self._iterate_over_index(scan.index) + return self + + # LC-MS/MS Database API + + def msms_for(self, neutral_mass, mass_error_tolerance=1e-5, start_time=None, end_time=None): + m = neutral_mass + w = neutral_mass * mass_error_tolerance + q = self.session.query(PrecursorInformation).join( + PrecursorInformation.precursor).filter( + PrecursorInformation.neutral_mass.between(m - w, m + w), + PrecursorInformation.sample_run_id == self.sample_run_id).order_by( + MSScan.scan_time) + if start_time is not None: + q = q.filter(MSScan.scan_time >= start_time) + if end_time is not None: + q = q.filter(MSScan.scan_time <= end_time) + return q + + def ms1_peaks_above(self, threshold=1000): + accumulate = [ + (x[0], x[1].convert(), x[1].id) for x in self.session.query(MSScan.scan_id, DeconvolutedPeak).join( + DeconvolutedPeak).filter( + MSScan.ms_level == 1, MSScan.sample_run_id == self.sample_run_id, + DeconvolutedPeak.neutral_mass > threshold + ).order_by(MSScan.index).yield_per(1000)] + return accumulate + + def precursor_information(self): + prec_info = self.session.query(PrecursorInformation).filter( + PrecursorInformation.sample_run_id == self.sample_run_id).all() + return prec_info +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/connection.py",".py","6041","191","import os +from typing import Callable, Union, Protocol, runtime_checkable + +from six import string_types as basestring + +from sqlalchemy import create_engine, event +from sqlalchemy.orm import sessionmaker, scoped_session +from sqlalchemy.engine import Connectable + +from sqlalchemy import exc +from sqlalchemy.engine import Engine +from sqlalchemy.orm.session import Session +from sqlalchemy.orm import Query + +from .base import Base +from .migration import Migration +from .tandem import GlycopeptideSpectrumMatch, GlycopeptideSpectrumMatchScoreSet + + +ConnectFrom = Union[str, + Connectable, + 'ConnectionRecipe', + scoped_session, + Session] + + +@runtime_checkable +class HasSession(Protocol): + session: Union[Session, scoped_session] + + +def configure_connection(connection: ConnectFrom, create_tables=True): + if isinstance(connection, basestring): + try: + eng = create_engine(connection) + except exc.ArgumentError: + eng = SQLiteConnectionRecipe(connection)() + elif isinstance(connection, Connectable): + eng = connection + elif isinstance(connection, ConnectionRecipe): + eng = connection() + elif isinstance(connection, (scoped_session, Session)): + eng = connection.get_bind() + elif isinstance(connection, HasSession): + eng = connection.session.get_bind() + create_tables = False + else: + raise ValueError( + ""Could not determine how to get a database connection from %r"" % connection) + if create_tables: + Base.metadata.create_all(bind=eng) + Migration(eng, GlycopeptideSpectrumMatch).run() + Migration(eng, GlycopeptideSpectrumMatchScoreSet).run() + return eng + + +initialize = configure_connection + +def _noop_on_connect(connection, connection_record): + pass + + +class ConnectionRecipe(object): + connection_url: str + connect_args: dict + on_connect: Callable + engine_args: dict + + def __init__(self, connection_url: str, connect_args=None, on_connect=None, **engine_args): + if connect_args is None: + connect_args = {} + if on_connect is None: + on_connect = _noop_on_connect + + self.connection_url = connection_url + self.connect_args = connect_args + self.on_connect = on_connect + self.engine_args = engine_args + + def __call__(self) -> Engine: + connection = create_engine( + self.connection_url, connect_args=self.connect_args, + **self.engine_args) + event.listens_for(connection, 'connect')(self.on_connect) + return connection + + +class SQLiteConnectionRecipe(ConnectionRecipe): + connect_args = { + 'timeout': 180, + } + + @staticmethod + def _configure_connection(dbapi_connection, connection_record): + # disable pysqlite's emitting of the BEGIN statement entirely. + # also stops it from emitting COMMIT before any DDL. + iso_level = dbapi_connection.isolation_level + dbapi_connection.isolation_level = None + try: + dbapi_connection.execute(""PRAGMA page_size = 5120;"") + dbapi_connection.execute(""PRAGMA cache_size = 12000;"") + dbapi_connection.execute(""PRAGMA temp_store = 3;"") + if not int(os.environ.get(""NOWAL"", '0')): + dbapi_connection.execute(""PRAGMA journal_mode = WAL;"") + dbapi_connection.execute(""PRAGMA wal_autocheckpoint = 100;"") + # dbapi_connection.execute(""PRAGMA foreign_keys = ON;"") + dbapi_connection.execute(""PRAGMA journal_size_limit = 1000000;"") + pass + except Exception as e: + print(e) + dbapi_connection.isolation_level = iso_level + + def __init__(self, connection_url, **engine_args): + super(SQLiteConnectionRecipe, self).__init__( + self._construct_url(connection_url), self.connect_args, self._configure_connection) + + def _construct_url(self, path): + if path.startswith(""sqlite://""): + return path + else: + return ""sqlite:///%s"" % path + + +class DatabaseBoundOperation(object): + engine: Engine + _original_connection: ConnectFrom + _sessionmaker: scoped_session + + def __init__(self, connection): + self.engine = self._configure_connection(connection) + + self._original_connection = connection + self._sessionmaker = scoped_session( + sessionmaker(bind=self.engine, autoflush=False)) + + def bridge(self, other: 'DatabaseBoundOperation'): + self.engine = other.engine + self._sessionmaker = other._sessionmaker + + def _configure_connection(self, connection: ConnectFrom): + eng = configure_connection(connection, create_tables=True) + return eng + + def __eq__(self, other): + return str(self.engine) == str(other.engine) and\ + (self.__class__ is other.__class__) + + def __hash__(self): + return hash(str(self.engine)) + + def __ne__(self, other): + return not (self == other) + + def __reduce__(self): + return self.__class__, (self._original_connection,) + + @property + def session(self): + return self._sessionmaker + + def query(self, *args) -> Query: + return self.session.query(*args) + + def _analyze_database(self): + conn = self.engine.connect() + inner = conn.connection.connection + cur = inner.cursor() + cur.execute(""analyze;"") + inner.commit() + + def _sqlite_reload_analysis_plan(self): + conn = self.engine.connect() + conn.execute(""ANALYZE sqlite_master;"") + + def _sqlite_checkpoint_wal(self): + conn = self.engine.connect() + inner = conn.connection.connection + cur = inner.cursor() + cur.execute(""PRAGMA wal_checkpoint(SQLITE_CHECKPOINT_RESTART);"") + + @property + def dialect(self): + return self.engine.dialect + + def is_sqlite(self): + return self.dialect.name == ""sqlite"" + + def close(self): + self.session.remove() + self.engine.dispose() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/analysis.py",".py","6928","190","import re +import os +from functools import partial + +from typing import Optional, TYPE_CHECKING + +from sqlalchemy import ( + Column, Integer, String, ForeignKey, PickleType, + func) + +from sqlalchemy.orm import relationship, backref, object_session +from sqlalchemy.ext.declarative import declared_attr + +import dill + +from glycresoft.serialize.base import ( + Base, HasUniqueName) + +from glycresoft.serialize.spectrum import SampleRun + +from glycresoft.serialize.hypothesis.generic import HasFiles +from glycresoft.serialize.param import HasParameters + +from ms_deisotope.data_source import ProcessedRandomAccessScanSource +from ms_deisotope.output import ProcessedMSFileLoader + +from glycresoft.structure.enums import AnalysisTypeEnum, GlycopeptideSearchStrategy + +if TYPE_CHECKING: + from glycresoft.composition_distribution_model.site_model.glycoproteome_model import GlycoproteomeModel + + +DillType = partial(PickleType, pickler=dill) + + +class _AnalysisParametersProps: + def open_ms_file(self) -> Optional[ProcessedRandomAccessScanSource]: + path = self.parameters.get(""sample_path"") + if not path: + return None + if os.path.exists(path): + return ProcessedMSFileLoader(path) + return None + + def glycosite_model_path(self) -> Optional['GlycoproteomeModel']: + from glycresoft.composition_distribution_model.site_model.glycoproteome_model import ( + GlycoproteomeModel, GlycosylationSiteModel) + + path = self.parameters.get('glycosylation_site_models_path') + if os.path.exists(path): + with open(path, 'rt', encoding='utf8') as fh: + site_models = GlycosylationSiteModel.load(fh) + target_model = GlycoproteomeModel.bind_to_hypothesis( + object_session(self), + site_models, + hypothesis_id=self.hypothesis_id, + fuzzy=True) + return target_model + return None + + @property + def mass_shifts(self): + return self.parameters.get('mass_shifts', []) + + @property + def ms1_scoring_model(self): + return self.parameters.get('scoring_model') + + @property + def msn_scoring_model(self): + return self.parameters.get('tandem_scoring_model') + + @property + def retention_time_model(self): + return self.parameters.get('retention_time_model') + + @property + def fdr_estimator(self): + return self.parameters.get('fdr_estimator') + + @property + def search_strategy(self): + strategy_str = self.parameters.get('search_strategy') + strategy = GlycopeptideSearchStrategy[strategy_str] + return strategy + + @property + def is_multiscore(self): + strategy = self.search_strategy + return strategy == GlycopeptideSearchStrategy.multipart_target_decoy_competition + + +class Analysis(Base, HasUniqueName, HasFiles, HasParameters, _AnalysisParametersProps): + __tablename__ = ""Analysis"" + + id: int = Column(Integer, primary_key=True) + sample_run_id: int = Column(Integer, ForeignKey(SampleRun.id, ondelete=""CASCADE""), index=True) + sample_run: SampleRun = relationship(SampleRun) + analysis_type: str = Column(String(128)) + status: str = Column(String(28)) + + def __init__(self, **kwargs): + self._init_parameters(kwargs) + super(Analysis, self).__init__(**kwargs) + + def __repr__(self): + sample_run = self.sample_run + if sample_run: + sample_run_name = sample_run.name + else: + sample_run_name = """" + return ""Analysis(%s, %s)"" % (self.name, sample_run_name) + + def _infer_hypothesis_id(self): + try: + hypothesis_id = self.parameters['hypothesis_id'] + return hypothesis_id + except KeyError: + session = object_session(self) + if self.analysis_type == AnalysisTypeEnum.glycopeptide_lc_msms: + from . import IdentifiedGlycopeptide, GlycopeptideHypothesis, Glycopeptide + hypothesis_id = session.query(func.distinct(GlycopeptideHypothesis.id)).join( + Glycopeptide).join( + IdentifiedGlycopeptide, + Glycopeptide.id == IdentifiedGlycopeptide.structure_id).filter( + IdentifiedGlycopeptide.analysis_id == self.id).scalar() + return hypothesis_id + elif self.analysis_type == AnalysisTypeEnum.glycan_lc_ms: + from . import GlycanComposition, GlycanCompositionChromatogram, GlycanHypothesis + hypothesis_id = session.query(func.distinct(GlycanHypothesis.id)).join(GlycanComposition).join( + GlycanCompositionChromatogram, + GlycanCompositionChromatogram.glycan_composition_id == GlycanComposition.id).filter( + GlycanCompositionChromatogram.analysis_id == self.id).scalar() + return hypothesis_id + else: + raise ValueError(self.analysis_type) + + @property + def hypothesis_id(self): + return self._infer_hypothesis_id() + + def get_hypothesis(self): + from . import GlycopeptideHypothesis, GlycanHypothesis + hypothesis_id = self.hypothesis_id + if hypothesis_id is None: + raise ValueError( + ""Analysis does not have a Hypothesis (analysis id: %r, name: %r)"" % ( + self.id, self.name)) + session = object_session(self) + if self.analysis_type == AnalysisTypeEnum.glycopeptide_lc_msms: + return session.query(GlycopeptideHypothesis).get(hypothesis_id) + elif self.analysis_type == AnalysisTypeEnum.glycan_lc_ms: + return session.query(GlycanHypothesis).get(hypothesis_id) + + hypothesis = property(get_hypothesis) + + def aggregate_identified_glycoproteins(self, glycopeptides=None): + from glycresoft.tandem.glycopeptide.identified_structure import IdentifiedGlycoprotein + from . import Protein + if glycopeptides is None: + glycopeptides = self.identified_glycopeptides.all() + + protein_index = {} + session = object_session(self) + proteins = session.query(Protein).all() + for p in proteins: + protein_index[p.id] = p + + glycoproteome = IdentifiedGlycoprotein.aggregate(glycopeptides, index=protein_index) + return glycoproteome + + + +class BoundToAnalysis(object): + + @declared_attr + def analysis_id(self): + return Column(Integer, ForeignKey(Analysis.id, ondelete=""CASCADE""), index=True) + + @declared_attr + def analysis(self): + return relationship(Analysis, backref=backref(self._collection_name(), lazy='dynamic')) + + @classmethod + def _collection_name(cls): + name = cls.__name__ + collection_name = re.sub(r""(.+?)([A-Z])"", lambda match: match.group(1).lower() + + ""_"" + match.group(2).lower(), name, 0) + 's' + return collection_name +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/identification.py",".py","18322","528","from typing import Dict, Optional +from sqlalchemy import Column, Numeric, Integer, ForeignKey, select +from sqlalchemy.orm import relationship, backref, object_session +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.ext.hybrid import hybrid_method + +from glycresoft.serialize.analysis import BoundToAnalysis + +from glycresoft.serialize.chromatogram import ChromatogramSolution, ChromatogramWrapper, CompoundMassShift, MissingChromatogramError + +from glycresoft.serialize.tandem import ( + GlycopeptideSpectrumCluster, + GlycopeptideSpectrumMatch, + GlycopeptideSpectrumSolutionSet, +) + +from glycresoft.serialize.hypothesis import Glycopeptide + +from glycresoft.tandem.chromatogram_mapping import TandemAnnotatedChromatogram +from glycresoft.chromatogram_tree import GlycopeptideChromatogram +from glycresoft.chromatogram_tree.utils import ArithmeticMapping + +from glycresoft.serialize.base import Base + + +class IdentifiedStructure(BoundToAnalysis, ChromatogramWrapper): + @declared_attr + def id(self): + return Column(Integer, primary_key=True) + + @declared_attr + def chromatogram_solution_id(self): + return Column(Integer, ForeignKey(ChromatogramSolution.id, ondelete=""CASCADE""), index=True) + + def has_chromatogram(self): + return self.chromatogram_solution_id is not None + + @declared_attr + def chromatogram(self): + return relationship(ChromatogramSolution, lazy=""select"") + + def get_chromatogram(self): + return self.chromatogram.get_chromatogram() + + @property + def total_signal(self): + try: + return self.chromatogram.total_signal + except AttributeError: + return 0 + + @property + def composition(self): + raise NotImplementedError() + + @property + def entity(self): + raise NotImplementedError() + + def bisect_mass_shift(self, mass_shift): + chromatogram = self._get_chromatogram() + new_mass_shift, new_no_mass_shift = chromatogram.bisect_mass_shift(mass_shift) + + for chrom in (new_mass_shift, new_no_mass_shift): + chrom.entity = self.entity + chrom.composition = self.entity + chrom.glycan_composition = self.glycan_composition + return new_mass_shift, new_no_mass_shift + + +class AmbiguousGlycopeptideGroup(Base, BoundToAnalysis): + __tablename__ = ""AmbiguousGlycopeptideGroup"" + + id = Column(Integer, primary_key=True) + + def __repr__(self): + return ""AmbiguousGlycopeptideGroup(%d)"" % (self.id,) + + @classmethod + def serialize(cls, members, session, analysis_id, *args, **kwargs): + inst = cls(analysis_id=analysis_id) + session.add(inst) + session.flush() + for member in members: + member.ambiguous_id = inst.id + session.add(member) + session.flush() + return inst + + def __iter__(self): + return iter(self.members) + + +class IdentifiedGlycopeptide(Base, IdentifiedStructure): + __tablename__ = ""IdentifiedGlycopeptide"" + + structure_id = Column(Integer, ForeignKey(Glycopeptide.id, ondelete=""CASCADE""), index=True) + + structure = relationship(Glycopeptide) + + ms1_score = Column(Numeric(8, 7, asdecimal=False), index=True) + ms2_score = Column(Numeric(12, 6, asdecimal=False), index=True) + q_value = Column(Numeric(8, 7, asdecimal=False), index=True) + + spectrum_cluster_id = Column(Integer, ForeignKey(GlycopeptideSpectrumCluster.id, ondelete=""CASCADE""), index=True) + + spectrum_cluster = relationship(GlycopeptideSpectrumCluster, backref=backref(""owners"", lazy=""dynamic"")) + + ambiguous_id = Column(Integer, ForeignKey(AmbiguousGlycopeptideGroup.id, ondelete=""CASCADE""), index=True) + + shared_with = relationship(AmbiguousGlycopeptideGroup, backref=backref(""members"", lazy=""dynamic"")) + + @property + def score_set(self): + """"""The :class:`~.ScoreSet` of the best MS/MS match + + Returns + ------- + :class:`~.ScoreSet` + """""" + if not self.is_multiscore(): + return None + best_match = self._best_spectrum_match + if best_match is None: + return None + return best_match.score_set + + @property + def localizations(self): + return self.best_spectrum_match.localizations + + @property + def best_spectrum_match(self) -> GlycopeptideSpectrumMatch: + return self._best_spectrum_match + + @property + def q_value_set(self): + """"""The :class:`~.FDRSet` of the best MS/MS match + + Returns + ------- + :class:`~.FDRSet` + """""" + if not self.is_multiscore(): + return None + best_match = self._best_spectrum_match + if best_match is None: + return None + return best_match.q_value_set + + def is_multiscore(self) -> bool: + """"""Check whether this match collection has been produced by summarizing a multi-score + match, rather than a single score match. + + Returns + ------- + bool + """""" + return self.spectrum_cluster.is_multiscore() + + @property + def _best_spectrum_match(self): + summary: IdentifiedGlycopeptideSummary = self._summary + if summary is not None and summary.best_spectrum_match_id is not None: + session = object_session(self) + return session.query(GlycopeptideSpectrumMatch).get(summary.best_spectrum_match_id) + + is_multiscore = self.is_multiscore() + best_match = None + if is_multiscore: + best_score = 0.0 + best_q_value = 1.0 + else: + best_score = 0.0 + for solution_set in self.spectrum_cluster: + try: + match = solution_set.solution_for(self.structure) + if is_multiscore: + q_value = match.q_value + if q_value <= best_q_value: + q_delta = abs(best_q_value - q_value) + best_q_value = q_value + if q_delta > 0.001: + best_score = match.score + best_match = match + else: + score = match.score + if score > best_score: + best_score = score + best_match = match + else: + score = match.score + if score > best_score: + best_score = score + best_match = match + except KeyError: + continue + return best_match + + @hybrid_method + def is_multiply_glycosylated(self): + return self.structure.is_multiply_glycosylated() + + @is_multiply_glycosylated.expression + def is_multiply_glycosylated(self): + expr = ( + select([Glycopeptide.is_multiply_glycosylated()]) + .where(Glycopeptide.id == IdentifiedGlycopeptide.structure_id) + .label(""is_multiply_glycosylated"") + ) + return expr + + @property + def glycan_composition(self): + return self.structure.glycan_composition + + @property + def protein_relation(self): + return self.structure.protein_relation + + @property + def start_position(self): + return self.protein_relation.start_position + + @property + def end_position(self): + return self.protein_relation.end_position + + def overlaps(self, other): + return self.protein_relation.overlaps(other.protein_relation) + + def spans(self, position): + return position in self.protein_relation + + @property + def spectrum_matches(self): + return self.spectrum_cluster.spectrum_solutions + + @classmethod + def serialize( + cls, + obj, + session, + chromatogram_solution_id, + tandem_cluster_id, + analysis_id, + build_summary: bool = False, + *args, + **kwargs, + ): + inst = cls( + chromatogram_solution_id=chromatogram_solution_id, + spectrum_cluster_id=tandem_cluster_id, + analysis_id=analysis_id, + q_value=obj.q_value, + ms2_score=obj.ms2_score, + ms1_score=obj.ms1_score, + structure_id=obj.structure.id, + ) + if build_summary: + inst._build_summary() + session.add(inst) + session.flush() + return inst + + @property + def tandem_solutions(self): + return self.spectrum_cluster.spectrum_solutions + + def mass_shift_tandem_solutions(self): + mapping = ArithmeticMapping() + for sm in self.tandem_solutions: + try: + mapping[sm.solution_for(self.structure).mass_shift] += 1 + except KeyError: + continue + return mapping + + def get_chromatogram(self, *args, **kwargs): + chromatogram = self.chromatogram.convert(*args, **kwargs) + chromatogram.chromatogram = chromatogram.chromatogram.clone(GlycopeptideChromatogram) + structure = self.structure.convert() + chromatogram.chromatogram.entity = structure + return chromatogram + + @classmethod + def bulk_convert( + cls, + iterable, + expand_shared_with: bool = True, + mass_shift_cache: Optional[Dict] = None, + scan_cache: Optional[Dict] = None, + structure_cache: Optional[Dict] = None, + peptide_relation_cache: Optional[Dict] = None, + shared_identification_cache: Optional[Dict] = None, + min_q_value: float = 0.2, + *args, + **kwargs, + ): + session = object_session(iterable[0]) + if mass_shift_cache is None: + mass_shift_cache = {m.id: m.convert() for m in session.query(CompoundMassShift).all()} + if scan_cache is None: + scan_cache = {} + if structure_cache is None: + structure_cache = {} + if peptide_relation_cache is None: + peptide_relation_cache = {} + if shared_identification_cache is None: + shared_identification_cache = {} + result = [ + obj.convert( + expand_shared_with=expand_shared_with, + mass_shift_cache=mass_shift_cache, + scan_cache=scan_cache, + structure_cache=structure_cache, + peptide_relation_cache=peptide_relation_cache, + min_q_value=min_q_value, + *args, + **kwargs, + ) + for obj in iterable + ] + return result + + def convert( + self, + expand_shared_with: bool = True, + mass_shift_cache: Optional[Dict] = None, + scan_cache: Optional[Dict] = None, + structure_cache: Optional[Dict] = None, + peptide_relation_cache: Optional[Dict] = None, + shared_identification_cache: Optional[Dict] = None, + min_q_value: float = 0.2, + *args, + **kwargs, + ): + # bind this name late to avoid circular import error + from glycresoft.tandem.glycopeptide.identified_structure import ( + IdentifiedGlycopeptide as MemoryIdentifiedGlycopeptide, + ) + + session = object_session(self) + if mass_shift_cache is None: + mass_shift_cache = {m.id: m.convert() for m in session.query(CompoundMassShift).all()} + if shared_identification_cache is None: + shared_identification_cache = dict() + if scan_cache is None: + scan_cache = dict() + if structure_cache is None: + structure_cache = dict() + if peptide_relation_cache is None: + peptide_relation_cache = dict() + if expand_shared_with and self.shared_with.members.count() > 1: + stored = list(self.shared_with) + converted = [] + for idgp in stored: + if idgp.id in shared_identification_cache: + converted.append(shared_identification_cache[idgp.id]) + else: + tmp = idgp.convert( + expand_shared_with=False, + mass_shift_cache=mass_shift_cache, + scan_cache=scan_cache, + structure_cache=structure_cache, + peptide_relation_cache=peptide_relation_cache, + shared_identification_cache=shared_identification_cache, + min_q_value=min_q_value, + *args, + **kwargs, + ) + shared_identification_cache[idgp.id] = tmp + converted.append(tmp) + for i in range(len(stored)): + converted[i].shared_with = converted[:i] + converted[i + 1 :] + for i, member in enumerate(stored): + if member.id == self.id: + return converted[i] + else: + spectrum_matches = GlycopeptideSpectrumSolutionSet.bulk_load_from_clusters( + session, + [self.spectrum_cluster_id], + mass_shift_cache=mass_shift_cache, + scan_cache=scan_cache, + structure_cache=structure_cache, + peptide_relation_cache=peptide_relation_cache, + min_q_value=min_q_value, + )[self.spectrum_cluster_id] + if structure_cache is not None: + if self.structure_id in structure_cache: + structure, _ = structure_cache[self.structure_id] + else: + structure = Glycopeptide.bulk_load( + session, + [self.structure_id], + peptide_relation_cache=peptide_relation_cache, + structure_cache=structure_cache, + )[0] + else: + structure = self.structure.convert() + + chromatogram = self.chromatogram + if chromatogram is not None: + chromatogram = self.chromatogram.convert(*args, **kwargs) + chromatogram.chromatogram = TandemAnnotatedChromatogram( + chromatogram.chromatogram.clone(GlycopeptideChromatogram) + ) + chromatogram.chromatogram.tandem_solutions.extend(spectrum_matches) + chromatogram.chromatogram.entity = structure + + inst = MemoryIdentifiedGlycopeptide(structure, spectrum_matches, chromatogram) + inst.id = self.id + shared_identification_cache[self.id] = inst + return inst + + @property + def composition(self): + return self.structure.convert() + + @property + def entity(self): + return self.structure.convert() + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + def __str__(self): + return str(self.structure) + + def has_scan(self, scan_id: str) -> bool: + return any([sset.scan.scan_id == scan_id for sset in self.tandem_solutions]) + + def get_scan(self, scan_id: str): + for sset in self.tandem_solutions: + if sset.scan.scan_id == scan_id: + return sset + raise KeyError(scan_id) + + @declared_attr + def _summary(self): + return relationship(""IdentifiedGlycopeptideSummary"", lazy=""joined"", uselist=False) + + @property + def total_signal(self): + summary = self._summary + if summary is not None: + return summary.total_signal + try: + return self.chromatogram.total_signal + except AttributeError: + return 0 + + @property + def apex_time(self): + summary = self._summary + if summary is not None and summary.apex_time is not None: + return summary.apex_time + return super().apex_time + + @property + def start_time(self): + summary = self._summary + if summary is not None and summary.start_time is not None: + return summary.start_time + return super().start_time + + @property + def end_time(self): + summary = self._summary + if summary is not None and summary.end_time is not None: + return summary.end_time + return super().end_time + + @property + def weighted_neutral_mass(self): + summary = self._summary + if summary is not None and summary.weighted_neutral_mass is not None: + return summary.weighted_neutral_mass + return super().weighted_neutral_mass + + def _build_summary(self): + if self._summary is not None: + return + session = object_session(self) + + try: + apex_time = self.apex_time + total_signal = self.total_signal + start_time = self.start_time + end_time = self.end_time + except MissingChromatogramError: + apex_time = total_signal = start_time = end_time = None + best_spectrum_match_id = self.best_spectrum_match.id + + summary = IdentifiedGlycopeptideSummary( + id=self.id, + weighted_neutral_mass=self.weighted_neutral_mass, + apex_time=apex_time, + total_signal=total_signal, + start_time=start_time, + end_time=end_time, + best_spectrum_match_id=best_spectrum_match_id, + ) + session.add(summary) + return summary + + +class IdentifiedGlycopeptideSummary(Base): + __tablename__ = ""IdentifiedGlycopeptideSummary"" + + id = Column(Integer, ForeignKey(IdentifiedGlycopeptide.id), primary_key=True) + + weighted_neutral_mass = Column(Numeric(12, 6, asdecimal=False), index=True) + apex_time = Column(Numeric(12, 6, asdecimal=False), index=True) + total_signal = Column(Numeric(12, 6, asdecimal=False), index=True) + start_time = Column(Numeric(12, 6, asdecimal=False), index=True) + end_time = Column(Numeric(12, 6, asdecimal=False), index=True) + best_spectrum_match_id = Column( + Integer, ForeignKey(GlycopeptideSpectrumMatch.id, ondelete=""CASCADE""), index=True, nullable=True + ) + + def __repr__(self): + return ( + f""{self.__class__.__name__}(id={self.id}, weighted_neutral_mass={self.weighted_neutral_mass}, apex_time={self.apex_time}, "" + f""total_signal={self.total_signal}, start_time={self.start_time}, end_time={self.end_time}, "" + f""best_spectrum_match_id={self.best_spectrum_match_id})"" + ) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/migration.py",".py","1285","38"," +from typing import Type +from sqlalchemy.engine import Connection + +from glycresoft.task import log_handle + +from .base import Base +from .utils import has_column + + +class Migration: + connection: Connection + tp: Type[Base] + + def __init__(self, connection: Connection, tp: Type[Base]): + self.connection = connection + self.tp = tp + + def add_column(self, prop): + log_handle.log(f""Adding column {prop} for {self.tp}"") + column_name = str(prop.compile(dialect=self.connection.dialect)).split('.')[-1] + column_type = prop.type.compile(self.connection.dialect) + migration = prop.info['needs_migration'] + if migration['default'] is None: + self.connection.execute( + f'ALTER TABLE {self.tp.__tablename__} ADD COLUMN {column_name} {column_type};') + else: + self.connection.execute( + f'ALTER TABLE {self.tp.__tablename__} ADD COLUMN {column_name} {column_type} DEFAULT {migration[""default""]};') + + def needs_migration(self): + for prop in self.tp.__mapper__.columns: + if prop.info.get(""needs_migration"") and not has_column(self.connection, self.tp.__tablename__, prop.name): + self.add_column(prop) + + def run(self): + self.needs_migration() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/__init__.py",".py","1742","65","from sqlalchemy import exc, func +from sqlalchemy.orm.session import object_session + +from glycresoft.serialize.base import Base + +from glycresoft.serialize.connection import DatabaseBoundOperation, ConnectFrom + +from glycresoft.serialize.spectrum import ( + SampleRun, + MSScan, + PrecursorInformation, + DeconvolutedPeak) + +from glycresoft.serialize.analysis import ( + Analysis, + BoundToAnalysis, + AnalysisTypeEnum) + +from glycresoft.serialize.chromatogram import ( + ChromatogramTreeNode, + Chromatogram, + ChromatogramSolution, + MassShift, + CompositionGroup, + CompoundMassShift, + UnidentifiedChromatogram, + GlycanCompositionChromatogram, + ChromatogramSolutionMassShiftedToChromatogramSolution) + +from glycresoft.serialize.tandem import ( + GlycopeptideSpectrumCluster, + GlycopeptideSpectrumMatch, + GlycopeptideSpectrumSolutionSet, + GlycanCompositionSpectrumCluster, + GlycanCompositionSpectrumSolutionSet, + GlycanCompositionSpectrumMatch, + UnidentifiedSpectrumCluster, + UnidentifiedSpectrumSolutionSet, + UnidentifiedSpectrumMatch, + GlycopeptideSpectrumMatchScoreSet, + ) + +from glycresoft.serialize.identification import ( + IdentifiedGlycopeptide, + AmbiguousGlycopeptideGroup) + +from glycresoft.serialize.serializer import ( + AnalysisSerializer, + AnalysisDeserializer, + DatabaseScanDeserializer, + DatabaseBoundOperation) + +from glycresoft.serialize.hypothesis import * + +# from glycresoft.serialize.migration import ( +# GlycanCompositionChromatogramAnalysisSerializer, +# GlycopeptideMSMSAnalysisSerializer) + +from glycresoft.serialize import config + +import sys +from glycresoft.serialize import spectrum + +sys.modules['ms_deisotope.output.db'] = spectrum +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/utils.py",".py","9664","332","import os +from copy import copy +from typing import Sequence +from uuid import uuid4 +import warnings +from sqlalchemy import create_engine, Table +from sqlalchemy.exc import OperationalError, ProgrammingError +from sqlalchemy.sql import ClauseElement +from sqlalchemy.engine.url import make_url +from sqlalchemy.engine.interfaces import Dialect +from sqlalchemy.engine import Connection + +from sqlalchemy.orm.session import object_session +from sqlalchemy.orm.exc import UnmappedInstanceError + +from glycresoft.task import log_handle + + +def get_or_create(session, model, defaults=None, **kwargs): + instance = session.query(model).filter_by(**kwargs).first() + if instance: + return instance, False + else: + params = dict((k, v) for k, v in kwargs.items() if not isinstance(v, ClauseElement)) + params.update(defaults or {}) + instance = model(**params) + session.add(instance) + return instance, True + + +#: Adapted from sqlalchemy-utils + +def get_bind(obj): + if hasattr(obj, 'bind'): + conn = obj.bind + else: + try: + conn = object_session(obj).bind + except UnmappedInstanceError: + conn = obj + + if not hasattr(conn, 'execute'): + raise TypeError( + 'This method accepts only Session, Engine, Connection and ' + 'declarative model objects.' + ) + return conn + + +def quote(mixed, ident): + """""" + Conditionally quote an identifier. + """""" + if isinstance(mixed, Dialect): + dialect = mixed + else: + dialect = get_bind(mixed).dialect + return dialect.preparer(dialect).quote(ident) + + +def database_exists(url): + """"""Check if a database exists. + + Parameters + ---------- + url: A SQLAlchemy engine URL. + + Returns + ------- + bool + + References + ---------- + http://sqlalchemy-utils.readthedocs.org/en/latest/_modules/sqlalchemy_utils/functions/database.html#database_exists + """""" + + url = copy(make_url(url)) + database = url.database + if url.drivername.startswith('postgres'): + url.database = 'template1' + else: + url.database = None + + engine = create_engine(url) + + if engine.dialect.name == 'postgresql': + text = ""SELECT 1 FROM \""pg_database\"" WHERE datname='%s'"" % database + return bool(engine.execute(text).scalar()) + + elif engine.dialect.name == 'mysql': + text = (""SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA "" + ""WHERE SCHEMA_NAME = '%s'"" % database) + return bool(engine.execute(text).scalar()) + + elif engine.dialect.name == 'sqlite': + return database is None or os.path.exists(database) + + else: + text = 'SELECT 1' + try: + url.database = database + engine = create_engine(url) + engine.execute(text) + return True + + except (ProgrammingError, OperationalError): + return False + + +def get_absolute_uri_for_session(session): + engine = session.get_bind() + url_ = engine.url + if url_.drivername.startswith('sqlite'): + database_path = url_.database + abs_database_path = os.path.abspath(database_path) + abs_database_path = '/'.join(abs_database_path.split(os.sep)) + return make_url(""sqlite:///%s"" % abs_database_path) + else: + return make_url(url_) + + +def get_uri_for_instance(model_obj): + session = object_session(model_obj) + uri = get_absolute_uri_for_session(session) + model_name = model_obj.__class__.__name__ + model_key = model_obj.id + + qstring = ""?%s=%d"" % (model_name, model_key) + + return str(uri) + qstring + + +def get_parts_from_uri(uri): + database, spec = uri.split(""?"", 1) + model, pk = spec.split(""="") + return database, model, pk + + +def create_database(url, encoding='utf8', template=None): + """"""Issue the appropriate CREATE DATABASE statement. + + Parameters + ---------- + url: str + A SQLAlchemy engine URL. + encoding: str + The encoding to create the database as. + template: str + The name of the template from which to create the new database. + + References + ---------- + http://sqlalchemy-utils.readthedocs.org/en/latest/_modules/sqlalchemy_utils/functions/database.html#create_database + + """""" + + url = copy(make_url(url)) + + database = url.database + + if url.drivername.startswith('postgresql'): + url.database = 'template1' + elif not url.drivername.startswith('sqlite'): + url.database = None + + engine = create_engine(url) + + if engine.dialect.name == 'postgresql': + if engine.driver == 'psycopg2': + from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT + engine.raw_connection().set_isolation_level( + ISOLATION_LEVEL_AUTOCOMMIT + ) + + if not template: + template = 'template0' + + text = ""CREATE DATABASE {0} ENCODING '{1}' TEMPLATE {2}"".format( + quote(engine, database), + encoding, + quote(engine, template) + ) + engine.execute(text) + + elif engine.dialect.name == 'mysql': + text = ""CREATE DATABASE {0} CHARACTER SET = '{1}'"".format( + quote(engine, database), + encoding + ) + engine.execute(text) + + elif engine.dialect.name == 'sqlite' and database != ':memory:': + open(database, 'w').close() + + else: + text = 'CREATE DATABASE {0}'.format(quote(engine, database)) + engine.execute(text) + return engine + + +def drop_database(url): + """"""Issue the appropriate DROP DATABASE statement. + + Parameters + ---------- + url: str + + References + ---------- + http://sqlalchemy-utils.readthedocs.org/en/latest/_modules/sqlalchemy_utils/functions/database.html#drop_database + """""" + + url = copy(make_url(url)) + + database = url.database + + if url.drivername.startswith('postgresql'): + url.database = 'template1' + elif not url.drivername.startswith('sqlite'): + url.database = None + + engine = create_engine(url) + + if engine.dialect.name == 'sqlite' and url.database != ':memory:': + os.remove(url.database) + + elif engine.dialect.name == 'postgresql' and engine.driver == 'psycopg2': + from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT + engine.raw_connection().set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) + + # Disconnect all users from the database we are dropping. + version = list( + map( + int, + engine.execute('SHOW server_version').first()[0].split('.') + ) + ) + pid_column = ( + 'pid' if (version[0] >= 9 and version[1] >= 2) else 'procpid' + ) + text = ''' + SELECT pg_terminate_backend(pg_stat_activity.%(pid_column)s) + FROM pg_stat_activity + WHERE pg_stat_activity.datname = '%(database)s' + AND %(pid_column)s <> pg_backend_pid(); + ''' % {'pid_column': pid_column, 'database': database} + engine.execute(text) + + # Drop the database. + text = 'DROP DATABASE {0}'.format(quote(engine, database)) + engine.execute(text) + + else: + text = 'DROP DATABASE {0}'.format(quote(engine, database)) + engine.execute(text) + + +class toggle_indices(object): + + def __init__(self, session, table): + if isinstance(table, type): + table = table.__table__ + self.table = table + self.session = session + + def drop(self): + for index in self.table.indexes: + # log_handle.log(""Dropping Index %r"" % index) + try: + conn = self.session.connection() + index.drop(conn) + self.session.commit() + except (OperationalError, ProgrammingError) as e: + self.session.rollback() + log_handle.error(""An error occurred during index.drop for %r"" % index, exception=e) + + def create(self): + for index in self.table.indexes: + try: + conn = self.session.connection() + index.create(conn) + self.session.commit() + except (OperationalError, ProgrammingError) as e: + self.session.rollback() + log_handle.error(""An error occurred during index.create for %r"" % index, exception=e) + + +def temp_table(table, metdata=None): + if metdata is None: + if hasattr(table, ""metadata""): + metadata = table.metadata + else: + from glycresoft.serialize import Base + metadata = Base.metadata + if hasattr(table, ""__table__""): + table = table.__table__ + cols = [c.copy() for c in table.columns] + constraints = [c.copy() for c in table.constraints] + return Table(""TempTable_%s"" % str(uuid4()), metadata, *(cols + constraints)) + + +def indices(table): + return {i.name: i for i in table.indexes} + + +def get_index(table, col_name): + for i in table.indexes: + if col_name in i.columns: + return i + + +def chunkiter(ids: Sequence, chunk_size: int=512): + n = len(ids) + for i in range(0, n + chunk_size, chunk_size): + yield ids[i:i + chunk_size] + + +def has_column(connection: Connection, tablename: str, column: str) -> bool: + if connection.dialect.driver in (""sqlite"", ""pysqlite""): + for col in connection.execute(f""PRAGMA table_info('{tablename}')"").fetchall(): + if col[1] == column: + return True + return False + else: + warnings.warn(""Could not determine how to check if column exists!"") + return False + + +def needs_migration(colprop, default=None): + colprop.info['needs_migration'] = {'default': default} + return colprop +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/chromatogram.py",".py","44344","1223","from array import array +from collections import Counter + +import numpy as np + +from sqlalchemy import ( + Column, Numeric, Integer, String, ForeignKey, + Table, select, join, alias, bindparam) +from sqlalchemy.orm import relationship, backref, object_session, deferred +from sqlalchemy.ext.associationproxy import association_proxy +from sqlalchemy.orm.collections import attribute_mapped_collection +from sqlalchemy.ext import baked + +from glycresoft.chromatogram_tree import ( + ChromatogramTreeNode as MemoryChromatogramTreeNode, + ChromatogramTreeList, + Chromatogram as MemoryChromatogram, + MassShift as MemoryMassShift, + CompoundMassShift as MemoryCompoundMassShift, + GlycanCompositionChromatogram as MemoryGlycanCompositionChromatogram, + ChromatogramInterface, SimpleEntityChromatogram) + +from glycresoft.chromatogram_tree.chromatogram import MIN_POINTS_FOR_CHARGE_STATE +from glycresoft.chromatogram_tree.utils import ArithmeticMapping + +from glycresoft.scoring import ( + ChromatogramSolution as MemoryChromatogramSolution) +from glycresoft.models import GeneralScorer + +from .analysis import BoundToAnalysis +from .hypothesis import GlycanComposition + +from .spectrum import ( + Base, DeconvolutedPeak, MSScan, Mass, make_memory_deconvoluted_peak) + +from glypy.composition.base import formula +from glypy import Composition + +try: + trapezoid = np.trapz +except AttributeError: + trapezoid = np.trapezoid + + +bakery = baked.bakery() + + +def extract_key(obj): + try: + return obj._key() + except AttributeError: + if obj is None: + return obj + return str(obj) + + +class SimpleSerializerCacheBase(object): + _model_class = None + + def __init__(self, session, store=None): + if store is None: + store = dict() + self.session = session + self.store = store + + def extract_key(self, obj): + return extract_key(obj) + + def serialize(self, obj, *args, **kwargs): + if obj is None: + return None + try: + db_obj = self.store[self.extract_key(obj)] + return db_obj + except KeyError: + db_obj = self._model_class.serialize(obj, self.session, *args, **kwargs) + self.store[self.extract_key(db_obj)] = db_obj + return db_obj + + def __getitem__(self, obj): + return self.serialize(obj) + + +class MassShift(Base): + __tablename__ = ""MassShift"" + + id = Column(Integer, primary_key=True, autoincrement=True) + name = Column(String(64), index=True, unique=True) + composition = Column(String(128)) + tandem_composition = deferred(Column(String(128))) + + _hash = None + _mass = None + _tandem_mass = None + + @property + def mass(self): + if self._mass is None: + self._mass = Composition(str(self.composition)).mass + return self._mass + + @property + def tandem_mass(self): + if self._tandem_mass is None: + if self.tandem_composition: + self._tandem_mass = Composition(str(self.tandem_composition)).mass + else: + self._tandem_mass = 0.0 + return self._tandem_mass + + def convert(self): + try: + tandem_composition = Composition(str(self.tandem_composition)) + except Exception: + tandem_composition = None + return MemoryMassShift( + str(self.name), Composition(str(self.composition)), tandem_composition) + + @classmethod + def serialize(cls, obj, session, *args, **kwargs): + shift = session.query(MassShift).filter(MassShift.name == obj.name).all() + if shift: + return shift[0] + else: + db_obj = MassShift( + name=obj.name, composition=formula(obj.composition), + tandem_composition=formula(obj.tandem_composition)) + session.add(db_obj) + session.flush() + return db_obj + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + def _key(self): + return self.name + + def __eq__(self, other): + return self.name == extract_key(other) + + def __hash__(self): + if self._hash is None: + self._hash = hash(self.name) + return self._hash + + +class CompoundMassShift(Base): + __tablename__ = ""CompoundMassShift"" + + id = Column(Integer, primary_key=True, autoincrement=True) + name = Column(String(64), index=True, unique=True) + + counts = association_proxy( + ""_counts"", ""count"", creator=lambda k, v: MassShiftToCompoundMassShift(individual_id=k.id, count=v)) + + _mass = None + _tandem_mass = None + + @property + def mass(self): + if self._mass is None: + self._mass = sum([k.mass * v for k, v in self.counts.items()]) + return self._mass + + @property + def tandem_mass(self): + if self._tandem_mass is None: + self._tandem_mass = sum([k.tandem_mass * v for k, v in self.counts.items()]) + return self._tandem_mass + + def convert(self): + return MemoryCompoundMassShift({k.convert(): v for k, v in self.counts.items()}) + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + @classmethod + def serialize(cls, obj, session, *args, **kwargs): + shift = session.query(CompoundMassShift).filter(CompoundMassShift.name == obj.name).all() + if shift: + return shift[0] + else: + db_obj = CompoundMassShift(name=obj.name) + session.add(db_obj) + session.flush() + if isinstance(obj, MemoryMassShift): + db_member = MassShift.serialize(obj, session, *args, **kwargs) + db_obj.counts[db_member] = 1 + else: + for member, count in obj.counts.items(): + db_member = MassShift.serialize(member, session, *args, **kwargs) + db_obj.counts[db_member] = count + session.add(db_obj) + session.flush() + return db_obj + + def _key(self): + return self.name + + +class MassShiftToCompoundMassShift(Base): + __tablename__ = ""MassShiftToCompoundMassShift"" + + compound_id = Column(Integer, ForeignKey(CompoundMassShift.id, ondelete=""CASCADE""), index=True, primary_key=True) + individual_id = Column(Integer, ForeignKey(MassShift.id, ondelete='CASCADE'), index=True, primary_key=True) + individual = relationship(MassShift) + compound = relationship(CompoundMassShift, backref=backref( + ""_counts"", collection_class=attribute_mapped_collection(""individual""), + cascade=""all, delete-orphan"")) + + count = Column(Integer) + + +class MassShiftSerializer(SimpleSerializerCacheBase): + _model_class = CompoundMassShift + + def extract_key(self, obj): + return obj.name + + +def _create_chromatogram_tree_node_branch(x): + return ChromatogramTreeNodeBranch(child_id=x.id) + + +class ChromatogramTreeNode(Base, BoundToAnalysis): + __tablename__ = ""ChromatogramTreeNode"" + + id = Column(Integer, primary_key=True, autoincrement=True) + node_type_id = Column(Integer, ForeignKey(CompoundMassShift.id, ondelete='CASCADE'), index=True) + scan_id = Column(Integer, ForeignKey(MSScan.id, ondelete='CASCADE'), index=True) + retention_time = Column(Numeric(8, 4, asdecimal=False), index=True) + neutral_mass = Mass() + + scan = relationship(MSScan) + node_type = relationship(CompoundMassShift, lazy='joined') + + children = association_proxy(""_children"", ""child"", creator=_create_chromatogram_tree_node_branch) + + members = relationship(DeconvolutedPeak, secondary=lambda: ChromatogramTreeNodeToDeconvolutedPeak, lazy=""subquery"") + + def charge_states(self): + u = set() + u.update({p.charge for p in self.members}) + for child in self.children: + u.update(child.charge_states()) + return u + + @classmethod + def _convert(cls, session, id, node_type_cache=None, scan_id_cache=None): + if node_type_cache is None: + node_type_cache = dict() + if scan_id_cache is None: + scan_id_cache = dict() + + node_table = cls.__table__ + attribs = session.execute(node_table.select().where(node_table.c.id == id)).fetchone() + + peak_table = DeconvolutedPeak.__table__ + + selector = select([DeconvolutedPeak.__table__]).select_from( + join(peak_table, ChromatogramTreeNodeToDeconvolutedPeak)).where( + ChromatogramTreeNodeToDeconvolutedPeak.c.node_id == id) + + members = session.execute(selector).fetchall() + + try: + scan_id = scan_id_cache[attribs.scan_id] + except KeyError: + selector = select([MSScan.__table__.c.scan_id]).where(MSScan.__table__.c.id == attribs.scan_id) + scan_id = session.execute(selector).fetchone() + scan_id_cache[attribs.scan_id] = scan_id + + members = [make_memory_deconvoluted_peak(m) for m in members] + + try: + node_type = node_type_cache[attribs.node_type_id] + except KeyError: + shift = session.query(CompoundMassShift).get(attribs.node_type_id) + node_type = shift.convert() + node_type_cache[attribs.node_type_id] = node_type + + children_ids = session.query(ChromatogramTreeNodeBranch.child_id).filter( + ChromatogramTreeNodeBranch.parent_id == id) + children = [cls._convert(session, i[0], node_type_cache) for i in children_ids] + + return MemoryChromatogramTreeNode( + attribs.retention_time, scan_id, children, members, + node_type) + + def _get_child_nodes(self, session): + query = bakery(lambda session: session.query(ChromatogramTreeNode).join( + ChromatogramTreeNodeBranch.child).filter( + ChromatogramTreeNodeBranch.parent_id == bindparam(""parent_id""))) + result = query(session).params(parent_id=self.id).all() + return result + + def _get_peaks(self, session): + query = bakery(lambda session: session.query(DeconvolutedPeak).join( + ChromatogramTreeNodeToDeconvolutedPeak).filter( + ChromatogramTreeNodeToDeconvolutedPeak.c.node_id == bindparam(""node_id""))) + result = query(session).params(node_id=self.id).all() + return result + + def convert(self, node_type_cache=None, scan_id_cache=None): + if scan_id_cache is not None: + try: + scan_id = scan_id_cache[self.scan_id] + except KeyError: + scan_id = self.scan.scan_id + scan_id_cache[self.scan_id] = scan_id + else: + scan_id = self.scan.scan_id + if node_type_cache is not None: + try: + node_type = node_type_cache[self.node_type_id] + except KeyError: + node_type = self.node_type.convert() + node_type_cache[self.node_type_id] = node_type + else: + node_type = self.node_type.convert() + + session = object_session(self) + # children = self.children + children = self._get_child_nodes(session) + # peaks = self.members + peaks = self._get_peaks(session) + + inst = MemoryChromatogramTreeNode( + self.retention_time, scan_id, [ + child.convert(node_type_cache, scan_id_cache) for child in children], + [p.convert() for p in peaks], + node_type) + return inst + + @classmethod + def serialize(cls, obj, session, analysis_id, peak_lookup_table=None, mass_shift_cache=None, + scan_lookup_table=None, node_peak_map=None, *args, **kwargs): + if mass_shift_cache is None: + mass_shift_cache = MassShiftSerializer(session) + inst = ChromatogramTreeNode( + scan_id=scan_lookup_table[obj.scan_id], retention_time=obj.retention_time, + analysis_id=analysis_id) + nt = mass_shift_cache.serialize(obj.node_type) + inst.node_type_id = nt.id + + session.add(inst) + session.flush() + + if peak_lookup_table is not None: + member_ids = [] + blocked = 0 + for member in obj.members: + peak_id = peak_lookup_table[obj.scan_id, member] + node_peak_key = (inst.id, peak_id) + if node_peak_key in node_peak_map: + blocked += 1 + continue + node_peak_map[node_peak_key] = True + member_ids.append(peak_id) + + if len(member_ids): + session.execute(ChromatogramTreeNodeToDeconvolutedPeak.insert(), [ # pylint: disable=no-value-for-parameter + {'node_id': inst.id, 'peak_id': member_id} for member_id in member_ids]) + elif blocked == 0: + raise Exception(""No Peaks Saved"") + + children = [cls.serialize( + child, session, + analysis_id=analysis_id, + peak_lookup_table=peak_lookup_table, + mass_shift_cache=mass_shift_cache, + scan_lookup_table=scan_lookup_table, + node_peak_map=node_peak_map, + *args, **kwargs) for child in obj.children] + branches = [ + ChromatogramTreeNodeBranch(parent_id=inst.id, child_id=child.id) + for child in children + ] + assert len(branches) == len(obj.children) + session.add_all(branches) + session.add(inst) + # assert len(inst.children) == len(obj.children) + session.flush() + return inst + + def _total_intensity_query(self, session): + session.query() + + +class ChromatogramTreeNodeBranch(Base): + __tablename__ = ""ChromatogramTreeNodeBranch"" + + parent_id = Column(Integer, ForeignKey(ChromatogramTreeNode.id, ondelete=""CASCADE""), index=True, primary_key=True) + child_id = Column(Integer, ForeignKey(ChromatogramTreeNode.id, ondelete=""CASCADE""), index=True, primary_key=True) + child = relationship(ChromatogramTreeNode, backref=backref( + ""parent""), foreign_keys=[child_id]) + parent = relationship(ChromatogramTreeNode, backref=backref( + ""_children"", lazy='subquery'), + foreign_keys=[parent_id]) + + def __repr__(self): + return ""ChromatogramTreeNodeBranch(%r, %r)"" % (self.parent_id, self.child_id) + + +ChromatogramTreeNodeToDeconvolutedPeak = Table( + ""ChromatogramTreeNodeToDeconvolutedPeak"", Base.metadata, + Column(""node_id"", Integer, ForeignKey( + ChromatogramTreeNode.id, ondelete='CASCADE'), primary_key=True), + Column(""peak_id"", Integer, ForeignKey( + DeconvolutedPeak.id, ondelete=""CASCADE""), primary_key=True)) + + +class Chromatogram(Base, BoundToAnalysis): + __tablename__ = ""Chromatogram"" + + _total_signal_cache = None + + id = Column(Integer, primary_key=True, autoincrement=True) + neutral_mass = Mass() + + @property + def composition(self): + return None + + start_time = Column(Numeric(8, 4, asdecimal=False), index=True) + end_time = Column(Numeric(8, 4, asdecimal=False), index=True) + + nodes = relationship(ChromatogramTreeNode, secondary=lambda: ChromatogramToChromatogramTreeNode) + + @property + def mass_shifts(self): + session = object_session(self) + return self._mass_shifts_query(session) + + def _mass_shifts_query(self, session): + # (root_peaks_join, branch_peaks_join, + # anode, bnode, apeak) = _mass_shifts_query_inner + + # branch_node_info = select([anode.c.node_type_id, anode.c.retention_time]).where( + # ChromatogramToChromatogramTreeNode.c.chromatogram_id == self.id + # ).select_from(branch_peaks_join) + + # root_node_info = select([anode.c.node_type_id, anode.c.retention_time]).where( + # ChromatogramToChromatogramTreeNode.c.chromatogram_id == self.id + # ).select_from(root_peaks_join) + + # all_node_info_q = root_node_info.union_all(branch_node_info).order_by( + # anode.c.retention_time) + + # all_node_info = session.execute(all_node_info_q).fetchall() + + all_node_info = session.execute(_mass_shift_query_stmt, dict(id=self.id)).fetchall() + + node_type_ids = set() + for node_type_id, rt in all_node_info: + node_type_ids.add(node_type_id) + + node_types = [] + for ntid in node_type_ids: + node_types.append(session.query(CompoundMassShift).get(ntid).convert()) + return node_types + + def mass_shift_signal_fractions(self): + session = object_session(self) + return self._mass_shift_signal_fraction_query(session) + + def bisect_mass_shift(self, mass_shift): + session = object_session(self) + + (root_peaks_join, branch_peaks_join, + anode, bnode, apeak) = _mass_shifts_query_inner + root_node_info = select( + [anode.c.node_type_id, anode.c.retention_time, apeak.c.intensity]).where( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == self.id + ).select_from(root_peaks_join) + + branch_node_info = select( + [anode.c.node_type_id, anode.c.retention_time, apeak.c.intensity]).where( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == self.id + ).select_from(branch_peaks_join) + + all_node_info_q = root_node_info.union_all(branch_node_info).order_by(anode.c.retention_time) + mass_shift_id = session.query(CompoundMassShift.id).filter(CompoundMassShift.name == mass_shift.name).scalar() + + new_mass_shift = SimpleEntityChromatogram() + new_no_mass_shift = SimpleEntityChromatogram() + + for r in sorted(session.execute(all_node_info_q), key=lambda x: x.retention_time): + if r.node_type_id == mass_shift_id: + new_mass_shift.setdefault(r.retention_time, 0) + new_mass_shift[r.retention_time] += r.intensity + else: + new_no_mass_shift.setdefault(r.retention_time, 0) + new_no_mass_shift[r.retention_time] += r.intensity + new_mass_shift.mass_shifts = {mass_shift} + new_no_mass_shift.mass_shifts = set(self.mass_shifts) - {mass_shift} + + return new_mass_shift, new_no_mass_shift + + def _mass_shift_signal_fraction_query(self, session): + (root_peaks_join, branch_peaks_join, + anode, bnode, apeak) = _mass_shifts_query_inner + root_node_info = select([anode.c.node_type_id, anode.c.retention_time, apeak.c.intensity]).where( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == self.id + ).select_from(root_peaks_join) + + branch_node_info = select([anode.c.node_type_id, anode.c.retention_time, apeak.c.intensity]).where( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == self.id + ).select_from(branch_peaks_join) + + all_node_info_q = root_node_info.union_all(branch_node_info).order_by(anode.c.retention_time) + acc = ArithmeticMapping() + for r in session.execute(all_node_info_q): + acc[r.node_type_id] += r.intensity + + acc = ArithmeticMapping( + {(session.query(CompoundMassShift).get(ntid).convert()): signal + for ntid, signal in acc.items()}) + return acc + + def get_chromatogram(self): + return self + + def _peaks_query(self, session): + anode = alias(ChromatogramTreeNode.__table__) + bnode = alias(ChromatogramTreeNode.__table__) + apeak = alias(DeconvolutedPeak.__table__) + + peak_join = apeak.join( + ChromatogramTreeNodeToDeconvolutedPeak, + ChromatogramTreeNodeToDeconvolutedPeak.c.peak_id == apeak.c.id) + + root_peaks_join = peak_join.join( + anode, + ChromatogramTreeNodeToDeconvolutedPeak.c.node_id == anode.c.id).join( + ChromatogramToChromatogramTreeNode, + ChromatogramToChromatogramTreeNode.c.node_id == anode.c.id) + + branch_peaks_join = peak_join.join( + anode, + ChromatogramTreeNodeToDeconvolutedPeak.c.node_id == anode.c.id).join( + ChromatogramTreeNodeBranch, + ChromatogramTreeNodeBranch.child_id == anode.c.id).join( + bnode, ChromatogramTreeNodeBranch.parent_id == bnode.c.id).join( + ChromatogramToChromatogramTreeNode, + ChromatogramToChromatogramTreeNode.c.node_id == bnode.c.id) + + branch_ids = select([apeak.c.id]).where( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == self.id + ).select_from(branch_peaks_join) + + root_ids = select([apeak.c.id]).where( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == self.id + ).select_from(root_peaks_join) + + all_ids = root_ids.union_all(branch_ids) + peaks = session.execute(all_ids).fetchall() + return {p[0] for p in peaks} + + _peak_hash_ = None + + def _build_peak_hash(self): + if self._peak_hash_ is None: + session = object_session(self) + self._peak_hash_ = frozenset(self._peaks_query(session)) + return self._peak_hash_ + + @property + def _peak_hash(self): + return self._build_peak_hash() + + def is_distinct(self, other): + return self._peak_hash.isdisjoint(other._peak_hash) + + @property + def charge_states(self): + states = Counter() + for node in self.nodes: + states += (Counter(node.charge_states())) + # Require more than `MIN_POINTS_FOR_CHARGE_STATE` data points to accept any + # charge state + collapsed_states = {k for k, v in states.items() if v >= min(MIN_POINTS_FOR_CHARGE_STATE, len(self))} + if not collapsed_states: + collapsed_states = set(states.keys()) + return collapsed_states + + def raw_convert(self, node_type_cache=None, scan_id_cache=None): + session = object_session(self) + node_ids = session.query(ChromatogramToChromatogramTreeNode.c.node_id).filter( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == self.id).all() + nodes = [ChromatogramTreeNode._convert( + session, ni[0], node_type_cache=node_type_cache, + scan_id_cache=scan_id_cache) for ni in node_ids] + nodes.sort(key=lambda x: x.retention_time) + inst = MemoryChromatogram(None, ChromatogramTreeList(nodes)) + return inst + + def orm_convert(self, *args, **kwargs): + nodes = [node.convert(*args, **kwargs) for node in self.nodes] + nodes.sort(key=lambda x: x.retention_time) + inst = MemoryChromatogram(None, ChromatogramTreeList(nodes)) + return inst + + def convert(self, node_type_cache=None, scan_id_cache=None, **kwargs): + return self.orm_convert( + node_type_cache=node_type_cache, + scan_id_cache=scan_id_cache, **kwargs) + + @classmethod + def serialize(cls, obj, session, analysis_id, peak_lookup_table=None, mass_shift_cache=None, + scan_lookup_table=None, node_peak_map=None, *args, **kwargs): + if mass_shift_cache is None: + mass_shift_cache = MassShiftSerializer(session) + inst = cls( + neutral_mass=obj.neutral_mass, start_time=obj.start_time, end_time=obj.end_time, + analysis_id=analysis_id) + session.add(inst) + session.flush() + node_ids = [] + for node in obj.nodes: + db_node = ChromatogramTreeNode.serialize( + node, session, analysis_id=analysis_id, + peak_lookup_table=peak_lookup_table, + mass_shift_cache=mass_shift_cache, + scan_lookup_table=scan_lookup_table, + node_peak_map=node_peak_map, *args, **kwargs) + node_ids.append(db_node.id) + session.execute(ChromatogramToChromatogramTreeNode.insert(), [ # pylint: disable=no-value-for-parameter + {""chromatogram_id"": inst.id, ""node_id"": node_id} for node_id in node_ids]) + return inst + + def _weighted_neutral_mass_query(self, session): + all_intensity_mass = session.execute(_weighted_neutral_mass_stmt, dict(id=self.id)).fetchall() + shift_ids = {} + acc_mass = 0.0 + acc_intensity = 0.0 + shift_ids = {} + for intensity, mass, shift_id in all_intensity_mass: + try: + delta_mass = shift_ids[shift_id] + except KeyError: + delta_mass = shift_ids[shift_id] = session.query(CompoundMassShift).get(shift_id).convert().mass + acc_mass += (mass - delta_mass) * intensity + acc_intensity += intensity + return acc_mass / acc_intensity + + def _as_array_query(self, session): + all_intensities = session.execute(_as_arrays_stmt, dict(id=self.id)).fetchall() + + time = array('d') + signal = array('d') + current_signal = all_intensities[0][0] + current_time = all_intensities[0][1] + + for intensity, rt in all_intensities[1:]: + if abs(current_time - rt) < 1e-4: + current_signal += intensity + else: + time.append(current_time) + signal.append(current_signal) + current_time = rt + current_signal = intensity + time.append(current_time) + signal.append(current_signal) + # Make sure intensity dtype doesn't undergo signed overflow by being + # sufficiently wide to hold the value (e.g. not int32) + return np.array(time), np.array(signal, dtype=np.float64) + + def as_arrays(self): + session = object_session(self) + return self._as_array_query(session) + + @property + def weighted_neutral_mass(self): + session = object_session(self) + return self._weighted_neutral_mass_query(session) + + def integrate(self): + time, intensity = self.as_arrays() + return trapezoid(intensity, time) + + @property + def total_signal(self): + if self._total_signal_cache is None: + session = object_session(self) + self._total_signal_cache = self._as_array_query(session)[1].sum() + return self._total_signal_cache + + @property + def apex_time(self): + time, intensity = self.as_arrays() + return time[np.argmax(intensity)] + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + def __len__(self): + return len(self.nodes) + + def __getitem__(self, i): + return self.nodes[i] + + def __iter__(self): + return iter(self.nodes) + + +ChromatogramInterface.register(Chromatogram) + + +class MissingChromatogramError(ValueError): + pass + + +class ChromatogramWrapper(object): + + def _get_chromatogram(self): + if self.chromatogram is None: + raise MissingChromatogramError() + return self.chromatogram + + def has_chromatogram(self): + return self.chromatogram is None + + def integrate(self): + return self._get_chromatogram().integrate() + + @property + def _peak_hash(self): + try: + return self._get_chromatogram()._peak_hash + except MissingChromatogramError: + return frozenset() + + def is_distinct(self, other): + return self._peak_hash.isdisjoint(other._peak_hash) + + @property + def mass_shifts(self): + try: + return self._get_chromatogram().mass_shifts + except MissingChromatogramError: + return [] + + def mass_shift_signal_fractions(self): + try: + return self._get_chromatogram().mass_shift_signal_fractions() + except MissingChromatogramError: + return ArithmeticMapping() + + @property + def weighted_neutral_mass(self): + return self._get_chromatogram().weighted_neutral_mass + + @property + def total_signal(self): + return self._get_chromatogram().total_signal + + def __len__(self): + return len(self._get_chromatogram()) + + def as_arrays(self): + return self._get_chromatogram().as_arrays() + + @property + def start_time(self): + return self._get_chromatogram().start_time + + @property + def end_time(self): + return self._get_chromatogram().end_time + + @property + def apex_time(self): + return self._get_chromatogram().apex_time + + @property + def neutral_mass(self): + return self._get_chromatogram().neutral_mass + + @property + def charge_states(self): + return self._get_chromatogram().charge_states + + def bisect_mass_shift(self, mass_shift): + return self._get_chromatogram().bisect_mass_shift(mass_shift) + + +ChromatogramInterface.register(ChromatogramWrapper) + + +ChromatogramToChromatogramTreeNode = Table( + ""ChromatogramToChromatogramTreeNode"", Base.metadata, + Column(""chromatogram_id"", Integer, ForeignKey( + Chromatogram.id, ondelete=""CASCADE""), primary_key=True), + Column(""node_id"", Integer, ForeignKey( + ChromatogramTreeNode.id, ondelete='CASCADE'), primary_key=True)) + + +class CompositionGroup(Base, BoundToAnalysis): + __tablename__ = ""CompositionGroup"" + + id = Column(Integer, primary_key=True) + composition = Column(String(512), index=True) + + @classmethod + def serialize(cls, obj, session, *args, **kwargs): + if obj is None: + return None + composition = session.query(cls).filter(cls.composition == str(obj)).all() + if composition: + return composition[0] + else: + db_obj = cls(composition=str(obj)) + session.add(db_obj) + session.flush() + return db_obj + + def convert(self): + return str(self.composition) + + def _key(self): + return self.composition + + def __repr__(self): + return ""CompositionGroup(%r, %d)"" % (self.convert(), self.id) + + +class CompositionGroupSerializer(SimpleSerializerCacheBase): + _model_class = CompositionGroup + + +class ScoredChromatogram(object): + score = Column(Numeric(8, 7, asdecimal=False), index=True) + internal_score = Column(Numeric(8, 7, asdecimal=False)) + + +class ChromatogramSolution(Base, BoundToAnalysis, ScoredChromatogram, ChromatogramWrapper): + __tablename__ = ""ChromatogramSolution"" + + id = Column(Integer, primary_key=True) + + chromatogram_id = Column(Integer, ForeignKey( + Chromatogram.id, ondelete='CASCADE'), index=True) + composition_group_id = Column(Integer, ForeignKey( + CompositionGroup.id, ondelete='CASCADE'), index=True) + + chromatogram = relationship(Chromatogram, lazy='select') + composition_group = relationship(CompositionGroup) + + def get_chromatogram(self): + return self.chromatogram.get_chromatogram() + + @property + def key(self): + if self.composition_group is not None: + return self.composition_group._key() + else: + return self.neutral_mass + + @property + def composition(self): + return self.composition_group + + def convert(self, *args, **kwargs): + chromatogram_scoring_model = kwargs.pop( + ""chromatogram_scoring_model"", GeneralScorer) + chromatogram = self.chromatogram.convert(*args, **kwargs) + composition = self.composition_group.convert() if self.composition_group else None + chromatogram.composition = composition + sol = MemoryChromatogramSolution( + chromatogram, self.score, chromatogram_scoring_model, self.internal_score) + used_as_mass_shift = [] + for pair in self.used_as_mass_shift: + used_as_mass_shift.append((pair[0], pair[1].convert())) + sol.used_as_mass_shift = used_as_mass_shift + + ambiguous_with = [] + for pair in self.ambiguous_with: + ambiguous_with.append((pair[0], pair[1].convert())) + sol.ambiguous_with = ambiguous_with + return sol + + @property + def used_as_mass_shift(self): + pairs = [] + for rel in self._mass_shifted_relationships_mass_shift: + pairs.append((rel.owner.key, rel.mass_shift)) + return pairs + + @property + def ambiguous_with(self): + pairs = [] + for rel in self._mass_shift_relationships_owned: + pairs.append((rel.mass_shifted.key, rel.mass_shift)) + return pairs + + @classmethod + def serialize(cls, obj, session, analysis_id, peak_lookup_table=None, mass_shift_cache=None, + scan_lookup_table=None, composition_cache=None, node_peak_map=None, + *args, **kwargs): + if mass_shift_cache is None: + mass_shift_cache = MassShiftSerializer(session) + if composition_cache is None: + composition_cache = CompositionGroupSerializer(session) + db_composition_group = composition_cache.serialize(obj.composition) + composition_group_id = db_composition_group.id if db_composition_group is not None else None + inst = cls( + composition_group_id=composition_group_id, + analysis_id=analysis_id, score=obj.score, + internal_score=obj.internal_score) + chromatogram = Chromatogram.serialize( + obj.chromatogram, session=session, analysis_id=analysis_id, + peak_lookup_table=peak_lookup_table, mass_shift_cache=mass_shift_cache, + scan_lookup_table=scan_lookup_table, node_peak_map=node_peak_map, + *args, **kwargs) + inst.chromatogram_id = chromatogram.id + session.add(inst) + session.flush() + return inst + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + +class ChromatogramSolutionWrapper(ChromatogramWrapper): + def _get_chromatogram(self): + return self.solution + + @property + def used_as_mass_shift(self): + return self._get_chromatogram().used_as_mass_shift + + @property + def ambiguous_with(self): + return self._get_chromatogram().ambiguous_with + + def bisect_mass_shift(self, mass_shift): + chromatogram = self._get_chromatogram() + new_mass_shift, new_no_mass_shift = chromatogram.bisect_mass_shift(mass_shift) + + for chrom in (new_mass_shift, new_no_mass_shift): + chrom.entity = self.entity + chrom.composition = self.entity + chrom.glycan_composition = self.glycan_composition + return new_mass_shift, new_no_mass_shift + + +class GlycanCompositionChromatogram(Base, BoundToAnalysis, ScoredChromatogram, ChromatogramSolutionWrapper): + __tablename__ = ""GlycanCompositionChromatogram"" + + id = Column(Integer, primary_key=True) + + chromatogram_solution_id = Column( + Integer, ForeignKey(ChromatogramSolution.id, ondelete='CASCADE'), index=True) + + solution = relationship(ChromatogramSolution) + + glycan_composition_id = Column( + Integer, ForeignKey(GlycanComposition.id, ondelete='CASCADE'), index=True) + + entity = relationship(GlycanComposition) + + def convert(self, *args, **kwargs): + entity = self.entity.convert() + solution = self.solution.convert(*args, **kwargs) + case = solution.chromatogram.clone(MemoryGlycanCompositionChromatogram) + case.composition = entity + solution.chromatogram = case + + solution.id = self.id + solution.solution_id = self.solution.id + + try: + solution.tandem_solutions = self.spectrum_cluster.convert() + except AttributeError: + solution.tandem_solutions = [] + + return solution + + @classmethod + def serialize(cls, obj, session, analysis_id, peak_lookup_table=None, mass_shift_cache=None, + scan_lookup_table=None, composition_cache=None, node_peak_map=None, + *args, **kwargs): + solution = ChromatogramSolution.serialize( + obj, session, analysis_id, peak_lookup_table=peak_lookup_table, + mass_shift_cache=mass_shift_cache, scan_lookup_table=scan_lookup_table, + composition_cache=composition_cache, node_peak_map=node_peak_map, + *args, **kwargs) + inst = cls( + chromatogram_solution_id=solution.id, glycan_composition_id=obj.composition.id, + score=obj.score, internal_score=obj.internal_score, analysis_id=analysis_id) + session.add(inst) + session.flush() + return inst + + @property + def glycan_composition(self): + return self.entity.convert() + + @property + def composition(self): + return self.glycan_composition + + @property + def key(self): + return self.glycan_composition + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + +class UnidentifiedChromatogram(Base, BoundToAnalysis, ScoredChromatogram, ChromatogramSolutionWrapper): + __tablename__ = ""UnidentifiedChromatogram"" + + id = Column(Integer, primary_key=True) + + chromatogram_solution_id = Column( + Integer, ForeignKey(ChromatogramSolution.id, ondelete='CASCADE'), index=True) + + solution = relationship(ChromatogramSolution) + + @property + def key(self): + return self.neutral_mass + + def convert(self, *args, **kwargs): + solution = self.solution.convert(*args, **kwargs) + solution.id = self.id + solution.solution_id = self.solution.id + + try: + solution.tandem_solutions = self.spectrum_cluster.convert() + except AttributeError: + solution.tandem_solutions = [] + + return solution + + @classmethod + def serialize(cls, obj, session, analysis_id, peak_lookup_table=None, mass_shift_cache=None, + scan_lookup_table=None, composition_cache=None, node_peak_map=None, + *args, **kwargs): + solution = ChromatogramSolution.serialize( + obj, session, analysis_id, peak_lookup_table, + mass_shift_cache, scan_lookup_table, composition_cache, + node_peak_map=node_peak_map, *args, **kwargs) + inst = cls( + chromatogram_solution_id=solution.id, + score=obj.score, internal_score=obj.internal_score, + analysis_id=analysis_id) + session.add(inst) + session.flush() + return inst + + def __repr__(self): + return ""DBUnidentified"" + repr(self.convert()) + + @property + def glycan_composition(self): + return None + + @property + def composition(self): + return None + + +class ChromatogramSolutionMassShiftedToChromatogramSolution(Base): + __tablename__ = ""ChromatogramSolutionAdductToChromatogramSolution"" + + mass_shifted_solution_id = Column(Integer, ForeignKey( + ChromatogramSolution.id, ondelete=""CASCADE""), primary_key=True) + mass_shift_id = Column(Integer, ForeignKey( + CompoundMassShift.id, ondelete='CASCADE'), primary_key=True) + owning_solution_id = Column(Integer, ForeignKey( + ChromatogramSolution.id, ondelete=""CASCADE""), primary_key=True) + + owner = relationship(ChromatogramSolution, backref=backref( + ""_mass_shift_relationships_owned""), + foreign_keys=[owning_solution_id]) + mass_shifted = relationship(ChromatogramSolution, backref=backref( + ""_mass_shifted_relationships_mass_shift""), + foreign_keys=[mass_shifted_solution_id]) + mass_shift = relationship(CompoundMassShift) + + def __repr__(self): + template = ""{self.__class__.__name__}({self.mass_shifted.key} -{self.mass_shift.name}-> {self.owner.key})"" + return template.format(self=self) + + +# SQL Operation pre-definition. The Chromatogram table involves several complex joins to load +# relevant tree-like structure information. To reduce the amount of time SQLAlchemy spends +# on compiling these queries into strings, we use ``bindparam``-instrumented statements +# and expressions. These statements are made global. + + +def __build_mass_shifts_query_inner(): + + anode = alias(ChromatogramTreeNode.__table__) + bnode = alias(ChromatogramTreeNode.__table__) + apeak = alias(DeconvolutedPeak.__table__) + + peak_join = apeak.join( + ChromatogramTreeNodeToDeconvolutedPeak, + ChromatogramTreeNodeToDeconvolutedPeak.c.peak_id == apeak.c.id) + + root_peaks_join = peak_join.join( + anode, + ChromatogramTreeNodeToDeconvolutedPeak.c.node_id == anode.c.id).join( + ChromatogramToChromatogramTreeNode, + ChromatogramToChromatogramTreeNode.c.node_id == anode.c.id) + + branch_peaks_join = peak_join.join( + anode, + ChromatogramTreeNodeToDeconvolutedPeak.c.node_id == anode.c.id).join( + ChromatogramTreeNodeBranch, + ChromatogramTreeNodeBranch.child_id == anode.c.id).join( + bnode, ChromatogramTreeNodeBranch.parent_id == bnode.c.id).join( + ChromatogramToChromatogramTreeNode, + ChromatogramToChromatogramTreeNode.c.node_id == bnode.c.id) + return root_peaks_join, branch_peaks_join, anode, bnode, apeak + + +_mass_shifts_query_inner = __build_mass_shifts_query_inner() + + +def __build_mass_shifts_query(): + (root_peaks_join, branch_peaks_join, + anode, bnode, apeak) = _mass_shifts_query_inner + + branch_node_info = select([anode.c.node_type_id, anode.c.retention_time]).where( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == bindparam('id') + ).select_from(branch_peaks_join) + + root_node_info = select([anode.c.node_type_id, anode.c.retention_time]).where( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == bindparam('id') + ).select_from(root_peaks_join) + + all_node_info_q = root_node_info.union_all(branch_node_info).order_by( + anode.c.retention_time) + return all_node_info_q + + +_mass_shift_query_stmt = __build_mass_shifts_query() + + +def __build_weighted_neutral_mass_query(): + anode = alias(ChromatogramTreeNode.__table__) + bnode = alias(ChromatogramTreeNode.__table__) + apeak = alias(DeconvolutedPeak.__table__) + + peak_join = apeak.join( + ChromatogramTreeNodeToDeconvolutedPeak, + ChromatogramTreeNodeToDeconvolutedPeak.c.peak_id == apeak.c.id) + + root_peaks_join = peak_join.join( + anode, + ChromatogramTreeNodeToDeconvolutedPeak.c.node_id == anode.c.id).join( + ChromatogramToChromatogramTreeNode, + ChromatogramToChromatogramTreeNode.c.node_id == anode.c.id) + + branch_peaks_join = peak_join.join( + anode, + ChromatogramTreeNodeToDeconvolutedPeak.c.node_id == anode.c.id).join( + ChromatogramTreeNodeBranch, + ChromatogramTreeNodeBranch.child_id == anode.c.id).join( + bnode, ChromatogramTreeNodeBranch.parent_id == bnode.c.id).join( + ChromatogramToChromatogramTreeNode, + ChromatogramToChromatogramTreeNode.c.node_id == bnode.c.id) + + branch_intensities = select([apeak.c.intensity, apeak.c.neutral_mass, anode.c.node_type_id]).where( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == bindparam(""id"") + ).select_from(branch_peaks_join) + + root_intensities = select([apeak.c.intensity, apeak.c.neutral_mass, anode.c.node_type_id]).where( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == bindparam(""id"") + ).select_from(root_peaks_join) + + all_intensity_mass_q = root_intensities.union_all(branch_intensities) + return all_intensity_mass_q + + +_weighted_neutral_mass_stmt = __build_weighted_neutral_mass_query() + + +def __build_as_arrays_query(): + anode = alias(ChromatogramTreeNode.__table__) + bnode = alias(ChromatogramTreeNode.__table__) + apeak = alias(DeconvolutedPeak.__table__) + + peak_join = apeak.join( + ChromatogramTreeNodeToDeconvolutedPeak, + ChromatogramTreeNodeToDeconvolutedPeak.c.peak_id == apeak.c.id) + + root_peaks_join = peak_join.join( + anode, + ChromatogramTreeNodeToDeconvolutedPeak.c.node_id == anode.c.id).join( + ChromatogramToChromatogramTreeNode, + ChromatogramToChromatogramTreeNode.c.node_id == anode.c.id) + + branch_peaks_join = peak_join.join( + anode, + ChromatogramTreeNodeToDeconvolutedPeak.c.node_id == anode.c.id).join( + ChromatogramTreeNodeBranch, + ChromatogramTreeNodeBranch.child_id == anode.c.id).join( + bnode, ChromatogramTreeNodeBranch.parent_id == bnode.c.id).join( + ChromatogramToChromatogramTreeNode, + ChromatogramToChromatogramTreeNode.c.node_id == bnode.c.id) + + branch_intensities = select([apeak.c.intensity, anode.c.retention_time]).where( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == bindparam(""id"") + ).select_from(branch_peaks_join) + + root_intensities = select([apeak.c.intensity, anode.c.retention_time]).where( + ChromatogramToChromatogramTreeNode.c.chromatogram_id == bindparam(""id"") + ).select_from(root_peaks_join) + + all_intensities_q = root_intensities.union_all(branch_intensities).order_by( + anode.c.retention_time) + + return all_intensities_q + + +_as_arrays_stmt = __build_as_arrays_query() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/config.py",".py","533","17","import logging +try: + import psycopg2 + DEC2FLOAT = psycopg2.extensions.new_type( + psycopg2.extensions.DECIMAL.values, + 'DEC2FLOAT', + lambda value, curs: float(value) if value is not None else None) + psycopg2.extensions.register_type(DEC2FLOAT) +except ImportError: + pass +logger = logging.getLogger(""sqlalchemy.pool.NullPool"") +logger.propagate = False +logger.addHandler(logging.NullHandler()) + +from dill._dill import _reverse_typemap +_reverse_typemap['IntType'] = int +_reverse_typemap['ListType'] = list","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/param.py",".py","8251","272"," +from functools import partial +from typing import Any, Callable, Optional, Union, MutableMapping +import six +from sqlalchemy import PickleType, Column +from sqlalchemy.orm import deferred +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.ext.mutable import Mutable + +import dill +import pyzstd + +from ms_deisotope.data_source._compression import starts_with_zstd_magic + + +class LazyMutableMappingWrapper(Mutable, MutableMapping[str, Any]): + _payload: Optional[bytes] + _unpickler: Callable[[bytes], MutableMapping[str, Any]] + _object: MutableMapping[str, Any] + + def __init__(self, payload=None, unpickler=None, _object=None): + if payload is None and _object is None: + _object = PartiallySerializedMutableMapping() + if payload is not None and not starts_with_zstd_magic(payload): + payload = pyzstd.compress(payload) + self._payload = payload + self._unpickler = unpickler + self._object = _object + + def _load(self): + if self._object is not None: + return self._object + self._object = self._unpickler.loads(pyzstd.decompress(self._payload)) + self._payload = None + return self._object + + def keys(self): + return self._load().keys() + + def values(self): + return self._load().values() + + def items(self): + return self._load().items() + + def __len__(self): + return len(self._load()) + + def __contains__(self, key): + return key in self._load() + + def __getitem__(self, key): + return self._load()[key] + + def __iter__(self): + return iter(self._load()) + + def __setitem__(self, key, value): + """"""Detect dictionary set events and emit change events."""""" + self._load()[key] = value + self.changed() + + def setdefault(self, key, value): + result = self._load().setdefault(key, value) + self.changed() + return result + + def __delitem__(self, key): + """"""Detect dictionary del events and emit change events."""""" + self._load().__delitem__(key) + self.changed() + + def update(self, *a, **kw): + self._load().update(*a, **kw) + self.changed() + + def pop(self, *arg): + result = self._load().pop(*arg) + self.changed() + return result + + def popitem(self): + result = self._load().popitem() + self.changed() + return result + + def clear(self): + self._load().clear() + self.changed() + + def __getstate__(self): + return self._payload, self._unpickler, self._object + + def __setstate__(self, state): + try: + (payload, unpickler, _object) = state + except Exception: + payload = None + unpickler = None + _object = state + self._payload = payload + self._unpickler = unpickler + self._object = PartiallySerializedMutableMapping() + self.update(_object or {}) + + def unload(self): + for k, v in self._load().store.items(): + if hasattr(v, 'serialized'): + if v.serialized: + v.serialize() + + @classmethod + def coerce(cls, key, value): + """"""Convert plain dictionary to instance of this class."""""" + if not isinstance(value, cls): + if isinstance(value, dict): + return cls(None, None, PartiallySerializedMutableMapping(value)) + elif isinstance(value, PartiallySerializedMutableMapping): + return cls(None, None, value) + elif isinstance(value, (str, bytes)): + return cls(value, dill.loads) + # We have an old `glycan_profiling` object + elif value.__class__.__name__ == cls.__name__: + return cls(value._payload, value._unpickler, value._object) + return Mutable.coerce(key, value) + else: + return value + + def __repr__(self): + return repr(self._load()) + + def _ipython_key_completions_(self): + return list(self.keys()) + + +class MappingCell(object): + __slots__ = (""value"", ""serialized"") + + value: Union[bytes, Any] + serialized: bool + _dynamic_loading_threshold = 5e3 + + def __init__(self, value, serialized=False): + self.value = value + self.serialized = serialized + if serialized and isinstance(value, bytes) and not starts_with_zstd_magic(value): + self.value = pyzstd.compress(value) + + def _view_value(self): + if self.serialized and len(self.value) < self._dynamic_loading_threshold: + self.deserialize() + value = self.value if not self.serialized else """" + return value + + def __repr__(self): + template = ""{self.__class__.__name__}({value}, serialized={self.serialized})"" + value = self._view_value() + return template.format(self=self, value=value) + + def serialize(self): + if not self.serialized: + self.value = pyzstd.compress(dill.dumps(self.value, 2)) + self.serialized = True + return self + + def deserialize(self): + if self.serialized: + if isinstance(self.value, six.text_type): + self.value = self.value.encode('latin1') + if starts_with_zstd_magic(self.value): + self.value = pyzstd.decompress(self.value) + self.value = dill.loads(self.value) + self.serialized = False + return self + + def copy(self): + return self.__class__(self.value, self.serialized) + + def __reduce__(self): + if self.serialized: + return self.__class__, (self.value, self.serialized) + else: + return self.copy().serialize().__reduce__() + + +class PartiallySerializedMutableMapping(MutableMapping[str, MappingCell]): + def __init__(self, arg=None, **kwargs): + self.store = {} + self.update(arg, **kwargs) + + def __getitem__(self, key): + cell = self.store[key] + if cell.serialized: + cell.deserialize() + return cell.value + + def __setitem__(self, key, value): + self.store[key] = MappingCell(value, False) + + def __delitem__(self, key): + del self.store[key] + + def __len__(self): + return len(self.store) + + def __iter__(self): + return iter(self.store) + + def __repr__(self): + rep = {} + for key, value in self.store.items(): + rep[key] = value._view_value() + return repr(rep) + + def _ipython_key_completions_(self): + return list(self.keys()) + + def update(self, arg=None, **kwargs): + if arg: + if isinstance(arg, PartiallySerializedMutableMapping): + self.store.update(arg.store) + else: + for key, value in arg.items(): + if isinstance(value, MappingCell): + self.store[key] = value + else: + self.store[key] = MappingCell(value) + for key, value in kwargs.items(): + if isinstance(value, MappingCell): + self.store[key] = value + else: + self.store[key] = MappingCell(value) + + def unload(self): + for k, v in self.items(): + if hasattr(v, ""serialized""): + if v.serialized: + v.serialize() + + +class _crossversion_dill(object): + + @staticmethod + def loads(string, *args, **kwargs): + try: + return dill.loads(string, *args, **kwargs) + except UnicodeDecodeError: + if six.PY3: + return dill.loads(string, encoding='latin1') + else: + raise + + @staticmethod + def dumps(obj, *args, **kwargs): + return dill.dumps(obj, *args, **kwargs) + + +DillType = partial(PickleType, pickler=_crossversion_dill) + + +class HasParameters(object): + def __init__(self, **kwargs): + self._init_parameters(kwargs) + super(HasParameters, self).__init__(**kwargs) + + def _init_parameters(self, kwargs): + kwargs.setdefault('parameters', PartiallySerializedMutableMapping()) + + @declared_attr + def parameters(self) -> LazyMutableMappingWrapper: + return deferred(Column(LazyMutableMappingWrapper.as_mutable(DillType), default=LazyMutableMappingWrapper)) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/base.py",".py","1429","52","try: + from sqlalchemy.orm import declarative_base +except ImportError: + from sqlalchemy.ext.declarative import declarative_base + +from sqlalchemy import ( + Column, Numeric, String) +from sqlalchemy.orm import validates +from sqlalchemy.orm.session import object_session + +Base = declarative_base() + + +def Mass(index=True): + return Column(Numeric(14, 6, asdecimal=False), index=index) + + +def find_by_name(session, model_class, name): + return session.query(model_class).filter(model_class.name == name).first() + + +def make_unique_name(session, model_class, name): + marked_name = name + i = 1 + while find_by_name(session, model_class, marked_name) is not None: + marked_name = ""%s (%d)"" % (name, i) + i += 1 + return marked_name + + +class HasUniqueName(object): + name = Column(String(128), default=u"""", unique=True) + uuid = Column(String(64), index=True, unique=True) + + @classmethod + def make_unique_name(cls, session, name): + return make_unique_name(session, cls, name) + + @classmethod + def find_by_name(cls, session, name): + return find_by_name(session, cls, name) + + @validates(""name"") + def ensure_unique_name(self, key, name): + session = object_session(self) + if session is not None: + model_class = self.__class__ + name = make_unique_name(session, model_class, name) + return name + else: + return name +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/tandem.py",".py","38577","1038","import warnings + +from typing import Any, DefaultDict, Dict, List, Optional, Tuple, Deque + +from sqlalchemy import ( + Column, Numeric, Integer, String, ForeignKey, + Boolean, Table, select) +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.orm import ( + relationship, backref, object_session, Load) +from sqlalchemy.exc import OperationalError + +from glycresoft.tandem.spectrum_match import ( + SpectrumMatch as MemorySpectrumMatch, + SpectrumSolutionSet as MemorySpectrumSolutionSet, + ScoreSet, FDRSet, MultiScoreSpectrumMatch, + MultiScoreSpectrumSolutionSet, LocalizationScore as MemoryLocalizationScore) + +from glycresoft.structure import ScanInformation + +from .analysis import BoundToAnalysis +from .hypothesis import Glycopeptide, GlycanComposition +from .chromatogram import CompoundMassShift +from .spectrum import ( + Base, MSScan) +from .utils import chunkiter, needs_migration + +def convert_scan_to_record(scan): + return ScanInformation( + scan.scan_id, scan.index, scan.scan_time, + scan.ms_level, scan.precursor_information.convert()) + + +class SpectrumMatchBase(BoundToAnalysis): + + score = Column(Numeric(12, 6, asdecimal=False), index=True) + + @declared_attr + def scan_id(self): + return Column(Integer, ForeignKey(MSScan.id), index=True) + + @declared_attr + def scan(self): + return relationship(MSScan) + + @declared_attr + def mass_shift_id(self): + return needs_migration(Column(Integer, ForeignKey(CompoundMassShift.id), index=True)) + + @declared_attr + def mass_shift(self): + return relationship(CompoundMassShift, uselist=False) + + def _check_mass_shift(self, session): + flag = session.info.get(""has_spectrum_match_mass_shift"") + if flag: + return self.mass_shift_id + elif flag is None: + try: + session.begin_nested() + shift_id = self.mass_shift_id + session.rollback() + session.info[""has_spectrum_match_mass_shift""] = True + return shift_id + except OperationalError as err: + session.rollback() + warnings.warn( + (""Encountered an error while checking if "" + ""SpectrumMatch-tables support mass shifts: %r"") % err) + session.info[""has_spectrum_match_mass_shift""] = False + return None + else: + return None + + def _resolve_mass_shift(self, session, mass_shift_cache=None): + mass_shift_id = self._check_mass_shift(session) + if mass_shift_id is not None: + if mass_shift_cache is not None: + try: + mass_shift = mass_shift_cache[mass_shift_id] + except KeyError: + mass_shift = self.mass_shift + mass_shift_cache[mass_shift_id] = mass_shift.convert() + mass_shift = mass_shift_cache[mass_shift_id] + return mass_shift + else: + return self.mass_shift.convert() + else: + return None + + def is_multiscore(self): + """"""Check whether this match has been produced by summarizing a multi-score + match, rather than a single score match. + + Returns + ------- + bool + """""" + return False + + +class SpectrumClusterBase(object): + def __getitem__(self, i): + return self.spectrum_solutions[i] + + def __iter__(self): + return iter(self.spectrum_solutions) + + def __len__(self): + return len(self.spectrum_solutions) + + def __repr__(self): + template = ""{self.__class__.__name__}(<{size}>)"" + return template.format(self=self, size=len(self)) + + @classmethod + def compute_key(cls, members) -> frozenset: + return frozenset([m.key for m in members]) + + def convert(self, mass_shift_cache=None, scan_cache=None, structure_cache=None, **kwargs): + if scan_cache is None: + scan_cache = dict() + if mass_shift_cache is None: + mass_shift_cache = dict() + matches = [x.convert(mass_shift_cache=mass_shift_cache, scan_cache=scan_cache, + structure_cache=structure_cache, **kwargs) for x in self.spectrum_solutions] + return matches + + def is_multiscore(self) -> bool: + """"""Check whether this match collection has been produced by summarizing a multi-score + match, rather than a single score match. + + Returns + ------- + bool + """""" + return self[0].is_multiscore() + + +class SolutionSetBase(object): + + @declared_attr + def scan_id(self): + return Column(Integer, ForeignKey(MSScan.id), index=True) + + @declared_attr + def scan(self): + return relationship(MSScan) + + @property + def scan_time(self): + return self.scan.scan_time + + def best_solution(self) -> SpectrumMatchBase: + best_match = self.spectrum_matches.filter_by(is_best_match=True).first() + if best_match is not None: + # If the best match is already marked, return it + return best_match + if not self.is_multiscore(): + return sorted(self.spectrum_matches, key=lambda x: x.score, reverse=True)[0] + else: + return sorted(self.spectrum_matches, key=lambda x: (x.score_set.convert()[0]), reverse=True)[0] + + def is_ambiguous(self) -> bool: + seen = set() + + for sm in self.spectrum_matches.filter_by(is_best_match=True).all(): + seen.add(str(sm.target)) + return len(seen) > 1 + + @property + def key(self) -> frozenset: + scan_id = self.scan.id + return frozenset([(scan_id, match.target.id) for match in self]) + + @property + def score(self): + return self.best_solution().score + + def __getitem__(self, i): + return self.spectrum_matches[i] + + def __iter__(self): + return iter(self.spectrum_matches) + + _target_map = None + + def _make_target_map(self): + self._target_map = { + sol.target: sol for sol in self + } + + def solution_for(self, target): + if self._target_map is None: + self._make_target_map() + return self._target_map[target] + + def is_multiscore(self): + """"""Check whether this match has been produced by summarizing a multi-score + match, rather than a single score match. + + Returns + ------- + bool + """""" + return self[0].is_multiscore() + + +class GlycopeptideSpectrumCluster(Base, SpectrumClusterBase, BoundToAnalysis): + __tablename__ = ""GlycopeptideSpectrumCluster"" + + id = Column(Integer, primary_key=True) + + @classmethod + def serialize(cls, obj, session, scan_look_up_cache, mass_shift_cache, analysis_id, *args, **kwargs): + inst = cls() + session.add(inst) + session.flush() + cluster_id = inst.id + for solution_set in obj.tandem_solutions: + GlycopeptideSpectrumSolutionSet.serialize( + solution_set, session, scan_look_up_cache, mass_shift_cache, analysis_id, + cluster_id, *args, **kwargs) + return inst + + +class GlycopeptideSpectrumSolutionSet(Base, SolutionSetBase, BoundToAnalysis): + __tablename__ = ""GlycopeptideSpectrumSolutionSet"" + + id = Column(Integer, primary_key=True) + cluster_id = Column( + Integer, + ForeignKey(GlycopeptideSpectrumCluster.id, ondelete=""CASCADE""), + index=True) + + cluster = relationship(GlycopeptideSpectrumCluster, backref=backref(""spectrum_solutions"", lazy='subquery')) + + is_decoy = Column(Boolean, index=True) + + @classmethod + def serialize(cls, obj: MemorySpectrumSolutionSet, session, scan_look_up_cache, mass_shift_cache, analysis_id, + cluster_id, is_decoy=False, *args, **kwargs): + obj.rank() + gpsm = obj.best_solution() + if gpsm is None: + gpsm = obj[0] + if not gpsm.best_match: + obj.mark_top_solutions() + inst = cls( + scan_id=scan_look_up_cache[obj.scan.id], + is_decoy=is_decoy, + analysis_id=analysis_id, + cluster_id=cluster_id) + session.add(inst) + session.flush() + GlycopeptideSpectrumMatch.serialize_bulk( + obj, session, scan_look_up_cache, mass_shift_cache, analysis_id, inst.id) + return inst + + def convert(self, mass_shift_cache=None, scan_cache=None, structure_cache=None, peptide_relation_cache=None): + if scan_cache is None: + scan_cache = {} + if mass_shift_cache is None: + mass_shift_cache = {} + session = object_session(self) + flag = session.info.get(""has_spectrum_match_mass_shift"") + if flag: + spectrum_match_q = self.spectrum_matches.options( + Load(GlycopeptideSpectrumMatch).undefer(""mass_shift_id"")).all() + else: + spectrum_match_q = self.spectrum_matches.all() + matches = [x.convert(mass_shift_cache=mass_shift_cache, scan_cache=scan_cache, + structure_cache=structure_cache, peptide_relation_cache=peptide_relation_cache) + for x in spectrum_match_q] + solution_set_tp = MemorySpectrumSolutionSet + if matches and matches[0].is_multiscore(): + solution_set_tp = MultiScoreSpectrumSolutionSet + inst = solution_set_tp( + convert_scan_to_record(self.scan), + matches + ) + inst._is_sorted = True + inst.id = self.id + return inst + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + @classmethod + def bulk_load(cls, session, + ids, + chunk_size: int=512, + mass_shift_cache=None, + scan_cache=None, + structure_cache=None, + peptide_relation_cache=None, + flatten=True, + min_q_value=0.2): + return cls._inner_bulk_load( + cls.id.in_, + session, + ids, + chunk_size, + mass_shift_cache, + scan_cache, + structure_cache, + peptide_relation_cache, + flatten, + min_q_value=min_q_value + ) + + @classmethod + def bulk_load_from_clusters(cls, session, + ids, + chunk_size: int = 512, + mass_shift_cache=None, + scan_cache=None, + structure_cache=None, + peptide_relation_cache=None, + min_q_value=0.2 + ): + by_id = cls._inner_bulk_load( + cls.cluster_id.in_, + session, + ids, + chunk_size, + mass_shift_cache, + scan_cache, + structure_cache, + peptide_relation_cache, + flatten=False, + min_q_value=min_q_value + ) + groups = DefaultDict(list) + for chunk in chunkiter(ids, chunk_size): + res = session.execute(select([cls.id, cls.cluster_id]).where(cls.cluster_id.in_(chunk))) + for (sset_id, cluster_id) in res.fetchall(): + groups[cluster_id].append(by_id[sset_id]) + return groups + + @classmethod + def _inner_bulk_load( + cls, + selector, + session, + ids, + chunk_size: int = 512, + mass_shift_cache=None, + scan_cache=None, + structure_cache=None, + peptide_relation_cache=None, + flatten=True, + min_q_value=0.2 + ): + if selector is None: + selector = cls.id.in_ + if scan_cache is None: + scan_cache = {} + if mass_shift_cache is None: + mass_shift_cache = { + m.id: m.convert() for m in session.query(CompoundMassShift).all() + } + out = {} + for chunk in chunkiter(ids, chunk_size): + res = session.execute(cls.__table__.select().where( + selector(chunk))) + for self in res.fetchall(): + gpsm_ids = [ + i[0] for i in session.query(GlycopeptideSpectrumMatch.id).filter( + GlycopeptideSpectrumMatch.solution_set_id == self.id, + GlycopeptideSpectrumMatch.q_value <= min_q_value + ).all() + ] + if not gpsm_ids: + gpsm_ids = [ + i[0] for i in session.query(GlycopeptideSpectrumMatch.id).filter( + GlycopeptideSpectrumMatch.solution_set_id == self.id, + ).order_by( + GlycopeptideSpectrumMatch.q_value.asc(), + GlycopeptideSpectrumMatch.score.desc() + ).limit(5) + ] + matches = GlycopeptideSpectrumMatch.bulk_load( + session, + gpsm_ids, + chunk_size, + mass_shift_cache=mass_shift_cache, + scan_cache=scan_cache, + structure_cache=structure_cache, + peptide_relation_cache=peptide_relation_cache + ) + matches = [matches[k] for k in gpsm_ids] + solution_set_tp = MemorySpectrumSolutionSet + if matches and matches[0].is_multiscore(): + solution_set_tp = MultiScoreSpectrumSolutionSet + + if self.scan_id not in scan_cache: + MSScan.bulk_load(session, [self.scan_id], scan_cache=scan_cache) + inst = solution_set_tp(scan_cache[self.scan_id], matches) + inst._is_sorted = True + inst.id = self.id + out[self.id] = inst + if flatten: + return [out[i] for i in ids] + return out + + +class GlycopeptideSpectrumMatch(Base, SpectrumMatchBase): + __tablename__ = ""GlycopeptideSpectrumMatch"" + + id = Column(Integer, primary_key=True) + solution_set_id = Column( + Integer, ForeignKey( + GlycopeptideSpectrumSolutionSet.id, ondelete='CASCADE'), + index=True) + solution_set = relationship( + GlycopeptideSpectrumSolutionSet, backref=backref(""spectrum_matches"", lazy='dynamic')) + + q_value = Column(Numeric(8, 7, asdecimal=False), index=True) + is_decoy = Column(Boolean) + is_best_match = Column(Boolean, index=True) + rank = needs_migration(Column(Integer, default=0), 0) + + structure_id = Column( + Integer, ForeignKey(Glycopeptide.id, ondelete='CASCADE'), + index=True) + + structure = relationship(Glycopeptide) + + @property + def target(self): + return self.structure + + @property + def q_value_set(self): + return self.score_set + + def is_multiscore(self): + """"""Check whether this match has been produced by summarizing a multi-score + match, rather than a single score match. + + Returns + ------- + bool + """""" + return self.score_set is not None + + @classmethod + def serialize(cls, obj, session, scan_look_up_cache, mass_shift_cache, analysis_id, + solution_set_id, is_decoy=False, save_score_set=True, *args, **kwargs): + inst = cls( + scan_id=scan_look_up_cache[obj.scan.id], + is_decoy=is_decoy, + analysis_id=analysis_id, + score=obj.score, + rank=obj.rank, + q_value=obj.q_value, + solution_set_id=solution_set_id, + is_best_match=obj.best_match, + structure_id=obj.target.id, + mass_shift_id=mass_shift_cache[obj.mass_shift].id) + session.add(inst) + session.flush() + if hasattr(obj, 'score_set') and save_score_set: + assert inst.id is not None + GlycopeptideSpectrumMatchScoreSet.serialize_from_spectrum_match(obj, session, inst.id) + if obj.localizations: + locs = (LocalizationScore.get_fields_from_object(obj, inst.id)) + if locs: + session.bulk_insert_mappings(LocalizationScore, locs) + + return inst + + @classmethod + def serialize_bulk(cls, objs, session, scan_look_up_cache, mass_shift_cache, analysis_id, + solution_set_id, is_decoy=False, save_score_set=True, *args, **kwargs): + acc = [] + revmap: Dict[Any, MemorySpectrumMatch] = {} + for obj in objs: + scan_id = scan_look_up_cache[obj.scan.id] + target_id = obj.target.id + shift_id = mass_shift_cache[obj.mass_shift].id + inst = cls( + scan_id=scan_look_up_cache[obj.scan.id], + is_decoy=is_decoy, + analysis_id=analysis_id, + score=obj.score, + rank=obj.rank, + q_value=obj.q_value, + solution_set_id=solution_set_id, + is_best_match=obj.best_match, + structure_id=target_id, + mass_shift_id=shift_id) + acc.append(inst) + revmap[scan_id, target_id, shift_id] = obj + + session.bulk_save_objects(acc) + + if save_score_set: + session.flush() + fwd = session.query(cls.id, cls.scan_id, cls.structure_id, cls.mass_shift_id).filter( + cls.solution_set_id == solution_set_id).all() + acc = [] + loc_acc = [] + for inst in fwd: + obj = revmap[inst.scan_id, inst.structure_id, inst.mass_shift_id] + if hasattr(obj, 'score_set'): + fields = GlycopeptideSpectrumMatchScoreSet.get_fields_from_object(obj, inst.id) + acc.append(fields) + if obj.localizations: + loc_acc.extend(LocalizationScore.get_fields_from_object(obj, inst.id)) + if acc: + session.bulk_insert_mappings(GlycopeptideSpectrumMatchScoreSet, acc) + if loc_acc: + session.bulk_insert_mappings( + LocalizationScore, + loc_acc + ) + + return revmap + + @classmethod + def bulk_load(cls, session, ids, chunk_size: int = 512, + mass_shift_cache: Optional[Dict] = None, + scan_cache: Optional[Dict] = None, + structure_cache: Optional[Dict] = None, + peptide_relation_cache: Optional[Dict] = None) -> Dict[int, MemorySpectrumMatch]: + if peptide_relation_cache is None: + peptide_relation_cache = {} + if structure_cache is None: + structure_cache = {} + if mass_shift_cache is None: + mass_shift_cache = {m.id: m.convert() for m in session.query(CompoundMassShift).all()} + if scan_cache is None: + scan_cache = {} + + out = {} + id_series = [] + scan_series = [] + mass_shift_series = [] + structure_series = [] + is_best_match_series = Deque() + rank_series = Deque() + solution_set_id = Deque() + score_map = {} + + for chunk in chunkiter(ids, chunk_size): + res = session.execute(cls.__table__.select().where( + cls.id.in_(chunk))) + for self in res.fetchall(): + id_series.append(self.id) + scan_series.append(self.scan_id) + mass_shift_series.append(mass_shift_cache[self.mass_shift_id]) + structure_series.append(self.structure_id) + is_best_match_series.append(self.is_best_match) + rank_series.append(self.rank) + solution_set_id.append(self.solution_set_id) + score_map[self.id] = (self.score, self.q_value) + + solution_set_id_to_cluster_id = {} + uniq_set_ids = list(set(solution_set_id)) + for chunk in chunkiter(uniq_set_ids, chunk_size): + res = session.execute( + select([GlycopeptideSpectrumSolutionSet.id, + GlycopeptideSpectrumSolutionSet.cluster_id]).where( + GlycopeptideSpectrumSolutionSet.id.in_(chunk))) + for (ssid, clid) in res.fetchall(): + solution_set_id_to_cluster_id[ssid] = clid + + scan_objects = MSScan.bulk_load( + session, scan_series, + chunk_size=chunk_size, scan_cache=scan_cache) + + structure_objects = Glycopeptide.bulk_load( + session, structure_series, + chunk_size=chunk_size, + peptide_relation_cache=peptide_relation_cache, + structure_cache=structure_cache) + + score_sets_map = GlycopeptideSpectrumMatchScoreSet.bulk_load( + session, ids, chunk_size=chunk_size) + + localization_map = LocalizationScore.bulk_load(session, ids, chunk_size=chunk_size) + + for id, scan, structure, mass_shift, best_match, rank, sset_id in zip( + id_series, + scan_objects, + structure_objects, + mass_shift_series, + is_best_match_series, + rank_series, + solution_set_id): + localizations = localization_map[id] + if id in score_sets_map: + score_set, fdr_set = score_sets_map[id] + out[id] = MultiScoreSpectrumMatch( + scan, structure, + id=id, + score_set=score_set, + best_match=best_match, + q_value_set=fdr_set, + mass_shift=mass_shift, + localizations=localizations, + rank=rank, + cluster_id=solution_set_id_to_cluster_id[sset_id] + ) + else: + score, q_value = score_map[id] + out[id] = MemorySpectrumMatch( + scan, structure, score, best_match, + q_value=q_value, + id=id, + mass_shift=mass_shift, + localizations=localizations, + rank=rank, + cluster_id=solution_set_id_to_cluster_id[sset_id] + ) + return out + + def convert(self, mass_shift_cache=None, scan_cache=None, structure_cache=None, peptide_relation_cache=None): + session = object_session(self) + key = self.scan_id + if scan_cache is None: + scan = session.query(MSScan).get(key).convert(False, False) + else: + try: + scan = scan_cache[key] + except KeyError: + scan = scan_cache[key] = session.query(MSScan).get(key).convert(False, False) + + key = self.structure_id + if structure_cache is None: + target = self.structure.convert(peptide_relation_cache=peptide_relation_cache) + else: + try: + target = structure_cache[key] + except KeyError: + target = structure_cache[key] = self.structure.convert(peptide_relation_cache=peptide_relation_cache) + + orm_locs = self.localizations + if orm_locs: + locs = [loc.convert() for loc in orm_locs] + else: + locs = [] + mass_shift = self._resolve_mass_shift(session, mass_shift_cache) + orm_score_set = self.score_set + if orm_score_set is None: + inst = MemorySpectrumMatch(scan, target, self.score, self.is_best_match, + mass_shift=mass_shift, localizations=locs) + else: + score_set, fdr_set = orm_score_set.convert() + inst = MultiScoreSpectrumMatch( + scan, target, score_set, self.is_best_match, + mass_shift=mass_shift, q_value_set=fdr_set, match_type=0, + localizations=locs) + + inst.q_value = self.q_value + inst.id = self.id + return inst + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + @property + def cluster_id(self): + return self.solution_set.cluster_id + + +class GlycanCompositionSpectrumCluster(Base, SpectrumClusterBase, BoundToAnalysis): + __tablename__ = ""GlycanCompositionSpectrumCluster"" + + id = Column(Integer, primary_key=True) + + @classmethod + def serialize(cls, obj, session, scan_look_up_cache, mass_shift_cache, analysis_id, *args, **kwargs): + inst = cls() + session.add(inst) + session.flush() + cluster_id = inst.id + for solution_set in obj.tandem_solutions: + GlycanCompositionSpectrumSolutionSet.serialize( + solution_set, session, scan_look_up_cache, mass_shift_cache, analysis_id, + cluster_id, *args, **kwargs) + return inst + + source = relationship( + ""GlycanCompositionChromatogram"", + secondary=lambda: GlycanCompositionChromatogramToGlycanCompositionSpectrumCluster, + backref=backref(""spectrum_cluster"", uselist=False)) + + +class GlycanCompositionSpectrumSolutionSet(Base, SolutionSetBase, BoundToAnalysis): + __tablename__ = ""GlycanCompositionSpectrumSolutionSet"" + + id = Column(Integer, primary_key=True) + cluster_id = Column( + Integer, + ForeignKey(GlycanCompositionSpectrumCluster.id, ondelete=""CASCADE""), + index=True) + + cluster = relationship(GlycanCompositionSpectrumCluster, backref=backref( + ""spectrum_solutions"", lazy='subquery')) + + @classmethod + def serialize(cls, obj, session, scan_look_up_cache, mass_shift_cache, analysis_id, cluster_id, *args, **kwargs): + inst = cls( + scan_id=scan_look_up_cache[obj.scan.id], + analysis_id=analysis_id, + cluster_id=cluster_id) + session.add(inst) + session.flush() + # if we have a real SpectrumSolutionSet, then it will be iterable + try: + list(obj) + except TypeError: + # otherwise we have a single SpectrumMatch + obj = [obj] + for solution in obj: + GlycanCompositionSpectrumMatch.serialize( + solution, session, scan_look_up_cache, mass_shift_cache, + analysis_id, inst.id, *args, **kwargs) + return inst + + def convert(self, mass_shift_cache=None, scan_cache=None, structure_cache=None): + if scan_cache is None: + scan_cache = dict() + matches = [x.convert(mass_shift_cache=mass_shift_cache, scan_cache=scan_cache, + structure_cache=structure_cache) for x in self.spectrum_matches] + matches.sort(key=lambda x: x.score, reverse=True) + inst = MemorySpectrumSolutionSet( + convert_scan_to_record(self.scan), + matches + ) + inst.q_value = min(x.q_value for x in inst) + inst.id = self.id + return inst + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + +class GlycanCompositionSpectrumMatch(Base, SpectrumMatchBase): + __tablename__ = ""GlycanCompositionSpectrumMatch"" + + id = Column(Integer, primary_key=True) + solution_set_id = Column( + Integer, ForeignKey( + GlycanCompositionSpectrumSolutionSet.id, ondelete='CASCADE'), + index=True) + solution_set = relationship(GlycanCompositionSpectrumSolutionSet, + backref=backref(""spectrum_matches"", lazy='subquery')) + + composition_id = Column( + Integer, ForeignKey(GlycanComposition.id, ondelete='CASCADE'), + index=True) + + composition = relationship(GlycanComposition) + + @property + def target(self): + return self.composition + + @classmethod + def serialize(cls, obj, session, scan_look_up_cache, mass_shift_cache, analysis_id, + solution_set_id, is_decoy=False, *args, **kwargs): + inst = cls( + scan_id=scan_look_up_cache[obj.scan.id], + analysis_id=analysis_id, + score=obj.score, + solution_set_id=solution_set_id, + composition_id=obj.target.id, + mass_shift_id=mass_shift_cache[obj.mass_shift].id) + session.add(inst) + session.flush() + return inst + + def convert(self, mass_shift_cache=None): + session = object_session(self) + scan = session.query(MSScan).get(self.scan_id).convert(False, False) + mass_shift = self._resolve_mass_shift(session, mass_shift_cache) + target = session.query(GlycanComposition).get(self.composition_id).convert() + inst = MemorySpectrumMatch(scan, target, self.score, mass_shift=mass_shift) + inst.id = self.id + return inst + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + +class UnidentifiedSpectrumCluster(Base, SpectrumClusterBase, BoundToAnalysis): + __tablename__ = ""UnidentifiedSpectrumCluster"" + + id = Column(Integer, primary_key=True) + + @classmethod + def serialize(cls, obj, session, scan_look_up_cache, mass_shift_cache, analysis_id, *args, **kwargs): + inst = cls() + session.add(inst) + session.flush() + cluster_id = inst.id + for solution_set in obj.tandem_solutions: + UnidentifiedSpectrumSolutionSet.serialize( + solution_set, session, scan_look_up_cache, mass_shift_cache, analysis_id, + cluster_id, *args, **kwargs) + return inst + + source = relationship( + ""UnidentifiedChromatogram"", + secondary=lambda: UnidentifiedChromatogramToUnidentifiedSpectrumCluster, + backref=backref(""spectrum_cluster"", uselist=False)) + + +class UnidentifiedSpectrumSolutionSet(Base, SolutionSetBase, BoundToAnalysis): + __tablename__ = ""UnidentifiedSpectrumSolutionSet"" + + id = Column(Integer, primary_key=True) + cluster_id = Column( + Integer, + ForeignKey(UnidentifiedSpectrumCluster.id, ondelete=""CASCADE""), + index=True) + + cluster = relationship(UnidentifiedSpectrumCluster, backref=backref( + ""spectrum_solutions"", lazy='subquery')) + + @classmethod + def serialize(cls, obj, session, scan_look_up_cache, mass_shift_cache, analysis_id, cluster_id, *args, **kwargs): + inst = cls( + scan_id=scan_look_up_cache[obj.scan.id], + analysis_id=analysis_id, + cluster_id=cluster_id) + session.add(inst) + session.flush() + # if we have a real SpectrumSolutionSet, then it will be iterable + try: + list(obj) + except TypeError: + # otherwise we have a single SpectrumMatch + obj = [obj] + for solution in obj: + UnidentifiedSpectrumMatch.serialize( + solution, session, scan_look_up_cache, mass_shift_cache, + analysis_id, inst.id, *args, **kwargs) + return inst + + def convert(self, mass_shift_cache=None, scan_cache=None, structure_cache=None): + if scan_cache is None: + scan_cache = dict() + if mass_shift_cache is None: + mass_shift_cache = dict() + matches = [x.convert(mass_shift_cache=mass_shift_cache, + scan_cache=scan_cache) for x in self.spectrum_matches] + matches.sort(key=lambda x: x.score, reverse=True) + inst = MemorySpectrumSolutionSet( + convert_scan_to_record(self.scan), + matches + ) + inst.q_value = min(x.q_value for x in inst) + inst.id = self.id + return inst + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + +class UnidentifiedSpectrumMatch(Base, SpectrumMatchBase): + __tablename__ = ""UnidentifiedSpectrumMatch"" + + id = Column(Integer, primary_key=True) + solution_set_id = Column( + Integer, ForeignKey( + UnidentifiedSpectrumSolutionSet.id, ondelete='CASCADE'), + index=True) + + solution_set = relationship(UnidentifiedSpectrumSolutionSet, + backref=backref(""spectrum_matches"", lazy='subquery')) + + @classmethod + def serialize(cls, obj, session, scan_look_up_cache, mass_shift_cache, analysis_id, solution_set_id, + is_decoy=False, *args, **kwargs): + inst = cls( + scan_id=scan_look_up_cache[obj.scan.id], + analysis_id=analysis_id, + score=obj.score, + solution_set_id=solution_set_id, + mass_shift_id=mass_shift_cache[obj.mass_shift].id) + session.add(inst) + session.flush() + return inst + + def convert(self, mass_shift_cache=None): + session = object_session(self) + scan = session.query(MSScan).get(self.scan_id).convert(False, False) + mass_shift = self._resolve_mass_shift(session, mass_shift_cache) + inst = MemorySpectrumMatch(scan, None, self.score, mass_shift=mass_shift) + inst.id = self.id + return inst + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + +GlycanCompositionChromatogramToGlycanCompositionSpectrumCluster = Table( + ""GlycanCompositionChromatogramToGlycanCompositionSpectrumCluster"", Base.metadata, + Column(""chromatogram_id"", Integer, ForeignKey( + ""GlycanCompositionChromatogram.id"", ondelete=""CASCADE""), primary_key=True), + Column(""cluster_id"", Integer, ForeignKey( + GlycanCompositionSpectrumCluster.id, ondelete=""CASCADE""), primary_key=True)) + + +UnidentifiedChromatogramToUnidentifiedSpectrumCluster = Table( + ""UnidentifiedChromatogramToUnidentifiedSpectrumCluster"", Base.metadata, + Column(""chromatogram_id"", Integer, ForeignKey( + ""UnidentifiedChromatogram.id"", ondelete=""CASCADE""), primary_key=True), + Column(""cluster_id"", Integer, ForeignKey( + UnidentifiedSpectrumCluster.id, ondelete=""CASCADE""), primary_key=True)) + + +class GlycopeptideSpectrumMatchScoreSet(Base): + __tablename__ = ""GlycopeptideSpectrumMatchScoreSet"" + + id = Column(Integer, ForeignKey(GlycopeptideSpectrumMatch.id), primary_key=True) + peptide_score = Column(Numeric(12, 6, asdecimal=False), index=False) + glycan_score = Column(Numeric(12, 6, asdecimal=False), index=False) + glycopeptide_score = Column(Numeric(12, 6, asdecimal=False), index=False) + glycan_coverage = needs_migration(Column(Numeric(8, 7, asdecimal=False), index=False), 0.0) + + total_q_value = Column(Numeric(8, 7, asdecimal=False), index=False) + peptide_q_value = Column(Numeric(8, 7, asdecimal=False), index=False) + glycan_q_value = Column(Numeric(8, 7, asdecimal=False), index=False) + glycopeptide_q_value = Column(Numeric(8, 7, asdecimal=False), index=False) + + spectrum_match = relationship( + GlycopeptideSpectrumMatch, backref=backref(""score_set"", lazy='joined', uselist=False)) + + @classmethod + def get_fields_from_object(cls, obj, db_id=None): + scores = obj.score_set + qs = obj.q_value_set + fields = dict( + id=db_id, + peptide_score=scores.peptide_score, + glycan_score=scores.glycan_score, + glycan_coverage=scores.glycan_coverage, + glycopeptide_score=scores.glycopeptide_score, + total_q_value=qs.total_q_value, + peptide_q_value=qs.peptide_q_value, + glycan_q_value=qs.glycan_q_value, + glycopeptide_q_value=qs.glycopeptide_q_value + ) + return fields + + @classmethod + def serialize_from_spectrum_match(cls, obj, session, db_id): + fields = cls.get_fields_from_object(obj, db_id) + session.execute(cls.__table__.insert(), fields) + + def convert(self): + score_set = ScoreSet( + peptide_score=self.peptide_score, + glycan_score=self.glycan_score, + glycopeptide_score=self.glycopeptide_score, + glycan_coverage=self.glycan_coverage) + fdr_set = FDRSet( + total_q_value=self.total_q_value, + peptide_q_value=self.peptide_q_value, + glycan_q_value=self.glycan_q_value, + glycopeptide_q_value=self.glycopeptide_q_value) + return score_set, fdr_set + + def __repr__(self): + return ""DB"" + repr(self.convert()) + + @classmethod + def bulk_load(cls, session, ids, chunk_size: int=512) -> Dict[int, Tuple[ScoreSet, FDRSet]]: + out = {} + for chunk in chunkiter(ids, chunk_size): + res = session.execute(cls.__table__.select().where(cls.id.in_(chunk))) + for self in res.fetchall(): + score_set = ScoreSet( + peptide_score=self.peptide_score, + glycan_score=self.glycan_score, + glycopeptide_score=self.glycopeptide_score, + glycan_coverage=self.glycan_coverage) + fdr_set = FDRSet( + total_q_value=self.total_q_value, + peptide_q_value=self.peptide_q_value, + glycan_q_value=self.glycan_q_value, + glycopeptide_q_value=self.glycopeptide_q_value) + out[self.id] = (score_set, fdr_set) + return out + + +class LocalizationScore(Base): + __tablename__ = ""LocalizationScore"" + + id = Column(Integer, ForeignKey( + GlycopeptideSpectrumMatch.id), primary_key=True) + + position = Column(Integer, primary_key=True) + modification = Column(String) + score = Column(Numeric(6, 3, asdecimal=False)) + + spectrum_match = relationship( + GlycopeptideSpectrumMatch, backref=backref(""localizations"", lazy='joined')) + + @classmethod + def get_fields_from_object(cls, obj: MemorySpectrumMatch, db_id=None): + instances = [] + for loc in obj.localizations: + inst = dict( + id=db_id, + position=loc.position, + modification=loc.modification, + score=loc.score + ) + instances.append(inst) + return instances + + def convert(self): + return MemoryLocalizationScore(self.position, self.modification, self.score) + + def __repr__(self): + return f""DB{self.__class__.__name__}({self.id}, {self.position}, {self.modification}, {self.score})"" + + def __str__(self): + return f""{self.modification}:{self.position}:{self.score}"" + + @classmethod + def bulk_load(cls, session, ids, chunk_size: int = 512) -> DefaultDict[int, List[MemoryLocalizationScore]]: + out = DefaultDict(list) + for chunk in chunkiter(ids, chunk_size): + res = session.execute( + cls.__table__.select().where(cls.id.in_(chunk))) + for self in res.fetchall(): + out[self.id].append(MemoryLocalizationScore( + self.position, self.modification, self.score)) + return out +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/hypothesis/peptide.py",".py","21018","582","import re + +from collections import OrderedDict, defaultdict + +from typing import Any, List, Mapping, Tuple + +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.orm import ( + relationship, backref, Query, + deferred, object_session) +from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method +from sqlalchemy import ( + Column, Numeric, Integer, String, ForeignKey, PickleType, + Text, Index, case, select, func) +from sqlalchemy.ext.mutable import MutableDict, MutableList + +from glycresoft.serialize.base import ( + Base) + + +from .hypothesis import GlycopeptideHypothesis +from .glycan import GlycanCombination +from .generic import JSONType, HasChemicalComposition +from ..utils import chunkiter + +from glycopeptidepy.structure import sequence, residue, PeptideSequenceBase +from glycopeptidepy.io.annotation import AnnotationCollection, GlycosylationSite, GlycosylationType +from glycresoft.structure.structure_loader import PeptideProteinRelation, FragmentCachingGlycopeptide +from glycresoft.structure.utils import LRUDict + + +class AminoAcidSequenceWrapperBase(PeptideSequenceBase): + _sequence_obj = None + + def _get_sequence_str(self): + raise NotImplementedError() + + def _get_sequence(self): + if self._sequence_obj is None: + self._sequence_obj = sequence.PeptideSequence( + self._get_sequence_str()) + return self._sequence_obj + + def __iter__(self): + return iter(self._get_sequence()) + + def __getitem__(self, i): + return self._get_sequence()[i] + + def __len__(self): + return len(self._get_sequence()) + + def __str__(self): + return str(self._get_sequence()) + + +class Protein(Base, AminoAcidSequenceWrapperBase): + __tablename__ = ""Protein"" + + id = Column(Integer, primary_key=True, autoincrement=True) + protein_sequence = Column(Text, default=u"""") + name = Column(String(128), index=True) + other = Column(MutableDict.as_mutable(PickleType)) + hypothesis_id = Column(Integer, ForeignKey( + GlycopeptideHypothesis.id, ondelete=""CASCADE"")) + hypothesis = relationship(GlycopeptideHypothesis, backref=backref('proteins', lazy='dynamic')) + + def __init__(self, *args: Any, **kwargs: Any) -> None: + annotations = kwargs.pop(""annotations"", AnnotationCollection([])) + self.other = MutableDict() + super().__init__(*args, **kwargs) + self.annotations = annotations + + def _get_sequence_str(self): + return self.protein_sequence.replace(""Z"", ""X"") + + _n_glycan_sequon_sites = None + + @property + def n_glycan_sequon_sites(self): + if self._n_glycan_sequon_sites is None: + sites = self.sites.filter(ProteinSite.name == ProteinSite.N_GLYCOSYLATION).all() + if sites: + self._n_glycan_sequon_sites = sorted([int(i) for i in sites]) + # else: + # try: + # self._n_glycan_sequon_sites = sequence.find_n_glycosylation_sequons(self._get_sequence()) + # except residue.UnknownAminoAcidException: + # self._n_glycan_sequon_sites = [] + else: + self._n_glycan_sequon_sites = [] + return self._n_glycan_sequon_sites + + _o_glycan_sequon_sites = None + + @property + def o_glycan_sequon_sites(self): + if self._o_glycan_sequon_sites is None: + sites = self.sites.filter(ProteinSite.name == ProteinSite.O_GLYCOSYLATION).all() + if sites: + self._o_glycan_sequon_sites = sorted([int(i) for i in sites]) + else: + try: + self._o_glycan_sequon_sites = sequence.find_o_glycosylation_sequons(self._get_sequence()) + except residue.UnknownAminoAcidException: + self._o_glycan_sequon_sites = [] + return self._o_glycan_sequon_sites + + _glycosaminoglycan_sequon_sites = None + + @property + def glycosaminoglycan_sequon_sites(self): + if self._glycosaminoglycan_sequon_sites is None: + sites = self.sites.filter(ProteinSite.name == ProteinSite.GAGYLATION).all() + if sites: + self._glycosaminoglycan_sequon_sites = sorted([int(i) for i in sites]) + else: + try: + self._glycosaminoglycan_sequon_sites = sequence.find_glycosaminoglycan_sequons( + self._get_sequence()) + except residue.UnknownAminoAcidException: + self._glycosaminoglycan_sequon_sites = [] + return self._glycosaminoglycan_sequon_sites + + @property + def glycosylation_sites(self): + try: + return self.n_glycan_sequon_sites # + self.o_glycan_sequon_sites + except residue.UnknownAminoAcidException: + return [] + + def _init_sites(self, include_cysteine_n_glycosylation: bool = False): + try: + parsed_sequence = self._get_sequence() + except residue.UnknownAminoAcidException: + return + sites = [] + try: + n_glycosites = sequence.find_n_glycosylation_sequons( + parsed_sequence, include_cysteine=include_cysteine_n_glycosylation) + for n_glycosite in n_glycosites: + sites.append( + ProteinSite(name=ProteinSite.N_GLYCOSYLATION, location=n_glycosite)) + except residue.UnknownAminoAcidException: + pass + if self.annotations is not None: + for modsite in self.annotations.modifications(): + if isinstance(modsite, GlycosylationSite): + if modsite.glycosylation_type == GlycosylationType.n_linked: + sites.append( + ProteinSite(name=ProteinSite.N_GLYCOSYLATION, location=modsite.position) + ) + elif modsite.glycosylation_type == GlycosylationType.o_linked: + sites.append( + ProteinSite(name=ProteinSite.O_GLYCOSYLATION, location=modsite.position) + ) + elif modsite.glycosylation_type == GlycosylationType.glycosaminoglycan: + sites.append( + ProteinSite(name=ProteinSite.GAGYLATION, location=modsite.position) + ) + + # The O- and GAG-linker sites are not determined by a multi AA sequon. We don't + # need to abstract them away and they are much too common. + # try: + # o_glycosites = sequence.find_o_glycosylation_sequons( + # parsed_sequence) + # for o_glycosite in o_glycosites: + # sites.append( + # ProteinSite(name=ProteinSite.O_GLYCOSYLATION, location=o_glycosite)) + # except residue.UnknownAminoAcidException: + # pass + + # try: + # gag_sites = sequence.find_glycosaminoglycan_sequons( + # parsed_sequence) + # for gag_site in gag_sites: + # sites.append( + # ProteinSite(name=ProteinSite.GAGYLATION, location=gag_site)) + # except residue.UnknownAminoAcidException: + # pass + self.sites.extend(sorted(set(sites))) + + def __repr__(self): + return ""DBProtein({0}, {1}, {2}, {3}...)"".format( + self.id, self.name, self.glycosylation_sites, + self.protein_sequence[:20] if self.protein_sequence is not None else """") + + def to_json(self, full=False): + d = OrderedDict(( + ('id', self.id), + ('name', self.name), + (""glycosylation_sites"", list(self.glycosylation_sites)), + ('other', self.other) + )) + if full: + d.update({ + ""protein_sequence"": self.protein_sequence + }) + for k, v in self.__dict__.items(): + if isinstance(v, Query): + d[k + '_count'] = v.count() + return d + + def reverse(self, copy_id=False, prefix=None, suffix=None): + n = len(self.protein_sequence) + sites = [] + for site in self.sites: # pylint: disable=access-member-before-definition + sites.append(site.__class__(name=site.name, location=n - site.location - 1)) + name = self.name + if name.startswith("">""): + if prefix: + name = "">"" + prefix + name[1:] + if suffix: + name = name + suffix + + inst = self.__class__(name=name, protein_sequence=self.protein_sequence[::-1]) + if copy_id: + inst.id = self.id + inst.sites = sites + return inst + + @property + def annotations(self) -> AnnotationCollection: + return self.other.get('annotations', AnnotationCollection([])) + + @annotations.setter + def annotations(self, value): + if not isinstance(value, AnnotationCollection) and value is not None: + value = AnnotationCollection(value) + elif value is None: + value = AnnotationCollection([]) + self.other['annotations'] = value + + @classmethod + def build_site_cache(cls, session, ids, chunk_size: int = 512) -> Mapping[int, Mapping[str, List[Tuple[int, str]]]]: + cache = defaultdict(lambda: defaultdict(list)) + + substr_expr = case( + [ + ( + ProteinSite.name == ProteinSite.N_GLYCOSYLATION, + 3 + ) + ], + else_=1 + ) + + for chunk in chunkiter(ids, chunk_size): + vals = session.query( + ProteinSite.name, + ProteinSite.location, + ProteinSite.protein_id, + func.substr( + Protein.protein_sequence, + # SQL standard says start position is 1 + ProteinSite.location + 1, + substr_expr + ) + ).join(cls).filter( + ProteinSite.protein_id.in_(chunk) + ).all() + + for (site_type, site_index, prot_id, marker) in vals: + cache[prot_id][site_type].append((site_index, marker)) + + return cache + + +class ProteinSite(Base): + __tablename__ = ""ProteinSite"" + + id = Column(Integer, primary_key=True) + name = Column(String(32), index=True) + location = Column(Integer, index=True) + protein_id = Column(Integer, ForeignKey(Protein.id, ondelete=""CASCADE""), index=True) + protein = relationship(Protein, backref=backref(""sites"", lazy='dynamic')) + + N_GLYCOSYLATION = ""N-Glycosylation"" + O_GLYCOSYLATION = ""O-Glycosylation"" + GAGYLATION = ""Glycosaminoglycosylation"" + + _hash = None + + def __repr__(self): + return (""{self.__class__.__name__}(location={self.location}, "" + ""name={self.name})"").format(self=self) + + def __hash__(self): + hash_val = self._hash + if hash_val is None: + hash_val = self._hash = hash((self.name, self.location)) + return hash_val + + def __index__(self): + return self.location + + def __int__(self): + return self.location + + def __add__(self, other): + return int(self) + int(other) + + def __radd__(self, other): + return int(self) + int(other) + + def __lt__(self, other): + return int(self) < int(other) + + def __gt__(self, other): + return int(self) > int(other) + + def __eq__(self, other): + if isinstance(other, ProteinSite): + return self.location == other.location and self.name == other.name + return int(self) == int(other) + + def __ne__(self, other): + return not (self == other) + + +def _convert_class_name_to_collection_name(name): + parts = re.split(r""([A-Z]+[a-z]+)"", name) + parts = [p.lower() for p in parts if p] + return '_'.join(parts) + 's' + + +class PeptideBase(AminoAcidSequenceWrapperBase): + @declared_attr + def protein_id(self): + return Column(Integer, ForeignKey( + Protein.id, ondelete=""CASCADE""), index=True) + + @declared_attr + def hypothesis_id(self): + return Column(Integer, ForeignKey( + GlycopeptideHypothesis.id, ondelete=""CASCADE""), index=True) + + @declared_attr + def protein(self): + if not hasattr(self, ""__collection_name__""): + name = _convert_class_name_to_collection_name(self.__name__) + else: + name = self.__collection_name__ + return relationship(Protein, backref=backref(name, lazy='dynamic')) + + calculated_mass = Column(Numeric(12, 6, asdecimal=False), index=True) + formula = Column(String(128)) + + def __iter__(self): + return iter(self.convert()) + + def __len__(self): + return len(self.convert()) + + @property + def total_mass(self): + return self.convert().total_mass + + _protein_relation = None + + @property + def protein_relation(self): + if self._protein_relation is None: + peptide = self + self._protein_relation = PeptideProteinRelation( + peptide.start_position, peptide.end_position, peptide.protein_id, + peptide.hypothesis_id) + return self._protein_relation + + @property + def start_position(self): + return self.protein_relation.start_position + + @property + def end_position(self): + return self.protein_relation.end_position + + def overlaps(self, other): + return self.protein_relation.overlaps(other.protein_relation) + + def spans(self, position): + return position in self.protein_relation + + +class Peptide(PeptideBase, HasChemicalComposition, Base): + __tablename__ = 'Peptide' + + id = Column(Integer, primary_key=True) + + count_glycosylation_sites = Column(Integer) + count_missed_cleavages = Column(Integer) + count_variable_modifications = Column(Integer) + + start_position = Column(Integer) + end_position = Column(Integer) + + peptide_score = Column(Numeric(12, 6, asdecimal=False)) + _scores = deferred(Column(""scores"", JSONType)) + peptide_score_type = Column(String(56)) + + base_peptide_sequence = Column(String(512)) + modified_peptide_sequence = Column(String(512)) + + sequence_length = Column(Integer) + + n_glycosylation_sites = Column(MutableList.as_mutable(JSONType)) + o_glycosylation_sites = Column(MutableList.as_mutable(JSONType)) + gagylation_sites = Column(MutableList.as_mutable(JSONType)) + + hypothesis = relationship(GlycopeptideHypothesis, backref=backref('peptides', lazy='dynamic')) + + def _get_sequence_str(self): + return self.modified_peptide_sequence + + def convert(self): + inst = sequence.parse(self.modified_peptide_sequence) + inst.id = self.id + return inst + + def __repr__(self): + return (""DBPeptideSequence({self.modified_peptide_sequence}, {self.n_glycosylation_sites},"" + "" {self.start_position}, {self.end_position})"").format(self=self) + + __table_args__ = ( + Index(""ix_Peptide_mass_search_index"", ""hypothesis_id"", ""calculated_mass""), + Index(""ix_Peptide_coordinate_index"", ""id"", ""calculated_mass"", + ""start_position"", ""end_position""),) + + @hybrid_method + def spans(self, position): + return position in self.protein_relation + + @spans.expression + def spans(self, position): + # Overhang at the end is for consistency with SpanningMixin, but this is not + # ideal + return (self.start_position <= position) & (position <= self.end_position) + + @hybrid_property + def scores(self): # pylint: disable=method-hidden + try: + if self._scores is None: + self.scores = [] + return self._scores + except Exception: + return [] + + @scores.setter + def scores(self, value): + self._scores = value + + +class Glycopeptide(PeptideBase, Base): + __tablename__ = ""Glycopeptide"" + + id = Column(Integer, primary_key=True) + peptide_id = Column(Integer, ForeignKey(Peptide.id, ondelete='CASCADE'), index=True) + glycan_combination_id = Column(Integer, ForeignKey(GlycanCombination.id, ondelete='CASCADE'), index=True) + + peptide = relationship(Peptide, backref=backref(""glycopeptides"", lazy='dynamic')) + glycan_combination = relationship(GlycanCombination) + + glycopeptide_sequence = Column(String(1024)) + + hypothesis = relationship(GlycopeptideHypothesis, backref=backref('glycopeptides', lazy='dynamic')) + + def _get_sequence_str(self): + return self.glycopeptide_sequence + + @classmethod + def bulk_load(cls, session, ids, chunk_size: int=512, peptide_relation_cache=None, structure_cache=None): + if peptide_relation_cache is None: + peptide_relation_cache = session.info.get(""peptide_relation_cache"") + if peptide_relation_cache is None: + peptide_relation_cache = session.info['peptide_relation_cache'] = LRUDict( + maxsize=1024) + if structure_cache is None: + structure_cache = {} + out = structure_cache + peptide_ids = [] + for chunk in chunkiter(ids, chunk_size): + chunk = list(filter(lambda x: x not in structure_cache, chunk)) + res = session.execute(cls.__table__.select().where( + cls.id.in_(chunk) + ) + ) + + for self in res.fetchall(): + inst = FragmentCachingGlycopeptide(self.glycopeptide_sequence) + inst.id = self.id + + peptide_id = self.peptide_id + out[self.id] = (inst, peptide_id) + if peptide_id not in peptide_relation_cache: + peptide_ids.append(peptide_id) + + for chunk in chunkiter(peptide_ids, chunk_size): + res = session.execute(Peptide.__table__.select().where( + Peptide.id.in_( + list(filter(lambda x: x not in peptide_relation_cache, + chunk))))) + + for self in res.fetchall(): + peptide_relation_cache[self.id] = PeptideProteinRelation( + self.start_position, + self.end_position, + self.protein_id, + self.hypothesis_id + ) + + result = [] + for i in ids: + inst, peptide_id = out[i] + inst.protein_relation = peptide_relation_cache[peptide_id] + result.append(inst) + return result + + def convert(self, peptide_relation_cache=None): + if peptide_relation_cache is None: + session = object_session(self) + peptide_relation_cache = session.info.get(""peptide_relation_cache"") + if peptide_relation_cache is None: + peptide_relation_cache = session.info['peptide_relation_cache'] = LRUDict(maxsize=1024) + inst = FragmentCachingGlycopeptide(self.glycopeptide_sequence) + inst.id = self.id + peptide_id = self.peptide_id + if peptide_id in peptide_relation_cache: + inst.protein_relation = peptide_relation_cache[self.peptide_id] + else: + session = object_session(self) + peptide_props = session.query( + Peptide.start_position, Peptide.end_position, + Peptide.protein_id, Peptide.hypothesis_id).filter(Peptide.id == peptide_id).first() + peptide_relation_cache[peptide_id] = inst.protein_relation = PeptideProteinRelation(*peptide_props) + return inst + + def __repr__(self): + return ""DBGlycopeptideSequence({self.glycopeptide_sequence}, {self.calculated_mass})"".format(self=self) + _protein_relation = None + + @hybrid_method + def is_multiply_glycosylated(self): + return self.glycan_combination.count > 1 + + @is_multiply_glycosylated.expression + def is_multiply_glycosylated(self): + expr = select([GlycanCombination.count > 1]).where( + GlycanCombination.id == Glycopeptide.glycan_combination_id).label( + ""is_multiply_glycosylated"") + return expr + + @property + def protein_relation(self): + if self._protein_relation is None: + peptide = self.peptide + self._protein_relation = PeptideProteinRelation( + peptide.start_position, peptide.end_position, peptide.protein_id, + peptide.hypothesis_id) + return self._protein_relation + + @property + def n_glycan_sequon_sites(self): + return self.peptide.n_glycosylation_sites + + @property + def o_glycan_sequon_sites(self): + return self.peptide.o_glycosylation_sites + + @property + def glycosaminoglycan_sequon_sites(self): + return self.peptide.gagylation_sites + + @property + def glycan_composition(self): + return self.glycan_combination.convert() + + __table_args__ = ( + Index(""ix_Glycopeptide_mass_search_index"", ""hypothesis_id"", ""calculated_mass""), + # Index(""ix_Glycopeptide_mass_search_index_full"", ""calculated_mass"", ""hypothesis_id"", + # ""peptide_id"", ""glycan_combination_id""), + ) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/hypothesis/hypothesis.py",".py","2556","75","from collections import Counter + +from sqlalchemy import ( + Column, Integer, String, ForeignKey, PickleType, func) + +from sqlalchemy.orm import relationship, object_session +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.ext.mutable import MutableDict + +from glycresoft.serialize.base import ( + Base, HasUniqueName) + +from .generic import HasFiles + + +from glypy.structure.glycan_composition import FrozenGlycanComposition + + +class HypothesisBase(HasUniqueName, HasFiles): + @declared_attr + def id(self): + return Column(Integer, primary_key=True, autoincrement=True) + + parameters = Column(MutableDict.as_mutable(PickleType), default=dict(), nullable=False) + status = Column(String(28)) + + def __repr__(self): + return ""{self.__class__.__name__}(id={self.id}, name={self.name})"".format(self=self) + + +class GlycanHypothesis(HypothesisBase, Base): + __tablename__ = ""GlycanHypothesis"" + + def monosaccharide_bounds(self): + from .glycan import GlycanComposition + bounds = Counter() + session = object_session(self) + for composition, in session.query(GlycanComposition.composition.distinct()).filter( + GlycanComposition.hypothesis_id == self.id): + composition = FrozenGlycanComposition.parse(composition) + for residue, count in composition.items(): + bounds[residue] = max(bounds[residue], count) + return {str(k): int(v) for k, v in bounds.items()} + + @property + def glycan_class_counts(self): + from .glycan import GlycanClass, GlycanComposition + session = object_session(self) + d = {k: v for k, v in session.query(GlycanClass.name, func.count(GlycanClass.name)).join( + GlycanComposition.structure_classes).group_by(GlycanClass.name).all()} + return d + + @property + def n_glycan_only(self): + counts = self.glycan_class_counts + k = counts.get('N-Glycan', 0) + return len(counts) == 1 and k > 0 + + +class GlycopeptideHypothesis(HypothesisBase, Base): + __tablename__ = ""GlycopeptideHypothesis"" + + glycan_hypothesis_id = Column(Integer, ForeignKey(GlycanHypothesis.id, ondelete=""CASCADE""), index=True) + glycan_hypothesis = relationship(GlycanHypothesis) + + def monosaccharide_bounds(self): + return self.glycan_hypothesis.monosaccharide_bounds() + + @property + def glycan_class_counts(self): + return self.glycan_hypothesis.glycan_class_counts + + @property + def n_glycan_only(self): + return self.glycan_hypothesis.n_glycan_only","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/hypothesis/__init__.py",".py","471","14","from .hypothesis import GlycanHypothesis, GlycopeptideHypothesis + +from .glycan import ( + GlycanComposition, GlycanCombination, GlycanClass, + GlycanStructure, GlycanTypes, GlycanCombinationGlycanComposition, + GlycanCompositionToClass, GlycanStructureToClass) + +from .peptide import ( + Protein, Peptide, Glycopeptide, ProteinSite) + +from .generic import ( + TemplateNumberStore as TemplateNumberStore, + ReferenceDatabase, ReferenceAccessionNumber, FileBlob) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/hypothesis/generic.py",".py","8565","281","import os +import gzip +import json + +from io import BytesIO +from functools import total_ordering + +import pickle + +from six import string_types as basestring + +import sqlalchemy +from sqlalchemy import ( + Column, Integer, String, ForeignKey, + PickleType, Boolean, Table, ForeignKeyConstraint, + BLOB) + +from sqlalchemy.types import TypeDecorator +from sqlalchemy.orm import relationship, deferred +from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.ext.mutable import MutableDict + +from ms_deisotope.data_source._compression import starts_with_gz_magic + +try: + from ms_deisotope.data_source._compression import starts_with_zstd_magic +except ImportError: + starts_with_zstd_magic = None + +try: + from pyzstd import ZstdFile +except ImportError: + ZstdFile = None + + +from glypy import Composition + +from ..base import ( + Base) + +from ..utils import get_or_create + + +def _ipython_key_completions_(self): + return list(self.keys()) + + +MutableDict._ipython_key_completions_ = _ipython_key_completions_ + + +@total_ordering +class ApplicationVersion(Base): + __tablename__ = ""ApplicationVersion"" + + id = Column(Integer, primary_key=True) + name = Column(String) + major = Column(Integer) + minor = Column(Integer) + patch = Column(Integer) + + def __eq__(self, other): + if other is None: + return False + try: + if self.name != other.name: + return False + except AttributeError: + pass + + return tuple(self) == tuple(other) + + def __lt__(self, other): + if other is None: + return False + try: + if self.name != other.name: + return False + except AttributeError: + pass + + return tuple(self) < tuple(other) + + def __iter__(self): + yield self.major + yield self.minor + yield self.patch + + +class ParameterStore(object): + parameters = Column(MutableDict.as_mutable(PickleType), default=dict) + + +class Taxon(Base): + __tablename__ = ""Taxon"" + id = Column(Integer, primary_key=True) + name = Column(String(128), index=True) + + @classmethod + def get(cls, session, id, name=None): + obj, made = get_or_create(session, cls, id=id, name=name) + return obj + + def __repr__(self): + return """".format(self.id, self.name) + + +class HasTaxonomy(object): + + @declared_attr + def taxa(cls): + taxon_association = Table( + ""%s_Taxa"" % cls.__tablename__, + cls.metadata, + Column(""taxon_id"", Integer, ForeignKey(Taxon.id, ondelete=""CASCADE""), primary_key=True), + Column(""entity_id"", Integer, ForeignKey( + ""%s.id"" % cls.__tablename__, ondelete=""CASCADE""), primary_key=True)) + cls.TaxonomyAssociationTable = taxon_association + return relationship(Taxon, secondary=taxon_association) + + @classmethod + def with_taxa(cls, ids): + try: + iter(ids) + return cls.taxa.any(Taxon.id.in_(tuple(ids))) + except Exception: + return cls.taxa.any(Taxon.id == ids) + + +class ReferenceDatabase(Base): + __tablename__ = ""ReferenceDatabase"" + id = Column(Integer, primary_key=True) + name = Column(String(128)) + url = Column(String(128)) + + @classmethod + def get(cls, session, id=None, name=None, url=None): + obj, made = get_or_create(session, cls, id=id, name=name, url=url) + return obj + + def __repr__(self): + return """".format(self.id, self.name) + + +class ReferenceAccessionNumber(Base): + __tablename__ = ""ReferenceAccessionNumber"" + id = Column(String(64), primary_key=True) + database_id = Column(Integer, ForeignKey(ReferenceDatabase.id), primary_key=True) + database = relationship(ReferenceDatabase) + + @classmethod + def get(cls, session, id, database_id): + obj, made = get_or_create(session, cls, id=id, database_id=database_id) + return obj + + def __repr__(self): + return """".format(self.id, self.database.name) + + +class HasReferenceAccessionNumber(object): + @declared_attr + def references(cls): + reference_number_association = Table( + ""%s_ReferenceAccessionNumber"" % cls.__tablename__, + cls.metadata, + Column(""accession_code"", String(64), primary_key=True), + Column(""database_id"", Integer, primary_key=True), + Column( + ""entity_id"", Integer, ForeignKey(""%s.id"" % cls.__tablename__, ondelete=""CASCADE""), primary_key=True), + ForeignKeyConstraint( + [""accession_code"", ""database_id""], + [""ReferenceAccessionNumber.id"", ""ReferenceAccessionNumber.database_id""])) + cls.ReferenceAccessionAssocationTable = reference_number_association + return relationship(ReferenceAccessionNumber, secondary=reference_number_association) + + +TemplateNumberStore = Table(""TemplateNumberStore"", Base.metadata, Column(""value"", Integer)) + + +class FileBlob(Base): + __tablename__ = 'FileBlob' + + id = Column(Integer, primary_key=True) + name = Column(String(256), index=True) + data = deferred(Column(BLOB)) + compressed = Column(Boolean) + + def __repr__(self): + return ""FileBlob({self.name})"".format(self=self) + + @classmethod + def from_file(cls, fp, compress=False): + inst = cls(name=os.path.basename(fp.name), compressed=compress) + data = fp.read() + has_gz_magic = starts_with_gz_magic(data) + if starts_with_zstd_magic is None: + has_zstd_magic = False + else: + has_zstd_magic = starts_with_zstd_magic(data) + if compress and not has_gz_magic and not has_zstd_magic: + buff = BytesIO() + with gzip.GzipFile(mode='wb', fileobj=buff) as compressor: + compressor.write(data) + buff.seek(0) + data = buff.read() + inst.name += '.gz' + if not compress and has_gz_magic: + inst.compressed = True + if not compress and has_zstd_magic: + inst.compressed = True + inst.data = data + return inst + + @classmethod + def from_path(cls, path, compress=False): + with open(path, 'rb') as fh: + inst = cls.from_file(fh, compress) + return inst + + def open(self, raw=False): + data_buffer = BytesIO(self.data) + if self.compressed and not raw: + if starts_with_gz_magic(self.data[:6]): + return gzip.GzipFile(fileobj=data_buffer) + elif (starts_with_zstd_magic is not None and ZstdFile is not None) and starts_with_zstd_magic(self.data[:6]): + return ZstdFile(data_buffer) + else: + raise ValueError(""Could not infer decompressor for %r"" % (self.data[:6], )) + return data_buffer + + +class HasFiles(object): + @declared_attr + def files(cls): + file_association = Table( + ""%s_Files"" % cls.__tablename__, + cls.metadata, + Column(""file_id"", Integer, ForeignKey(FileBlob.id, ondelete=""CASCADE""), primary_key=True), + Column(""entity_id"", Integer, ForeignKey( + ""%s.id"" % cls.__tablename__, ondelete=""CASCADE""), primary_key=True)) + cls.FileBlobAssociationTable = file_association + return relationship(FileBlob, secondary=file_association) + + def add_file(self, file_obj, compress=False): + if isinstance(file_obj, basestring): + f = FileBlob.from_path(file_obj, compress) + else: + f = FileBlob.from_file(file_obj, compress) + self.files.append(f) + + +class JSONType(TypeDecorator): + + impl = sqlalchemy.Text() + + def process_bind_param(self, value, dialect): + if value is not None: + value = ""J"" + json.dumps(value) + + return value + + def process_result_value(self, value, dialect): + if value is not None: + if isinstance(value, bytes): + # NOTE: This should only happen when loading a database originally written in Py2? + if value.startswith(b""J""): + value = json.loads(value[1:].decode('utf8')) + else: + value = pickle.loads(value) + else: + value = json.loads(value[1:]) + return value + + +class HasChemicalComposition(object): + _total_composition = None + + def total_composition(self): + if self._total_composition is None: + self._total_composition = Composition(self.formula) + return self._total_composition +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/serialize/hypothesis/glycan.py",".py","7301","230","from sqlalchemy.ext.declarative import declared_attr +from sqlalchemy.ext.hybrid import hybrid_method +from sqlalchemy.orm import relationship, backref, object_session +from sqlalchemy import ( + Column, Numeric, Integer, String, ForeignKey, + Table, Index) + +from glycresoft.serialize.base import (Base) + + +from glypy import Composition +from glypy.io import glycoct +from glycopeptidepy import HashableGlycanComposition + +from glycresoft.serialize.hypothesis.hypothesis import GlycanHypothesis, GlycopeptideHypothesis +from glycresoft.serialize.hypothesis.generic import HasReferenceAccessionNumber, HasChemicalComposition + + +class GlycanBase(HasChemicalComposition): + calculated_mass = Column(Numeric(12, 6, asdecimal=False), index=True) + formula = Column(String(128), index=True) + composition = Column(String(128)) + + def convert(self): + inst = HashableGlycanComposition.parse(self.composition) + inst.id = self.id + return inst + + _glycan_composition = None + + def __getitem__(self, key): + if self._glycan_composition is None: + self._glycan_composition = HashableGlycanComposition.parse(self.composition) + return self._glycan_composition[key] + + def keys(self): + if self._glycan_composition is None: + self._glycan_composition = HashableGlycanComposition.parse(self.composition) + return self._glycan_composition.keys() + + def mass(self): + return self.calculated_mass + + +class GlycanComposition(GlycanBase, Base): + __tablename__ = 'GlycanComposition' + + id = Column(Integer, primary_key=True) + + @declared_attr + def hypothesis_id(self): + return Column(Integer, ForeignKey( + GlycanHypothesis.id, ondelete=""CASCADE""), index=True) + + def __iter__(self): + return iter(self.keys()) + + @declared_attr + def hypothesis(self): + return relationship(GlycanHypothesis, backref=backref('glycans', lazy='dynamic')) + + def __repr__(self): + return ""DBGlycanComposition(%s)"" % (self.composition) + + structure_classes = relationship(""GlycanClass"", secondary=lambda: GlycanCompositionToClass, lazy='dynamic') + + __table_args__ = (Index(""ix_GlycanComposition_mass_search_index"", ""calculated_mass"", ""hypothesis_id""),) + + +class GlycanStructure(GlycanBase, Base, HasReferenceAccessionNumber): + __tablename__ = ""GlycanStructure"" + + id = Column(Integer, primary_key=True) + + glycan_sequence = Column(String(2048), index=True) + + glycan_composition_id = Column( + Integer, ForeignKey(GlycanComposition.id, ondelete='CASCADE'), index=True) + + glycan_composition = relationship(GlycanComposition, backref=backref(""glycan_structures"", lazy='dynamic')) + + @declared_attr + def hypothesis_id(self): + return Column(Integer, ForeignKey( + GlycanHypothesis.id, ondelete=""CASCADE""), index=True) + + @declared_attr + def hypothesis(self): + return relationship(GlycanHypothesis, backref=backref('glycan_structures', lazy='dynamic')) + + structure_classes = relationship(""GlycanClass"", secondary=lambda: GlycanStructureToClass, lazy='dynamic') + + def convert(self): + seq = self.glycan_sequence + structure = glycoct.loads(seq) + structure.id = self.id + return structure + + def __repr__(self): + return ""DBGlycanStructure:%d\n%s"" % (self.id, self.glycan_sequence) + + __table_args__ = (Index(""ix_GlycanStructure_mass_search_index"", ""calculated_mass"", ""hypothesis_id""),) + + +GlycanCombinationGlycanComposition = Table( + ""GlycanCombinationGlycanComposition"", Base.metadata, + Column(""glycan_id"", Integer, ForeignKey(""GlycanComposition.id"", ondelete=""CASCADE""), index=True), + Column(""combination_id"", Integer, ForeignKey(""GlycanCombination.id"", ondelete=""CASCADE""), index=True), + Column(""count"", Integer) +) + + +class GlycanCombination(GlycanBase, Base): + __tablename__ = 'GlycanCombination' + + id = Column(Integer, primary_key=True) + + @declared_attr + def hypothesis_id(self): + return Column(Integer, ForeignKey( + GlycopeptideHypothesis.id, ondelete=""CASCADE""), index=True) + + @declared_attr + def hypothesis(self): + return relationship(GlycopeptideHypothesis, backref=backref('glycan_combinations', lazy='dynamic')) + + count = Column(Integer) + + components = relationship( + GlycanComposition, + secondary=GlycanCombinationGlycanComposition, + lazy='dynamic') + + def __iter__(self): + for composition, count in self.components.add_columns( + GlycanCombinationGlycanComposition.c.count): + i = 0 + while i < count: + yield composition + i += 1 + + @property + def component_ids(self): + session = object_session(self) + ids = session.query(GlycanCombinationGlycanComposition.c.glycan_id).filter( + GlycanCombinationGlycanComposition.c.combination_id == self.id).all() + return [i[0] for i in ids] + + def _get_component_classes(self): + for case in self: + yield case.structure_classes.all() + + _component_classes = None + + @property + def component_classes(self): + if self._component_classes is None: + self._component_classes = tuple(self._get_component_classes()) + return self._component_classes + + @hybrid_method + def dehydrated_mass(self, water_mass=Composition(""H2O"").mass): + mass = self.calculated_mass + return mass - (water_mass * self.count) + + _dehydrated_composition = None + + def dehydrated_composition(self): + if self._dehydrated_composition is None: + self._dehydrated_composition = self.total_composition() - ( + self.count * Composition(""H2O"")) + return self._dehydrated_composition + + def __repr__(self): + rep = ""GlycanCombination({self.count}, {self.composition})"".format(self=self) + return rep + + +class GlycanClass(Base): + __tablename__ = 'GlycanClass' + + id = Column(Integer, primary_key=True) + name = Column(String(128), index=True) + + def __str__(self): + return self.name + + def __eq__(self, other): + return self.name == other + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash(self.name) + + def __repr__(self): + return ""GlycanClass(name=%r)"" % (self.name,) + + +class _namespace(object): + def __repr__(self): + return ""(%r)"" % self.__dict__ + + def __contains__(self, key): + return key in self.__dict__ + + def __getitem__(self, key): + return self.__dict__[key] + + +GlycanTypes = _namespace() +GlycanTypes.n_glycan = ""N-Glycan"" +GlycanTypes.o_glycan = ""O-Glycan"" +GlycanTypes.gag_linker = ""GAG-Linker"" + + +GlycanCompositionToClass = Table( + ""GlycanCompositionToClass"", Base.metadata, + Column(""glycan_id"", Integer, ForeignKey(""GlycanComposition.id"", ondelete=""CASCADE""), primary_key=True), + Column(""class_id"", Integer, ForeignKey(""GlycanClass.id"", ondelete=""CASCADE""), primary_key=True) +) + + +GlycanStructureToClass = Table( + ""GlycanStructureToClass"", Base.metadata, + Column(""glycan_id"", Integer, ForeignKey(""GlycanStructure.id"", ondelete=""CASCADE""), primary_key=True), + Column(""class_id"", Integer, ForeignKey(""GlycanClass.id"", ondelete=""CASCADE""), primary_key=True) +) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/chromatogram_solution.py",".py","10725","356","from operator import mul + +from typing import Generic, TypeVar, Optional, OrderedDict, Dict, Any + +try: + reduce +except NameError: + from functools import reduce + +import numpy as np + +from .shape_fitter import ChromatogramShapeModel +from .spacing_fitter import ChromatogramSpacingModel +from .charge_state import UniformChargeStateScoringModel +from .isotopic_fit import IsotopicPatternConsistencyModel +from .base import symbolic_composition, epsilon, ScoringFeatureBase +from .utils import logitsum, prod + +from glycresoft.chromatogram_tree import ChromatogramInterface, Chromatogram + + +class ScorerBase(object): + feature_set: OrderedDict[str, ScoringFeatureBase] + configuration: Dict[str, Any] + + def __init__(self, *args, **kwargs): + self.feature_set = OrderedDict() + self.configuration = dict() + + def __getitem__(self, k): + return self.feature_set[k] + + def __contains__(self, k): + return k in self.feature_set + + def __iter__(self): + return iter(self.feature_set) + + def __len__(self): + return len(self.feature_set) + + def configure(self, analysis_info): + for feature in self.features(): + config_data = feature.configure(analysis_info) + self.configuration[feature.get_feature_name()] = config_data + + def add_feature(self, scoring_feature): + if scoring_feature is None: + return + feature_type = scoring_feature.get_feature_type() + self.feature_set[feature_type] = scoring_feature + + def features(self): + for feature in self.feature_set.values(): + yield feature + + def compute_scores(self, chromatogram: ChromatogramInterface) -> 'ChromatogramScoreSet': + raise NotImplementedError() + + def logitscore(self, chromatogram: ChromatogramInterface) -> float: + score = logitsum(self.compute_scores(chromatogram)) + return score + + def score(self, chromatogram: ChromatogramInterface) -> float: + score = reduce(mul, self.compute_scores(chromatogram), 1.0) + return score + + def accept(self, solution: 'ChromatogramSolution') -> bool: + scored_features = solution.score_components() + for feature in self.features(): + if feature.reject(scored_features, solution): + return False + return True + + def __repr__(self): + template = ""{self.__class__.__name__}({features})"" + features = ', '.join([""%r: %s"" % kv for kv in self.feature_set.items()]) + return template.format(self=self, features=features) + + +class ChromatogramScoreSet(object): + scores: OrderedDict[str, float] + + def __init__(self, scores): + self.scores = OrderedDict(scores) + + def __iter__(self): + return iter(self.scores.values()) + + def __repr__(self): + return ""%s(%s)"" % (self.__class__.__name__, str(dict(self.scores))[1:-1]) + + def __getitem__(self, key): + return self.scores[key] + + def __setitem__(self, key, value): + self.scores[key] = value + + def __getattr__(self, key): + if key == ""scores"": + raise AttributeError(key) + try: + return self.scores[key] + except KeyError: + raise AttributeError(key) + + def keys(self): + return self.scores.keys() + + def values(self): + return self.scores.values() + + def items(self): + return self.scores.items() + + def __mul__(self, i): + new = self.__class__(self.scores) + for feature in self.keys(): + new[feature] *= i + return new + + def __div__(self, i): + new = self.__class__(self.scores) + for feature in self.keys(): + new[feature] /= i + return new + + def __add__(self, other): + new = self.__class__(self.scores) + for key, value in other.items(): + try: + new[key] += value + except KeyError: + new[key] = value + return new + + def product(self) -> float: + return prod(*self) + + def logitsum(self) -> float: + return logitsum(self) + + +class DummyScorer(ScorerBase): + def __init__(*args, **kwargs): + pass + + def score(self, *args, **kwargs): + return 1.0 + + @property + def line_test(self): + return 0.0 + + @property + def spacing_fit(self): + return 0.0 + + @property + def mean_fit(self): + return 0.0 + + def compute_scores(self, chromatogram): + line_score = 1 - epsilon + isotopic_fit = 1 - epsilon + spacing_fit = 1 - epsilon + charge_count = 1 - epsilon + return ChromatogramScoreSet([ + (""line_score"", line_score), (""isotopic_fit"", isotopic_fit), + (""spacing_fit"", spacing_fit), (""charge_count"", charge_count) + ]) + + def logitscore(self, chromatogram): + score = logitsum(self.compute_scores(chromatogram)) + return score + + +class ChromatogramScorer(ScorerBase): + def __init__(self, shape_fitter_model=ChromatogramShapeModel, + isotopic_fitter_model=IsotopicPatternConsistencyModel, + charge_scoring_model=UniformChargeStateScoringModel, + spacing_fitter_model=ChromatogramSpacingModel, + mass_shift_scoring_model=None, *models): + super(ChromatogramScorer, self).__init__() + self.add_feature(shape_fitter_model()) + self.add_feature(isotopic_fitter_model()) + self.add_feature(spacing_fitter_model()) + self.add_feature(charge_scoring_model()) + if mass_shift_scoring_model is not None: + self.add_feature(mass_shift_scoring_model()) + for model in models: + if model is not None: + self.add_feature(model()) + + def compute_scores(self, chromatogram): + scores = [] + for model in self.features(): + scores.append((model.get_feature_type(), model.score(chromatogram))) + return ChromatogramScoreSet(scores) + + def clone(self): + dup = self.__class__() + for feature in self.features(): + dup.add_feature(feature) + return dup + + +class ModelAveragingScorer(ScorerBase): + def __init__(self, models, weights=None): + if weights is None: + weights = [1.0 for i in range(len(models))] + self.models = models + self.weights = weights + + self.prepare_weights() + + def prepare_weights(self): + a = np.array(self.weights) + a /= a.sum() + self.weights = a + + def compute_scores(self, chromatogram): + score_set = ChromatogramScoreSet({}) + weights = 0 + for model, weight in zip(self.models, self.weights): + score = model.compute_scores(chromatogram) + score_set += (score * weight) + weights += weight + return score_set / weights + + def clone(self): + return self.__class__(list(self.models), list(self.weights)) + + +class CompositionDispatchScorer(ScorerBase): + def __init__(self, rule_model_map, default_model=None): + if default_model is None: + default_model = ChromatogramScorer() + self.rule_model_map = rule_model_map + self.default_model = default_model + + def clone(self): + return self.__class__({k: v.clone() for k, v in self.rule_model_map.items()}, self.default_model.clone()) + + def get_composition(self, obj): + if obj.composition is not None: + if obj.glycan_composition is not None: + return symbolic_composition(obj) + return None + + def find_model(self, composition): + if composition is None: + return self.default_model + for rule in self.rule_model_map: + if rule(composition): + return self.rule_model_map[rule] + + return self.default_model + + def compute_scores(self, chromatogram): + composition = self.get_composition(chromatogram) + model = self.find_model(composition) + return model.compute_scores(chromatogram) + + def accept(self, solution): + composition = self.get_composition(solution) + model = self.find_model(composition) + return model.accept(solution) + + +C = TypeVar(""C"", bound=ChromatogramInterface) + + +class ChromatogramSolution(Generic[C]): + _temp_score = 0.0 + + chromatogram: C + scorer: Optional[ScorerBase] + score: Optional[float] + internal_score: Optional[float] + _temp_score: float + score_set: Optional[ChromatogramScoreSet] + + def __init__(self, chromatogram, score=None, scorer=ChromatogramScorer(), internal_score=None, + score_set=None): + if internal_score is None: + internal_score = score + if isinstance(chromatogram, ChromatogramSolution): + chromatogram = chromatogram.get_chromatogram() + self.chromatogram = chromatogram + self.scorer = scorer + self.internal_score = internal_score + self.score = score + + if score is None: + self.compute_score() + + self.score_set = score_set + + def __getattr__(self, name): + return getattr(object.__getattribute__(self, ""chromatogram""), name) + + def __len__(self): + return len(self.chromatogram) + + def __iter__(self): + return iter(self.chromatogram) + + def __eq__(self, other): + return self.chromatogram.__eq__(other) + + def __hash__(self): + return self.chromatogram.__hash__() + + def compute_score(self): + try: + self.internal_score = self.score = self.scorer.score(self.chromatogram) + except ZeroDivisionError: + self.internal_score = self.score = 0.0 + + def score_components(self): + if self.score_set is None: + self.score_set = self.scorer.compute_scores(self.chromatogram) + return self.score_set + + @property + def logitscore(self) -> float: + return self.scorer.logitscore(self.chromatogram) + + def get_chromatogram(self): + return self.chromatogram + + def clone(self): + data = self.chromatogram.clone() + return self.__class__(data, self.score, self.scorer, self.internal_score) + + def __repr__(self): + return ""ChromatogramSolution(%s, %0.4f, %d, %0.4f)"" % ( + self.chromatogram.composition, self.chromatogram.neutral_mass, + self.chromatogram.n_charge_states, self.score) + + def __getitem__(self, i): + return self.chromatogram[i] + + def __dir__(self): + return list(set(('compute_score', 'score_components')) | set(dir(self.chromatogram))) + + def __eq__(self, other): + return self.get_chromatogram() == other.get_chromatogram() + + def __ne__(self, other): + return self.get_chromatogram() != other.get_chromatogram() + + +ChromatogramInterface.register(ChromatogramSolution) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/isotopic_fit.py",".py","4782","141","import numpy as np + +from ms_deisotope.scoring import g_test_scaled +from ms_deisotope.averagine import glycan, PROTON, mass_charge_ratio, TheoreticalIsotopicPattern +from ms_peak_picker.peak_set import FittedPeak +from brainpy import isotopic_variants + +from glycresoft.chromatogram_tree import Unmodified + +from .base import ScoringFeatureBase, epsilon + + +def envelope_to_peak_list(envelope): + return [FittedPeak(e[0], e[1], 0, 0, 0, 0, 0, 0, 0) for e in envelope] + + +def scale_theoretical_isotopic_pattern(eid, tid): + total = sum(p.intensity for p in eid) + for p in tid: + p.intensity *= total + + +def get_nearest_index(query_mz, peak_list): + best_index = None + best_error = float('inf') + + for i, peak in enumerate(peak_list): + error = abs(peak.mz - query_mz) + if error < best_error: + best_error = error + best_index = i + return best_index + + +def align_peak_list(experimental, theoretical): + retain = [] + for peak in experimental: + retain.append(theoretical[get_nearest_index(peak.mz, theoretical)]) + # return TheoreticalIsotopicPattern(retain, theoretical[0].mz) + return retain + + +def unspool_nodes(node): + yield node + for child in (node).children: + for x in unspool_nodes(child): + yield x + + +class IsotopicPatternConsistencyFitter(ScoringFeatureBase): + feature_type = ""isotopic_fit"" + + def __init__(self, chromatogram, averagine=glycan, charge_carrier=PROTON, weighted=True): + self.chromatogram = chromatogram + self.averagine = averagine + self.charge_carrier = charge_carrier + self.scores = [] + self.intensity = [] + self.mean_fit = None + self.weighted = weighted + + if chromatogram.composition is not None: + if chromatogram.elemental_composition is not None: + self.composition = chromatogram.elemental_composition + else: + raise Exception(chromatogram.composition) + else: + self.composition = None + + self.fit() + + def __repr__(self): + return ""IsotopicPatternConsistencyFitter(%s, %0.4f)"" % (self.chromatogram, self.mean_fit) + + def generate_isotopic_pattern(self, charge, node_type=Unmodified): + if self.composition is not None: + tid = isotopic_variants( + self.composition + node_type.composition, + charge=charge, charge_carrier=self.charge_carrier) + out = [] + total = 0. + for p in tid: + out.append(p) + total += p.intensity + if total >= 0.95: + break + return out + else: + tid = self.averagine.isotopic_cluster( + mass_charge_ratio( + self.chromatogram.neutral_mass + node_type.mass, + charge, charge_carrier=self.charge_carrier), + charge, + charge_carrier=self.charge_carrier) + return tid + + def score_isotopic_pattern(self, deconvoluted_peak, node_type=Unmodified): + eid, tid = self.prepare_isotopic_patterns(deconvoluted_peak, node_type) + return g_test_scaled(None, eid, tid) + + def prepare_isotopic_patterns(self, deconvoluted_peak, node_type=Unmodified): + tid = self.generate_isotopic_pattern(deconvoluted_peak.charge, node_type) + eid = envelope_to_peak_list(deconvoluted_peak.envelope) + scale_theoretical_isotopic_pattern(eid, tid) + tid = align_peak_list(eid, tid) + return eid, tid + + def fit(self): + for node in self.chromatogram.nodes.unspool(): + for peak in node.members: + score = self.score_isotopic_pattern(peak, node.node_type) + self.scores.append(score) + self.intensity.append(peak.intensity) + self.intensity = np.array(self.intensity) + self.scores = np.array(self.scores) + if self.weighted: + self.mean_fit = np.average(self.scores, weights=self.intensity) + else: + self.mean_fit = np.mean(self.scores) + + @classmethod + def score(cls, chromatogram, *args, **kwargs): + return max(1 - cls(chromatogram).mean_fit, epsilon) + + +class IsotopicPatternConsistencyModel(ScoringFeatureBase): + feature_type = ""isotopic_fit"" + + def __init__(self, averagine=glycan, charge_carrier=PROTON): + self.averagine = averagine + self.charge_carrier = charge_carrier + + def fit(self, chromatogram): + fitter = IsotopicPatternConsistencyFitter( + chromatogram, averagine=self.averagine, + charge_carrier=self.charge_carrier) + return fitter + + def score(self, chromatogram, *args, **kwargs): + return max(1 - self.fit(chromatogram).mean_fit, epsilon) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/spacing_fitter.py",".py","7498","235","import numpy as np + +from .base import ScoringFeatureBase, epsilon + + +def total_intensity(peaks): + return sum(p.intensity for p in peaks) + + +def binsearch(array, x): + lo = 0 + hi = len(array) + while hi != lo: + mid = (hi + lo) // 2 + y = array[mid] + err = y - x + if abs(err) < 1e-4: + return mid + elif hi - 1 == lo: + return mid + elif err > 0: + hi = mid + else: + lo = mid + return 0 + + +class TimeOffsetIndex(object): + def __init__(self, array): + self.array = np.array(array) + self.average_delta = self.estimate_average_delta() + + def estimate_average_delta(self, weights=None): + if weights is None: + weights = np.ones(len(self) - 1) + return np.average(self[1:] - self[:-1], weights=weights) + + def index_for(self, x): + return binsearch(self.array, x) + + def __getitem__(self, i): + return self.array[i] + + def __len__(self): + return len(self.array) + + def delta(self, x): + i = self.index_for(x) + if i == 0: + return self.average_delta + try: + y = self.array[i + 1] + return y - x + except IndexError: + return self.average_delta + + +def blunt(x): + if x < 0.1: + return x + elif 0.1 < x < 0.5: + return np.sqrt(x) / 3.5 + else: + return x + + +class ChromatogramSpacingFitter(ScoringFeatureBase): + feature_type = ""spacing_fit"" + + def __init__(self, chromatogram, *args, **kwargs): + transform_fn = kwargs.get(""transform_fn"") + if transform_fn is None: + def transform_fn(x): + return x + self.chromatogram = chromatogram + self.rt_deltas = [] + self.intensity_deltas = [] + self.score = None + self.transform_fn = transform_fn + + if len(chromatogram) < 3: + self.score = 1.0 + else: + self.fit() + + def transform(self, d_rt): + return self.transform_fn(d_rt) + + def fit(self): + times, intensities = self.chromatogram.as_arrays() + last_rt = times[0] + last_int = intensities[0] + + for rt, inten in zip(times[1:], intensities[1:]): + d_rt = rt - last_rt + self.rt_deltas.append(self.transform(d_rt)) + self.intensity_deltas.append(abs(last_int - inten)) + last_rt = rt + last_int = inten + + self.rt_deltas = np.array(self.rt_deltas, dtype=np.float16) + self.intensity_deltas = np.array(self.intensity_deltas, dtype=np.float32) + 1 + + self.score = np.average(self.rt_deltas, weights=self.intensity_deltas) + + def __repr__(self): + return ""ChromatogramSpacingFitter(%s, %0.4f)"" % (self.chromatogram, self.score) + + @classmethod + def score(cls, chromatogram, *args, **kwargs): + return max(1 - 2 * cls(chromatogram, *args, **kwargs).score, epsilon) + + +class RelativeScaleChromatogramSpacingFitter(ChromatogramSpacingFitter): + + def __init__(self, chromatogram, index, *args, **kwargs): + self.index = index + super(RelativeScaleChromatogramSpacingFitter, self).__init__( + chromatogram, *args, **kwargs) + + def fit(self): + times, intensities = self.chromatogram.as_arrays() + last_rt = times[0] + last_int = intensities[0] + + for rt, inten in zip(times[1:], intensities[1:]): + d_rt = rt - last_rt + scale = d_rt / self.index.delta(rt) + self.rt_deltas.append(self.transform(d_rt) * scale) + self.intensity_deltas.append(abs(last_int - inten)) + last_rt = rt + last_int = inten + + self.rt_deltas = np.array(self.rt_deltas, dtype=np.float16) + self.intensity_deltas = np.array(self.intensity_deltas, dtype=np.float32) + 1 + + self.score = np.average(self.rt_deltas, weights=self.intensity_deltas) + + +class PartitionAwareRelativeScaleChromatogramSpacingFitter(RelativeScaleChromatogramSpacingFitter): + def __init__(self, chromatogram, index, gap_size=0.25, *args, **kwargs): + self.gap_size = gap_size + self.partitions = [0] + self.intensities = [] + super(PartitionAwareRelativeScaleChromatogramSpacingFitter, self).__init__( + chromatogram, index, *args, **kwargs) + + def best_partition(self): + i = 0 + n = len(self.partitions) - 1 + abundance = 0 + best_score = 0 + for i in range(n): + start = self.partitions[i] + end = self.partitions[i + 1] - 1 + score = np.average( + self.rt_deltas[start:end], + weights=self.intensity_deltas[start:end]) + current_abundance = np.sum(self.intensities[start:end]) + if current_abundance > abundance: + abundance = current_abundance + best_score = score + + return best_score + + def fit(self): + times, intensities = self.chromatogram.as_arrays() + last_rt = times[0] + last_int = intensities[0] + + i = 1 + for rt, inten in zip(times[1:], intensities[1:]): + d_rt = rt - last_rt + if d_rt > self.gap_size: + self.partitions.append(i) + scale = d_rt / self.index.delta(rt) + self.rt_deltas.append(self.transform(d_rt) * scale) + self.intensity_deltas.append(abs(last_int - inten)) + self.intensities.append(inten) + last_rt = rt + last_int = inten + i += 1 + + self.partitions.append(i - 1) + + self.rt_deltas = np.array(self.rt_deltas, dtype=np.float16) + self.intensity_deltas = np.array(self.intensity_deltas, dtype=np.float32) + 1 + self.intensities = np.array(self.intensities, dtype=np.float32) + + self.score = self.best_partition() + + +class ChromatogramSpacingModel(ScoringFeatureBase): + feature_type = 'spacing_fit' + + def __init__(self, index=None, gap_size=0.25): + self.index = index + self.gap_size = gap_size + self.transform_fn = None + + def configure(self, analysis_data): + peak_loader = analysis_data['peak_loader'] + gap_size = analysis_data['delta_rt'] + self.index = TimeOffsetIndex(peak_loader.ms1_scan_times()) + tic = peak_loader.extract_total_ion_current_chromatogram() + self.index.average_delta = self.index.estimate_average_delta(tic[1:]) + self.gap_size = gap_size + if self.index.average_delta > 0.2: + def transform_fn(x): + return x / (self.index.average_delta * 15) + else: + transform_fn = None + self.transform_fn = transform_fn + return { + ""index"": self.index, + ""gap_size"": self.gap_size, + ""transform_fn"": self.transform_fn + } + + def fit(self, chromatogram): + if self.index is None: + return ChromatogramSpacingFitter(chromatogram) + else: + return PartitionAwareRelativeScaleChromatogramSpacingFitter( + chromatogram, index=self.index, + gap_size=self.gap_size, transform_fn=self.transform_fn) + + def score(self, chromatogram, *args, **kwargs): + if self.index is None: + return ChromatogramSpacingFitter.score(chromatogram) + else: + return PartitionAwareRelativeScaleChromatogramSpacingFitter.score( + chromatogram, index=self.index, gap_size=self.gap_size, + transform_fn=self.transform_fn) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/__init__.py",".py","1662","54","from .base import ( + ScoringFeatureBase, + DummyFeature, + epsilon) + +from .shape_fitter import ( + ChromatogramShapeFitter, ChromatogramShapeModel, AdaptiveMultimodalChromatogramShapeFitter) + +from .spacing_fitter import ( + ChromatogramSpacingFitter, ChromatogramSpacingModel, + PartitionAwareRelativeScaleChromatogramSpacingFitter, + total_intensity) + +from .isotopic_fit import ( + IsotopicPatternConsistencyFitter, IsotopicPatternConsistencyModel) + +from .charge_state import ( + UniformChargeStateScoringModel, MassScalingChargeStateScoringModel, + ChargeStateDistributionScoringModelBase) + +from .chromatogram_solution import ( + ChromatogramSolution, ChromatogramScorer, ModelAveragingScorer, + CompositionDispatchScorer, DummyScorer, ChromatogramScoreSet, + ScorerBase) + +from .mass_shift_scoring import ( + MassScalingMassShiftScoringModel) + +from .utils import logit, logitsum + + +__all__ = [ + ""ScoringFeatureBase"", ""DummyFeature"", ""epsilon"", + + ""ChromatogramShapeFitter"", ""ChromatogramShapeModel"", + ""AdaptiveMultimodalChromatogramShapeFitter"", + + ""ChromatogramSpacingFitter"", ""ChromatogramSpacingModel"", + ""PartitionAwareRelativeScaleChromatogramSpacingFitter"", + ""total_intensity"", + + ""IsotopicPatternConsistencyFitter"", ""IsotopicPatternConsistencyModel"", + ""UniformChargeStateScoringModel"", ""MassScalingChargeStateScoringModel"", + ""ChargeStateDistributionScoringModelBase"", + + ""ChromatogramSolution"", ""ChromatogramScorer"", ""ModelAveragingScorer"", + ""CompositionDispatchScorer"", ""DummyScorer"", ""ChromatogramScoreSet"", + ""ScorerBase"", + + ""MassScalingMassShiftScoringModel"", + + 'logit', 'logitsum', +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/mass_shift_scoring.py",".py","8604","235","import json +import warnings + +from collections import defaultdict +from io import StringIO + +from glypy.composition import Composition, formula + +from glycresoft.chromatogram_tree import Unmodified, MassShift, CompoundMassShift +from .base import ( + MassScalingCountScoringModel, + UniformCountScoringModelBase, + ScoringFeatureBase) + + +class MassShiftScoringModelBase(ScoringFeatureBase): + feature_type = ""mass_shift_score"" + + def __init__(self, mass_shift_types=None): + if mass_shift_types is not None: + self.mass_shift_types = set(mass_shift_types) | {Unmodified} + else: + self.mass_shift_types = None + + def get_state_count(self, chromatogram): + if self.mass_shift_types is None: + return len(chromatogram.mass_shifts) + else: + return len( + [t for t in self.mass_shift_types + if t in chromatogram.mass_shifts]) + + def get_states(self, chromatogram): + if self.mass_shift_types is None: + return chromatogram.mass_shifts + else: + return [t for t in self.mass_shift_types + # if t in chromatogram.mass_shifts + if [k for k in chromatogram.mass_shifts if k == t or k.composed_with(t)] + ] + + def get_signal_proportions(self, chromatogram): + fractions = chromatogram.mass_shift_signal_fractions() + total = sum(fractions.values()) + if self.mass_shift_types is None: + return {k: v / total for k, v in fractions.items()} + else: + proportions = defaultdict(float) + for t in self.mass_shift_types: + for k, f in fractions.items(): + if k.composed_with(t): + proportions[t] += f + total = sum(proportions.values()) + return {k: v / total for k, v in proportions.items()} + + +class UniformMassShiftScoringModel(MassShiftScoringModelBase, UniformCountScoringModelBase): + pass + + +uniform_model = UniformMassShiftScoringModel() + + +class MassScalingMassShiftScoringModel(MassShiftScoringModelBase, MassScalingCountScoringModel): + def __init__(self, table, mass_shift_types=None, neighborhood_width=100., fit_information=None): + MassShiftScoringModelBase.__init__(self, mass_shift_types) + MassScalingCountScoringModel.__init__(self, table, neighborhood_width) + self.fit_information = fit_information or {} + + def transform_state(self, state): + return state.name + + def handle_missing_neighborhood(self, chromatogram, neighborhood, *args, **kwargs): + warnings.warn( + (""%f was not found for this mass_shift "" + ""scoring model. Defaulting to uniform model"") % neighborhood) + return uniform_model.score(chromatogram, *args, **kwargs) + + def handle_missing_bin(self, chromatogram, bins, key, neighborhood, *args, **kwargs): + warnings.warn(""%s not found for this mass range (%f). Using bin average (%r)"" % ( + key, neighborhood, chromatogram.mass_shifts)) + return 0 + + def clone(self): + text_buffer = StringIO() + self.dump(text_buffer) + text_buffer.seek(0) + return self.load(text_buffer) + + def _serialize_mass_shift(self, mass_shift): + return {""name"": mass_shift.name, ""composition"": formula(mass_shift.composition)} + + def _serialize_compound_mass_shift(self, mass_shift): + return { + ""name"": mass_shift.name, + ""composition"": formula(mass_shift.composition), + ""counts"": { + k.name: v for k, v in mass_shift.counts.items() + }, + ""definitions"": { + k.name: formula(k.composition) for k, v in mass_shift.counts.items() + } + } + + def _serialize_mass_shift_types(self): + if self.mass_shift_types is None: + return None + mass_shift_types = [] + for mass_shift in self.mass_shift_types: + if isinstance(mass_shift, CompoundMassShift): + mass_shift_types.append(self._serialize_compound_mass_shift(mass_shift)) + elif isinstance(mass_shift, MassShift): + mass_shift_types.append(self._serialize_mass_shift(mass_shift)) + return mass_shift_types + + @classmethod + def _deserialize_mass_shift(cls, data, memo=None): + if memo is not None: + if data['name'] in memo: + return memo[data['name']] + inst = MassShift(data['name'], Composition(str(data['composition']))) + if memo is not None: + memo[inst.name] = inst + return inst + + @classmethod + def _deserialize_compound_mass_shift(cls, data, memo=None): + if memo is not None: + if data['name'] in memo: + return memo[data['name']] + definitions = {} + for k, v in data['definitions'].items(): + definitions[k] = cls._deserialize_mass_shift({""name"": k, ""composition"": v}) + + components = {} + for k, v in data['counts'].items(): + components[definitions[k]] = v + inst = CompoundMassShift(components) + + if memo is not None: + memo[inst.name] = inst + return inst + + @classmethod + def _deserialize_mass_shift_types(cls, data): + if data is None: + return None + mass_shift_types = [] + memo = { + Unmodified.name: Unmodified + } + for entry in data: + if ""counts"" in entry: + mass_shift_types.append(cls._deserialize_compound_mass_shift(entry, memo)) + else: + mass_shift_types.append(cls._deserialize_mass_shift(entry, memo)) + return mass_shift_types + + def dump(self, file_obj): + json.dump( + { + ""neighborhood_width"": self.neighborhood_width, + ""table"": self.table, + ""mass_shift_types"": self._serialize_mass_shift_types(), + ""fit_information"": self.fit_information + }, + file_obj, indent=4, sort_keys=True) + + @classmethod + def load(cls, file_obj): + data = json.load(file_obj) + table = data.pop(""table"") + width = float(data.pop(""neighborhood_width"")) + mass_shift_types = data.pop(""mass_shift_types"") + if mass_shift_types is not None: + mass_shift_types = cls._deserialize_mass_shift_types(mass_shift_types) + if isinstance(mass_shift_types, list): + mass_shift_types = set(mass_shift_types) + + def numeric_keys(table, dtype=float, convert_value=lambda x: x): + return {abs(dtype(k)): convert_value(v) for k, v in table.items()} + + table = numeric_keys(table) + + return cls(table=table, neighborhood_width=width, mass_shift_types=mass_shift_types) + + @classmethod + def fit(cls, observations, missing=0.01, mass_shift_types=None, neighborhood_width=100., + scale_unmodified=0.25): + if not scale_unmodified: + scale_unmodified = 1 + bins = defaultdict(lambda: defaultdict(float)) + + self = cls({}, mass_shift_types=mass_shift_types, + neighborhood_width=neighborhood_width) + + fit_info = { + ""scale_unmodified"": scale_unmodified, + ""missing"": missing, + ""track"": defaultdict(lambda: defaultdict(list)), + ""count"": defaultdict(int) + } + + all_keys = set() + for sol in observations: + neighborhood = self.neighborhood_of(sol.neutral_mass) + fit_info['count'][neighborhood] += 1 + for c in self.get_states(sol): + key = self.transform_state(c) + all_keys.add(key) + val = sol.total_signal_for(c) / (sol.total_signal) + bins[neighborhood][key] += val + fit_info['track'][neighborhood][key].append(val) + + model_table = {} + + all_states = set() + for level in bins.values(): + all_states.update(level.keys()) + + for neighborhood, counts in bins.items(): + for c in all_states: + if str(c) == Unmodified.name: + counts[c] *= scale_unmodified + counts[str(c)] += missing + total = sum(counts.values()) + entry = {k: v / total for k, v in counts.items()} + model_table[neighborhood] = entry + + return cls(model_table, mass_shift_types=mass_shift_types, neighborhood_width=neighborhood_width, + fit_information=fit_info) + + +MassScalingAdductScoringModel = MassScalingMassShiftScoringModel +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/utils.py",".py","304","23","from operator import mul +try: + reduce +except NameError: + from functools import reduce + +import numpy as np + + +def logit(x): + return np.log(x) - np.log(1 - x) + + +def logitsum(xs): + total = 0 + for x in xs: + total += logit(x) + return total + + +def prod(*x): + return reduce(mul, x, 1) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/base.py",".py","10375","338","import numpy as np +try: + import cPickle as pickle +except ImportError: + import pickle +from abc import ABCMeta, abstractmethod +from six import add_metaclass + +from glycresoft import symbolic_expression +from glycopeptidepy import HashableGlycanComposition +from glypy.structure.glycan_composition import FrozenMonosaccharideResidue as FMR + + +epsilon = 1e-6 + + +def symbolic_composition(obj): + """"""Extract the glycan composition from *obj* and converts it + into an instance of :class:`.GlycanSymbolContext` + + The extraction process first attempts to access *obj.glycan_composition* + but on an :class:`AttributeError` calls :meth:`.HashableGlycanComposition.parse` + on *obj*. The resulting :class:`.GlycanComposition` object is then passed + to :class:`.GlycanSymbolContext` + + Parameters + ---------- + obj : object + The object to convert + + Returns + ------- + GlycanSymbolContext + """""" + try: + composition = obj.glycan_composition + except AttributeError: + composition = HashableGlycanComposition.parse(obj) + composition = symbolic_expression.GlycanSymbolContext(composition) + return composition + + +class ScoringFeatureBase(object): + """"""A base class for a type that either on instantiation + or on invokation of :meth:`score` will produce a confidence + metric for a (possibly annotated) chromatogram + """""" + name = None + feature_type = None + + @classmethod + def get_feature_type(self): + return self.feature_type + + @classmethod + def get_feature_name(self): + name = getattr(self, ""name"", None) + if name is None: + return ""%s:%s"" % (self.get_feature_type(), self.__name__) + else: + return name + + @classmethod + def reject(self, score_components, solution): + score = score_components[self.get_feature_type()] + return score < 0.15 + + @classmethod + def configure(cls, analysis_data): + return {} + + +class DummyFeature(ScoringFeatureBase): + def __init__(self, name, feature_type): + self.name = name + self.feature_type = feature_type + + def score(self, chromatogram, *args, **kwargs): + return 0.985 + + def get_feature_type(self): + return self.feature_type + + def get_feature_name(self): + name = getattr(self, ""name"", None) + if name is None: + name = self.__name__ + return ""%s:%s"" % (self.get_feature_type(), name) + + def reject(self, score_components, solution): + score = score_components[self.feature_type] + return score < 0.15 + + def clone(self): + return self + + +@add_metaclass(ABCMeta) +class DiscreteCountScoringModelBase(object): + def __init__(self, *args, **kwargs): + pass + + def score(self, chromatogram, *args, **kwargs): + return 0 + + def dump(self, file_obj): + pickle.dump(self, file_obj) + + @classmethod + def load(cls, file_obj): + return pickle.load(file_obj) + + @abstractmethod + def get_state_count(self, chromatogram): + # Returns the number of states + raise NotImplementedError() + + @abstractmethod + def get_states(self, chromatogram): + # Returns a list enumerating the states + # this entity was observed in + raise NotImplementedError() + + @abstractmethod + def get_signal_proportions(self, chromatogram): + # Returns a mapping from state to proportion of + # total signal observed in state + raise NotImplementedError() + + def reject(self, score_components, solution): + score = score_components[self.feature_type] + return score < 0.15 + + +class UniformCountScoringModelBase(DiscreteCountScoringModelBase): + def score(self, chromatogram, *args, **kwargs): + return min(0.4 * self.get_state_count(chromatogram), 1.0) - epsilon + + +def decay(x, step=0.4, rate=1.5): + v = 0 + for i in range(x): + v += (step / (i + rate)) + return v + + +class DecayRateCountScoringModelBase(DiscreteCountScoringModelBase): + def __init__(self, step=0.4, rate=1.5): + self.step = step + self.rate = rate + + def score(self, chromatogram, *args, **kwargs): + k = self.get_state_count(chromatogram) + return decay(k, self.step, self.rate) - epsilon + + def clone(self): + return self.__class__(self.step, self.rate) + + +class LogarithmicCountScoringModelBase(DiscreteCountScoringModelBase): + def __init__(self, steps=5): + self.base = steps + + def _logarithmic_change_of_base(self, k): + if k >= self.base: + return 1.0 + return np.log(k) / np.log(self.base) + + def score(self, chromatogram, *args, **kwargs): + # Ensure k > 1 so that the value is greater than 0.0 + # as `log(1) = 0` + k = self.get_state_count(chromatogram) + 1 + return self._logarithmic_change_of_base(k) - epsilon + + def clone(self): + return self.__class__(self.base) + + +def ones(x): + return (x - (np.floor(x / 10.) * 10)) + + +def neighborhood_of(x, scale=100.): + n = x / scale + up = ones(n) > 5 + if up: + neighborhood = (np.floor(n / 10.) + 1) * 10 + else: + neighborhood = (np.floor(n / 10.) + 1) * 10 + return neighborhood * scale + + +class MassScalingCountScoringModel(DiscreteCountScoringModelBase): + def __init__(self, table, neighborhood_width=100.): + self.table = table + self.neighborhood_width = neighborhood_width + + def neighborhood_of(self, mass): + n = mass / self.neighborhood_width + up = ones(n) > 5 + if up: + neighborhood = (np.floor(n / 10.) + 1) * 10 + else: + neighborhood = (np.floor(n / 10.) + 1) * 10 + return neighborhood * self.neighborhood_width + + def get_neighborhood_key(self, neutral_mass): + neighborhood = self.neighborhood_of(neutral_mass) + return neighborhood + + def handle_missing_neighborhood(self, chromatogram, neighborhood, *args, **kwargs): + return 0 + + def handle_missing_bin(self, chromatogram, bins, key, neighborhood, *args, **kwargs): + return sum(bins.values()) / float(len(bins)) + + def transform_state(self, state): + return state + + def score(self, chromatogram, *args, **kwargs): + total = 0. + neighborhood = self.get_neighborhood_key(chromatogram.neutral_mass) + if neighborhood not in self.table: + return self.handle_missing_neighborhood( + chromatogram, neighborhood, *args, **kwargs) + + bins = self.table[neighborhood] + + for state in self.get_states(chromatogram): + state = self.transform_state(state) + try: + total += bins[state] + except KeyError: + total += self.handle_missing_bin( + chromatogram, bins, state, neighborhood, *args, **kwargs) + total = max(min(total, 1.0) - epsilon, epsilon) + return total + + def clone(self): + return self.__class__(self.table, self.neighborhood_width) + + +class ProportionBasedMassScalingCountScoringModel(MassScalingCountScoringModel): + + def kullback_leibler_divergence(self, observed, expected): + total = 0 + for key in expected: + try: + observed_frequency = observed[key] + except KeyError: + observed_frequency = 1e-3 + total += observed_frequency * (np.log(observed_frequency) - np.log(expected[key])) + return total + + def expnorm_kl(self, observed, expected): + return 1 - np.exp(-self.kullback_leibler_divergence(observed, expected)) + + def score(self, chromatogram, *args, **kwargs): + neighborhood = self.get_neighborhood_key(chromatogram.neutral_mass) + if neighborhood not in self.table: + return self.handle_missing_neighborhood( + chromatogram, neighborhood, *args, **kwargs) + + model_bin = self.table[neighborhood] + observed_dist = dict() + + for key, proportion in self.get_signal_proportions(chromatogram): + key = self.transform_state(key) + observed_dist[key] = proportion + score = self.expnorm_kl(observed_dist, model_bin) + score = max(min(score, 1.0) - epsilon, epsilon) + return score + + +class CompositionDispatchingModel(ScoringFeatureBase): + def __init__(self, rule_model_map, default_model): + self.rule_model_map = rule_model_map + self.default_model = default_model + + def get_composition(self, obj): + if obj.composition is not None: + if obj.glycan_composition is not None: + return symbolic_composition(obj) + return None + + def find_model(self, composition): + if composition is None: + return self.default_model + for rule in self.rule_model_map: + if rule(composition): + return self.rule_model_map[rule] + + return self.default_model + + def score(self, chromatogram, *args, **kwargs): + composition = self.get_composition(chromatogram) + model = self.find_model(composition) + return model.score(chromatogram, *args, **kwargs) + + def get_feature_type(self): + return self.default_model.get_feature_type() + + def get_feature_name(self): + return ""%s:%s(%s)"" % ( + self.get_feature_type(), self.__class__.__name__, + "", "".join([v.get_feature_name() + for v in self.rule_model_map.values()])) + + def reject(self, score_components, solution): + # score = score_components[self.get_feature_type()] + # return score < 0.15 + composition = self.get_composition(solution) + model = self.find_model(composition) + return model.reject(score_components, solution) + + def clone(self): + return self.__class__(self.rule_model_map, self.default_model) + + +neuac = FMR.from_iupac_lite(""NeuAc"") +neugc = FMR.from_iupac_lite(""NeuGc"") +neu = FMR.from_iupac_lite(""Neu"") +sulfate = FMR.from_iupac_lite(""@sulfate"") +hexuronic_acid = FMR.from_iupac_lite(""aHex"") + + +def is_sialylated(composition): + return (composition[neuac] + composition[neugc] + composition[neu]) > 0 + + +def degree_of_sialylation(composition): + return (composition[neuac] + composition[neugc] + composition[neu]) + + +def is_high_mannose(composition): + return (composition['HexNAc'] == 2 and composition['Hex'] > 3 and + not is_sialylated(composition)) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/shape_fitter.py",".py","26629","811","from collections import OrderedDict +from itertools import product + +import six + +import numpy as np + +from scipy.optimize import leastsq +from numpy import pi, sqrt, exp +from scipy.special import erf +from scipy.ndimage import gaussian_filter1d + +from ms_peak_picker import search + +from .base import ScoringFeatureBase, epsilon + +try: + trapezoid = np.trapz +except AttributeError: + trapezoid = np.trapezoid + +MIN_POINTS = 5 +MAX_POINTS = 2000 +SIGMA_EPSILON = 1e-3 + + +def prepare_arrays_for_linear_fit(x, y): + X = np.vstack((np.ones(len(x)), np.array(x))).T + Y = np.array(y) + return X, Y + + +def linear_regression_fit(x, y, prepare=False): + if prepare: + x, y = prepare_arrays_for_linear_fit(x, y) + B = np.linalg.inv(x.T.dot(x)).dot(x.T.dot(y)) + Yhat = x.dot(B) + return Yhat + + +def linear_regression_residuals(x, y): + X, Y = prepare_arrays_for_linear_fit(x, y) + Yhat = linear_regression_fit(X, Y) + return (Y - Yhat) ** 2 + + +def flat_line_residuals(y): + residuals = ( + (y - ((y.max() + y.min()) / 2.))) ** 2 + return residuals + + +class PeakShapeModelBase(object): + def __repr__(self): + return ""{self.__class__.__name__}()"".format(self=self) + + @classmethod + def nargs(self): + return six.get_function_code(self.shape).co_argcount - 1 + + @classmethod + def get_min_points(self): + return getattr(self, ""min_points"", self.nargs() + 1) + + +def gaussian_shape(xs, center, amplitude, sigma): + if sigma == 0: + sigma = SIGMA_EPSILON + norm = (amplitude) / (sigma * sqrt(2 * pi)) * \ + exp(-((xs - center) ** 2) / (2 * sigma ** 2)) + return norm + + +class GaussianModel(PeakShapeModelBase): + min_points = 6 + + @staticmethod + def fit(params, xs, ys): + center, amplitude, sigma = params + return ys - GaussianModel.shape(xs, center, amplitude, sigma) + + @staticmethod + def shape(xs, center, amplitude, sigma): + return gaussian_shape(xs, center, amplitude, sigma) + + @staticmethod + def guess(xs, ys): + center = np.average(xs, weights=ys / ys.sum()) + height_at = np.abs(xs - center).argmin() + apex = ys[height_at] + sigma = np.abs(center - xs[[search.nearest_left(ys, apex / 2, height_at), + search.nearest_right(ys, apex / 2, height_at + 1)]]).sum() + return center, apex, sigma + + @staticmethod + def params_to_dict(params): + center, amplitude, sigma = params + return OrderedDict(((""center"", center), (""amplitude"", amplitude), (""sigma"", sigma))) + + @staticmethod + def center(params_dict): + return params_dict['center'] + + @staticmethod + def spread(params_dict): + return params_dict['sigma'] + + +class SimplifiedGaussianModel(GaussianModel): + def __init__(self, chromatogram): + xs, ys = chromatogram.as_arrays() + self.mean, self.base_amplitude, self.sigma = GaussianModel.guess(xs, ys) + + def guess(self, chromatogram): + return (self.base_amplitude,) + + def shape(self, xs, amplitude): + return GaussianModel.shape(xs, self.mean, amplitude, self.sigma) + + def fit(self, xs, ys, params): + amplitude, = params + return ys - self.shape(xs, amplitude) + + +def skewed_gaussian_shape(xs, center, amplitude, sigma, gamma): + if sigma == 0: + sigma = SIGMA_EPSILON + amp_over_sigma_sqrt2pi = (amplitude) / (sigma * sqrt(2 * pi)) + sigma_squared_2 = 2 * sigma ** 2 + sigma_sqrt2 = (sigma * sqrt(2)) + + norm = amp_over_sigma_sqrt2pi * \ + exp(-((xs - center) ** 2) / sigma_squared_2) + skew = (1 + erf((gamma * (xs - center)) / sigma_sqrt2)) + return norm * skew + + +class SkewedGaussianModel(PeakShapeModelBase): + @staticmethod + def fit(params, xs, ys): + center, amplitude, sigma, gamma = params + return ys - SkewedGaussianModel.shape(xs, center, amplitude, sigma, gamma) * ( + sigma / 2. if abs(sigma) > 2 else 1.) + + @staticmethod + def guess(xs, ys): + center = np.average(xs, weights=ys / ys.sum()) + height_at = np.abs(xs - center).argmin() + apex = ys[height_at] + sigma = np.abs(center - xs[[search.nearest_left(ys, apex / 2, height_at), + search.nearest_right(ys, apex / 2, height_at + 1)]]).sum() + gamma = 1 + return center, apex, sigma, gamma + + @staticmethod + def params_to_dict(params): + center, amplitude, sigma, gamma = params + return OrderedDict(((""center"", center), (""amplitude"", amplitude), (""sigma"", sigma), (""gamma"", gamma))) + + @staticmethod + def shape(xs, center, amplitude, sigma, gamma): + return skewed_gaussian_shape(xs, center, amplitude, sigma, gamma) + + @staticmethod + def center(params_dict): + return params_dict['center'] + + @staticmethod + def spread(params_dict): + return params_dict['sigma'] + + +class PenalizedSkewedGaussianModel(SkewedGaussianModel): + @staticmethod + def fit(params, xs, ys): + center, amplitude, sigma, gamma = params + return ys - PenalizedSkewedGaussianModel.shape(xs, center, amplitude, sigma, gamma) * ( + sigma / 2. if abs(sigma) > 2 else 1.) * (gamma / 2. if abs(gamma) > 40 else 1.) * ( + center if center > xs[-1] or center < xs[0] else 1.) + + +def bigaussian_shape(xs, center, amplitude, sigma_left, sigma_right): + if sigma_left == 0: + sigma_left = SIGMA_EPSILON + if sigma_right == 0: + sigma_right = SIGMA_EPSILON + ys = np.zeros_like(xs, dtype=np.float32) + left_mask = xs < center + ys[left_mask] = amplitude / sqrt(2 * pi) * np.exp(-(xs[left_mask] - center) ** 2 / (2 * sigma_left ** 2)) + right_mask = xs >= center + ys[right_mask] = amplitude / sqrt(2 * pi) * np.exp(-(xs[right_mask] - center) ** 2 / (2 * sigma_right ** 2)) + return ys + + +class BiGaussianModel(PeakShapeModelBase): + + @staticmethod + def center(params_dict): + return params_dict['center'] + + @staticmethod + def spread(params_dict): + return (params_dict['sigma_left'] + params_dict['sigma_right']) / 2. + + @staticmethod + def shape(xs, center, amplitude, sigma_left, sigma_right): + return bigaussian_shape(xs, center, amplitude, sigma_left, sigma_right) + + @staticmethod + def fit(params, xs, ys): + center, amplitude, sigma_left, sigma_right = params + return ys - BiGaussianModel.shape( + xs, center, amplitude, sigma_left, sigma_right) * ( + center if center > xs[-1] or center < xs[0] else 1.) + + @staticmethod + def params_to_dict(params): + center, amplitude, sigma_left, sigma_right = params + return OrderedDict( + ((""center"", center), (""amplitude"", amplitude), (""sigma_left"", sigma_left), (""sigma_right"", sigma_right))) + + @staticmethod + def guess(xs, ys): + center = np.average(xs, weights=ys / ys.sum()) + height_at = np.abs(xs - center).argmin() + apex = ys[height_at] + sigma = np.abs(center - xs[[search.nearest_left(ys, apex / 2, height_at), + search.nearest_right(ys, apex / 2, height_at + 1)]]).sum() + return center, apex, sigma, sigma + + +class FittedPeakShape(object): + def __init__(self, params, shape_model): + self.params = params + self.shape_model = shape_model + + def keys(self): + return self.params.keys() + + def values(self): + return self.params.values() + + def items(self): + return self.params.items() + + def __iter__(self): + return iter(self.params) + + def shape(self, xs): + return self.shape_model.shape(xs, **self.params) + + def __getitem__(self, key): + return self.params[key] + + def __repr__(self): + return ""Fitted{self.shape_model.__class__.__name__}({params})"".format( + self=self, params="", "".join(""%s=%0.3f"" % (k, v) for k, v in self.params.items())) + + @property + def center(self): + return self['center'] + + @property + def amplitude(self): + return self['amplitude'] + + @property + def spread(self): + return self.shape_model.spread(self) + + +class ChromatogramShapeFitterBase(ScoringFeatureBase): + feature_type = ""line_score"" + + def __init__(self, chromatogram, smooth=True, fitter=PenalizedSkewedGaussianModel()): + self.chromatogram = chromatogram + self.smooth = smooth + self.xs = None + self.ys = None + self.line_test = None + self.off_center = None + self.shape_fitter = fitter + + def is_invalid(self): + n = len(self.chromatogram) + return n < MIN_POINTS or n < self.shape_fitter.get_min_points() + + def handle_invalid(self): + self.line_test = 1 - 5e-6 + + def extract_arrays(self): + self.xs, self.ys = self.chromatogram.as_arrays() + if self.smooth: + self.ys = gaussian_filter1d(self.ys, self.smooth) + if len(self.xs) > MAX_POINTS: + new_xs = np.linspace(self.xs.min(), self.xs.max(), MAX_POINTS) + new_ys = np.interp(new_xs, self.xs, self.ys) + self.xs = new_xs + self.ys = new_ys + self.ys = gaussian_filter1d(self.ys, self.smooth) + + def compute_residuals(self): + raise NotImplementedError() + + def compute_fitted(self): + raise NotImplementedError() + + def null_model_residuals(self): + residuals = linear_regression_residuals(self.xs, self.ys) + return residuals + + def perform_line_test(self): + residuals = self.compute_residuals() + line_test = (residuals ** 2).sum() / ( + (self.null_model_residuals()).sum()) + self.line_test = max(line_test, 1e-5) + + def plot(self, ax=None): + if ax is None: + from matplotlib import pyplot as plt + fig, ax = plt.subplots(1) + ob1 = ax.plot(self.xs, self.ys, label='Observed')[0] + ob2 = ax.scatter(self.xs, self.ys, label='Observed') + f1 = ax.plot(self.xs, self.compute_fitted(), label='Fitted')[0] + r1 = ax.plot(self.xs, self.compute_residuals(), label='Residuals')[0] + ax.legend( + ( + (ob1, ob2), + (f1,), + (r1,) + ), (""Observed"", ""Fitted"", ""Residuals"") + ) + return ax + + @property + def fit_parameters(self): + raise NotImplementedError() + + @classmethod + def score(cls, chromatogram, *args, **kwargs): + return max(1 - cls(chromatogram).line_test, epsilon) + + def integrate(self): + time = self.xs + smoothed = self.compute_fitted() + return trapezoid(smoothed, time) + + +class ChromatogramShapeFitter(ChromatogramShapeFitterBase): + def __init__(self, chromatogram, smooth=True, fitter=PenalizedSkewedGaussianModel()): + super(ChromatogramShapeFitter, self).__init__(chromatogram, smooth=smooth, fitter=fitter) + + self.params = None + self.params_dict = None + + if self.is_invalid(): + self.handle_invalid() + else: + self.extract_arrays() + self.peak_shape_fit() + self.perform_line_test() + self.off_center_factor() + + @property + def fit_parameters(self): + return self.params_dict + + def __repr__(self): + return ""ChromatogramShapeFitter(%s, %0.4f)"" % (self.chromatogram, self.line_test) + + def off_center_factor(self): + center = self.shape_fitter.center(self.params_dict) + spread = self.shape_fitter.spread(self.params_dict) + self.off_center = abs(1 - abs(1 - (2 * abs( + self.xs[self.ys.argmax()] - center) / abs(spread)))) + if self.off_center > 1: + self.off_center = 1. / self.off_center + self.line_test /= self.off_center + + def compute_residuals(self): + return self.shape_fitter.fit(self.params, self.xs, self.ys) + + def compute_fitted(self): + return self.shape_fitter.shape(self.xs, **self.params_dict) + + def interpolate(self, x): + return self.shape_fitter.shape(x, **self.params_dict) + + def peak_shape_fit(self): + xs, ys = self.xs, self.ys + params = self.shape_fitter.guess(xs, ys) + fit = leastsq(self.shape_fitter.fit, + params, (xs, ys)) + params = fit[0] + self.params = params + self.params_dict = FittedPeakShape(self.shape_fitter.params_to_dict(params), self.shape_fitter) + + def iterfits(self): + yield self.compute_fitted() + + +def shape_fit_test(chromatogram, smooth=True): + return ChromatogramShapeFitter(chromatogram, smooth).line_test + + +def peak_indices(x, min_height=0): + """"""Find the index of local maxima. + + Parameters + ---------- + x : np.ndarray + Data to find local maxima in + min_height : float, optional + Minimum peak height + + Returns + ------- + np.ndarray[int] + Indices of maxima in x + + References + ---------- + https://github.com/demotu/BMC/blob/master/functions/detect_peaks.py + """""" + if x.size < 3: + return np.array([], dtype=int) + # find indices of all peaks + dx = x[1:] - x[:-1] + rising_edges = np.where((np.hstack((dx, 0)) <= 0) & + (np.hstack((0, dx)) > 0))[0] + falling_edges = np.where((np.hstack((dx, 0)) < 0) & + (np.hstack((0, dx)) >= 0))[0] + indices = np.unique(np.hstack((rising_edges, falling_edges))) + if indices.size and min_height > 0: + indices = indices[x[indices] >= min_height] + return indices + + +class MultimodalChromatogramShapeFitter(ChromatogramShapeFitterBase): + def __init__(self, chromatogram, max_peaks=5, smooth=True, fitter=BiGaussianModel()): + super(MultimodalChromatogramShapeFitter, self).__init__(chromatogram, smooth=smooth, fitter=fitter) + self.max_peaks = max_peaks + self.params_list = [] + self.params_dict_list = [] + + if self.is_invalid(): + self.handle_invalid() + else: + try: + self.extract_arrays() + self.peak_shape_fit() + self.perform_line_test() + except TypeError: + self.handle_invalid() + + @property + def fit_parameters(self): + return self.params_dict_list + + def __repr__(self): + return ""MultimodalChromatogramShapeFitter(%s, %0.4f)"" % (self.chromatogram, self.line_test) + + def peak_shape_fit(self): + return self.set_up_peak_fit() + + def set_up_peak_fit(self, ys=None, min_height=0, peak_count=0): + xs = self.xs + if ys is None: + ys = self.ys + params = self.shape_fitter.guess(xs, ys) + params_dict = self.shape_fitter.params_to_dict(params) + + indices = peak_indices(ys, min_height) + center = xs[max(indices, key=lambda x: ys[x])] + params_dict['center'] = center + + fit = leastsq(self.shape_fitter.fit, + list(params_dict.values()), (xs, ys)) + params = fit[0] + params_dict = FittedPeakShape(self.shape_fitter.params_to_dict(params), self.shape_fitter) + self.params_list.append(params) + self.params_dict_list.append(params_dict) + + residuals = self.shape_fitter.fit(params, xs, ys) + + fitted_apex_index = search.get_nearest(xs, params_dict['center'], 0) + fitted_apex = ys[fitted_apex_index] + + new_min_height = fitted_apex * 0.5 + + if new_min_height < min_height: + min_height *= 0.85 + else: + min_height = new_min_height + + indices = peak_indices(residuals, min_height) + + peak_count += 1 + if indices.size and peak_count < self.max_peaks: + residuals, params_dict = self.set_up_peak_fit(residuals, min_height, peak_count=peak_count) + + return residuals, params_dict + + def compute_fitted(self): + xs = self.xs + fitted = np.zeros_like(xs) + for params_dict in self.params_dict_list: + fitted += self.shape_fitter.shape(xs, **params_dict) + return fitted + + def interpolate(self, x): + fitted = np.zeros_like(x) + for params_dict in self.params_dict_list: + fitted += self.shape_fitter.shape(x, **params_dict) + return fitted + + def compute_residuals(self): + return self.ys - self.compute_fitted() + + def iterfits(self): + xs = self.xs + for params_dict in self.params_dict_list: + yield self.shape_fitter.shape(xs, **params_dict) + + +class AdaptiveMultimodalChromatogramShapeFitter(ChromatogramShapeFitterBase): + def __init__(self, chromatogram, max_peaks=5, smooth=True, fitters=None): + if fitters is None: + fitters = (GaussianModel(), BiGaussianModel(), PenalizedSkewedGaussianModel(),) + super(AdaptiveMultimodalChromatogramShapeFitter, self).__init__( + chromatogram, smooth=smooth, fitter=fitters[0]) + self.max_peaks = max_peaks + self.fitters = fitters + self.params_list = [] + self.params_dict_list = [] + + self.alternative_fits = [] + self.best_fit = None + + if self.is_invalid(): + self.handle_invalid() + else: + self.extract_arrays() + self.peak_shape_fit() + self.perform_line_test() + + def is_invalid(self): + return len(self.chromatogram) < MIN_POINTS + + @property + def fit_parameters(self): + return self.best_fit.fit_parameters + + @property + def xs(self): + try: + return self.best_fit.xs + except AttributeError: + return self._xs + + @xs.setter + def xs(self, value): + self._xs = value + + @property + def ys(self): + try: + return self.best_fit.ys + except AttributeError: + return self._ys + + @ys.setter + def ys(self, value): + self._ys = value + + def compute_fitted(self): + return self.best_fit.compute_fitted() + + def interpolate(self, x): + return self.best_fit.interpolate(x) + + def compute_residuals(self): + return self.best_fit.compute_residuals() + + def _get_gap_size(self): + return np.average(self.xs[1:] - self.xs[:-1], + weights=(self.ys[1:] + self.ys[:-1])) * 2 + + def has_sparse_tails(self): + gap = self._get_gap_size() + partition = [False, False] + if self.xs[1] - self.xs[0] > gap: + partition[0] = True + if self.xs[-1] - self.xs[-2] > gap: + partition[1] = True + return partition + + def generate_trimmed_chromatogram_slices(self): + for tails in set(product(*zip(self.has_sparse_tails(), [False, False]))): + if not tails[0] and not tails[1]: + continue + if tails[0]: + slice_start = self.xs[1] + else: + slice_start = self.xs[0] + if tails[1]: + slice_end = self.xs[-2] + else: + slice_end = self.xs[-1] + subset = self.chromatogram.slice(slice_start, slice_end) + yield subset + + def peak_shape_fit(self): + for fitter in self.fitters: + model_fit = ProfileSplittingMultimodalChromatogramShapeFitter( + self.chromatogram, self.max_peaks, self.smooth, fitter=fitter) + self.alternative_fits.append(model_fit) + model_fit = MultimodalChromatogramShapeFitter( + self.chromatogram, self.max_peaks, self.smooth, fitter=fitter) + self.alternative_fits.append(model_fit) + for subset in self.generate_trimmed_chromatogram_slices(): + model_fit = ProfileSplittingMultimodalChromatogramShapeFitter( + subset, self.max_peaks, + self.smooth, fitter=fitter) + self.alternative_fits.append(model_fit) + ix = np.nanargmin([f.line_test for f in self.alternative_fits]) + # self.best_fit = min(self.alternative_fits, key=lambda x: x.line_test) + self.best_fit = self.alternative_fits[ix] + self.params_list = self.best_fit.params_list + self.params_dict_list = self.best_fit.params_dict_list + self.shape_fitter = self.best_fit.shape_fitter + + def perform_line_test(self): + self.line_test = self.best_fit.line_test + + def plot(self, *args, **kwargs): + return self.best_fit.plot(*args, **kwargs) + + def iterfits(self): + xs = self.xs + for params_dict in self.params_dict_list: + yield self.shape_fitter.shape(xs, **params_dict) + + def __repr__(self): + return ""AdaptiveMultimodalChromatogramShapeFitter(%s, %0.4f)"" % (self.chromatogram, self.line_test) + + +class SplittingPoint(object): + __slots__ = [""first_maximum"", ""minimum"", ""second_maximum"", ""minimum_index"", ""total_distance""] + + def __init__(self, first_maximum, minimum, second_maximum, minimum_index): + self.first_maximum = first_maximum + self.minimum = minimum + self.second_maximum = second_maximum + self.minimum_index = minimum_index + self.total_distance = self.compute_distance() + + def compute_distance(self): + return (self.first_maximum - self.minimum) + (self.second_maximum - self.minimum) + + def __repr__(self): + return ""SplittingPoint(%0.4f, %0.4f, %0.4f, %0.2f, %0.3e)"" % ( + self.first_maximum, self.minimum, self.second_maximum, self.minimum_index, self.total_distance) + + +class ProfileSplittingMultimodalChromatogramShapeFitter(ChromatogramShapeFitterBase): + def __init__(self, chromatogram, max_splits=3, smooth=True, fitter=BiGaussianModel()): + super(ProfileSplittingMultimodalChromatogramShapeFitter, self).__init__( + chromatogram, smooth=smooth, fitter=fitter) + self.max_splits = max_splits + self.params_list = [] + self.params_dict_list = [] + self.partition_sites = [] + + if self.is_invalid(): + self.handle_invalid() + else: + self.extract_arrays() + self.peak_shape_fit() + self.perform_line_test() + + def __repr__(self): + return ""ProfileSplittingMultimodalChromatogramShapeFitter(%s, %0.4f)"" % (self.chromatogram, self.line_test) + + def _extreme_indices(self, ys): + maxima_indices = peak_indices(ys) + minima_indices = peak_indices(-ys) + return maxima_indices, minima_indices + + def locate_extrema(self, xs=None, ys=None): + if xs is None: + xs = self.xs + if ys is None: + ys = self.ys + + maxima_indices, minima_indices = self._extreme_indices(ys) + candidates = [] + + for i in range(len(maxima_indices)): + max_i = maxima_indices[i] + for j in range(i + 1, len(maxima_indices)): + max_j = maxima_indices[j] + for k in range(len(minima_indices)): + min_k = minima_indices[k] + y_i = ys[max_i] + y_j = ys[max_j] + y_k = ys[min_k] + if max_i < min_k < max_j and (y_i - y_k) > (y_i * 0.01) and ( + y_j - y_k) > (y_j * 0.01): + point = SplittingPoint(y_i, y_k, y_j, xs[min_k]) + candidates.append(point) + if candidates: + best_point = max(candidates, key=lambda x: x.total_distance) + self.partition_sites.append(best_point) + + return candidates + + def build_partitions(self): + segments = [] + + last_x = self.xs.min() - 1 + for point in self.partition_sites: + mask = (self.xs <= point.minimum_index) & (self.xs > last_x) + if any(mask): + xs, ys = self.xs[mask], self.ys[mask] + # if len(xs) > 1: + segments.append((xs, ys)) + last_x = point.minimum_index + mask = self.xs > last_x + if any(mask): + xs, ys = self.xs[mask], self.ys[mask] + # if len(xs) > 1: + segments.append((xs, ys)) + return segments + + def set_up_peak_fit(self, xs, ys): + params = self.shape_fitter.guess(xs, ys) + params_dict = FittedPeakShape(self.shape_fitter.params_to_dict(params), self.shape_fitter) + if len(params) > len(xs): + self.params_list.append(params) + self.params_dict_list.append(params_dict) + return ys, params_dict + + fit = leastsq(self.shape_fitter.fit, + list(params_dict.values()), (xs, ys)) + params = fit[0] + params_dict = FittedPeakShape(self.shape_fitter.params_to_dict(params), self.shape_fitter) + self.params_list.append(params) + self.params_dict_list.append(params_dict) + + residuals = self.shape_fitter.fit(params, xs, ys) + return residuals, params_dict + + def peak_shape_fit(self): + self.locate_extrema() + for segment in self.build_partitions(): + self.set_up_peak_fit(*segment) + + def compute_fitted(self): + fitted = [] + for segment, params_dict in zip(self.build_partitions(), self.params_dict_list): + fitted.append(self.shape_fitter.shape(segment[0], **params_dict)) + return np.concatenate(fitted) + + def interpolate(self, x): + fitted = np.zeros_like(x) + for params_dict in self.params_dict_list: + fitted += self.shape_fitter.shape(x, **params_dict) + return fitted + + def compute_residuals(self): + return self.ys - self.compute_fitted() + + def iterfits(self): + for segment, params_dict in zip(self.build_partitions(), self.params_dict_list): + yield self.shape_fitter.shape(segment[0], **params_dict) + + +try: + _bigaussian_shape = bigaussian_shape + _skewed_gaussian_shape = skewed_gaussian_shape + _gaussian_shape = gaussian_shape + + from ms_deisotope._c.feature_map.shape_fitter import ( + bigaussian_shape, skewed_gaussian_shape, gaussian_shape) + + has_c = True +except ImportError: + has_c = False + +try: + _plocate_extrema = ProfileSplittingMultimodalChromatogramShapeFitter.locate_extrema + from glycresoft._c.scoring.shape_fitter import locate_extrema as _clocate_extrema + ProfileSplittingMultimodalChromatogramShapeFitter.locate_extrema = _clocate_extrema +except ImportError: + pass + + +class ChromatogramShapeModel(ScoringFeatureBase): + feature_type = ""line_score"" + + def __init__(self, smooth=True): + self.smooth = smooth + + def fit(self, chromatogram, *args, **kwargs): + return AdaptiveMultimodalChromatogramShapeFitter(chromatogram, smooth=self.smooth) + + def score(self, chromatogram, *args, **kwargs): + fit = self.fit(chromatogram, *args, **kwargs) + return max(1 - fit.line_test, epsilon) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/charge_state.py",".py","7500","230","import json +import warnings + +from collections import defaultdict +from io import StringIO + +import numpy as np + +from .base import ( + UniformCountScoringModelBase, + DecayRateCountScoringModelBase, + LogarithmicCountScoringModelBase, + MassScalingCountScoringModel, + ScoringFeatureBase) + + +class ChargeStateDistributionScoringModelBase(ScoringFeatureBase): + feature_type = ""charge_count"" + + def get_state_count(self, chromatogram): + return chromatogram.n_charge_states + + def get_states(self, chromatogram): + return chromatogram.charge_states + + def get_signal_proportions(self, chromatogram): + proportions = {} + states = self.get_states(chromatogram) + rest = chromatogram + total = 0 + for state in states: + part, rest = rest.bisect_charge(state) + proportions[state] = part.total_signal + total += part.total_signal + for k in proportions: + proportions[k] /= total + # Anything left in `rest` is from a charge state with too + # little support to be used + return proportions + + def reject(self, score_components, solution): + score = score_components[self.feature_type] + return score < 0.05 + + +_CHARGE_MODEL = ChargeStateDistributionScoringModelBase + + +class UniformChargeStateScoringModel( + _CHARGE_MODEL, UniformCountScoringModelBase): + pass + + +class DecayRateChargeStateScoringModel( + _CHARGE_MODEL, DecayRateCountScoringModelBase): + pass + + +class LogarithmicChargeStateScoringModel( + _CHARGE_MODEL, LogarithmicCountScoringModelBase): + pass + + +def decay(x, step=0.4, rate=1.5): + v = 0 + for i in range(x): + v += (step / (i + rate)) + return v + + +def ones(x): + return (x - (np.floor(x / 10.) * 10)) + + +def neighborhood_of(x, scale=100.): + n = x / scale + up = ones(n) > 5 + if up: + neighborhood = (np.floor(n / 10.) + 1) * 10 + else: + neighborhood = (np.floor(n / 10.) + 1) * 10 + return neighborhood * scale + + +uniform_model = UniformChargeStateScoringModel() +decay_model = DecayRateChargeStateScoringModel() + + +class MassScalingChargeStateScoringModel(_CHARGE_MODEL, MassScalingCountScoringModel): + def __init__(self, table, neighborhood_width=100., fit_information=None): + # self.table = table + # self.neighborhood_width = neighborhood_width + _CHARGE_MODEL.__init__(self) + MassScalingCountScoringModel.__init__(self, table, neighborhood_width) + self.fit_information = fit_information or {} + + def handle_missing_neighborhood(self, chromatogram, neighborhood, *args, **kwargs): + warnings.warn( + (""%f was not found for this charge state "" + ""scoring model. Defaulting to uniform model"") % neighborhood) + return uniform_model.score(chromatogram, *args, **kwargs) + + def handle_missing_bin(self, chromatogram, bins, key, neighborhood, *args, **kwargs): + warnings.warn(""%d not found for this mass range (%f). Using bin average (%r)"" % ( + key, neighborhood, chromatogram.charge_states)) + return sum(bins.values()) / float(len(bins)) + + def transform_state(self, state): + return abs(state) + + @classmethod + def fit(cls, observations, missing=0.01, neighborhood_width=100., + ignore_singly_charged=False): + bins = defaultdict(lambda: defaultdict(float)) + + fit_info = { + ""ignore_singly_charged"": ignore_singly_charged, + ""missing"": missing, + } + + self = cls({}, neighborhood_width=neighborhood_width) + + for sol in observations: + neighborhood = self.neighborhood_of(sol.neutral_mass) + for c, val in self.get_signal_proportions(sol).items(): + c = self.transform_state(c) + if ignore_singly_charged and c == 1: + continue + bins[neighborhood][c] += 1 + + model_table = {} + + all_states = set() + for level in bins.values(): + all_states.update(level.keys()) + + all_states.add(1 * (min(all_states) / abs(min(all_states)))) + + for neighborhood, counts in bins.items(): + for c in all_states: + counts[c] += missing + total = sum(counts.values()) + entry = {k: v / total for k, v in counts.items()} + model_table[neighborhood] = entry + + return cls(model_table, neighborhood_width, fit_information=fit_info) + + def dump(self, file_obj, include_fit_information=True): + json.dump( + { + ""neighborhood_width"": self.neighborhood_width, + ""table"": self.table, + ""fit_information"": self.fit_information if include_fit_information else {} + }, + file_obj, indent=4, sort_keys=True) + + @classmethod + def load(cls, file_obj): + data = json.load(file_obj) + table = data.pop(""table"") + width = float(data.pop(""neighborhood_width"")) + + def numeric_keys(table, dtype=float, convert_value=lambda x: x): + return {abs(dtype(k)): convert_value(v) for k, v in table.items()} + + table = numeric_keys(table, convert_value=lambda x: numeric_keys(x, int)) + + return cls(table=table, neighborhood_width=width) + + def clone(self): + text_buffer = StringIO() + self.dump(text_buffer) + text_buffer.seek(0) + return self.load(text_buffer) + + +class WeightedMassScalingChargeStateScoringModel(MassScalingChargeStateScoringModel): + @classmethod + def fit(cls, observations, missing=0.01, neighborhood_width=100., + ignore_singly_charged=False, smooth=0): + bins = defaultdict(lambda: defaultdict(float)) + + fit_info = { + ""ignore_singly_charged"": ignore_singly_charged, + ""missing"": missing, + ""smooth"": smooth, + ""track"": defaultdict(lambda: defaultdict(list)), + ""count"": defaultdict(int) + } + + self = cls({}, neighborhood_width=neighborhood_width) + + for sol in observations: + neighborhood = self.neighborhood_of(sol.neutral_mass) + fit_info['count'][neighborhood] += 1 + for c, val in self.get_signal_proportions(sol).items(): + c = self.transform_state(c) + if ignore_singly_charged and c == 1: + continue + fit_info['track'][neighborhood][c].append(val) + bins[neighborhood][c] += val + + model_table = {} + + all_states = set() + for level in bins.values(): + all_states.update(level.keys()) + + all_states.add(1 * (min(all_states) / abs(min(all_states)))) + + for neighborhood, counts in bins.items(): + largest_charge = None + largest_charge_total = 0 + for c in all_states: + counts[c] += missing + if counts[c] > largest_charge_total: + largest_charge = c + largest_charge_total = counts[c] + if smooth > 0: + smooth_shift = largest_charge_total * smooth + for c in all_states: + if c != largest_charge and counts[c] > missing: + counts[c] += smooth_shift + + total = sum(counts.values()) + entry = {k: v / total for k, v in counts.items()} + model_table[neighborhood] = entry + + return cls(model_table, neighborhood_width, fit_information=fit_info) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/elution_time_grouping/recalibrator.py",".py","8424","203","from collections import namedtuple + +import numpy as np +try: + from matplotlib import pyplot as plt +except ImportError: + pass + +from scipy import stats + +from .linear_regression import SMALL_ERROR + + +CalibrationPoint = namedtuple(""CalibrationPoint"", ( + ""reference_index"", ""reference_point_rt"", ""reference_point_rt_pred"", + # rrt = Relative Retention Time, prrt = Predicted Relative Retention Time + ""rrt"", ""prrt"", ""residuals"", 'weight')) + + +class RecalibratingPredictor(object): + def __init__(self, training_examples, testing_examples, model, scale=1.0, dilation=1.0, weighted=True): + if training_examples is None: + training_examples = [] + self.training_examples = np.array(training_examples) + self.testing_examples = np.array(testing_examples) + self.model = model + self.scale = scale + self.dilation = dilation + self.configurations = dict() + self._fit() + self.apex_time_array = np.array( + [self.model._get_apex_time(c) for c in testing_examples]) + if weighted: + self.weight_array = np.array( + [np.log10(c.total_signal) for c in testing_examples]) + self.weight_array /= self.weight_array.max() + else: + self.weight_array = np.ones_like(self.apex_time_array) + self.weighted = weighted + self.weight_array /= self.weight_array.max() + self.predicted_apex_time_array = self._predict() + self.score_array = self._score() + + def _adapt_dilate_fit(self, reference_point, dilation): + parameters = np.hstack( + [self.model.parameters[0], dilation * self.model.parameters[1:]]) + predicted_reference_point_rt = self.model._prepare_data_vector( + reference_point).dot(parameters) + reference_point_rt = self.model._get_apex_time(reference_point) + resid = [] + relative_retention_time = [] + predicted_relative_retention_time = [] + for ex in self.testing_examples: + rrt = self.model._get_apex_time(ex) - reference_point_rt + prrt = self.model._prepare_data_vector(ex).dot( + parameters) - predicted_reference_point_rt + relative_retention_time.append(rrt) + predicted_relative_retention_time.append(prrt) + resid.append(prrt - rrt) + return (reference_point_rt, predicted_reference_point_rt, + relative_retention_time, predicted_relative_retention_time, resid) + + def _predict_delta_single(self, test_point, reference_point, dilation=None): + if dilation is None: + dilation = self.dilation + parameters = np.hstack( + [self.model.parameters[0], dilation * self.model.parameters[1:]]) + predicted_reference_point_rt = self.model._prepare_data_vector( + reference_point).dot(parameters) + reference_point_rt = self.model._get_apex_time(reference_point) + rrt = self.model._get_apex_time(test_point) - reference_point_rt + prrt = self.model._prepare_data_vector(test_point).dot( + parameters) - predicted_reference_point_rt + return prrt - rrt + + def predict_delta_single(self, test_point, dilation=None): + if dilation is None: + dilation = self.dilation + delta = [] + weight = [] + for _i, reference_point in enumerate(self.testing_examples): + delta.append(self._predict_delta_single( + test_point, reference_point, dilation)) + weight.append(np.log10(reference_point.total_signal)) + return np.dot(delta, weight) / np.sum(weight), np.std(delta) + + def score_single(self, test_point): + delta, _sd = (self.predict_delta_single(test_point)) + delta = abs(delta) + score = stats.t.sf( + delta, + df=self._df(), scale=self.scale) * 2 + score -= SMALL_ERROR + if score < SMALL_ERROR: + score = SMALL_ERROR + return score + + def _fit(self): + for i, training_reference_point in enumerate(self.training_examples): + reference_point = [ + c for c in self.testing_examples + if (c.glycan_composition == training_reference_point.glycan_composition)] + if not reference_point: + continue + reference_point = max( + reference_point, key=lambda x: x.total_signal) + dilation = self.dilation + (reference_point_rt, predicted_reference_point_rt, + relative_retention_time, + predicted_relative_retention_time, resid) = self._adapt_dilate_fit(reference_point, dilation) + self.configurations[i] = CalibrationPoint( + i, reference_point_rt, predicted_reference_point_rt, + np.array(relative_retention_time), np.array( + predicted_relative_retention_time), + np.array(resid), np.log10(reference_point.total_signal) + ) + if not self.configurations: + for i, reference_point in enumerate(self.testing_examples): + dilation = self.dilation + (reference_point_rt, predicted_reference_point_rt, + relative_retention_time, + predicted_relative_retention_time, resid) = self._adapt_dilate_fit(reference_point, dilation) + self.configurations[-i] = CalibrationPoint( + i, reference_point_rt, predicted_reference_point_rt, + np.array(relative_retention_time), np.array( + predicted_relative_retention_time), + np.array(resid), np.log10(reference_point.total_signal) + ) + + def _predict(self): + configs = self.configurations + predicted_apex_time_array = [] + weight = [] + for _key, calibration_point in configs.items(): + predicted_apex_time_array.append( + (calibration_point.prrt + calibration_point.reference_point_rt) * calibration_point.weight) + weight.append(calibration_point.weight) + return np.sum(predicted_apex_time_array, axis=0) / np.sum(weight) + + def _df(self): + return max(len(self.configurations) - len(self.model.parameters), 1) + + def _score(self): + score = stats.t.sf( + abs(self.predicted_apex_time_array - self.apex_time_array), + df=self._df(), scale=self.scale) * 2 + score -= SMALL_ERROR + score[score < SMALL_ERROR] = SMALL_ERROR + return score + + def R2(self, adjust=False): + y = self.apex_time_array + w = self.weight_array + yhat = self.predicted_apex_time_array + residuals = (y - yhat) + rss = (w * residuals * residuals).sum() + tss = (y - y.mean()) + tss = (w * tss * tss).sum() + if adjust: + n = len(y) + k = len(self.model.parameters) + adjustment_factor = (n - 1.0) / float(n - k - 1.0) + else: + adjustment_factor = 1.0 + R2 = (1 - adjustment_factor * (rss / tss)) + return R2 + + @classmethod + def predict(cls, training_examples, testing_examples, model, dilation=1.0): + inst = cls(training_examples, testing_examples, model, dilation) + return inst.predicted_apex_time_array + + @classmethod + def score(cls, training_examples, testing_examples, model, dilation=1.0): + inst = cls(training_examples, testing_examples, model, dilation) + return inst.score_array + + def plot(self, ax=None): + if ax is None: + _fig, ax = plt.subplots(1) + X = self.apex_time_array + Y = self.predicted_apex_time_array + S = np.array([c.total_signal for c in self.testing_examples]) + S /= S.max() + S *= 100 + ax.scatter(X, Y, s=S, marker='o') + ax.plot((X.min(), X.max()), (X.min(), X.max()), + color='black', linestyle='--', lw=0.75) + ax.set_xlabel('Experimental Apex Time', fontsize=18) + ax.set_ylabel('Predicted Apex Time', fontsize=18) + ax.figure.text(0.8, 0.15, ""$R^2=%0.4f$"" % self.R2(), ha='center') + return ax + + def filter(self, threshold): + filtered = self.__class__( + self.training_examples, + self.testing_examples[self.score_array > threshold], + self.model, + self.scale, + self.dilation, + self.weighted) + return filtered +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/elution_time_grouping/reviser.py",".py","50485","1312","import logging +import operator + +from typing import ( + Callable, DefaultDict, Dict, + List, Mapping, Optional, Set, + TYPE_CHECKING, Tuple, Union, + OrderedDict, Iterable, NamedTuple) +from array import array +from dataclasses import dataclass + +from matplotlib import pyplot as plt + +import numpy as np + +from glypy.structure.glycan_composition import HashableGlycanComposition, FrozenMonosaccharideResidue +from glycresoft.chromatogram_tree import mass_shift + +from glycresoft.chromatogram_tree.mass_shift import Unmodified, Ammonium, Deoxy +from glycresoft.scoring.elution_time_grouping.structure import GlycopeptideChromatogramProxy +from glycresoft.structure.structure_loader import GlycanCompositionDeltaCache + +from glycresoft._c.composition_network.graph import CachingGlycanCompositionVectorContext, GlycanCompositionVector + +from glycresoft.task import LoggingMixin + +logger = logging.getLogger(__name__) +logger.addHandler(logging.NullHandler()) + + +if TYPE_CHECKING: + from glycresoft.scoring.elution_time_grouping.model import ElutionTimeFitter + from glycresoft.tandem.chromatogram_mapping import SpectrumMatchUpdater, TandemAnnotatedChromatogram + from glycresoft.tandem.target_decoy import NearestValueLookUp, TargetDecoyAnalyzer + from glycresoft.tandem.spectrum_match import SpectrumMatch, MultiScoreSpectrumMatch + + +def _invert_fn(fn): + def wrapper(*args, **kwargs): + value = fn(*args, **kwargs) + return not value + return wrapper + + +class RevisionRule(object): + delta_glycan: HashableGlycanComposition + mass_shift_rule: Optional['MassShiftRule'] + priority: int + name: Optional[str] + delta_cache: Optional[GlycanCompositionDeltaCache] + + def __init__(self, delta_glycan, mass_shift_rule=None, priority=0, name=None): + self.delta_glycan = HashableGlycanComposition.parse(delta_glycan) + self.mass_shift_rule = mass_shift_rule + self.priority = priority + self.name = name + self.delta_cache = None + + def monosaccharides(self) -> Set[FrozenMonosaccharideResidue]: + return set(self.delta_glycan) + + def clone(self): + return self.__class__( + self.delta_glycan.clone(), + self.mass_shift_rule.clone() if self.mass_shift_rule else None, + self.priority, + self.name) + + def is_valid_revision(self, record: GlycopeptideChromatogramProxy, + new_record: GlycopeptideChromatogramProxy) -> bool: + valid = not any(v < 0 for v in new_record.glycan_composition.values()) + if valid: + if self.mass_shift_rule: + return self.mass_shift_rule.valid(record) + return valid + + def valid(self, record: GlycopeptideChromatogramProxy) -> bool: + new_record = self(record) + valid = self.is_valid_revision(record, new_record) + return valid + + def with_cache(self): + new = self.clone() + new.delta_cache = GlycanCompositionDeltaCache(op=operator.add) + return new + + def without_cache(self): + return self.clone() + + def _apply(self, record: 'GlycopeptideChromatogramProxy') -> 'GlycopeptideChromatogramProxy': + if self.delta_cache: + new_gc = self.delta_cache(record.glycan_composition, self.delta_glycan) + new_record = record.copy() + new_record.update_glycan_composition(new_gc) + return new_record + else: + # Re-compute the new glycan every time + return record.shift_glycan_composition(self.delta_glycan) + + def __call__(self, record): + result = self._apply(record) + if self.mass_shift_rule is not None: + return self.mass_shift_rule(result) + return result + + def revert(self, record): + return record.shift_glycan_composition(-self.delta_glycan) + + def invert_rule(self): + return self.__class__( + -self.delta_glycan, self.mass_shift_rule.invert() if self.mass_shift_rule else None, self.priority) + + def __eq__(self, other): + try: + return self.delta_glycan == other.delta_glycan and self.mass_shift_rule == other.mass_shift_rule + except AttributeError: + return self.delta_glycan == other + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash(self.delta_glycan) + + def __repr__(self): + if self.mass_shift_rule: + template = ""{self.__class__.__name__}({self.delta_glycan}, {self.mass_shift_rule}, {self.name})"" + else: + template = ""{self.__class__.__name__}({self.delta_glycan}, {self.name})"" + return template.format(self=self) + + +class ValidatingRevisionRule(RevisionRule): + def __init__(self, delta_glycan, validator, mass_shift_rule=None, priority=0, name=None): + super(ValidatingRevisionRule, self).__init__( + delta_glycan, mass_shift_rule=mass_shift_rule, priority=priority, name=name) + self.validator = validator + + def clone(self): + return self.__class__( + self.delta_glycan.clone(), self.validator, self.mass_shift_rule.clone() if self.mass_shift_rule else None, + self.priority, self.name) + + def is_valid_revision(self, record: GlycopeptideChromatogramProxy, + new_record: GlycopeptideChromatogramProxy) -> bool: + if super().is_valid_revision(record, new_record): + return self.validator(record) + return False + + def invert_rule(self, validator: Optional[Callable[['GlycopeptideChromatogramProxy'], bool]]=None): + if validator is None: + validator = _invert_fn(self.validator) + return self.__class__( + -self.delta_glycan, validator, self.mass_shift_rule.invert() if self.mass_shift_rule else None, + self.priority) + + +class MassShiftRule(object): + def __init__(self, mass_shift, multiplicity): + self.mass_shift = mass_shift + self.sign = int(multiplicity / abs(multiplicity)) + self.multiplicity = abs(multiplicity) + self.single = abs(multiplicity) == 1 + + def invert_rule(self): + return self.__class__(self.mass_shift, -self.sign * self.multiplicity) + + def clone(self): + return self.__class__(self.mass_shift, self.multiplicity * self.sign) + + def valid(self, record): + assert isinstance(self.mass_shift, mass_shift.MassShift) + if self.sign < 0: + # Can only lose a mass shift if all the mass shifts of the analyte are able to lose + # self.mass_shift without going negative + for shift in record.mass_shifts: + # The current mass shift is a compound mass shift, potentially having multiple copies of self.mass_shift + if isinstance(shift, mass_shift.CompoundMassShift) and \ + shift.counts.get(self.mass_shift, 0) < self.multiplicity: + return False + # The current mass shift is a single simple mass shift and it isn't a match for self.mass_shift + # or self.multiplicity > 1 + elif isinstance(shift, mass_shift.MassShift) and (shift != self.mass_shift) or \ + (shift == self.mass_shift and not self.single): + return False + return True + else: + # Can always gain a mass shift + return True + + def apply(self, record): + new = record.copy() + new.mass_shifts = [ + m + (self.mass_shift * self.sign * self.multiplicity) for m in new.mass_shifts] + return new + + def __call__(self, record): + return self.apply(record) + + def __eq__(self, other): + if other is None: + return False + return self.mass_shift == other.mass_shift and self.multiplicity == other.multiplicity + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash(self.mass_shift) + + def __repr__(self): + template = ""{self.__class__.__name__}({self.mass_shift}, {self.multiplicity})"" + return template.format(self=self) + + +def modify_rules(rules: Iterable[RevisionRule], symbol_map: Mapping[str, str]): + rules = list(rules) + for sym_from, sym_to in symbol_map.items(): + editted: List[RevisionRule] = [] + for rule in rules: + if sym_from in rule.delta_glycan: + if rule.delta_cache is not None: + rule = rule.with_cache() + else: + rule = rule.clone() + count = rule.delta_glycan.pop(sym_from) + rule.delta_glycan[sym_to] = count + editted.append(rule) + rules = editted + return rules + + +def always(x): + return True + + +SpectrumMatchType = Union['SpectrumMatch', 'MultiScoreSpectrumMatch'] + +class RevisionQueryResult(NamedTuple): + spectrum_match: Optional[SpectrumMatchType] + found: bool + + +class OriginalRevisionQueryResult(NamedTuple): + original_spectrum_match: Optional[SpectrumMatchType] + revision_spectrum_match: Optional[SpectrumMatchType] + skip: bool + + +class RevisionValidatorBase(LoggingMixin): + spectrum_match_builder: 'SpectrumMatchUpdater' + + def __init__(self, spectrum_match_builder, threshold_fn=always): + self.spectrum_match_builder = spectrum_match_builder + self.threshold_fn = threshold_fn + + def find_revision_gpsm(self, chromatogram: 'TandemAnnotatedChromatogram', revised) -> RevisionQueryResult: + found_revision = False + revised_gpsm = None + try: + revised_gpsm = chromatogram.best_match_for(revised.structure) + found_revision = True + except KeyError: + if self.spectrum_match_builder is not None: + self.spectrum_match_builder.get_spectrum_solution_sets( + revised, + chromatogram, + invalidate_reference=False + ) + try: + revised_gpsm = chromatogram.best_match_for(revised.structure) + found_revision = True + except KeyError: + logger.debug( + ""Failed to find revised spectrum match for %s in %r"", + revised.structure, + chromatogram) + return RevisionQueryResult(revised_gpsm, found_revision) + + def find_gpsms(self, source: 'TandemAnnotatedChromatogram', + revised: GlycopeptideChromatogramProxy, + original: GlycopeptideChromatogramProxy) -> OriginalRevisionQueryResult: + '''Find spectrum matches in ``source`` for the pair of alternative interpretations + for this feature. + + Parameters + ---------- + source : :class:`~.TandemAnnotatedChromatogram` + The chromatogram with MS2 spectra to find spectrum matches from + revised : :class:`~.GlycopeptideChromatogramProxy` + The revised structure + original : :class:`~.GlycopeptideChromatogramProxy` + The original structure + + Returns + ------- + original_gpsm : :class:`~.SpectrumMatchType` + The best spectrum match for the original structure + revised_gpsm : :class:`~.SpectrumMatchType` + The best spectrum match for the revised structure + skip : :class:`bool` + Whether there were any failures to find a revised solution, telling + the caller to skip over this one. + ''' + original_gpsm = None + revised_gpsm = None + skip = False + if source is None: + # Can't validate without a source to read the spectrum match metadata + skip = True + return OriginalRevisionQueryResult(original_gpsm, revised_gpsm, skip) + + revised_gpsm, found_revision = self.find_revision_gpsm(source, revised) + + if not found_revision: + # Can't find a spectrum match to the revised form, assume we're allowed to + # revise. + self.debug( + ""...... Permitting revision for %s (%0.3f) from %s to %s because revision not evaluated"", + revised.tag, revised.apex_time, original.glycan_composition, revised.glycan_composition) + skip = True + return OriginalRevisionQueryResult(original_gpsm, revised_gpsm, skip) + + try: + original_gpsm = source.best_match_for(original.structure) + except KeyError: + # Can't find a spectrum match to the original, assume we're allowed to + # revise. + self.debug( + ""...... Permitting revision for %s (%0.3f) from %s to %s because original not evaluated"" % + (revised.tag, revised.apex_time, original.glycan_composition, revised.glycan_composition)) + skip = True + return OriginalRevisionQueryResult(original_gpsm, revised_gpsm, skip) + skip = revised_gpsm is None or original_gpsm is None + return OriginalRevisionQueryResult(original_gpsm, revised_gpsm, skip) + + def validate(self, revised: GlycopeptideChromatogramProxy, original: GlycopeptideChromatogramProxy) -> bool: + raise NotImplementedError() + + def __call__(self, revised: GlycopeptideChromatogramProxy, original: GlycopeptideChromatogramProxy) -> bool: + return self.validate(revised, original) + + def msn_score_for(self, source: 'TandemAnnotatedChromatogram', solution: GlycopeptideChromatogramProxy) -> float: + gpsm, found = self.find_revision_gpsm(source, solution) + if not found or gpsm is None: + return 0 + return gpsm.score + + +class PeptideYUtilizationPreservingRevisionValidator(RevisionValidatorBase): + '''Prevent a revision that leads to substantial loss of peptide+Y ion-explainable + signal. + + This does not use peptide backbone fragments because they are by definition the + revision algorithm only updates the glycan composition, not the peptide backbone. + ''' + threshold: float + + def __init__(self, threshold=0.85, spectrum_match_builder=None, threshold_fn=always): + super(PeptideYUtilizationPreservingRevisionValidator, self).__init__( + spectrum_match_builder, threshold_fn) + self.threshold = threshold + + def validate(self, revised, original): + source = revised.source + if source is None: + # Can't validate without a source to read the spectrum match metadata + return True + + original_gpsm, revised_gpsm, skip = self.find_gpsms( + source, revised, original) + if skip: + return True + if hasattr(original_gpsm, 'score_set'): + original_utilization = original_gpsm.score_set.stub_glycopeptide_intensity_utilization + if not original_utilization: + # Anything is better than or equal to zero + return True + + revised_utilization = revised_gpsm.score_set.stub_glycopeptide_intensity_utilization + utilization_ratio = revised_utilization / original_utilization + valid = utilization_ratio > self.threshold + + self.debug( + ""...... Checking revision by peptide+Y ions for %s (%0.3f) from %s to %s: %0.3f / %0.3f: %r"" % + (revised.tag, revised.apex_time, original.glycan_composition, revised.glycan_composition, + revised_utilization, original_utilization, valid)) + else: + # TODO: Make this check explicit by directly calculating the metric here. + valid = True + return valid + + +class OxoniumIonRequiringUtilizationRevisionValidator(RevisionValidatorBase): + scale: float + + def __init__(self, scale=1.0, spectrum_match_builder=None, threshold_fn=always): + super(OxoniumIonRequiringUtilizationRevisionValidator, + self).__init__(spectrum_match_builder, threshold_fn) + self.scale = scale + + def validate(self, revised: GlycopeptideChromatogramProxy, original: GlycopeptideChromatogramProxy) -> bool: + source = revised.source + if source is None: + # Can't validate without a source to read the spectrum match metadata + return True + + original_gpsm, revised_gpsm, skip = self.find_gpsms( + source, revised, original) + if skip: + return True + if hasattr(original_gpsm, 'score_set'): + original_utilization: float = original_gpsm.score_set.oxonium_ion_intensity_utilization + revised_utilization: float = revised_gpsm.score_set.oxonium_ion_intensity_utilization + + threshold = original_utilization * self.scale + valid = (revised_utilization - threshold) >= 0 + self.debug( + ""...... Checking revision by oxonium ions for %s (%0.3f) from %s to %s: %0.3f / %0.3f: %r"" % + (revised.tag, revised.apex_time, original.glycan_composition, revised.glycan_composition, + revised_utilization, original_utilization, valid)) + else: + # TODO: Make this check explicit by directly calculating the metric here. + valid = True + return valid + + +class CompoundRevisionValidator(object): + validators: List[RevisionValidatorBase] + + def __init__(self, validators=None): + if validators is None: + validators = [] + self.validators = list(validators) + + @property + def spectrum_match_builder(self): + return self.validators[0].spectrum_match_builder + + def validate(self, revised, original): + for rule in self.validators: + if not rule(revised, original): + return False + return True + + def __call__(self, revised, original): + return self.validate(revised, original) + + def msn_score_for(self, source, solution: GlycopeptideChromatogramProxy) -> float: + return self.validators[0].msn_score_for(source, solution) + + +def _new_array(): + return array('d') + + +def display_table(rows: List[str], headers: List[str]) -> str: + rows = [headers] + rows + widths = list(map(lambda col: max(map(len, col)), zip(*rows))) + + buffer = [] + for i, row in enumerate(rows): + buffer.append(' | '.join(col.center(w) for col, w in zip(row, widths))) + if i == 0: + buffer.append( + '|'.join('-' * (w + 2 if j > 0 else w + 1) + for j, (col, w) in enumerate(zip(row, widths))) + ) + + return '\n'.join(buffer) + + +@dataclass +class RevisionEvent: + rt_score: float + chromatogram_record: GlycopeptideChromatogramProxy + rule: Optional[RevisionRule] + msn_score: float + + +class ValidatedGlycome: + valid_glycans: Set[HashableGlycanComposition] + monosaccharides: Set[FrozenMonosaccharideResidue] + + def __init__(self, valid_glycans): + self.valid_glycans = valid_glycans + self.monosaccharides = self._collect_monosaccharides() + + def _collect_monosaccharides(self): + keys = set() + for gc in self.valid_glycans: + keys.update(gc) + return keys + + def __contains__(self, glycan_composition: HashableGlycanComposition) -> bool: + return glycan_composition in self.valid_glycans + + def __bool__(self): + return bool(self.valid_glycans) + + def __nonzero__(self): + return bool(self.valid_glycans) + + def __iter__(self): + return iter(self.valid_glycans) + + def __len__(self): + return len(self.valid_glycans) + + def check(self, record: GlycopeptideChromatogramProxy) -> bool: + return record.glycan_composition in self.valid_glycans + + +class IndexedValidatedGlycome(ValidatedGlycome): + indexer: CachingGlycanCompositionVectorContext + indexed_valid_glycans: Set[GlycanCompositionVector] + + def __init__(self, valid_glycans): + super().__init__(valid_glycans) + self.indexer = CachingGlycanCompositionVectorContext(self.monosaccharides) + self.indexed_valid_glycans = { + self.indexer.encode(gc) for gc in self.valid_glycans + } + + def encode(self, record: GlycopeptideChromatogramProxy): + if ""_indexed_glycan_composition"" in record.kwargs: + return record.kwargs[""_indexed_glycan_composition""] + vec = self.indexer.encode(record.glycan_composition) + record.kwargs[""_indexed_glycan_composition""] = vec + return vec + + def check(self, record: GlycopeptideChromatogramProxy) -> bool: + return self.encode(record) in self.indexed_valid_glycans + + + +class ModelReviser(LoggingMixin): + valid_glycans: Optional[ValidatedGlycome] + revision_validator: Optional[RevisionValidatorBase] + + model: 'ElutionTimeFitter' + rules: 'RevisionRuleList' + chromatograms: List[GlycopeptideChromatogramProxy] + + original_scores: array + original_times: array + + alternative_records: DefaultDict[RevisionRule, List[GlycopeptideChromatogramProxy]] + alternative_scores: DefaultDict[RevisionRule, array] + alternative_times: DefaultDict[RevisionRule, array] + + def __init__(self, model, rules, chromatograms=None, valid_glycans=None, revision_validator=None): + if chromatograms is None: + chromatograms = model.chromatograms + self.model = model + self.chromatograms = chromatograms + self.original_scores = array('d') + self.original_times = array('d') + self.rules = list(rules) + self.alternative_records = DefaultDict(list) + self.alternative_scores = DefaultDict(_new_array) + self.alternative_times = DefaultDict(_new_array) + if valid_glycans is not None: + if isinstance(valid_glycans, set): + valid_glycans = ValidatedGlycome(valid_glycans) + self.valid_glycans = valid_glycans + self.revision_validator = revision_validator + + def rescore(self, case): + return self.model.score(case) + + def modify_rules(self, symbol_map): + self.rules = self.rules.modify_rules(symbol_map) + return self + + def propose_revisions(self, case): + propositions = { + None: (case, self.rescore(case)), + } + for rule in self.rules: + if rule.valid(case): + rec = rule(case) + if self.valid_glycans and not self.valid_glycans.check(rec): + continue + propositions[rule] = (rec, self.rescore(rec)) + return propositions + + def process_rule(self, rule: RevisionRule): + alts = [] + alt_scores = array('d') + alt_times = array('d') + for case in self.chromatograms: + rec = rule(case) + if rule.is_valid_revision(case, rec): + if self.valid_glycans and not self.valid_glycans.check(rec): + alts.append(None) + alt_scores.append(0.0) + alt_times.append(0.0) + continue + alts.append(rec) + alt_times.append(self.model.predict(rec)) + alt_scores.append(self.rescore(rec)) + else: + alts.append(None) + alt_scores.append(0.0) + alt_times.append(0.0) + self.alternative_records[rule] = alts + self.alternative_scores[rule] = alt_scores + self.alternative_times[rule] = alt_times + + def process_model(self): + scores = array('d') + times = array('d') + for case in self.chromatograms: + scores.append(self.rescore(case)) + times.append(self.model.predict(case)) + self.original_scores = scores + self.original_times = times + + def evaluate(self): + self.process_model() + for rule in self.rules: + self.process_rule(rule) + + def select_revision_atlernative(self, alternatives: List[RevisionEvent], + original: GlycopeptideChromatogramProxy, + minimum_rt_score: float) -> GlycopeptideChromatogramProxy: + alternatives = [alt for alt in alternatives if alt.rt_score > minimum_rt_score] + alternatives.sort(key=lambda x: x.msn_score, reverse=True) + + table = [ + (str(alt.chromatogram_record.glycan_composition), + (','.join(map(lambda x: x.name, alt.chromatogram_record.mass_shifts))), + (alt.rule.name if alt.rule is not None else '-'), + '%0.3f' % alt.rt_score, '%0.3f' % alt.msn_score) + for alt in alternatives + ] + + if len({alt.chromatogram_record.glycan_composition for alt in alternatives}) > 1: + self.log('\n' + display_table(table, ['Glycan Composition', 'Mass Shifts', + 'Revision Rule', 'RT Score', 'MSn Score'])) + + best_event = alternatives[0] + best_record = best_event.chromatogram_record + best_rule = best_event.rule + if best_rule is not None: # If *somehow* the best solution at the time this is called is still unchanged? + best_record.revised_from = (best_rule, original) + return best_record + + def _msn_score_if_available(self, source, solution: GlycopeptideChromatogramProxy) -> float: + if self.revision_validator is None: + return 0.0 + return self.revision_validator.msn_score_for(source, solution) + + def revise(self, threshold=0.2, delta_threshold=0.2, minimum_time_difference=0.5): + chromatograms = self.chromatograms + original_scores = self.original_scores + original_times = self.original_times + next_round = [] + for i in range(len(chromatograms)): + original_score = best_score = original_scores[i] + best_rule = None + delta_best_score = float('inf') + original_solution = best_record = chromatograms[i] + original_time = original_times[i] + + alternative_solutions = [ + RevisionEvent(original_score, original_solution, None, + self._msn_score_if_available( + original_solution.source, + original_solution) + ) + ] + + for rule in self.rules: + alt_rec = self.alternative_records[rule][i] + alt_score = self.alternative_scores[rule][i] + alt_time = self.alternative_times[rule][i] + if not np.isclose(alt_score, 0.0) and abs(alt_time - original_time) > minimum_time_difference: + if self.revision_validator and not self.revision_validator(alt_rec, original_solution): + continue + alternative_solutions.append( + RevisionEvent( + alt_score, alt_rec, rule, + self._msn_score_if_available( + original_solution.source, alt_rec))) + if alt_score > best_score: + delta_best_score = alt_score - original_score + best_score = alt_score + best_rule = rule + best_record = alt_rec + + + if best_score > threshold and delta_best_score > delta_threshold: + if best_rule is not None: + best_record = self.select_revision_atlernative( + alternative_solutions, original_solution, best_score * 0.9) + next_round.append(best_record) + else: + next_round.append(chromatograms[i]) + return next_round + + +dhex = FrozenMonosaccharideResidue.from_iupac_lite(""d-Hex"") +fuc = FrozenMonosaccharideResidue.from_iupac_lite(""Fuc"") +neuac = FrozenMonosaccharideResidue.from_iupac_lite(""Neu5Ac"") +hexnac = FrozenMonosaccharideResidue.from_iupac_lite(""HexNAc"") + +# The correct glycan was incorrectly assigned as the unadducted form of +# another glycan. +# +# Gain an ammonium adduct and a NeuAc, lose a Hex and Fuc +AmmoniumMaskedRule = RevisionRule( + HashableGlycanComposition(Hex=-1, Fuc=-1, Neu5Ac=1), + mass_shift_rule=MassShiftRule(Ammonium, 1), priority=1, name=""Ammonium Masked"") + +AmmoniumMaskedNeuGcRule = RevisionRule( + HashableGlycanComposition(Hex=-2, Neu5Gc=1), + mass_shift_rule=MassShiftRule(Ammonium, 1), priority=1, name=""Ammonium Masked NeuGc"") + +# The correct glycan was incorrectly assigned as the ammonium adducted form of another +# glycan +AmmoniumUnmaskedRule = RevisionRule( + HashableGlycanComposition(Hex=1, Fuc=1, Neu5Ac=-1), + mass_shift_rule=MassShiftRule(Ammonium, -1), priority=1, name=""Ammonium Unmasked"") + +AmmoniumUnmaskedNeuGcRule = RevisionRule( + HashableGlycanComposition(Hex=2, Neu5Gc=-1), + mass_shift_rule=MassShiftRule(Ammonium, -1), priority=1, name=""Ammonium Unmasked NeuGc"") + +# The glycan was incorrectly assigned identified because of an error in monoisotopic peak +# assignment. +IsotopeRule = RevisionRule(HashableGlycanComposition(Fuc=-2, Neu5Ac=1), name=""Isotope Error"") +IsotopeRule2 = RevisionRule(HashableGlycanComposition(Fuc=-4, Neu5Ac=2), name=""Isotope Error 2"") + +IsotopeRuleNeuGc = RevisionRule(HashableGlycanComposition(Fuc=-1, Hex=-1, NeuGc=1), name=""Isotope Error NeuGc"") + +HexNAc2NeuAc2ToHex6Deoxy = ValidatingRevisionRule( + HashableGlycanComposition(Hex=-6, HexNAc=2, Neu5Ac=2), + mass_shift_rule=MassShiftRule(Deoxy, 1), + validator=lambda x: x.glycan_composition[neuac] == 0 and x.glycan_composition.query(dhex) == 0 and \ + x.glycan_composition[hexnac] == 2 and x.mass_shifts == [Unmodified], + name=""Rare precursor deoxidation followed by large mass ambiguity"") + +HexNAc2NeuAc2ToHex6AmmoniumRule = ValidatingRevisionRule( + HashableGlycanComposition(Hex=-6, HexNAc=2, Neu5Ac=2), + mass_shift_rule=MassShiftRule(Ammonium, 1), + validator=lambda x: x.glycan_composition[neuac] == 0 and x.glycan_composition.query(dhex) == 0 and \ + x.glycan_composition[hexnac] == 2, + name=""Ammonium Masked followed by Large Mass Ambiguity"") + + +# Not yet in use, needs to be explored more. In practice, this cannot even be used +# with such a small chromatographic shift (<= 0.5 minutes) on fucose and hexose. +IsotopeAmmoniumFucToHex = RevisionRule(HashableGlycanComposition(Fuc=-1, Hex=1), + mass_shift_rule=MassShiftRule(Ammonium, 1), + name='Ammonium Isotope Error') + +# Not yet in use, needs to be explored more +dHex2HexNAc2NeuAc1ToHex6AmmoniumRule = ValidatingRevisionRule( + HashableGlycanComposition(Fuc=2, Hex=-6, HexNAc=2, Neu5Ac=1), + mass_shift_rule=MassShiftRule(Ammonium, 1), + validator=lambda x: x.glycan_composition[neuac] == 0 and x.glycan_composition.query( + dhex) == 0 and x.glycan_composition[hexnac] == 1, + name=""Ammonium Masked followed by Large Mass Ambiguity II"") + + +HexNAc2Fuc1NeuAc2ToHex7 = ValidatingRevisionRule( + HashableGlycanComposition(Hex=-7, HexNAc=2, Neu5Ac=2, Fuc=1), + validator=lambda x: x.glycan_composition[neuac] == 0 and x.glycan_composition.query(dhex) == 0 and \ + x.glycan_composition[hexnac] == 2, + name=""Large Mass Ambiguity"") + +# Moving a hydroxyl group from another monosaccharide onto a Sialic acid or vis-versa obscures their mass identity +NeuGc1Fuc1ToNeuAc1Hex1Rule = RevisionRule( + HashableGlycanComposition(Neu5Ac=1, Hex=1, Neu5Gc=-1, Fuc=-1), name=""NeuAc Masked By NeuGc"") +NeuAc1Hex1ToNeuGc1Fuc1Rule = RevisionRule( + HashableGlycanComposition(Neu5Ac=-1, Hex=-1, Neu5Gc=1, Fuc=1), name=""NeuGc Masked By NeuAc"") + +Sulfate1HexNAc2ToHex3Rule = RevisionRule( + HashableGlycanComposition(HexNAc=2, sulfate=1, Hex=-3), name=""Sulfate + 2 HexNAc Masked By 3 Hex"") +Hex3ToSulfate1HexNAc2Rule = Sulfate1HexNAc2ToHex3Rule.invert_rule() +Hex3ToSulfate1HexNAc2Rule.name = ""3 Hex Masked By Sulfate + 2 HexNAc"" + +Phosphate1HexNAc2ToHex3Rule = RevisionRule( + HashableGlycanComposition(HexNAc=2, phosphate=1, Hex=-3), name=""Phosphate + 2 HexNAc Masked By 3 Hex"") +Hex3ToPhosphate1HexNAc2Rule = Phosphate1HexNAc2ToHex3Rule.invert_rule() +Hex3ToPhosphate1HexNAc2Rule.name = ""3 Hex Masked By Phosphate + 2 HexNAc"" + +SulfateToPhosphateRule = RevisionRule( + HashableGlycanComposition(sulfate=-1, phosphate=1), + name=""Phosphate Masked By Sulfate"") +PhosphateToSulfateRule = SulfateToPhosphateRule.invert_rule() +PhosphateToSulfateRule.name = ""Sulfate Masked By Phosphate"" + + +class RevisionRuleList(object): + rules: List[RevisionRule] + by_name: Dict[str, RevisionRule] + + def __init__(self, rules): + self.rules = list(rules) + self.by_name = { + rule.name: rule for rule in self.rules + if rule.name + } + + def modify_rules(self, symbol_map): + self.rules = modify_rules(self.rules, symbol_map) + return self + + def with_cache(self): + return self.__class__([ + rule.with_cache() for rule in self.rules + ]) + + def filter_defined(self, valid_glycans: ValidatedGlycome): + acc = [] + for rule in self.rules: + keys = rule.monosaccharides() + if keys == (keys & valid_glycans.monosaccharides): + acc.append(rule) + self.rules = acc + return self + + def __getitem__(self, i): + if i in self.by_name: + return self.by_name[i] + return self.rules[i] + + def __len__(self): + return len(self.rules) + + def __iter__(self): + return iter(self.rules) + + def __repr__(self): + return ""{self.__class__.__name__}({self.rules})"".format(self=self) + + +class IntervalModelReviser(ModelReviser): + alpha: float = 0.01 + + def rescore(self, case): + return self.model.score_interval(case, alpha=self.alpha) + + +# In reviser, combine the score from the absolute coordinate with the +# score relative to each other glycoform in the group? This might look +# something like the old recalibrator code, but adapted for the interval_score +# method + + +class FDREstimatorBase(object): + estimator: 'TargetDecoyAnalyzer' + + def estimate_fdr(self): + from glycresoft.tandem.target_decoy import TargetDecoyAnalyzer + self.estimator = TargetDecoyAnalyzer( + self.target_scores.view([('score', np.float64)]).view(np.recarray), + self.decoy_scores[self.decoy_is_valid].view([('score', np.float64)]).view(np.recarray)) + + @property + def q_value_map(self): + return self.estimator.q_value_map + + def score_for_fdr(self, fdr_value: float) -> float: + return self.estimator.score_for_fdr(fdr_value) + + def plot(self): + ax = self.estimator.plot() + ax.set_xlim(-0.01, 1) + return ax + + +class RuleBasedFDREstimator(FDREstimatorBase): + rule: RevisionRule + + chromatograms: Union[List[GlycopeptideChromatogramProxy], np.ndarray] + decoy_chromatograms: Union[List[GlycopeptideChromatogramProxy], np.ndarray] + + target_scores: np.ndarray + decoy_scores: np.ndarray + + target_predictions: np.ndarray + decoy_predictions: np.ndarray + decoy_residuals: np.ndarray + + decoy_is_valid: np.ndarray + over_time: OrderedDict + + def __init__(self, rule, chromatograms, rt_model, valid_glycans=None): + self.rule = rule + self.chromatograms = chromatograms + self.decoy_chromatograms = [] + self.rt_model = rt_model + self.target_scores = np.array([]) + self.decoy_scores = np.array([]) + self.decoy_is_valid = np.array([]) + self.valid_glycans = valid_glycans + self.estimator = None + self.over_time = OrderedDict() + + self.prepare() + + @property + def name(self): + return self.rule.name + + def prepare(self): + self.target_scores = np.array([self.rt_model.score_interval(p, 0.01) for p in self.chromatograms]) + self.target_times = np.array([p.apex_time for p in self.chromatograms]) + self.target_predictions = np.array([ + self.rt_model.predict(p) for p in self.chromatograms + ]) + self.target_residuals = self.target_times - self.target_predictions + decoy_scores = [] + decoy_is_valid = [] + self.decoy_chromatograms = [] + for p in self.chromatograms: + p = self.rule(p) + self.decoy_chromatograms.append(p) + decoy_is_valid.append(p.glycan_composition in self.valid_glycans if self.valid_glycans else True) + if self.rule.valid(p): + decoy_scores.append(self.rt_model.score_interval(p, 0.01)) + else: + decoy_scores.append(np.nan) + + self.decoy_times = np.array([p.apex_time for p in self.decoy_chromatograms]) + self.decoy_predictions = np.array([ + self.rt_model.predict(p) for p in self.decoy_chromatograms + ]) + self.decoy_residuals = self.decoy_times - self.decoy_predictions + + + self.decoy_scores = np.array(decoy_scores) + self.decoy_is_valid = np.array(decoy_is_valid) + + self.target_scores[np.isnan(self.target_scores)] = 0.0 + self.decoy_scores[np.isnan(self.decoy_scores)] = 0.0 + self.chromatograms = np.array(self.chromatograms) + self.decoy_chromatograms = np.array(self.decoy_chromatograms) + + self.estimate_fdr() + + def __repr__(self): + template = ""{self.__class__.__name__}({self.rule})"" + return template.format(self=self) + + def get_residuals_from_interval(self, span): + target_mask = [span.contains(i) for i in self.target_times] + target_residuals = self.target_residuals[target_mask] + target_residuals = target_residuals[~np.isnan(target_residuals)] + + decoy_mask = [span.contains(i) for i in self.decoy_times] + decoy_residuals = self.decoy_residuals[decoy_mask & self.decoy_is_valid] + decoy_residuals = decoy_residuals[~np.isnan(decoy_residuals)] + return target_residuals, decoy_residuals + + def get_scores_from_interval(self, span): + target_mask = [span.contains(i) for i in self.target_times] + target_scores = self.target_scores[target_mask] + target_scores = target_scores[~np.isnan(target_scores)] + + decoy_mask = [span.contains(i) for i in self.decoy_times] + decoy_scores = self.decoy_scores[decoy_mask & + self.decoy_is_valid] + decoy_scores = decoy_scores[~np.isnan(decoy_scores)] + return target_scores, decoy_scores + + def get_scores_from_mask(self, mask): + target_scores = self.target_scores[mask] + target_scores = target_scores[~np.isnan(target_scores)] + + decoy_scores = self.decoy_scores[mask & + self.decoy_is_valid] + decoy_scores = decoy_scores[~np.isnan(decoy_scores)] + return target_scores, decoy_scores + + def get_interval_masks(self): + spans = [mod for mod in self.rt_model.models.values()] + centers = np.array([s.centroid for s in spans]) + masks = [ + np.fromiter(map(span.contains, self.target_times), bool) for span in spans] + return masks, centers + + def fit_over_time(self): + masks, centers = self.get_interval_masks() + for i, mask in enumerate(masks): + target_scores, decoy_scores = self.get_scores_from_mask(mask) + facet = FDRFacet(target_scores, decoy_scores) + self.over_time[centers[i]] = facet + + def __getstate__(self): + state = { + ""estimator"": self.estimator, + ""target_scores"": self.target_scores, + ""target_predictions"": self.target_predictions, + ""target_times"": self.target_times, + ""decoy_scores"": self.decoy_scores, + ""decoy_predictions"": self.decoy_predictions, + ""decoy_times"": self.decoy_times, + ""decoy_is_valid"": self.decoy_is_valid, + ""rule"": self.rule, + ""over_time"": self.over_time + } + return state + + def __setstate__(self, state): + self.estimator = state['estimator'] + self.target_scores = state['target_scores'] + self.decoy_scores = state['decoy_scores'] + self.decoy_is_valid = state['decoy_is_valid'] + self.rule = state['rule'] + + self.target_times = state.get(""target_times"", np.array([])) + self.target_predictions = state.get(""target_predictions"", np.array([])) + + self.decoy_times = state.get(""decoy_times"", np.array([])) + self.decoy_predictions = state.get(""decoy_predictions"", np.array([])) + self.over_time = state.get(""over_time"", OrderedDict()) + + self.target_residuals = self.target_times - self.target_predictions + self.decoy_residuals = self.decoy_times - self.decoy_predictions + + self.rt_model = None + self.chromatograms = None + self.decoy_chromatograms = None + self.valid_glycans = None + + def copy(self): + proto, newargs, state = self.__reduce__() + dup = proto(*newargs) + dup.__setstate__(state) + + dup.rt_model = self.rt_model + dup.chromatograms = self.chromatograms + dup.decoy_chromatograms = self.decoy_chromatograms + dup.valid_glycans = self.valid_glycans + return dup + + +class FDRFacet(FDREstimatorBase): + def __init__(self, target_scores, decoy_scores): + self.target_scores = target_scores + self.decoy_scores = decoy_scores + if decoy_scores is None: + self.decoy_is_valid = np.array([], dtype=bool) + else: + self.decoy_is_valid = np.ones_like(decoy_scores).astype(bool) + if self.target_scores is not None and self.decoy_scores is not None: + self.estimate_fdr() + + def __getstate__(self): + state = { + ""estimator"": self.estimator + } + return state + + def __setstate__(self, state): + self.estimator = state['estimator'] + self.target_scores = self.estimator.targets['score'] + self.decoy_scores = self.estimator.decoys['score'] + self.decoy_is_valid = np.ones_like(self.decoy_scores).astype(bool) + + def __reduce__(self): + return self.__class__, (None, None), self.__getstate__() + + +def make_normalized_monotonic_bell(X: np.ndarray, Y: np.ndarray, symmetric: bool=False) -> np.ndarray: + center = np.abs(X).argmin() + Ynew = np.zeros_like(Y) + last_y = None + for i in range(center, X.size): + if last_y is None: + last_y = Y[i] + if Y[i] > last_y: + last_y = Y[i] + Ynew[i] = last_y + + last_y = None + for i in range(center, -1, -1): + if last_y is None: + last_y = Y[i] + if Y[i] > last_y: + last_y = Y[i] + Ynew[i] = last_y + + if symmetric: + Ynew = (Ynew + Ynew[::-1]) / 2 + + try: + maximum = Ynew[:center].max() + Ynew[:center] /= maximum + except ValueError: + pass + + try: + maximum = Ynew[center:].max() + Ynew[center:] /= maximum + except ValueError: + pass + + return Ynew + + +def dropna(array: np.ndarray) -> np.ndarray: + mask = ~np.isnan(array) + return array[mask] + + +class ResidualFDREstimator(object): + rules: RevisionRuleList + residual_mapper: 'PosteriorErrorToScore' + + def __init__(self, rules, rt_model=None, residual_mapper=None): + self.rules = rules + self.rt_model = rt_model + self.residual_mapper = residual_mapper + if residual_mapper is None: + self.fit() + + def _extract_scores_from_rules(self) -> Tuple[np.ndarray, np.ndarray]: + rule = self.rules[0] + target_scores = rule.target_residuals[ + ~np.isnan(rule.target_residuals)] + all_decoys = [] + for rule in self.rules: + all_decoys.extend(rule.decoy_residuals[ + ~np.isnan(rule.decoy_residuals) & rule.decoy_is_valid]) + return target_scores, np.array(all_decoys) + + def _extract_scores_from_model(self, rt_model, seed=1, n_resamples=1) -> Tuple[np.ndarray, np.ndarray]: + rng = np.random.RandomState(seed) + decoys = np.array([]) + for i in range(n_resamples): + decoys = np.concatenate( + ( + decoys, + dropna( + rt_model._summary_statistics['apex_time_array'] - rng.permutation( + rt_model._summary_statistics['predicted_apex_time_array'].copy()) + ) + ) + ) + + targets = dropna(rt_model._summary_statistics['residuals_array']) + return targets, decoys + + def fit(self): + models: List[PosteriorErrorToScore] = [] + if self.rules: + try: + fit_from_rules = self.fit_from_rules() + models.append(fit_from_rules) + except Exception: + logger.error(""Failed to fit FDR from delta rules"", exc_info=True) + + if self.rt_model: + try: + fit_from_rt_model = self.fit_from_rt_model() + models.append(fit_from_rt_model) + except Exception as err: + show_traceback = str(err) != ""No non-zero range in the posterior error distribution."" + logger.error( + ""Failed to fit FDR from permutations: %r"", err, exc_info=show_traceback) + if models: + models.sort(key=lambda x: x.width_at_half_max()) + model = models[0] + self.residual_mapper = model + else: + raise ValueError(""Could not fit any FDR model for retention time!"") + + def fit_from_rules(self): + from glycresoft.tandem.glycopeptide.dynamic_generation.multipart_fdr import ( + FiniteMixtureModelFDREstimatorDecoyGaussian + ) + target_scores, all_decoy_scores = self._extract_scores_from_rules() + fmm = FiniteMixtureModelFDREstimatorDecoyGaussian(all_decoy_scores, target_scores) + fmm.fit(max_target_components=3, + max_decoy_components=len(self.rules) * 2) + return PosteriorErrorToScore.from_model(fmm) + + def fit_from_rt_model(self): + from glycresoft.tandem.glycopeptide.dynamic_generation.multipart_fdr import ( + FiniteMixtureModelFDREstimatorDecoyGaussian + ) + target_scores, all_decoy_scores = self._extract_scores_from_model(self.rt_model) + fmm = FiniteMixtureModelFDREstimatorDecoyGaussian( + all_decoy_scores, target_scores) + fmm.fit(max_target_components=3) + return PosteriorErrorToScore.from_model(fmm) + + def bounds_for_probability(self, probability: float) -> np.ndarray: + return self.residual_mapper.bounds_for_probability(probability) + + def __reduce__(self): + return self.__class__, (self.rules, None, self.residual_mapper) + + def __getitem__(self, i): + return self.rules[i] + + def __len__(self): + return len(self.rules) + + def __iter__(self): + return iter(self.rules) + + def plot(self, ax=None, **kwargs): + return self.residual_mapper.plot(ax, **kwargs) + + def score(self, chromatogram: GlycopeptideChromatogramProxy, *args, **kwargs) -> float: + t_pred = self.rt_model.predict(chromatogram, *args, **kwargs) + residual = chromatogram.apex_time - t_pred + return self.residual_mapper(residual) + + def __call__(self, chromatogram: GlycopeptideChromatogramProxy, *args, **kwds) -> float: + return self.score(chromatogram, *args, **kwds) + + +def _prepare_domain(target_scores, decoy_scores, delta=0.1): + lo = min(target_scores.min(), decoy_scores.min()) + hi = max(target_scores.max(), decoy_scores.max()) + sign = np.sign(lo) + lo = sign * max(abs(lo), abs(hi)) + sign = np.sign(hi) + hi = sign * max(abs(lo), abs(hi)) + domain = np.concatenate( + (np.arange(lo, 0, delta), np.arange(0.0, hi + delta, delta), )) + return domain + + +class PosteriorErrorToScore(object): + mapper: 'NearestValueLookUp' + domain: np.ndarray + normalized_score: np.ndarray + + @classmethod + def from_model(cls, model, delta=0.1, symmetric=True): + domain = _prepare_domain(model.target_scores, model.decoy_scores, delta=delta) + return cls(model, domain, symmetric=symmetric) + + def __init__(self, model, domain, symmetric=True): + self.model = model + self.domain = domain + self.normalized_score = None + self.mapper = None + if self.model is not None: + self._create_normalized(symmetric=symmetric) + + def _create_normalized(self, symmetric=True): + from glycresoft.tandem.target_decoy import NearestValueLookUp + Y = self.model.estimate_posterior_error_probability(self.domain) + self.normalized_score = np.clip( + 1 - make_normalized_monotonic_bell(self.domain, Y, symmetric=symmetric), 0, 1) + support = np.where(self.normalized_score != 0)[0] + if len(support) == 0: + raise ValueError(""No non-zero range in the posterior error distribution."") + lo, hi = support[[0, -1]] + lo = max(lo - 5, 0) + hi += 5 + self.domain = self.domain[lo:hi] + self.normalized_score = self.normalized_score[lo:hi] + self.mapper = NearestValueLookUp(zip(self.domain, self.normalized_score)) + + def __call__(self, value): + if isinstance(value, (np.ndarray, Iterable)): + return np.array([self.mapper[v] for v in value]) + return self.mapper[value] + + def __getstate__(self): + return { + ""mapper"": self.mapper, + } + + def __setstate__(self, state): + self.mapper = state[""mapper""] + self.domain, self.normalized_score = map(np.array, zip(*self.mapper.items)) + + def __reduce__(self): + return self.__class__, (None, None), self.__getstate__() + + def copy(self): + proto, newargs, state = self.__reduce__() + dup = proto(*newargs) + dup.__setstate__(state) + dup.model = self.model + return dup + + def bounds_for_probability(self, probability: float) -> np.ndarray: + xbounds = np.where(self.normalized_score >= probability)[0] + if len(xbounds) == 0: + return np.array([0.0, 0.0]) + lo, hi = xbounds[[0, -1]] + return self.domain[[lo, hi]] + + def at_half_max(self): + half_max = self.normalized_score.max() / 2 + return self.bounds_for_probability(half_max) + + def width_at_half_max(self) -> float: + lo, hi = self.at_half_max() + return hi - lo + + def plot(self, ax=None): + if ax is None: + _fig, ax = plt.subplots(1, 1) + ax.plot(self.domain, self.normalized_score) + ax.set_xlabel(r""$t - \hat{t}$"") + ax.set_ylabel(""Probability"") + return ax +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/elution_time_grouping/model.py",".py","96699","2419","import csv +import itertools +import logging +import gzip +import io +import array + +from numbers import Number +from collections import defaultdict, namedtuple +from functools import partial +from typing import (Any, Callable, ClassVar, + DefaultDict, Dict, Iterator, + List, Optional, Set, Tuple, + Type, Union, OrderedDict) +from multiprocessing import cpu_count +from concurrent import futures + +import numpy as np +from scipy import stats + +import dill + +try: + from matplotlib import pyplot as plt +except ImportError: + pass + +from glypy.utils import make_counter +from glypy.structure.glycan_composition import HashableGlycanComposition, FrozenMonosaccharideResidue + +from glycopeptidepy.structure.sequence.implementation import PeptideSequence +from glycresoft.chromatogram_tree.chromatogram import Chromatogram, ChromatogramInterface + +from glycresoft.database.composition_network.space import composition_distance, DistanceCache + + +from ms_deisotope.peak_dependency_network.intervals import SpanningMixin + +from glycresoft.task import TaskBase + +from glycresoft.chromatogram_tree import Unmodified, Ammonium +from glycresoft.scoring.base import ScoringFeatureBase + +from glycresoft.structure import FragmentCachingGlycopeptide +from glycresoft.structure.structure_loader import GlycanCompositionDeltaCache + +from .structure import ( + ChromatogramProxy, _get_apex_time, GlycopeptideChromatogramProxy, + GlycoformAggregator, DeltaOverTimeFilter) +from .linear_regression import ( + WLSSolution, ransac, weighted_linear_regression_fit, + prediction_interval, SMALL_ERROR, + weighted_linear_regression_fit_ridge) +from .reviser import (IntervalModelReviser, IsotopeRule, AmmoniumMaskedRule, + AmmoniumUnmaskedRule, HexNAc2NeuAc2ToHex6AmmoniumRule, + IsotopeRule2, HexNAc2Fuc1NeuAc2ToHex7, PhosphateToSulfateRule, + SulfateToPhosphateRule, Sulfate1HexNAc2ToHex3Rule, Hex3ToSulfate1HexNAc2Rule, + Phosphate1HexNAc2ToHex3Rule, Hex3ToPhosphate1HexNAc2Rule, HexNAc2NeuAc2ToHex6Deoxy, + AmmoniumMaskedNeuGcRule, AmmoniumUnmaskedNeuGcRule, IsotopeRuleNeuGc, + RevisionValidatorBase, + PeptideYUtilizationPreservingRevisionValidator, + RevisionRuleList, + RuleBasedFDREstimator, + ResidualFDREstimator, + ValidatedGlycome) + +from . import reviser as libreviser + +logger = logging.getLogger(""glycresoft.elution_time_model"") +logger.addHandler(logging.NullHandler()) + + +CALIBRATION_QUANTILES = [0.25, 0.75] + + +ChromatogramType = Union[Chromatogram, ChromatogramProxy, ChromatogramInterface] + + +class IntervalRange(object): + lower: float + upper: float + + def __init__(self, lower=None, upper=None): + if isinstance(lower, IntervalRange): + self.lower = lower.lower + self.upper = lower.upper + elif isinstance(lower, (tuple, list)): + self.lower, self.upper = lower + else: + self.lower = lower + self.upper = upper + + def clamp(self, value: float) -> float: + if self.lower is None: + return value + if value < self.lower: + return self.lower + if value > self.upper: + return self.upper + return value + + def interval(self, value: List[float]) -> List[float]: + center = np.mean(value) + lower = center - self.clamp(abs(center - value[0])) + upper = center + self.clamp(abs(value[1] - center)) + return [lower, upper] + + def __repr__(self): + return ""{self.__class__.__name__}({self.lower}, {self.upper})"".format(self=self) + + +class AbundanceWeightedMixin(object): + def build_weight_matrix(self) -> np.ndarray: + W = np.array([ + 1.0 / (x.total_signal * x.weight) for x in self.chromatograms + ]) + if len(self.chromatograms) == 0: + return np.diag(W) + W /= W.max() + return W + + +class ChromatgramFeatureizerBase(object): + + transform = None + + def feature_names(self) -> List[str]: + return ['intercept', 'mass'] + + def _get_apex_time(self, chromatogram: ChromatogramType) -> float: + t = _get_apex_time(chromatogram) + if self.transform is None: + return t + return t - self.transform(chromatogram) + + def _prepare_data_vector(self, chromatogram: ChromatogramType) -> np.ndarray: + return np.array([1, chromatogram.weighted_neutral_mass, ]) + + def _prepare_data_matrix(self, mass_array, chromatograms: Optional[List[ChromatogramType]]=None) -> np.ndarray: + if chromatograms is None: + chromatograms = self.chromatograms + return np.vstack(( + np.ones(len(mass_array)), + np.array(mass_array), + )).T + + def build_weight_matrix(self) -> np.ndarray: + return 1.0 / np.array([x.weight for x in self.chromatograms]) + + +class PredictorBase(object): + transform = None + + def predict(self, chromatogram: ChromatogramType) -> float: + t = self._predict(self._prepare_data_vector(chromatogram)) + if self.transform is None: + return t + return t + self.transform(chromatogram) + + def _predict(self, x: np.ndarray) -> float: + return x.dot(self.parameters) + + def predict_interval(self, chromatogram: ChromatogramType, alpha: float = 0.05) -> np.ndarray: + x = self._prepare_data_vector(chromatogram) + return self._predict_interval(x, alpha=alpha) + + def _predict_interval(self, x: np.ndarray, alpha: float=0.05) -> np.ndarray: + y = self._predict(x) + return prediction_interval(self.solution, x, y, alpha=alpha) + + def __call__(self, x: ChromatogramType) -> float: + return self.predict(x) + + +class LinearModelBase(PredictorBase, SpanningMixin): + def _init_model_data(self): + self.neutral_mass_array = np.array([ + x.weighted_neutral_mass for x in self.chromatograms + ]) + self.data = self._prepare_data_matrix(self.neutral_mass_array, self.chromatograms) + + self.apex_time_array = np.array([ + self._get_apex_time(x) for x in self.chromatograms + ]) + + self.weight_matrix = self.build_weight_matrix() + self._update_model_time_range() + + def _update_model_time_range(self): + if len(self.apex_time_array) == 0: + self.start = 0.0 + self.end = 0.0 + self.centroid = 0.0 + else: + self.start = self.apex_time_array.min() + self.end = self.apex_time_array.max() + if self.weight_matrix.ndim > 1: + d = np.diag(self.weight_matrix) + else: + d = self.weight_matrix + self.centroid = self.apex_time_array.dot(d) / d.sum() + + @property + def start_time(self) -> float: + return self.start + + @property + def end_time(self) -> float: + return self.end + + def _fit(self, resample=False, alpha=None): + if resample: + solution = ransac(self.data, self.apex_time_array, + self.weight_matrix, regularize_alpha=alpha) + if alpha is None: + alt = weighted_linear_regression_fit( + self.data, self.apex_time_array, self.weight_matrix) + else: + alt = weighted_linear_regression_fit_ridge( + self.data, self.apex_time_array, self.weight_matrix, alpha) + if alt.R2 > solution.R2: + return alt + return solution + else: + if alpha is None: + solution = weighted_linear_regression_fit( + self.data, self.apex_time_array, self.weight_matrix) + else: + solution = weighted_linear_regression_fit_ridge( + self.data, self.apex_time_array, self.weight_matrix, alpha) + return solution + + def default_regularization(self) -> np.ndarray: + p = self.data.shape[1] + return np.ones_like(p) * 0.001 + + @property + def estimate(self) -> np.ndarray: + if self.solution is None: + return None + return self.solution.yhat + + @estimate.setter + def estimate(self, value): + pass + + @property + def residuals(self) -> np.ndarray: + if self.solution is None: + return None + return self.solution.residuals + + @residuals.setter + def residuals(self, value): + pass + + @property + def parameters(self) -> np.ndarray: + if self.solution is None: + return None + return self.solution.parameters + + @parameters.setter + def parameters(self, value): + pass + + @property + def projection_matrix(self) -> np.ndarray: + if self.solution is None: + return None + return self.solution.projection_matrix + + @projection_matrix.setter + def projection_matrix(self, value): + pass + + def fit(self, resample=False, alpha=None): + solution = self._fit(resample=resample, alpha=alpha) + self.solution = solution + return self + + def loglikelihood(self) -> float: + n = self.data.shape[0] + n2 = n / 2.0 + rss = self.solution.rss + # The ""concentrated likelihood"" + likelihood = -np.log(rss) * n2 + # The likelihood constant + likelihood -= (1 + np.log(np.pi / n2)) / n2 + if self.weight_matrix.ndim > 1: + W = np.diag(self.weight_matrix) + else: + W = self.weight_matrix + likelihood += 0.5 * np.sum(np.log(W)) + return likelihood + + @property + def rss(self) -> float: + x = self.data + y = self.apex_time_array + w = self.weight_matrix + if w.ndim > 1: + w = np.diag(w) + yhat = x.dot(self.parameters) + residuals = (y - yhat) + rss = (w * residuals * residuals).sum() + return rss + + @property + def mse(self) -> float: + return self.rss / (len(self.apex_time_array) - len(self.parameters) - 1.0) + + def parameter_significance(self) -> np.ndarray: + if self.weight_matrix.ndim > 1: + W = np.diag(self.weight_matrix) + else: + W = self.weight_matrix + XtWX_inv = np.linalg.pinv( + ((self.data.T * W).dot(self.data))) + # With unknown variance, use the mean squared error estimate + sigma_params = np.sqrt(np.diag(self.mse * XtWX_inv)) + degrees_of_freedom = len(self.apex_time_array) - \ + len(self.parameters) - 1.0 + # interval = stats.t.interval(1 - alpha / 2.0, degrees_of_freedom) + t_score = np.abs(self.parameters) / sigma_params + p_value = stats.t.sf(t_score, degrees_of_freedom) * 2 + return p_value + + def parameter_confidence_interval(self, alpha=0.05) -> np.ndarray: + if self.weight_matrix.ndim > 1: + W = np.diag(self.weight_matrix) + else: + W = self.weight_matrix + X = self.data + sigma_params = np.sqrt( + np.diag((self.mse) * np.linalg.pinv( + (X.T * W).dot(X)))) + degrees_of_freedom = len(self.apex_time_array) - \ + len(self.parameters) - 1 + iv = stats.t.interval((1 - alpha) / 2., degrees_of_freedom) + iv = np.array(iv) * sigma_params.reshape((-1, 1)) + return np.array(self.parameters).reshape((-1, 1)) + iv + + def R2(self, adjust=True) -> float: + x = self.data + y = self.apex_time_array + w = self.weight_matrix + if w.ndim > 1: + w = np.diag(w) + yhat = x.dot(self.parameters) + residuals = (y - yhat) + rss = (w * residuals * residuals).sum() + tss = (y - y.mean()) + tss = (w * tss * tss).sum() + n = len(y) + k = len(self.parameters) + if adjust: + adjustment_factor = (n - 1.0) / max(float(n - k - 1.0), 1) + else: + adjustment_factor = 1.0 + R2 = (1 - adjustment_factor * (rss / tss)) + return R2 + + def _df(self) -> int: + return max(len(self.apex_time_array) - len(self.parameters), 1) + + +class IntervalScoringMixin(object): + _interval_padding = 0.0 + + def _threshold_interval(self, interval) -> np.ndarray: + width = (interval[1] - interval[0]) / 2.0 + if self.width_range is not None: + if np.isnan(width): + width = self.width_range.upper + else: + width = self.width_range.clamp(width) + return width + + def has_interval_been_thresholded(self, chromatogram: ChromatogramType, alpha: float = 0.05) -> bool: + interval = self.predict_interval(chromatogram, alpha=alpha) + width = (interval[1] - interval[0]) / 2.0 + thresholded_width = self._threshold_interval(interval) + return width > thresholded_width + + def score_interval(self, chromatogram: ChromatogramType, alpha: float = 0.05) -> float: + interval = self.predict_interval(chromatogram, alpha=alpha) + pred = interval.mean() + delta = abs(chromatogram.apex_time - pred) + width = self._threshold_interval(interval) + self._interval_padding + return max(1 - delta / width, 0.0) + + def _truncate_interval(self, interval): + centroid = interval.mean() + width = self._threshold_interval(interval) + self._interval_padding + return centroid + np.array([-width, width]) + + def calibrate_prediction_interval(self, chromatograms=None, alpha: float=0.05): + if chromatograms is None: + chromatograms = self.chromatograms + ivs = np.array([self.predict_interval(c, alpha) + for c in chromatograms]) + widths = (ivs[:, 1] - ivs[:, 0]) / 2.0 + widths = widths[~np.isnan(widths)] + self.width_range = IntervalRange( + *np.quantile(widths, CALIBRATION_QUANTILES)) + if np.isnan(self.width_range.lower): + raise ValueError(""Width range cannot be NaN"") + return self + + @property + def interval_padding(self) -> Optional[float]: + return self._interval_padding + + @interval_padding.setter + def interval_padding(self, value): + if value is None: + value = 0.0 + self._interval_padding = value + + +class ElutionTimeFitter(LinearModelBase, ChromatgramFeatureizerBase, ScoringFeatureBase, IntervalScoringMixin): + feature_type = 'elution_time' + + chromatograms: Optional[List] + neutral_mass_array: np.ndarray + data: np.ndarray + apex_time_array: np.ndarray + weight_matrix: np.ndarray + solution: WLSSolution + scale: float + transform: Any + width_range: IntervalRange + regularize: bool + + chromatogram_type: ClassVar[Type] = ChromatogramProxy + + def __init__(self, chromatograms, scale=1, transform=None, width_range=None, regularize=False): + self.chromatograms = chromatograms + self.neutral_mass_array = None + self.data = None + self.apex_time_array = None + self.weight_matrix = None + self.solution = None + self.scale = scale + self.transform = transform + self.width_range = IntervalRange(width_range) + self.regularize = regularize + self._init_model_data() + + def __getstate__(self): + state = {} + state['chromatograms'] = self.chromatograms + state['solution'] = self.solution + state['scale'] = self.scale + state['transform'] = self.transform + state['width_range'] = self.width_range + state['regularize'] = self.regularize + state['start_time'] = self.start + state['end_time'] = self.end + state['centroid'] = self.centroid + return state + + def __setstate__(self, state): + self.chromatograms = state['chromatograms'] + self.solution = state['solution'] + self.scale = state['scale'] + self.transform = state['transform'] + self.width_range = state['width_range'] + self.regularize = state['regularize'] + self.start = state['start_time'] + self.end = state['end_time'] + self.centroid = state['centroid'] + + if self.solution is not None: + (self.data, self.apex_time_array) = self.solution.data + self.weight_matrix = self.solution.weights + if self.chromatograms: + self._init_model_data() + + def __reduce__(self): + return self.__class__, (self.chromatograms or [], ), self.__getstate__() + + def _get_chromatograms(self): + return self.chromatograms + + def drop_chromatograms(self): + self.chromatograms = None + return self + + def score(self, chromatogram: ChromatogramType) -> float: + apex = self.predict(chromatogram) + # Use heavier tails (scale 2) to be more tolerant of larger chromatographic + # errors. + # The survival function's maximum value is 0.5, so double this to map the + # range of values to be (0, 1) + score = stats.t.sf( + abs(apex - self._get_apex_time(chromatogram)), + df=self._df(), scale=self.scale) * 2 + return max((score - SMALL_ERROR), SMALL_ERROR) + + def plot(self, ax=None): + if ax is None: + _fig, ax = plt.subplots(1) + ax.scatter(self.neutral_mass_array, + self.apex_time_array, label='Observed') + theoretical_mass = np.linspace( + max(self.neutral_mass_array.min() - 200, 0), + self.neutral_mass_array.max() + 200, 400) + X = self._prepare_data_matrix(theoretical_mass) + Y = X.dot(self.parameters) + ax.plot(theoretical_mass, Y, linestyle='--', label='Trend Line') + pred_interval = self._predict_interval(X) + ax.fill_between( + theoretical_mass, pred_interval[0, :], pred_interval[1, :], + alpha=0.4, label='Prediction Interval') + return ax + + def clone(self): + return self.__class__(self.chromatograms) + + def summary(self, join_char=' | ', justify=True): + if justify: + formatter = str.ljust + else: + def formatter(x, y): + return x + column_labels = ['Feature Name', ""Value"", ""p-value"", ""Conf. Int.""] + feature_names = list(map(str, self.feature_names())) + parameter_values = ['%0.2f' % val for val in self.parameters] + signif = ['%0.3f' % val for val in self.parameter_significance()] + ci = ['%0.2f-%0.2f' % tuple(cinv) + for cinv in self.parameter_confidence_interval()] + sizes = list(map(len, column_labels)) + value_sizes = [max(map(len, col)) + for col in [feature_names, parameter_values, signif, ci]] + sizes = list(map(max, zip(sizes, value_sizes))) + table = [[formatter(v, sizes[i]) for i, v in enumerate(column_labels)]] + for row in zip(feature_names, parameter_values, signif, ci): + table.append([ + formatter(v, sizes[i]) for i, v in enumerate(row) + ]) + joiner = join_char.join + table_str = '\n'.join(map(joiner, table)) + return table_str + + def to_csv(self, fh): + writer = csv.writer(fh) + writer.writerow([""name"", ""value""]) + for fname, value in zip(self.feature_names(), self.parameters): + writer.writerow([fname, value]) + + def to_dict(self) -> Dict: + out = OrderedDict() + keys = self.feature_names() + for k, v in zip(keys, self.parameters): + out[k] = v + return out + + def _infer_factors(self) -> List[str]: + keys = set() + for record in self.chromatograms: + keys.update(record.glycan_composition) + keys = sorted(map(str, keys)) + return keys + + def plot_residuals(self, ax=None): + if ax is None: + _fig, ax = plt.subplots(1) + w = np.diag(self.weight_matrix) if self.weight_matrix.ndim > 1 else self.weight_matrix + ax.scatter(self.apex_time_array, self.residuals, s=w * 1000.0, alpha=0.25, + edgecolor='black') + return ax + + +class SimpleLinearFitter(LinearModelBase): + x: np.ndarray + y: np.ndarray + + weight_matrix: np.ndarray + data: np.ndarray + + def __init__(self, x, y): + self.x = np.array(x) + self.y = self.apex_time_array = np.array(y) + self.weight_matrix = np.diag(np.ones_like(y)) + self.data = np.stack((np.ones_like(x), x)).T + + def predict(self, vx) -> np.ndarray: + if not isinstance(vx, (list, tuple, np.ndarray)): + vx = [vx] + return np.stack((np.ones_like(vx), vx)).T.dot(self.parameters) + + def _prepare_data_vector(self, x) -> np.ndarray: + return np.array([1., x]) + + +class AbundanceWeightedElutionTimeFitter(AbundanceWeightedMixin, ElutionTimeFitter): + pass + + +class FactorChromatogramFeatureizer(ChromatgramFeatureizerBase): + def feature_names(self) -> List[str]: + return ['intercept'] + self.factors + + def _prepare_data_matrix(self, mass_array, chromatograms: Optional[List[ChromatogramType]]=None) -> np.ndarray: + if chromatograms is None: + chromatograms = self.chromatograms + return np.vstack([np.ones(len(mass_array)), ] + [ + np.array([c.glycan_composition[f] for c in chromatograms]) + for f in self.factors]).T + + def _prepare_data_vector(self, chromatogram: ChromatogramType, no_intercept=False) -> np.ndarray: + intercept = 0 if no_intercept else 1 + return np.array( + [intercept] + [ + chromatogram.glycan_composition[f] for f in self.factors]) + + +class FactorTransform(PredictorBase, FactorChromatogramFeatureizer): + factors: List[str] + parameters: np.ndarray + + def __init__(self, factors, parameters, intercept=0.0): + self.factors = factors + # Add a zero intercept + self.parameters = np.concatenate([[intercept], parameters]) + + +class FactorElutionTimeFitter(FactorChromatogramFeatureizer, ElutionTimeFitter): + def __init__(self, chromatograms, factors=None, scale=1, transform=None, width_range=None, regularize=False): + if factors is None: + factors = ['Hex', 'HexNAc', 'Fuc', 'Neu5Ac'] + self.factors = list(factors) + self._coerced_factors = [ + FrozenMonosaccharideResidue.from_iupac_lite(f) + for f in self.factors + ] + super(FactorElutionTimeFitter, self).__init__( + chromatograms, scale=scale, transform=transform, + width_range=width_range, regularize=regularize) + + def __getstate__(self): + state = super(FactorElutionTimeFitter, self).__getstate__() + state['factors'] = self.factors + return state + + def __setstate__(self, state): + super(FactorElutionTimeFitter, self).__setstate__(state) + self.factors = state['factors'] + self._coerced_factors = [ + FrozenMonosaccharideResidue.from_iupac_lite(f) + for f in self.factors + ] + + def predict_delta_glycan(self, chromatogram: ChromatogramType, delta_glycan: HashableGlycanComposition) -> float: + try: + shifted = chromatogram.shift_glycan_composition(delta_glycan) + except AttributeError: + shifted = GlycopeptideChromatogramProxy.from_chromatogram( + chromatogram).shift_glycan_composition(delta_glycan) + return self.predict(shifted) + + def prediction_plot(self, ax=None): + if ax is None: + _fig, ax = plt.subplots(1) + ax.scatter(self.apex_time_array, self.estimate) + preds = np.array(self.estimate) + obs = np.array(self.apex_time_array) + lo, hi = min(preds.min(), obs.min()), max(preds.max(), obs.max()) + lo -= 0.2 + hi += 0.2 + ax.set_xlim(lo, hi) + ax.set_ylim(lo, hi) + ax.plot([lo, hi], [lo, hi], color='black', linestyle='--', lw=0.75) + ax.set_xlabel(""Experimental RT (Min)"", fontsize=14) + ax.set_ylabel(""Predicted RT (Min)"", fontsize=14) + ax.figure.text(0.15, 0.8, ""$R^2:%0.2f$\nMSE:%0.2f"" % (self.R2(True), self.mse)) + return ax + + def plot(self, ax=None, include_intervals=True): + from glycresoft.plotting.colors import ColorMapper + if ax is None: + _fig, ax = plt.subplots(1) + colorer = ColorMapper() + factors = self.factors + column_offset = 1 + distinct_combinations = set() + partitions = defaultdict(list) + for i, row in enumerate(self.data): + key = tuple(row[column_offset:]) + distinct_combinations.add(key) + partitions[key].append( + (self.neutral_mass_array[i], self.apex_time_array[i])) + + theoretical_mass = np.linspace( + max(self.neutral_mass_array.min() - 200, 0), + self.neutral_mass_array.max() + 200, 400) + for combination in distinct_combinations: + members = partitions[combination] + ox, oy = zip(*members) + v = np.ones_like(theoretical_mass) + factor_partition = [v * f for f in combination] + label_part = ','.join([""%s:%d"" % (fl, fv) for fl, fv in zip( + factors, combination)]) + color = colorer[combination] + ax.scatter(ox, oy, label=label_part, color=color) + X = np.vstack([ + np.ones_like(theoretical_mass), + # theoretical_mass, + ] + factor_partition).T + Y = X.dot(self.parameters) + ax.plot( + theoretical_mass, Y, linestyle='--', color=color) + if include_intervals: + pred_interval = self._predict_interval(X) + ax.fill_between( + theoretical_mass, pred_interval[0, :], pred_interval[1, :], + alpha=0.4, color=color) + + return ax + + def clone(self): + return self.__class__(self.chromatograms, factors=self.factors, scale=self.scale) + + def predict(self, chromatogram: ChromatogramType, no_intercept=False) -> float: + return self._predict(self._prepare_data_vector(chromatogram, no_intercept=no_intercept)) + + +class AbundanceWeightedFactorElutionTimeFitter(AbundanceWeightedMixin, FactorElutionTimeFitter): + pass + + +class PeptideBackboneKeyedMixin(object): + def get_peptide_key(self, chromatogram: ChromatogramType) -> str: + try: + return chromatogram.peptide_key + except AttributeError: + return GlycopeptideChromatogramProxy.from_chromatogram(chromatogram).peptide_key + + +class PeptideGroupChromatogramFeatureizer(FactorChromatogramFeatureizer, PeptideBackboneKeyedMixin): + + def _prepare_data_matrix(self, mass_array: np.ndarray, + chromatograms: Optional[List[ChromatogramType]]=None) -> np.ndarray: + if chromatograms is None: + chromatograms = self.chromatograms + p = len(self._peptide_to_indicator) + n = len(chromatograms) + peptides = np.zeros((n, p + len(self.factors))) + for i, c in enumerate(chromatograms): + peptide_key = self.get_peptide_key(c) + if peptide_key in self._peptide_to_indicator: + j = self._peptide_to_indicator[peptide_key] + peptides[i, j] = 1 + gc = c.glycan_composition + for j, f in enumerate(self._coerced_factors, p): + peptides[i, j] = gc._getitem_fast(f) + + # Omit the intercept, so that all peptide levels are used without inducing linear dependence. + return peptides + + def feature_names(self) -> List[str]: + names = [] + peptides = [None] * len(self._peptide_to_indicator) + for key, value in self._peptide_to_indicator.items(): + peptides[value] = key + names.extend(peptides) + names.extend(self.factors) + return names + + def _prepare_data_vector(self, chromatogram: ChromatogramType, no_intercept=False) -> np.ndarray: + k = len(self._peptide_to_indicator) + feature_vector = np.zeros(k + len(self.factors)) + max_peptide_i = k - 1 + if not no_intercept: + peptide_key = self.get_peptide_key(chromatogram) + if peptide_key in self._peptide_to_indicator: + feature_vector[self._peptide_to_indicator[peptide_key]] = 1 + else: + logger.debug( + ""Peptide sequence of %s not part of the model."", chromatogram) + gc = chromatogram.glycan_composition + for i, f in enumerate(self._coerced_factors, 1 + max_peptide_i): + feature_vector[i] = gc._getitem_fast(f) + return feature_vector + + def has_peptide(self, peptide) -> bool: + '''Check if the peptide is included in the model. + + Parameters + ---------- + peptide : str + The peptide sequence to check + + Returns + ------- + bool + ''' + if not isinstance(peptide, str): + peptide = self.get_peptide_key(peptide) + return peptide in self._peptide_to_indicator + + def predict_component_times(self, chromatogram: ChromatogramType): + y_gp = self.predict(chromatogram) + deglyco = chromatogram.copy() + deglyco.glycan_composition.clear() + y_p = self.predict(deglyco) + y_g = y_gp - y_p + return y_p, y_g + + +class PeptideFactorElutionTimeFitter(PeptideGroupChromatogramFeatureizer, FactorElutionTimeFitter): + _peptide_to_indicator: DefaultDict[str, int] + by_peptide: DefaultDict[str, List] + peptide_groups: List + + chromatogram_type: ClassVar[Type] = GlycopeptideChromatogramProxy + + def __init__(self, chromatograms, factors=None, scale=1, transform=None, width_range=None, regularize=False): + if factors is None: + factors = ['Hex', 'HexNAc', 'Fuc', 'Neu5Ac'] + self._peptide_to_indicator = defaultdict(make_counter(0)) + self.by_peptide = defaultdict(list) + self.peptide_groups = [] + # Ensure that _peptide_to_indicator is properly initialized + for obs in chromatograms: + key = self.get_peptide_key(obs) + self.peptide_groups.append(self._peptide_to_indicator[key]) + self.by_peptide[key].append(obs) + self.peptide_groups = np.array(self.peptide_groups) + super(PeptideFactorElutionTimeFitter, self).__init__( + chromatograms, list(factors), scale=scale, transform=transform, + width_range=width_range, regularize=regularize) + + def __getstate__(self): + state = super(PeptideFactorElutionTimeFitter, self).__getstate__() + state['_peptide_to_indicator'] = self._peptide_to_indicator + state['peptide_groups'] = self.peptide_groups + state['by_peptide'] = self.by_peptide + return state + + def __setstate__(self, state): + super(PeptideFactorElutionTimeFitter, self).__setstate__(state) + self._peptide_to_indicator = state['_peptide_to_indicator'] + self.peptide_groups = state['peptide_groups'] + self.by_peptide = state['by_peptide'] + + + def drop_chromatograms(self): + super(PeptideFactorElutionTimeFitter, self).drop_chromatograms() + self.by_peptide = {k: [] for k in self.by_peptide} + return self + + @property + def peptide_count(self) -> int: + return len(self.by_peptide) + + def default_regularization(self) -> np.ndarray: + monosaccharide_alphas = {} + alpha = np.concatenate(( + np.zeros(self.peptide_count), + [monosaccharide_alphas.get(f, 0.01) for f in self.factors] + )) + return alpha + + def fit(self, resample=False, alpha=None): + if alpha is None and self.regularize: + alpha = self.default_regularization() + return super().fit(resample, alpha) + + def groupwise_R2(self, adjust=True): + x = self.data + y = self.apex_time_array + w = self.weight_matrix + if w.ndim > 1: + w = np.diag(w) + yhat = x.dot(self.parameters) + residuals = (y - yhat) + rss_u = (w * residuals * residuals) + tss = (y - y.mean()) + tss_u = (w * tss * tss) + + mapping = {} + for key, value in self._peptide_to_indicator.items(): + mask = x[:, value] == 1 + rss = rss_u[mask].sum() + tss = tss_u[mask].sum() + n = len(y) + k = len(self.parameters) + if adjust: + adjustment_factor = (n - 1.0) / float(n - k - 1.0) + else: + adjustment_factor = 1.0 + R2 = (1 - adjustment_factor * (rss / tss)) + mapping[key] = R2 + return mapping + + def plot_residuals(self, ax=None, subset=None): + if ax is None: + _fig, ax = plt.subplots(1) + if subset is not None and subset: + if isinstance(subset[0], int): + group_ids = subset + else: + group_ids = [self._peptide_to_indicator[k] for k in subset] + else: + group_ids = np.unique(self.peptide_groups) + group_label_map = {v: k for k, v in self._peptide_to_indicator.items()} + preds = np.array(self.estimate) + obs = np.array(self.apex_time_array) + if self.weight_matrix.ndim > 1: + weights = np.diag(self.weight_matrix) + else: + weights = self.weight_matrix + for i in group_ids: + mask = self.peptide_groups == i + dv = preds[mask] - obs[mask] + sub = obs[mask] + a = ax.scatter( + sub, dv, + s=weights[mask] * 500, + edgecolors='black', + alpha=0.5, + label=""%s %0.2f"" % (group_label_map[i], sub.min())) + f = SimpleLinearFitter(obs[mask], dv).fit() + x = np.linspace(sub.min(), sub.max()) + ax.plot(x, f.predict(x), color=a.get_facecolor()[0]) + + return ax + + def prediction_plot(self, ax=None, subset=None): + if ax is None: + _fig, ax = plt.subplots(1) + if subset is not None and subset: + if isinstance(subset[0], int): + group_ids = subset + else: + group_ids = [self._peptide_to_indicator[k] for k in subset] + else: + group_ids = np.unique(self.peptide_groups) + group_label_map = {v: k for k, v in self._peptide_to_indicator.items()} + preds = np.array(self.estimate) + obs = np.array(self.apex_time_array) + if self.weight_matrix.ndim > 1: + weights = np.diag(self.weight_matrix) + else: + weights = self.weight_matrix + for i in group_ids: + mask = self.peptide_groups == i + ax.scatter( + obs[mask], preds[mask], + s=weights[mask] * 500, + edgecolors='black', + alpha=0.5, + label=""%s %0.2f"" % (group_label_map[i], obs[mask].min())) + + lo, hi = min(preds.min(), obs.min()), max(preds.max(), obs.max()) + lo -= 0.2 + hi += 0.2 + ax.set_xlim(lo, hi) + ax.set_ylim(lo, hi) + ax.plot([lo, hi], [lo, hi], color='black', linestyle='--', lw=0.75) + ax.set_xlabel(""Experimental RT (Min)"", fontsize=14) + ax.set_ylabel(""Predicted RT (Min)"", fontsize=14) + ax.figure.text(0.15, 0.8, ""$R^2:%0.2f$\nMSE:%0.2f"" % + (self.R2(True), self.mse)) + return ax + + +class AbundanceWeightedPeptideFactorElutionTimeFitter(AbundanceWeightedMixin, PeptideFactorElutionTimeFitter): + pass + + +class ModelEnsemble(PeptideBackboneKeyedMixin, IntervalScoringMixin): + models: OrderedDict[float, ElutionTimeFitter] + _models: List[ElutionTimeFitter] + _chromatograms: Optional[List[GlycopeptideChromatogramProxy]] + _summary_statistics: Dict[str, Any] + width_range: IntervalRange + residual_fdr: Optional[ResidualFDREstimator] + + def __init__(self, models, width_range=None): + self._set_models(models) + self.width_range = IntervalRange(width_range) + self._chromatograms = None + self.external_peptide_offsets = {} + self._summary_statistics = {} + self.residual_fdr = None + + @property + def model_width(self) -> float: + points = sorted(self.models) + return np.mean(np.diff(points)) * 4 + + def __reduce__(self): + return self.__class__, (OrderedDict(), self.width_range), self.__getstate__() + + def __getstate__(self): + state = dict() + models = OrderedDict() + for key, value in self.models.items(): + buffer = io.BytesIO() + writer = gzip.GzipFile(fileobj=buffer, mode='wb') + dill.dump(value, writer, 2) + writer.flush() + models[key] = buffer.getvalue() + state['models'] = models + state['summary_statistics'] = self._summary_statistics + state['interval_padding'] = self._interval_padding + state['residual_fdr'] = self.residual_fdr + return state + + def __setstate__(self, state): + if not state: + return + models = OrderedDict() + for key, buffer in state.get('models', {}).items(): + buffer = io.BytesIO(buffer) + reader = gzip.GzipFile(fileobj=buffer) + model = dill.load(reader) + models[key] = model + if models: + self._set_models(models) + self._summary_statistics = state.get(""summary_statistics"", {}) + self._interval_padding = state.get(""interval_padding"", 0.0) + self.residual_fdr = state.get('residual_fdr') + + def _set_models(self, models): + self.models = models + self._models = list(models.values()) + + def _compute_summary_statistics(self) -> Dict[str, Any]: + chromatograms = self.chromatograms + apex_time_array = np.array([ + c.apex_time for c in chromatograms + ]) + labels = [(str(c.structure), c.mass_shifts) for c in chromatograms] + predicted_apex_time_array = np.array([ + self.predict(c) for c in chromatograms + ]) + confidence_intervals = np.array([ + self.predict_interval(c, alpha=0.01) for c in chromatograms + ]) + residuals_array = apex_time_array - predicted_apex_time_array + self._summary_statistics.update({ + ""apex_time_array"": apex_time_array, + ""predicted_apex_time_array"": predicted_apex_time_array, + ""confidence_intervals"": confidence_intervals, + ""residuals_array"": residuals_array, + ""labels"": labels, + ""original_width_range"": [self.width_range.lower, self.width_range.upper] if self.width_range else None + }) + + def R2(self, adjust=True) -> float: + apex_time_array = self._summary_statistics['apex_time_array'] + predicted_apex_time_array = self._summary_statistics['predicted_apex_time_array'] + mask = ~np.isnan(predicted_apex_time_array) + return np.corrcoef(apex_time_array[mask], predicted_apex_time_array[mask])[0, 1] ** 2 + + def _models_for(self, chromatogram: Union[Number, ChromatogramType]) -> Iterator[Tuple[ElutionTimeFitter, float]]: + if not isinstance(chromatogram, Number): + point = chromatogram.apex_time + else: + point = chromatogram + for model in self._models: + if model.contains(point): + weight = abs(model.centroid - point) + 1 + yield model, 1.0 / weight + + def models_for(self, chromatogram: Union[Number, ChromatogramType]) -> List[Tuple[ElutionTimeFitter, float]]: + return list(self._models_for(chromatogram)) + + def coverage_for(self, chromatogram: GlycopeptideChromatogramProxy) -> float: + refs = array.array('d') + weights = array.array('d') + for mod, weight in self._models_for(chromatogram): + refs.append(mod.has_peptide(chromatogram)) + weights.append(weight) + if len(weights) == 0: + return 0 + else: + coverage = np.dot(refs, weights) / np.sum(weights) + return coverage + + def has_peptide(self, chromatogram: ChromatogramType) -> bool: + return any(m.has_peptide(chromatogram) for m in self._models) + + def estimate_query_point(self, + glycopeptide: Union[str, PeptideSequence, ChromatogramType] + ) -> GlycopeptideChromatogramProxy: + if isinstance(glycopeptide, str): + key = str(PeptideSequence(glycopeptide).deglycosylate()) + glycopeptide = PeptideSequence(glycopeptide) + case = GlycopeptideChromatogramProxy( + glycopeptide.total_mass, + -1, 1, glycopeptide.glycan_composition, structure=glycopeptide) + elif isinstance(glycopeptide, PeptideSequence): + key = str(glycopeptide.clone().deglycosylate()) + case = GlycopeptideChromatogramProxy( + glycopeptide.total_mass, + -1, 1, glycopeptide.glycan_composition, structure=glycopeptide) + else: + key = self.get_peptide_key(glycopeptide) + case = glycopeptide.clone() + preds = [] + for t, mod in self.models.items(): + if mod.has_peptide(key): + preds.append(mod.predict(case)) + query_point = np.nanmedian(preds) + case.apex_time = query_point + return case + + def predict_interval_external_peptide(self, chromatogram: ChromatogramType, alpha=0.05, merge=True) -> List[float]: + key = self.get_peptide_key(chromatogram) + offset = self.external_peptide_offsets[key] + interval = self.predict_interval(chromatogram, alpha=alpha, merge=merge) + if merge: + interval += offset + else: + interval = [iv + offset for iv in interval] + return interval + + def predict_interval(self, chromatogram: ChromatogramType, alpha: float=0.05, + merge: bool=True, check_peptide: bool=True) -> np.ndarray: + weights = [] + preds = [] + for mod, w in self._models_for(chromatogram): + if check_peptide and not mod.has_peptide(chromatogram): + continue + preds.append(mod.predict_interval(chromatogram, alpha=alpha)) + weights.append(w) + weights = np.array(weights) + if len(weights) == 0: + return np.array([np.nan, np.nan]) + + mask = ~np.isnan(weights) & ~(np.isnan(preds).sum(axis=1).astype(bool)) + preds = np.array(preds) + preds = preds[mask, :] + weights = weights[mask] + if len(weights) == 0: + return np.array([np.nan, np.nan]) + weights /= weights.max() + if merge: + if len(weights) == 0: + return np.array([np.nan, np.nan]) + avg = np.average(preds, weights=weights, axis=0) + return avg + return preds, weights + + def predict(self, chromatogram: ChromatogramType, merge: bool=True, + check_peptide: bool=True) -> Union[float, Tuple[np.ndarray, np.ndarray]]: + weights = [] + preds = [] + for mod, w in self._models_for(chromatogram): + if check_peptide and not mod.has_peptide(chromatogram): + continue + preds.append(mod.predict(chromatogram)) + weights.append(w) + if len(weights) == 0: + return np.nan + weights = np.array(weights) + weights /= weights.max() + if merge: + avg = np.average(preds, weights=weights) + return avg + return np.array(preds), weights + + def score(self, chromatogram: ChromatogramType, merge=True) -> Union[float, Tuple[np.ndarray, np.ndarray]]: + weights = [] + preds = [] + for mod, w in self._models_for(chromatogram): + preds.append(mod.score(chromatogram)) + weights.append(w) + weights = np.array(weights) + weights /= weights.max() + if merge: + avg = np.average(preds, weights=weights) + return avg + preds = np.array(preds) + return preds, weights + + def _get_chromatograms(self): + if self._chromatograms: + return self._chromatograms + chroma = set() + for model in self.models.values(): + for chrom in model._get_chromatograms(): + chroma.add(chrom) + self._chromatograms = sorted(chroma, key=lambda x: x.apex_time) + return self._chromatograms + + def drop_chromatograms(self): + self._chromatograms = None + for model in self._models: + model.drop_chromatograms() + return self + + @property + def chromatograms(self): + return self._get_chromatograms() + + def calibrate_prediction_interval(self, chromatograms: Optional[List[GlycopeptideChromatogramProxy]]=None, + alpha: float=0.01): + if chromatograms is None: + chromatograms = self.chromatograms + ivs = np.array([self.predict_interval(c, alpha) + for c in chromatograms]) + if len(ivs) == 0: + widths = [] + else: + widths = (ivs[:, 1] - ivs[:, 0]) / 2.0 + widths = widths[~np.isnan(widths)] + if len(widths) == 0: + self.width_range = IntervalRange(0.0, float('inf')) + else: + self.width_range = IntervalRange(*np.quantile(widths, CALIBRATION_QUANTILES)) + if np.isnan(self.width_range.lower): + raise ValueError(""Width range cannot be NaN"") + return self + + def plot_number_of_training_points(self, ax=None, color='teal', markerfacecolor='mediumspringgreen', + markeredgecolor='mediumaquamarine', markersize=7, marker='.'): + if ax is None: + _fig, ax = plt.subplots(1) + ts, n_pts = zip(*[(k, v.data.shape[0]) for k, v in self.models.items()]) + ax.plot(ts, n_pts, marker=marker, markersize=markersize, + color=color, + markerfacecolor=markerfacecolor, + markeredgecolor=markeredgecolor) + + def nearest_multiple_of_ten(value): + return round(value / 10) * 10 + + ax.spines['top'].set_visible(False) + ax.spines['right'].set_visible(False) + + tick_multiple = (nearest_multiple_of_ten(max(n_pts)) // 3) + if tick_multiple <= 0: + tick_multiple = 5 + + ax.yaxis.set_major_locator(plt.MultipleLocator(tick_multiple)) + ax.set_ylabel(""# of Data Points"", size=14) + ax.set_xlabel(""Time"", size=14) + return ax + + def plot_factor_coefficients(self, ax=None, weight_by_obs=False): + if ax is None: + _fig, ax = plt.subplots(1) + from glycresoft.plotting.colors import get_color + + param_cis = {} + + def local_point(point, factor): + val = [] + ci = [] + weights = [] + for mod, weight in self._models_for(point): + i = mod.feature_names().index(factor) + val.append(mod.parameters[i]) + try: + param_ci = param_cis[mod.start_time, mod.end_time] + except KeyError: + param_cis[mod.start_time, mod.end_time] = param_ci = mod.parameter_confidence_interval() + ci_i = param_ci[i] + d = (ci_i[1] - ci_i[0]) / 2 + ci.append(d) + weights.append(weight * len(mod.apex_time_array) if weight_by_obs else weight) + if not weights: + return 0.0, 0.0 + return np.average(val, weights=weights), np.average(ci, weights=weights) + + times = np.arange(self._models[0].start_time, self._models[-1].end_time, 1) + factors = set() + for x in self.models.values(): + factors.update(x.factors) + for factor in factors: + yval = [] + xval = [] + ci_width = [] + for t in times: + xval.append(t) + y, ci_delta = local_point(t, factor) + yval.append(y) + ci_width.append(ci_delta) + c = get_color(factor) + xval = np.array(xval) + yval = np.array(yval) + ci_width = np.array(ci_width) + ax.plot(xval, yval, label=factor, marker='.', color=c) + ax.fill_between(xval, yval - ci_width, yval + ci_width, + color=c, alpha=0.25) + ax.set_xlabel(""Time"", size=14) + ax.set_ylabel(""Local Average Factor Coefficient"", size=14) + ax.legend(loc='upper left', frameon=False, bbox_to_anchor=(1.0, 1.0)) + ax.spines['top'].set_visible(False) + ax.spines['right'].set_visible(False) + ax.figure.tight_layout() + return ax + + def plot_residuals(self, ax=None): + if ax is None: + _fig, ax = plt.subplots(1) + apex_time = self._summary_statistics['apex_time_array'] + residuals = self._summary_statistics['residuals_array'] + ax.scatter(apex_time, residuals, s=15, edgecolors='black', alpha=0.5, color='teal') + ax.set_xlabel(""Time"", size=14) + ax.set_ylabel(""Residuals"", size=14) + ax.spines['top'].set_visible(False) + ax.spines['right'].set_visible(False) + + max_val = np.nanmax(residuals) + min_val = np.nanmin(residuals) + for t, mod in self.models.items(): + ax.vlines([mod.start, mod.end], min_val, max_val, colors='gray', lw=0.5, linestyles='--') + + ax.set_ylim(min_val - 1, max_val + 1) + ax.hlines([-self.width_range.upper, self.width_range.upper], + apex_time.min(), apex_time.max(), linestyles='--', lw=0.5, color='gray') + + if self.interval_padding: + ax.hlines([-self.width_range.upper - self.interval_padding, self.width_range.upper + self.interval_padding], + apex_time.min(), apex_time.max(), linestyles='dotted', lw=0.5, color='black') + ax.figure.tight_layout() + return ax + + def estimate_mean_error_from_interval(self) -> float: + cis = self._summary_statistics['confidence_intervals'] + ys = self._summary_statistics['apex_time_array'] + # The widths of each interval + widths = (cis[:, 1] - cis[:, 0]) / 2 + centroid_error = np.abs(cis - ys[:, None]) + error_from_nearest_interval_edge = np.clip(centroid_error - widths[:, None], 0, np.inf).min(axis=1) + mean_error = np.nanmean(error_from_nearest_interval_edge) + return mean_error + + def _reconstitute_proxies(self) -> List[GlycopeptideChromatogramProxy]: + proxies = [] + + summary_values = self._summary_statistics + + for i, (label, mass_shifts) in enumerate(summary_values['labels']): + gp = FragmentCachingGlycopeptide(label) + gc = gp.glycan_composition + apex_time = summary_values['apex_time_array'][i] + proxies.append( + GlycopeptideChromatogramProxy( + gp.total_mass, apex_time, 1.0, gc, mass_shifts=mass_shifts, structure=gp + ) + ) + return proxies + + +def unmodified_modified_predicate(x): + return Unmodified in x.mass_shifts and Ammonium in x.mass_shifts + + +class EnsembleBuilder(TaskBase): + aggregator: GlycoformAggregator + points: Optional[np.ndarray] + centers: OrderedDict + models: OrderedDict + + def __init__(self, aggregator: GlycoformAggregator): + self.aggregator = aggregator + self.points = None + self.centers = OrderedDict() + self.models = OrderedDict() + + def estimate_width(self) -> float: + try: + width = int(max(np.nanmedian(v) for v in + self.aggregator.deltas().values() + if len(v) > 0)) + 1 + except ValueError: + width = 2.0 + width *= 2.0 + self.log(""... Estimated Region Width: %0.2f"" % (width, )) + return width + + def generate_points(self, width: float) -> np.ndarray: + points = np.arange( + int(self.aggregator.start_time) - 1, + int(self.aggregator.end_time) + 1, width / 4.) + if len(points) > 0 and points[-1] <= self.aggregator.end_time: + points = np.append(points, self.aggregator.end_time + 1) + return points + + def partition(self, width: Optional[float]=None, predicate: Optional[Callable]=None): + if width is None: + width_value = self.estimate_width() + width = defaultdict(lambda: width_value) + elif isinstance(width, (float, int, np.ndarray)): + width_value = width + width = defaultdict(lambda: width_value) + else: + width_value = None + if predicate is None: + predicate = bool + if self.points is None: + if width_value is None: + raise ValueError(""width_value was None"") + self.points = self.generate_points(width_value) + centers = OrderedDict() + for point in self.points: + w = width[point] + centers[point] = GlycoformAggregator( + list(filter(predicate, + self.aggregator.overlaps(point - w, point + w)))) + self.centers = centers + return self + + def estimate_delta_widths(self, baseline: Optional[float]=None) -> OrderedDict: + if baseline is None: + baseline = 0.0 + + delta_index = defaultdict(list) + time = [] + for cent, group in self.centers.items(): + time.append(cent) + deltas = group.deltas() + + for factor in self.aggregator.factors: + val = np.nanmedian(deltas.get(factor, [])) + delta_index[factor].append(val) + + delta_index = { + k: DeltaOverTimeFilter(k, v, time) for k, v in delta_index.items() + } + + group_widths = OrderedDict() + for t in time: + best = 0 + for k, v in delta_index.items(): + val = v[v.search(t)] + best = max(abs(val), best) + best = round(best) * 2 + if best < 1: + best = 2 + if best < baseline: + best = baseline + group_widths[t] = best + return group_widths + + def _fit(self, i: int, point: float, members: List[GlycopeptideChromatogramProxy], + point_members: List[List[GlycopeptideChromatogramProxy]], + predicate: Callable[[Any], bool], model_type: Callable[..., ElutionTimeFitter], + regularize: bool = False, resample: bool = False) -> Tuple[float, ElutionTimeFitter]: + n = len(point_members) + obs = list(filter(predicate, members)) + if not obs: + return point, None + + m = model_type( + obs, self.aggregator.factors, regularize=regularize) + + if m.data.shape[0] <= m.data.shape[1]: + offset = 1 + while m.data.shape[0] <= m.data.shape[1] and offset < (len(point_members) // 2 + 1): + extra = set(members) + for j in range(1, offset + 1): + if i > j: + extra.update(list(point_members[i - j][1])) + if i + j < n: + extra.update(list(point_members[i + j][1])) + obs = sorted(filter(predicate, extra), key=lambda x: x.apex_time) + m = model_type(obs, self.aggregator.factors, regularize=regularize) + offset += 1 + self.debug( + ""... Borrowed %d observations from regions %d steps away for region at %0.3f (%d members, %r)"" % ( + len(extra - set(members)), offset, point, len(members), m.data.shape)) + + m = m.fit(resample=resample) + return point, m + + def fit(self, predicate: Optional[Callable[[Any], bool]]=None, + model_type: Optional[Callable[..., ElutionTimeFitter]]=None, + regularize: bool=False, resample: bool=False, n_workers: Optional[int]=None): + if model_type is None: + model_type = AbundanceWeightedPeptideFactorElutionTimeFitter + if predicate is None: + predicate = bool + if n_workers is None: + n_workers = min(cpu_count(), 6) + + models: OrderedDict[float, ElutionTimeFitter] = OrderedDict() + point_members = list(self.centers.items()) + + tasks: OrderedDict[float, futures.Future[Tuple[float, + ElutionTimeFitter]]] = OrderedDict() + with futures.ThreadPoolExecutor(n_workers, thread_name_prefix=""ElutionTimeModelFitter"") as executor: + for i, (point, members) in enumerate(point_members): + m: ElutionTimeFitter + + result = executor.submit( + self._fit, i, point, members, point_members, predicate, + model_type, regularize, resample) + tasks[point] = result + + for _, result in tasks.items(): + point, m = result.result() + if m is None: + continue + models[point] = m + self.models = models + return self + + def merge(self): + return ModelEnsemble(self.models) + + +DeltaParam = namedtuple( + ""DeltaParam"", (""mean"", ""sdev"", ""size"", ""values"", ""weights"")) + + +class LocalShiftGraph(object): + chromatograms: List + max_distance: float + key_cache: GlycanCompositionDeltaCache + distance_cache: DistanceCache + edges: DefaultDict[frozenset, List] + shift_to_delta: DefaultDict[str, List[Tuple[GlycopeptideChromatogramProxy, frozenset]]] + groups: GlycoformAggregator + key_cache: Dict + delta_params: Dict[str, DeltaParam] + + def __init__(self, chromatograms, max_distance=3, key_cache=None, distance_cache=None, delta_cache=None): + if distance_cache is None: + distance_cache = DistanceCache(composition_distance) + if delta_cache is None: + delta_cache = GlycanCompositionDeltaCache() + self.chromatograms = chromatograms + self.max_distance = max_distance + self.edges = defaultdict(list) + self.shift_to_delta = defaultdict(list) + self.groups = GlycoformAggregator(chromatograms) + self.key_cache = key_cache or {} + self.distance_cache = distance_cache + self.delta_cache = delta_cache + + self.build_edges() + self.delta_params = self.estimate_delta_distribution() + + def build_edges(self): + for key, group in self.groups.by_peptide.items(): + base_time = 0.0 + a: GlycopeptideChromatogramProxy + b: GlycopeptideChromatogramProxy + for a, b in itertools.permutations(group, 2): + distance = self.distance_cache( + a.glycan_composition, b.glycan_composition)[0] + if distance > self.max_distance or distance == 0: + continue + delta_comp = self.delta_cache(a.glycan_composition, b.glycan_composition) + # Construct the structure property directly without paying property overhead + structure_key = (key + delta_comp.serialize()) + if structure_key in self.key_cache: + structure = self.key_cache[structure_key] + else: + structure = FragmentCachingGlycopeptide(structure_key) + self.key_cache[structure_key] = structure + rec = GlycopeptideChromatogramProxy( + a.weighted_neutral_mass, base_time + a.apex_time - b.apex_time, + np.sqrt(a.total_signal * b.total_signal), + delta_comp, + structure=structure, + peptide_key=key, + weight=float(distance) ** 4 + (a.weight + b.weight) + ) + rec._structure = structure + + a_tag = a.tag + b_tag = b.tag + if a_tag is not None and b_tag is not None: + edge_key = frozenset((a_tag, b_tag)) + else: + edge_key = frozenset((str(a.structure), str(b.structure))) + delta_key = delta_comp + self.edges[edge_key].append(rec) + # Use string form to discard 0-value keys + self.shift_to_delta[str(delta_key)].append((rec, edge_key)) + + def estimate_delta_distribution(self) -> Dict[str, DeltaParam]: + params = {} + for shift, delta_chroms in self.shift_to_delta.items(): + apex_times = array.array('f') + weights = array.array('f') + for rec, _key in delta_chroms: + apex_times.append(rec.apex_time) + weights.append(rec.total_signal if rec.total_signal > 1 else (1 + 1e-13)) + + apex_times = np.array(apex_times) + weights = np.log10(weights) + + W = weights.sum() + weighted_mean: float = np.dot(apex_times, weights) / W + weighted_sdev: float = np.sqrt( + weights.dot((apex_times - weighted_mean) ** 2) / (W - 1) + ) + if weighted_sdev > abs(weighted_mean): + tmp = weighted_sdev + weighted_sdev = max(abs(weighted_mean), 1.0) + logger.debug( + ""Delta parameter %r's standard deviation was over-dispersed %r/%r. Capping at %r"", + shift, tmp, weighted_mean, weighted_sdev + ) + + # NOTE: When len(delta_chroms) == 1, weighted_sdev = 0.0, so no observations + # are allowed through. This is intentional because we cannot trust singletons here. + upper = weighted_mean + weighted_sdev * 2.5 + lower = weighted_mean - weighted_sdev * 2.5 + ii = [] + for i, x in enumerate(apex_times): + if lower < x < upper: + ii.append(i) + if len(ii) != len(apex_times): + apex_times = apex_times[ii] + weights = weights[ii] + W = weights.sum() + if len(weights): + weighted_mean = np.dot(apex_times, weights) / W + weighted_sdev = np.sqrt(weights.dot((apex_times - weighted_mean) ** 2) / (W - 1)) + else: + weighted_mean = 0 + weighted_sdev = 1 + + params[shift] = DeltaParam(weighted_mean, weighted_sdev, len(apex_times), apex_times, weights) + return params + + def is_composite(self, shift) -> bool: + value = HashableGlycanComposition.parse(shift) + return sum(map(abs, value.values())) > 1 + + def composite_to_individuals(self, shift) -> List[Tuple[HashableGlycanComposition, int]]: + shift = HashableGlycanComposition.parse(shift) + return [(HashableGlycanComposition({k: v / abs(v)}), v) for k, v in shift.items()] + + def compose_shift(self, shift) -> Tuple[float, float]: + parts = self.composite_to_individuals(shift) + mean = 0.0 + variance = 0.0 + for (part, mult) in parts: + # Throw a KeyError if we do not have a component edge + # to reference. + param = self.delta_params[part] + mean += param.mean * abs(mult) + variance += param.sdev ** 2 * abs(mult) + return mean, np.sqrt(variance) + + def process_edges(self) -> set: + bad_edges = set() + for shift, delta_chroms in self.shift_to_delta.items(): + params = self.delta_params[shift] + + spread = params.sdev * 2 + lo = params.mean - spread + hi = params.mean + spread + + + bad = False + if self.is_composite(shift): + try: + comp_mean, comp_sdev = self.compose_shift(shift) + maybe_bad = not (comp_mean - (comp_sdev * 1.2) < params.mean < comp_mean + (comp_sdev * 1.2)) + if maybe_bad and params.size < 3: + bad = True + except KeyError: + # We don't have a component edge to support this composite edge, so we don't + # have enough information in the training data, so we're unable QC these edges. + # This is different from when we have a singular observation of any component, + # which may be a logical failure here. + # logger.debug(""Missing component key %r"", err) + pass + + if bad: + for delta_chrom, edge_key in delta_chroms: + bad_edges.add(edge_key) + else: + for delta_chrom, edge_key in delta_chroms: + if delta_chrom.apex_time < lo or delta_chrom.apex_time > hi: + bad_edges.add(edge_key) + pruned = [] + for e in bad_edges: + pruned.extend(self.edges.pop(e)) + return pruned + + def select_edges(self): + edges = [] + for es in self.edges.values(): + edges.extend(es) + return edges + + +class RelativeShiftFactorElutionTimeFitter(AbundanceWeightedPeptideFactorElutionTimeFitter): + def __init__(self, chromatograms, factors=None, scale=1, transform=None, width_range=None, + regularize=False, max_distance=3, key_cache=None, distance_cache=None, + delta_cache=None): + if key_cache is None: + key_cache = {} + if distance_cache is None: + distance_cache = DistanceCache(composition_distance) + if delta_cache is None: + delta_cache = GlycanCompositionDeltaCache() + self.key_cache = key_cache + self.distance_cache = distance_cache + self.delta_cache = delta_cache + self.max_distance = max_distance + if chromatograms: + recs, groups = self.build_deltas(chromatograms, max_distance=max_distance) + else: + recs = [] + groups = GlycoformAggregator() + self.groups = groups + self.peptide_offsets = {} + super(RelativeShiftFactorElutionTimeFitter, self).__init__( + recs, factors, scale=scale, transform=transform, + width_range=width_range, regularize=regularize) + + def drop_chromatograms(self): + super(RelativeShiftFactorElutionTimeFitter, self).drop_chromatograms() + self.groups = None + return self + + def __getstate__(self): + state = super(RelativeShiftFactorElutionTimeFitter, self).__getstate__() + state['groups'] = self.groups + state['peptide_offsets'] = self.peptide_offsets + state['max_distance'] = self.max_distance + return state + + def __setstate__(self, state): + super(RelativeShiftFactorElutionTimeFitter, self).__setstate__(state) + self.groups = state['groups'] + self.peptide_offsets = state['peptide_offsets'] + self.max_distance = state['max_distance'] + self.key_cache = dict() + + def build_deltas(self, chromatograms, max_distance): + recs = [] + groups = GlycoformAggregator(chromatograms) + for key, group in groups.by_peptide.items(): + base_time = 0.0 + for a, b in itertools.permutations(group, 2): + distance = self.distance_cache( + a.glycan_composition, b.glycan_composition)[0] + if distance > max_distance or distance == 0: + continue + delta_comp = self.delta_cache(a.glycan_composition, b.glycan_composition) + structure = (key + str(delta_comp)) + if structure in self.key_cache: + structure = self.key_cache[structure] + else: + structure_key = structure + structure = FragmentCachingGlycopeptide(structure) + self.key_cache[structure_key] = structure + rec = GlycopeptideChromatogramProxy( + a.weighted_neutral_mass, base_time + a.apex_time - b.apex_time, + np.sqrt(a.total_signal * b.total_signal), + delta_comp, structure=structure, + weight=float(distance) ** 4 + (a.weight + b.weight), + peptide_key=a.peptide_key + ) + recs.append(rec) + if len(recs) == 0: + raise ValueError(""No deltas constructed"") + return recs, groups + + def _get_chromatograms(self): + return list(self.groups) + + def fit(self, *args, **kwargs): + super(RelativeShiftFactorElutionTimeFitter, self).fit(*args, **kwargs) + for key, group in self.groups.by_peptide.items(): + remainders = [] + weights = [] + for case in group: + offset = self.predict(case) + remainders.append(case.apex_time - offset) + weights.append(case.total_signal) + remainders = np.array(remainders) + self.peptide_offsets[key] = np.average(remainders, weights=weights) + return self + + def predict(self, chromatogram): + time = super(RelativeShiftFactorElutionTimeFitter, + self).predict(chromatogram) + key = self.get_peptide_key(chromatogram) + time += self.peptide_offsets.get(key, 0) + return time + + def predict_interval(self, chromatogram, *args, **kwargs): + iv = super(RelativeShiftFactorElutionTimeFitter, + self).predict_interval(chromatogram) + key = self.get_peptide_key(chromatogram) + iv += self.peptide_offsets.get(key, 0) + return iv + + def calibrate_prediction_interval(self, chromatograms=None, alpha=0.05): + return super(RelativeShiftFactorElutionTimeFitter, self).calibrate_prediction_interval(list(self.groups), alpha) + + def _update_model_time_range(self): + if len(self.groups) == 0: + self.start = 0.0 + self.end = 0.0 + self.centroid = 0.0 + else: + apexes = [] + weights = [] + for case in self.groups: + t = case.apex_time + w = case.total_signal + apexes.append(t) + weights.append(w) + apexes = np.array(apexes) + self.start = apexes.min() + self.end = apexes.max() + self.centroid = apexes.dot(weights) / np.sum(weights) + + # This omission is by design, it prevents peptide backbones that did + # not have a pair from being considered. + # + # def has_peptide(self, peptide): + # if not isinstance(peptide, str): + # peptide = self.get_peptide_key(peptide) + # return peptide in self.peptide_offsets + + +class LocalOutlierFilteringRelativeShiftFactorElutionTimeFitter(RelativeShiftFactorElutionTimeFitter): + def build_deltas(self, chromatograms, max_distance): + graph = LocalShiftGraph( + chromatograms, max_distance, + key_cache=self.key_cache, + distance_cache=self.distance_cache) + graph.process_edges() + groups = graph.groups + recs = graph.select_edges() + if len(recs) == 0: + raise ValueError(""No deltas constructed"") + return recs, groups + + +def mask_in(full_set: List[GlycopeptideChromatogramProxy], incoming: List[GlycopeptideChromatogramProxy]) -> List[GlycopeptideChromatogramProxy]: + """""" + Replace the entries in ``full_set`` with the entries in ``incoming`` if their tags match, + otherwise use the original value. + + Returns + ------- + List[GlycopeptideChromatogramProxy] + """""" + incoming_map = {i.tag: i for i in incoming} + out = [] + for chrom in full_set: + if chrom.tag in incoming_map: + out.append(incoming_map[chrom.tag]) + else: + out.append(chrom) + return out + + +# The self paramter is included as this function is later bound to a class directly +# so it gets made into a method +def model_type_dispatch(self, chromatogams: List[GlycopeptideChromatogramProxy], + factors: Optional[List[str]]=None, + scale: float=1, + transform=None, + width_range: Optional[IntervalRange]=None, + regularize: bool=False, + key_cache=None, + distance_cache: Optional[DistanceCache]=None, + delta_cache: Optional[GlycanCompositionDeltaCache]=None): + try: + model = RelativeShiftFactorElutionTimeFitter( + chromatogams, factors, scale, transform, width_range, regularize, + max_distance=3, key_cache=key_cache, distance_cache=distance_cache, + delta_cache=delta_cache) + if model.data.shape[0] == 0: + raise ValueError(""No relative data points"") + return model + except (ValueError, AssertionError): + model = AbundanceWeightedPeptideFactorElutionTimeFitter( + chromatogams, factors, scale, transform, width_range, regularize) + return model + + +# The self paramter is included as this function is later bound to a class directly +# so it gets made into a method +def model_type_dispatch_outlier_remove(self, chromatogams: List[GlycopeptideChromatogramProxy], + factors: Optional[List[str]]=None, + scale: float=1, + transform=None, + width_range: Optional[IntervalRange]=None, + regularize: bool=False, + key_cache=None, + distance_cache: Optional[DistanceCache]=None, + delta_cache: Optional[GlycanCompositionDeltaCache]=None): + try: + model = LocalOutlierFilteringRelativeShiftFactorElutionTimeFitter( + chromatogams, factors, scale, transform, width_range, regularize, + max_distance=3, key_cache=key_cache, distance_cache=distance_cache, + delta_cache=delta_cache) + if model.data.shape[0] == 0: + raise ValueError(""No relative data points"") + return model + except (ValueError, AssertionError): + model = AbundanceWeightedPeptideFactorElutionTimeFitter( + chromatogams, factors, scale, transform, width_range, regularize) + return model + + +class GlycopeptideElutionTimeModelBuildingPipeline(TaskBase): + '''A local regression-based ensemble of overlapping + retention time models. + ''' + + model_type = model_type_dispatch_outlier_remove + + aggregate: GlycoformAggregator + calibration_alpha: float + _current_model: ModelEnsemble + model_history: List[ModelEnsemble] + n_workers: int + + revised_tags: Set[int] + revision_history: List[List[GlycopeptideChromatogramProxy]] + revision_rules: RevisionRuleList + revision_validator: RevisionValidatorBase + + valid_glycans: Optional[Set[HashableGlycanComposition]] + initial_filter: Callable[..., bool] + + key_cache: Dict + distance_cache: DistanceCache + delta_cache: GlycanCompositionDeltaCache + + def __init__(self, aggregate, calibration_alpha=0.001, valid_glycans=None, + initial_filter=unmodified_modified_predicate, revision_validator=None, + n_workers=None): + if n_workers is None: + n_workers = cpu_count() + if revision_validator is None: + revision_validator = PeptideYUtilizationPreservingRevisionValidator() + self.aggregate = aggregate + self.calibration_alpha = calibration_alpha + self.n_workers = n_workers + self._current_model = None + self.model_history = [] + self.revision_history = [] + self.revised_tags = set() + # The indexed variant doesn't work well without expanding the space to also + # include revision rules and requires that the chromatogram proxies need to + # have special copy logic + self.valid_glycans = ValidatedGlycome(valid_glycans) if valid_glycans else None + self.initial_filter = initial_filter + self.key_cache = {} + self.revision_validator = revision_validator + + self.distance_cache = DistanceCache(composition_distance) + self.delta_cache = GlycanCompositionDeltaCache() + self.revision_rules = self._default_rules() + self._check_rules() + + def _default_rules(self): + return RevisionRuleList([ + AmmoniumMaskedRule, + AmmoniumUnmaskedRule, + AmmoniumMaskedNeuGcRule, + AmmoniumUnmaskedNeuGcRule, + IsotopeRule, + IsotopeRule2, + IsotopeRuleNeuGc, + HexNAc2NeuAc2ToHex6AmmoniumRule, + HexNAc2NeuAc2ToHex6Deoxy, + HexNAc2Fuc1NeuAc2ToHex7, + SulfateToPhosphateRule, + PhosphateToSulfateRule, + Sulfate1HexNAc2ToHex3Rule, + Hex3ToSulfate1HexNAc2Rule, + Phosphate1HexNAc2ToHex3Rule, + Hex3ToPhosphate1HexNAc2Rule, + ]).with_cache() + + def _check_rules(self): + if self.valid_glycans: + fucose = 0 + dhex = 0 + for gc in self.valid_glycans: + fucose += gc['Fuc'] + dhex += gc['dHex'] + if fucose == 0 and dhex > 0: + self.revision_rules = self.revision_rules.modify_rules({libreviser.fuc: libreviser.dhex}) + elif dhex == 0 and fucose > 0: + # no-op, we don't need to make changes to the current + # rules. + pass + else: + self.log(""No Fuc or d-Hex detected in valid glycans, no rule modifications inferred"") + n_rules_before = len(self.revision_rules) + self.revision_rules = self.revision_rules.filter_defined(self.valid_glycans) + n_rules_after = len(self.revision_rules) + self.log(f""Using {n_rules_after} revision rules ({n_rules_before - n_rules_after} removed)."") + + @property + def current_model(self): + return self._current_model + + @current_model.setter + def current_model(self, value): + if self._current_model is not None and value is not self._current_model: + pass + # self.model_history.append(self._current_model) + self._current_model = value + + def fit_first_model(self, regularize=False): + model = self.fit_model( + self.aggregate, + self.initial_filter, + regularize=regularize) + return model + + def fit_model(self, aggregate, predicate, regularize=False, resample=False): + builder = EnsembleBuilder(aggregate) + w = builder.estimate_width() + # If width changing over time is allowed, approximate narrow windows will inevitably produce + # skewed results. This is also true of the first and last set of windows, regardless, especially + # when sparse. + builder.partition(w) + model_type = partial( + self.model_type, + key_cache=self.key_cache, + distance_cache=self.distance_cache, + delta_cache=self.delta_cache) + builder.fit(predicate, model_type=model_type, + regularize=regularize, resample=resample, + n_workers=self.n_workers) + model = builder.merge() + model.calibrate_prediction_interval(alpha=self.calibration_alpha) + self.log(""... Calibrated Prediction Intervals: %0.3f-%0.3f"" % ( + model.width_range.lower, model.width_range.upper)) + return model + + def fit_model_with_revision(self, source, revision, regularize=False): + masked_in_all_recs = mask_in(source, revision) + aggregate = GlycoformAggregator(masked_in_all_recs) + tags = {t.tag for t in revision} + return self.fit_model(aggregate, lambda x: x.tag in tags, regularize=regularize) + + def make_reviser(self, model, chromatograms): + reviser = IntervalModelReviser( + model, self.revision_rules, + chromatograms, + valid_glycans=self.valid_glycans, + revision_validator=self.revision_validator) + return reviser + + def revise_with(self, model, chromatograms, delta=0.35, min_time_difference=None, verbose=True): + if min_time_difference is None: + min_time_difference = max(model.width_range.lower, 0.5) + + reviser = self.make_reviser(model, chromatograms) + reviser.evaluate() + revised = reviser.revise(0.2, delta, min_time_difference) + if verbose: + self.debug(""... Revising Observations"") + k = 0 + local_aggregate = GlycoformAggregator(chromatograms) + for new, old in zip(revised, chromatograms): + if new.structure != old.structure: + self.revised_tags.add(new.tag) + neighbor_count = len(local_aggregate[old]) + k += 1 + self.log( + ""...... %s: %0.2f %s (%0.2f) => %s (%0.2f) %0.2f/%0.2f with %d references"" % ( + new.tag, new.apex_time, + old.structure, model.predict(old), + new.glycan_composition, model.predict(new), + model.score_interval(old, alpha=0.01), + model.score_interval(new, alpha=0.01), + neighbor_count - 1, + ) + ) + self.debug(""... Updated %d assignments"" % (k, )) + return revised + + def compute_model_coverage(self, model, aggregate, tag=True): + coverages = [] + for i, chrom in enumerate(aggregate): + if tag: + chrom.annotations['tag'] = i + coverage = model.coverage_for(chrom) + + coverages.append(coverage) + return np.array(coverages) + + def subset_aggregate_by_coverage(self, chromatograms, coverages, threshold): + # This happens when there are *no* models that span this observation's + # time point. We force them to be included. + nans = np.isnan(coverages) + if nans.any(): + self.log(""Encountered %d missing observations"" % nans.sum()) + return np.array(list(chromatograms))[ + np.where((coverages >= threshold) | nans | np.isclose(coverages, threshold))[0] + ] + + def reweight(self, model, chromatograms, base_weight=0.2): + reweighted = [] + total = 0.0 + total_ignored = 0 + for rec in chromatograms: + rec = rec.copy() + s = w = model.score_interval(rec, 0.01) + if np.isnan(w): + s = w = 0 + total_ignored += w == 0 + rec.weight = w + 1e-6 + if np.isnan(rec.weight): + rec.weight = base_weight + reweighted.append(rec) + total += s + self.log(""... Total Score for %d chromatograms = %f (%d ignored)"" % + (len(chromatograms), total, total_ignored)) + return reweighted + + def make_groups_from(self, chromatograms): + return GlycoformAggregator(chromatograms).by_peptide.values() + + def find_uncovered_group_members(self, chromatograms, coverages, min_size=2, seen=None): + recs = [] + for chrom, cov in zip(chromatograms, coverages): + if seen and chrom.tag in seen: + continue + if not np.isclose(cov, 1.0) and len(self.aggregate[chrom]) > min_size: + recs.append(chrom) + return recs + + def validate_revisions(self, model, revisions, delta=0.35, min_time_difference=None): + originals = [] + for index, revision in revisions: + _rule, original = revision.revised_from + originals.append(original) + self.log(""... Validating revisions with final model"") + recalculated = self.revise_with( + model, originals, delta=delta, min_time_difference=min_time_difference, verbose=False) + + result = [] + for i, checked in enumerate(recalculated): + index, revision = revisions[i] + _rule, original = revision.revised_from + + checked_rt = model.predict(checked) + revision_rt = model.predict(revision) + checked_score = model.score_interval(checked, alpha=0.01) + revision_score = model.score_interval(revision, alpha=0.01) + + if abs(checked_rt - revision_rt) < min_time_difference: + continue + if abs(checked_score - revision_score) < delta: + continue + + if checked_score == revision_score == 0: + if abs(revision_rt - revision.apex_time) / abs(checked_rt - revision.apex_time) < 0.5: + continue + + if revision.glycan_composition != checked.glycan_composition: + self.log(""...... Rejected Revision: %s"" % (revision.structure, )) + self.log( + ""...... %s: %0.2f %s (%0.2f) => %s (%0.2f) %0.2f/%0.2f"" % ( + revision.tag, revision.apex_time, + revision.glycan_composition, model.predict(revision), + checked.glycan_composition, model.predict(checked), + model.score_interval(revision, alpha=0.01), + model.score_interval(checked, alpha=0.01), + ) + ) + if checked.glycan_composition == original.glycan_composition: + checked = original + + result.append((index, checked)) + return result + + def estimate_fdr(self, chromatograms, model, rules=None): + if rules is None: + rules = self.revision_rules + estimators = [] + for rule in rules: + self.log(""... Fitting decoys for %r"" % (rule, )) + estimator = RuleBasedFDREstimator( + rule, chromatograms, model, self.valid_glycans) + estimators.append(estimator) + + fitted_rules = RevisionRuleList(estimators) + self.log(""... Re-calibrating score from decoy residuals"") + try: + residual_fdr = ResidualFDREstimator(fitted_rules, model) + width = np.abs(residual_fdr.bounds_for_probability(0.95)).max() + if model.width_range: + delta = width - model.width_range.upper + max_delta = min(model.model_width / 2, delta) + if max_delta != delta: + self.log(""... Maximum padding interval exceeded (%0.3f > %0.3f)"" % ( + delta, max_delta)) + delta = max_delta + if delta > 0: + model.interval_padding = delta + self.log(""... Setting padding interval from residual FDR: %0.3f"" % + (delta, )) + for estimator in fitted_rules: + estimator.prepare() + t05 = estimator.score_for_fdr(0.05) + t01 = estimator.score_for_fdr(0.01) + self.log(""... FDR for {}"".format(estimator.rule)) + self.log(""...... 5%: {:0.2f} 1%: {:0.2f}"".format(t05, t01)) + self.log(""... Fitting relationship over time"") + estimator.fit_over_time() + except ValueError as err: + logger.error(""Unable to fit Residual FDR for RT Model: %s"", err, exc_info=False) + residual_fdr = None + model.residual_fdr = residual_fdr + return fitted_rules + + def extract_rules_used(self, chromatograms): + rules_used = set() + for record in chromatograms: + if record.revised_from: + rule, _ = record.revised_from + rules_used.add(rule) + return rules_used + + def run(self, k=10, base_weight=0.3, revision_threshold=0.35, final_round=True, regularize=True): + self.log(""Fitting first model..."") + # The first model is fit on those cases where we have both + # the Unmodified form as well as a modified form e.g. Ammonium-adducted + self.current_model = self.fit_first_model(regularize=regularize) + + all_records = list(self.aggregate) + + # Compute the coverage over all the chromatograms, where coverage is defined + # as the sum of the weights of all models that span that chromatogram which + # have a definition for that peptide divided by the sum of all model weights + # that span that chromatogram, regardless of whether they contain the peptide + coverages = self.compute_model_coverage( + self.current_model, all_records) + + # Select only those chromatograms that have 100% coverage (always defined in the model) + # but regardless of modification state. + covered_recs = self.subset_aggregate_by_coverage( + all_records, coverages, 1.0) + + # Attempt to revise chromatograms which are covered by the current model + revised_recs = self.revise_with( + self.current_model, covered_recs, 0.35, max(self.current_model.width_range.lower * 0.5, 0.5)) + + # Update the list of chromatogram records + all_records = mask_in(list(self.aggregate), revised_recs) + + # Fit a new model on the revised data + self.current_model = model = self.fit_model_with_revision( + all_records, revised_recs, regularize=regularize) + + delta_time_scale = 1.0 + minimum_delta = 2.0 + k_scale = 2.0 + + # Record how many chromatograms were kept last time + last_covered = covered_recs + for i in range(k): + self.log(""Iteration %d"" % i) + coverages = self.compute_model_coverage(model, all_records) + coverage_threshold = (1.0 - (i * 1.0 / (k_scale * k))) + covered_recs = self.subset_aggregate_by_coverage( + all_records, coverages, coverage_threshold) + + if len(covered_recs) == len(last_covered): + self.log(""No new observations added, skipping"") + continue + + new = {c.tag for c in covered_recs} - \ + {c.tag for c in last_covered} + last_covered = covered_recs + self.log(""... Covering %d chromatograms at threshold %0.2f"" % ( + len(covered_recs), coverage_threshold)) + self.debug(""... Added %d new tags"" % len(new)) + revised_recs = self.revise_with( + model, covered_recs, revision_threshold, + max(self.current_model.width_range.lower * delta_time_scale, minimum_delta)) + revised_recs = self.reweight(model, revised_recs, base_weight) + all_records = mask_in(all_records, revised_recs) + + self.current_model = model = self.fit_model_with_revision( + all_records, revised_recs, regularize=regularize) + + if final_round: + self.log(""Open Update Round"") + coverages = self.compute_model_coverage(model, all_records) + coverage_threshold = (1.0 - (i * 1.0 / (k_scale * k))) + covered_recs = self.subset_aggregate_by_coverage( + all_records, coverages, coverage_threshold) + + extra_recs = self.find_uncovered_group_members( + all_records, + coverages + ) + + self.debug(f""...... Found {len(covered_recs)} covered chromatograms"") + self.debug(f""...... Found {len(extra_recs)} additional chromatograms"") + + covered_recs = np.concatenate((covered_recs, extra_recs)) + covered_recs = self.reweight(model, covered_recs, base_weight=0.01) + + all_records = mask_in(all_records, covered_recs) + self.current_model = model = self.fit_model_with_revision( + all_records, covered_recs, regularize=regularize) + revised_recs = self.revise_with( + model, covered_recs, revision_threshold, + max(self.current_model.width_range.lower * delta_time_scale, minimum_delta)) + + all_records = mask_in(all_records, revised_recs) + + for i in range(k): + self.log(""Iteration %d"" % (i + k)) + coverages = self.compute_model_coverage(model, all_records) + coverage_threshold = (1.0 - (i * 1.0 / (k_scale * k))) + covered_recs = self.subset_aggregate_by_coverage( + all_records, coverages, coverage_threshold) + new = set() + if len(covered_recs) == len(last_covered): + self.log(""No new observations added, skipping"") + continue + else: + new = {c.tag for c in covered_recs} - \ + {c.tag for c in last_covered} + last_covered = covered_recs + self.log(""... Covering %d chromatograms at threshold %0.2f"" % ( + len(covered_recs), coverage_threshold)) + self.log(""... Added %d new tags"" % len(new)) + revised_recs = self.revise_with( + model, covered_recs, revision_threshold, + max(self.current_model.width_range.lower * delta_time_scale, minimum_delta)) + revised_recs = self.reweight(model, revised_recs, base_weight) + all_records = mask_in(all_records, revised_recs) + + self.current_model = model = self.fit_model_with_revision( + all_records, revised_recs, regularize=regularize) + + self.log(""Final Update Round"") + coverages = self.compute_model_coverage(model, all_records) + coverage_threshold = (1.0 - (i * 1.0 / (k_scale * k))) + covered_recs = self.subset_aggregate_by_coverage( + all_records, coverages, coverage_threshold) + + extra_recs = self.find_uncovered_group_members( + all_records, coverages) + + self.log(""... Added %d new tags"" % len(extra_recs)) + covered_recs = np.concatenate((covered_recs, extra_recs)) + covered_recs = self.reweight(model, covered_recs, base_weight=0.01) + + all_records = mask_in(all_records, covered_recs) + self.current_model = model = self.fit_model_with_revision( + all_records, covered_recs, regularize=regularize) + revised_recs = self.revise_with( + model, covered_recs, revision_threshold, + max(self.current_model.width_range.lower * delta_time_scale, minimum_delta)) + + all_records = mask_in(all_records, revised_recs) + + self.log(""Estimating summary statistics"") + model._compute_summary_statistics() + + try: + mean_error_from_interval = model.estimate_mean_error_from_interval() + except IndexError: + self.log(""Unable to fit final model"") + return None, all_records + + self.log(""... Adding padding mean interval error: %0.3f"" % (mean_error_from_interval, )) + model.interval_padding = mean_error_from_interval + self.log(""Last revision"") + revised_recs = self.revise_with( + model, revised_recs, revision_threshold, + max(self.current_model.width_range.lower * delta_time_scale, minimum_delta)) + all_records = mask_in(all_records, revised_recs) + + was_revised = [(i, record) for i, record in enumerate(all_records) if record.revised_from] + for i, record in self.validate_revisions(model, was_revised, revision_threshold, + max(self.current_model.width_range.lower * delta_time_scale, + minimum_delta)): + all_records[i] = record + rules_used = self.extract_rules_used(all_records) + self.log(""Estimating FDR for revision rules"") + model._summary_statistics['fdr_estimates'] = self.estimate_fdr(all_records, model, rules_used) + self.log(""Final Model Variance Explained: %0.3f"" % (model.R2(), )) + return model, all_records + + +ModelBuildingPipeline = GlycopeptideElutionTimeModelBuildingPipeline + + +class ElutionTimeModel(ScoringFeatureBase): + feature_type = 'elution_time' + + def __init__(self, fit=None, factors=None): + self.fit = fit + self.factors = factors + + def configure(self, analysis_data): + if self.fit is None: + matches = analysis_data['matches'] + fitter = AbundanceWeightedFactorElutionTimeFitter( + matches, self.factors) + fitter.fit() + self.fit = fitter + + def score(self, chromatogram, *args, **kwargs): + if self.fit is not None: + return self.fit.score(chromatogram) + else: + return 0.5 +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/elution_time_grouping/__init__.py",".py","1077","26","from .linear_regression import (weighted_linear_regression_fit, prediction_interval, ransac) + +from .structure import ( + ChromatogramProxy, GlycopeptideChromatogramProxy, + CommonGlycopeptide, _get_apex_time, GlycoformAggregator) + +from .model import ( + ElutionTimeFitter, AbundanceWeightedElutionTimeFitter, + FactorElutionTimeFitter, AbundanceWeightedFactorElutionTimeFitter, + PeptideFactorElutionTimeFitter, AbundanceWeightedPeptideFactorElutionTimeFitter, + ElutionTimeModel, ModelBuildingPipeline as GlycopeptideElutionTimeModelBuildingPipeline, + ModelEnsemble) + +from .reviser import ( + ModelReviser, IntervalModelReviser, PeptideYUtilizationPreservingRevisionValidator, + OxoniumIonRequiringUtilizationRevisionValidator, CompoundRevisionValidator, + RevisionRule, ValidatingRevisionRule, MassShiftRule) + +from .cross_run import ( + ReplicatedAbundanceWeightedPeptideFactorElutionTimeFitter, LinearRetentionTimeCorrector, +) + +from .recalibrator import (CalibrationPoint, RecalibratingPredictor) + +from .pipeline import GlycopeptideElutionTimeModeler +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/elution_time_grouping/cross_run.py",".py","9712","230","'''Extra logic for fitting a model across multiple LC-MS runs. +''' +from collections import defaultdict + +import numpy as np + +try: + from matplotlib import pyplot as plt +except ImportError: + pass + + +import glycopeptidepy + +from .model import AbundanceWeightedPeptideFactorElutionTimeFitter, make_counter +from .structure import CommonGlycopeptide +from .linear_regression import weighted_linear_regression_fit + + +class ReplicatedAbundanceWeightedPeptideFactorElutionTimeFitter(AbundanceWeightedPeptideFactorElutionTimeFitter): + def __init__(self, chromatograms, factors=None, scale=1, replicate_key_attr='analysis_name', + use_retention_time_normalization=False, reference_sample=None): + if replicate_key_attr is None: + replicate_key_attr = 'analysis_name' + if factors is None: + factors = ['Hex', 'HexNAc', 'Fuc', 'Neu5Ac'] + self.replicate_key_attr = replicate_key_attr + self.reference_sample = reference_sample + self._replicate_to_indicator = defaultdict(make_counter(0)) + self.use_retention_time_normalization = use_retention_time_normalization + self.run_normalizer = None + # Ensure that _replicate_to_indicator is properly initialized + # for obs in chromatograms: + # _ = self._replicate_to_indicator[self._get_replicate_key(obs)] + self.chromatograms = chromatograms + + index, samples = self._build_common_glycopeptides() + self.replicate_names = samples + if self.use_retention_time_normalization: + self.run_normalizer = LinearRetentionTimeCorrector(index, samples, self.reference_sample) + if self.reference_sample is None: + self.reference_sample = self.run_normalizer.reference_key + self.run_normalizer.fit() + else: + if self.reference_sample is None: + self.reference_sample = samples[0] + _ = self._replicate_to_indicator[self.reference_sample] + for sample_key in samples: + _ = self._replicate_to_indicator[sample_key] + super(ReplicatedAbundanceWeightedPeptideFactorElutionTimeFitter, self).__init__( + chromatograms, list(factors), scale) + + def reset_reference_sample(self, reference_sample): + self.reference_sample = reference_sample + self._replicate_to_indicator = defaultdict(make_counter(0)) + _ = self._replicate_to_indicator[self.reference_sample] + for sample_key in self.replicate_names: + _ = self._replicate_to_indicator[sample_key] + self.data = self._prepare_data_matrix(self.neutral_mass_array) + + def _get_apex_time(self, chromatogram): + value = super(ReplicatedAbundanceWeightedPeptideFactorElutionTimeFitter, + self)._get_apex_time(chromatogram) + if self.use_retention_time_normalization and self.run_normalizer is not None: + replicate_id = self._get_replicate_key(chromatogram) + value = self.run_normalizer.correct(value, replicate_id) + return value + + def _build_common_glycopeptides(self): + index = defaultdict(dict) + for case in self.chromatograms: + index[str(case.structure)][self._get_replicate_key(case)] = case + result = [CommonGlycopeptide(glycopeptidepy.parse(k), v) for k, v in index.items()] + samples = set() + for case in result: + samples.update(case.keys()) + return result, sorted(samples) + + def _get_replicate_key(self, chromatogram): + if isinstance(self.replicate_key_attr, (str, unicode)): + return getattr(chromatogram, self.replicate_key_attr) + elif callable(self.replicate_key_attr): + return self.replicate_key_attr(chromatogram) + + def _prepare_data_matrix(self, mass_array): + design_matrix = super( + ReplicatedAbundanceWeightedPeptideFactorElutionTimeFitter, + self)._prepare_data_matrix(mass_array) + p = len(self._replicate_to_indicator) + n = len(self.chromatograms) + replicate_matrix = np.zeros((p, n)) + indicator = dict(self._replicate_to_indicator) + for i, c in enumerate(self.chromatograms): + try: + # Here, if one of the levels is not omitted, the matrix will be linearly dependent. + # So drop the 0th factor level. + j = indicator[self._get_replicate_key(c)] + if j != 0: + replicate_matrix[j, i] = 1 + except KeyError: + pass + return np.hstack((replicate_matrix.T, design_matrix)) + + def feature_names(self): + names = [] + replicates = [None] * len(self._replicate_to_indicator) + for key, value in self._replicate_to_indicator.items(): + replicates[value] = key + names.extend(replicates) + peptides = [None] * len(self._peptide_to_indicator) + for key, value in self._peptide_to_indicator.items(): + peptides[value] = key + names.extend(peptides) + names.extend(self.factors) + return names + + def _prepare_data_vector(self, chromatogram, no_intercept=False): + data_vector = super( + ReplicatedAbundanceWeightedPeptideFactorElutionTimeFitter, + self)._prepare_data_vector(chromatogram, no_intercept=no_intercept) + p = len(self._replicate_to_indicator) + replicates = [0 for _ in range(p)] + indicator = dict(self._replicate_to_indicator) + if not no_intercept: + try: + # Here, if one of the levels is not omitted, the matrix will be linearly dependent. + # So drop the 0th factor level. + j = self._get_replicate_key(chromatogram) + if j != 0: + replicates[indicator[j]] = 1 + except KeyError: + import warnings + warnings.warn( + ""Replicate Key %s not part of the model."" % (j, )) + return np.hstack((replicates, data_vector)) + + +class LinearRetentionTimeCorrector(object): + def __init__(self, common_observations, sample_keys, reference_key=None): + self.common_observations = common_observations + self.sample_keys = sample_keys + self.reference_key = reference_key + self.sample_to_correction_parameters = dict() + self.sample_to_vector = dict() + if self.reference_key is None: + self.reference_key = self.select_reference() + + def build_sample_distance_matrix(self): + n = len(self.sample_keys) + distance_matrix = np.zeros((n, n)) + for i in range(n): + ivec = self._make_vector_for(self.sample_keys[i]) + for j in range(i + 1, n): + jvec = self._make_vector_for(self.sample_keys[j]) + wls = self._fit_correction(jvec, ivec) + distance = wls.R2 + distance_matrix[i, j] = distance + distance_matrix[j, i] = distance + return distance_matrix + + def select_reference(self): + distance_matrix = self.build_sample_distance_matrix() + return self.sample_keys[np.argmin(distance_matrix.sum(axis=0))] + + def _make_vector_for(self, sample): + if sample in self.sample_to_vector: + return self.sample_to_vector[sample] + result = [] + for obs in self.common_observations: + try: + result.append(obs[sample].apex_time) + except KeyError: + result.append(np.nan) + result = self.sample_to_vector[sample] = np.array(result) + return result + + def _fit_correction(self, a, b): + delta = b - a + mask = ~(np.isnan(delta)) + wls_fit = weighted_linear_regression_fit( + b[mask], delta[mask], prepare=True) + return wls_fit + + def fit_correction_for(self, sample_key): + sample = self._make_vector_for(sample_key) + reference = self._make_vector_for(self.reference_key) + wls_fit = self._fit_correction(sample, reference) + self.sample_to_correction_parameters[sample_key] = wls_fit + return wls_fit + + def fit(self): + for sample_key in self.sample_keys: + if sample_key == self.reference_key: + continue + self.fit_correction_for(sample_key) + + def correct(self, x, sample_key): + return x - self._correction_factor_for(x, sample_key) + + def _correction_factor_for(self, x, sample_key): + if sample_key == self.reference_key: + return 0 + fit = self.sample_to_correction_parameters[sample_key] + return (fit.parameters[1] * x + fit.parameters[0]) + + def plot(self, ax=None): + if ax is None: + _fig, ax = plt.subplots(1) + X = self._make_vector_for(self.reference_key) + mask = ~np.isnan(X) + X = X[mask] + Xhat = np.arange(X.min(), X.max()) + for sample_key in sorted(self.sample_keys): + if sample_key == self.reference_key: + ax.scatter(X, np.zeros_like(X), label=""%s Reference"" % (sample_key, )) + else: + fit = self.sample_to_correction_parameters[sample_key] + ax.scatter(fit.data[0][:, 1], fit.data[1], + label=r'%s %0.2fX + %0.2f ($R^2$=%0.2f)' % ( + sample_key, fit.parameters[1], fit.parameters[0], fit.R2)) + Yhat = Xhat * fit.parameters[1] + fit.parameters[0] + ax.plot(Xhat, Yhat, linestyle='--') + legend = ax.legend(fontsize=6) + frame = legend.get_frame() + frame.set_linewidth(0.5) + frame.set_alpha(0.5) + ax.set_xlabel(""Time"") + ax.set_ylabel(r""$\delta$ Time"") + return ax +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/elution_time_grouping/structure.py",".py","20916","640","import csv + +import io +from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Mapping +from glycresoft.structure.structure_loader import GlycanCompositionDeltaCache + +import numpy as np +from scipy.ndimage import gaussian_filter1d, median_filter + +try: + from matplotlib import pyplot as plt +except ImportError: + pass + +from glycopeptidepy import PeptideSequence + +from glypy.structure.glycan_composition import HashableGlycanComposition, FrozenGlycanComposition + +from glycresoft.structure import FragmentCachingGlycopeptide +from ms_deisotope.peak_dependency_network.intervals import SpanningMixin, IntervalTreeNode + +from glycresoft.chromatogram_tree.utils import ArithmeticMapping +from glycresoft.chromatogram_tree.mass_shift import MassShiftBase, Unmodified +from glycresoft.chromatogram_tree.chromatogram import ChromatogramInterface + +from glycresoft.tandem.spectrum_match import SpectrumMatchBase + + +def _try_parse(value): + if isinstance(value, (int, float)): + return value + try: + return int(value) + except (ValueError, TypeError): + try: + return float(value) + except (ValueError, TypeError): + return value + + +def _get_apex_time(chromatogram): + try: + if hasattr(chromatogram, ""as_arrays""): + x, y = chromatogram.as_arrays() + else: + x, y = chromatogram.get_chromatogram().as_arrays() + y = gaussian_filter1d(y, 1) + return x[np.argmax(y)] + except (AttributeError, TypeError): + return chromatogram.apex_time + + +class ChromatogramProxy(object): + + weighted_neutral_mass: float + apex_time: float + total_signal: float + glycan_composition: HashableGlycanComposition + source: Any + mass_shifts: List[MassShiftBase] + weight: float + kwargs: Dict[str, Any] + + def __init__(self, weighted_neutral_mass, apex_time, total_signal, glycan_composition, source=None, + mass_shifts=None, weight=1.0, **kwargs): + if mass_shifts is None: + mass_shifts = [Unmodified] + self.weighted_neutral_mass = weighted_neutral_mass + self.apex_time = apex_time + self.total_signal = total_signal + self.glycan_composition = glycan_composition + self.source = source + self.mass_shifts = mass_shifts + self.weight = weight + self.kwargs = kwargs + + @property + def revised_from(self): + return self.kwargs.get(""revised_from"") + + @revised_from.setter + def revised_from(self, value): + self.kwargs['revised_from'] = value + + @property + def annotations(self): + return self.kwargs + + @property + def tag(self) -> Optional[int]: + return self.kwargs.get('tag') + + @tag.setter + def tag(self, value: int): + self.kwargs['tag'] = value + + def __repr__(self): + return ""%s(%f, %f, %f, %s, %s)"" % ( + self.__class__.__name__, + self.weighted_neutral_mass, self.apex_time, self.total_signal, + self.glycan_composition, self.kwargs) + + def pack(self): + self.source = None + + @classmethod + def from_obj(cls, obj, **kwargs): + if isinstance(obj, ChromatogramInterface): + return cls.from_chromatogram(obj) + elif isinstance(obj, cls): + return obj.__class__.from_chromatogram(obj, **kwargs) + elif isinstance(obj, SpectrumMatchBase): + return cls.from_spectrum_match(obj, **kwargs) + else: + return cls.from_chromatogram(obj) + + @classmethod + def from_chromatogram(cls, obj, **kwargs): + try: + apex_time = _get_apex_time(obj) + except (AttributeError, ValueError, TypeError): + apex_time = obj.apex_time + mass_shifts = getattr(obj, 'mass_shifts') + kwargs.setdefault('mass_shifts', mass_shifts) + inst = cls( + obj.weighted_neutral_mass, apex_time, obj.total_signal, + HashableGlycanComposition(obj.glycan_composition), obj, **kwargs) + return inst + + @classmethod + def from_spectrum_match(cls, spectrum_match, source=None, **kwargs): + if source is None: + source = spectrum_match + return cls( + spectrum_match.scan.precursor_information.neutral_mass, spectrum_match.scan.scan_time, 0.0, + spectrum_match.target.glycan_composition, source, [spectrum_match.mass_shift], **kwargs) + + def get_chromatogram(self): + return self.source.get_chromatogram() + + def _to_csv(self): + d = self._prepare_state() + d['mass_shifts'] = ';'.join(m.name for m in d['mass_shifts']) + return d + + def _prepare_state(self): + d = { + ""weighted_neutral_mass"": self.weighted_neutral_mass, + ""apex_time"": self.apex_time, + ""total_signal"": self.total_signal, + ""glycan_composition"": self.glycan_composition, + ""weight"": float(self.weight), + ""mass_shifts"": [m for m in self.mass_shifts], + } + d.update(self.kwargs) + return d + + @classmethod + def _from_state(cls, state): + new = cls.__new__(cls) + new.__setstate__(state) + return new + + def copy(self): + dup = self._from_state(self._prepare_state()) + dup.source = self.source + return dup + + def __eq__(self, other: 'ChromatogramProxy'): + if other is None: + return False + if self.glycan_composition != other.glycan_composition: + return False + if not np.isclose(self.apex_time, other.apex_time): + return False + if not np.isclose(self.total_signal, other.total_signal): + return False + if self.mass_shifts != other.mass_shifts: + return False + if not np.isclose(self.weighted_neutral_mass, other.weighted_neutral_mass): + return False + return True + + def __ne__(self, other: 'ChromatogramProxy'): + return not self == other + + def __hash__(self): + return hash(self.glycan_composition) + + def __getstate__(self): + state = self._prepare_state() + state['glycan_composition'] = str(state['glycan_composition']) + state['weight'] = self.weight + return state + + def __setstate__(self, state): + state = dict(state) + self.glycan_composition = state.pop(""glycan_composition"", None) + if self.glycan_composition is not None: + if isinstance(self.glycan_composition, HashableGlycanComposition): + pass + else: + self.glycan_composition = HashableGlycanComposition.parse(str(self.glycan_composition)) + self.apex_time = state.pop(""apex_time"", None) + self.total_signal = state.pop(""total_signal"", None) + self.weighted_neutral_mass = state.pop(""weighted_neutral_mass"", None) + self.weight = state.pop('weight', 1.0) + self.source = None + self.mass_shifts = state.pop(""mass_shifts"", [Unmodified]) + self.kwargs = state + + def __getattr__(self, attr): + try: + return self.annotations[attr] + except KeyError: + raise AttributeError(attr) + + @classmethod + def _csv_keys(cls, keys): + return ['glycan_composition', 'apex_time', 'total_signal', 'weighted_neutral_mass', ] + \ + sorted(set(keys) - {'glycan_composition', 'apex_time', + 'total_signal', 'weighted_neutral_mass', }) + + @classmethod + def to_csv(cls, instances: Iterable, fh: io.TextIOBase): + cases = [c._to_csv() for c in instances] + keys = cls._csv_keys(cases[0].keys()) + writer = csv.DictWriter(fh, fieldnames=keys) + writer.writeheader() + writer.writerows(cases) + + @classmethod + def _from_csv(cls, row): + mass = float(row.pop(""weighted_neutral_mass"")) + apex_time = float(row.pop(""apex_time"")) + total_signal = float(row.pop(""total_signal"")) + gc = HashableGlycanComposition.parse(row.pop(""glycan_composition"")) + kwargs = {k: _try_parse(v) for k, v in row.items()} + return cls(mass, apex_time, total_signal, gc, **kwargs) + + @classmethod + def from_csv(cls, fh: io.TextIOBase): + cases = [] + reader = csv.DictReader(fh) + + for row in reader: + cases.append(cls._from_csv(row)) + return cases + + def update_glycan_composition(self, glycan_composition: HashableGlycanComposition) -> 'ChromatogramProxy': + self.glycan_composition = glycan_composition + + def shift_glycan_composition(self, delta: HashableGlycanComposition): + inst = self.copy() + if isinstance(self.glycan_composition, HashableGlycanComposition): + new_gc = self.glycan_composition + delta + else: + new_gc = HashableGlycanComposition(self.glycan_composition) + delta + inst.update_glycan_composition(new_gc) + return inst + + +class GlycopeptideChromatogramProxy(ChromatogramProxy): + _structure = None + + @classmethod + def _csv_keys(cls, keys): + return ['structure', 'glycan_composition', 'apex_time', + 'total_signal', 'weighted_neutral_mass'] + \ + sorted(set(keys) - {'structure', 'glycan_composition', + 'apex_time', 'total_signal', 'weighted_neutral_mass'}) + + @property + def peptide_key(self) -> str: + if ""peptide_key"" in self.kwargs: + return self.kwargs[""peptide_key""] + structure = self.structure + if isinstance(structure, str): + peptide = str(PeptideSequence(structure).deglycosylate()) + else: + peptide = str(structure.clone().deglycosylate()) + self.kwargs[""peptide_key""] = peptide + return peptide + + @property + def structure(self) -> FragmentCachingGlycopeptide: + if self._structure is None: + self._structure = FragmentCachingGlycopeptide( + str(self.kwargs[""structure""])) + return self._structure + + @structure.setter + def structure(self, value: FragmentCachingGlycopeptide): + self._structure = value + self.kwargs['structure'] = str(value) + if value and self.glycan_composition != value.glycan_composition: + self.glycan_composition = HashableGlycanComposition( + value.glycan_composition) + + @classmethod + def from_chromatogram(cls, obj, **kwargs): + gp = FragmentCachingGlycopeptide(str(obj.structure)) + result = super(GlycopeptideChromatogramProxy, cls).from_chromatogram( + obj, structure=gp, **kwargs) + _key = result.peptide_key + return result + + @classmethod + def from_spectrum_match(cls, spectrum_match, source=None, **kwargs): + if source is None: + source = spectrum_match + gp = FragmentCachingGlycopeptide(str(spectrum_match.target)) + return cls( + spectrum_match.scan.precursor_information.neutral_mass, spectrum_match.scan.scan_time, 0.0, + spectrum_match.target.glycan_composition, source, [spectrum_match.mass_shift], structure=gp, **kwargs) + + def shift_glycan_composition(self, delta): + inst = super(GlycopeptideChromatogramProxy, + self).shift_glycan_composition(delta) + return inst + + def update_glycan_composition(self, glycan_composition: HashableGlycanComposition) -> 'GlycopeptideChromatogramProxy': + original_structure = str(self.structure) + super().update_glycan_composition(glycan_composition) + structure = self.structure.clone() + structure.glycan = self.glycan_composition + self.structure = structure + self.kwargs['original_structure'] = original_structure + + def __eq__(self, other: 'GlycopeptideChromatogramProxy'): + result = super().__eq__(other) + if not result: + return result + return self.structure == other.structure + + def __hash__(self): + return hash(self.structure) + + +class CommonGlycopeptide(object): + def __init__(self, structure, mapping): + self.mapping = mapping + self.structure = structure + + def __getitem__(self, key): + return self.mapping[key] + + def __setitem__(self, key, value): + self.mapping[key] = value + + def __delitem__(self, key): + del self.mapping[key] + + def keys(self): + return self.mapping.keys() + + def __iter__(self): + return iter(self.mapping) + + def __len__(self): + return len(self.mapping) + + @property + def glycan_composition(self): + return self.structure.glycan_composition + + @property + def apex_times(self): + return ArithmeticMapping({k: v.apex_time for k, v in self.mapping.items()}) + + @property + def total_signals(self): + return ArithmeticMapping({k: v.total_signal for k, v in self.mapping.items()}) + + def __repr__(self): + template = ""{self.__class__.__name__}({self.structure!s}, {count} observations)"" + count = len(self.mapping) + return template.format(self=self, count=count) + + +class GlycoformAggregator(Mapping): + _interval_tree: IntervalTreeNode + by_peptide: Dict[str, 'GlycoformGroup'] + factors: Dict[str, float] + + def __init__(self, glycoforms=None, *args, **kwargs): + self.by_peptide = dict() + self.factors = None + self._interval_tree = None + if glycoforms is not None: + self.gather(glycoforms) + + def _get_peptide_key(self, chromatogram): + if isinstance(chromatogram, GlycopeptideChromatogramProxy): + return chromatogram.peptide_key + return str(PeptideSequence(str(chromatogram.structure)).deglycosylate()) + + def gather(self, iterable: Iterable[GlycopeptideChromatogramProxy]): + for rec in iterable: + key = self._get_peptide_key(rec) + try: + group = self.by_peptide[key] + except KeyError: + group = self.by_peptide[key] = GlycoformGroup([], key) + group.append(rec) + self._reindex() + return self + + def _reindex(self): + self.factors = self._infer_factors(self.glycoforms()) + self._interval_tree = IntervalTreeNode.build(self.values()) + return self + + def overlaps(self, start: float, end: float) -> List[GlycopeptideChromatogramProxy]: + groups = self._interval_tree.overlaps(start, end) + out = [] + for group in groups: + out.extend(group.overlaps(start, end)) + return out + + @property + def start_time(self): + return min(v.start_time for v in self.values()) + + @property + def end_time(self): + return max(v.end_time for v in self.values()) + + def __getitem__(self, key) -> 'GlycoformGroup': + if not isinstance(key, str): + key = self._get_peptide_key(key) + return self.by_peptide[key] + + def __setitem__(self, key, value: 'GlycoformGroup'): + if not isinstance(key, str): + key = self._get_peptide_key(key) + self.by_peptide[key] = value + + def __contains__(self, key) -> bool: + if not isinstance(key, str): + key = self._get_peptide_key(key) + return key in self.by_peptide + + def keys(self): + return (self.by_peptide).keys() + + def __iter__(self): + return self.glycoforms() + + def values(self): + return self.by_peptide.values() + + def items(self): + return self.by_peptide.items() + + def __len__(self): + return len(self.by_peptide) + + def has_relative_pairs(self) -> bool: + return any(len(v) > 1 for k, v in self.by_peptide.items()) + + def _deltas_for(self, monosaccharide: str, include_pairs: bool = False): + deltas = [] + pairs = [] + for _backbone, cases in self.by_peptide.items(): + for target in cases: + gc = FrozenGlycanComposition.parse( + str(target.glycan_composition)) + gc[monosaccharide] += 1 + for case in cases: + if case.glycan_composition == gc: + deltas.append(case.apex_time - target.apex_time) + if include_pairs: + pairs.append((case, target, deltas[-1])) + deltas = np.array(deltas) + if include_pairs: + return deltas, pairs + return deltas + + def _infer_factors(self, chromatograms: Iterable[GlycopeptideChromatogramProxy]) -> List[str]: + keys = set() + for record in chromatograms: + keys.update(record.glycan_composition) + keys = sorted(map(str, keys)) + return keys + + def deltas(self, factors: Iterable[str] = None, include_pairs: bool = False): + if factors is None: + factors = self.factors + return {f: self._deltas_for(f, include_pairs=include_pairs) for f in factors} + + def glycoforms(self) -> Iterator[GlycopeptideChromatogramProxy]: + for group in self.values(): + for member in group: + yield member + + def tag(self): + i = 0 + for member in self: + member.tag = i + i += 1 + return self + + def get_tag(self, tag: int) -> GlycopeptideChromatogramProxy: + for x in self: + if x.tag == tag: + return x + raise KeyError(tag) + + def has_tag(self, tag: int) -> bool: + for x in self: + if x.tag == tag: + return True + return False + + +class GlycoformGroup(Sequence[GlycopeptideChromatogramProxy], SpanningMixin): + members: List[GlycopeptideChromatogramProxy] + group_id: str + start: float + end: float + base_time: Optional[float] + + def __init__(self, members, group_id): + self.members = list(members) + self.group_id = group_id + self.start_time = 0 + self.end_time = 0 + self.base_time = None + + @property + def start_time(self): + return self.start + + @start_time.setter + def start_time(self, value): + self.start = value + + @property + def end_time(self): + return self.end + + @end_time.setter + def end_time(self, value): + self.end = value + + def overlaps(self, start: float, end: float): + return [m for m in self if start <= m.apex_time <= end] + + def _update(self): + start_time = float('inf') + end_time = 0.0 + for member in self.members: + if member.apex_time < start_time: + start_time = member.apex_time + if member.apex_time > end_time: + end_time = member.apex_time + self.start_time = start_time + self.end_time = end_time + + def __len__(self): + return len(self.members) + + def __getitem__(self, i): + return self.members[i] + + def append(self, glycoform: GlycopeptideChromatogramProxy): + self.members.append(glycoform) + self._update() + + def extend(self, glycoforms: Iterable[GlycopeptideChromatogramProxy]): + self.members.extend(glycoforms) + self._update() + + def __repr__(self): + return ""{self.__class__.__name__}({self.members!r}, {self.group_id!r})"".format(self=self) + + +class DeltaOverTimeFilter(object): + def __init__(self, key, delta, time): + self.key = key + self.delta = np.array(delta) + self.time = np.array(time) + self.delta = self.gap_fill() + self.smoothed = self.smooth() + + def smooth(self): + return median_filter(self.delta, size=5, mode='nearest') + + def __array__(self): + return self.smoothed + + def __getitem__(self, i): + return self.smoothed[i] + + def __len__(self): + return len(self.time) + + def gap_fill(self, width=2): + x = self.delta.copy() + for i in range(len(x)): + if np.isnan(x[i]): + x[i] = np.nanmean(np.concatenate( + (x[max(i - width, 0):i], x[i + 1:i + width]))) + return x + + def plot(self, ax=None): + if ax is None: + fig, ax = plt.subplots(1) + ax.plot(self.time, self.delta, label='Raw') + ax.scatter(self.time, self.delta) + ax.plot(self.time, self.smoothed, + label=""Smoothed"", alpha=0.95, ls='--') + return ax + + def search(self, time): + lo = 0 + n = hi = len(self.time) + while hi != lo: + mid = (hi + lo) // 2 + x = self.time[mid] + err = (x - time) + if err == 0: + return mid + elif (hi - lo) == 1: + err = abs(err) + if mid != 0: + prev_err = self.time[mid - 1] - time + if abs(prev_err) < err: + return mid - 1 + if mid < n - 1: + next_err = self.time[mid + 1] - time + if abs(next_err) < err: + return mid + 1 + return mid + elif err > 0: + hi = mid + else: + lo = mid +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/elution_time_grouping/pipeline.py",".py","10755","238","import os + +from collections import defaultdict + +import dill as pickle + +import numpy as np + +from scipy.stats import gaussian_kde + +import glycopeptidepy + +from glycresoft.task import TaskBase +from glycresoft.output.csv_format import csv_stream + +from .structure import GlycopeptideChromatogramProxy +from .cross_run import ReplicatedAbundanceWeightedPeptideFactorElutionTimeFitter + + +# Deprecated. Adapt to model.GlycopeptideElutionTimeModelBuildingPipeline +class GlycopeptideElutionTimeModeler(TaskBase): + _model_class = ReplicatedAbundanceWeightedPeptideFactorElutionTimeFitter + + def __init__(self, glycopeptide_chromatograms, factors=None, refit_filter=0.01, replicate_key_attr=None, + test_chromatograms=None, use_retention_time_normalization=False, prefer_joint_model=False, + minimum_observations_for_specific_model=20): + if replicate_key_attr is None: + replicate_key_attr = 'analysis_name' + if test_chromatograms is not None: + if not isinstance(test_chromatograms[0], GlycopeptideChromatogramProxy): + test_chromatograms = [ + GlycopeptideChromatogramProxy.from_chromatogram(i) for i in test_chromatograms] + + self.replicate_key_attr = replicate_key_attr + if not isinstance(glycopeptide_chromatograms[0], GlycopeptideChromatogramProxy): + glycopeptide_chromatograms = [ + GlycopeptideChromatogramProxy.from_chromatogram(i) for i in glycopeptide_chromatograms] + self.glycopeptide_chromatograms = glycopeptide_chromatograms + self.test_chromatograms = test_chromatograms + self.prefer_joint_model = prefer_joint_model + self.minimum_observations_for_specific_model = minimum_observations_for_specific_model + self.factors = factors + if self.factors is None: + self.factors = self._infer_factors() + self.use_retention_time_normalization = use_retention_time_normalization + self.joint_model = None + self.refit_filter = refit_filter + self.by_peptide = defaultdict(list) + self.peptide_specific_models = dict() + self.delta_by_factor = dict() + self._partition_by_sequence() + + def _partition_by_sequence(self): + for record in self.glycopeptide_chromatograms: + key = glycopeptidepy.parse(str(record.structure)).deglycosylate() + self.by_peptide[key].append(record) + + def _deltas_for(self, monosaccharide): + deltas = [] + for _backbone, cases in self.by_peptide.items(): + for target in cases: + gc = target.glycan_composition.clone() + gc[monosaccharide] += 1 + key = self.joint_model._get_replicate_key(target) + for case in cases: + if case.glycan_composition == gc and self.joint_model._get_replicate_key(case) == key: + deltas.append(case.apex_time - target.apex_time) + return np.array(deltas) + + def _infer_factors(self): + keys = set() + for record in self.glycopeptide_chromatograms: + keys.update(record.glycan_composition) + keys = sorted(map(str, keys)) + return keys + + def fit_model(self, glycopeptide_chromatograms): + model = self._model_class( + glycopeptide_chromatograms, self.factors, + replicate_key_attr=self.replicate_key_attr, + use_retention_time_normalization=self.use_retention_time_normalization) + model.fit() + return model + + def fit(self): + self.log(""Fitting Joint Model"") + model = self.fit_model(self.glycopeptide_chromatograms) + self.log(""R^2: %0.3f, MSE: %0.3f"" % (model.R2(), model.mse)) + if self.refit_filter != 0.0: + self.log(""Filtering Training Data"") + filtered_cases = [ + case for case in self.glycopeptide_chromatograms + if model.score(case) > self.refit_filter + ] + self.log(""Re-fitting After Filtering"") + model = self.fit_model(filtered_cases) + self.log(""R^2: %0.3f, MSE: %0.3f"" % (model.R2(), model.mse)) + self.log('\n' + model.summary()) + self.joint_model = model + factors = sorted(self.factors) + self.log(""Measuring Single Monosaccharide Deltas, Median and MAD"") + for key in factors: + deltas = self._deltas_for(key) + self.delta_by_factor[key] = deltas + self.log(""%s: %0.3f %0.3f"" % + (key, + np.median(deltas), + np.median(np.abs(deltas - np.median(deltas)), ))) + for key, members in self.by_peptide.items(): + distinct_members = set(str(m.structure) for m in members) + self.log(""Fitting Model For %s (%d observations, %d distinct)"" % (key, len(members), len(distinct_members))) + if len(distinct_members) <= max(len(self.factors), self.minimum_observations_for_specific_model): + self.log(""Too few distinct observations for %s"" % (key, )) + continue + model = self.fit_model(members) + self.log(""R^2: %0.3f, MSE: %0.3f"" % (model.R2(), model.mse)) + if self.refit_filter != 0.0: + self.log(""Filtering Training Data"") + filtered_cases = [ + case for case in members + if model.score(case) > self.refit_filter + ] + self.log(""Re-fitting After Filtering"") + model = self.fit_model(filtered_cases) + self.log(""R^2: %0.3f, MSE: %0.3f"" % (model.R2(), model.mse)) + self.log('\n' + model.summary()) + self.peptide_specific_models[key] = model + joint_perf = np.mean(map(self.joint_model.score, members)) + spec_perf = np.mean(map(model.score, members)) + self.log(""Mean Peptide Model Score: %0.3f"" % (spec_perf, )) + self.log(""Mean Joint Model Score: %0.3f"" % (joint_perf, )) + + def evaluate_training(self): + for key, group in self.by_peptide.items(): + self.log(""Evaluating %s"" % key) + for obs in group: + model = self._model_for(obs) + score = model.score(obs) + pred = model.predict(obs) + delta = model._get_apex_time(obs) - pred + obs.annotations['score'] = score + obs.annotations['predicted_apex_time'] = pred + obs.annotations['delta_apex_time'] = delta + + def evaluate(self, observations): + for obs in observations: + model = self._model_for(obs) + score = model.score(obs) + pred = model.predict(obs) + delta = model._get_apex_time(obs) - pred + obs.annotations['score'] = score + obs.annotations['predicted_apex_time'] = pred + obs.annotations['delta_apex_time'] = delta + + def _model_for(self, observation): + if self.prefer_joint_model: + return self.joint_model + key = glycopeptidepy.parse(str(observation.structure)).deglycosylate() + model = self.peptide_specific_models.get(key, self.joint_model) + return model + + def predict(self, observation): + model = self._model_for(observation) + return model.predict(observation) + + def score(self, observation): + model = self._model_for(observation) + return model.score(observation) + + def run(self): + self.fit() + self.evaluate_training() + if self.test_chromatograms: + self.evaluate(self.test_chromatograms) + + def write(self, path): + from glycresoft.output.report.base import render_plot + from glycresoft.plotting.base import figax + if not os.path.exists(path): + os.makedirs(path) + elif not os.path.isdir(path): + raise IOError(""Expected a path to a directory, %s is a file!"" % (path, )) + pjoin = os.path.join + self.log(""Writing scored chromatograms"") + with csv_stream(open(pjoin(path, ""scored_chromatograms.csv""), 'wb')) as fh: + GlycopeptideChromatogramProxy.to_csv(self.glycopeptide_chromatograms, fh) + if self.test_chromatograms: + with csv_stream(open(pjoin(path, ""test_chromatograms.csv""), 'wb')) as fh: + GlycopeptideChromatogramProxy.to_csv(self.test_chromatograms, fh) + self.log(""Writing joint model descriptors"") + with csv_stream(open(pjoin(path, ""joint_model_parameters.csv""), 'wb')) as fh: + self.joint_model.to_csv(fh) + with open(pjoin(path, ""joint_model_predplot.png""), 'wb') as fh: + ax = figax() + self.joint_model.prediction_plot(ax=ax) + fh.write(render_plot(ax, dpi=160.0).getvalue()) + + if self.use_retention_time_normalization: + with open(pjoin(path, ""retention_time_normalization.png""), 'wb') as fh: + ax = figax() + self.joint_model.run_normalizer.plot(ax=ax) + ax.set_title(""Cross-Run RT Correction"") + fh.write(render_plot(ax, dpi=160.0).getvalue()) + + for key, model in self.peptide_specific_models.items(): + self.log(""Writing %s model descriptors"" % (key, )) + with csv_stream(open(pjoin(path, ""%s_model_parameters.csv"" % (key, )), 'wb')) as fh: + model.to_csv(fh) + with open(pjoin(path, ""%s_model_predplot.png"" % (key, )), 'wb') as fh: + ax = figax() + model.prediction_plot(ax=ax) + ax.set_title(key) + fh.write(render_plot(ax, dpi=160.0).getvalue()) + + for factor, deltas in self.delta_by_factor.items(): + with open(pjoin(path, '%s_delta_hist.png' % (factor.replace(""@"", """"), )), 'wb') as fh: + ax = figax() + + ax.hist(deltas, bins='auto', density=False, ec='black', alpha=0.5) + ax.set_title(factor) + ax.figure.text(0.75, 0.8, 'Median: %0.3f' % np.median(deltas), ha='center') + ax.set_xlabel(""RT Shift (Min)"") + ax.set_ylabel(""Count"") + ax2 = ax.twinx() + if len(deltas) > 1: + x = np.linspace(deltas.min() + -0.1, deltas.max() + 0.1) + m = gaussian_kde(deltas) + ax2.fill_between(x, 0, m.pdf(x), alpha=0.5, color='green') + ax2.set_ylabel(""Density"") + ax2.set_ylim(0, ax2.get_ylim()[1]) + else: + m = None + fh.write(render_plot(ax, dpi=160.0).getvalue()) + + self.log(""Saving models"") + with open(pjoin(path, ""model.pkl""), 'wb') as fh: + pickle.dump(self, fh, -1) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/scoring/elution_time_grouping/linear_regression.py",".py","11687","365","'''The barebone-essentials of weighted ordinary least squares and +a RANSAC-wrapper of it. +''' +import random +import functools + +from typing import Tuple, Optional + +import numpy as np +from scipy import stats + +from glycresoft._c.scoring.elution_time_grouping import posprocess_linear_fit + +def is_square(x: np.ndarray): + if x.ndim == 2: + return x.shape[0] == x.shape[1] + return False + + +class WLSSolution(object): + '''A structured container for :func:`weighted_linear_regression_fit` + output. + ''' + __slots__ = ('yhat', 'parameters', 'data', 'weights', 'residuals', + 'projection_matrix', 'rss', 'press', 'R2', 'variance_matrix') + + yhat: np.ndarray + parameters: np.ndarray + data: Tuple[np.ndarray, np.ndarray] + weights: np.ndarray + residuals: np.ndarray + projection_matrix: np.ndarray + rss: float + press: float + R2: float + variance_matrix: np.ndarray + + def __init__(self, yhat, parameters, data, weights, residuals, projection_matrix, rss, press, R2, variance_matrix): + self.yhat = yhat + self.parameters = parameters + self.data = data + self.weights = weights + self.residuals = residuals + self.projection_matrix = projection_matrix + self.rss = rss + self.press = press + self.R2 = R2 + self.variance_matrix = variance_matrix + + @property + def y(self) -> np.ndarray: + return self.data[1] + + @property + def X(self) -> np.ndarray: + return self.data[0] + + def __getstate__(self): + state = {} + state['parameters'] = self.parameters + state['data'] = self.data + if is_square(self.weights): + self.weights = np.diag(self.weights) + state['weights'] = self.weights + # state['projection_matrix'] = self.projection_matrix + state['projection_matrix'] = None + state['rss'] = self.rss + state['press'] = self.press + state['R2'] = self.R2 + state['variance_matrix'] = self.variance_matrix + return state + + def __setstate__(self, state): + X, y = state['data'] + self.parameters = state['parameters'] + self.data = state['data'] + self.weights = state['weights'] + if is_square(self.weights): + self.weights = np.diag(self.weights) + self.projection_matrix = state['projection_matrix'] + self.rss = state['rss'] + self.press = state['press'] + self.R2 = state['R2'] + self.variance_matrix = state['variance_matrix'] + self.yhat = X.dot(self.parameters) + self.residuals = y - self.yhat + + def __repr__(self): + template = ""{self.__class__.__name__}({fields})"" + fields = ', '.join([""%s=%r"" % (k, getattr(self, k)) for k in self.__slots__]) + return template.format(self=self, fields=fields) + + +SMALL_ERROR = 1e-5 + +T_ISF = functools.lru_cache(None)(stats.t.isf) + + +def prepare_arrays_for_linear_fit(x: np.ndarray, y: np.ndarray, w: Optional[np.ndarray]=None): + """"""Prepare data for estimating parameter values using the + weighted ordinary least squares method implemented in :func:`weighted_linear_regerssion_fit` + + Parameters + ---------- + x : :class:`np.ndarray` + The data vector or matrix of predictors. Does not contain a common + intercept. + y : :class:`np.ndarray` + The response variable, should have the same outer dimension as x + w : :class:`np.ndarray`, optional + The optional weight matrix. If omitted, the identity matrix of appropriate + shape will be returned. + + Returns + ------- + X : :class:`np.ndarray` + The predictors, with a common intercept term added. + y : :class:`np.ndarray` + The response variable. + w : :class:`np.ndarray` + The weight matrix of X + """""" + X = np.vstack((np.ones(len(x)), np.array(x))).T + Y = np.array(y) + if w is None: + W = np.ones(Y.shape[0]) + else: + W = np.array(w) + return X, Y, W + + +def weighted_linear_regression_fit_ridge(X: np.ndarray, y: np.ndarray, + w: Optional[np.ndarray]=None, + alpha: Optional[np.ndarray]=None, + prepare: bool=False) -> WLSSolution: + if prepare: + X, y, w = prepare_arrays_for_linear_fit(X, y, w) + elif w is None: + w = np.ones(y.shape[0]) + if alpha is None: + alpha = 0.0 + elif isinstance(alpha, np.ndarray): + if alpha.ndim == 1: + alpha = np.diag(alpha) + else: + raise TypeError(""Could not infer the format for alpha"") + + if w.ndim == 1: + Xtw = X.T * w + else: + Xtw = X.T @ w + w = np.ascontiguousarray(np.diag(w)) + V = np.linalg.pinv((Xtw @ X) + alpha) + A = V @ Xtw + del Xtw + B = A @ y + H = X @ A + yhat = X @ B + residuals = (y - yhat) + # leave_one_out_error = residuals / (1 - np.diag(H)) + # press = (np.diag(w) * leave_one_out_error * leave_one_out_error).sum() + # rss = (np.diag(w) * residuals * residuals).sum() + # tss = (y - y.mean()) + # tss = (np.diag(w) * tss * tss).sum() + diag_H = np.require(np.ascontiguousarray(np.diag(H)), requirements=""W"") + w = np.require(w, requirements=""W"") + press, rss, tss = posprocess_linear_fit(y, residuals, w, diag_H) + if tss == 0: + tss = 1e-16 + return WLSSolution( + yhat, B, (X, y), w, residuals, H, + rss, press, 1 - (rss / (tss)), V) + + +def weighted_linear_regression_fit(X: np.ndarray, y: np.ndarray, + w: Optional[np.ndarray]=None, prepare: bool=False) -> WLSSolution: + """"""Fit a linear model using weighted least squares. + + Parameters + ---------- + x : :class:`np.ndarray` + The data vector or matrix of predictors + y : :class:`np.ndarray` + The response variable, should have the same outer dimension as x + w : :class:`np.ndarray`, optional + The optional weight matrix + prepare : bool, optional + Whether or not to pass the parameters through :func:`prepare_arrays_for_linear_fit` + + Returns + ------- + WLSSolution + """""" + if prepare: + X, y, w = prepare_arrays_for_linear_fit(X, y, w) + elif w is None: + w = np.eye(y.shape[0]) + if w.ndim == 1: + Xtw = X.T * w + else: + Xtw = X.T @ w + w = np.ascontiguousarray(np.diag(w)) + V = np.linalg.pinv(Xtw.dot(X)) + A = V.dot(Xtw) + B = A.dot(y) + H = X.dot(A) + yhat = X.dot(B) + residuals = (y - yhat) + # leave_one_out_error = residuals / (1 - np.diag(H)) + # press = (np.diag(w) * leave_one_out_error * leave_one_out_error).sum() + # rss = (np.diag(w) * residuals * residuals).sum() + # tss = (y - y.mean()) + # tss = (np.diag(w) * tss * tss).sum() + diag_H = np.require(np.ascontiguousarray(np.diag(H)), requirements='W') + w = np.require(w, requirements='W') + press, rss, tss = posprocess_linear_fit(y, residuals, w, diag_H) + return WLSSolution( + yhat, B, (X, y), w, residuals, H, + rss, press, 1 - (rss / (tss)), V) + + +def ransac(x, y, w=None, max_trials=100, regularize_alpha=None): + ''' + RANSAC Regression, inspired heavily by sklearn's + much more complex implementation + ''' + X = x + residual_threshold = np.median(np.abs(y - np.median(y))) + + if w is None: + w = np.eye(y) + + def loss(y_true, y_pred): + return np.abs(y_true - y_pred) + + n_trials = 0 + n_samples = X.shape[0] + min_samples = X.shape[1] * 5 + if min_samples > X.shape[0]: + min_samples = X.shape[1] + 1 + + if min_samples > X.shape[0]: + if regularize_alpha is not None: + return weighted_linear_regression_fit_ridge(X, y, w, regularize_alpha) + return weighted_linear_regression_fit(X, y, w) + + sample_indices = np.arange(n_samples) + + rng = random.Random(1) + + n_inliers_best = 1 + score_best = -np.inf + X_inlier_best = None + y_inlier_best = None + w_inlier_best = None + + while n_trials < max_trials: + n_trials += 1 + subset_ix = rng.sample(sample_indices, min_samples) + X_subset = X[subset_ix] + y_subset = y[subset_ix] + w_subset = np.diag(np.diag(w)[subset_ix]) + + # fit parameters on random subset of the data + if regularize_alpha is not None: + fit = weighted_linear_regression_fit_ridge( + X_subset, y_subset, w_subset, regularize_alpha) + else: + fit = weighted_linear_regression_fit(X_subset, y_subset, w_subset) + + # compute goodness of fit for the fitted parameters with + # the full dataset + yhat = np.dot(X, fit.parameters) + residuals_subset = loss(y, yhat) + + # locate inliers based on residual threshold + inlier_subset_mask = residuals_subset < residual_threshold + n_inliers_subset = inlier_subset_mask.sum() + + # determine the quality of the fitted parameters for + # the inliers using R2 + inlier_subset_ix = sample_indices[inlier_subset_mask] + X_inlier_subset = X[inlier_subset_ix] + y_inlier_subset = y[inlier_subset_ix] + w_inlier_subset = np.diag(np.diag(w)[inlier_subset_ix]) + # w_inlier_best = 1 + + yhat_inlier_subset = X_inlier_subset.dot(fit.parameters) + rss = (w_inlier_subset * np.square( + y_inlier_subset - yhat_inlier_subset)).sum() + tss = (w_inlier_subset * np.square( + y_inlier_subset - y_inlier_subset.mean())).sum() + + score_subset = 1 - (rss / tss) + + # If the number of inliers chosen hasn't improved and the score hasn't + # improved, don't update the current best + if n_inliers_subset < n_inliers_best and score_subset < score_best: + continue + + score_best = score_subset + X_inlier_best = X_inlier_subset + y_inlier_best = y_inlier_subset + w_inlier_best = w_inlier_subset + + if regularize_alpha is None: + return weighted_linear_regression_fit_ridge( + X_inlier_best, y_inlier_best, w_inlier_best, regularize_alpha) + # fit the final best inlier set for the final parameters + return weighted_linear_regression_fit( + X_inlier_best, y_inlier_best, w_inlier_best) + + +def fitted_interval(solution: WLSSolution, x0: np.ndarray, + y0: np.ndarray, alpha: float=0.05) -> np.ndarray: + n = len(solution.residuals) + k = len(solution.parameters) + df = n - k + sigma2 = solution.rss / df + xtx_inv = solution.variance_matrix + h = x0.dot(xtx_inv).dot(x0.T) + if not np.isscalar(h): + h = np.diag(h) + + error_of_fit = np.sqrt(sigma2 * h) + + t = T_ISF(alpha / 2., df) + width = t * error_of_fit + return np.stack([y0 - width, y0 + width]) + + +def prediction_interval(solution, x0, y0, alpha=0.05): + """"""Calculate the prediction interval around `x0` with response + `y0` given the `solution`. + + Parameters + ---------- + solution : :class:`WLSSolution` + The fitted model + x0 : :class:`np.ndarray` + The new predictors + y0 : float + The predicted response + alpha : float, optional + The prediction interval width. Defaults to 0.05 + + Returns + ------- + :class:`np.ndarray` : + The lower and upper bound of the prediction interval. + """""" + n = len(solution.residuals) + k = len(solution.parameters) + xtx_inv = solution.variance_matrix + df = n - k + sigma2 = solution.rss / df + h = x0.dot(xtx_inv).dot(x0.T) + if not np.isscalar(h): + h = np.diag(h) + error_of_prediction = np.sqrt(sigma2 * (1 + h)) + + t = T_ISF(alpha / 2., df) + width = t * error_of_prediction + return np.stack([y0 - width, y0 + width]) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/composition_aggregation.py",".py","2983","96","from glypy.composition import formula as _formulastr, Composition +from ms_deisotope.utils import dict_proxy +from collections import defaultdict + + +@dict_proxy(""composition"") +class Formula(object): + """"""Represent a hashable composition wrapper and a backing object supplying + other attributes and properties. Used to make handling of objects which posses + composition-like behavior easier. + + This class implements the Mapping interface, supplying its composition as key-value data. + + Attributes + ---------- + composition : Composition + The elemental composition to proxy + data : object + An arbitrary object to proxy attribute look ups to. + Usually the source of :attr:`composition` + name : str + The formula for the given composition. Used for hashing and equality testing + """""" + def __init__(self, composition, data): + self.composition = composition + self.name = _formulastr(composition) + self.data = data + self._hash = hash(self.name) + + def __getattr__(self, attr): + if attr == ""data"": + return None + return getattr(self.data, attr) + + def __eq__(self, other): + return self.name == other.name + + def __hash__(self): + return self._hash + + def total_composition(self): + return Composition(self.composition) + + +@dict_proxy(""composition"") +class CommonComposition(object): + """"""A type to represent multiple objects which share the same elemental composition, + holding a list of all the objects which it shares formulae with. + + This class implements the Mapping interface, supplying its composition as key-value data. + + Attributes + ---------- + base_data : list + All the objects which are bundled together. + composition : Composition + The composition being represented. + """""" + def __init__(self, composition, base_data): + self.composition = composition + self.base_data = base_data + + @property + def name(self): + return '|'.join(x.name for x in self.base_data) + + @classmethod + def aggregate(cls, iterable): + """"""Combine an iterable of objects which are hashable and function as + composition mappings into a list of :class:`CommonComposition` instances such + that each composition is represented exactly once. + + Parameters + ---------- + iterable : Iterable + An iterable of any type of object which is both hashable and provides a Composition-like + interface + + Returns + ------- + list + """""" + agg = defaultdict(list) + for item in iterable: + agg[item].append(item.data) + results = [] + for key, collected in agg.items(): + results.append(cls(key, collected)) + return results + + def __repr__(self): + return ""CommonComposition(%s)"" % dict(self.composition) + + def total_composition(self): + return Composition(self.composition) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/mass_collection.py",".py","22099","688","import operator +import logging + +from typing import Callable, List, Optional, TypeVar, Generic +from abc import ABCMeta, abstractmethod, abstractproperty +from collections.abc import Sequence as SequenceABC + +try: + from itertools import imap +except ImportError: + imap = map + +import dill + +from six import add_metaclass + +from sqlalchemy.orm.session import Session + +from glycopeptidepy import HashableGlycanComposition + +from .composition_network import CompositionGraph, n_glycan_distance + +logger = logging.getLogger(__name__) +logger.addHandler(logging.NullHandler()) + + +T = TypeVar(""T"") + + +@add_metaclass(ABCMeta) +class SearchableMassCollection(Generic[T]): + def __len__(self): + return len(self.structures) + + def __iter__(self): + return iter(self.structures) + + def __getitem__(self, index) -> T: + return self.structures[index] + + def _convert(self, bundle): + return bundle + + @abstractproperty + def lowest_mass(self) -> float: + raise NotImplementedError() + + def reset(self, **kwargs): + pass + + @abstractproperty + def highest_mass(self) -> float: + raise NotImplementedError() + + def search_mass_ppm(self, mass: float, error_tolerance: float) -> List[T]: + """"""Search for the set of all items in :attr:`structures` within `error_tolerance` PPM + of the queried `mass`. + + Parameters + ---------- + mass : float + The neutral mass to search for + error_tolerance : float, optional + The range of mass errors (in Parts-Per-Million Error) to allow + + Returns + ------- + list + The list of instances which meet the criterion + """""" + tol = mass * error_tolerance + return self.search_mass(mass, tol) + + @abstractmethod + def search_mass(self, mass: float, error_tolerance: float=0.1) -> List[T]: + raise NotImplementedError() + + def __repr__(self): + size = len(self) + return ""{self.__class__.__name__}({size})"".format(self=self, size=size) + + def mark_hit(self, match): + # no-op to be taken when a structure + # gets matched. + return match + + def mark_batch(self): + # no-op to be taken when a batch of + # structures is to be searched. This hint + # helps finalize any intermediary operations. + pass + +SequenceABC.register(SearchableMassCollection) + + +class MassDatabase(SearchableMassCollection[T]): + """"""A quick-to-search database of :class:`HashableGlycanComposition` instances + stored in memory. + + Implements the Sequence interface, with `__iter__`, `__len__`, and `__getitem__`. + + Attributes + ---------- + structures : list + A list of :class:`HashableGlycanComposition` instances, sorted by mass + """""" + def __init__(self, structures, network=None, distance_fn=n_glycan_distance, + glycan_composition_type=HashableGlycanComposition, sort=True): + self.glycan_composition_type = glycan_composition_type + if not isinstance(structures[0], glycan_composition_type): + structures = list(map(glycan_composition_type, structures)) + self.structures = structures + if sort: + self.structures.sort(key=lambda x: x.mass()) + if network is None: + self.network = CompositionGraph(self.structures) + if distance_fn is not None: + self.network.create_edges(1, distance_fn=distance_fn) + else: + self.network = network + + @classmethod + def from_network(cls, network): + structures = [node.composition for node in network.nodes] + return cls(structures, network) + + @property + def lowest_mass(self): + return self.structures[0].mass() + + @property + def highest_mass(self): + return self.structures[-1].mass() + + @property + def glycan_composition_network(self): + return self.network + + def search_binary(self, mass, error_tolerance=1e-6): + """"""Search within :attr:`structures` for the index of a structure + with a mass nearest to `mass`, within `error_tolerance` + + Parameters + ---------- + mass : float + The neutral mass to search for + error_tolerance : float, optional + The approximate error tolerance to accept + + Returns + ------- + int + The index of the structure with the nearest mass + """""" + lo = 0 + n = hi = len(self) + + while hi != lo: + mid = (hi + lo) // 2 + x = self[mid] + err = x.mass() - mass + if abs(err) <= error_tolerance: + best_index = mid + best_error = abs(err) + i = mid - 1 + while i >= 0: + x = self.structures[i] + err = abs((x.mass() - mass) / mass) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i -= 1 + i = mid + 1 + while i < n: + x = self.structures[i] + err = abs((x.mass() - mass) / mass) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i += 1 + return best_index + elif (hi - lo) == 1: + best_index = mid + best_error = err + i = mid - 1 + while i >= 0: + x = self.structures[i] + err = abs((x.mass() - mass) / mass) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i -= 1 + i = mid + 1 + while i < n: + x = self.structures[i] + err = abs((x.mass() - mass) / mass) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i += 1 + return best_index + elif err > 0: + hi = mid + elif err < 0: + lo = mid + + def search_mass(self, mass, error_tolerance=0.1): + """"""Search for the set of all items in :attr:`structures` within `error_tolerance` Da + of the queried `mass`. + + Parameters + ---------- + mass : float + The neutral mass to search for + error_tolerance : float, optional + The range of mass errors (in Daltons) to allow + + Returns + ------- + list + The list of items instances which meet the mass criterion + """""" + if len(self) == 0: + return [] + lo_mass = mass - error_tolerance + hi_mass = mass + error_tolerance + lo = self.search_binary(lo_mass) + hi = self.search_binary(hi_mass) + 1 + return [structure for structure in self[lo:hi] if lo_mass <= structure.mass() <= hi_mass] + + def search_between(self, lower, higher): + if len(self) == 0: + return [] + lo = self.search_binary(lower) + hi = self.search_binary(higher) + 1 + return self.__class__( + [structure for structure in self[lo:hi] if lower <= structure.mass() <= higher], sort=False) + + +class MassObject(object): + __slots__ = ('obj', 'mass') + + def __init__(self, obj, mass): + self.obj = obj + self.mass = mass + + def __getattr__(self, attr): + return getattr(self.obj, attr) + + def __reduce__(self): + return self.__class__, (self.obj, self.mass) + + def __repr__(self): + return ""MassObject(%r, %r)"" % (self.obj, self.mass) + + def __lt__(self, other): + return self.mass < other.mass + + def __gt__(self, other): + return self.mass > other.mass + + def __eq__(self, other): + return abs(self.mass - other.mass) < 1e-3 + + def __ne__(self, other): + return abs(self.mass - other.mass) >= 1e-3 + + +def identity(x): + return x + + +class _NeutralMassDatabase(SearchableMassCollection[T]): + def __init__(self, structures, mass_getter=operator.attrgetter(""calculated_mass""), sort=True): + self.mass_getter = mass_getter + self.structures = self._prepare(structures, sort) + + def _prepare(self, structures, sort=True): + temp = [] + for obj in structures: + mass = self.mass_getter(obj) + temp.append(MassObject(obj, mass)) + if sort: + temp.sort() + return temp + + def __reduce__(self): + return self.__class__, ([], identity, False), self.__getstate__() + + def __getstate__(self): + return { + 'mass_getter': dill.dumps(self.mass_getter), + 'structures': self.structures + } + + def __setstate__(self, state): + self.mass_getter = dill.loads(state['mass_getter']) + self.structures = state['structures'] + + def __iter__(self): + for obj in self.structures: + yield obj.obj + + def __getitem__(self, i): + if isinstance(i, slice): + return [mo.obj for mo in self.structures[i]] + return self.structures[i].obj + + @property + def lowest_mass(self): + return self.structures[0].mass + + @property + def highest_mass(self): + return self.structures[-1].mass + + def search_binary(self, mass, error_tolerance=1e-6): + """"""Search within :attr:`structures` for the index of a structure + with a mass nearest to `mass`, within `error_tolerance` + + Parameters + ---------- + mass : float + The neutral mass to search for + error_tolerance : float, optional + The approximate error tolerance to accept + + Returns + ------- + int + The index of the structure with the nearest mass + """""" + lo = 0 + n = hi = len(self.structures) + while hi != lo: + mid = (hi + lo) // 2 + x = self.structures[mid] + err = x.mass - mass + if abs(err) <= error_tolerance: + best_index = mid + best_error = err + i = mid - 1 + while i >= 0: + x = self.structures[i] + err = abs((x.mass - mass) / mass) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i -= 1 + i = mid + 1 + while i < n: + x = self.structures[i] + err = abs((x.mass - mass) / mass) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i += 1 + return best_index + elif (hi - lo) == 1: + best_index = mid + best_error = err + i = mid - 1 + while i >= 0: + x = self.structures[i] + err = abs((x.mass - mass) / mass) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i -= 1 + i = mid + 1 + while i < n: + x = self.structures[i] + err = abs((x.mass - mass) / mass) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i += 1 + return best_index + elif err > 0: + hi = mid + elif err < 0: + lo = mid + + def search_mass(self, mass, error_tolerance=0.1): + """"""Search for the set of all items in :attr:`structures` within `error_tolerance` Da + of the queried `mass`. + + Parameters + ---------- + mass : float + The neutral mass to search for + error_tolerance : float, optional + The range of mass errors (in Daltons) to allow + + Returns + ------- + list + The list of instances which meet the criterion + """""" + if len(self) == 0: + return [] + lo_mass = mass - error_tolerance + hi_mass = mass + error_tolerance + lo = self.search_binary(lo_mass) + hi = self.search_binary(hi_mass) + 1 + return [structure.obj for structure in self.structures[lo:hi] if lo_mass <= structure.mass <= hi_mass] + + def search_between(self, lower, higher): + lo = self.search_binary(lower) + hi = self.search_binary(higher) + 1 + return self.__class__( + [structure.obj for structure in self.structures[lo:hi] if lower <= structure.mass <= higher], + self.mass_getter, sort=False) + + def _merge_neutral_mass_database(self, other, id_fn=id): + new = {id_fn(x.obj): x for x in self.structures} + new.update({id_fn(x.obj): x for x in other.structures}) + structures = list(new.values()) + structures.sort() + self.structures = structures + return self + + def _merge_other(self, other, id_fn=id): + new = {id_fn(x): x for x in self} + new.update({id_fn(x): x for x in other}) + structures = list(new.values()) + self.structures = self._pack(structures, True) + return self + + def merge(self, other, id_fn=id): + if isinstance(other, NeutralMassDatabase): + return self._merge_neutral_mass_database(other, id_fn) + else: + return self._merge_other(other, id_fn) + + +try: + from glycresoft._c.database.mass_collection import ( + MassObject, NeutralMassDatabaseImpl as _NeutralMassDatabaseImpl) + + class NeutralMassDatabase(_NeutralMassDatabaseImpl, _NeutralMassDatabase[T]): + pass +except ImportError: + NeutralMassDatabase = _NeutralMassDatabase + + +class ConcatenatedDatabase(SearchableMassCollection[T]): + def __init__(self, databases): + self.databases = list(databases) + + def reset(self, **kwargs): + return [d.reset(**kwargs) for d in self.databases] + + @property + def lowest_mass(self): + return min(db.lowest_mass for db in self.databases) + + @property + def highest_mass(self): + return max(db.highest_mass for db in self.databases) + + def search_mass(self, mass, error_tolerance=0.1): + """"""Search for the set of all items in :attr:`structures` within `error_tolerance` Da + of the queried `mass`. + + Parameters + ---------- + mass : float + The neutral mass to search for + error_tolerance : float, optional + The range of mass errors (in Daltons) to allow + + Returns + ------- + list + The list of instances which meet the criterion + """""" + hits = [] + for database in self.databases: + hits += database.search_mass(mass, error_tolerance) + return hits + + def search_between(self, lower, higher): + result = [] + for database in self.databases: + subset = database.search_between(lower, higher) + if len(subset) > 0: + result.append(subset) + return self.__class__(result) + + def add(self, database): + self.databases.append(database) + return self + + def __len__(self): + return sum(map(len, self.databases)) + + +class SearchableMassCollectionWrapper(SearchableMassCollection[T]): + searchable_mass_collection: SearchableMassCollection + + @property + def highest_mass(self): + return self.searchable_mass_collection.highest_mass + + @property + def lowest_mass(self): + return self.searchable_mass_collection.lowest_mass + + def reset(self, **kwargs): + return self.searchable_mass_collection.reset(**kwargs) + + # Fake the disk-backed interface + + @property + def session(self) -> Session: + return self.searchable_mass_collection.session + + @property + def hypothesis_id(self): + return self.searchable_mass_collection.hypothesis_id + + @property + def hypothesis(self): + return self.searchable_mass_collection.hypothesis + + def __len__(self): + return len(self.searchable_mass_collection) + + @property + def peptides(self): + return self.searchable_mass_collection.peptides + + @property + def proteins(self): + return self.searchable_mass_collection.proteins + + def query(self, *args, **kwargs): + return self.searchable_mass_collection.query(*args, **kwargs) + + +class TransformingMassCollectionAdapter(SearchableMassCollectionWrapper[T]): + def __init__(self, searchable_mass_collection, transformer): + self.searchable_mass_collection = searchable_mass_collection + self.transformer = transformer + + def search_mass_ppm(self, mass: float, error_tolerance: float=1e-5) -> List[T]: + result = self.searchable_mass_collection.search_mass_ppm(mass, error_tolerance) + return [self.transformer(r) for r in result] + + def __reduce__(self): + return self.__class__, (self.searchable_mass_collection, None), self.__getstate__() + + def __getstate__(self): + return { + ""transformer"": dill.dumps(self.transformer) + } + + def __setstate__(self, state): + self.transformer = dill.loads(state['transformer']) + + def search_mass(self, mass, error_tolerance): # pylint: disable=signature-differs + result = self.searchable_mass_collection.search_mass(mass, error_tolerance) + return [self.transformer(r) for r in result] + + def __getitem__(self, i): + return self.transformer(self.searchable_mass_collection[i]) + + def __iter__(self): + return imap(self.transformer, self.searchable_mass_collection) + + def search_between(self, lower, higher): + return self.__class__( + self.searchable_mass_collection.search_between(lower, higher), self.transformer) + + +class MassCollectionProxy(SearchableMassCollectionWrapper[T]): + _session: Optional[Session] + session_resolver: Callable[[], Session] + + def __init__(self, resolver, session_resolver=None, hypothesis_id=None, hypothesis_resolver=None): + self._searchable_mass_collection = None + self._session = None + self._hypothesis_id = hypothesis_id + self._hypothesis = None + self.resolver = resolver + self.session_resolver = session_resolver + self.hypothesis_resolver = hypothesis_resolver + + @property + def hypothesis_id(self): + if self._hypothesis_id is not None: + return self._hypothesis_id + else: + logger.info(""Loading hypothesis ID from resolver"") + self._hypothesis_id = self.searchable_mass_collection.hypothesis_id + return self._hypothesis_id + + @property + def session(self) -> Session: + if self._session is None and self.session_resolver is not None: + self._session = self.session_resolver() + if self._session is not None: + return self._session + else: + logger.info(""Loading session from primary resolver"") + self._session = self.searchable_mass_collection.session + return self._session + + @property + def hypothesis(self): + if self._hypothesis is not None: + return self._hypothesis + elif self.hypothesis_resolver: + self._hypothesis = self.hypothesis_resolver() + return self._hypothesis + else: + return super().hypothesis + + def query(self, *args, **kwargs): + return self.session.query(*args, **kwargs) + + @property + def searchable_mass_collection(self): + if self._searchable_mass_collection is None: + self._searchable_mass_collection = self.resolver() + return self._searchable_mass_collection + + def search_mass_ppm(self, mass: float, error_tolerance: float=1e-5) -> List[T]: + result = self.searchable_mass_collection.search_mass_ppm(mass, error_tolerance) + return result + + def __reduce__(self): + return self.__class__, (None,), self.__getstate__() + + def __getstate__(self): + return { + ""resolver"": dill.dumps(self.resolver), + ""session_resolver"": dill.dumps(self.session_resolver), + ""hypothesis_resolver"": dill.dumps(self.hypothesis_resolver), + ""hypothesis_id"": self._hypothesis_id + } + + def _has_resolved(self): + return self._searchable_mass_collection is not None + + def __repr__(self): + if self._has_resolved(): + size = len(self) + else: + size = ""?"" + return ""{self.__class__.__name__}({size})"".format(self=self, size=size) + + def __setstate__(self, state): + self.resolver = dill.loads(state['resolver']) + self.session_resolver = dill.loads(state['session_resolver']) + self.hypothesis_resolver = dill.loads(state['hypothesis_resolver']) + self._hypothesis_id = state['hypothesis_id'] + + def search_mass(self, mass: float, error_tolerance: float) -> List[T]: # pylint: disable=signature-differs + result = self.searchable_mass_collection.search_mass(mass, error_tolerance) + return result + + def __getitem__(self, i) -> T: + return self.searchable_mass_collection[i] + + def __iter__(self): + return iter(self.searchable_mass_collection) + + def search_between(self, lower: float, higher: float) -> List[T]: + return self.searchable_mass_collection.search_between(lower, higher) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/__init__.py",".py","214","7","from .mass_collection import ( + SearchableMassCollection, NeutralMassDatabase) + +from .disk_backed_database import ( + GlycopeptideDiskBackedStructureDatabase, + GlycanCompositionDiskBackedStructureDatabase) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/disk_backed_database.py",".py","26403","644","import operator + +from collections import defaultdict +try: + from itertools import imap +except ImportError: + imap = map + +import logging + + +from sqlalchemy import select, join + +from glycresoft.serialize import ( + GlycanComposition, Glycopeptide, Peptide, + func, GlycopeptideHypothesis, GlycanHypothesis, + DatabaseBoundOperation, GlycanClass, GlycanTypes, + GlycanCompositionToClass, ProteinSite, Protein, GlycanCombination) + +from .mass_collection import SearchableMassCollection, NeutralMassDatabase +from .intervals import ( + PPMQueryInterval, FixedQueryInterval, LRUIntervalSet, + IntervalSet, MassIntervalNode) +from .index import (ProteinIndex, PeptideIndex, ) +from glycresoft.structure.structure_loader import ( + CachingGlycanCompositionParser, CachingGlycopeptideParser, + CachingPeptideParser) +from .composition_network import CompositionGraph, n_glycan_distance + + +logger = logging.getLogger(""glycresoft.database"") + +_empty_interval = NeutralMassDatabase([]) + + +# The maximum total number of items across all loaded intervals that a database +# is allowed to hold in memory at once before it must start pruning intervals. +# This is to prevent the program from running out of memory because it loaded +# too many large intervals into memory while not exceeding the maximum number of +# intervals allowed. +DEFAULT_THRESHOLD_CACHE_TOTAL_COUNT = 6e5 + +# The maximum number of mass intervals to hold in memory at once. +DEFAULT_CACHE_SIZE = 3 + +# Controls the mass interval loaded from the database when a +# query misses the alreadly loaded intervals. Uses the assumption +# that if a mass is asked for, the next mass asked for will be +# close to it, so by pre-emptively loading more data now, less +# time will be spent searching the disk later. The larger this +# number, the more data that will be preloaded. If this number is +# too large, memory and disk I/O is wasted. If too small, then not +# only does it not help solve the pre-loading problem, but it also +# truncates the range that the in-memory interval search actually covers +# and may lead to missing matches. This means this number must chosen +# carefully given the non-constant error criterion we're using, PPM error. +# +# The default value of 1 is good for 10 ppm error intervals on structures +# up to 1e5 Da +DEFAULT_LOADING_INTERVAL = 1. + + +class DiskBackedStructureDatabaseBase(SearchableMassCollection, DatabaseBoundOperation): + """"""A disk-backed structure database that implements the :class:`~.SearchableMassCollection` + interface. It includes an in-memory caching system to keep recently used mass intervals in memory + and optimistically fetches nearby masses around queried masses. + + Attributes + ---------- + hypothesis_id : int + The database id number of the hypothesis + loading_interval : float + The size of the region around a queried mass (in Daltons) to load when + optimistically fetching records from the disk. + cache_size : int + The maximum number of intervals in-memory mass intervals to cache + intervals : :class:`~.LRUIntervalSet` + An LRU caching interval collection over masses read from the disk store + model_type : type + The ORM type to query against. It must provide an attribute called ``calculated_mass`` + peptides : :class:`~.PeptideIndex` + An index for looking up :class:`~.Peptide` ORM objects. + proteins : :class:`~.ProteinIndex` + An index for looking up :class:`~.Protein` ORM objects. + threshold_cache_total_count : int + The total number of records to retain in the in-memory cache before pruning entries, + independent of the number of loaded intervals + """""" + + def __init__(self, connection, hypothesis_id=1, cache_size=DEFAULT_CACHE_SIZE, + loading_interval=DEFAULT_LOADING_INTERVAL, + threshold_cache_total_count=DEFAULT_THRESHOLD_CACHE_TOTAL_COUNT, + model_type=Glycopeptide): + DatabaseBoundOperation.__init__(self, connection) + self.hypothesis_id = hypothesis_id + self.model_type = model_type + self.loading_interval = loading_interval + self.threshold_cache_total_count = threshold_cache_total_count + self._intervals = LRUIntervalSet([], cache_size) + self._ignored_intervals = IntervalSet([]) + self.proteins = ProteinIndex(self.session, self.hypothesis_id) + self.peptides = PeptideIndex(self.session, self.hypothesis_id) + + @property + def cache_size(self): + return self._intervals.max_size + + @cache_size.setter + def cache_size(self, value): + self._intervals.max_size = value + + @property + def intervals(self): + return self._intervals + + def reset(self, **kwargs): + self.intervals.clear() + + def __reduce__(self): + return self.__class__, ( + self._original_connection, self.hypothesis_id, self.cache_size, + self.loading_interval, self.threshold_cache_total_count, + self.model_type) + + def _make_loading_interval(self, mass, error_tolerance=1e-5): + width = mass * error_tolerance + if width > self.loading_interval: + return FixedQueryInterval(mass, width * 2) + else: + return FixedQueryInterval(mass, self.loading_interval) + + def _upkeep_memory_intervals(self): + """"""Perform routine maintainence of the interval cache, ensuring its size does not + exceed the upper limit + """""" + n = len(self._intervals) + if n > 1: + while (len(self._intervals) > 1 and + self._intervals.total_count > + self.threshold_cache_total_count): + logger.info(""Upkeep Memory Intervals %d %d"", self._intervals.total_count, len(self._intervals)) + self._intervals.remove_lru_interval() + + def _get_record_properties(self): + return self.fields + + def _limit_to_hypothesis(self, selectable): + return selectable.where(Peptide.__table__.c.hypothesis_id == self.hypothesis_id) + + def ignore_interval(self, interval): + self._ignored_intervals.insert_interval(interval) + + def is_interval_ignored(self, interval): + is_ignored = self._ignored_intervals.find_interval(interval) + return is_ignored is not None and is_ignored.contains_interval(interval) + + def insert_interval(self, mass, ppm_error_tolerance=1e-5): + logger.debug(""Calling insert_interval with mass %f"", mass) + node = self.make_memory_interval(mass, ppm_error_tolerance) + logger.debug(""New Node: %r"", node) + # We won't insert this node if it is empty. + if len(node.group) == 0: + # Ignore seems to be not-working. + # self.ignore_interval(FixedQueryInterval(mass)) + return node.group + nearest_interval = self._intervals.find_interval(node) + # Should an insert be performed if the query just didn't overlap well + # with the database? + if nearest_interval is None: + # No nearby interval, so we should insert + logger.debug(""No nearby interval for %r"", node) + self._intervals.insert_interval(node) + return node.group + elif nearest_interval.overlaps(node): + logger.debug(""Nearest interval %r overlaps this %r"", nearest_interval, node) + nearest_interval = self._intervals.extend_interval(nearest_interval, node) + return nearest_interval.group + elif not nearest_interval.contains_interval(node): + logger.debug(""Nearest interval %r didn't contain this %r"", nearest_interval, node) + # Nearby interval didn't contain this interval + self._intervals.insert_interval(node) + return node.group + else: + # Situation unclear. + # Not worth inserting, so just return the group + logger.info(""Unknown Condition Overlap %r / %r"", node, nearest_interval) + return nearest_interval.group + + def clear_cache(self): + self._intervals.clear() + + def has_interval(self, mass, ppm_error_tolerance): + q = PPMQueryInterval(mass, ppm_error_tolerance) + match = self._intervals.find_interval(q) + if match is not None: + q2 = self._make_loading_interval(mass, ppm_error_tolerance) + logger.debug(""Nearest interval %r"", match) + # We are completely contained in an existing interval, so just + # use that one. + if match.contains_interval(q): + logger.debug(""Query interval %r was completely contained in %r"", q, match) + return match.group + # We overlap with an extending interval, so we should populate + # the new one and merge them. + elif match.overlaps(q2): + q3 = q2.difference(match).scale(1.05) + logger.debug(""Query interval partially overlapped, creating disjoint interval %r"", q3) + match = self._intervals.extend_interval( + match, + self.make_memory_interval_from_mass_interval(q3.start, q3.end) + ) + return match.group + # We might need to insert a new interval + else: + logger.debug(""Query interval %r did not overlap with %r"", q, match) + if self.is_interval_ignored(q): + return match.group + else: + return self.insert_interval(mass, ppm_error_tolerance) + else: + logger.debug(""No existing interval contained %r"", q) + is_ignored = self._ignored_intervals.find_interval(q) + if is_ignored is not None and is_ignored.contains_interval(q): + return _empty_interval + else: + return self.insert_interval(mass, ppm_error_tolerance) + + def search_mass_ppm(self, mass, error_tolerance): + self._upkeep_memory_intervals() + return self.has_interval(mass, error_tolerance).search_mass_ppm(mass, error_tolerance) + + def search_mass(self, mass, error_tolerance): # pylint: disable=signature-differs + return self._search_mass_interval(mass - error_tolerance, mass + error_tolerance) + + def _search_mass_interval(self, start, end): + model = self.model_type + return self.session.query(self.model_type).filter( + model.hypothesis_id == self.hypothesis_id, + model.calculated_mass.between( + start, end)).all() + + def on_memory_interval(self, mass, interval): + if len(interval) > self.threshold_cache_total_count: + logger.info(""Interval Length %d for %f"", len(interval), mass) + + def make_memory_interval(self, mass, error_tolerance=None): + interval = self._make_loading_interval(mass, error_tolerance) + node = self.make_memory_interval_from_mass_interval(interval.start, interval.end) + return node + + def make_memory_interval_from_mass_interval(self, start, end): + logger.debug(""Querying the database for masses between %f and %f"", start, end) + out = self._search_mass_interval(start, end) + logger.debug(""Retrieved %d records"", len(out)) + self.on_memory_interval((start + end) / 2.0, out) + mass_db = self._prepare_interval(out) + # bind the bounds of the returned dataset to the bounds of the query + node = MassIntervalNode(mass_db) + node.start = start + node.end = end + return node + + def _prepare_interval(self, query_results): + return NeutralMassDatabase(query_results, operator.attrgetter(""calculated_mass"")) + + @property + def lowest_mass(self): + return self.session.query(func.min(self.model_type.calculated_mass)).filter( + self.model_type.hypothesis_id == self.hypothesis_id).first() + + @property + def highest_mass(self): + return self.session.query(func.max(self.model_type.calculated_mass)).filter( + self.model_type.hypothesis_id == self.hypothesis_id).first() + + def get_record(self, id): + return self.session.query(self.model_type).get(id) + + def get_object_by_id(self, id): + return self.session.query(self.model_type).get(id) + + def get_object_by_reference(self, reference): + return self.session.query(self.model_type).get(reference.id) + + def search_between(self, lower, upper): + return self.make_memory_interval_from_mass_interval(lower, upper) + + def valid_glycan_set(self): + glycan_query = self.query( + GlycanCombination).join( + GlycanCombination.components).join( + GlycanComposition.structure_classes).group_by(GlycanCombination.id) + + glycan_compositions = [ + c.convert() for c in glycan_query.all()] + + return set(glycan_compositions) + + +class DeclarativeDiskBackedDatabase(DiskBackedStructureDatabaseBase): + """"""A base class for creating :class:`DiskBackedStructureDatabaseBase` that map against + ad hoc SQL queries rather than ORM classes + + Attributes + ---------- + identity_field: :class:`sqlalchemy.sql.Selectable` + The database column from which the entity identity should be determined + mass_field: :class:`sqlalchemy.Column` + The column to read the mass from + fields: list of :class:`sqlalchemy.ColumnElement` + The columns to extract from the database to compose records + + """""" + + def __init__(self, connection, hypothesis_id=1, cache_size=DEFAULT_CACHE_SIZE, + loading_interval=DEFAULT_LOADING_INTERVAL, + threshold_cache_total_count=DEFAULT_THRESHOLD_CACHE_TOTAL_COUNT): + super(DeclarativeDiskBackedDatabase, self).__init__( + connection, hypothesis_id, cache_size, loading_interval, + threshold_cache_total_count, None) + self._glycan_composition_network = None + + def __reduce__(self): + return self.__class__, ( + self._original_connection, self.hypothesis_id, self.cache_size, + self.loading_interval, self.threshold_cache_total_count) + + @property + def glycan_composition_network(self): + return self._glycan_composition_network + + @property + def lowest_mass(self): + q = select( + [func.min(self.mass_field)]).select_from( + self.selectable) + q = self._limit_to_hypothesis(q) + return self.session.execute(q).scalar() + + @property + def highest_mass(self): + q = select( + [func.max(self.mass_field)]).select_from( + self.selectable) + q = self._limit_to_hypothesis(q) + return self.session.execute(q).scalar() + + def _get_record_properties(self): + return self.fields + + def _limit_to_hypothesis(self, selectable): + raise NotImplementedError() + + @property + def structures(self): + stmt = self._limit_to_hypothesis( + select(self._get_record_properties()).select_from( + self.selectable)).order_by( + self.mass_field) + return imap(self._convert, self.session.execute(stmt)) + + def __iter__(self): + stmt = self._limit_to_hypothesis( + select(self._get_record_properties()).select_from( + self.selectable)).order_by( + self.mass_field) + cursor = self.session.execute(stmt) + converter = self._convert + while True: + block_size = 2 ** 16 + block = cursor.fetchmany(block_size) + if not block: + break + for row in block: + yield converter(row) + + def __getitem__(self, i): + stmt = self._limit_to_hypothesis( + select(self._get_record_properties()).select_from( + self.selectable)).order_by( + self.mass_field).offset(i) + return self._convert(self.session.execute(stmt).fetchone()) + + def search_mass(self, mass, error_tolerance): + return self._search_mass_interval(mass - error_tolerance, mass + error_tolerance) + + def _search_mass_interval(self, start, end): + conn = self.session.connection() + stmt = self._limit_to_hypothesis( + select(self._get_record_properties()).select_from(self.selectable)).where( + self.mass_field.between( + start, end)) + return conn.execute(stmt).fetchall() + + def get_record(self, id): + record = self.session.execute(select(self._get_record_properties()).select_from( + self.selectable).where( + self.identity_field == id)).first() + return record + + def get_all_records(self): + records = self.session.execute( + select( + self._get_record_properties()).select_from(self.selectable)) + return list(records) + + def get_object_by_id(self, id): + return self._convert(self.get_record(id)) + + def get_object_by_reference(self, reference): + return self._convert(self.get_object_by_id(reference.id)) + + def __len__(self): + try: + return self.hypothesis.parameters['database_size'] + except KeyError: + stmt = select([func.count(self.identity_field)]).select_from( + self.selectable) + stmt = self._limit_to_hypothesis(stmt) + return self.session.execute(stmt).scalar() + + +class GlycopeptideDiskBackedStructureDatabase(DeclarativeDiskBackedDatabase): + selectable = join(Glycopeptide.__table__, Peptide.__table__) + fields = [ + Glycopeptide.__table__.c.id, + Glycopeptide.__table__.c.calculated_mass, + Glycopeptide.__table__.c.glycopeptide_sequence, + Glycopeptide.__table__.c.protein_id, + Peptide.__table__.c.start_position, + Peptide.__table__.c.end_position, + Peptide.__table__.c.calculated_mass.label(""peptide_mass""), + Glycopeptide.__table__.c.hypothesis_id, + ] + mass_field = Glycopeptide.__table__.c.calculated_mass + identity_field = Glycopeptide.__table__.c.id + + def __init__(self, connection, hypothesis_id=1, cache_size=DEFAULT_CACHE_SIZE, + loading_interval=DEFAULT_LOADING_INTERVAL, + threshold_cache_total_count=DEFAULT_THRESHOLD_CACHE_TOTAL_COUNT): + super(GlycopeptideDiskBackedStructureDatabase, self).__init__( + connection, hypothesis_id, cache_size, loading_interval, + threshold_cache_total_count) + self._convert_cache = CachingGlycopeptideParser() + + def _convert(self, bundle): + inst = self._convert_cache.parse(bundle) + inst.hypothesis_id = self.hypothesis_id + return inst + + @property + def hypothesis(self): + return self.session.query(GlycopeptideHypothesis).get(self.hypothesis_id) + + def _limit_to_hypothesis(self, selectable): + return selectable.where(Glycopeptide.__table__.c.hypothesis_id == self.hypothesis_id) + + def make_key_maker(self): + return GlycopeptideIdKeyMaker(self, self.hypothesis_id) + + +class GlycopeptideIdKeyMaker(object): + def __init__(self, database, hypothesis_id): + self.database = database + self.hypothesis_id = hypothesis_id + self.lookup_map = defaultdict(list) + for gc in self.database.valid_glycan_set(): + self.lookup_map[str(gc)].append(gc.id) + + def make_id_controlled_structures(self, structure, references): + glycan_ids = self.lookup_map[structure.glycan_composition] + result = [] + for glycan_id in glycan_ids: + for ref in references: + ref_rec = self.database.query(Glycopeptide).get(ref.id) + alts = self.database.query(Glycopeptide).filter( + Glycopeptide.peptide_id == ref_rec.peptide_id, + Glycopeptide.glycan_combination_id == glycan_id).all() + for alt in alts: + result.append(alt.convert()) + return result + + def __call__(self, structure, references): + return self.make_id_controlled_structures(structure, references) + + +class InMemoryPeptideStructureDatabase(NeutralMassDatabase): + def __init__(self, records, source_database=None, sort=True): + super(InMemoryPeptideStructureDatabase, self).__init__(records, sort=sort) + self.source_database = source_database + + @property + def hypothesis(self): + return self.source_database.hypothesis + + @property + def hypothesis_id(self): + return self.source_database.hypothesis_id + + @property + def session(self): + return self.source_database.session + + def query(self, *args, **kwargs): + return self.source_database.query(*args, **kwargs) + + @property + def peptides(self): + return self.source_database.peptides + + @property + def proteins(self): + return self.source_database.proteins + + +class GlycanCompositionDiskBackedStructureDatabase(DeclarativeDiskBackedDatabase): + selectable = (GlycanComposition.__table__) + fields = [ + GlycanComposition.__table__.c.id, GlycanComposition.__table__.c.calculated_mass, + GlycanComposition.__table__.c.composition, GlycanComposition.__table__.c.formula, + GlycanComposition.__table__.c.hypothesis_id + ] + mass_field = GlycanComposition.__table__.c.calculated_mass + identity_field = GlycanComposition.__table__.c.id + + def __init__(self, connection, hypothesis_id=1, cache_size=DEFAULT_CACHE_SIZE, + loading_interval=DEFAULT_LOADING_INTERVAL, + threshold_cache_total_count=DEFAULT_THRESHOLD_CACHE_TOTAL_COUNT): + super(GlycanCompositionDiskBackedStructureDatabase, self).__init__( + connection, hypothesis_id, cache_size, loading_interval, + threshold_cache_total_count) + self._convert_cache = CachingGlycanCompositionParser() + + def _convert(self, bundle): + inst = self._convert_cache(bundle) + inst.hypothesis_id = self.hypothesis_id + return inst + + @property + def glycan_composition_network(self): + if self._glycan_composition_network is None: + self._glycan_composition_network = CompositionGraph(tuple(self.structures)) + self._glycan_composition_network.create_edges(1, n_glycan_distance) + return self._glycan_composition_network + + @property + def hypothesis(self): + return self.session.query(GlycanHypothesis).get(self.hypothesis_id) + + def glycan_compositions_of_type(self, glycan_type): + try: + glycan_type = glycan_type.name + except AttributeError: + glycan_type = str(glycan_type) + if glycan_type in GlycanTypes: + glycan_type = GlycanTypes[glycan_type] + stmt = self._limit_to_hypothesis( + select(self._get_record_properties()).select_from( + self.selectable.join(GlycanCompositionToClass).join(GlycanClass)).where( + GlycanClass.__table__.c.name == glycan_type)).order_by( + self.mass_field) + return imap(self._convert, self.session.execute(stmt)) + + def glycan_composition_network_from(self, query=None): + if query is None: + query = self.structures + compositions = tuple(query) + graph = CompositionGraph(compositions) + graph.create_edges(1) + return graph + + def _limit_to_hypothesis(self, selectable): + return selectable.where(GlycanComposition.__table__.c.hypothesis_id == self.hypothesis_id) + + +class PeptideDiskBackedStructureDatabase(DeclarativeDiskBackedDatabase): + selectable = Peptide.__table__ + fields = [ + Peptide.__table__.c.id, + Peptide.__table__.c.calculated_mass, + Peptide.__table__.c.modified_peptide_sequence, + Peptide.__table__.c.protein_id, + Peptide.__table__.c.start_position, + Peptide.__table__.c.end_position, + Peptide.__table__.c.hypothesis_id, + Peptide.__table__.c.n_glycosylation_sites, + Peptide.__table__.c.o_glycosylation_sites, + Peptide.__table__.c.gagylation_sites, + ] + mass_field = Peptide.__table__.c.calculated_mass + identity_field = Peptide.__table__.c.id + + def __init__(self, connection, hypothesis_id=1, cache_size=DEFAULT_CACHE_SIZE, + loading_interval=DEFAULT_LOADING_INTERVAL, + threshold_cache_total_count=int(DEFAULT_THRESHOLD_CACHE_TOTAL_COUNT / 5)): + super(PeptideDiskBackedStructureDatabase, self).__init__( + connection, hypothesis_id, cache_size, loading_interval, + threshold_cache_total_count) + self._convert_cache = CachingPeptideParser() + self.peptides = PeptideIndex(self.session, self.hypothesis_id) + self.proteins = ProteinIndex(self.session, self.hypothesis_id) + + # This should exist, but it conflicts with other conversion mechanisms + # def _convert(self, bundle): + # inst = self._convert_cache.parse(bundle) + # inst.hypothesis_id = self.hypothesis_id + # return inst + + def _limit_to_hypothesis(self, selectable): + return selectable.where(Peptide.__table__.c.hypothesis_id == self.hypothesis_id) + + @property + def hypothesis(self): + return self.session.query(GlycopeptideHypothesis).get(self.hypothesis_id) + + def spanning_n_glycosylation_site(self): + q = select(self.fields).select_from( + self.selectable.join(Protein.__table__).join(ProteinSite.__table__)).where( + Peptide.spans(ProteinSite.location) & (ProteinSite.name == ProteinSite.N_GLYCOSYLATION) + & (Protein.hypothesis_id == self.hypothesis_id)).order_by( + self.mass_field).group_by(Peptide.id) + return q + + def having_glycosylation_site(self): + pickle_size = func.length( + Peptide.__table__.c.o_glycosylation_sites) + \ + func.length( + Peptide.__table__.c.n_glycosylation_sites) + min_pickle_size = self.session.query(func.min(pickle_size)).scalar() + if min_pickle_size is None: + min_pickle_size = 0 + q = select(self.fields).where( + (pickle_size > min_pickle_size) & + (Peptide.__table__.c.hypothesis_id == self.hypothesis_id) + ).order_by(self.mass_field) + return q + + def has_protein_sites(self): + has_sites = self.query(ProteinSite).join(ProteinSite.protein).filter( + Protein.hypothesis_id == self.hypothesis_id, + ProteinSite.name == ProteinSite.N_GLYCOSYLATION).first() + return has_sites is not None + +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/index.py",".py","2136","66","'''Auxiliary data structures used to look up records from a database +using the Sequence interface or the Mapping interface for convenience. + +Maintainence Note: Mostly unused outside of debugging +''' + +from glycresoft.serialize import ( + Protein, Peptide, Glycopeptide) + +from glycresoft.structure import LRUCache + + +class ProteinIndex(object): + def __init__(self, session, hypothesis_id): + self.session = session + self.hypothesis_id = hypothesis_id + + def _get_by_id(self, id): + return self.session.query(Protein).get(id) + + def _get_by_name(self, name): + return self.session.query(Protein).filter( + Protein.hypothesis_id == self.hypothesis_id, + Protein.name == name).one() + + def __getitem__(self, key): + if isinstance(key, int): + return self._get_by_id(key) + else: + return self._get_by_name(key) + + def __iter__(self): + q = self.session.query(Protein).filter(Protein.hypothesis_id == self.hypothesis_id) + return iter(q) + + def __len__(self): + return self.session.query(Protein).filter(Protein.hypothesis_id == self.hypothesis_id).count() + + +class PeptideIndex(object): + def __init__(self, session, hypothesis_id): + self.session = session + self.hypothesis_id = hypothesis_id + + def _get_by_id(self, id): + return self.session.query(Peptide).get(id) + + def _get_by_sequence(self, modified_peptide_sequence, protein_id): + return self.session.query(Peptide).filter( + Peptide.hypothesis_id == self.hypothesis_id, + Peptide.modified_peptide_sequence == modified_peptide_sequence, + Peptide.protein_id == protein_id).one() + + def __getitem__(self, key): + if isinstance(key, int): + return self._get_by_id(key) + else: + return self._get_by_sequence(*key) + + def __iter__(self): + q = self.session.query(Peptide).filter(Peptide.hypothesis_id == self.hypothesis_id) + return iter(q) + + def __len__(self): + return self.session.query(Peptide).filter(Peptide.hypothesis_id == self.hypothesis_id).count() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/intervals.py",".py","12921","416","import logging +import operator + +from ms_deisotope.peak_dependency_network.intervals import SpanningMixin + +from glycresoft.structure.lru import LRUCache +from glycresoft.database.mass_collection import ConcatenatedDatabase + + +logger = logging.getLogger(""glycresoft.intervals"") + + +class QueryIntervalBase(SpanningMixin): + def __init__(self, center, start, end): + self.center = center + self.start = start + self.end = end + + def copy(self): + return QueryIntervalBase(self.center, self.start, self.end) + + def __hash__(self): + return hash((self.start, self.center, self.end)) + + def __eq__(self, other): + return (self.start, self.center, self.end) == (other.start, other.center, other.end) + + def __repr__(self): + return ""QueryInterval(%0.4f, %0.4f)"" % (self.start, self.end) + + def extend(self, other): + self.start = min(self.start, other.start) + self.end = max(self.end, other.end) + self.center = (self.start + self.end) / 2. + return self + + def scale(self, x): + new = QueryIntervalBase( + self.center, + self.center - ((self.center - self.start) * x), + self.center + ((self.end - self.center) * x)) + return new + + def difference(self, other): + if self.start < other.start: + if self.end < other.start: + return self.copy() + else: + return QueryIntervalBase(self.center, self.start, other.start) + elif self.start > other.end: + return self.copy() + elif self.start <= other.end: + return QueryIntervalBase(self.center, other.end, self.end) + else: + return self.copy() + + +class PPMQueryInterval(QueryIntervalBase): + + def __init__(self, mass, error_tolerance=2e-5): + self.center = mass + self.start = mass - (mass * error_tolerance) + self.end = mass + (mass * error_tolerance) + + +class FixedQueryInterval(QueryIntervalBase): + + def __init__(self, mass, width=3): + self.center = mass + self.start = mass - width + self.end = mass + width + + +try: + has_c = True + _QueryIntervalBase = QueryIntervalBase + _PPMQueryInterval = PPMQueryInterval + _FixedQueryInterval = FixedQueryInterval + + from glycresoft._c.structure.intervals import ( + QueryIntervalBase, PPMQueryInterval, FixedQueryInterval) +except ImportError: + has_c = False + + +class IntervalSet(object): + + def __init__(self, intervals=None): + if intervals is None: + intervals = list() + self.intervals = sorted(intervals, key=lambda x: x.center) + self._total_count = None + self.compute_total_count() + + def _invalidate(self): + self._total_count = None + + @property + def total_count(self): + if self._total_count is None: + self.compute_total_count() + return self._total_count + + def compute_total_count(self): + self._total_count = 0 + for interval in self: + self._total_count += interval.size + return self._total_count + + def __iter__(self): + return iter(self.intervals) + + def __len__(self): + return len(self.intervals) + + def __getitem__(self, i): + return self.intervals[i] + + def __repr__(self): + return ""%s(%r)"" % (self.__class__.__name__, self.intervals) + + def _repr_pretty_(self, p, cycle): + return p.pretty(self.intervals) + + def find_insertion_point(self, mass): + lo = 0 + hi = len(self) + if hi == 0: + return 0, False + while hi != lo: + mid = (hi + lo) // 2 + x = self[mid] + err = x.center - mass + if abs(err) <= 1e-9: + return mid, True + elif (hi - lo) == 1: + return mid, False + elif err > 0: + hi = mid + else: + lo = mid + raise ValueError((hi, lo, err, len(self))) + + def extend_interval(self, target, expansion): + logger.debug(""Extending %r by %r"", target, expansion) + self._invalidate() + target.extend(expansion) + i, _ = self.find_insertion_point(target.center) + consolidate = False + if i > 0: + before = self[i - 1] + consolidate |= before.overlaps(target) + # print(before, target) + if i < len(self) - 1: + after = self[i + 1] + consolidate |= after.overlaps(target) + # print(after, target) + if consolidate: + logger.debug(""Consolidation was required for extension of %r by %r"", target, expansion) + self.consolidate() + new_interval = self.find_interval(target) + logger.debug(""Consolidated interval %r spans the original %r"", new_interval, target) + return new_interval + return target + + def insert_interval(self, interval): + center = interval.center + n = len(self) + if n != 0: + index, matched = self.find_insertion_point(center) + index += 1 + if matched and self[index - 1].overlaps(interval): + new_group = self.extend_interval(self[index - 1], interval) + return new_group + if index < n and interval.overlaps(self[index]): + new_group = self.extend_interval(self[index], interval) + return new_group + if index == 1: + if self[index - 1].center > center: + index -= 1 + else: + index = 0 + self._insert_interval(index, interval) + return interval + + def _insert_interval(self, index, interval): + self._invalidate() + self.intervals.insert(index, interval) + + def find_interval(self, query): + lo = 0 + n = hi = len(self) + while hi != lo: + mid = (hi + lo) // 2 + x = self[mid] + err = x.center - query.center + if err == 0 or x.contains_interval(query): + return x + elif (hi - 1) == lo: + best_err = abs(err) + best_i = mid + if mid < (n - 1): + err = abs(self[mid + 1].center - query.center) + if err < best_err: + best_err = err + best_i = mid + 1 + if mid > -1: + err = abs(self[mid - 1].center - query.center) + if err < best_err: + best_err = err + best_i = mid - 1 + return self[best_i] + elif err > 0: + hi = mid + else: + lo = mid + + def find(self, mass, ppm_error_tolerance): + return self.find_interval(PPMQueryInterval(mass, ppm_error_tolerance)) + + def remove_interval(self, center): + self._invalidate() + ix, match = self.find_insertion_point(center) + self.intervals.pop(ix) + + def clear(self): + self.intervals = [] + + def consolidate(self): + intervals = list(self) + self.clear() + if len(intervals) == 0: + return + result = [] + last = intervals[0] + for current in intervals[1:]: + if last.overlaps(current): + last.extend(current) + else: + result.append(last) + last = current + result.append(last) + for r in result: + self.insert_interval(r) + + +class LRUIntervalSet(IntervalSet): + + def __init__(self, intervals=None, max_size=1000): + super(LRUIntervalSet, self).__init__(intervals) + self.max_size = max_size + self.current_size = len(self) + self.lru = LRUCache() + for item in self: + self.lru.add_node(item) + + def insert_interval(self, interval): + if self.current_size == self.max_size: + self.remove_lru_interval() + super(LRUIntervalSet, self).insert_interval(interval) + + def _insert_interval(self, index, interval): + super(LRUIntervalSet, self)._insert_interval(index, interval) + self.lru.add_node(interval) + self.current_size += 1 + + def extend_interval(self, target, expansion): + self.lru.remove_node(target) + try: + result = super(LRUIntervalSet, self).extend_interval(target, expansion) + self.lru.add_node(result) + return result + except Exception: + self.lru.add_node(target) + raise + + def find_interval(self, query): + match = super(LRUIntervalSet, self).find_interval(query) + if match is not None: + try: + self.lru.hit_node(match) + except KeyError: + self.lru.add_node(match) + return match + + def remove_lru_interval(self): + lru_interval = self.lru.get_least_recently_used() + logger.debug(""Removing LRU interval %r"", lru_interval) + self.lru.remove_node(lru_interval) + self.remove_interval(lru_interval.center) + self.current_size -= 1 + + def clear(self): + super(LRUIntervalSet, self).clear() + self.lru = LRUCache() + self.current_size = len(self) + + def consolidate(self): + super(LRUIntervalSet, self).consolidate() + self.current_size = len(self) + + +class MassIntervalNode(SpanningMixin): + """"""Contains a NeutralMassDatabase object and provides an interval-like + API. Intended for use with IntervalSet. + + Attributes + ---------- + center : float + The central point of mass for the interval + end : float + The upper-most mass in the wrapped collection + group : NeutralMassDatabase + The collection of massable objects wrapped + growth : int + The number of times the interval had been expanded + size : int + The number of items in :attr:`group` + start : float + The lower-most mass in the wrapped collection + """""" + def __init__(self, interval): + self.wrap(interval) + self.growth = 0 + + def __hash__(self): + return hash((self.start, self.center, self.end)) + + def __eq__(self, other): + return (self.start, self.center, self.end) == (other.start, other.center, other.end) + + def wrap(self, interval): + """"""Updates the internal state of the interval to wrap + + Parameters + ---------- + interval : NeutralMassDatabase + The new collection to wrap. + """""" + self.group = interval + try: + self.start = interval.lowest_mass + self.end = interval.highest_mass + except IndexError: + self.start = 0 + self.end = 0 + self.center = (self.start + self.end) / 2. + self.size = len(self.group) + + def __repr__(self): + return ""%s(%0.4f, %0.4f, %r)"" % ( + self.__class__.__name__, + self.start, self.end, len(self.group) if self.group is not None else 0) + + def _combine_databases(self, current_group, new_group): + return current_group.merge(new_group, operator.attrgetter('id')) + + def extend(self, new_data): + """"""Add the components of `new_data` to `group` and update + the interval's internal state + + Parameters + ---------- + new_data : MassIntervalNode + Iterable of massable objects + """""" + start = min(self.start, new_data.start) + end = max(self.end, new_data.end) + + self.wrap(self._combine_databases(self.group, new_data.group)) + self.growth += 1 + + # max will deal with 0s correctly + self.end = max(end, self.end) + # min will prefer 0 and not behave as expected + if start != 0 and self.start != 0: + self.start = min(start, self.start) + elif start != 0: + # self.start is 0 + self.start = start + # otherwise they're both 0 and we are out of luck + + def __iter__(self): + return iter(self.group) + + def __getitem__(self, i): + return self.group[i] + + def __len__(self): + return len(self.group) + + def search_mass(self, *args, **kwargs): + """"""A proxy for :meth:`NeutralMassDatabase.search_mass` + """""" + return self.group.search_mass(*args, **kwargs) + + def search_mass_ppm(self, *args, **kwargs): + return self.group.search_mass_ppm(*args, **kwargs) + + def constrain(self, lower, higher): + subset = self.group.search_between(lower, higher) + start = max(lower, self.start) + end = min(higher, self.end) + self.wrap(subset) + self.end = end + self.start = start + return self + + +class ConcatenateMassIntervalNode(MassIntervalNode): + + def _combine_databases(self, current_group, new_group): + if isinstance(current_group, ConcatenatedDatabase): + return current_group.add(new_group) + return ConcatenatedDatabase([current_group, new_group]) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/glycan_composition_filter.py",".py","6558","231","''' +Usage: + list_of_db_glycans = get_db_glycans() + gcf = GlycanCompositionFilter(list_of_db_glycans) + index = InclusionFilter(gcf.query(""Fuc"", 1, 3).add(""HexNAc"", 4, 6).add(""Neu5Ac"", 0, 2)) + id_of_interest = 5 + print(5 in index) +''' +from collections import defaultdict, Counter + + +class FilterTreeNode(object): + def __init__(self, members=None): + if members is None: + members = [] + self.members = members + self.children = defaultdict(FilterTreeNode) + self.splitting_key = None + self.split_value = None + + def add(self, member): + self.members.append(member) + + def split_on(self, key): + if self.splitting_key is not None: + raise ValueError(""Already split node"") + for member in self.members: + self.children[member[key]].add(member) + + self.splitting_key = key + for key, child in self.children.items(): + child.split_value = key + + def split_sequence(self, key_sequence): + if len(key_sequence) == 0: + return + key = key_sequence[0] + self.split_on(key) + for child in self.children.values(): + child.split_sequence(key_sequence[1:]) + + def __repr__(self): + return ""FilterTreeNode(%d, %r, ^%r, %d)"" % ( + len(self.members), self.splitting_key, + self.split_value, len(self.children)) + + def query(self, key, lo=0, hi=100): + if str(key) == str(self.splitting_key): + result_set = [] + hi = min(max(self.children.keys()), hi) + for i in range(lo, hi + 1): + result_set.append(self.children[i]) + return QuerySet(result_set) + else: + out = [] + for child in self.children.values(): + out.append(child.query(key, lo, hi)) + return QuerySet.union(out) + + def __iter__(self): + if len(self.children) == 0: + for member in self.members: + yield member + else: + for child in self.children.values(): + for item in child: + yield item + + +class QuerySet(object): + def __init__(self, node_list): + self.node_list = node_list + + def __iter__(self): + for node in self.node_list: + for item in node: + yield item + + def query(self, key, lo=0, hi=100): + out = [] + for node in self.node_list: + out.append(node.query(key, lo, hi)) + return QuerySet.union(out) + + @classmethod + def union(cls, queries): + node_list = [] + for q in queries: + node_list.extend(q.node_list) + return cls(node_list) + + @classmethod + def intersect(cls, queries): + item_map = {} + member_map = Counter() + for q in queries: + for item in q: + item_map[item.id] = item + member_map[item.id] += 1 + n = len(queries) + out = [] + for key, value in member_map.items(): + if value == n: + out.append(item_map[key]) + return out + + +class QueryInterval(object): + def __init__(self, key, low=0, high=100): + self.key = str(key) + self.low = low + self.high = high + + def __repr__(self): + return ""QueryInterval(%r, %d, %d)"" % (self.key, self.low, self.high) + + def __iter__(self): + yield self.key + yield self.low + yield self.high + + def __eq__(self, other): + return (self.key == other.key and self.low == other.low and self.high == other.high) + + def __ne__(self, other): + return not (self == other) + + +class QueryComposer(object): + def __init__(self, parent): + self.parent = parent + self.filters = [] + + def __call__(self, filter_spec_or_key, lo=0, hi=100): + if isinstance(filter_spec_or_key, QueryInterval): + self.filters.append(filter_spec_or_key) + else: + self.filters.append(QueryInterval(filter_spec_or_key, lo, hi)) + return self + + def add(self, *args, **kwargs): + self(*args, **kwargs) + return self + + def collate(self): + monosaccharides = list(map(str, self.parent.monosaccharides)) + filters = sorted(self.filters, key=lambda x: str(x.key)) + kept_filters = [] + for filt in filters: + if filt.key in monosaccharides: + kept_filters.append(filt) + return kept_filters + + def __eq__(self, other): + if isinstance(other, QueryComposer): + return self.collate() == other.collate() + else: + return self.collate() == other + + def __ne__(self, other): + return not (self == other) + + def all(self): + return list(self._compose()) + + def _compose(self): + query = None + for filt in self.collate(): + if query is None: + query = self.parent.root.query(*filt) + else: + query = query.query(*filt) + if query is None: + return self.parent + return query + + def __iter__(self): + return iter(self._compose()) + + +class GlycanCompositionFilter(object): + def __init__(self, members): + self.members = members + self.monosaccharides = list() + self._extract_monosaccharides(members) + self.root = FilterTreeNode(members) + self._build_partitions() + + def _extract_monosaccharides(self, iterable): + monosaccharides = set() + for case in iterable: + monosaccharides.update(case.keys()) + self.monosaccharides = sorted(monosaccharides, key=str) + + def _build_partitions(self): + self.root.split_sequence(self.monosaccharides) + + def query(self, *args, **kwargs): + compose = QueryComposer(self) + return compose(*args, **kwargs) + + def filter_index(self, *args, **kwargs): + query_set = self.query(*args, **kwargs) + return InclusionFilter(query_set) + + def __iter__(self): + return iter(self.members) + + +class InclusionFilter(object): + def __init__(self, query_set): + self.query_set = query_set + self.hash_index = set() + self._build_index() + + def _build_index(self): + for case in self.query_set: + self.hash_index.add(case.id) + + def __repr__(self): + return ""InclusionFilter()"" + + def contains_all(self, keys): + for key in keys: + if key not in self: + return False + return True + + def __contains__(self, key): + return key in self.hash_index +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/composition_network/neighborhood.py",".py","14138","376","import numbers as abc_numbers +from typing import Callable, Dict, Iterable, List, Optional, OrderedDict, DefaultDict as defaultdict, TYPE_CHECKING, Set, Tuple + +import numpy as np + +from glypy.structure.glycan_composition import FrozenMonosaccharideResidue, HashableGlycanComposition + +from ..glycan_composition_filter import GlycanCompositionFilter +from ... import symbolic_expression + +from .space import CompositionSpace, n_glycan_distance +from .rule import CompositionExpressionRule, CompositionRangeRule, CompositionRuleClassifier + +if TYPE_CHECKING: + from glycresoft.database.composition_network import CompositionGraph, CompositionGraphNode + + +class NeighborhoodCollection(object): + neighborhoods: OrderedDict[str, CompositionRuleClassifier] + + def __init__(self, neighborhoods=None): + if neighborhoods is None: + neighborhoods = OrderedDict() + self.neighborhoods = OrderedDict() + if isinstance(neighborhoods, (dict)): + self.neighborhoods = OrderedDict(neighborhoods) + else: + for item in neighborhoods: + self.add(item) + + def add(self, classifier: CompositionRuleClassifier): + self.neighborhoods[classifier.name] = classifier + + def remove(self, key: str): + return self.neighborhoods.pop(key) + + def update(self, iterable: Iterable[CompositionRuleClassifier]): + for case in iterable: + self.add(case) + + def clear(self): + self.neighborhoods.clear() + + def copy(self): + return self.__class__(self.neighborhoods) + + clone = copy + + def __iter__(self): + return iter(self.neighborhoods.values()) + + def __repr__(self): + return ""NeighborhoodCollection(%s)"" % (', '.join(self.neighborhoods.keys())) + + def __eq__(self, other): + return list(self) == list(other) + + def __ne__(self, other): + return not (self == other) + + def get_neighborhood(self, key: str) -> CompositionRuleClassifier: + return self.neighborhoods[key] + + def __getitem__(self, key): + try: + return self.get_neighborhood(key) + except KeyError: + if isinstance(key, abc_numbers.Number): + return tuple(self.neighborhoods.values())[key] + else: + raise + + def __len__(self): + return len(self.neighborhoods) + + +def make_n_glycan_neighborhoods() -> NeighborhoodCollection: + """"""Create broad N-glycan neighborhoods. + + This method is primarily designed for human-like N-glycan biosynthesis and does + not deal well with abundant Gal-alpha Gal or LacDiNAc extensions. + + Returns + ------- + NeighborhoodCollection + """""" + neighborhoods = NeighborhoodCollection() + + _neuraminic = ""(%s)"" % ' + '.join(map(str, ( + FrozenMonosaccharideResidue.from_iupac_lite(""NeuAc""), + FrozenMonosaccharideResidue.from_iupac_lite(""NeuGc"") + ))) + _hexose = ""(%s)"" % ' + '.join( + map(str, map(FrozenMonosaccharideResidue.from_iupac_lite, ['Hex', ]))) + _hexnac = ""(%s)"" % ' + '.join( + map(str, map(FrozenMonosaccharideResidue.from_iupac_lite, ['HexNAc', ]))) + + high_mannose = CompositionRangeRule( + _hexose, 3, 12) & CompositionRangeRule( + _hexnac, 2, 2) & CompositionRangeRule( + _neuraminic, 0, 0) + high_mannose.name = ""high-mannose"" + neighborhoods.add(high_mannose) + + base_hexnac = 3 + base_neuac = 2 + for i, spec in enumerate(['hybrid', 'bi', 'tri', 'tetra', 'penta', ""hexa"", ""hepta""]): + if i == 0: + rule = CompositionRangeRule( + _hexnac, base_hexnac - 1, base_hexnac + 1 + ) & CompositionRangeRule( + _neuraminic, 0, base_neuac) & CompositionRangeRule( + _hexose, base_hexnac + i - 1, + base_hexnac + i + 3) + rule.name = spec + neighborhoods.add(rule) + else: + sialo = CompositionRangeRule( + _hexnac, base_hexnac + i - 1, base_hexnac + i + 1 + ) & CompositionRangeRule( + _neuraminic, 1, base_neuac + i + ) & CompositionRangeRule( + _hexose, base_hexnac + i - 1, + base_hexnac + i + 2) + + sialo.name = ""%s-antennary"" % spec + asialo = CompositionRangeRule( + _hexnac, base_hexnac + i - 1, base_hexnac + i + 1 + ) & CompositionRangeRule( + _neuraminic, 0, 1 if i < 2 else 0 + ) & CompositionRangeRule( + _hexose, base_hexnac + i - 1, + base_hexnac + i + 2) + + asialo.name = ""asialo-%s-antennary"" % spec + neighborhoods.add(sialo) + neighborhoods.add(asialo) + return neighborhoods + + +def make_mammalian_n_glycan_neighborhoods() -> NeighborhoodCollection: + """"""Create broad N-glycan neighborhoods allowing for mammalian N-glycans. + + This method deals with N-glycosyltransferases not found in humans (specifically Gal-alpha Gal) + which skew the boundaries between neighborhoods on the Hexose dimension. :func:`make_n_glycan_neighborhoods` + already handles NeuGc trivially. + + Returns + ------- + NeighborhoodCollection + """""" + neighborhoods = NeighborhoodCollection() + + _neuraminic = ""(%s)"" % ' + '.join(map(str, ( + FrozenMonosaccharideResidue.from_iupac_lite(""NeuAc""), + FrozenMonosaccharideResidue.from_iupac_lite(""NeuGc"") + ))) + _terminal = _neuraminic + \ + "" + max(%s - %%d, 0)"" % FrozenMonosaccharideResidue.from_iupac_lite(""Hex"") + _hexose = ""(%s)"" % ' + '.join( + map(str, map(FrozenMonosaccharideResidue.from_iupac_lite, ['Hex', ]))) + _hexnac = ""(%s)"" % ' + '.join( + map(str, map(FrozenMonosaccharideResidue.from_iupac_lite, ['HexNAc', ]))) + + high_mannose = CompositionRangeRule( + _hexose, 3, 12) & CompositionRangeRule( + _hexnac, 2, 2) & CompositionRangeRule( + _neuraminic, 0, 0) + high_mannose.name = ""high-mannose"" + neighborhoods.add(high_mannose) + + base_hexnac = 3 + base_terminal_groups = 2 + for i, spec in enumerate(['hybrid', 'bi', 'tri', 'tetra', 'penta', ""hexa"", ""hepta""]): + if spec == 'hybrid': + rule = CompositionRangeRule( + _hexnac, base_hexnac - 1, base_hexnac + 1 + ) & CompositionRangeRule( + _neuraminic, 0, base_terminal_groups) & CompositionRangeRule( + _hexose, base_hexnac + i - 1, + base_hexnac + i + 3) + rule.name = spec + neighborhoods.add(rule) + else: + sialo = CompositionRangeRule( + _hexnac, base_hexnac + i - 1, base_hexnac + i + 1 + ) & CompositionRangeRule( + (_neuraminic), 1, base_terminal_groups + i + ) & CompositionExpressionRule( + ""(Hex > %d) & (Hex < (%d - (NeuAc + NeuGc)))"" % (base_hexnac + i - 2, base_hexnac + (2 * i) + 3)) + + sialo.name = ""%s-antennary"" % spec + asialo = CompositionRangeRule( + _hexnac, base_hexnac + i - 1, base_hexnac + i + 1 + ) & CompositionRangeRule( + _neuraminic, 0, 1 if i < 2 else 0 + ) & CompositionRangeRule( + _hexose, base_hexnac + i - 1, + base_hexnac + (2 * i) + 3) + asialo.name = ""asialo-%s-antennary"" % spec + neighborhoods.add(sialo) + neighborhoods.add(asialo) + return neighborhoods + + +def make_adjacency_neighborhoods(network: ""CompositionGraph""): + space = CompositionSpace([node.composition for node in network]) + + rules = [] + for node in network: + terms = [] + for monosaccharide in space.monosaccharides: + terms.append((""abs({} - {})"".format( + monosaccharide, node.composition[monosaccharide]))) + expr = '(%s) < 2' % (' + '.join(terms),) + expr_rule = CompositionExpressionRule(expr) + rule = CompositionRuleClassifier(str(node.composition), [expr_rule]) + rules.append(rule) + return rules + + +_n_glycan_neighborhoods = make_n_glycan_neighborhoods() + + +class NeighborhoodWalker(object): + network: ""CompositionGraph"" + neighborhoods: NeighborhoodCollection + distance_fn: Callable[[HashableGlycanComposition, HashableGlycanComposition], Tuple[int, float]] + + symbols: symbolic_expression.SymbolSpace + filter_space: GlycanCompositionFilter + + neighborhood_assignments: defaultdict[""CompositionGraphNode"", Set[str]] + neighborhood_maps: defaultdict[str, List[""CompositionGraphNode""]] + + def __init__(self, network, neighborhoods=None, assign=True, distance_fn=n_glycan_distance): + if neighborhoods is None: + if network.neighborhoods: + neighborhoods = NeighborhoodCollection(network.neighborhoods) + else: + neighborhoods = NeighborhoodCollection(_n_glycan_neighborhoods) + self.network = network + self.neighborhood_assignments = defaultdict(set) + self.neighborhoods = neighborhoods + self.distance_fn = distance_fn + self.filter_space = GlycanCompositionFilter( + [self.normalize_composition(node.composition) for node in self.network]) + + self.symbols = symbolic_expression.SymbolSpace(self.filter_space.monosaccharides) + + self.neighborhood_maps = defaultdict(list) + + if assign: + self.assign() + + def normalize_composition(self, composition): + return self.network.normalize_composition(composition) + + def _pack_maps(self): + key_neighborhood_assignments = defaultdict(set) + key_neighborhood_maps = defaultdict(list) + + for key, value in self.neighborhood_assignments.items(): + key_neighborhood_assignments[key.glycan_composition] = value + for key, value in self.neighborhood_maps.items(): + key_neighborhood_maps[key.glycan_composition] = value + return key_neighborhood_assignments, key_neighborhood_maps + + def _unpack_maps(self, packed_maps): + (key_neighborhood_assignments, key_neighborhood_maps) = packed_maps + + for key, value in key_neighborhood_assignments.items(): + self.neighborhood_assignments[self.network[key.glycan_composition]] = value + + for key, value in key_neighborhood_maps.items(): + self.neighborhood_maps[self.network[key.glycan_composition]] = value + + def __getstate__(self): + return self._pack_maps() + + def __setstate__(self, state): + self._unpack_maps(state) + + def __reduce__(self): + return self.__class__, (self.network, self.neighborhoods, False) + + def neighborhood_names(self): + return [n.name for n in self.neighborhoods] + + def __getitem__(self, key): + return self.neighborhood_assignments[key] + + def query_neighborhood(self, neighborhood: CompositionRuleClassifier): + query = None + filters = [] + for rule in neighborhood.rules: + if not self.symbols.partially_defined(rule.symbols): + continue + + filters.append(rule) + try: + low = rule.low + high = rule.high + except AttributeError: + continue + if low is None: + low = 0 + if high is None: + # No glycan will have more than 100 of a single residue + # in practice. + high = 100 + name = rule.symbols[0] + if query is None: + query = self.filter_space.query(name, low, high) + else: + query.add(name, low, high) + if filters: + query = filter(lambda x: all([f(x) for f in filters]), query) + else: + query = query.all() + return query + + def assign(self): + for neighborhood in self.neighborhoods: + query = self.query_neighborhood(neighborhood) + if query is None: + raise ValueError(""Query cannot be None! %r"" % neighborhood) + for composition in query: + composition = self.normalize_composition(composition) + if neighborhood(composition): + self.neighborhood_assignments[ + self.network[composition]].add(neighborhood.name) + for node in self.network: + for neighborhood in self[node]: + self.neighborhood_maps[neighborhood].append(node) + + def compute_belongingness(self, node: ""CompositionGraphNode"", neighborhood: CompositionRuleClassifier, + distance_cache: Optional[Dict]=None) -> float: + count = 0 + total_weight = 0 + distance_fn = self.distance_fn + for member in self.neighborhood_maps[neighborhood]: + if distance_cache is None: + distance, weight = distance_fn(node.glycan_composition, member.glycan_composition) + else: + # assumes that distance is symmetric + key = (node.index, member.index) if node.index < member.index else (member.index, node.index) + try: + distance, weight = distance_cache[key] + except KeyError: + distance, weight = distance_fn(node.glycan_composition, member.glycan_composition) + distance_cache[key] = distance, weight + + if distance == 0: + weight = 1.0 + total_weight += weight + count += 1 + if count == 0: + return 0 + return total_weight / count + + def build_belongingness_matrix(self) -> np.ndarray: + neighborhood_count = len(self.neighborhoods) + belongingness_matrix = np.zeros( + (len(self.network), neighborhood_count)) + + distance_cache = dict() + + for node in self.network: + was_in = self.neighborhood_assignments[node] + for i, neighborhood in enumerate(self.neighborhoods): + if neighborhood.name in was_in: + belongingness_matrix[node.index, i] = self.compute_belongingness( + node, neighborhood.name, distance_cache=distance_cache) + return belongingness_matrix +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/composition_network/space.py",".py","3411","106","from glypy.structure.glycan_composition import FrozenMonosaccharideResidue, HashableGlycanComposition + +from glycresoft.database.glycan_composition_filter import GlycanCompositionFilter + +from typing import List, Tuple + +_hexose = FrozenMonosaccharideResidue.from_iupac_lite(""Hex"") +_hexnac = FrozenMonosaccharideResidue.from_iupac_lite(""HexNAc"") + + +def composition_distance(c1: HashableGlycanComposition, c2: HashableGlycanComposition) -> Tuple[int, float]: + """"""N-Dimensional Manhattan Distance or L1 Norm"""""" + keys = set(c1) | set(c2) + distance = 0.0 + try: + c1_get = c1._getitem_fast + c2_get = c2._getitem_fast + except AttributeError: + c1_get = c1.__getitem__ + c2_get = c2.__getitem__ + for k in keys: + distance += abs(c1_get(k) - c2_get(k)) + return int(distance), 1 / distance if distance > 0 else 1 + + +# Old alias +n_glycan_distance = composition_distance + + +class CompositionSpace(object): + filter: GlycanCompositionFilter + + def __init__(self, members): + self.filter = GlycanCompositionFilter(members) + + @property + def monosaccharides(self): + return self.filter.monosaccharides + + def find_narrowly_related(self, composition: HashableGlycanComposition, window: int=1) -> List: + partitions = [] + for i in range(len(self.monosaccharides)): + j = 0 + m = self.monosaccharides[j] + if i == j: + q = self.filter.query( + m, composition[m] - window, composition[m] + window) + else: + q = self.filter.query( + m, composition[m], composition[m]) + for m in self.monosaccharides[1:]: + j += 1 + center = composition[m] + if j == i: + q.add(m, center - window, center + window) + else: + q.add(m, center, center) + partitions.append(q) + out = set() + for case in partitions: + out.update(case) + return out + + def l1_distance(self, c1, c2): + keys = set(c1) | set(c2) + distance = 0 + for k in keys: + distance += abs(c1[k] - c2[k]) + return distance + + def find_related_broad(self, composition, window=1): + m = self.monosaccharides[0] + q = self.filter.query( + m, composition[m] - window, composition[m] + window) + for m in self.monosaccharides[1:]: + center = composition[m] + q.add(m, center - window, center + window) + return q.all() + + def find_related(self, composition, window=1): + if window == 1: + return self.find_narrowly_related(composition, window) + candidates = self.find_related_broad(composition, window) + out = [] + for case in candidates: + if self.l1_distance(composition, case) <= window: + out.append(case) + return out + + +class DistanceCache(object): + '''A caching wrapper around a distance function (e.g. composition_distance). + ''' + def __init__(self, distance_function): + self.distance_function = distance_function + self.cache = dict() + + def __call__(self, x, y): + key = frozenset((x, y)) + try: + return self.cache[key] + except KeyError: + d = self.distance_function(x, y) + self.cache[key] = d + return d +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/composition_network/__init__.py",".py","1212","30","from .space import (n_glycan_distance, composition_distance, CompositionSpace) + +from .rule import ( + CompositionRuleBase, CompositionExpressionRule, CompositionRangeRule, + CompositionRatioRule, CompositionRuleClassifier) + +from .neighborhood import ( + NeighborhoodCollection, NeighborhoodWalker, make_n_glycan_neighborhoods, + make_adjacency_neighborhoods, make_mammalian_n_glycan_neighborhoods) + +from .graph import ( + CompositionNormalizer, CompositionGraph, CompositionGraphNode, + CompositionGraphEdge, EdgeSet, DijkstraPathFinder, + GraphReader, GraphWriter, dump, load, normalize_composition) + +__all__ = [ + ""n_glycan_distance"", ""composition_distance"", ""CompositionSpace"", + + ""CompositionRuleBase"", ""CompositionExpressionRule"", ""CompositionRangeRule"", + ""CompositionRatioRule"", ""CompositionRuleClassifier"", + + ""NeighborhoodCollection"", ""NeighborhoodWalker"", ""make_n_glycan_neighborhoods"", + ""make_adjacency_neighborhoods"", ""make_mammalian_n_glycan_neighborhoods"", + + ""CompositionNormalizer"", ""CompositionGraph"", ""CompositionGraphNode"", + ""CompositionGraphEdge"", ""EdgeSet"", ""DijkstraPathFinder"", + ""GraphReader"", ""GraphWriter"", ""dump"", + ""load"", ""normalize_composition"", +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/composition_network/rule.py",".py","9288","294","from io import StringIO +from typing import Union, Protocol + +from glycopeptidepy import HashableGlycanComposition +from glycopeptidepy.utils import simple_repr + +from glycresoft import symbolic_expression + + +class HasGlycanComposition(Protocol): + glycan_composition: HashableGlycanComposition + + +AsGlycanComposition = Union[HashableGlycanComposition, str, HasGlycanComposition] + + +class CompositionRuleBase(object): + + __repr__ = simple_repr + + def __call__(self, obj: AsGlycanComposition) -> bool: + raise NotImplementedError() + + def get_composition(self, obj: AsGlycanComposition) -> symbolic_expression.GlycanSymbolContext: + try: + composition = obj.glycan_composition + except AttributeError: + composition = HashableGlycanComposition.parse(obj) + composition = symbolic_expression.GlycanSymbolContext(composition) + return composition + + def __and__(self, other): + if isinstance(other, CompositionRuleClassifier): + other = other.copy() + other.rules.append(self) + return other + else: + return CompositionRuleClassifier(None, [self, other]) + + def get_symbols(self): + raise NotImplementedError() + + @property + def symbols(self): + return self.get_symbols() + + def is_univariate(self): + return len(self.get_symbols()) == 1 + + def serialize(self): + raise NotImplementedError() + + @classmethod + def parse(cls, line, handle=None): + raise NotImplementedError() + + +def int_or_none(x): + try: + return int(x) + except ValueError: + return None + + +class CompositionExpressionRule(CompositionRuleBase): + def __init__(self, expression, required=True): + self.expression = symbolic_expression.ExpressionNode.parse(str(expression)) + self.required = required + + def get_symbols(self): + return self.expression.get_symbols() + + def __call__(self, obj): + composition = self.get_composition(obj) + if composition.partially_defined(self.expression): + return composition[self.expression] + else: + if self.required: + return False + else: + return True + + def serialize(self): + tokens = [""CompositionExpressionRule"", str(self.expression), + str(self.required)] + return '\t'.join(tokens) + + @classmethod + def parse(cls, line, handle=None): + tokens = line.strip().split(""\t"") + n = len(tokens) + i = 0 + while tokens[i] != ""CompositionExpressionRule"" and i < n: + i += 1 + i += 1 + if i >= n: + raise ValueError(""Coult not parse %r with %s"" % (line, cls)) + expr = symbolic_expression.parse_expression(tokens[i]) + required = tokens[i + 1].lower() in ('true', 'yes', '1') + return cls(expr, required) + + def __repr__(self): + template = ""{self.__class__.__name__}(expression={self.expression}, required={self.required})"" + return template.format(self=self) + + +class CompositionRangeRule(CompositionRuleBase): + + def __init__(self, expression, low=None, high=None, required=True): + self.expression = symbolic_expression.ExpressionNode.parse(str(expression)) + self.low = low + self.high = high + self.required = required + + def __repr__(self): + template = \ + (""{self.__class__.__name__}(expression={self.expression}, "" + ""low={self.low}, high={self.high}, required={self.required})"") + return template.format(self=self) + + def get_symbols(self): + return self.expression.get_symbols() + + def __call__(self, obj: AsGlycanComposition) -> bool: + composition = self.get_composition(obj) + if composition.partially_defined(self.expression): + if self.low is None: + return composition[self.expression] <= self.high + elif self.high is None: + return self.low <= composition[self.expression] + return self.low <= composition[self.expression] <= self.high + else: + if self.required and self.low > 0: + return False + else: + return True + + def serialize(self): + tokens = [""CompositionRangeRule"", str(self.expression), str(self.low), + str(self.high), str(self.required)] + return '\t'.join(tokens) + + @classmethod + def parse(cls, line, handle=None): + tokens = line.strip().split(""\t"") + n = len(tokens) + i = 0 + while tokens[i] != ""CompositionRangeRule"" and i < n: + i += 1 + i += 1 + if i >= n: + raise ValueError(""Coult not parse %r with %s"" % (line, cls)) + expr = symbolic_expression.parse_expression(tokens[i]) + low = int_or_none(tokens[i + 1]) + high = int_or_none(tokens[i + 2]) + required = tokens[i + 3].lower() in ('true', 'yes', '1') + return cls(expr, low, high, required) + + +class CompositionRatioRule(CompositionRuleBase): + def __init__(self, numerator, denominator, ratio_threshold, required=True): + self.numerator = numerator + self.denominator = denominator + self.ratio_threshold = ratio_threshold + self.required = required + + def __repr__(self): + template = \ + (""{self.__class__.__name__}(numerator={self.numerator}, "" + ""denominator={self.denominator}, ratio_threshold={self.ratio_threshold}, "" + ""required={self.required})"") + return template.format(self=self) + + def _test(self, x): + if isinstance(self.ratio_threshold, (tuple, list)): + return self.ratio_threshold[0] <= x < self.ratio_threshold[1] + else: + return x >= self.ratio_threshold + + def get_symbols(self): + return (self.numerator, self.denominator) + + def __call__(self, obj: AsGlycanComposition) -> bool: + composition = self.get_composition(obj) + val = composition[self.numerator] + ref = composition[self.denominator] + + if ref == 0 and self.required: + return False + else: + ratio = val / float(ref) + return self._test(ratio) + + def serialize(self): + tokens = [""CompositionRatioRule"", str(self.numerator), str(self.denominator), + str(self.ratio_threshold), str(self.required)] + return '\t'.join(tokens) + + @classmethod + def parse(cls, line, handle=None): + tokens = line.strip().split(""\t"") + n = len(tokens) + i = 0 + while tokens[i] != ""CompositionRatioRule"" and i < n: + i += 1 + i += 1 + numerator = symbolic_expression.parse_expression(tokens[i]) + denominator = symbolic_expression.parse_expression(tokens[i + 1]) + ratio_threshold = float(tokens[i + 2]) + required = tokens[i + 3].lower() in ('true', 'yes', '1') + return cls(numerator, denominator, ratio_threshold, required) + + +class CompositionRuleClassifier(object): + + def __init__(self, name, rules): + self.name = name + self.rules = rules + + def __iter__(self): + return iter(self.rules) + + def __call__(self, obj: AsGlycanComposition) -> bool: + for rule in self: + if not rule(obj): + return False + return True + + def __eq__(self, other): + try: + return self.name == other.name + except AttributeError: + return self.name == other + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash(self.name) + + __repr__ = simple_repr + + def copy(self): + return CompositionRuleClassifier(self.name, list(self.rules)) + + def __and__(self, other): + if isinstance(other, CompositionRuleClassifier): + other = other.copy() + other.rules.extend(self.rules) + return other + else: + self = self.copy() + self.rules.append(other) + return self + + def get_symbols(self): + symbols = set() + for rule in self: + symbols.update(rule.symbols) + return symbols + + @property + def symbols(self): + return self.get_symbols() + + def serialize(self): + text_buffer = StringIO() + text_buffer.write(""CompositionRuleClassifier\t%s\n"" % (self.name,)) + for rule in self: + text = rule.serialize() + text_buffer.write(""\t%s\n"" % (text,)) + text_buffer.seek(0) + return text_buffer.read() + + @classmethod + def parse(cls, lines): + line = lines[0] + name = line.strip().split(""\t"")[1] + rules = [] + for line in lines[1:]: + if line == """": + continue + rule_type = line.split(""\t"")[0] + if rule_type == ""CompositionRangeRule"": + rule = CompositionRangeRule.parse(line) + elif rule_type == ""CompositionRatioRule"": + rule = CompositionRatioRule.parse(line) + elif rule_type == ""CompositionExpressionRule"": + rule = CompositionExpressionRule.parse(line) + else: + raise ValueError(""Unrecognized Rule Type: %r"" % (line,)) + rules.append(rule) + return cls(name, rules) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/composition_network/graph.py",".py","26649","790","import numbers as abc_numbers +from io import StringIO +from collections import defaultdict, deque +from typing import Callable, Dict, List, Optional, Tuple, Union + +import numpy as np + +from glypy.composition import composition_transform +from glypy.structure.glycan_composition import FrozenMonosaccharideResidue, GlycanComposition + + +from glycopeptidepy import HashableGlycanComposition +from glycopeptidepy.structure.glycan import GlycanCompositionProxy + +from glycresoft import symbolic_expression + +from .space import (n_glycan_distance, composition_distance, CompositionSpace) +from .neighborhood import NeighborhoodCollection +from .rule import CompositionRuleClassifier + + +_hexose = FrozenMonosaccharideResidue.from_iupac_lite(""Hex"") +_hexnac = FrozenMonosaccharideResidue.from_iupac_lite(""HexNAc"") + + +class CompositionNormalizer(object): + cache: Dict[HashableGlycanComposition, HashableGlycanComposition] + + def __init__(self, cache=None): + if cache is None: + cache = dict() + self.cache = cache + + def _normalize_key(self, key: Union[str, GlycanCompositionProxy, GlycanComposition]) -> HashableGlycanComposition: + if isinstance(key, str): + key = HashableGlycanComposition.parse(key) + return HashableGlycanComposition( + {self._normalize_monosaccharide(k): v for k, v in key.items()}) + + def _normalize_monosaccharide(self, key): + is_derivatized = composition_transform.has_derivatization(key) + if is_derivatized: + key = key.copy_underivatized() + return key + + def _get_solution(self, key: Union[HashableGlycanComposition, str, + GlycanComposition, GlycanCompositionProxy]) -> HashableGlycanComposition: + if isinstance(key, (str, HashableGlycanComposition)): + try: + return self.cache[key] + except KeyError: + result = self._normalize_key(key) + self.cache[key] = result + return result + else: + return self._normalize_key(key) + + def normalize_composition(self, c): + return self._get_solution(c) + + def __call__(self, c): + return self.normalize_composition(c) + + def copy(self): + return self.__class__(self.cache.copy()) + + +normalize_composition = CompositionNormalizer() + + +class DijkstraPathFinder(object): + + def __init__(self, graph, start, end, limit=float('inf')): + self.graph = graph + self.start = start + self.end = end + self.distance = defaultdict(lambda: float('inf')) + self.distance[start._str] = 0 + self.unvisited_finite_distance = dict() + self.limit = limit + + def find_smallest_unvisited(self, unvisited): + smallest_distance = float('inf') + smallest_node = None + + if not self.unvisited_finite_distance: + iterable = [(k, self.distance[k]) for k in unvisited] + else: + iterable = self.unvisited_finite_distance.items() + + for node, distance in iterable: + if distance <= smallest_distance: + smallest_distance = distance + smallest_node = node + return self.graph[smallest_node] + + def find_path(self): + unvisited = set([node._str for node in self.graph]) + + visit_queue = deque([self.start]) + while self.end._str in unvisited: + try: + current_node = visit_queue.popleft() + except IndexError: + current_node = self.find_smallest_unvisited(unvisited) + try: + unvisited.remove(current_node._str) + except KeyError: + continue + try: + self.unvisited_finite_distance.pop(current_node._str) + except KeyError: + pass + edges = current_node.edges + for edge in edges: + terminal = edge._traverse(current_node) + if terminal._str not in unvisited: + continue + path_length = self.distance[current_node._str] + edge.order + terminal_distance = self.distance[terminal._str] + if terminal_distance > path_length: + self.distance[terminal._str] = path_length + if terminal._str in unvisited and terminal_distance < self.limit: + self.unvisited_finite_distance[ + terminal._str] = path_length + if terminal_distance < self.limit: + visit_queue.append(terminal) + + def search(self): + self.find_path() + return self.distance[self.end._str] + + +try: + _has_c = True + from glycresoft._c.composition_network.graph import DijkstraPathFinder +except ImportError: + _has_c = False + +class CompositionGraphNode(object): + composition: HashableGlycanComposition + index: int + _score: float + marked: bool + edges: 'EdgeSet' + _str: str + _hash: int + internal_score: float + + __slots__ = ( + ""composition"", ""index"", ""_score"", ""marked"", ""edges"", ""_str"", ""_hash"", ""internal_score"") + + def __init__(self, composition, index, score=0., marked=False, **kwargs): + self.composition = composition + self.index = index + self.edges = EdgeSet() + self._str = str(self.composition) + self._hash = hash(str(self._str)) + self._score = score + self.internal_score = 0.0 + self.marked = marked + + @property + def glycan_composition(self): + return self.composition + + @property + def order(self): + return len(self.edges) + + @property + def score(self): + if self._score == 0: + return self.internal_score + else: + return self._score + + @score.setter + def score(self, value): + self._score = value + + def edge_to(self, node): + return self.edges.edge_to(self, node) + + def neighbors(self): + result = [edge._traverse(self) for edge in self.edges] + return result + + def __eq__(self, other): + try: + return (self)._str == str(other) + except AttributeError: + return str(self) == str(other) + + def __str__(self): + return self._str + + def __hash__(self): + return self._hash + + def __repr__(self): + return ""CompositionGraphNode(%s, %d, %0.2f)"" % ( + self._str, int(self.index) if self.index is not None else -1, + self.score if self.score != 0 else self.internal_score) + + def copy(self): + dup = CompositionGraphNode(self.composition, self.index, self.score) + dup.internal_score = self.internal_score + return dup + + def clone(self): + return self.copy() + + +class EdgeSet(object): + store: Dict[Tuple[CompositionGraphNode, CompositionGraphNode], 'CompositionGraphEdge'] + + def __init__(self, store=None): + if store is None: + store = dict() + self.store = store + + def edge_to(self, node1, node2): + if node2.index < node1.index: + node1, node2 = node2, node1 + return self.store[node1, node2] + + def add(self, edge): + self.store[edge.node1, edge.node2] = edge + + def add_if_shorter(self, edge): + try: + prev = self.store[edge.node1, edge.node2] + if prev.order < edge.order: + return False + else: + self.store[edge.node1, edge.node2] = edge + return True + except KeyError: + self.store[edge.node1, edge.node2] = edge + return True + + def remove(self, edge): + self.store.pop((edge.node1, edge.node2)) + + def __iter__(self): + return iter(self.store.values()) + + def __len__(self): + return len(self.store) + + def __repr__(self): + return str(set(self.store.values())) + + def __eq__(self, other): + return self.store == other.store + + +class CompositionGraphEdge(object): + __slots__ = [""node1"", ""node2"", ""order"", ""weight"", ""_hash"", ""_str""] + + node1: CompositionGraphNode + node2: CompositionGraphNode + order: int + weight: float + _hash: int + _str: str + + def __init__(self, node1, node2, order, weight=1.0): + self.node1 = node1 + self.node2 = node2 + self.order = order if order > 0 else 1 + self.weight = weight + self._hash = hash((node1, node2, order)) + self._str = ""(%s)"" % ', '.join(map(str, (node1, node2, order))) + + node1.edges.add_if_shorter(self) + node2.edges.add_if_shorter(self) + + def __getitem__(self, key): + str_key = str(key) + if str_key == self.node1._str: + return self.node2 + elif str_key == self.node2._str: + return self.node1 + else: + raise KeyError(key) + + def _traverse(self, node): + return self.node1 if node is self.node2 else self.node2 + + def __eq__(self, other): + return self._str == other._str + + def __str__(self): + return self._str + + def __repr__(self): + return self._str + + def __hash__(self): + return self._hash + + def __reduce__(self): + return self.__class__, (self.node1, self.node2, self.order, self.weight) + + def copy_for(self, node1, node2): + return self.__class__(node1, node2, self.order, self.weight) + + def remove(self): + try: + self.node1.edges.remove(self) + except KeyError: + pass + try: + self.node2.edges.remove(self) + except KeyError: + pass + + +class CompositionGraphBase(object): + def copy(self): + graph = CompositionGraph([], self.distance_fn) + graph._composition_normalizer = self._composition_normalizer.copy() + for node in self.nodes: + graph.add_node(node.clone()) + for edge in self.edges: + n1 = graph.nodes[edge.node1.index] + n2 = graph.nodes[edge.node2.index] + e = edge.copy_for(n1, n2) + graph.edges.add(e) + graph.neighborhoods.update(self.neighborhoods.copy()) + return graph + + +try: + _has_c = True + from glycresoft._c.composition_network.graph import ( + CompositionGraphEdge, CompositionGraphNode, EdgeSet, CompositionGraphBase) +except ImportError: + _has_c = False + + +class CompositionGraph(CompositionGraphBase): + neighborhoods: NeighborhoodCollection + nodes: List[CompositionGraphNode] + node_map: Dict[HashableGlycanComposition, CompositionGraphNode] + _composition_normalizer: CompositionNormalizer + distance_fn: Callable[[HashableGlycanComposition, HashableGlycanComposition], Tuple[float, float]] + edges: EdgeSet + cache_state: Dict + + def __init__(self, compositions, distance_fn=n_glycan_distance, neighborhoods=None, cache_state: Optional[Dict]=None): + if neighborhoods is None: + neighborhoods = [] + if cache_state is None: + cache_state = {} + self.nodes = [] + self.node_map = {} + self._composition_normalizer = CompositionNormalizer() + self.distance_fn = distance_fn + self.create_nodes(compositions) + self.edges = EdgeSet() + self.neighborhoods = NeighborhoodCollection(neighborhoods) + self.cache_state = cache_state + + def create_nodes(self, compositions): + """"""Given an iterable of GlycanComposition-like or strings encoding GlycanComposition-like + objects construct nodes representing these compositions and add them to the graph. + + The order items appear in the list will affect their graph node's :attr:`index` attribute + and in turn affect their order in edges. For consistent behavior, order nodes by mass. + + Parameters + ---------- + compositions : Iterable + An iterable source of GlycanComposition-like objects + """""" + i = 0 + compositions = map(self.normalize_composition, compositions) + + for c in sorted(set(compositions), key=lambda x: (x.mass(), len(x))): + n = CompositionGraphNode(c, i) + self.add_node(n) + i += 1 + + def add_node(self, node: CompositionGraphNode, reindex=False): + """"""Given a CompositionGraphNode, add it to the graph. + + If `reindex` is `True` then a full re-indexing of the graph will + take place after the insertion is made. Otherwise it is assumed that + `node` is being added in index-specified order. + + Parameters + ---------- + node : CompositionGraphNode + The node to be added + """""" + key = str(self.normalize_composition(node.composition)) + if key in self.node_map: + raise ValueError(""Redundant composition!"") + self.nodes.append(node) + self.node_map[key] = node + + if reindex: + self._reindex() + return self + + def create_edges(self, distance=1, distance_fn=composition_distance): + """"""Traverse composition-space to find nodes similar to each other + and construct CompositionGraphEdges between them to represent that + similarity. + + Parameters + ---------- + distance : int, optional + The maximum dissimilarity between two nodes permitted + to allow the construction of an edge between them + distance_fn : callable, optional + A function to use to compute the bounded distance between two nodes + that are within `distance` of eachother in raw composition-space + """""" + if distance_fn is None: + distance_fn = self.distance_fn + space = CompositionSpace([node.composition for node in self]) + for node in self: + if node is None: + continue + for related in space.find_related(node.composition, distance): + related_node = self.node_map[str(related)] + # Ensures no duplicates assuming symmetric search window + if node.index < related_node.index: + diff, weight = distance_fn(node.composition, related) + e = CompositionGraphEdge(node, related_node, diff, weight) + self.edges.add(e) + return self + + def add_edge(self, node1: CompositionGraphNode, node2: CompositionGraphNode): + if node1.index > node2.index: + node1, node2 = node2, node1 + diff, weight = self.distance_fn(node1.composition, node2.composition) + e = CompositionGraphEdge(node1, node2, diff, weight) + self.edges.add(e) + + def remove_node(self, node: CompositionGraphNode, bridge: bool=True, limit: int=5, ignore_marked: bool=True): + """"""Removes the Glycan Composition given by `node` from the graph + and all edges connecting to it. This will reindex the graph. + + If two Glycan Compositions `x` and `y` are connected *through* `node`, + `bridge` is true, and the shortest path connecting `x` and + `y` is longer than the sum of the path from `x` to `node` and from `node` + to `y`, create a new edge connecting `x` and `y`, if the new edge is shorter + than `limit`. + + Parameters + ---------- + node : CompositionGraphNode-like + The node to be removed + bridge : bool, optional + Whether or not to create new edges + bridging neighbors + limit : int, optional + The maximum path length under which + to bridge neighbors + + Returns + ------- + list + The list of edges removed + """""" + node = self[node.glycan_composition] + subtracted_edges = list(node.edges) + for edge in subtracted_edges: + self.remove_edge(edge) + self.nodes.pop(node.index) + self.node_map.pop(str(node.composition)) + self._reindex() + + if bridge: + seen = set() + for edge in subtracted_edges: + for other_edge in subtracted_edges: + if edge == other_edge: + continue + node1 = edge._traverse(node) + node2 = other_edge._traverse(node) + if ignore_marked and (node1.marked or node2.marked): + continue + key = frozenset((node1.index, node2.index)) + if key in seen: + continue + seen.add(key) + old_distance = edge.order + other_edge.order + if old_distance >= limit: + continue + try: + if node1.edge_to(node2): + continue + except KeyError: + pass + path_finder = DijkstraPathFinder( + self, node1, node2, min(old_distance + 1, limit)) + shortest_path = path_finder.search() + + # The distance function may not be transitive, in which case, an ""edge through"" + # solution may not make sense. + # shortest_path = self.distance_fn(node1._composition, node2._composition)[0] + path_length = min(old_distance, shortest_path) + if path_length < limit: + if node1.index > node2.index: + node1, node2 = node2, node1 + new_edge = CompositionGraphEdge( + node1, node2, path_length, 1.) + self.edges.add_if_shorter(new_edge) + return subtracted_edges + + def remove_edge(self, edge: CompositionGraphEdge): + edge.remove() + self.edges.remove(edge) + + def _reindex(self): + i = 0 + for node in self: + node.index = i + i += 1 + + def normalize_composition(self, composition): + return self._composition_normalizer(composition) + + def __getitem__(self, key): + if isinstance(key, (str, GlycanComposition, GlycanCompositionProxy)): + key = self.normalize_composition(key) + return self.node_map[key] + # use the ABC Integral to catch all numerical types that could be used as an + # index including builtin int and long, as well as all the NumPy flavors of + # integers + elif isinstance(key, (abc_numbers.Integral, slice)): + return self.nodes[key] + else: + try: + result = [] + iter(key) + try: + if isinstance(key[0], (bool, np.bool_)): + for b, k in zip(key, self): + if b: + result.append(k) + else: + for k in key: + result.append(self[k]) + except TypeError: + # Handle unindexable iteratables + for k in key: + result.append(self[k]) + return result + except Exception as e: + if len(key) == 0: + return [] + raise IndexError( + ""An error occurred (%r) during indexing with %r"" % (e, key)) + + def __iter__(self): + return iter(self.nodes) + + def __len__(self): + return len(self.nodes) + + def __reduce__(self): + return self.__class__, ([], self.distance_fn), self.__getstate__() + + def __getstate__(self): + string_buffer = StringIO() + dump(self, string_buffer) + return string_buffer, self.distance_fn + + def __setstate__(self, state): + string_buffer, distance_fn = state + string_buffer.seek(0) + net, neighborhoods = load(string_buffer) + self.nodes = net.nodes + self.neighborhoods = NeighborhoodCollection(neighborhoods) + self.node_map = net.node_map + self.edges = net.edges + self.distance_fn = distance_fn + self._composition_normalizer = CompositionNormalizer() + + def __repr__(self): + return ""{self.__class__.__name__}({node_count} nodes, {edge_count} edges)"".format( + self=self, node_count=len(self), edge_count=len(self.edges)) + + def clone(self): + return self.copy() + + def __eq__(self, other): + try: + return self.nodes == other.nodes and self.edges == other.edges + except AttributeError: + return False + + def __ne__(self, other): + return not (self == other) + + def assign(self, observed, inplace=False): + if not inplace: + network = self.clone() + else: + network = self + solution_map = {} + for case in observed: + if case.glycan_composition is None: + continue + s = solution_map.get(case.glycan_composition) + if s is None or s.score < case.score: + solution_map[case.glycan_composition] = case + + for node in network.nodes: + node.internal_score = 0 + + for composition, solution in solution_map.items(): + try: + node = network[composition] + node.internal_score = solution.internal_score + except KeyError: + # Not all exact compositions have nodes + continue + return network + + def unassign(self, inplace=False): + if not inplace: + network = self.clone() + else: + network = self + for node in network: + node.score = node.internal_score = 0 + return network + + def augment_with_decoys(self, pseudodistance=2): + compositions = [] + if pseudodistance == 0: + raise ValueError(""Cannot use decoys with pseudodistance of size 0"") + for node in self: + t = node.glycan_composition.copy() + d = node.glycan_composition.copy() + d['#decoy#'] = pseudodistance + compositions.append(t) + compositions.append(d) + return self.__class__(compositions, self.distance_fn, self.neighborhoods) + + def merge(self, other): + edges = other.edges + for node in other: + self.add_node(node) + self._reindex() + for edge in edges: + self.add_edge(self[edge.node1], self[edge.node2]) + return self + + +try: + _has_c = True + from glycresoft._c.composition_network.graph import reindex_graph as _reindex_graph + CompositionGraph._reindex = _reindex_graph +except ImportError: + _has_c = False + + +class GraphWriter(object): + + def __init__(self, network, file_obj): + self.network = network + self.file_obj = file_obj + self.handle_graph(self.network) + + def write(self, text): + self.file_obj.write(text) + + def handle_node(self, node): + composition = node.composition.serialize() + index = (node.index) + score = node.score + self.write(""%d\t%s\t%f\n"" % (index, composition, score)) + + def handle_edge(self, edge): + index1 = edge.node1.index + index2 = edge.node2.index + diff = edge.order + weight = edge.weight + line = (""%d\t%d\t%d\t%f"" % (index1, index2, diff, weight)) + trimmed = line.rstrip(""0"") + if line != trimmed: + trimmed += '0' + self.write(trimmed + '\n') + + def handle_graph(self, graph): + self.write(""#COMPOSITIONGRAPH 1.1\n"") + self.write(""#NODE\n"") + for node in self.network.nodes: + self.handle_node(node) + self.write(""#EDGE\n"") + for edge in self.network.edges: + self.handle_edge(edge) + try: + if graph.neighborhoods: + self.write(""#NEIGHBORHOOD\n"") + for neighborhood in graph.neighborhoods: + self.handle_neighborhood(neighborhood) + except AttributeError: + pass + + def handle_neighborhood(self, neighborhood_rule): + self.write(""BEGIN NEIGHBORHOOD\n"") + self.write(neighborhood_rule.serialize()) + self.write(""END NEIGHBORHOOD\n"") + + +class GraphReader(object): + + @classmethod + def read(cls, file_obj): + inst = cls(file_obj) + return inst.network, inst.neighborhoods + + def __init__(self, file_obj): + self.file_obj = file_obj + self.network = CompositionGraph([]) + self.neighborhoods = self.network.neighborhoods + self.handle_graph_file() + + def handle_node_line(self, line): + try: + index, composition, score = line.replace(""\n"", """").split(""\t"") + score = float(score) + except ValueError: + index, composition = line.replace(""\n"", """").split(""\t"") + score = 0. + + index = int(index) + composition = HashableGlycanComposition.parse(composition) + node = CompositionGraphNode(composition, index, score) + node.internal_score = score + self.network.nodes.append(node) + self.network.node_map[str(node.composition)] = node + + def handle_edge_line(self, line): + index1, index2, diff, weight = line.replace(""\n"", """").split(""\t"") + index1, index2, diff, weight = int(index1), int( + index2), int(diff), float(weight) + node1 = self.network.nodes[index1] + node2 = self.network.nodes[index2] + edge = CompositionGraphEdge(node1, node2, diff, weight) + self.network.edges.add(edge) + + def handle_graph_file(self): + state = ""START"" + buffering = [] + for line in self.file_obj: + line = line.strip() + if state == ""START"": + if line == ""#NODE"": + state = ""NODE"" + elif state == ""NODE"": + if line == ""#EDGE"": + state = ""EDGE"" + else: + self.handle_node_line(line) + elif state == ""EDGE"": + if line == ""#NEIGHBORHOOD"": + state = ""NEIGHBORHOOD"" + else: + self.handle_edge_line(line) + elif state == ""NEIGHBORHOOD"": + if line.startswith(""BEGIN NEIGHBORHOOD""): + if buffering: + self.handle_neighborhood(buffering) + buffering = [] + elif line.startswith(""END NEIGHBORHOOD""): + if buffering: + self.handle_neighborhood(buffering) + buffering = [] + else: + buffering.append(line) + + def handle_neighborhood(self, lines): + rule = CompositionRuleClassifier.parse(lines) + self.neighborhoods.add(rule) + + +dump = GraphWriter +load = GraphReader.read +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/prebuilt/glycosaminoglycan_linkers.py",".py","2931","59","from glycresoft.database.builder.glycan import TextFileGlycanHypothesisSerializer +from glycresoft.database.prebuilt.utils import hypothesis_register, BuildBase +from io import StringIO + + +hypothesis_metadata = { + ""name"": ""Glycosaminoglycan Linkers"", + ""hypothesis_type"": ""glycan_composition"", + ""description"": '' +} + +source_text = u'''{Xyl:1; a,enHex:1; Hex:2; aHex:1; HexNAc:1} GAG-linker +{Xyl:1; a,enHex:1; Hex:2; aHex:1; HexNAc(S):1} GAG-linker +{Xyl:1; Fuc:1; a,enHex:1; Hex:2; aHex:1; HexNAc:1} GAG-linker +{Xyl:1; Fuc:1; a,enHex:1; Hex:1; aHex:1; HexS:1; HexNAc(S):1} GAG-linker +{Xyl:1; Fuc:1; a,enHex:1; Hex:2; aHex:1; HexNAc(S):1} GAG-linker +{Fuc:1; a,enHex:1; Hex:2; aHex:1; HexNAc:1; XylP:1} GAG-linker +{a,enHex:1; Hex:2; aHex:1; HexNAc:1; XylP:1} GAG-linker +{a,enHex:1; Hex:2; aHex:1; XylP:1; HexNAc(S):1} GAG-linker +{a,enHex:1; Hex:1; aHex:1; XylP:1; HexS:1; HexNAc(S):1} GAG-linker +{Xyl:1; a,enHex:1; Hex:2; aHex:1; HexNAc(S):1} GAG-linker +{Xyl:1; a,enHex:1; Hex:1; aHex:1; HexS:1; HexNAc(S):1} GAG-linker +{Xyl:1; a,enHex:1; aHex:1; HexS:2; HexNAc(S):1} GAG-linker +{Xyl:1; a,enHex:1; Hex:2; aHex:1; HexNAc:1; Neu5Ac:1} GAG-linker +{Xyl:1; a,enHex:1; Hex:2; aHex:1; HexNAc(S):1; Neu5Ac:1} GAG-linker +{Xyl:1; a,enHex:1; Hex:1; aHex:1; HexS:1; HexNAc(S):1; Neu5Ac:1} GAG-linker +{Xyl:1; a,enHex:1; Hex:2; aHex:1; HexNAc:1; Neu5Ac:1} GAG-linker +{Xyl:1; a,enHex:1; Hex:2; aHex:1; HexNAc(S):1; Neu5Ac:1} GAG-linker +{a,enHex:1; Hex:2; aHex:1; XylP:1; HexNAc(S):1; Neu5Ac:1} GAG-linker +{Xyl:1; a,enHex:1; Hex:1; aHex:1; HexS:1; HexNAc(S):1; Neu5Ac:1} GAG-linker +{a,enHex:1; Hex:1; aHex:1; XylP:1; HexS:1; HexNAc(S):1; Neu5Ac:1} GAG-linker +{Xyl:1; a,enHex:1; Hex:2; aHex:1; HexNAc:1; Neu5Gc:1} GAG-linker +{Xyl:1; a,enHex:1; Hex:2; aHex:1; HexNAc(S):1; Neu5Gc:1} GAG-linker +{Xyl:1; a,enHex:1; Hex:1; aHex:1; HexS:1; HexNAc(S):1; Neu5Gc:1} GAG-linker +{Xyl:1; a,enHex:1; Hex:2; aHex:1; HexNAc:1; Neu5Gc:1} GAG-linker +{Xyl:1; a,enHex:1; Hex:2; aHex:1; HexNAc(S):1; Neu5Gc:1} GAG-linker +{a,enHex:1; Hex:2; aHex:1; XylP:1; HexNAc(S):1; Neu5Gc:1} GAG-linker +{Xyl:1; a,enHex:1; Hex:1; aHex:1; HexS:1; HexNAc(S):1; Neu5Gc:1} GAG-linker +{a,enHex:1; Hex:1; aHex:1; XylP:1; HexS:1; HexNAc(S):1; Neu5Gc:1} GAG-linker''' + + +@hypothesis_register(hypothesis_metadata['name']) +class GlycosaminoglycanLinkersBuilder(BuildBase): + + def get_hypothesis_metadata(self): + return hypothesis_metadata + + def prepare_buffer(self): + text_buffer = StringIO(source_text) + return text_buffer + + def build(self, database_connection, **kwargs): + kwargs.setdefault('hypothesis_name', self.hypothesis_metadata['name']) + task = TextFileGlycanHypothesisSerializer( + self.prepare_buffer(), database_connection, + **kwargs) + task.start() + return task +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/prebuilt/combinatorial_mammalian_n_linked.py",".py","933","34","from glycresoft.database.builder.glycan import CombinatorialGlycanHypothesisSerializer +from glycresoft.database.prebuilt.utils import hypothesis_register, BuildBase +from io import StringIO + + +combinatorial_source = u'''Hex 3 10 +HexNAc 2 9 +Fuc 0 5 +NeuAc 0 5 +NeuGc 0 5 + +Fuc < HexNAc +HexNAc > (NeuAc + NeuGc) + 1''' + +hypothesis_metadata = { + ""name"": 'Combinatorial Mammalian N-Glycans', + ""hypothesis_type"": 'glycan_composition' +} + + +# @hypothesis_register(hypothesis_metadata['name']) +class CombinatorialMammalianNGlycansBuilder(BuildBase): + + def get_hypothesis_metadata(self): + return hypothesis_metadata + + def build(self, database_connection, **kwargs): + kwargs.setdefault('hypothesis_name', self.hypothesis_metadata['name']) + task = CombinatorialGlycanHypothesisSerializer( + StringIO(combinatorial_source), database_connection, + **kwargs) + task.start() + return task +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/prebuilt/__init__.py",".py","583","21","from .utils import hypothesis_register +from . import heparin +from . import combinatorial_mammalian_n_linked +from . import glycosaminoglycan_linkers +from . import combinatorial_human_n_linked +from . import biosynthesis_human_n_linked +from . import biosynthesis_mammalian_n_linked +from . import human_mucin_o_linked + + +__all__ = [ + ""hypothesis_register"", + ""heparin"", + ""combinatorial_mammalian_n_linked"", + ""combinatorial_human_n_linked"", + ""glycosaminoglycan_linkers"", + ""biosynthesis_human_n_linked"", + ""biosynthesis_mammalian_n_linked"", + ""human_mucin_o_linked"", +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/prebuilt/heparin.py",".py","1184","38","from glycresoft.database.builder.glycan import CombinatorialGlycanHypothesisSerializer +from glycresoft.database.prebuilt.utils import hypothesis_register, BuildBase +from io import StringIO + +combinatorial_source = u'''HexA 1 9 +HexN 1 9 +enHexA 0 1 +@acetyl 0 9 +@sulfate 0 48 + +@acetyl <= HexN +@sulfate <= ((HexN * 3 - @acetyl) + (HexA * 2) + (enHexA * 2)) +HexA <= HexN + 1 +HexN <= HexA + 1 +''' + +hypothesis_metadata = { + ""name"": 'Low Molecular Weight Heparins', + ""hypothesis_type"": 'glycan_composition', + ""description"": 'A database of heparin and heparan sulfate chains covering' + ' the combinatorial space of possible saccharides of up to 18 monosaccharides.' +} + + +@hypothesis_register(hypothesis_metadata['name']) +class LowMolecularWeightHeparansBuilder(BuildBase): + + def get_hypothesis_metadata(self): + return hypothesis_metadata + + def build(self, database_connection, **kwargs): + kwargs.setdefault('hypothesis_name', self.hypothesis_metadata['name']) + task = CombinatorialGlycanHypothesisSerializer( + StringIO(combinatorial_source), database_connection, + **kwargs) + task.start() + return task +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/prebuilt/utils.py",".py","604","24","from glycresoft.structure import KeyTransformingDecoratorDict + + +def key_transform(name): + return str(name).lower().replace("" "", '-') + + +hypothesis_register = KeyTransformingDecoratorDict(key_transform) + + +class BuildBase(object): + def get_hypothesis_metadata(self): + raise NotImplementedError() + + @property + def hypothesis_metadata(self): + return self.get_hypothesis_metadata() + + def build(self, database_connection, **kwargs): + raise NotImplementedError() + + def __call__(self, database_connection, **kwargs): + return self.build(database_connection, **kwargs) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/prebuilt/combinatorial_human_n_linked.py",".py","907","33","from glycresoft.database.builder.glycan import CombinatorialGlycanHypothesisSerializer +from glycresoft.database.prebuilt.utils import hypothesis_register, BuildBase +from io import StringIO + + +combinatorial_source = u'''Hex 3 10 +HexNAc 2 9 +Fuc 0 4 +NeuAc 0 5 + +Fuc < HexNAc +HexNAc > (NeuAc) + 1''' + +hypothesis_metadata = { + ""name"": 'Combinatorial Human N-Glycans', + ""hypothesis_type"": 'glycan_composition' +} + + +# @hypothesis_register(hypothesis_metadata['name']) +class CombinatorialHumanNGlycansBuilder(BuildBase): + + def get_hypothesis_metadata(self): + return hypothesis_metadata + + def build(self, database_connection, **kwargs): + kwargs.setdefault('hypothesis_name', self.hypothesis_metadata['name']) + task = CombinatorialGlycanHypothesisSerializer( + StringIO(combinatorial_source), database_connection, + **kwargs) + task.start() + return task +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/prebuilt/biosynthesis_human_n_linked.py",".py","1433","40","import pkg_resources + +from glycresoft.database.builder.glycan import ( + GlycanCompositionEnzymeGraph, ExistingGraphGlycanHypothesisSerializer, GlycanTypes) +from glycresoft.database.prebuilt.utils import hypothesis_register, BuildBase + +from io import StringIO + + +def load_graph(): + resource_bytes = pkg_resources.resource_string( + __name__, + ""data/human_composition_enzyme_graph.json"") + resource_buffer = StringIO(resource_bytes.decode('utf8')) + return GlycanCompositionEnzymeGraph.load(resource_buffer) + + +hypothesis_metadata = { + ""name"": 'Biosynthesis Human N-Glycans', + ""hypothesis_type"": 'glycan_composition', + ""description"": ""A collection of biosynthetically feasible *N*-glycans using enzymes commonly found in humans"" + "" and limited to at most 26 monosaccharides. `GnTE` is explicitly omitted to make the space tractable."" +} + + +@hypothesis_register(hypothesis_metadata['name']) +class BiosynthesisHumanNGlycansBuilder(BuildBase): + + def get_hypothesis_metadata(self): + return hypothesis_metadata + + def build(self, database_connection, **kwargs): + if kwargs.get('hypothesis_name') is None: + kwargs['hypothesis_name'] = (self.hypothesis_metadata['name']) + task = ExistingGraphGlycanHypothesisSerializer( + load_graph(), database_connection, glycan_classification=GlycanTypes.n_glycan, + **kwargs) + task.start() + return task +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/prebuilt/biosynthesis_mammalian_n_linked.py",".py","1446","40","import pkg_resources + +from glycresoft.database.builder.glycan import ( + GlycanCompositionEnzymeGraph, ExistingGraphGlycanHypothesisSerializer, GlycanTypes) +from glycresoft.database.prebuilt.utils import hypothesis_register, BuildBase + +from io import StringIO + + +def load_graph(): + resource_bytes = pkg_resources.resource_string( + __name__, + ""data/mammalian_composition_enzyme_graph.json"") + resource_buffer = StringIO(resource_bytes.decode('utf8')) + return GlycanCompositionEnzymeGraph.load(resource_buffer) + + +hypothesis_metadata = { + ""name"": 'Biosynthesis Mammalian N-Glycans', + ""hypothesis_type"": 'glycan_composition', + ""description"": ""A collection of biosynthetically feasible *N*-glycans using enzymes commonly found in mammals"" + "" and limited to at most 26 monosaccharides. `GnTE` is explicitly omitted to make the space tractable."" +} + + +@hypothesis_register(hypothesis_metadata['name']) +class BiosynthesisMammalianNGlycansBuilder(BuildBase): + + def get_hypothesis_metadata(self): + return hypothesis_metadata + + def build(self, database_connection, **kwargs): + if kwargs.get('hypothesis_name') is None: + kwargs['hypothesis_name'] = (self.hypothesis_metadata['name']) + task = ExistingGraphGlycanHypothesisSerializer( + load_graph(), database_connection, glycan_classification=GlycanTypes.n_glycan, + **kwargs) + task.start() + return task +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/prebuilt/human_mucin_o_linked.py",".py","1278","40","import pkg_resources + +from glycresoft.database.builder.glycan import ( + TextFileGlycanHypothesisSerializer) +from glycresoft.database.prebuilt.utils import hypothesis_register, BuildBase + +from io import StringIO + + +def load_text(): + resource_bytes = pkg_resources.resource_string( + __name__, + ""data/mucin_compositions.txt"") + resource_buffer = StringIO(resource_bytes.decode('utf8')) + return resource_buffer + + +hypothesis_metadata = { + ""name"": 'Biosynthesis Human Mucin O-Glycans', + ""hypothesis_type"": 'glycan_composition', + ""description"": ""A collection of biosynthetically feasible mucin *O*-glycans using enzymes commonly found in humans"" + "" and limited to at most 11 monosaccharides. Includes the standard cores 1-6."" +} + + +@hypothesis_register(hypothesis_metadata['name']) +class BiosynthesisHumanMucinOGlycansBuilder(BuildBase): + + def get_hypothesis_metadata(self): + return hypothesis_metadata + + def build(self, database_connection, **kwargs): + if kwargs.get('hypothesis_name') is None: + kwargs['hypothesis_name'] = (self.hypothesis_metadata['name']) + task = TextFileGlycanHypothesisSerializer( + load_text(), database_connection, + **kwargs) + task.start() + return task +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/prebuilt/data/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/base.py",".py","1220","42","from glycresoft.task import TaskBase + + +class HypothesisSerializerBase(TaskBase): + + def set_parameters(self, params): + if self.hypothesis.parameters is None: + self.hypothesis.parameters = {} + self.session.add(self.hypothesis) + self.session.commit() + new_params = dict(self.hypothesis.parameters) + new_params.update(params) + self.hypothesis.parameters = new_params + self.session.add(self.hypothesis) + self.session.commit() + + @property + def hypothesis(self): + if self._hypothesis is None: + self._construct_hypothesis() + return self._hypothesis + + @property + def hypothesis_name(self): + if self._hypothesis_name is None: + self._construct_hypothesis() + return self._hypothesis_name + + @property + def hypothesis_id(self): + if self._hypothesis_id is None: + self._construct_hypothesis() + return self._hypothesis_id + + def on_end(self): + hypothesis = self.hypothesis + self.session.add(hypothesis) + hypothesis.status = ""complete"" + self.session.add(hypothesis) + self.session.commit() + self.log(""Hypothesis Completed"") +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/common.py",".py","30227","734","import itertools +from typing import Iterable, Optional +from uuid import uuid4 +from collections import defaultdict, Counter +from multiprocessing import Process, Queue, Event, RLock +from threading import Thread +from itertools import product + +from queue import Empty as QueueEmptyException + +from glypy import Composition +from glypy.composition import formula +from glypy.structure.glycan_composition import FrozenGlycanComposition + +from glycresoft.serialize import DatabaseBoundOperation, func +from glycresoft.serialize.hypothesis import GlycopeptideHypothesis +from glycresoft.serialize.hypothesis.peptide import Glycopeptide, Peptide, Protein, ProteinSite +from glycresoft.serialize.hypothesis.glycan import ( + GlycanCombination, GlycanClass, GlycanComposition, + GlycanTypes, GlycanCombinationGlycanComposition) +from glycresoft.serialize.utils import toggle_indices +from glycresoft.task import TaskBase + +from glycresoft.database.builder.glycan import glycan_combinator +from glycresoft.database.builder.base import HypothesisSerializerBase + +from glycresoft.database.builder.glycopeptide.proteomics.remove_duplicate_peptides import DeduplicatePeptides + +from glycopeptidepy.structure.sequence import ( + _n_glycosylation, _o_glycosylation, _gag_linker_glycosylation) + +from glycopeptidepy.algorithm import reverse_sequence +from glycopeptidepy.structure.sequence import ( + find_n_glycosylation_sequons, + PeptideSequence +) + +from glycopeptidepy.structure.residue import UnknownAminoAcidException + +_DEFAULT_GLYCAN_STEP_LIMIT = 15000 + + +def slurp(session, model, ids, flatten=True): + if flatten: + ids = [j for i in ids for j in i] + total = len(ids) + last = 0 + step = 100 + results = [] + while last < total: + results.extend(session.query(model).filter( + model.id.in_(ids[last:last + step]))) + last += step + return results + + +class GlycopeptideHypothesisSerializerBase(DatabaseBoundOperation, HypothesisSerializerBase): + """"""Common machinery for Glycopeptide Hypothesis construction. + + Attributes + ---------- + uuid : str + The uuid of the hypothesis to be constructed + """""" + def __init__(self, database_connection, hypothesis_name=None, glycan_hypothesis_id=None, + full_cross_product=True, use_uniprot=True, uniprot_source_file: Optional[str]=None): + DatabaseBoundOperation.__init__(self, database_connection) + self._hypothesis_name = hypothesis_name + self._hypothesis_id = None + self._hypothesis = None + self._glycan_hypothesis_id = glycan_hypothesis_id + self.uuid = str(uuid4().hex) + self.total_glycan_combination_count = -1 + self.use_uniprot = use_uniprot + self.uniprot_source_file = uniprot_source_file + self.full_cross_product = full_cross_product + + def _construct_hypothesis(self): + if self._hypothesis_name is None or self._hypothesis_name.strip() == """": + self._hypothesis_name = self._make_name() + + if self.glycan_hypothesis_id is None: + raise ValueError(""glycan_hypothesis_id must not be None"") + self._hypothesis = GlycopeptideHypothesis( + name=self._hypothesis_name, glycan_hypothesis_id=self._glycan_hypothesis_id, + uuid=self.uuid) + self.session.add(self._hypothesis) + self.session.commit() + + self._hypothesis_id = self._hypothesis.id + self._hypothesis_name = self._hypothesis.name + self._glycan_hypothesis_id = self._hypothesis.glycan_hypothesis_id + + def _make_name(self): + return ""GlycopeptideHypothesis-"" + self.uuid + + @property + def glycan_hypothesis_id(self): + if self._glycan_hypothesis_id is None: + self._construct_hypothesis() + return self._glycan_hypothesis_id + + @property + def n_glycan_only(self): + if self._hypothesis is None: + self._construct_hypothesis() + return self._hypothesis.n_glycan_only + + def peptide_ids_with_n_glycosites(self): + # May include the residue beyond the final + q = self.session.query(Peptide.id.distinct()).join(Protein).join(Protein.sites).filter( + Peptide.spans(ProteinSite.location) & + (ProteinSite.name == ProteinSite.N_GLYCOSYLATION) & + (Protein.hypothesis_id == self._hypothesis_id)).all() + return [i[0] for i in q] + + def peptide_ids(self): + if self.n_glycan_only: + return self.peptide_ids_with_n_glycosites() + q = self.session.query(Peptide.id).filter(Peptide.hypothesis_id == self._hypothesis_id).all() + return [i[0] for i in q] + + def combinate_glycans(self, n): + combinator = glycan_combinator.GlycanCombinationSerializer( + self.engine, self.glycan_hypothesis_id, + self.hypothesis_id, n) + combinator.run() + self.total_glycan_combination_count = combinator.total_count + if not (self.total_glycan_combination_count > 0): + raise ValueError(""No glycan combinations were generated. No glycopeptides can be produced!"") + + def _count_produced_glycopeptides(self): + count = self.query( + func.count(Glycopeptide.id)).filter( + Glycopeptide.hypothesis_id == self.hypothesis_id).scalar() + self.log(""Generated %d glycopeptides"" % count) + self.set_parameters({ + ""database_size"": count + }) + return count + + def _sql_analyze_database(self): + self.log(""Analyzing Indices"") + self._analyze_database() + if self.is_sqlite(): + self._sqlite_reload_analysis_plan() + self.log(""Done Analyzing Indices"") + + def deduplicate_peptides(self): + DeduplicatePeptides(self._original_connection, + self.hypothesis_id).run() + + +class GlycopeptideHypothesisDestroyer(DatabaseBoundOperation, TaskBase): + def __init__(self, database_connection, hypothesis_id): + DatabaseBoundOperation.__init__(self, database_connection) + self.hypothesis_id = hypothesis_id + + def delete_glycopeptides(self): + self.log(""Delete Glycopeptides"") + self.session.query(Glycopeptide).filter( + Glycopeptide.hypothesis_id == self.hypothesis_id).delete( + synchronize_session=False) + self.session.commit() + + def delete_peptides(self): + self.log(""Delete Peptides"") + q = self.session.query(Protein.id).filter(Protein.hypothesis_id == self.hypothesis_id) + for protein_id, in q: + self.session.query(Peptide).filter( + Peptide.protein_id == protein_id).delete( + synchronize_session=False) + self.session.commit() + + def delete_protein(self): + self.log(""Delete Protein"") + self.session.query(Protein).filter(Protein.hypothesis_id == self.hypothesis_id).delete( + synchronize_session=False) + self.session.commit() + + def delete_hypothesis(self): + self.log(""Delete Hypothesis"") + self.session.query(GlycopeptideHypothesis).filter( + GlycopeptideHypothesis.id == self.hypothesis_id).delete() + self.session.commit() + + def run(self): + self.delete_glycopeptides() + self.delete_peptides() + self.delete_protein() + self.delete_hypothesis() + self.session.commit() + + +def distinct_glycan_classes(session, hypothesis_id): + structure_classes = session.query(GlycanClass.name.distinct()).join( + GlycanComposition.structure_classes).join( + GlycanCombinationGlycanComposition).join( + GlycanCombination).filter( + GlycanCombination.hypothesis_id == hypothesis_id).all() + return [sc[0] for sc in structure_classes] + + +def composition_to_structure_class_map(session, glycan_hypothesis_id): + mapping = defaultdict(list) + id_to_class_iterator = session.query(GlycanComposition.id, GlycanClass.name).join( + GlycanComposition.structure_classes).filter( + GlycanComposition.hypothesis_id == glycan_hypothesis_id).all() + for gc_id, sc_name in id_to_class_iterator: + mapping[gc_id].append(sc_name) + return mapping + + +def combination_structure_class_map(session, hypothesis_id, composition_class_map): + mapping = defaultdict(list) + iterator = session.query( + GlycanCombinationGlycanComposition).join(GlycanCombination).filter( + GlycanCombination.hypothesis_id == hypothesis_id).order_by(GlycanCombination.id) + for glycan_id, combination_id, count in iterator: + listing = mapping[combination_id] + for i in range(count): + listing.append(composition_class_map[glycan_id]) + return mapping + + +class GlycanCombinationPartitionTable(TaskBase): + def __init__(self, session, glycan_combinations, glycan_classes, hypothesis): + self.session = session + self.tables = defaultdict(lambda: defaultdict(list)) + self.hypothesis_id = hypothesis.id + self.glycan_hypothesis_id = hypothesis.glycan_hypothesis_id + self.glycan_classes = glycan_classes + self.build_table(glycan_combinations) + + def build_table(self, glycan_combinations): + composition_class_map = composition_to_structure_class_map( + self.session, self.glycan_hypothesis_id) + combination_class_map = combination_structure_class_map( + self.session, self.hypothesis_id, composition_class_map) + + for entry in glycan_combinations: + size_table = self.tables[entry.count] + component_classes = combination_class_map[entry.id] + class_assignment_generator = product(*component_classes) + for classes in class_assignment_generator: + counts = Counter(c for c in classes) + key = tuple(counts[c] for c in self.glycan_classes) + class_table = size_table[key] + class_table.append(entry) + + def build_key(self, mapping): + return tuple(mapping.get(c, 0) for c in self.glycan_classes) + + def get_entries(self, size, mapping): + key = self.build_key(mapping) + return self.tables[size][key] + + def __getitem__(self, key): + size, mapping = key + return self.get_entries(size, mapping) + + +def limiting_combinations(iterable: Iterable, n: int, limit: int=100): + i = 0 + for result in itertools.combinations(iterable, n): + i += 1 + yield result + if i > limit: + break + + +class GlycanCombinationRecord(object): + __slots__ = [ + 'id', 'calculated_mass', 'formula', 'count', 'glycan_composition_string', + '_composition', '_dehydrated_composition'] + + id: int + calculated_mass: float + formula: str + count: int + glycan_composition_string: str + + _composition: Composition + _dehydrated_composition: Composition + + def __init__(self, combination): + self.id = combination.id + self.calculated_mass = combination.calculated_mass + self.formula = combination.formula + self.count = combination.count + self.glycan_composition_string = combination.composition + self._composition = None + self._dehydrated_composition = None + + def total_composition(self): + if self._composition is None: + self._composition = self.convert().total_composition() + return self._composition + + def dehydrated_composition(self): + if self._dehydrated_composition is None: + self._dehydrated_composition = self.total_composition() - (Composition(""H2O"") * self.count) + return self._dehydrated_composition + + def convert(self): + gc = FrozenGlycanComposition.parse(self.glycan_composition_string) + gc.id = self.id + gc.count = self.count + return gc + + def __repr__(self): + return ""GlycanCombinationRecord(%d, %s)"" % ( + self.id, self.glycan_composition_string) + + +class PeptideGlycosylator(object): + def __init__(self, session, hypothesis_id, glycan_offset=None, glycan_limit=_DEFAULT_GLYCAN_STEP_LIMIT): + self.session = session + + self.glycan_offset = glycan_offset + self.glycan_limit = glycan_limit + + self.hypothesis_id = hypothesis_id + self.hypothesis = self.session.query(GlycopeptideHypothesis).get(hypothesis_id) + self.total_combinations = self._get_total_combination_count() + + self.build_glycan_table(self.glycan_offset) + + def _get_total_combination_count(self): + count = self.session.query( + GlycanCombination).filter( + GlycanCombination.hypothesis_id == self.hypothesis_id).count() + return count + + def _load_glycan_records(self): + if self.glycan_offset is None: + glycan_combinations = self.session.query( + GlycanCombination).filter( + GlycanCombination.hypothesis_id == self.hypothesis_id).all() + glycan_combinations = [GlycanCombinationRecord(gc) for gc in glycan_combinations] + else: + glycan_combinations = self.session.query( + GlycanCombination).filter( + GlycanCombination.hypothesis_id == self.hypothesis_id).offset( + self.glycan_offset).limit(self.glycan_limit).all() + return glycan_combinations + + def _build_size_table(self, glycan_combinations): + self.glycan_combination_partitions = GlycanCombinationPartitionTable( + self.session, glycan_combinations, distinct_glycan_classes( + self.session, self.hypothesis_id), self.hypothesis) + + def build_glycan_table(self, offset=None): + self.glycan_offset = offset + glycan_combinations = self._load_glycan_records() + self._build_size_table(glycan_combinations) + + def handle_peptide(self, peptide): + water = Composition(""H2O"") + peptide_composition = Composition(str(peptide.formula)) + obj = peptide.convert() + reference = obj.clone() + + # Handle N-linked glycosylation sites + + n_glycosylation_unoccupied_sites = set(peptide.n_glycosylation_sites) + for site in list(n_glycosylation_unoccupied_sites): + if obj[site][1]: + n_glycosylation_unoccupied_sites.remove(site) + for i in range(len(n_glycosylation_unoccupied_sites)): + i += 1 + for gc in self.glycan_combination_partitions[i, {GlycanTypes.n_glycan: i}]: + total_mass = peptide.calculated_mass + gc.calculated_mass - (gc.count * water.mass) + formula_string = formula(peptide_composition + gc.dehydrated_composition()) + + for site_set in limiting_combinations(n_glycosylation_unoccupied_sites, i): + sequence = reference.clone() + for site in site_set: + sequence.add_modification(site, _n_glycosylation.name) + sequence.glycan = gc.convert() + + glycopeptide_sequence = str(sequence) + + glycopeptide = dict( + calculated_mass=total_mass, + formula=formula_string, + glycopeptide_sequence=glycopeptide_sequence, + peptide_id=peptide.id, + protein_id=peptide.protein_id, + hypothesis_id=peptide.hypothesis_id, + glycan_combination_id=gc.id) + yield glycopeptide + + # Handle O-linked glycosylation sites + o_glycosylation_unoccupied_sites = set(peptide.o_glycosylation_sites) + for site in list(o_glycosylation_unoccupied_sites): + if obj[site][1]: + o_glycosylation_unoccupied_sites.remove(site) + + for i in range(len(o_glycosylation_unoccupied_sites)): + i += 1 + for gc in self.glycan_combination_partitions[i, {GlycanTypes.o_glycan: i}]: + total_mass = peptide.calculated_mass + gc.calculated_mass - (gc.count * water.mass) + formula_string = formula(peptide_composition + gc.dehydrated_composition()) + + for site_set in limiting_combinations(o_glycosylation_unoccupied_sites, i): + sequence = reference.clone() + for site in site_set: + sequence.add_modification(site, _o_glycosylation.name) + sequence.glycan = gc.convert() + + glycopeptide_sequence = str(sequence) + + glycopeptide = dict( + calculated_mass=total_mass, + formula=formula_string, + glycopeptide_sequence=glycopeptide_sequence, + peptide_id=peptide.id, + protein_id=peptide.protein_id, + hypothesis_id=peptide.hypothesis_id, + glycan_combination_id=gc.id) + yield glycopeptide + + # Handle GAG glycosylation sites + gag_unoccupied_sites = set(peptide.gagylation_sites) + for site in list(gag_unoccupied_sites): + if obj[site][1]: + gag_unoccupied_sites.remove(site) + for i in range(len(gag_unoccupied_sites)): + i += 1 + for gc in self.glycan_combination_partitions[i, {GlycanTypes.gag_linker: i}]: + total_mass = peptide.calculated_mass + gc.calculated_mass - (gc.count * water.mass) + formula_string = formula(peptide_composition + gc.dehydrated_composition()) + for site_set in limiting_combinations(gag_unoccupied_sites, i): + sequence = reference.clone() + for site in site_set: + sequence.add_modification(site, _gag_linker_glycosylation.name) + sequence.glycan = gc.convert() + + glycopeptide_sequence = str(sequence) + + glycopeptide = dict( + calculated_mass=total_mass, + formula=formula_string, + glycopeptide_sequence=glycopeptide_sequence, + peptide_id=peptide.id, + protein_id=peptide.protein_id, + hypothesis_id=peptide.hypothesis_id, + glycan_combination_id=gc.id) + yield glycopeptide + + +def null_log_handler(msg): + print(msg) + + +class PeptideGlycosylatingProcess(Process): + process_name = ""glycopeptide-build-worker"" + + def __init__(self, connection, hypothesis_id, input_queue, chunk_size=5000, done_event=None, + log_handler=null_log_handler, glycan_offset=None, + glycan_limit=_DEFAULT_GLYCAN_STEP_LIMIT): + Process.__init__(self) + self.daemon = True + self.connection = connection + self.input_queue = input_queue + self.chunk_size = chunk_size + self.hypothesis_id = hypothesis_id + self.done_event = done_event + self.log_handler = log_handler + + self.glycan_offset = glycan_offset + self.glycan_limit = glycan_limit + + self.session = None + self.work_done_event = Event() + + def is_work_done(self): + return self.work_done_event.is_set() + + def process_result(self, collection): + self.session.bulk_insert_mappings(Glycopeptide, collection, render_nulls=True) + self.session.commit() + + def load_peptides(self, work_items): + peptides = slurp(self.session, Peptide, work_items, flatten=False) + return peptides + + def task(self): + database = DatabaseBoundOperation(self.connection) + self.session = database.session + has_work = True + + glycosylator = PeptideGlycosylator( + database.session, self.hypothesis_id, + glycan_offset=self.glycan_offset, + glycan_limit=self.glycan_limit) + result_accumulator = [] + + n = 0 + n_gps = 0 + while has_work: + try: + work_items = self.input_queue.get(timeout=5) + if work_items is None: + has_work = False + continue + except Exception: + if self.done_event.is_set(): + has_work = False + continue + peptides = self.load_peptides(work_items) + n += len(peptides) + for peptide in peptides: + for gp in glycosylator.handle_peptide(peptide): + result_accumulator.append(gp) + if len(result_accumulator) > self.chunk_size: + n_gps += len(result_accumulator) + self.process_result(result_accumulator) + result_accumulator = [] + if len(result_accumulator) > 0: + n_gps += len(result_accumulator) + self.process_result(result_accumulator) + result_accumulator = [] + self.work_done_event.set() + # It seems there is no public API to force the process to check if it is done + # but the internal method is invoked when creating a Process `repr` on Python 2. + # This problem supposedly doesn't exist in Python 3. + repr(self) + self.log_handler(""Process %r completed. (%d peptides, %d glycopeptides)"" % (self.pid, n, n_gps)) + + def run(self): + new_name = getattr(self, 'process_name', None) + if new_name is not None: + TaskBase().try_set_process_name(new_name) + try: + self.task() + except Exception as e: + import traceback + self.log_handler( + ""An exception has occurred for %r.\n%r\n%s"" % ( + self, e, traceback.format_exc())) + + +class NonSavingPeptideGlycosylatingProcess(PeptideGlycosylatingProcess): + def process_result(self, collection): + pass + + +class QueuePushingPeptideGlycosylatingProcess(PeptideGlycosylatingProcess): + def __init__(self, connection, hypothesis_id, input_queue, output_queue, chunk_size=5000, + done_event=None, log_handler=null_log_handler, database_mutex=None, + glycan_offset=None, glycan_limit=_DEFAULT_GLYCAN_STEP_LIMIT): + super(QueuePushingPeptideGlycosylatingProcess, self).__init__( + connection, hypothesis_id, input_queue, chunk_size, done_event, log_handler, + glycan_offset=glycan_offset, glycan_limit=glycan_limit) + self.output_queue = output_queue + self.database_mutex = database_mutex + + def load_peptides(self, work_items): + with self.database_mutex: + result = super(QueuePushingPeptideGlycosylatingProcess, self).load_peptides(work_items) + return result + + def process_result(self, collection): + self.output_queue.put(collection) + + +class MultipleProcessPeptideGlycosylator(TaskBase): + def __init__(self, connection_specification, hypothesis_id, chunk_size=6500, n_processes=4, + glycan_combination_count=None, glycan_limit=_DEFAULT_GLYCAN_STEP_LIMIT): + self.n_processes = n_processes + self.connection_specification = connection_specification + self.chunk_size = chunk_size + self.hypothesis_id = hypothesis_id + self.glycan_combination_count = glycan_combination_count + self.current_glycan_offset = 0 + self.glycan_limit = glycan_limit + + self.input_queue = Queue(10) + self.output_queue = Queue(1000) + self.workers = [] + self.dealt_done_event = Event() + self.ipc_controller = self.ipc_logger() + self.database_mutex = RLock() + + def spawn_worker(self): + worker = QueuePushingPeptideGlycosylatingProcess( + self.connection_specification, self.hypothesis_id, self.input_queue, + self.output_queue, self.chunk_size, self.dealt_done_event, + self.ipc_controller.sender(), self.database_mutex, + glycan_offset=self.current_glycan_offset, + glycan_limit=self.glycan_limit) + return worker + + def push_work_batches(self, peptide_ids): + n = len(peptide_ids) + i = 0 + chunk_size = max(min(int(n * 0.05), 1000), 5) + while i < n: + self.input_queue.put(peptide_ids[i:(i + chunk_size)]) + i += chunk_size + self.log(""... Dealt Peptides %d-%d %0.2f%%"" % (i - chunk_size, min(i, n), (min(i, n) / float(n)) * 100)) + self.log(""... All Peptides Dealt"") + self.dealt_done_event.set() + + def create_queue_feeder_thread(self, peptide_ids): + queue_feeder = Thread(target=self.push_work_batches, args=(peptide_ids,)) + queue_feeder.daemon = True + queue_feeder.start() + return queue_feeder + + def spawn_all_workers(self): + self.workers = [] + + for i in range(self.n_processes): + worker = self.spawn_worker() + worker.start() + self.workers.append(worker) + + def process(self, peptide_ids): + connection = DatabaseBoundOperation(self.connection_specification) + session = connection.session + + self.log(""Begin Creation. Dropping Indices"") + index_controller = toggle_indices(session, Glycopeptide) + index_controller.drop() + + while self.current_glycan_offset < self.glycan_combination_count: + _current_progress = float(self.current_glycan_offset + self.glycan_limit) + _current_percent_complete = _current_progress / self.glycan_combination_count * 100.0 + _current_percent_complete = min(_current_percent_complete, 100.0) + self.log(""... Processing Glycan Combinations %d-%d (%0.2f%%)"" % ( + self.current_glycan_offset, min(self.current_glycan_offset + self.glycan_limit, + self.glycan_combination_count), + _current_percent_complete)) + queue_feeder = self.create_queue_feeder_thread(peptide_ids) + self.spawn_all_workers() + + has_work = True + last = 0 + i = 0 + while has_work: + try: + batch = self.output_queue.get(True, 5) + try: + waiting_batches = self.output_queue.qsize() + if waiting_batches > 10: + with self.database_mutex: + self.log(""... %d waiting sets."" % (waiting_batches,)) + try: + for _ in range(waiting_batches): + batch.extend(self.output_queue.get(True, 1)) + # check to see if any new work items have arrived while + # we've been draining the queue + waiting_batches = self.output_queue.qsize() + if waiting_batches != 0: + # if so, while the barrier is up, let's write the batch + # to disk and then try to drain the queue again + i += len(batch) + try: + session.bulk_insert_mappings(Glycopeptide, batch, render_nulls=True) + session.commit() + except Exception: + session.rollback() + raise + batch = [] + for _ in range(waiting_batches): + batch.extend(self.output_queue.get_nowait()) + except QueueEmptyException: + pass + except NotImplementedError: + # platform does not support qsize() + pass + + with self.database_mutex: + i += len(batch) + + try: + session.bulk_insert_mappings(Glycopeptide, batch, render_nulls=True) + session.commit() + except Exception: + session.rollback() + raise + + if (i - last) > self.chunk_size * 20: + self.log(""... %d Glycopeptides Created"" % (i,)) + last = i + except QueueEmptyException: + if all(w.is_work_done() for w in self.workers): + has_work = False + continue + + queue_feeder.join() + + for worker in self.workers: + self.log(""Joining Process %r (%s)"" % (worker.pid, worker.is_alive())) + worker.join(10) + if worker.is_alive(): + self.log(""Failed to join %r"" % worker.pid) + if worker.exitcode != 0 and worker.exitcode is not None: + raise ValueError(""One or more workers failed to exit successfully"") + + self.current_glycan_offset += self.glycan_limit + + self.log(""All Work Done. Rebuilding Indices"") + index_controller.create() + + +class ProteinReversingMixin: + def reverse_protein(self, protein: Protein) -> Protein: + original_sequence = protein.protein_sequence + n = len(original_sequence) + if ""("" in protein.protein_sequence: + protein.protein_sequence = str(reverse_sequence( + protein.protein_sequence, suffix_len=0)) + + else: + protein.protein_sequence = protein.protein_sequence[::-1] + protein.hypothesis_id = self.hypothesis_id + sites = [] + original_sequence = PeptideSequence(original_sequence) + try: + n_glycosites = find_n_glycosylation_sequons( + original_sequence, + include_cysteine=self.include_cysteine_n_glycosylation) + for n_glycosite in n_glycosites: + sites.append( + ProteinSite(name=ProteinSite.N_GLYCOSYLATION, location=n - n_glycosite - 1)) + except UnknownAminoAcidException: + pass + protein.sites.extend(sites) + return protein +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/naive_glycopeptide.py",".py","10817","252"," +from typing import Optional + +from glycopeptidepy.structure.residue import UnknownAminoAcidException + +from glycresoft.serialize import func +from glycresoft.serialize.hypothesis.peptide import ( + Peptide, Protein, Glycopeptide) +from glycresoft.serialize.utils import toggle_indices + +from six import string_types as basestring + +from .proteomics.peptide_permutation import ( + ProteinDigestor, + MultipleProcessProteinDigestor, + UniprotProteinAnnotator) + +from .proteomics.fasta import open_fasta +from .common import ( + GlycopeptideHypothesisSerializerBase, + PeptideGlycosylator, PeptideGlycosylatingProcess, + NonSavingPeptideGlycosylatingProcess, + MultipleProcessPeptideGlycosylator, ProteinReversingMixin) + + + + +class FastaGlycopeptideHypothesisSerializer(GlycopeptideHypothesisSerializerBase): + def __init__(self, fasta_file, connection, glycan_hypothesis_id, hypothesis_name=None, + protease='trypsin', constant_modifications=None, variable_modifications=None, + max_missed_cleavages=2, max_glycosylation_events=1, semispecific=False, + max_variable_modifications=None, full_cross_product=True, + peptide_length_range=(5, 60), require_glycosylation_sites=True, + use_uniprot=True, include_cysteine_n_glycosylation: bool=False, + uniprot_source_file: Optional[str]=None): + GlycopeptideHypothesisSerializerBase.__init__( + self, connection, hypothesis_name, glycan_hypothesis_id, full_cross_product, + use_uniprot=use_uniprot, + uniprot_source_file=uniprot_source_file) + self.fasta_file = fasta_file + self.protease = protease + self.constant_modifications = constant_modifications + self.variable_modifications = variable_modifications + self.max_missed_cleavages = max_missed_cleavages + self.max_glycosylation_events = max_glycosylation_events + self.semispecific = semispecific + self.max_variable_modifications = max_variable_modifications + self.peptide_length_range = peptide_length_range or (5, 60) + self.require_glycosylation_sites = require_glycosylation_sites + self.include_cysteine_n_glycosylation = include_cysteine_n_glycosylation + + params = { + ""fasta_file"": fasta_file, + ""enzymes"": [protease] if isinstance(protease, basestring) else list(protease), + ""constant_modifications"": constant_modifications, + ""variable_modifications"": variable_modifications, + ""max_missed_cleavages"": max_missed_cleavages, + ""max_glycosylation_events"": max_glycosylation_events, + ""semispecific"": semispecific, + ""max_variable_modifications"": max_variable_modifications, + ""full_cross_product"": self.full_cross_product, + ""peptide_length_range"": self.peptide_length_range, + ""require_glycosylation_sites"": self.require_glycosylation_sites, + ""include_cysteine_n_glycosylation"": self.include_cysteine_n_glycosylation, + ""uniprot_source_file"": self.uniprot_source_file, + } + self.set_parameters(params) + + def extract_proteins(self): + i = 0 + protein: Protein + for protein in open_fasta(self.fasta_file): + protein.hypothesis_id = self.hypothesis_id + protein._init_sites( + include_cysteine_n_glycosylation=self.include_cysteine_n_glycosylation) + + self.session.add(protein) + i += 1 + if i % 5000 == 0: + self.log(""... %d Proteins Extracted"" % (i,)) + self.session.commit() + + self.session.commit() + self.log(""%d Proteins Extracted"" % (i,)) + return i + + def protein_ids(self): + return [i[0] for i in self.query(Protein.id).filter(Protein.hypothesis_id == self.hypothesis_id).all()] + + def _make_digestor(self): + digestor = ProteinDigestor( + self.protease, self.constant_modifications, self.variable_modifications, + self.max_missed_cleavages, + min_length=self.peptide_length_range[0], + max_length=self.peptide_length_range[1], + semispecific=self.semispecific, + require_glycosylation_sites=self.require_glycosylation_sites, + include_cysteine_n_glycosylation=self.include_cysteine_n_glycosylation) + return digestor + + def digest_proteins(self): + digestor = self._make_digestor() + i = 0 + j = 0 + protein_ids = self.protein_ids() + n = len(protein_ids) + interval = min(n / 10., 100000) + acc = [] + for protein_id in protein_ids: + i += 1 + protein = self.query(Protein).get(protein_id) + if i % interval == 0: + self.log(""... %0.3f%% Complete (%d/%d). %d Peptides Produced."" % (i * 100. / n, i, n, j)) + for peptide in digestor.process_protein(protein): + acc.append(peptide) + j += 1 + if len(acc) > 100000: + self.session.bulk_save_objects(acc) + self.session.commit() + acc = [] + self.session.bulk_save_objects(acc) + self.session.commit() + acc = [] + + def split_proteins(self): + annotator = UniprotProteinAnnotator( + self, + self.protein_ids(), + self.constant_modifications, + self.variable_modifications, + include_cysteine_n_glycosylation=self.include_cysteine_n_glycosylation, + uniprot_source_file=self.uniprot_source_file) + annotator.run() + self.deduplicate_peptides() + + def glycosylate_peptides(self): + glycosylator = PeptideGlycosylator(self.session, self.hypothesis_id) + acc = [] + i = 0 + for peptide_id in self.peptide_ids(): + peptide = self.query(Peptide).get(peptide_id) + for glycopeptide in glycosylator.handle_peptide(peptide): + acc.append(glycopeptide) + i += 1 + if len(acc) > 100000: + self.session.bulk_insert_mappings(Glycopeptide, acc, render_nulls=True) + self.session.commit() + acc = [] + self.session.bulk_insert_mappings(Glycopeptide, acc, render_nulls=True) + self.session.commit() + + def run(self): + self.log(""Extracting Proteins"") + self.extract_proteins() + self.log(""Digesting Proteins"") + index_toggler = toggle_indices(self.session, Peptide) + index_toggler.drop() + self.digest_proteins() + self.log(""Rebuilding Peptide Index"") + index_toggler.create() + if self.use_uniprot: + self.split_proteins() + self.log(""Combinating Glycans"") + self.combinate_glycans(self.max_glycosylation_events) + if self.full_cross_product: + self.log(""Building Glycopeptides"") + self.glycosylate_peptides() + self._sql_analyze_database() + if self.full_cross_product: + self._count_produced_glycopeptides() + self.log(""Done"") + + +class MultipleProcessFastaGlycopeptideHypothesisSerializer(FastaGlycopeptideHypothesisSerializer): + def __init__(self, fasta_file, connection, glycan_hypothesis_id, hypothesis_name=None, + protease='trypsin', constant_modifications=None, variable_modifications=None, + max_missed_cleavages=2, max_glycosylation_events=1, semispecific=False, + max_variable_modifications=None, full_cross_product=True, peptide_length_range=(5, 60), + require_glycosylation_sites: bool=True, use_uniprot: bool=True, + include_cysteine_n_glycosylation: bool=False, + uniprot_source_file: Optional[str]=None, + n_processes: int=4): + super(MultipleProcessFastaGlycopeptideHypothesisSerializer, self).__init__( + fasta_file, connection, glycan_hypothesis_id, hypothesis_name, + protease=protease, + constant_modifications=constant_modifications, + variable_modifications=variable_modifications, + max_missed_cleavages=max_missed_cleavages, + max_glycosylation_events=max_glycosylation_events, + semispecific=semispecific, + max_variable_modifications=max_variable_modifications, + full_cross_product=full_cross_product, + peptide_length_range=peptide_length_range, + require_glycosylation_sites=require_glycosylation_sites, + use_uniprot=use_uniprot, + include_cysteine_n_glycosylation=include_cysteine_n_glycosylation, + uniprot_source_file=uniprot_source_file) + self.n_processes = n_processes + + def digest_proteins(self): + digestor = self._make_digestor() + task = MultipleProcessProteinDigestor( + self._original_connection, + self.hypothesis_id, + self.protein_ids(), + digestor, n_processes=self.n_processes) + task.run() + n_peptides = self.query(func.count(Peptide.id)).filter( + Peptide.hypothesis_id == self.hypothesis_id).scalar() + self.log(""%d Base Peptides Produced"" % (n_peptides,)) + + def _spawn_glycosylator(self, input_queue, done_event): + return PeptideGlycosylatingProcess( + self._original_connection, self.hypothesis_id, input_queue, + chunk_size=3500, done_event=done_event) + + def glycosylate_peptides(self): + dispatcher = MultipleProcessPeptideGlycosylator( + self._original_connection, self.hypothesis_id, + glycan_combination_count=self.total_glycan_combination_count, + n_processes=self.n_processes) + dispatcher.process(self.peptide_ids()) + + +_MPFGHS = MultipleProcessFastaGlycopeptideHypothesisSerializer + +class ReversingMultipleProcessFastaGlycopeptideHypothesisSerializer(_MPFGHS, ProteinReversingMixin): + def extract_proteins(self): + i = 0 + for protein in open_fasta(self.fasta_file): + try: + protein = self.reverse_protein(protein) + except UnknownAminoAcidException: + continue + + self.session.add(protein) + i += 1 + if i % 5000 == 0: + self.log(""... %d Proteins Extracted"" % (i,)) + self.session.commit() + + self.session.commit() + self.log(""%d Proteins Extracted"" % (i,)) + return i + + +class NonSavingMultipleProcessFastaGlycopeptideHypothesisSerializer(_MPFGHS): + def _spawn_glycosylator(self, input_queue, done_event): + return NonSavingPeptideGlycosylatingProcess( + self._original_connection, self.hypothesis_id, input_queue, + chunk_size=3500, done_event=done_event) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/informed_glycopeptide.py",".py","8810","195","import os +from typing import Optional +from glycresoft.serialize.hypothesis.peptide import (Peptide, Glycopeptide) + +from .common import ( + GlycopeptideHypothesisSerializerBase, PeptideGlycosylator, + MultipleProcessPeptideGlycosylator) +from .proteomics import mzid_proteome + + +class MzIdentMLGlycopeptideHypothesisSerializer(GlycopeptideHypothesisSerializerBase): + _display_name = ""MzIdentML Glycopeptide Hypothesis Serializer"" + + def __init__(self, mzid_path, connection, glycan_hypothesis_id, hypothesis_name=None, + target_proteins=None, max_glycosylation_events=1, reference_fasta=None, + full_cross_product=True, peptide_length_range=(5, 60), use_uniprot=True, + uniprot_source_file: Optional[str]=None): + if target_proteins is None: + target_proteins = [] + GlycopeptideHypothesisSerializerBase.__init__( + self, connection, hypothesis_name, glycan_hypothesis_id, + full_cross_product, use_uniprot=use_uniprot, uniprot_source_file=uniprot_source_file) + self.mzid_path = mzid_path + self.reference_fasta = reference_fasta + self._make_proteome(mzid_path, target_proteins, reference_fasta) + self.target_proteins = target_proteins + self.max_glycosylation_events = max_glycosylation_events + self.peptide_length_range = peptide_length_range or (5, 60) + assert len(self.peptide_length_range) == 2 + + self.set_parameters({ + ""mzid_file"": os.path.abspath(mzid_path), + ""reference_fasta"": os.path.abspath( + reference_fasta) if reference_fasta is not None else None, + ""target_proteins"": target_proteins, + ""max_glycosylation_events"": max_glycosylation_events, + ""full_cross_product"": self.full_cross_product, + ""peptide_length_range"": self.peptide_length_range + }) + + def _make_proteome(self, mzid_path, target_proteins, reference_fasta): + self.proteome = mzid_proteome.Proteome( + mzid_path, self._original_connection, self.hypothesis_id, + target_proteins=target_proteins, + reference_fasta=reference_fasta, + use_uniprot=self.use_uniprot, + uniprot_source_file=self.uniprot_source_file + ) + + def retrieve_target_protein_ids(self): + return self.proteome.retrieve_target_protein_ids() + + def peptide_ids(self): + out = [] + for protein_id in self.retrieve_target_protein_ids(): + out.extend(i[0] for i in self.query(Peptide.id).filter( + Peptide.protein_id == protein_id)) + return out + + def glycosylate_peptides(self): + glycosylator = PeptideGlycosylator(self.session, self.hypothesis_id) + acc = [] + i = 0 + for peptide_id in self.peptide_ids(): + peptide = self.query(Peptide).get(peptide_id) + for glycopeptide in glycosylator.handle_peptide(peptide): + acc.append(glycopeptide) + i += 1 + if len(acc) > 100000: + self.session.bulk_insert_mappings(Glycopeptide, acc, render_nulls=True) + self.session.commit() + acc = [] + self.session.bulk_insert_mappings(Glycopeptide, acc, render_nulls=True) + self.session.commit() + + def run(self): + self.log(""Loading Proteome"") + self.proteome.load() + self.set_parameters({ + ""enzymes"": self.proteome.enzymes, + ""constant_modifications"": self.proteome.constant_modifications, + ""include_baseline_peptides"": self.proteome.include_baseline_peptides + }) + self.log(""Combinating Glycans"") + self.combinate_glycans(self.max_glycosylation_events) + if self.full_cross_product: + self.log(""Building Glycopeptides"") + self.glycosylate_peptides() + self._sql_analyze_database() + if self.full_cross_product: + self._count_produced_glycopeptides() + self.log(""Done"") + + +class MultipleProcessMzIdentMLGlycopeptideHypothesisSerializer(MzIdentMLGlycopeptideHypothesisSerializer): + _display_name = ""Multiple Process MzIdentML Glycopeptide Hypothesis Serializer"" + + def __init__(self, mzid_path, connection, glycan_hypothesis_id, hypothesis_name=None, + target_proteins=None, max_glycosylation_events=1, reference_fasta=None, + full_cross_product=True, peptide_length_range=(5, 60), + uniprot_source_file: Optional[str]=None, + n_processes=4): + super(MultipleProcessMzIdentMLGlycopeptideHypothesisSerializer, self).__init__( + mzid_path, connection, glycan_hypothesis_id, hypothesis_name, target_proteins, + max_glycosylation_events, reference_fasta, full_cross_product, + peptide_length_range, uniprot_source_file=uniprot_source_file) + self.n_processes = n_processes + self.proteome.n_processes = n_processes + + def glycosylate_peptides(self): + dispatcher = MultipleProcessPeptideGlycosylator( + self._original_connection, self.hypothesis_id, + glycan_combination_count=self.total_glycan_combination_count, + n_processes=self.n_processes) + dispatcher.process(self.peptide_ids()) + + +class ReversingMultipleProcessMzIdentMLGlycopeptideHypothesisSerializer(MultipleProcessMzIdentMLGlycopeptideHypothesisSerializer): + def _make_proteome(self, mzid_path, target_proteins, reference_fasta): + self.proteome = mzid_proteome.ReverseProteome( + mzid_path, self._original_connection, self.hypothesis_id, + target_proteins=target_proteins, + reference_fasta=reference_fasta, + use_uniprot=self.use_uniprot, + uniprot_source_file=self.uniprot_source_file + ) + + +class MzIdentMLPeptideHypothesisSerializer(GlycopeptideHypothesisSerializerBase): + def __init__(self, mzid_path, connection, hypothesis_name=None, + target_proteins=None, reference_fasta=None, + include_baseline_peptides=False, + uniprot_source_file: Optional[str] = None): + if target_proteins is None: + target_proteins = [] + GlycopeptideHypothesisSerializerBase.__init__( + self, connection, hypothesis_name, 0, uniprot_source_file=uniprot_source_file) + self.mzid_path = mzid_path + self.reference_fasta = reference_fasta + self.proteome = mzid_proteome.Proteome( + mzid_path, self._original_connection, self.hypothesis_id, + target_proteins=target_proteins, reference_fasta=reference_fasta, + include_baseline_peptides=include_baseline_peptides) + self.target_proteins = target_proteins + self.include_baseline_peptides = include_baseline_peptides + + self.set_parameters({ + ""mzid_file"": os.path.abspath(mzid_path), + ""reference_fasta"": os.path.abspath( + reference_fasta) if reference_fasta is not None else None, + ""target_proteins"": target_proteins, + }) + + def retrieve_target_protein_ids(self): + # if len(self.target_proteins) == 0: + # return [ + # i[0] for i in + # self.query(Protein.id).filter( + # Protein.hypothesis_id == self.hypothesis_id).all() + # ] + # else: + # result = [] + # for target in self.target_proteins: + # if isinstance(target, basestring): + # if target in self.proteome.accession_map: + # target = self.proteome.accession_map[target] + # match = self.query(Protein.id).filter( + # Protein.name == target, + # Protein.hypothesis_id == self.hypothesis_id).first() + # if match: + # result.append(match[0]) + # else: + # self.log(""Could not locate protein '%s'"" % target) + # elif isinstance(target, int): + # result.append(target) + # return result + return self.proteome.retrieve_target_protein_ids() + + def peptide_ids(self): + out = [] + for protein_id in self.retrieve_target_protein_ids(): + out.extend(i[0] for i in self.query(Peptide.id).filter( + Peptide.protein_id == protein_id)) + return out + + def run(self): + self.log(""Loading Proteome"") + self.proteome.load() + self.set_parameters({ + ""enzymes"": self.proteome.enzymes, + ""constant_modifications"": self.proteome.constant_modifications, + ""include_baseline_peptides"": self.proteome.include_baseline_peptides + }) + self.log(""Done"") +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/migrate.py",".py","10423","227","from uuid import uuid4 + +from glycresoft.serialize import ( + DatabaseBoundOperation, GlycopeptideHypothesis, + Protein, Peptide, Glycopeptide, GlycanCombination, + GlycanCombinationGlycanComposition, ProteinSite) + +from glycresoft.serialize.utils import get_uri_for_instance + +from glycresoft.database.builder.glycan.migrate import GlycanHypothesisMigrator + +from glycresoft.task import TaskBase + + +class GlycopeptideHypothesisMigrator(DatabaseBoundOperation, TaskBase): + def __init__(self, database_connection): + DatabaseBoundOperation.__init__(self, database_connection) + self.hypothesis_id = None + self.glycan_hypothesis_id = None + self._glycan_hypothesis_migrator = None + self.protein_id_map = dict() + self.peptide_id_map = dict() + self.glycan_combination_id_map = dict() + self.glycopeptide_id_map = dict() + + def clear(self): + self.protein_id_map.clear() + self.peptide_id_map.clear() + self.glycan_combination_id_map.clear() + self.glycopeptide_id_map.clear() + + def _migrate(self, obj): + self.session.add(obj) + self.session.flush() + new_id = obj.id + return new_id + + def commit(self): + self.session.commit() + + def migrate_hypothesis(self, hypothesis): + new_inst = GlycopeptideHypothesis( + name=hypothesis.name, + uuid=str(uuid4().hex), + status=hypothesis.status, + glycan_hypothesis_id=None, + parameters=dict(hypothesis.parameters)) + new_inst.parameters[""original_uuid""] = hypothesis.uuid + new_inst.parameters['copied_from'] = get_uri_for_instance(hypothesis) + self.hypothesis_id = self._migrate(new_inst) + self.create_glycan_hypothesis_migrator(hypothesis.glycan_hypothesis) + new_inst.glycan_hypothesis_id = self.glycan_hypothesis_id + self._migrate(new_inst) + + def migrate_glycan_composition(self, glycan_composition): + self._glycan_hypothesis_migrator.migrate_glycan_composition( + glycan_composition) + + def migrate_glycan_combination(self, glycan_combination): + new_inst = GlycanCombination( + calculated_mass=glycan_combination.calculated_mass, + formula=glycan_combination.formula, + composition=glycan_combination.composition, + count=glycan_combination.count, + hypothesis_id=self.hypothesis_id) + self.glycan_combination_id_map[glycan_combination.id] = self._migrate(new_inst) + component_acc = [] + for component, count in glycan_combination.components.add_columns( + GlycanCombinationGlycanComposition.c.count): + new_component_id = self._glycan_hypothesis_migrator.glycan_composition_id_map[component.id] + component_acc.append( + {""glycan_id"": new_component_id, ""combination_id"": new_inst.id, ""count"": count}) + if component_acc: + self.session.execute(GlycanCombinationGlycanComposition.insert(), component_acc) + + def migrate_protein(self, protein): + new_inst = Protein( + name=protein.name, + protein_sequence=protein.protein_sequence, + other=dict(protein.other or dict()), + hypothesis_id=self.hypothesis_id) + new_id = self._migrate(new_inst) + self.protein_id_map[protein.id] = new_id + for position in protein.sites.all(): + self.session.add( + ProteinSite(location=position.location, name=position.name, protein_id=new_id)) + self.session.flush() + + def create_glycan_hypothesis_migrator(self, glycan_hypothesis): + self._glycan_hypothesis_migrator = GlycanHypothesisMigrator(self._original_connection) + self._glycan_hypothesis_migrator.bridge(self) + self._glycan_hypothesis_migrator.migrate_hypothesis(glycan_hypothesis) + self.glycan_hypothesis_id = self._glycan_hypothesis_migrator.hypothesis_id + + def migrate_peptides_bulk(self, peptides): + reverse_map = {} + n = len(peptides) + buffer = [] + for i, peptide in enumerate(peptides): + if i % 15000 == 0 and i: + self.log(""... Migrating Peptides %d/%d (%0.2f%%)"" % + (i, n, i * 100.0 / n)) + self.session.bulk_save_objects(buffer) + buffer = [] + new_inst = Peptide( + calculated_mass=peptide.calculated_mass, + base_peptide_sequence=peptide.base_peptide_sequence, + modified_peptide_sequence=peptide.modified_peptide_sequence, + formula=peptide.formula, + count_glycosylation_sites=peptide.count_glycosylation_sites, + count_missed_cleavages=peptide.count_missed_cleavages, + count_variable_modifications=peptide.count_variable_modifications, + start_position=peptide.start_position, + end_position=peptide.end_position, + peptide_score=peptide.peptide_score, + peptide_score_type=peptide.peptide_score_type, + sequence_length=peptide.sequence_length, + # Update the protein id + protein_id=self.protein_id_map[peptide.protein_id], + # Update the hypothesis id + hypothesis_id=self.hypothesis_id, + n_glycosylation_sites=peptide.n_glycosylation_sites, + o_glycosylation_sites=peptide.o_glycosylation_sites, + gagylation_sites=peptide.gagylation_sites) + buffer.append(new_inst) + reverse_map[(peptide.modified_peptide_sequence, + self.protein_id_map[peptide.protein_id], + peptide.start_position, )] = peptide.id + + if buffer: + self.session.bulk_save_objects(buffer) + buffer = [] + + self.session.flush() + self.log(""... Reconstructing Reverse Mapping"") + migrated = self.session.query( + Peptide.id, Peptide.modified_peptide_sequence, + Peptide.protein_id, Peptide.start_position).filter( + Peptide.hypothesis_id == self.hypothesis_id).yield_per(10000) + m = 0 + for peptide in migrated: + m += 1 + self.peptide_id_map[ + reverse_map[peptide.modified_peptide_sequence, + peptide.protein_id, peptide.start_position]] = peptide.id + if m != n: + raise ValueError(""Peptide Migration Unsuccessful"") + return m + + def migrate_peptide(self, peptide): + new_inst = Peptide( + calculated_mass=peptide.calculated_mass, + base_peptide_sequence=peptide.base_peptide_sequence, + modified_peptide_sequence=peptide.modified_peptide_sequence, + formula=peptide.formula, + count_glycosylation_sites=peptide.count_glycosylation_sites, + count_missed_cleavages=peptide.count_missed_cleavages, + count_variable_modifications=peptide.count_variable_modifications, + start_position=peptide.start_position, + end_position=peptide.end_position, + peptide_score=peptide.peptide_score, + peptide_score_type=peptide.peptide_score_type, + sequence_length=peptide.sequence_length, + # Update the protein id + protein_id=self.protein_id_map[peptide.protein_id], + # Update the hypothesis id + hypothesis_id=self.hypothesis_id, + n_glycosylation_sites=peptide.n_glycosylation_sites, + o_glycosylation_sites=peptide.o_glycosylation_sites, + gagylation_sites=peptide.gagylation_sites) + self.peptide_id_map[peptide.id] = self._migrate(new_inst) + + def migrate_glycopeptide_bulk(self, glycopeptides): + reverse_map = {} + n = len(glycopeptides) + buffer = [] + for i, glycopeptide in enumerate(glycopeptides): + if i % 50000 == 0 and i: + self.log(""... Migrating Glycopeptide %d/%d (%0.2f%%)"" % (i, n, i * 100.0 / n)) + self.session.bulk_save_objects(buffer) + buffer = [] + new_inst = Glycopeptide( + calculated_mass=glycopeptide.calculated_mass, + formula=glycopeptide.formula, + glycopeptide_sequence=glycopeptide.glycopeptide_sequence, + peptide_id=self.peptide_id_map[glycopeptide.peptide_id], + protein_id=self.protein_id_map[glycopeptide.protein_id], + hypothesis_id=self.hypothesis_id, + glycan_combination_id=self.glycan_combination_id_map[glycopeptide.glycan_combination_id]) + buffer.append(new_inst) + reverse_map[(glycopeptide.glycopeptide_sequence, + self.peptide_id_map[glycopeptide.peptide_id], + self.glycan_combination_id_map[glycopeptide.glycan_combination_id], )] = glycopeptide.id + + if buffer: + self.session.bulk_save_objects(buffer) + buffer = [] + + self.session.flush() + self.log(""... Reconstructing Reverse Mapping"") + migrated = self.session.query( + Glycopeptide.id, Glycopeptide.glycopeptide_sequence, + Glycopeptide.peptide_id, Glycopeptide.glycan_combination_id).filter( + Glycopeptide.hypothesis_id == self.hypothesis_id).yield_per(10000) + + m = 0 + for glycopeptide in migrated: + m += 1 + self.glycopeptide_id_map[ + reverse_map[glycopeptide.glycopeptide_sequence, + glycopeptide.peptide_id, + glycopeptide.glycan_combination_id]] = glycopeptide.id + if m != n: + raise ValueError(""Glycopeptide Migration Unsuccessful"") + return m + + def migrate_glycopeptide(self, glycopeptide): + new_inst = Glycopeptide( + calculated_mass=glycopeptide.calculated_mass, + formula=glycopeptide.formula, + glycopeptide_sequence=glycopeptide.glycopeptide_sequence, + peptide_id=self.peptide_id_map[glycopeptide.peptide_id], + protein_id=self.protein_id_map[glycopeptide.protein_id], + hypothesis_id=self.hypothesis_id, + glycan_combination_id=self.glycan_combination_id_map[glycopeptide.glycan_combination_id]) + self.glycopeptide_id_map[glycopeptide.id] = self._migrate(new_inst) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/extending_glycopeptide.py",".py","4074","123","from glypy.composition import formula + +from .proteomics.peptide_permutation import peptide_permutations +from glycresoft.serialize import Peptide, DatabaseBoundOperation + + +class ProteomeCollection(object): + def __init__(self, proteins, peptides): + self.proteins = proteins + self.peptides = peptides + + def add_modifications(self, constant_modifications=None, variable_modifications=None, max_variable_modifications=4): + if constant_modifications is None: + constant_modifications = [] + if variable_modifications is None: + variable_modifications = [] + result = MemoryPeptideCollection() + for peptide in self.peptides: + for modified_peptide, n_variable_modifications in peptide_permutations( + str(peptide), constant_modifications, variable_modifications): + total_modification_count = ( + n_variable_modifications + peptide.count_variable_modifications) + if total_modification_count > max_variable_modifications: + continue + inst = Peptide( + base_peptide_sequence=peptide.base_peptide_sequence, + modified_peptide_sequence=str(modified_peptide), + count_missed_cleavages=peptide.count_missed_cleavages, + count_variable_modifications=total_modification_count, + sequence_length=peptide.sequence_length, + start_position=peptide.start_position, + end_position=peptide.end_position, + calculated_mass=modified_peptide.mass, + formula=formula(modified_peptide.total_composition())) + result.add(inst) + return result + + +class PeptideCollectionBase(object): + def __init__(self, *args, **kwargs): + pass + + def __iter__(self): + raise NotImplementedError() + + def add(self, peptide): + raise NotImplementedError() + + def update(self, peptides): + for peptide in peptides: + self.add(peptide) + + def save(self): + raise NotImplementedError() + + def __len__(self): + raise NotImplementedError() + + def __repr__(self): + return ""{self.__class__.__name__}({size})"".format(self=self, size=len(self)) + + +class MemoryPeptideCollection(PeptideCollectionBase): + def __init__(self, storage=None, *args, **kwargs): + PeptideCollectionBase.__init__(self, *args, **kwargs) + self.storage = list(storage or []) + + def __iter__(self): + return iter(self.storage) + + def __len__(self): + return len(self.storage) + + def add(self, peptide): + self.storage.append(peptide) + + def save(self): + pass + + +class DatabasePeptideCollection(PeptideCollectionBase, DatabaseBoundOperation): + def __init__(self, connection, hypothesis_id=None, *args, **kwargs): + if hypothesis_id is None: + hypothesis_id = 1 + DatabaseBoundOperation.__init__(self, connection) + PeptideCollectionBase.__init__(self, *args, **kwargs) + self.hypothesis_id = hypothesis_id + self._operation_count = 0 + self._batch_size = int(kwargs.get(""batch_size"", 1000)) + + def __iter__(self): + q = self._get_query() + q = q.yield_per(5000) + return q + + def _get_query(self): + q = self.session.query(Peptide).filter(Peptide.hypothesis_id == self.hypothesis_id) + return q + + def __len__(self): + return self._get_query().count() + + def _add(self, peptide): + peptide.hypothesis_id = self.hypothesis_id + self.session.add(peptide) + self._operation_count += 1 + + def add(self, peptide): + self._add(peptide) + self._flush_if_work_done() + + def update(self, peptides): + for peptide in peptides: + self._add(peptide) + self._flush_if_work_done() + + def _flush_if_work_done(self): + if self._operation_count > self._batch_size: + self.session.flush() + + def save(self): + self.session.commit() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/proteomics/fasta.py",".py","7776","263","import re +import textwrap +from io import BytesIO, TextIOWrapper + +from collections import OrderedDict +from typing import Union + +from glycopeptidepy.io.fasta import FastaFileParser, FastaFileWriter, PEFFReader +from glycopeptidepy.io.annotation import from_peff + +from glycresoft.serialize.hypothesis.peptide import Protein +from .sequence_tree import SuffixTree + + +class ProteinFastaFileParser(FastaFileParser): + def __init__(self, *args, **kwargs): + super(ProteinFastaFileParser, self).__init__(*args, **kwargs) + + def process_result(self, d): + p = Protein(name=str(d['name']), protein_sequence=d['sequence']) + return p + + +class PEFFProteinFastaFileParser(PEFFReader): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def process_result(self, d): + p = Protein(name=str(d['name']), protein_sequence=d['sequence']) + p.annotations = from_peff(d['name']) + return p + + +def open_fasta(path: str): + if path.endswith("".peff"") or path.endswith("".peff.gz""): + return PEFFProteinFastaFileParser(path) + else: + return ProteinFastaFileParser(path) + + +class ProteinFastaFileWriter(FastaFileWriter): + + def write(self, protein): + defline = ''.join( + ["">"", protein.name, "" "", str(protein.glycosylation_sites)]) + seq = '\n'.join(textwrap.wrap(protein.protein_sequence, 80)) + super(ProteinFastaFileWriter, self).write(defline, seq) + + def writelines(self, iterable): + for protein in iterable: + self.write(protein) + + +class SequenceLabel(object): + + def __init__(self, label, sequence): + self.label = label + self.sequence = sequence + + def __getitem__(self, i): + if isinstance(i, int): + return self.label[i] + else: + return SequenceLabel(self.label[i], self.sequence) + + def __len__(self): + return len(self.label) + + def __iter__(self): + return iter(self.label) + + def __repr__(self): + return ""SequenceLabel(%s, %r)"" % (self.label, self.sequence) + + +class FastaIndex(object): + def __init__(self, path, block_size=1000000, encoding='utf-8'): + self.path = path + self.block_size = block_size + self.index = OrderedDict() + self.encoding = encoding + + self.build_index() + + def _chunk_iterator(self): + delim = b""\n>"" + read_size = self.block_size + with open(self.path, 'rb') as f: + buff = f.read(read_size) + started_with_with_delim = buff.startswith(delim) + parts = buff.split(delim) + tail = parts[-1] + front = parts[:-1] + i = 0 + for part in front: + i += 1 + if part == b'': + continue + if i == 1: + if started_with_with_delim: + yield delim + part + else: + yield part + else: + yield delim + part + running = True + while running: + buff = f.read(read_size) + if len(buff) == 0: + running = False + buff = tail + else: + buff = tail + buff + parts = buff.split(delim) + tail = parts[-1] + front = parts[:-1] + for part in front: + yield delim + part + yield delim + tail + + def _generate_offsets(self): + i = 0 + defline_pattern = re.compile(br""\s*>([^\n]+)\n"") + for line in self._chunk_iterator(): + match = defline_pattern.match(line) + if match: + yield i, match.group(1) + i += len(line) + yield i, None + + def build_index(self): + index = OrderedDict() + g = self._generate_offsets() + last_offset = 0 + last_defline = None + for offset, defline in g: + if last_defline is not None: + index[last_defline] = (last_offset, offset) + last_defline = defline + last_offset = offset + assert last_defline is None + self.index = index + + def _ensure_bytes(self, string): + if isinstance(string, bytes): + return string + try: + return string.encode(self.encoding) + except (AttributeError, UnicodeEncodeError): + raise TypeError(""{!r} could not be encoded"".format(string)) + + def _offset_of(self, key): + key = self._ensure_bytes(key) + return self.index[key] + + def __len__(self): + return len(self.index) + + def keys(self): + return self.index.keys() + + def __iter__(self): + return iter(self.index) + + def fetch_sequence(self, key): + start, end = self._offset_of(key) + with open(self.path, 'rb') as f: + f.seek(start) + data = f.read(end - start) + buff = TextIOWrapper(BytesIO(data)) + return next(ProteinFastaFileParser(buff)) + + def __getitem__(self, key): + return self.fetch_sequence(key) + + +class DeflineSuffix(object): + def __init__(self, label, original): + self.label = label + self.original = original + + def __getitem__(self, i): + if isinstance(i, int): + return self.label[i] + else: + return DeflineSuffix(self.label[i], self.original) + + def __len__(self): + return len(self.label) + + def __iter__(self): + return iter(self.label) + + def __repr__(self): + return ""DeflineSuffix(%s, %r)"" % (self.label, self.original) + + +class FastaProteinSequenceResolver(object): + def __init__(self, path, encoding='utf-8', strategy='exact'): + self.path = path + self.encoding = encoding + self.index = FastaIndex(self.path, encoding=self.encoding) + self.resolver = None + self.strategy = strategy + + self._build_resolver(strategy) + + def _build_resolver(self, strategy='exact'): + if strategy == 'suffix': + keys = self.index.keys() + resolver = SuffixTree() + i = 0 + for key in keys: + i += 1 + label = DeflineSuffix(key.decode(self.encoding).split("" "")[0], key) + resolver.add_ngram(label) + self.resolver = resolver + elif strategy == 'exact': + keys = self.index.keys() + resolver = dict() + i = 0 + for key in keys: + i += 1 + label = DeflineSuffix(key.decode(self.encoding).split("" "")[0], key) + resolver[label.label] = label + self.resolver = resolver + + def find(self, name): + if self.strategy == 'suffix': + labels = self.resolver.subsequences_of(name) + sequences = [ + self.index[label.original] for label in labels] + else: + try: + label = self.resolver[name] + return [self.index[label.original]] + except KeyError: + return [] + return sequences + + def __getitem__(self, name): + return self.find(name) + + +class ProteinSequenceListResolver(object): + + @classmethod + def build_from_fasta(cls, fasta): + return cls(ProteinFastaFileParser(fasta)) + + def __init__(self, protein_list): + protein_list = [SequenceLabel(str(prot.name), prot) + for prot in protein_list] + self.resolver = SuffixTree() + for prot in protein_list: + self.resolver.add_ngram(prot) + + def find(self, name): + return [label_seq.sequence for label_seq in self.resolver.subsequences_of(name)] + + def __getitem__(self, name): + return self.find(name) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/proteomics/mzid_parser.py",".py","8731","245","import re +import logging +from lxml.etree import LxmlError +from pyteomics import mzid +from pyteomics.xml import ( + unitint, unitfloat, unitstr) + +try: + from pyteomics.xml import cvstr +except ImportError: + def cvstr(x, *a, **kw): + return str(x) + + +logger = logging.getLogger(""mzid"") + +MzIdentML = mzid.MzIdentML +_local_name = mzid.xml._local_name +peptide_evidence_ref = re.compile(r""(?PPEPTIDEEVIDENCE_PEPTIDE_\d+_DBSEQUENCE_)(?P.+)"") + + +class MultipleProteinMatchesException(Exception): + + def __init__(self, message, evidence_id, db_sequences, key): + Exception.__init__(self, message) + self.evidence_id = evidence_id + self.db_sequences = db_sequences + self.key = key + + +class MultipleProteinInfoDict(dict): + multi = None + + +class MissingProteinException(Exception): + pass + + +class MissingPeptideEvidenceHandler(object): + parser = re.compile( + r""(?PPEPTIDEEVIDENCE_(?PPEPTIDE_\d+)_(?PDBSEQUENCE_.+))"") + + def __init__(self, full_id): + self.full_id = full_id + + def __repr__(self): + return ""MissingPeptideEvidenceHandler(%r)"" % (self.full_id,) + + def reconstruct_evidence(self): + match = self.parser.search(self.full_id) + if match is None: + raise ValueError(""Cannot interpret %r"" % (self.full_id,)) + data = match.groupdict() + result = { + ""isDecoy"": False, + ""end"": None, + ""start"": None, + ""peptide_ref"": data[""peptide_id""], + ""dBSequence_ref"": data['parent_accession'], + 'pre': None, + ""post"": None, + ""id"": self.full_id + } + return result + + @classmethod + def recover(cls, full_id): + inst = cls(full_id) + return inst.reconstruct_evidence() + + +class Parser(MzIdentML): + + _index_tags = MzIdentML._indexed_tags - {'SearchDatabase', } + + def _handle_ref(self, info, key, value): + try: + referenced = self.get_by_id(value, retrieve_refs=True) + except AttributeError: + if key == ""peptideEvidence_ref"": + referenced = MissingPeptideEvidenceHandler.recover(value) + else: + raise AttributeError(key) + info.update(referenced) + del info[key] + info.pop('id', None) + + def _retrieve_refs(self, info, **kwargs): + multi = None + for k, v in dict(info).items(): + if k.endswith('_ref'): + is_multi_db_sequence = peptide_evidence_ref.match(info[k]) + if is_multi_db_sequence and ':' in is_multi_db_sequence.groupdict()['parent_accession']: + groups = is_multi_db_sequence.groupdict() + evidence_id = groups['evidence_id'] + db_sequences = groups['parent_accession'].split(':') + if len(db_sequences) > 1: + multi = MultipleProteinMatchesException( + """", evidence_id, db_sequences, k) + else: + try: + self._handle_ref(info, k, v) + except (KeyError, LxmlError): + info['skip'] = True + info = MultipleProteinInfoDict(info) + info.multi = multi + return info, multi + + def _handle_param(self, element, **kwargs): + """"""Unpacks cvParam and userParam tags into key-value pairs"""""" + types = {'int': unitint, 'float': unitfloat, 'string': unitstr} + attribs = element.attrib + unit_info = None + unit_accesssion = None + if 'unitCvRef' in attribs or 'unitName' in attribs: + unit_accesssion = attribs.get('unitAccession') + unit_name = attribs.get(""unitName"", unit_accesssion) + unit_info = unit_name + accession = attribs.get(""accession"") + # value = attribs.get(""value"", """") + if 'value' in attribs and attribs['value'] != '': + try: + if attribs.get('type') in types: + value = types[attribs['type']](attribs['value'], unit_info) + else: + value = unitfloat(attribs['value'], unit_info) + except ValueError: + value = unitstr(attribs['value'], unit_info) + return {cvstr(attribs['name'], accession, unit_accesssion): value} + else: + return {'name': cvstr(attribs['name'], accession, unit_accesssion)} + + def _find_by_id_reset(self, *a, **kw): + return MzIdentML._find_by_id_reset(self, *a, **kw) + + def _insert_param(self, info, param, **kwargs): + newinfo = self._handle_param(param, **kwargs) + if not ('name' in info and 'name' in newinfo): + info.update(newinfo) + else: + if not isinstance(info['name'], list): + info['name'] = [info['name']] + info['name'].append(newinfo.pop('name')) + + def _find_immediate_params(self, element, **kwargs): + return element.xpath('./*[local-name()=""{}"" or local-name()=""{}""]'.format(""cvParam"", ""userParam"")) + + def _recursive_populate(self, element, info, kwargs): + for child in element.iterchildren(): + cname = _local_name(child) + if cname in ('cvParam', 'userParam'): + self._insert_param(info, child, **kwargs) + else: + if cname not in self.schema_info['lists']: + info[cname] = self._get_info_smart(child, **kwargs) + else: + info.setdefault(cname, []).append( + self._get_info_smart(child, **kwargs)) + + def _convert_values(self, element, info, kwargs): + converters = self._converters + for k, v in info.items(): + try: + for t, a in converters.items(): + if (_local_name(element), k) in self.schema_info[t]: + info[k] = a(v) + except KeyError: + continue + + def _populate_references(self, element, info, kwargs): + info = MultipleProteinInfoDict(info) + infos = [info] + # resolve refs + if kwargs.get('retrieve_refs'): + try: + _, multi = self._retrieve_refs(info, **kwargs) + except ValueError as e: + print(info, e, kwargs) + raise e + if multi is not None: + info.multi = multi + if info.multi: + e = info.multi + if e is not None: + evidence_id = e.evidence_id + db_sequences = e.db_sequences + key = e.key + infos = [] + for name in db_sequences: + dup = info.copy() + dup[key] = evidence_id + name + self._retrieve_refs(dup, **kwargs) + infos.append(dup) + return infos + + def _get_info(self, element, **kwargs): + """"""Extract info from element's attributes, possibly recursive. + and elements are treated in a special way."""""" + name = _local_name(element) + if name in {'cvParam', 'userParam'}: + return self._handle_param(element) + + info = dict(element.attrib) + # process subelements + if kwargs.get('recursive'): + self._recursive_populate(element, info, kwargs) + else: + for param in self._find_immediate_params(element): + self._insert_param(info, param, **kwargs) + + # process element text + if element.text and element.text.strip(): + stext = element.text.strip() + if stext: + if info: + info[name] = stext + else: + return stext + + self._convert_values(element, info, kwargs) + + infos = self._populate_references(element, info, kwargs) + + # flatten the excessive nesting + for info in infos: + for k, v in dict(info).items(): + if k in self._structures_to_flatten: + info.update(v) + del info[k] + + # another simplification + for k, v in dict(info).items(): + if isinstance(v, dict) and 'name' in v and len(v) == 1: + info[k] = v['name'] + out = [] + for info in infos: + if len(info) == 2 and 'name' in info and ( + 'value' in info or 'values' in info): + name = info.pop('name') + info = {name: info.popitem()[1]} + out.append(info) + if len(out) == 1: + out = out[0] + return out +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/proteomics/share_peptides.py",".py","7517","205","import logging +import re + + +from collections import defaultdict + + +from glycresoft.serialize import ( + Peptide, Protein, DatabaseBoundOperation) + +from .utils import slurp + + +from multiprocessing import Process, Queue, Event + + +logger = logging.getLogger(""share_peptides"") + + +class PeptideBlueprint(object): + def __init__(self, base_peptide_sequence, modified_peptide_sequence, sequence_length, + calculated_mass, formula, count_glycosylation_sites, count_missed_cleavages, + count_variable_modifications, peptide_score, peptide_score_type, n_glycosylation_sites, + o_glycosylation_sites, gagylation_sites): + self.base_peptide_sequence = base_peptide_sequence + self.modified_peptide_sequence = modified_peptide_sequence + self.sequence_length = sequence_length + self.calculated_mass = calculated_mass + self.formula = formula + self.count_glycosylation_sites = count_glycosylation_sites + self.count_missed_cleavages = count_missed_cleavages + self.count_variable_modifications = count_variable_modifications + self.peptide_score = peptide_score + self.peptide_score_type = peptide_score_type + self.n_glycosylation_sites = n_glycosylation_sites + self.o_glycosylation_sites = o_glycosylation_sites + self.gagylation_sites = gagylation_sites + + def as_db_instance(self): + return Peptide( + base_peptide_sequence=self.base_peptide_sequence, modified_peptide_sequence=self.modified_peptide_sequence, + sequence_length=self.sequence_length, + calculated_mass=self.calculated_mass, formula=self.formula, + count_glycosylation_sites=self.count_glycosylation_sites, + count_missed_cleavages=self.count_missed_cleavages, + count_variable_modifications=self.count_variable_modifications, peptide_score=self.peptide_score, + peptide_score_type=self.peptide_score_type, n_glycosylation_sites=self.n_glycosylation_sites, + o_glycosylation_sites=self.o_glycosylation_sites, + gagylation_sites=self.gagylation_sites) + + @classmethod + def from_db_instance(cls, inst): + return cls( + base_peptide_sequence=inst.base_peptide_sequence, modified_peptide_sequence=inst.modified_peptide_sequence, + sequence_length=inst.sequence_length, + calculated_mass=inst.calculated_mass, formula=inst.formula, + count_glycosylation_sites=inst.count_glycosylation_sites, + count_missed_cleavages=inst.count_missed_cleavages, + count_variable_modifications=inst.count_variable_modifications, peptide_score=inst.peptide_score, + peptide_score_type=inst.peptide_score_type, n_glycosylation_sites=inst.n_glycosylation_sites, + o_glycosylation_sites=inst.o_glycosylation_sites, + gagylation_sites=inst.gagylation_sites) + + +class PeptideIndex(object): + def __init__(self, store=None): + if store is None: + store = defaultdict(list) + self.store = store + + def all_but(self, key): + for bin_key, values in self.store.items(): + if key == bin_key: + continue + for v in values: + yield v + + def populate(self, iterable): + for peptide in iterable: + self.store[peptide.protein_id].append(PeptideBlueprint.from_db_instance(peptide)) + + +class PeptideSharer(DatabaseBoundOperation): + def __init__(self, connection, hypothesis_id): + DatabaseBoundOperation.__init__(self, connection) + self.hypothesis_id = hypothesis_id + self.index = PeptideIndex() + self.index.populate(self._get_all_peptides()) + + def find_contained_peptides(self, target_protein): + session = self.session + + protein_id = target_protein.id + + i = 0 + j = 0 + target_protein_sequence = target_protein.protein_sequence + keepers = [] + for peptide in self.stream_distinct_peptides(target_protein): + + match = self.decider_fn(peptide.base_peptide_sequence, target_protein_sequence) + + if match is not False: + start, end, distance = match + peptide = peptide.as_db_instance() + peptide.hypothesis_id = self.hypothesis_id + peptide.protein_id = protein_id + peptide.start_position = start + peptide.end_position = end + keepers.append(peptide) + j += 1 + i += 1 + if i % 100000 == 0: + logger.info(""%d peptides handled for %r"", i, target_protein) + if len(keepers) > 1000: + session.bulk_save_objects(keepers) + session.commit() + keepers = [] + logger.info(""%d peptides shared for %r"", j, target_protein) + + session.bulk_save_objects(keepers) + session.commit() + # session.expunge_all() + + def decider_fn(self, query_seq, target_seq, **kwargs): + match = re.search(query_seq, target_seq) + if match: + return match.start(), match.end(), 0 + return False + + def _get_all_peptides(self): + return self.session.query(Peptide).filter( + Peptide.hypothesis_id == self.hypothesis_id).all() + + def stream_distinct_peptides(self, protein): + q = self.index.all_but(protein.id) + + for i in q: + yield i + + +class PeptideSharingProcess(Process): + def __init__(self, connection, hypothesis_id, input_queue, done_event=None): + Process.__init__(self) + self.connection = connection + self.input_queue = input_queue + self.hypothesis_id = hypothesis_id + self.done_event = done_event + + def task(self): + database = DatabaseBoundOperation(self.connection) + session = database.session + has_work = True + + sharer = PeptideSharer(self.connection, self.hypothesis_id) + + while has_work: + try: + work_items = self.input_queue.get(timeout=5) + if work_items is None: + has_work = False + continue + except Exception: + if self.done_event.is_set(): + has_work = False + continue + proteins = slurp(session, Protein, work_items, flatten=False) + for protein in proteins: + sharer.find_contained_peptides(protein) + + def run(self): + self.task() + + +class MultipleProcessPeptideSharer(object): + def __init__(self, connection, hypothesis_id, protein_ids, n_processes=4): + self.connection = connection + self.hypothesis_id = hypothesis_id + self.protein_ids = protein_ids + self.n_processes = n_processes + + def run(self): + input_queue = Queue(100) + done_event = Event() + processes = [ + PeptideSharingProcess( + self.connection, self.hypothesis_id, input_queue, + done_event=done_event) for i in range(self.n_processes) + ] + protein_ids = self.protein_ids + i = 0 + chunk_size = 20 + for process in processes: + input_queue.put(protein_ids[i:(i + chunk_size)]) + i += chunk_size + process.start() + + while i < len(protein_ids): + input_queue.put(protein_ids[i:(i + chunk_size)]) + i += chunk_size + + done_event.set() + for process in processes: + process.join() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/proteomics/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/proteomics/remove_duplicate_peptides.py",".py","2270","59","from glycresoft.serialize.utils import temp_table +from glycresoft.serialize import ( + Peptide, Protein, DatabaseBoundOperation, + TemplateNumberStore) + +from glycresoft.task import TaskBase + + +class DeduplicatePeptides(DatabaseBoundOperation, TaskBase): + def __init__(self, connection, hypothesis_id): + DatabaseBoundOperation.__init__(self, connection) + self.hypothesis_id = hypothesis_id + + def run(self): + self.remove_duplicates() + + def find_best_peptides(self): + q = self.session.query( + Peptide.id, Peptide.peptide_score, + Peptide.modified_peptide_sequence, Peptide.protein_id, Peptide.start_position).join( + Protein).filter(Protein.hypothesis_id == self.hypothesis_id).yield_per(10000) + keepers = dict() + for id, score, modified_peptide_sequence, protein_id, start_position in q: + key = (modified_peptide_sequence, protein_id, start_position) + result = keepers.get(key) + if result is None: + keepers[key] = (id, score) + elif result[1] < score: + keepers[key] = (id, score) + return keepers + + def store_best_peptides(self, keepers): + table = temp_table(TemplateNumberStore) + conn = self.session.connection() + table.create(conn) + payload = [{""value"": x[0]} for x in keepers.values()] + conn.execute(table.insert(), payload) + self.session.commit() + return table + + def remove_duplicates(self): + self.log(""... Deduplicating Peptides"") + keepers = self.find_best_peptides() + self.log(""... Marking Candidates"") + table = self.store_best_peptides(keepers) + ids = self.session.query(table.c.value) + self.log(""... Building Mask"") + q = self.session.query(Peptide.id).filter( + Peptide.protein_id == Protein.id, + Protein.hypothesis_id == self.hypothesis_id, + ~Peptide.id.in_(ids.correlate(None))) + self.log(""... Removing Duplicates"") + self.session.execute(Peptide.__table__.delete( + Peptide.__table__.c.id.in_(q.selectable))) + conn = self.session.connection() + table.drop(conn) + self.log(""... Complete"") + self.session.commit() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/proteomics/peptide_permutation.py",".py","31301","707","import bisect +import itertools + +from multiprocessing import Process, Queue, Event, cpu_count + +from typing import List, Optional, Set, Tuple + +from lxml.etree import XMLSyntaxError + +from ms_deisotope.peak_dependency_network.intervals import Interval, IntervalTreeNode + +from glycopeptidepy import enzyme +from .utils import slurp +from .uniprot import (uniprot, get_uniprot_accession, UniprotProteinDownloader, UniprotProteinXML, Empty) + +from glypy.composition import formula +from glycopeptidepy.io import annotation +from glycopeptidepy.structure import sequence, modification, residue +from glycopeptidepy.structure.modification import ModificationRule +from glycopeptidepy.algorithm import PeptidoformGenerator +from glycopeptidepy import PeptideSequence + +from glycresoft.task import TaskBase +from glycresoft.serialize import DatabaseBoundOperation +from glycresoft.serialize.hypothesis.peptide import Peptide, Protein + +from six import string_types as basestring + + +RestrictedModificationTable = modification.RestrictedModificationTable +combinations = itertools.combinations +product = itertools.product +chain_iterable = itertools.chain.from_iterable + +SequenceLocation = modification.SequenceLocation + + +def span_test(site_list, start, end): + i = bisect.bisect_left(site_list, start) + after_start = site_list[i:] + out = [] + for j in after_start: + if j < end: + out.append(j) + else: + break + return out + + +def n_glycan_sequon_sites(peptide: Peptide, protein: Protein, use_local_sequence: bool=False, + include_cysteine: bool = False, allow_modified=frozenset()): + sites = set() + sites |= set(site - peptide.start_position for site in span_test( + protein.n_glycan_sequon_sites, peptide.start_position, peptide.end_position)) + if use_local_sequence: + sites |= set(sequence.find_n_glycosylation_sequons( + peptide.modified_peptide_sequence, allow_modified=allow_modified, include_cysteine=include_cysteine)) + return sorted(sites) + + +def o_glycan_sequon_sites(peptide: Peptide, protein: Protein=None, use_local_sequence: bool=False): + sites = set() + sites |= set(site - peptide.start_position for site in span_test( + protein.o_glycan_sequon_sites, peptide.start_position, peptide.end_position)) + if use_local_sequence: + sites |= set(sequence.find_o_glycosylation_sequons( + peptide.modified_peptide_sequence)) + return sorted(sites) + + +def gag_sequon_sites(peptide: Peptide, protein: Protein = None, use_local_sequence: bool = False): + sites = set() + sites |= set(site - peptide.start_position for site in span_test( + protein.glycosaminoglycan_sequon_sites, peptide.start_position, peptide.end_position)) + if use_local_sequence: + sites = sequence.find_glycosaminoglycan_sequons( + peptide.modified_peptide_sequence) + return sorted(sites) + + +def get_base_peptide(peptide_obj): + if isinstance(peptide_obj, Peptide): + return PeptideSequence(peptide_obj.base_peptide_sequence) + else: + return PeptideSequence(str(peptide_obj)) + + +class PeptidePermuter(PeptidoformGenerator): + constant_modifications: List[ModificationRule] + variable_modifications: List[ModificationRule] + max_variable_modifications: int + + n_term_modifications: List[ModificationRule] + c_term_modifications: List[ModificationRule] + + def prepare_peptide(self, sequence): + return get_base_peptide(sequence) + + @classmethod + def peptide_permutations(cls, + sequence, + constant_modifications: List[ModificationRule], + variable_modifications: List[ModificationRule], + max_variable_modifications: int=4): + inst = cls(constant_modifications, variable_modifications, + max_variable_modifications) + return inst(sequence) + + +peptide_permutations = PeptidePermuter.peptide_permutations + + +def cleave_sequence(sequence, + protease: enzyme.Protease, + missed_cleavages: int=2, + min_length: int=6, + max_length: int=60, + semispecific: bool=False): + peptide: str + start: int + end: int + missed: int + for peptide, start, end, missed in protease.cleave(sequence, missed_cleavages=missed_cleavages, + min_length=min_length, max_length=max_length, + semispecific=semispecific): + if ""X"" in peptide: + continue + yield peptide, start, end, missed + + +class ProteinDigestor(TaskBase): + + protease: enzyme.Protease + constant_modifications: List[ModificationRule] + variable_modifications: List[ModificationRule] + peptide_permuter: PeptidePermuter + min_length: int + max_length: int + max_missed_cleavages: int + variable_signal_peptide: int + max_variable_modifications: int + semispecific: bool + include_cysteine_n_glycosylation: bool + require_glycosylation_sites: bool + + def __init__(self, protease, constant_modifications=None, variable_modifications=None, + max_missed_cleavages: int=2, min_length: int=6, max_length: int=60, semispecific: bool=False, + max_variable_modifications=None, require_glycosylation_sites: bool=False, + include_cysteine_n_glycosylation: bool=False): + if constant_modifications is None: + constant_modifications = [] + if variable_modifications is None: + variable_modifications = [] + self.protease = self._prepare_protease(protease) + self.constant_modifications = constant_modifications + self.variable_modifications = variable_modifications + self.peptide_permuter = PeptidePermuter( + self.constant_modifications, + self.variable_modifications, + max_variable_modifications=max_variable_modifications) + self.max_missed_cleavages = max_missed_cleavages + self.min_length = min_length + self.max_length = max_length + self.semispecific = semispecific + self.include_cysteine_n_glycosylation = include_cysteine_n_glycosylation + self.max_variable_modifications = max_variable_modifications + self.require_glycosylation_sites = require_glycosylation_sites + + def _prepare_protease(self, protease): + if isinstance(protease, enzyme.Protease): + pass + elif isinstance(protease, basestring): + protease = enzyme.Protease(protease) + elif isinstance(protease, (list, tuple)): + protease = enzyme.Protease.combine(*protease) + return protease + + def cleave(self, sequence: Protein): + return cleave_sequence(sequence, self.protease, self.max_missed_cleavages, + min_length=self.min_length, max_length=self.max_length, + semispecific=self.semispecific) + + def digest(self, protein: Protein): + sequence = protein.protein_sequence + try: + size = len(protein) + except residue.UnknownAminoAcidException: + size = len(sequence) + for peptide, start, end, n_missed_cleavages in self.cleave(sequence): + if end - start > self.max_length: + continue + protein_n_term = start == 0 + protein_c_term = end == size + for inst in self.modify_string( + peptide, protein_n_term=protein_n_term, protein_c_term=protein_c_term): + inst.count_missed_cleavages = n_missed_cleavages + inst.start_position = start + inst.end_position = end + yield inst + + def modify_string(self, peptide: Peptide, protein_n_term: bool=False, protein_c_term: bool=False): + base_peptide = str(peptide) + for modified_peptide, n_variable_modifications in self.peptide_permuter( + peptide, protein_n_term=protein_n_term, protein_c_term=protein_c_term): + formula_string = formula(modified_peptide.total_composition()) + # formula_string = """" + inst = Peptide( + base_peptide_sequence=base_peptide, + modified_peptide_sequence=str(modified_peptide), + count_missed_cleavages=-1, + count_variable_modifications=n_variable_modifications, + sequence_length=len(modified_peptide), + start_position=-1, + end_position=-1, + calculated_mass=modified_peptide.mass, + formula=formula_string) + yield inst + + def process_protein(self, protein_obj: Protein): + protein_id = protein_obj.id + hypothesis_id = protein_obj.hypothesis_id + + for peptide in self.digest(protein_obj): + peptide.protein_id = protein_id + peptide.hypothesis_id = hypothesis_id + peptide.peptide_score = 0 + peptide.peptide_score_type = 'null_score' + n_glycosites = n_glycan_sequon_sites( + peptide, protein_obj, include_cysteine=self.include_cysteine_n_glycosylation) + o_glycosites = o_glycan_sequon_sites(peptide, protein_obj) + gag_glycosites = gag_sequon_sites(peptide, protein_obj) + if self.require_glycosylation_sites: + if (len(n_glycosites) + len(o_glycosites) + len(gag_glycosites)) == 0: + continue + peptide.count_glycosylation_sites = len(n_glycosites) + peptide.n_glycosylation_sites = sorted(n_glycosites) + peptide.o_glycosylation_sites = sorted(o_glycosites) + peptide.gagylation_sites = sorted(gag_glycosites) + yield peptide + + def __call__(self, protein_obj): + return self.process_protein(protein_obj) + + @classmethod + def digest_protein(cls, sequence, protease: enzyme.Protease, constant_modifications: List[ModificationRule] = None, + variable_modifications: List[ModificationRule] = None, max_missed_cleavages: int=2, + min_length: int=6, max_length: int=60, semispecific: bool=False): + inst = cls( + protease, constant_modifications, variable_modifications, + max_missed_cleavages, min_length, max_length, semispecific) + if isinstance(sequence, basestring): + sequence = Protein(protein_sequence=sequence) + return inst(sequence) + + +digest = ProteinDigestor.digest_protein + + +class ProteinDigestingProcess(Process): + process_name = ""protein-digest-worker"" + + def __init__(self, connection, hypothesis_id, input_queue, digestor, done_event=None, + chunk_size=5000, message_handler=None): + Process.__init__(self) + self.connection = connection + self.input_queue = input_queue + self.hypothesis_id = hypothesis_id + self.done_event = done_event + self.digestor = digestor + self.chunk_size = chunk_size + self.message_handler = message_handler + + def task(self): + database = DatabaseBoundOperation(self.connection) + session = database.session + has_work = True + + digestor = self.digestor + acc = [] + if self.message_handler is None: + self.message_handler = lambda x: None + while has_work: + try: + work_items = self.input_queue.get(timeout=5) + if work_items is None: + has_work = False + continue + except Exception: + if self.done_event.is_set(): + has_work = False + continue + proteins = slurp(session, Protein, work_items, flatten=False) + acc = [] + + threshold_size = 3000 + + for protein in proteins: + size = len(protein.protein_sequence) + if size > threshold_size: + self.message_handler(""...... Started digesting %s (%d)"" % (protein.name, size)) + i = 0 + for peptide in digestor.process_protein(protein): + acc.append(peptide) + i += 1 + if len(acc) > self.chunk_size: + session.bulk_save_objects(acc) + session.commit() + acc = [] + if i % 10000 == 0: + self.message_handler( + ""...... Digested %d peptides from %r (%d)"" % ( + i, protein.name, size)) + if size > threshold_size: + self.message_handler(""...... Finished digesting %s (%d)"" % (protein.name, size)) + session.bulk_save_objects(acc) + session.commit() + acc = [] + if acc: + session.bulk_save_objects(acc) + session.commit() + acc = [] + + def run(self): + new_name = getattr(self, 'process_name', None) + if new_name is not None: + TaskBase().try_set_process_name(new_name) + self.task() + + +class MultipleProcessProteinDigestor(TaskBase): + def __init__(self, connection, hypothesis_id, protein_ids, digestor, n_processes=4): + self.connection = connection + self.hypothesis_id = hypothesis_id + self.protein_ids = protein_ids + self.digestor = digestor + self.n_processes = n_processes + + def run(self): + logger = self.ipc_logger() + input_queue = Queue(2 * self.n_processes) + done_event = Event() + processes = [ + ProteinDigestingProcess( + self.connection, self.hypothesis_id, input_queue, + self.digestor, done_event=done_event, + message_handler=logger.sender()) for i in range( + self.n_processes) + ] + protein_ids = self.protein_ids + i = 0 + n = len(protein_ids) + if n <= self.n_processes: + chunk_size = 1 + elif n < 100: + chunk_size = 2 + else: + chunk_size = int(n / 100.0) + interval = 30 + for process in processes: + input_queue.put(protein_ids[i:(i + chunk_size)]) + i += chunk_size + process.start() + + last = i + while i < n: + input_queue.put(protein_ids[i:(i + chunk_size)]) + i += chunk_size + if i - last > interval: + self.log(""... Dealt Proteins %d-%d %0.2f%%"" % ( + i - chunk_size, min(i, n), (min(i, n) / float(n)) * 100)) + last = i + + error_occurred = False + for process in processes: + if process.exitcode is not None and process.exitcode != 0: + error_occurred = True + + if error_occurred: + self.error(""An error occurred while digesting proteins."") + done_event.set() + for process in processes: + if process.is_alive(): + process.terminate() + logger.stop() + raise ValueError( + ""One or more worker processes exited with an error."") + + done_event.set() + for process in processes: + process.join() + if process.exitcode != 0: + raise ValueError(""One or more worker processes exited with an error."") + logger.stop() + + +class PeptideInterval(Interval): + def __init__(self, peptide): + Interval.__init__(self, peptide.start_position, peptide.end_position, [peptide]) + self.data['peptide'] = str(peptide) + + +class ProteinSplitter(TaskBase): + + constant_modifications: List[ModificationRule] + variable_modifications: List[ModificationRule] + min_length: int + variable_signal_peptide: int + include_cysteine_n_glycosylation: bool + + def __init__(self, constant_modifications=None, variable_modifications=None, + min_length=6, variable_signal_peptide=10, include_cysteine_n_glycosylation: bool=False): + if constant_modifications is None: + constant_modifications = [] + if variable_modifications is None: + variable_modifications = [] + + self.constant_modifications = constant_modifications + self.variable_modifications = variable_modifications + self.min_length = min_length + self.variable_signal_peptide = variable_signal_peptide + self.peptide_permuter = PeptidePermuter( + self.constant_modifications, self.variable_modifications) + self.include_cysteine_n_glycosylation = include_cysteine_n_glycosylation + + def __reduce__(self): + return self.__class__, (self.constant_modifications, + self.variable_modifications, + self.min_length, + self.variable_signal_peptide, + self.include_cysteine_n_glycosylation) + + def handle_protein(self, protein_obj: Protein, sites: Optional[Set[int]]=None): + annot_sites = self.get_split_sites_from_annotations(protein_obj) + if sites is None: + try: + accession = get_uniprot_accession(protein_obj.name) + if accession: + try: + extra_sites, more_annots = self.get_split_sites_from_uniprot(accession) + # Trigger SQLAlchemy mutable update via assignment instead of in-place updates + protein_obj.annotations = list(protein_obj.annotations) + list(more_annots) + return self.split_protein(protein_obj, sorted(annot_sites | extra_sites)) + except IOError: + return self.split_protein(protein_obj, annot_sites) + else: + return self.split_protein(protein_obj, annot_sites) + except XMLSyntaxError: + return self.split_protein(protein_obj, annot_sites) + except Exception as e: + self.error( + (""An unhandled error occurred while retrieving"" + "" non-proteolytic cleavage sites""), e) + return self.split_protein(protein_obj, annot_sites) + else: + if not isinstance(sites, set): + sites = set(sites) + try: + return self.split_protein(protein_obj, sorted(sites | annot_sites)) + except IOError: + return [] + + def get_split_sites_from_annotations(self, protein: Protein) -> Set[int]: + annots = protein.annotations + split_sites = self._split_sites_from_annotations(annots) + return split_sites + + def _split_sites_from_annotations(self, annots: annotation.AnnotationCollection) -> Set[int]: + cleavable_annots = annots.cleavable() + split_sites = set() + for annot in cleavable_annots: + split_sites.add(annot.start) + split_sites.add(annot.end) + if self.variable_signal_peptide and annot.feature_type == annotation.SignalPeptide.feature_type: + for i in range(1, self.variable_signal_peptide + 1): + split_sites.add(annot.end + i) + if 0 in split_sites: + split_sites.remove(0) + return split_sites + + def get_split_sites_from_features(self, record) -> Set[int]: + if isinstance(record, uniprot.UniProtProtein): + annots = annotation.from_uniprot(record) + elif isinstance(record, annotation.AnnotationCollection): + annots = record + return self._split_sites_from_annotations(annots) + + def get_split_sites_from_uniprot(self, accession: str) -> Tuple[Set[int], annotation.AnnotationCollection]: + try: + record = uniprot.get(accession) + except Exception as err: + self.error(f""Failed to obtain Uniprot Record for {accession!r}: {err.__class__}:{str(err)}"") + return set() + if record is None: + self.error(f""Failed to obtain Uniprot Record for {accession!r}"") + return set() + sites = self.get_split_sites_from_features(record) + return sites, annotation.from_uniprot(record) + + def _make_split_expression(self, sites: List[int]) -> List: + return [ + (Peptide.start_position < s) & (Peptide.end_position > s) for s in sites] + + def _permuted_peptides(self, sequence): + return self.peptide_permuter(sequence) + + def split_protein(self, protein_obj: Protein, sites: Optional[List[int]]=None): + if isinstance(sites, set): + sites = sorted(sites) + if sites is None: + sites = [] + if not sites: + return + seen = set() + sites_seen = set() + peptides = protein_obj.peptides.all() + peptide_intervals = IntervalTreeNode.build(map(PeptideInterval, peptides)) + for site in sites: + overlap_region = peptide_intervals.contains_point(site - 1) + spanned_intervals: IntervalTreeNode = IntervalTreeNode.build(overlap_region) + # No spanned peptides. May be caused by regions of protein which digest to peptides + # of unacceptable size. + if spanned_intervals is None: + continue + lo = spanned_intervals.start + hi = spanned_intervals.end + # Get the set of all sites spanned by any peptide which spans the current query site + spanned_sites = [s for s in sites if lo <= s <= hi] + for i in range(1, len(spanned_sites) + 1): + for split_sites in itertools.combinations(spanned_sites, i): + site_key = frozenset(split_sites) + if site_key in sites_seen: + continue + sites_seen.add(site_key) + spanning_peptides_query = spanned_intervals.contains_point(split_sites[0]) + for site_j in split_sites[1:]: + spanning_peptides_query = [ + sp for sp in spanning_peptides_query if site_j in sp + ] + spanning_peptides = [] + for sp in spanning_peptides_query: + spanning_peptides.extend(sp) + for peptide in spanning_peptides: + peptide_start_position = peptide.start_position + adjusted_sites = [0] + [s - peptide_start_position for s in split_sites] + [ + peptide.sequence_length] + for j in range(len(adjusted_sites) - 1): + # TODO: Cleavage sites may be off by one in the start. Revisit the index math here. + begin = adjusted_sites[j] + end = adjusted_sites[j + 1] + if end - begin < self.min_length: + continue + start_position = begin + peptide_start_position + end_position = end + peptide_start_position + if (start_position, end_position) in seen: + continue + else: + seen.add((start_position, end_position)) + for modified_peptide, n_variable_modifications in self._permuted_peptides( + peptide.base_peptide_sequence[begin:end]): + + inst = Peptide( + base_peptide_sequence=str(peptide.base_peptide_sequence[begin:end]), + modified_peptide_sequence=str(modified_peptide), + count_missed_cleavages=peptide.count_missed_cleavages, + count_variable_modifications=n_variable_modifications, + sequence_length=len(modified_peptide), + start_position=start_position, + end_position=end_position, + calculated_mass=modified_peptide.mass, + formula=formula(modified_peptide.total_composition()), + protein_id=protein_obj.id) + inst.hypothesis_id = protein_obj.hypothesis_id + inst.peptide_score = 0 + inst.peptide_score_type = 'null_score' + n_glycosites = n_glycan_sequon_sites( + inst, protein_obj, include_cysteine=self.include_cysteine_n_glycosylation) + o_glycosites = o_glycan_sequon_sites(inst, protein_obj) + gag_glycosites = gag_sequon_sites(inst, protein_obj) + inst.count_glycosylation_sites = len(n_glycosites) + inst.n_glycosylation_sites = sorted(n_glycosites) + inst.o_glycosylation_sites = sorted(o_glycosites) + inst.gagylation_sites = sorted(gag_glycosites) + yield inst + + +class UniprotProteinAnnotator(TaskBase): + hypothesis_builder: DatabaseBoundOperation + protein_ids: List[int] + constant_modifications: List[ModificationRule] + variable_modifications: List[ModificationRule] + variable_signal_peptide: int + include_cysteine_n_glycosylation: bool + + def __init__(self, hypothesis_builder, protein_ids, constant_modifications, + variable_modifications, variable_signal_peptide=10, + include_cysteine_n_glycosylation: bool=False, + uniprot_source_file: Optional[str]=None): + self.hypothesis_builder = hypothesis_builder + self.protein_ids = protein_ids + self.constant_modifications = constant_modifications + self.variable_modifications = variable_modifications + self.variable_signal_peptide = variable_signal_peptide + self.session = hypothesis_builder.session + self.include_cysteine_n_glycosylation = include_cysteine_n_glycosylation + self.uniprot_source_file = uniprot_source_file + + def query(self, *args, **kwargs): + return self.session.query(*args, **kwargs) + + def commit(self): + return self.session.commit() + + def run(self): + self.log(""Begin Applying Protein Annotations"") + splitter = ProteinSplitter(self.constant_modifications, self.variable_modifications, + variable_signal_peptide=self.variable_signal_peptide, + include_cysteine_n_glycosylation=self.include_cysteine_n_glycosylation) + i = 0 + j = 0 + protein_ids = self.protein_ids + protein_names = [self.query(Protein.name).filter( + Protein.id == protein_id).first()[0] for protein_id in protein_ids] + name_to_id = {n: i for n, i in zip(protein_names, protein_ids)} + if self.uniprot_source_file is not None: + self.log(f""... Loading from local XML file {self.uniprot_source_file!r}"") + uniprot_queue = UniprotProteinXML(self.uniprot_source_file, protein_names) + else: + self.log(""... Loading from UniProt web service"") + uniprot_queue = UniprotProteinDownloader( + protein_names, + n_threads=getattr(self.hypothesis_builder, ""n_processes"", cpu_count() // 2) * 4) + uniprot_queue.start() + n = len(protein_ids) + interval = int(min((n * 0.1) + 1, 1000)) + acc = [] + seen = set() + # TODO: This seems to periodically exit before finishing processing of all proteins? + while True: + try: + protein_name, record = uniprot_queue.get() + protein_id = name_to_id[protein_name] + seen.add(protein_id) + protein = self.query(Protein).get(protein_id) + i += 1 + # Record not found in UniProt + if isinstance(record, (Exception, str)) and not protein.annotations: + message = str(record) + # Many, many records that used to exist no longer do. We don't care if they are absent. + # if ""Document is empty"" not in message: + self.log(f""... Skipping {protein_name}: {message}"") + continue + if record is None and not protein.annotations: + self.log(f""... Skipping {protein_name}: no record found"") + continue + if i % interval == 0: + self.log( + f""... {i * 100. / n:0.3f}% Complete ({i}/{n}). {j} Peptides Produced."") + + if not isinstance(record, (uniprot.UniProtProtein, annotation.AnnotationCollection)): + sites = None + else: + if isinstance(record, uniprot.UniProtProtein): + record = annotation.from_uniprot(record) + # Trigger SQLAlchemy mutable update via assignment instead of in-place updates + protein.annotations = list(protein.annotations) + list(record) + self.session.add(protein) + sites = splitter.get_split_sites_from_features(record) + for peptide in splitter.handle_protein(protein, sites): + acc.append(peptide) + j += 1 + if len(acc) > 100000: + self.log( + f""... {i * 100. / n:0.3f}% Complete ({i}/{n}). {j} Peptides Produced."") + self.session.bulk_save_objects(acc) + self.session.commit() + acc = [] + except Empty: + uniprot_queue.join() + if uniprot_queue.done_event.is_set(): + break + + leftover_ids = set(protein_ids) - seen + if leftover_ids: + self.log(f""{len(leftover_ids)} IDs not covered by queue, sequentially querying UniProt"") + + for protein_id in leftover_ids: + i += 1 + protein = self.query(Protein).get(protein_id) + if i % interval == 0: + self.log( + f""... {i * 100. / n:0.3f}% Complete ({i}/{n}). {j} Peptides Produced."") + for peptide in splitter.handle_protein(protein): + acc.append(peptide) + j += 1 + if len(acc) > 100000: + self.log( + f""... {i * 100. / n:0.3f}% Complete ({i}/{n}). {j} Peptides Produced."") + self.session.bulk_save_objects(acc) + self.session.commit() + acc = [] + self.session.add(protein) + self.log( + f""... {i * 100. / n:0.3f}% Complete ({i}/{n}). {j} Peptides Produced."") + self.session.bulk_save_objects(acc) + self.session.commit() + acc = [] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/proteomics/sequence_tree.py",".py","5383","198","from contextlib import contextmanager +from collections import defaultdict + + +def identity(x): + return x + + +class TreeReprMixin(object): + def __repr__(self): + base = dict(self) + return repr(base) + + +class PrefixTree(TreeReprMixin, defaultdict): + ''' + A hash-based Prefix Tree for testing for + sequence inclusion. This implementation works for any + slice-able sequence of hashable objects, not just strings. + ''' + def __init__(self): + defaultdict.__init__(self, PrefixTree) + self.labels = set() + + def add(self, sequence, label=None): + """"""Adds a single Sequence-like object to the tree + structure, placing the ith member of `sequence` on + the ith level of `self`. At each level, if `label` + is not None, it is added to the level's `labels` set. + + Parameters + ---------- + sequence : Sequence + Sequence-like object to add to the tree + label : object, optional + An arbitrary object which denotes or is associated with + `sequence` + + Returns + ------- + self + """""" + layer = self + if label is None: + label = sequence + if label: + layer.labels.add(label) + for i in range(len(sequence)): + layer = layer[sequence[i]] + if label: + layer.labels.add(label) + + return self + + def add_ngram(self, sequence, label=None): + """"""Adds successive prefixes of `sequence` + to the tree by calling :meth:`add`. This process + is identical to calling :meth:`add` once for a prefix + tree. + + Parameters + ---------- + sequence : Sequence + Sequence-like object to add to the tree + label : object, optional + An arbitrary object which denotes or is associated with + `sequence` + """""" + if label is None: + label = sequence + for i in range(1, len(sequence) + 1): + self.add(sequence[:i], label) + + def __contains__(self, sequence): + layer = self + j = 0 + for i in sequence: + if not dict.__contains__(layer, i): + break + layer = layer[i] + j += 1 + return len(sequence) == j + + def depth_in(self, sequence): + layer = self + count = 0 + for i in sequence: + if not dict.__contains__(layer, i): + break + else: + layer = layer[i] + count += 1 + return count + + def subsequences_of(self, sequence): + layer = self + for i in sequence: + layer = layer[i] + return layer.labels + + def __iter__(self): + return iter(self.labels) + + +class SuffixTree(PrefixTree): + ''' + A hash-based Suffix Tree for testing for + sequence inclusion. This implementation works for any + slice-able sequence of hashable objects, not just strings. + ''' + def __init__(self): + defaultdict.__init__(self, SuffixTree) + self.labels = set() + + def add_ngram(self, sequence, label=None): + if label is None: + label = sequence + for i in range(len(sequence)): + self.add(sequence[i:], label=label) + + +class KeyTransformingPrefixTree(PrefixTree): + def __init__(self, transformer): + defaultdict.__init__(self, lambda: KeyTransformingPrefixTree(transformer)) + self.transformer = transformer + self.labels = set() + + def get(self, key): + return self[self.transformer(key)] + + def add(self, sequence, label=None): + layer = self + t = self.transformer + if label is None: + label = sequence + if label: + layer.labels.add(label) + for i in range(len(sequence)): + layer = layer[t(sequence[i])] + if label: + layer.labels.add(label) + return self + + def __contains__(self, sequence): + layer = self + j = 0 + t = self.transformer + for i in sequence: + j += 1 + if not dict.__contains__(layer, t(i)): + break + layer = layer[i] + return j == len(sequence) + + def depth_in(self, sequence): + layer = self + count = 0 + t = self.transformer + for i in sequence: + if not dict.__contains__(layer, t(i)): + break + else: + layer = layer[i] + count += 1 + return count + + def subsequences_of(self, sequence): + layer = self + t = self.transformer + for i in sequence: + layer = layer[t(i)] + return layer.labels + + __repr__ = dict.__repr__ + + def __iter__(self): + return iter(self.labels) + + @contextmanager + def with_identity(self): + t = self.transformer + self.transformer = identity + yield + self.transformer = t + + +class KeyTransformingSuffixTree(KeyTransformingPrefixTree): + def __init__(self, transformer): + defaultdict.__init__(self, lambda: KeyTransformingSuffixTree(transformer)) + self.transformer = transformer + self.labels = set() + + def add_ngram(self, sequence, label=None): + if label is None: + label = sequence + for i in range(len(sequence)): + self.add(sequence[i:], label=label) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/proteomics/utils.py",".py","336","13","def slurp(session, model, ids, flatten=True): + if flatten: + ids = [j for i in ids for j in i] + total = len(ids) + last = 0 + step = 100 + results = [] + while last < total: + results.extend(session.query(model).filter( + model.id.in_(ids[last:last + step]))) + last += step + return results +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/proteomics/uniprot.py",".py","12541","381","import re +import threading +import multiprocessing + +from queue import Empty +from typing import IO, List, Deque, Union + +import urllib3 +from ms_deisotope.data_source._compression import get_opener + +from glycopeptidepy.io import uniprot, fasta, annotation +from glycopeptidepy.io.utils import UniprotToPeffConverter + +from glycresoft.task import TaskBase +from glycresoft.serialize import Protein + + +uniprot_accession_pattern = re.compile( + r""""""(([OPQ]\d[A-Z0-9][A-Z0-9][A-Z0-9]\d)| + ([A-Z0-9]\d[A-Z][A-Z0-9][A-Z0-9]\d)| + ([A-NR-Z]\d[A-Z][A-Z0-9][A-Z0-9]\d[A-Z][A-Z0-9][A-Z0-9]\d))"""""", + re.X) + + +def is_uniprot_accession(accession: str) -> bool: + return bool(uniprot_accession_pattern.match(accession)) + + +def get_uniprot_accession(name): + try: + peff_header = fasta.peff_parser(name) + # Don't bother UniProt over PEFF specifications, they won't parse correctly + # with the partial UniProt parser + if peff_header: + return None + except fasta.UnparsableDeflineError: + pass + try: + return fasta.partial_uniprot_parser(name).accession + except (AttributeError, fasta.UnparsableDeflineError): + # Some programs will just put the accession number into the mzIdentML + # identifier, so we'll check if the first word looks like an accession + # number and try it if so. + accession = str(name).split("" "")[0] + if is_uniprot_accession(accession): + return accession + return None + + +def retry(task, n=5): + result = None + errs = [] + for i in range(n): + try: + result = task() + return result, errs + except Exception as err: + errs.append(err) + raise errs[-1] + + +HAS_BATCH_HANDLER = hasattr(uniprot, 'get_features_for_many') + + +class UniprotSource(TaskBase): + def task_handler(self, accession_number): + accession = get_uniprot_accession(accession_number) + if accession is None: + accession = accession_number + protein_data, errs = retry(lambda: uniprot.get(accession), 5) + self.output_queue.put((accession_number, protein_data)) + return protein_data + + def batch_handler(self, accession_list): + idents_map = {} + for acc in accession_list: + acc_ = get_uniprot_accession(acc) + if acc_ is None: + acc_ = acc + idents_map[acc_] = acc + idents = list(idents_map) + result, errs = retry(lambda: uniprot.get_features_for_many(idents), 5) + if errs: + self.log(f""... Handled batch of size {len(accession_list)} and encountered {len(errs)} errors"") + + for (acc, protein_data) in result: + name = idents_map[acc] + self.output_queue.put((name, protein_data)) + + def fetch(self, accession_number): + if isinstance(accession_number, list) and HAS_BATCH_HANDLER: + try: + self.batch_handler(accession_number) + except Exception as e: + self.error_handler(accession_number[0], e) + else: + try: + self.task_handler(accession_number) + except Exception as e: + self.error_handler(accession_number, e) + + def error_handler(self, accession_number, error): + self.output_queue.put((accession_number, Exception(str(error)))) + + +class UniprotRequestingProcess(multiprocessing.Process, UniprotSource): + process_name = ""glycresoft-annotation-worker"" + + def __init__(self, input_queue, output_queue, feeder_done_event, done_event): + multiprocessing.Process.__init__(self) + self.input_queue = input_queue + self.output_queue = output_queue + self.feeder_done_event = feeder_done_event + self.done_event = done_event + + def run(self): + new_name = getattr(self, 'process_name', None) + if new_name is not None: + TaskBase().try_set_process_name(new_name) + urllib3.disable_warnings() + while True: + try: + accession = self.input_queue.get(True, 3) + except Empty: + if self.feeder_done_event.is_set(): + break + self.input_queue.task_done() + self.fetch(accession) + + self.done_event.set() + + +def chunked(seq, size=128): + n = len(seq) + for i in range(0, n + size, size): + z = seq[i:i + size] + if z: + yield z + + +class UniprotProteinDownloader(UniprotSource): + accession_list: List[str] + input_queue: multiprocessing.JoinableQueue + output_queue: multiprocessing.Queue + no_more_work: multiprocessing.Event + done_event: multiprocessing.Event + workers: List[UniprotRequestingProcess] + + def __init__(self, accession_list, n_threads=10): + self.accession_list = accession_list + self.n_threads = n_threads + self.input_queue = multiprocessing.JoinableQueue(2000) + self.output_queue = multiprocessing.Queue() + self.no_more_work = multiprocessing.Event() + self.done_event = multiprocessing.Event() + self.workers = [] + + def task_handler(self, accession_number): + accession = get_uniprot_accession(accession_number) + if accession is None: + accession = accession_number + protein_data = uniprot.get(accession) + self.output_queue.put((accession_number, protein_data)) + return protein_data + + def fetch(self, accession_number): + try: + self.task_handler(accession_number) + except Exception as e: + self.error_handler(accession_number, e) + + def error_handler(self, accession_number, error): + self.output_queue.put((accession_number, error)) + + def feeder_task(self): + n = len(self.accession_list) + k = n // max(100, self.n_threads) + k = max(min(k, 100), 1) + self.log(f""... Submitting UniProt queries in batches of size {k}"") + + for i, item in enumerate(chunked(self.accession_list, k)): + if i % 1000 == 0 and i: + self.input_queue.join() + self.input_queue.put(item) + self.no_more_work.set() + + def run(self): + feeder = threading.Thread(target=self.feeder_task) + feeder.start() + self.workers = workers = [] + n = min(self.n_threads, len(self.accession_list)) + for i in range(n): + t = UniprotRequestingProcess( + self.input_queue, self.output_queue, self.no_more_work, + multiprocessing.Event()) + t.daemon = True + t.start() + workers.append(t) + + def join(self): + for worker in self.workers: + if not worker.done_event.is_set(): + break + else: + worker.join() + else: + self.done_event.set() + return True + return False + + def start(self): + self.run() + + def get(self, blocking=True, timeout=3): + return self.output_queue.get(blocking, timeout) + + +class UniprotProteinXML(UniprotSource): + path: Union[str, IO] + store: annotation.AnnotationDatabase + queue: Deque[str] + done_event: threading.Event + + def __init__(self, path: str, ids: List[str]): + self.path = path + self.store = {} + self.work = Deque(ids) + self.load() + self.done_event = threading.Event() + + def join(self): + return + + def load(self): + if self.path == '-': + self.store = annotation.AnnotationDatabase({}) + else: + stream = get_opener(self.path) + if uniprot.is_uniprot_xml(stream): + self.store = annotation.AnnotationDatabase.from_uniprot_xml(stream) + else: + self.store = annotation.AnnotationDatabase.load(stream) + + def fetch(self, accession_number: str): + accession = get_uniprot_accession(accession_number) + try: + features = self.store[accession] + return accession_number, features + except KeyError: + return accession_number, Exception(f""{accession_number!r} not found"") + + def get(self, *args, **kwargs): + if self.work: + acc = self.work.popleft() + if not self.work: + self.done_event.set() + return self.fetch(acc) + else: + raise Empty() + + +class UniprotProteinSource(TaskBase): + def __init__(self, accession_list, hypothesis_id, n_threads=4): + self._accession_list = accession_list + self.n_threads = n_threads + self.downloader = None + self.hypothesis_id = hypothesis_id + self.proteins = [] + + self._clean_accession_list() + + def _clean_accession(self, accession_string): + if accession_string.startswith("">""): + accession_string = accession_string[1:] + accession_string = accession_string.strip() + result = None + if ""|"" in accession_string: + try: + fields = fasta.default_parser(accession_string) + result = fields.accession + except fasta.UnparsableDeflineError: + result = accession_string + else: + result = accession_string + return result + + def _clean_accession_list(self): + cleaned = [] + for entry in self._accession_list: + cleaned.append(self._clean_accession(entry)) + self._accession_list = cleaned + + def _make_downloader(self): + self.downloader = UniprotProteinDownloader( + self._accession_list, self.n_threads) + return self.downloader + + def make_protein(self, accession, uniprot_protein): + sequence = uniprot_protein.sequence + name = ""sp|{accession}|{gene_name} {description}"".format( + accession=accession, gene_name=uniprot_protein.gene_name, + description=uniprot_protein.recommended_name) + protein = Protein( + name=name, protein_sequence=sequence, + hypothesis_id=self.hypothesis_id) + return protein + + def run(self): + downloader = self._make_downloader() + downloader.start() + + has_work = True + + while has_work: + try: + accession, value = downloader.get(True, 3) + if isinstance(value, Exception): + self.log(""Could not retrieve %s - %r"" % (accession, value)) + else: + protein = self.make_protein(accession, value) + self.proteins.append(protein) + except Empty: + # If we haven't completed the download process, block + # now and wait for the threads to join, then continue + # trying to fetch results + if not downloader.done_event.is_set(): + downloader.join() + continue + # Otherwise we've already waited for all the results to + # arrive and we can stop iterating + else: + has_work = False + + +class UniprotToPEFFTranslator(TaskBase): + input_fasta_path: str + output_path: str + n_processes: int + + def __init__(self, input_fasta_path, output_path, n_processes: int=12) -> None: + super().__init__() + self.input_fasta_path = input_fasta_path + self.output_path = output_path + self.n_processes = n_processes + + def run(self): + reader = fasta.ProteinFastaFileReader(self.input_fasta_path, index=True) + + accessions = [] + for key in reader.index.keys(): + acc = key.get(""accession"") + if acc: + accessions.append(acc) + + queue = UniprotProteinDownloader(accessions, self.n_processes) + + queue.start() + + header_block = fasta.PEFFHeaderBlock() + header_block['Prefix'] = 'sp' + header_block['SequenceType'] = 'AA' + + converter = UniprotToPeffConverter() + + with open(self.output_path, 'wb') as fh: + writer = fasta.PEFFWriter(fh) + writer.write_header([header_block]) + while True: + try: + name, rec = queue.get() + try: + prot = converter(rec) + writer.write(prot) + except fasta.UnknownAminoAcidException as err: + self.log(f""Skipping {name}, failed to convert to PEFF: {err}"") + + except Empty: + queue.join() + if queue.done_event.is_set(): + break +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/proteomics/mzid_proteome.py",".py","55956","1446","import os +import re +import operator +import logging +from collections import defaultdict +from dataclasses import dataclass +from typing import Any, DefaultDict, Dict, List, Mapping, Optional, Set, Tuple + +from six import string_types as basestring + +from glycopeptidepy.io import fasta as glycopeptidepy_fasta +from glycopeptidepy.structure import sequence, modification, residue +from glycopeptidepy.enzyme import Protease, enzyme_rules +from glypy.composition import formula + +from glycresoft.serialize import ( + Peptide, Protein, DatabaseBoundOperation) + +from glycresoft.task import TaskBase + +from ..common import ProteinReversingMixin + +from .mzid_parser import Parser +from .peptide_permutation import ( + ProteinDigestor, n_glycan_sequon_sites, + o_glycan_sequon_sites, gag_sequon_sites, UniprotProteinAnnotator) +from .remove_duplicate_peptides import DeduplicatePeptides +from .share_peptides import PeptideSharer +from .fasta import FastaProteinSequenceResolver + +logger = logging.getLogger(""mzid"") + + +PeptideSequence = sequence.PeptideSequence +Residue = residue.Residue +Modification = modification.Modification +ModificationNameResolutionError = modification.ModificationNameResolutionError +AnonymousModificationRule = modification.AnonymousModificationRule + +GT = ""greater"" +LT = ""lesser"" + +PROTEOMICS_SCORE = { + ""PEAKS:peptideScore"": GT, + ""mascot:score"": GT, + ""PEAKS:proteinScore"": GT, + ""MS-GF:EValue"": LT, + ""Byonic:Score"": GT, + ""percolator:Q value"": LT, + r""X\!Tandem:expect"": GT, + ""Morpheus:Morpheus score"": GT, + ""MetaMorpheus:score"": GT, +} + + +def score_comparator(score_type): + try: + preference = PROTEOMICS_SCORE[score_type] + if preference == LT: + return operator.lt + else: + return operator.gt + except KeyError: + raise KeyError(""Don't know how to compare score of type %r"" % score_type) + + +WHITELIST_GLYCOSITE_PTMS = [Modification(""Deamidation""), Modification(""HexNAc"")] + + +class allset(object): + + def __contains__(self, x): + return True + + +class ParameterizedProtease(Protease): + def __init__(self, name, used_missed_cleavages=1, cleavage_start=None, cleavage_end=None): + super(ParameterizedProtease, self).__init__(name, cleavage_start, cleavage_end) + self.used_missed_cleavages = used_missed_cleavages + + +def resolve_database_url(url): + if url.startswith(""file://""): + path = url.replace(""file://"", """") + while path.startswith(""/"") and len(path) > 0: + path = path[1:] + if os.path.exists(path): + if os.path.isfile(path): + return path + else: + raise IOError(""File URI %r points to a directory"" % url) + else: + raise IOError(""File URI %r does not exist on local system"" % url) + elif url.startswith(""http""): + return url + elif os.path.exists(url): + if os.path.isfile(url): + return url + else: + raise IOError(""File path %r points to a directory"" % url) + else: + raise IOError(""Cannot resolve URL %r"" % url) + + +def protein_names(mzid_path, pattern=r'.*'): + pattern = re.compile(pattern) + parser = Parser(mzid_path, retrieve_refs=False, + iterative=True, build_id_cache=False, use_index=False) + for protein in parser.iterfind( + ""DBSequence"", retrieve_refs=False, recursive=False, iterative=True): + name = protein['accession'] + if pattern.match(name): + yield name + + +def remove_peptide_sequence_alterations(base_sequence, insert_sites, delete_sites): + """""" + Remove all the sequence insertions and deletions in order to reconstruct the + original peptide sequence. + + Parameters + ---------- + base_sequence : str + The peptide sequence string which contains a combination + of insertion and deletions. + insert_sites : list + A list of (position, None) pairs indicating the position of + an amino acid insertion to be removed. + delete_sites : list + A list of (position, residue) pairs indicating the position + and identity of amino acids that were deleted and need to be + re-inserted. + + Returns + ------- + str + """""" + sequence_copy = list(base_sequence) + + alteration_sites = insert_sites + delete_sites + alteration_sites.sort() + shift = 0 + for position, residue_ in alteration_sites: + if residue_ is None: + sequence_copy.pop(position - shift) + shift += 1 + else: + sequence_copy.insert(position - shift + 1, residue_) + shift -= 1 + sequence_copy = ''.join(sequence_copy) + return sequence_copy + + +class PeptideGroup(object): + """"""Maps Protein ID to :class:`Peptide`, keeping track of the top scoring example + for each :class:`Peptide` instance observed from the set of target Proteins + + Attributes + ---------- + has_target_match: bool + Description + members: dict + Mapping from Protein ID to :class:`Peptide` + scores: defaultdict(list) + Mapping from Protein ID to score + """""" + + members: Dict + scores: DefaultDict[str, List[float]] + has_target_match: bool + + def __init__(self): + self.members = dict() + self.scores = defaultdict(list) + self.has_target_match = False + self._first = None + self._last = None + + def __getitem__(self, key): + return self.members[key] + + def __setitem__(self, key, value): + self.members[key] = value + if self._first is None: + self._first = value + self._last = value + + def clear(self): + self.members.clear() + self.has_target_match = False + self._first = None + self._last = None + + def _update_has_target_match(self, protein_set: Set[str]) -> bool: + for key in self.members: + if key in protein_set: + return True + return False + + def update_state(self, protein_set: Set[str]): + had = self.has_target_match + if not had: + has = self.has_target_match = self._update_has_target_match(protein_set) + else: + has = had + if not had and has: + for key in list(self.members): + if key not in protein_set: + self.members.pop(key) + self.scores.pop(key) + else: + if self._last.protein_id not in protein_set: + try: + self.members.pop(self._last.protein_id) + self.scores.pop(self._last.protein_id) + except KeyError: + pass + + def keys(self): + return self.members.keys() + + def values(self): + return self.members.values() + + def items(self): + return self.members.items() + + def bind_scores(self): + acc = [] + for key, peptide in self.members.items(): + peptide.scores = self.scores[key] + acc.extend(self.scores[key]) + return acc + + def first(self): + return self._first + + def __nonzero__(self): + if self.members: + return True + else: + return False + + def __bool__(self): + if self.members: + return True + else: + return False + + def __len__(self): + return len(self.members) + + def add(self, peptide): + comparator = score_comparator(peptide.peptide_score_type) + if self: + first = self.first() + if comparator(peptide.peptide_score, first.peptide_score): + self.clear() + self[peptide.protein_id] = peptide + elif first.peptide_score == peptide.peptide_score: + self[peptide.protein_id] = peptide + else: + self[peptide.protein_id] = peptide + self.scores[peptide.protein_id].append(peptide.peptide_score) + + +class PeptideCollection(object): + store: DefaultDict[str, PeptideGroup] + protein_set: Set[str] + scores: List[float] + + def __init__(self, protein_set): + self.store = defaultdict(PeptideGroup) + self.protein_set = protein_set + self.scores = [] + + def bind_scores(self): + acc = [] + for key, value in self.store.items(): + acc.extend(value.bind_scores()) + self.scores = acc + return acc + + def add(self, peptide): + group = self.store[peptide.modified_peptide_sequence] + group.add(peptide) + group.update_state(self.protein_set) + self.store[peptide.modified_peptide_sequence] = group + + def items(self): + for key, mapping in self.store.items(): + yield key, mapping.values() + + def __len__(self): + return sum(map(len, self.store.values())) + + +class MzIdentMLPeptide(object): + peptide_dict: Dict[str, Any] + insert_sites: List[Tuple[int, str]] + deleteion_sites: List[Tuple[int, str]] + + modification_counter: int + missed_cleavages: Optional[int] + + base_sequence: str + peptide_sequence: PeptideSequence + glycosite_candidates: List[int] + + modification_translation_table: Dict[str, Modification] + enzyme: Optional[Protease] + mzid_id: Optional[str] + + def __init__(self, peptide_dict, enzyme=None, constant_modifications=None, + modification_translation_table=None, process=True): + if modification_translation_table is None: + modification_translation_table = dict() + if constant_modifications is None: + constant_modifications = list() + + self.peptide_dict = peptide_dict + + self.insert_sites = [] + self.deleteion_sites = [] + self.modification_counter = 0 + self.missed_cleavages = 0 + + self.base_sequence = peptide_dict[""PeptideSequence""] + self.peptide_sequence = PeptideSequence(peptide_dict[""PeptideSequence""]) + + self.glycosite_candidates = sequence.find_n_glycosylation_sequons( + self.peptide_sequence, WHITELIST_GLYCOSITE_PTMS) + + self.constant_modifications = constant_modifications + self.modification_translation_table = modification_translation_table + self.enzyme = enzyme + self.mzid_id = peptide_dict.get('id') + + if process: + self.process() + + def handle_missed_cleavages(self): + if self.enzyme is not None: + self.missed_cleavages = self.enzyme.missed_cleavages(self.base_sequence) + else: + self.missed_cleavages = None + + def handle_substitutions(self): + if ""SubstitutionModification"" in self.peptide_dict: + subs = self.peptide_dict[""SubstitutionModification""] + for sub in subs: + pos = sub['location'] - 1 + replace = Residue(sub[""replacementResidue""]) + self.peptide_sequence.substitute(pos, replace) + self.modification_counter += 1 + + def add_modification(self, modification: Modification, position: int): + if position == -1: + targets = modification.rule.n_term_targets + for t in targets: + if t.position_modifier is not None and t.amino_acid_targets is None: + break + else: + position += 1 + if position == len(self.peptide_sequence): + targets = modification.rule.c_term_targets + for t in targets: + if t.position_modifier is not None and t.amino_acid_targets is None: + break + else: + position -= 1 + if position == -1: + self.peptide_sequence.n_term = modification + elif position == len(self.peptide_sequence): + self.peptide_sequence.c_term = modification + else: + self.peptide_sequence.add_modification(position, modification) + + def add_insertion(self, site: int, symbol=None): + self.insert_sites.append((site, symbol)) + + def add_deletion(self, site: int, symbol): + self.deleteion_sites.append((site, symbol)) + + def handle_modifications(self): + if ""Modification"" in self.peptide_dict: + mods: List[Dict[str, Any]] = self.peptide_dict[""Modification""] + for mod in mods: + pos: int = mod[""location""] - 1 + accession = None + try: + if ""unknown modification"" in mod: + try: + _name = mod['unknown modification'] + if _name in self.modification_translation_table: + modification = self.modification_translation_table[_name]() + else: + modification = Modification(str(_name)) + except ModificationNameResolutionError: + raise KeyError(""Cannot find key in %r"" % (mod,)) + else: + try: + _name = mod[""name""] + accession = getattr(_name, ""accession"", None) + _name = str(_name) + if accession is not None: + accession = str(accession) + try: + modification = Modification(accession) + except ModificationNameResolutionError: + modification = Modification(_name) + else: + modification = Modification(_name) + + except (KeyError, ModificationNameResolutionError) as e: + raise KeyError(""Cannot find key %s in %r"" % (e, mod)) + + try: + rule_text = ""%s (%s)"" % (_name, mod[""residues""][0]) + if (rule_text not in self.constant_modifications) and not ( + pos in self.glycosite_candidates and modification in WHITELIST_GLYCOSITE_PTMS): + self.modification_counter += 1 + except KeyError: + self.modification_counter += 1 + + self.add_modification(modification, pos) + except KeyError: + if ""unknown modification"" in mod: + mod_description = mod[""unknown modification""] + insertion = re.search(r""(\S{3})\sinsertion"", mod_description) + deletion = re.search(r""(\S{3})\sdeletion"", mod_description) + self.modification_counter += 1 + if insertion: + self.add_insertion(mod['location'] - 1, None) + elif deletion: + sym = Residue(deletion.groups()[0]).symbol + self.add_deletion(mod['location'] - 1, sym) + elif 'monoisotopicMassDelta' in mod: + mass = float(mod['monoisotopicMassDelta']) + modification = AnonymousModificationRule(str(_name), mass)() + self.add_modification(modification, pos) + else: + raise + else: + raise + + def process(self): + self.handle_substitutions() + self.handle_modifications() + self.handle_missed_cleavages() + + def original_sequence(self): + sequence_copy = remove_peptide_sequence_alterations( + self.base_sequence, self.insert_sites, self.deleteion_sites) + return sequence_copy + + def __repr__(self): + return f""{self.__class__.__name__}({self.peptide_sequence}, {self.glycosite_candidates})"" + + +class _EvidenceMixin: + @property + def score_type(self) -> Tuple[Optional[float], Optional[str]]: + score = score_type = None + for k, v in self.peptide_dict.items(): + if k in PROTEOMICS_SCORE: + score_type = k + score = v + break + return score, score_type + + @property + def evidence_list(self) -> List[Dict[str, Any]]: + evidence_list = self.peptide_dict[""PeptideEvidenceRef""] + # Flatten the evidence list if it has extra nesting because of alternative + # mzid parsing + if isinstance(evidence_list[0], list): + evidence_list = [x for sub in evidence_list for x in sub] + return evidence_list + + +class PeptideIdentification(MzIdentMLPeptide, _EvidenceMixin): + def __init__(self, peptide_dict, enzyme=None, constant_modifications=None, + modification_translation_table=None, process=True): + super(PeptideIdentification, self).__init__( + peptide_dict, enzyme, constant_modifications, modification_translation_table, + process) + + +class ProteinStub(object): + name: str + id: int + protein_sequence: str + n_glycan_sequon_sites: List[int] + o_glycan_sequon_sites: List[int] + glycosaminoglycan_sequon_sites: List[int] + + def __len__(self): + return len(self.protein_sequence) + + def __init__(self, name, id, sequence, n_glycan_sequon_sites, o_glycan_sequon_sites, + glycosaminoglycan_sequon_sites): + self.name = name + self.id = id + self.protein_sequence = sequence + self.n_glycan_sequon_sites = n_glycan_sequon_sites + self.o_glycan_sequon_sites = o_glycan_sequon_sites + self.glycosaminoglycan_sequon_sites = glycosaminoglycan_sequon_sites + + @classmethod + def from_protein(cls, protein): + return cls( + str(protein.name), + getattr(protein, 'id', None), + str(protein), + protein.n_glycan_sequon_sites, + protein.o_glycan_sequon_sites, + protein.glycosaminoglycan_sequon_sites) + + def __repr__(self): + trailer = self.protein_sequence[:10] + '...' + return f""{self.__class__.__name__}({self.name!r}, {self.id}, {trailer!r})"" + + +class ProteinStubLoaderBase(object): + store: Mapping[str, ProteinStub] + + def __init__(self, store=None): + if store is None: + store = dict() + self.store = store + + def __getitem__(self, key: str) -> ProteinStub: + return self.get_protein_by_name(key) + + def __contains__(self, key: str): + return key in self.store + + def _load_protein(self, protein_name: str): + raise NotImplementedError() + + def get_protein_by_name(self, protein_name: str) -> ProteinStub: + try: + return self.store[protein_name] + except KeyError: + protein = self._load_protein(protein_name) + try: + stub = ProteinStub.from_protein(protein) + except AttributeError: + logger.error(""Failed to load stub for %s"" % (protein_name,)) + raise + self.store[protein_name] = stub + return stub + + +class MemoryProteinStubLoader(ProteinStubLoaderBase): + def _load_protein(self, protein_name): + raise KeyError(protein_name) + + +class DatabaseProteinStubLoader(ProteinStubLoaderBase): + hypothesis_id: int + alias_map: Dict[str, str] + + def __init__(self, session, hypothesis_id, store=None, alias_map: Optional[Dict[str, str]]=None): + if alias_map is None: + alias_map = {} + self.session = session + self.hypothesis_id = hypothesis_id + self.alias_map = alias_map + super(DatabaseProteinStubLoader, self).__init__(store) + + def _load_protein(self, protein_name: str) -> Protein: + if protein_name in self.alias_map: + protein_name = self.alias_map[protein_name] + protein = self.session.query(Protein).filter( + Protein.name == protein_name, + Protein.hypothesis_id == self.hypothesis_id).first() + if protein is None: + breakpoint() + raise KeyError(protein_name) + return protein + + +class FastaProteinStubLoader(ProteinStubLoaderBase): + def __init__(self, fasta_path, store=None): + super(FastaProteinStubLoader, self).__init__(store) + self.parser = glycopeptidepy_fasta.ProteinFastaFileParser(fasta_path, index=True) + + def _load_protein(self, protein_name: str): + return self.parser[protein_name] + + +class PeptideMapperBase(object): + enzyme: Protease + constant_modifications: Dict[str, Modification] + modification_translation_table: Dict[str, Modification] + + peptide_grouper: PeptideCollection + protein_loader: ProteinStubLoaderBase + + + counter: int + peptide_length_range: Tuple[int, int] + + + def __init__(self, enzyme=None, constant_modifications=None, modification_translation_table=None, + protein_filter=None, peptide_length_range=(5, 60)): + if protein_filter is None: + protein_filter = allset() + + self.enzyme = enzyme + self.constant_modifications = constant_modifications or [] + self.modification_translation_table = modification_translation_table or {} + + self.peptide_grouper = PeptideCollection(protein_filter) + self.counter = 0 + + self.protein_loader = self._make_protein_loader() + self.peptide_length_range = peptide_length_range + + def _make_protein_loader(self): + raise NotImplementedError() + + +class PeptideConverter(PeptideMapperBase): + hypothesis_id: int + include_cysteine_n_glycosylation: bool + + def __init__(self, session, hypothesis_id, enzyme=None, constant_modifications=None, + modification_translation_table=None, protein_filter=None, + peptide_length_range=(5, 60), + include_cysteine_n_glycosylation: bool = False, + protein_alias_map: Optional[Dict[str, str]]=None): + self.session = session + self.hypothesis_id = hypothesis_id + self.include_cysteine_n_glycosylation = include_cysteine_n_glycosylation + self.protein_alias_map = protein_alias_map + super(PeptideConverter, self).__init__( + enzyme, constant_modifications, modification_translation_table, + protein_filter, peptide_length_range) + + def _make_protein_loader(self): + return DatabaseProteinStubLoader(self.session, self.hypothesis_id, alias_map=self.protein_alias_map) + + def get_protein(self, evidence): + return self.protein_loader[evidence['accession']] + + def pack_peptide(self, peptide_ident: PeptideIdentification, start: int, end: int, score: float, + score_type: str, parent_protein: Protein): + match = Peptide( + calculated_mass=peptide_ident.peptide_sequence.mass, + base_peptide_sequence=peptide_ident.base_sequence, + modified_peptide_sequence=str(peptide_ident.peptide_sequence), + formula=formula(peptide_ident.peptide_sequence.total_composition()), + count_glycosylation_sites=None, + count_missed_cleavages=peptide_ident.missed_cleavages, + count_variable_modifications=peptide_ident.modification_counter, + start_position=start, + end_position=end, + peptide_score=score, + peptide_score_type=score_type, + sequence_length=end - start, + protein_id=parent_protein.id, + hypothesis_id=self.hypothesis_id) + n_glycosites = n_glycan_sequon_sites( + match, parent_protein, include_cysteine=self.include_cysteine_n_glycosylation) + o_glycosites = o_glycan_sequon_sites(match, parent_protein) + gag_glycosites = gag_sequon_sites(match, parent_protein) + match.count_glycosylation_sites = len(n_glycosites) + len(o_glycosites) + match.n_glycosylation_sites = sorted(n_glycosites) + match.o_glycosylation_sites = sorted(o_glycosites) + match.gagylation_sites = sorted(gag_glycosites) + return match + + def copy_db_peptide(self, db_peptide: Peptide): + dup = Peptide( + calculated_mass=db_peptide.calculated_mass, + base_peptide_sequence=db_peptide.base_peptide_sequence, + modified_peptide_sequence=db_peptide.modified_peptide_sequence, + formula=db_peptide.formula, + count_glycosylation_sites=db_peptide.count_glycosylation_sites, + count_missed_cleavages=db_peptide.count_missed_cleavages, + count_variable_modifications=db_peptide.count_variable_modifications, + start_position=db_peptide.start_position, + end_position=db_peptide.end_position, + peptide_score=db_peptide.peptide_score, + peptide_score_type=db_peptide.peptide_score_type, + sequence_length=db_peptide.sequence_length, + protein_id=db_peptide.protein_id, + hypothesis_id=db_peptide.hypothesis_id, + n_glycosylation_sites=db_peptide.n_glycosylation_sites, + o_glycosylation_sites=db_peptide.o_glycosylation_sites, + gagylation_sites=db_peptide.gagylation_sites) + return dup + + def has_occupied_glycosites(self, db_peptide: Peptide): + occupied_sites = [] + n_glycosylation_sites = db_peptide.n_glycosylation_sites + peptide_obj = PeptideSequence(db_peptide.modified_peptide_sequence) + + for site in n_glycosylation_sites: + if peptide_obj[site][1]: + occupied_sites.append(site) + return len(occupied_sites) > 0 + + def clear_sites(self, db_peptide: Peptide): + # TODO: Make this a combinatorial generator so that it optionally clears each + # putative combination of glycosites across N/O forms. + occupied_sites = [] + n_glycosylation_sites = db_peptide.n_glycosylation_sites + peptide_obj = PeptideSequence(db_peptide.modified_peptide_sequence) + + for site in n_glycosylation_sites: + if peptide_obj[site][1]: + occupied_sites.append(site) + + for site in occupied_sites: + peptide_obj.drop_modification(site, peptide_obj[site][1][0]) + + copy = self.copy_db_peptide(db_peptide) + copy.calculated_mass = peptide_obj.mass + copy.modified_peptide_sequence = str(peptide_obj) + copy.count_variable_modifications -= len(occupied_sites) + return copy + + def sequence_starts_at(self, sequence: str, parent_protein: Protein) -> int: + found = parent_protein.protein_sequence.find(sequence) + if found == -1: + raise ValueError(""Peptide not found in Protein\n%s\n%r\n\n"" % (parent_protein.name, sequence)) + return found + + def handle_peptide_dict(self, peptide_dict: Dict[str, Any]): + peptide_ident = PeptideIdentification( + peptide_dict, self.enzyme, self.constant_modifications, + self.modification_translation_table) + + score, score_type = peptide_ident.score_type + evidence_list = peptide_ident.evidence_list + + for evidence in evidence_list: + if ""skip"" in evidence: + continue + if evidence.get(""isDecoy"", False): + continue + + parent_protein = self.get_protein(evidence) + if parent_protein is None: + continue + + start = evidence[""start""] - 1 + end = evidence[""end""] + length = len(peptide_ident.base_sequence) + if not (self.peptide_length_range[0] <= length <= self.peptide_length_range[1]): + continue + + sequence_copy = peptide_ident.original_sequence() + found = self.sequence_starts_at(sequence_copy, parent_protein) + + if found != start: + start = found + end = start + length + + match = self.pack_peptide( + peptide_ident, start, end, score, score_type, parent_protein) + self.add_to_group(match) + if self.has_occupied_glycosites(match): + cleared = self.clear_sites(match) + self.add_to_group(cleared) + + def add_to_group(self, match): + self.counter += 1 + self.peptide_grouper.add(match) + + def save_accumulation(self): + acc = [] + self.peptide_grouper.bind_scores() + for key, group in self.peptide_grouper.items(): + acc.extend(group) + self.session.bulk_save_objects(acc) + self.session.commit() + + +class MzIdentMLProteomeExtraction(TaskBase): + def __init__(self, mzid_path, reference_fasta=None, peptide_length_range=(5, 60)): + self.mzid_path = mzid_path + self.reference_fasta = reference_fasta + self.parser = Parser(mzid_path, retrieve_refs=True, iterative=True, use_index=True) + self.enzymes = [] + self.constant_modifications = [] + self.modification_translation_table = {} + + self._protein_resolver = None + self._ignore_protein_regex = None + self._used_database_path = None + + self.peptide_length_range = peptide_length_range or (5, 60) + + def load_enzyme(self): + self.parser.reset() + # self.enzymes = list({e['name'].lower() for e in self.parser.iterfind( + # ""EnzymeName"", retrieve_refs=True, iterative=True)}) + enzymes = list(self.parser.iterfind(""Enzyme"", retrieve_refs=True, iterative=True)) + processed_enzymes = [] + for enz in enzymes: + permitted_missed_cleavages = int(enz.get(""missedCleavages"", 1)) + # It's a standard enzyme, so we can look it up by name + if ""EnzymeName"" in enz: + try: + enz_name = enz.get('EnzymeName') + if isinstance(enz_name, dict): + if len(enz_name) == 1: + enz_name = list(enz_name)[0] + else: + self.log(""Could not interpret Enzyme Name %r"" % (enz,)) + protease = ParameterizedProtease(enz_name.lower(), permitted_missed_cleavages) + processed_enzymes.append(protease) + except (KeyError, re.error) as e: + self.log(""Could not resolve protease from name %r (%s)"" % (enz['EnzymeName'].lower(), e)) + elif ""SiteRegexp"" in enz: + pattern = enz['SiteRegexp'] + try: + protease = ParameterizedProtease(pattern, permitted_missed_cleavages) + processed_enzymes.append(protease) + except re.error as e: + self.log(""Could not resolve protease from name %r (%s)"" % (enz['SiteRegexp'].lower(), e)) + except KeyError: + self.log(""No protease information available: %r"" % (enz,)) + elif ""name"" in enz and enz['name'].lower() in enzyme_rules: + protease = ParameterizedProtease(enz[""name""].lower(), permitted_missed_cleavages) + processed_enzymes.append(protease) + elif ""id"" in enz and enz['id'].lower() in enzyme_rules: + protease = ParameterizedProtease(enz[""id""].lower(), permitted_missed_cleavages) + processed_enzymes.append(protease) + else: + self.log(""No protease information available: %r"" % (enz,)) + self.enzymes = list(set(processed_enzymes)) + + def load_modifications(self): + self.parser.reset() + search_param_modifications = list(self.parser.iterfind( + ""ModificationParams"", retrieve_refs=True, iterative=True)) + constant_modifications = [] + + for param in search_param_modifications: + for mod in param['SearchModification']: + try: + name = mod['name'] + except KeyError: + name = mod['unknown modification'] + try: + Modification(str(name)) + except ModificationNameResolutionError: + self.modification_translation_table[name] = modification.AnonymousModificationRule( + str(name), mod['massDelta']) + + residues = mod['residues'] + if mod.get('fixedMod', False): + identifier = ""%s (%s)"" % (name, ''.join(residues).replace("" "", """")) + constant_modifications.append(identifier) + self.constant_modifications = constant_modifications + + def _make_protein_resolver(self): + if self.reference_fasta is not None: + self._protein_resolver = FastaProteinSequenceResolver(self.reference_fasta) + return + else: + path = self._find_used_database() + if path is not None: + self._protein_resolver = FastaProteinSequenceResolver(path) + return + raise ValueError(""Cannot construct a Protein Resolver. Cannot fetch additional protein information."") + + def _clear_protein_resolver(self): + self._protein_resolver = None + + def _find_used_database(self): + if self._used_database_path is not None: + return self._used_database_path + self.parser.reset() + databases = list(self.parser.iterfind(""SearchDatabase"", iterative=True)) + # use only the first database + if len(databases) > 1: + self.log(""... %d databases found: %r"" % (len(databases), databases)) + self.log(""... Using first only"") + database = databases[0] + if ""decoy DB accession regexp"" in database: + self._ignore_protein_regex = re.compile(database[""decoy DB accession regexp""]) + if ""FASTA format"" in database.get('FileFormat', {}): + self.log(""... Database described in FASTA format"") + db_location = database.get(""location"") + if db_location is None: + raise ValueError(""No location present for database"") + else: + try: + path = resolve_database_url(db_location) + with open(path, 'r') as handle: + for i, line in enumerate(handle): + if i > 1000: + raise ValueError(""No FASTA Header before thousandth line. Probably not a FASTA file"") + if line.startswith("">""): + break + self._used_database_path = path + return path + except (IOError, ValueError): + return None + else: + return None + + def resolve_protein(self, name): + if self._protein_resolver is None: + self._make_protein_resolver() + proteins = self._protein_resolver.find(name) + if len(proteins) > 1: + self.log(""Protein Name %r resolved to multiple proteins: %r. Using first only."" % (name, proteins)) + elif len(proteins) == 0: + raise KeyError(name) + return proteins[0] + + def _load_peptides(self): + self.parser.reset() + i = 0 + try: + enzyme = self.enzymes[0] + except IndexError as e: + logger.exception(""Enzyme not found."", exc_info=e) + enzyme = None + for peptide in self.parser.iterfind(""Peptide"", iterative=True, retrieve_refs=True): + i += 1 + mzid_peptide = MzIdentMLPeptide( + peptide, enzyme, self.constant_modifications, + self.modification_translation_table) + if i % 1000 == 0: + self.log(""Loaded Peptide %r"" % (mzid_peptide,)) + yield mzid_peptide + + def _map_peptide_to_proteins(self): + self.parser.reset() + i = 0 + peptide_to_proteins = defaultdict(set) + for evidence in self.parser.iterfind('PeptideEvidence', iterative=True): + i += 1 + peptide_to_proteins[evidence['peptide_ref']].add( + evidence['dBSequence_ref']) + return peptide_to_proteins + + def _handle_protein(self, name, sequence, data): + raise NotImplementedError() + + def load_proteins(self): + self.parser.reset() + self._find_used_database() + protein_map = {} + self.parser.reset() + for protein in self.parser.iterfind(""DBSequence"", recursive=True, iterative=True): + seq = protein.pop('Seq', None) + name = protein.pop('accession') + if seq is None: + try: + prot = self.resolve_protein(name) + seq = prot.protein_sequence + except KeyError: + if self._can_ignore_protein(name): + continue + else: + self.log(""Could not resolve protein %r"" % (name,)) + + if ""protein description"" in protein: + name = "" "".join( + (name, + protein.pop(""protein description"")) + ) + + if name in protein_map: + if seq != protein_map[name].protein_sequence: + self.log(""Multiple proteins with the name %r"" % name) + continue + try: + p = self._handle_protein(name, seq, protein) + protein_map[name] = p + except residue.UnknownAminoAcidException: + self.log(""Unknown Amino Acid in %r"" % (name,)) + continue + except Exception as e: + self.log(""%r skipped: %r"" % (name, e)) + continue + self._clear_protein_resolver() + return protein_map + + +class Proteome(DatabaseBoundOperation, MzIdentMLProteomeExtraction): + def __init__(self, mzid_path, connection, hypothesis_id, include_baseline_peptides=True, + target_proteins=None, reference_fasta=None, + peptide_length_range=(5, 60), use_uniprot=True, + include_cysteine_n_glycosylation: bool=False, + uniprot_source_file: Optional[str]=None): + DatabaseBoundOperation.__init__(self, connection) + MzIdentMLProteomeExtraction.__init__(self, mzid_path, reference_fasta) + if target_proteins is None: + target_proteins = [] + self.hypothesis_id = hypothesis_id + self.target_proteins = target_proteins + self.include_baseline_peptides = include_baseline_peptides + self.peptide_length_range = peptide_length_range or (5, 60) + self.use_uniprot = use_uniprot + self.accession_map = {} + self.include_cysteine_n_glycosylation = include_cysteine_n_glycosylation + self.uniprot_source_file = uniprot_source_file + + def _can_ignore_protein(self, name): + if name not in self.target_proteins: + return True + elif (self._ignore_protein_regex is not None) and ( + self._ignore_protein_regex.match(name)): + return True + return False + + def _make_protein_from_state(self, name: str, seq: str, state: dict): + p = Protein( + name=name, + protein_sequence=seq, + other=state, + hypothesis_id=self.hypothesis_id) + p._init_sites(self.include_cysteine_n_glycosylation) + return p + + def load_proteins(self): + self.parser.reset() + self._find_used_database() + session = self.session + protein_map = {} + self.accession_map = {} + self.parser.reset() + for protein in self.parser.iterfind( + ""DBSequence"", retrieve_refs=True, recursive=True, iterative=True): + seq = protein.pop('Seq', None) + accession = name = protein.pop('accession') + if seq is None: + try: + prot = self.resolve_protein(name) + seq = prot.protein_sequence + except KeyError: + if self._can_ignore_protein(name): + continue + else: + self.log(""Could not resolve protein %r"" % (name,)) + + if ""protein description"" in protein: + name = "" "".join( + (name, + protein.pop(""protein description"")) + ) + + if name in protein_map: + if seq != protein_map[name].protein_sequence: + self.log(""Multiple proteins with the name %r"" % name) + continue + try: + p = self._make_protein_from_state(name, seq, protein) + session.add(p) + session.flush() + protein_map[name] = p + self.accession_map[accession] = name + except residue.UnknownAminoAcidException: + self.log(""Unknown Amino Acid in %r"" % (name,)) + continue + except Exception as e: + self.log(""%r skipped: %r"" % (name, e)) + continue + session.commit() + self._clear_protein_resolver() + + def _make_peptide_converter(self, session, protein_filter: Set[int], enzyme: Protease, **kwargs): + return PeptideConverter( + session, self.hypothesis_id, enzyme, + self.constant_modifications, + self.modification_translation_table, + protein_filter=protein_filter, + protein_alias_map=self.accession_map, **kwargs) + + def load_spectrum_matches(self): + self.parser.reset() + last = 0 + i = 0 + try: + enzyme = self.enzymes[0] + except IndexError as e: + logger.exception(""Enzyme not found."", exc_info=e) + enzyme = None + session = self.session + + protein_filter = set(self.retrieve_target_protein_ids()) + + peptide_converter = self._make_peptide_converter( + session, protein_filter, enzyme) + + for spectrum_identification in self.parser.iterfind( + ""SpectrumIdentificationItem"", retrieve_refs=True, iterative=True): + peptide_converter.handle_peptide_dict(spectrum_identification) + i += 1 + if i % 1000 == 0: + self.log(""... %d spectrum matches processed."" % i) + if (peptide_converter.counter - last) > 1000000: + last = peptide_converter.counter + self.log(""... %d peptides saved. %d distinct cases."" % ( + peptide_converter.counter, len( + peptide_converter.peptide_grouper))) + self.log(""... %d peptides saved. %d distinct cases."" % ( + peptide_converter.counter, len( + peptide_converter.peptide_grouper))) + peptide_converter.save_accumulation() + + def load(self): + self.log(""... Loading Enzyme"") + self.load_enzyme() + self.log(""... Loading Modifications"") + self.load_modifications() + self.log(""... Loading Proteins"") + self.load_proteins() + self.log(""... Loading Spectrum Matches"") + self.load_spectrum_matches() + self.log(""Sharing Common Peptides"") + self.remove_duplicates() + self.share_common_peptides() + self.remove_duplicates() + self.log(""... %d Peptides Total"" % (self.count_peptides())) + if self.include_baseline_peptides: + self.log(""... Building Baseline Peptides"") + self.build_baseline_peptides() + self.remove_duplicates() + self.log(""... %d Peptides Total"" % (self.count_peptides())) + if self.use_uniprot: + self.split_proteins() + self.log(""... Removing Duplicate Peptides"") + self.remove_duplicates() + self.log(""... %d Peptides Total"" % (self.count_peptides())) + + def retrieve_target_protein_ids(self): + if not self.target_proteins: + return [ + i[0] for i in + self.query(Protein.id).filter( + Protein.hypothesis_id == self.hypothesis_id).all() + ] + else: + result = [] + for target in self.target_proteins: + if isinstance(target, basestring): + if target in self.accession_map: + target = self.accession_map[target] + match = self.query(Protein.id).filter( + Protein.name == target, + Protein.hypothesis_id == self.hypothesis_id).first() + if match: + result.append(match[0]) + else: + self.log(""Could not locate protein '%s'"" % target) + elif isinstance(target, int): + result.append(target) + return result + + def get_target_proteins(self): + ids = self.retrieve_target_protein_ids() + return [self.session.query(Protein).get(i) for i in ids] + + def count_peptides(self): + peptide_count = self.session.query(Peptide).filter( + Peptide.hypothesis_id == self.hypothesis_id).count() + return peptide_count + + def make_restricted_modification_rules(self, rule_strings: List[str]): + standard_rules = [] + alternative_rules: DefaultDict[str, List[str]] = DefaultDict(list) + for rule_str in rule_strings: + name = modification.RestrictedModificationTable.extract_name(rule_str) + if name in self.modification_translation_table: + if isinstance(self.modification_translation_table[name], AnonymousModificationRule): + alternative_rules[name].append(rule_str) + else: + standard_rules.append(rule_str) + else: + standard_rules.append(rule_str) + + mod_table = modification.RestrictedModificationTable( + constant_modifications=standard_rules, + variable_modifications=[]) + rules = [mod_table[c] for c in standard_rules] + if alternative_rules: + for name, rule_strs in alternative_rules.items(): + rule: AnonymousModificationRule = self.modification_translation_table[name].clone() + rule.targets = {modification.RestrictedModificationTable.extract_target(s) for s in rule_strs} + rules.append(rule) + return rules + + def build_baseline_peptides(self): + const_modifications = self.make_restricted_modification_rules(self.constant_modifications) + digestor = ProteinDigestor( + self.enzymes[0], const_modifications, + max_missed_cleavages=self.enzymes[0].used_missed_cleavages, + include_cysteine_n_glycosylation=self.include_cysteine_n_glycosylation, + min_length=self.peptide_length_range[0], + max_length=self.peptide_length_range[1]) + accumulator = [] + i = 0 + for protein in self.get_target_proteins(): + for peptide in digestor.process_protein(protein): + peptide.hypothesis_id = self.hypothesis_id + accumulator.append(peptide) + i += 1 + if len(accumulator) > 5000: + self.session.bulk_save_objects(accumulator) + self.session.commit() + accumulator = [] + if i % 1000 == 0: + self.log(""... %d Baseline Peptides Created"" % i) + + self.session.bulk_save_objects(accumulator) + self.session.commit() + + def share_common_peptides(self): + sharer = PeptideSharer(self._original_connection, self.hypothesis_id) + proteins = self.get_target_proteins() + i = 0 + n = len(proteins) + for protein in proteins: + i += 1 + # self.log(""... Accumulating Proteins for %r"" % protein) + sharer.find_contained_peptides(protein) + if i % 5 == 0: + self.log(""... %0.3f%% Done (%s)"" % (i / float(n) * 100., protein.name)) + + def split_proteins(self): + const_modifications = self.make_restricted_modification_rules(self.constant_modifications) + protein_ids = self.retrieve_target_protein_ids() + if self.use_uniprot: + annotator = UniprotProteinAnnotator( + self, + protein_ids, + const_modifications, + [], + uniprot_source_file=self.uniprot_source_file + ) + annotator.run() + + def remove_duplicates(self): + DeduplicatePeptides(self._original_connection, self.hypothesis_id).run() + + +@dataclass +class _PositionedPeptideFacade: + start_position: int + end_position: int + modified_peptide_sequence: str + + +class ReverseMzIdentMLPeptide(MzIdentMLPeptide): + peptide_dict: Dict[str, Any] + insert_sites: List[Tuple[int, str]] + deleteion_sites: List[Tuple[int, str]] + + modification_counter: int + missed_cleavages: Optional[int] + + base_sequence: str + peptide_sequence: PeptideSequence + glycosite_candidates: List[int] + + modification_translation_table: Dict[str, Modification] + enzyme: Optional[Protease] + mzid_id: Optional[str] + + def __init__(self, peptide_dict, protein: Protein, enzyme=None, constant_modifications=None, + modification_translation_table=None, process=True): + if modification_translation_table is None: + modification_translation_table = dict() + if constant_modifications is None: + constant_modifications = list() + + facade = self.update_sequence(peptide_dict, protein) + + self.peptide_dict = peptide_dict + + self.insert_sites = [] + self.deleteion_sites = [] + self.modification_counter = 0 + self.missed_cleavages = 0 + + self.base_sequence = peptide_dict[""PeptideSequence""] + self.peptide_sequence = PeptideSequence(peptide_dict[""PeptideSequence""]) + + self.glycosite_candidates = n_glycan_sequon_sites(facade, protein) + + self.constant_modifications = constant_modifications + self.modification_translation_table = modification_translation_table + self.enzyme = enzyme + self.mzid_id = peptide_dict.get('id') + + if process: + self.process() + + def _reflect_position(self, position: int) -> int: + n = len(self.base_sequence) + return n - position + + def update_sequence(self, peptide_dict: dict, protein: Protein): + seq = peptide_dict['PeptideSequence'] + start = protein.protein_sequence[::-1].find(seq) + n = len(protein) + # Reflect the coordinates around the reversal point + end = n - start + start = end - len(seq) + seq = protein.protein_sequence[start + 1:end + 1] + peptide_dict['PeptideSequence'] = seq + return _PositionedPeptideFacade(start, end, seq) + + def handle_substitutions(self): + if ""SubstitutionModification"" in self.peptide_dict: + subs = self.peptide_dict[""SubstitutionModification""] + for sub in subs: + pos = sub['location'] - 1 + pos = max(self._reflect_position(pos) - 2, 0) + replace = Residue(sub[""replacementResidue""]) + self.peptide_sequence.substitute(pos, replace) + self.modification_counter += 1 + + def add_modification(self, modification: Modification, position: int): + if position == -1: + targets = modification.rule.n_term_targets + for t in targets: + if t.position_modifier is not None and t.amino_acid_targets is None: + break + else: + position += 1 + if position == len(self.peptide_sequence): + targets = modification.rule.c_term_targets + for t in targets: + if t.position_modifier is not None and t.amino_acid_targets is None: + break + else: + position -= 1 + if position == -1: + self.peptide_sequence.n_term = modification + elif position == len(self.peptide_sequence): + self.peptide_sequence.c_term = modification + else: + new_position = max(self._reflect_position(position) - 2, 0) + self.peptide_sequence.add_modification(new_position, modification) + + def add_insertion(self, site: int, symbol=None): + site = self._reflect_position(site) + self.insert_sites.append((site, symbol)) + + def add_deletion(self, site: int, symbol): + site = self._reflect_position(site) + self.deleteion_sites.append((site, symbol)) + + def __repr__(self): + return f""{self.__class__.__name__}({self.peptide_sequence}, {self.glycosite_candidates})"" + + +class ReversePeptideIdentification(ReverseMzIdentMLPeptide, _EvidenceMixin): + pass + + +class ReversePeptideConverter(PeptideConverter): + def _get_evidence_list(self, peptide_dict: Dict[str, Any]) -> List[Dict[str, Any]]: + evidence_list = peptide_dict[""PeptideEvidenceRef""] + # Flatten the evidence list if it has extra nesting because of alternative + # mzid parsing + if isinstance(evidence_list[0], list): + evidence_list = [x for sub in evidence_list for x in sub] + return evidence_list + + def __init__(self, session, hypothesis_id, enzyme=None, constant_modifications=None, + modification_translation_table=None, protein_filter=None, + peptide_length_range=(5, 60), + include_cysteine_n_glycosylation: bool = False, + protein_alias_map: Optional[Dict[str, str]]=None): + super().__init__( + session, hypothesis_id, enzyme=enzyme, constant_modifications=constant_modifications, + modification_translation_table=modification_translation_table, protein_filter=protein_filter, + peptide_length_range=peptide_length_range, + include_cysteine_n_glycosylation=include_cysteine_n_glycosylation, + protein_alias_map=protein_alias_map + ) + + def handle_peptide_dict(self, peptide_dict: Dict[str, Any]): + evidence_list = self._get_evidence_list(peptide_dict) + for evidence in evidence_list: + if ""skip"" in evidence: + continue + if evidence.get(""isDecoy"", False): + continue + + parent_protein = self.get_protein(evidence) + if parent_protein is None: + continue + + peptide_ident = ReversePeptideIdentification( + peptide_dict, + parent_protein, + self.enzyme, + self.constant_modifications, + self.modification_translation_table + ) + + score, score_type = peptide_ident.score_type + + start = evidence[""start""] - 1 + end = evidence[""end""] + length = len(peptide_ident.base_sequence) + if not (self.peptide_length_range[0] <= length <= self.peptide_length_range[1]): + continue + + sequence_copy = peptide_ident.original_sequence() + found = self.sequence_starts_at(sequence_copy, parent_protein) + + if found != start: + start = found + end = start + length + + match = self.pack_peptide( + peptide_ident, start, end, score, score_type, parent_protein) + self.add_to_group(match) + if self.has_occupied_glycosites(match): + cleared = self.clear_sites(match) + self.add_to_group(cleared) + + +class ReverseProteome(Proteome, ProteinReversingMixin): + def _make_protein_from_state(self, name: str, seq: str, state: dict): + p = super()._make_protein_from_state(name, seq, state) + p.sites = [] + self.reverse_protein(p) + return p + + def _make_peptide_converter(self, session, protein_filter: Set[int], enzyme: Protease, **kwargs): + return ReversePeptideConverter( + session, + self.hypothesis_id, + enzyme=enzyme, + constant_modifications=self.constant_modifications, + modification_translation_table=self.modification_translation_table, + protein_filter=protein_filter, + protein_alias_map=self.accession_map, **kwargs) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycopeptide/proteomics/proteome.py",".py","2098","53","from glycresoft.serialize import ( + Peptide, Protein, DatabaseBoundOperation) + +from .remove_duplicate_peptides import DeduplicatePeptides + + +class ProteomeBase(DatabaseBoundOperation): + def __init__(self, connection, hypothesis_id, target_proteins=None, + constant_modifications=None, variable_modifications=None): + if constant_modifications is None: + constant_modifications = [] + if variable_modifications is None: + variable_modifications = [] + DatabaseBoundOperation.__init__(self, connection) + self.hypothesis_id = hypothesis_id + self.target_proteins = target_proteins + self.constant_modifications = constant_modifications + self.variable_modifications = variable_modifications + + def retrieve_target_protein_ids(self): + if len(self.target_proteins) == 0: + return [ + i[0] for i in + self.query(Protein.id).filter( + Protein.hypothesis_id == self.hypothesis_id).all() + ] + else: + result = [] + for target in self.target_proteins: + if isinstance(target, str): + match = self.query(Protein.id).filter( + Protein.name == target, + Protein.hypothesis_id == self.hypothesis_id).first() + if match: + result.append(match[0]) + else: + self.log(""Could not locate protein '%s'"" % target) + elif isinstance(target, int): + result.append(target) + return result + + def get_target_proteins(self): + ids = self.retrieve_target_protein_ids() + return [self.session.query(Protein).get(i) for i in ids] + + def count_peptides(self): + peptide_count = self.session.query(Peptide).filter( + Peptide.hypothesis_id == self.hypothesis_id).count() + return peptide_count + + def remove_duplicates(self): + DeduplicatePeptides(self._original_connection, self.hypothesis_id).run() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycan/synthesis.py",".py","15599","392","from collections import defaultdict + +from glypy.io import iupac, glycoct +from glypy.structure.glycan_composition import HashableGlycanComposition, FrozenGlycanComposition +from glypy.enzyme import ( + make_n_glycan_pathway, make_mucin_type_o_glycan_pathway, + MultiprocessingGlycome, Glycosylase, Glycosyltransferase, + EnzymeGraph, GlycanCompositionEnzymeGraph, _enzyme_graph_inner) + +from glycresoft.task import TaskBase, log_handle + +from glycresoft.database.builder.glycan.glycan_source import ( + GlycanHypothesisSerializerBase, GlycanTransformer, + DBGlycanComposition, formula, GlycanCompositionToClass, + GlycanTypes) + +from glycresoft.structure import KeyTransformingDecoratorDict + + +def key_transform(name): + return str(name).lower().replace("" "", '-') + + +synthesis_register = KeyTransformingDecoratorDict(key_transform) + + +class MultiprocessingGlycomeTask(MultiprocessingGlycome, TaskBase): + def _log(self, message): + log_handle.log(message) + + def log_generation_chunk(self, i, chunks, current_generation): + self._log("".... Task %d/%d finished (%d items generated)"" % ( + i, len(chunks), len(current_generation))) + + +class GlycanSynthesis(TaskBase): + glycan_classification = None + + def __init__(self, glycosylases=None, glycosyltransferases=None, seeds=None, limits=None, + convert_to_composition=True, n_processes=5): + self.glycosylases = glycosylases or {} + self.glycosyltransferases = glycosyltransferases or {} + self.seeds = seeds or [] + self.limits = limits or [] + self.convert_to_composition = convert_to_composition + self.n_processes = n_processes + + def remove_enzyme(self, enzyme_name): + if enzyme_name in self.glycosylases: + return self.glycosylases.pop(enzyme_name) + elif enzyme_name in self.glycosyltransferases: + return self.glycosyltransferases.pop(enzyme_name) + else: + raise KeyError(enzyme_name) + + def add_enzyme(self, enzyme_name, enzyme): + if isinstance(enzyme, Glycosylase): + self.glycosylases[enzyme_name] = enzyme + elif isinstance(enzyme, Glycosyltransferase): + self.glycosyltransferases[enzyme_name] = enzyme + else: + raise TypeError(""Don't know where to put object of type %r"" % type(enzyme)) + + def add_limit(self, limit): + self.limits.append(limit) + + def add_seed(self, structure): + if structure in self.seeds: + return + self.seeds.append(structure) + + def build_glycome(self): + glycome = MultiprocessingGlycomeTask( + self.glycosylases, self.glycosyltransferases, + self.seeds, track_generations=False, + limits=self.limits, processes=self.n_processes) + return glycome + + def convert_enzyme_graph_composition(self, glycome): + self.log(""Converting Enzyme Graph into Glycan Set"") + glycans = set() + glycans.update(glycome.enzyme_graph) + for i, v in enumerate(glycome.enzyme_graph.values()): + if i and i % 100000 == 0: + self.log("".... %d Glycans In Set"" % (len(glycans))) + glycans.update(v) + self.log("".... %d Glycans In Set"" % (len(glycans))) + + composition_graph = defaultdict(_enzyme_graph_inner) + compositions = set() + + cache = StructureConverter() + + i = 0 + for s in glycans: + i += 1 + gc = cache[s] + for child, enz in glycome.enzyme_graph[s].items(): + composition_graph[gc][cache[child]].update(enz) + if i % 1000 == 0: + self.log("".... Converted %d Compositions (%d/%d Structures, %0.2f%%)"" % ( + len(compositions), i, len(glycans), float(i) / len(glycans) * 100.0)) + compositions.add(gc) + return compositions, composition_graph + + def extract_structures(self, glycome): + self.log(""Converting Enzyme Graph into Glycan Set"") + solutions = list() + for i, structure in enumerate(glycome.seen): + if i and i % 10000 == 0: + self.log("".... %d Glycans Extracted"" % (i,)) + solutions.append(structure) + return solutions, glycome.enzyme_graph + + def run(self): + logger = self.ipc_logger() + glycome = self.build_glycome() + old_logger = glycome._log + glycome._log = logger.handler + for i, gen in enumerate(glycome.run()): + self.log("".... Generation %d: %d Structures"" % (i, len(gen))) + self.glycome = glycome + logger.stop() + glycome._log = old_logger + if self.convert_to_composition: + compositions, composition_enzyme_graph = self.convert_enzyme_graph_composition(glycome) + return compositions, composition_enzyme_graph + else: + structures, enzyme_graph = self.extract_structures(glycome) + return structures, enzyme_graph + + +class Limiter(object): + def __init__(self, max_nodes=26, max_mass=5500.0): + self.max_mass = max_mass + self.max_nodes = max_nodes + + def __call__(self, x): + return len(x) < self.max_nodes and x.mass() < self.max_mass + + +GlycanSynthesis.size_limiter_type = Limiter + + +@synthesis_register(""n-glycan"") +@synthesis_register(""mammalian-n-glycan"") +class NGlycanSynthesis(GlycanSynthesis): + + glycan_classification = GlycanTypes.n_glycan + + def _get_initial_components(self): + glycosidases, glycosyltransferases, seeds = make_n_glycan_pathway() + glycosyltransferases.pop('siat2_3') + + child = iupac.loads(""a-D-Neup5Gc"") + parent = iupac.loads(""b-D-Galp-(1-4)-b-D-Glcp2NAc"") + siagct2_6 = Glycosyltransferase(6, 2, parent, child, parent_node_id=3) + + glycosyltransferases['siagct2_6'] = siagct2_6 + return glycosidases, glycosyltransferases, seeds + + def __init__(self, glycosylases=None, glycosyltransferases=None, seeds=None, limits=None, + convert_to_composition=True, n_processes=5): + sylases, transferases, more_seeds = self._get_initial_components() + sylases.update(glycosylases or {}) + transferases.update(glycosyltransferases or {}) + more_seeds.extend(seeds or []) + super(NGlycanSynthesis, self).__init__(sylases, transferases, more_seeds, + limits, convert_to_composition, n_processes) + + +@synthesis_register(""human-n-glycan"") +class HumanNGlycanSynthesis(NGlycanSynthesis): + def _get_initial_components(self): + glycosidases, glycosyltransferases, seeds = super( + HumanNGlycanSynthesis, self)._get_initial_components() + glycosyltransferases.pop('siagct2_6') + glycosyltransferases.pop('agal13galt') + glycosyltransferases.pop('gntE') + return glycosidases, glycosyltransferases, seeds + + +@synthesis_register(""mucin-o-glycan"") +@synthesis_register(""mammalian-mucin-o-glycan"") +class MucinOGlycanSynthesis(GlycanSynthesis): + + glycan_classification = GlycanTypes.o_glycan + + def _get_initial_components(self): + glycosidases, glycosyltransferases, seeds = make_mucin_type_o_glycan_pathway() + parent = iupac.loads(""a-D-Galp2NAc"") + child = iupac.loads(""a-D-Neup5Gc"") + sgt6gal1 = Glycosyltransferase(6, 2, parent, child, terminal=False) + glycosyltransferases['sgt6gal1'] = sgt6gal1 + + parent = iupac.loads(""b-D-Galp-(1-3)-a-D-Galp2NAc"") + child = iupac.loads(""a-D-Neup5Gc"") + sgt3gal2 = Glycosyltransferase(3, 2, parent, child, parent_node_id=3) + glycosyltransferases['sgt3gal2'] = sgt3gal2 + + parent = iupac.loads(""b-D-Galp-(1-3)-a-D-Galp2NAc"") + child = iupac.loads(""a-D-Neup5Gc"") + sgt6gal2 = Glycosyltransferase(6, 2, parent, child, parent_node_id=3) + glycosyltransferases['sgt6gal2'] = sgt6gal2 + return glycosidases, glycosyltransferases, seeds + + def __init__(self, glycosylases=None, glycosyltransferases=None, seeds=None, limits=None, + convert_to_composition=True, n_processes=5): + sylases, transferases, more_seeds = self._get_initial_components() + sylases.update(glycosylases or {}) + transferases.update(glycosyltransferases or {}) + more_seeds.extend(seeds or []) + super(MucinOGlycanSynthesis, self).__init__(sylases, transferases, more_seeds, + limits, convert_to_composition, n_processes) + + +@synthesis_register(""human-mucin-o-glycan"") +class HumanMucinOGlycanSynthesis(MucinOGlycanSynthesis): + def _get_initial_components(self): + glycosidases, glycosyltransferases, seeds = super(HumanMucinOGlycanSynthesis)._get_initial_components() + glycosyltransferases.pop(""sgt6gal1"") + glycosyltransferases.pop(""sgt3gal2"") + glycosyltransferases.pop(""sgt6gal2"") + return glycosidases, glycosyltransferases, seeds + + +class StructureConverter(object): + def __init__(self): + self.cache = dict() + + def convert(self, structure_text): + if structure_text in self.cache: + return self.cache[structure_text] + structure = glycoct.loads(structure_text) + gc = HashableGlycanComposition.from_glycan(structure).thaw() + gc.drop_stems() + gc.drop_configurations() + gc.drop_positions() + gc = HashableGlycanComposition(gc) + self.cache[structure_text] = gc + return gc + + def __getitem__(self, structure_text): + return self.convert(structure_text) + + def __repr__(self): + return ""%s(%d)"" % (self.__class__.__name__, len(self.cache)) + + +class AdaptExistingGlycanGraph(TaskBase): + def __init__(self, graph, enzymes_to_remove): + self.graph = graph + self.enzymes_to_remove = set(enzymes_to_remove) + self.enzymes_available = set(self.graph.enzymes()) + if (self.enzymes_to_remove - self.enzymes_available): + raise ValueError(""Required enzymes %r not found"" % ( + self.enzymes_to_remove - self.enzymes_available,)) + + def remove_enzymes(self): + enz_to_remove = self.enzymes_to_remove + for enz in enz_to_remove: + self.log("".... Removing Enzyme %s"" % (enz,)) + self.graph.remove_enzyme(enz) + for entity in (self.graph.parentless() - self.graph.seeds): + self.graph.remove(entity) + + def run(self): + self.log(""Adapting Enzyme Graph with %d nodes and %d edges"" % ( + self.graph.node_count(), self.graph.edge_count())) + self.remove_enzymes() + self.log(""After Adaption, Graph has %d nodes and %d edges"" % ( + self.graph.node_count(), self.graph.edge_count())) + + +class ExistingGraphGlycanHypothesisSerializer(GlycanHypothesisSerializerBase): + def __init__(self, enzyme_graph, database_connection, enzymes_to_remove=None, reduction=None, + derivatization=None, hypothesis_name=None, glycan_classification=None): + if enzymes_to_remove is None: + enzymes_to_remove = set() + + GlycanHypothesisSerializerBase.__init__(self, database_connection, hypothesis_name) + + self.enzyme_graph = enzyme_graph + self.enzymes_to_remove = set(enzymes_to_remove) + self.glycan_classification = glycan_classification + + self.reduction = reduction + self.derivatization = derivatization + + self.loader = None + self.transformer = None + + def build_glycan_compositions(self): + adapter = AdaptExistingGlycanGraph(self.enzyme_graph, self.enzymes_to_remove) + adapter.start() + components = adapter.graph.nodes() + for component in components: + if isinstance(component, FrozenGlycanComposition): + component = component.thaw() + yield component, [self.glycan_classification] + + def make_pipeline(self): + self.loader = self.build_glycan_compositions() + self.transformer = GlycanTransformer(self.loader, self.reduction, self.derivatization) + + def run(self): + self.make_pipeline() + structure_class_lookup = self.structure_class_loader + + acc = [] + counter = 0 + for composition, structure_classes in self.transformer: + mass = composition.mass() + composition_string = composition.serialize() + formula_string = formula(composition.total_composition()) + inst = DBGlycanComposition( + calculated_mass=mass, formula=formula_string, + composition=composition_string, + hypothesis_id=self.hypothesis_id) + self.session.add(inst) + self.session.flush() + counter += 1 + for structure_class in structure_classes: + structure_class = structure_class_lookup[structure_class] + acc.append(dict(glycan_id=inst.id, class_id=structure_class.id)) + if len(acc) % 100 == 0: + self.session.execute(GlycanCompositionToClass.insert(), acc) + acc = [] + if acc: + self.session.execute(GlycanCompositionToClass.insert(), acc) + acc = [] + self.session.commit() + self.log(""Generated %d glycan compositions"" % counter) + + +class SynthesisGlycanHypothesisSerializer(GlycanHypothesisSerializerBase): + def __init__(self, glycome, database_connection, reduction=None, + derivatization=None, hypothesis_name=None, glycan_classification=None): + if glycan_classification is None: + glycan_classification = glycome.glycan_classification + + GlycanHypothesisSerializerBase.__init__(self, database_connection, hypothesis_name) + + self.glycome = glycome + self.glycan_classification = glycan_classification + + self.reduction = reduction + self.derivatization = derivatization + + self.loader = None + self.transformer = None + + def build_glycan_compositions(self): + components, enzyme_graph = self.glycome.start() + for component in components: + yield component, [self.glycan_classification] + + def make_pipeline(self): + self.loader = self.build_glycan_compositions() + self.transformer = GlycanTransformer(self.loader, self.reduction, self.derivatization) + + def run(self): + self.make_pipeline() + structure_class_lookup = self.structure_class_loader + + acc = [] + counter = 0 + for composition, structure_classes in self.transformer: + mass = composition.mass() + composition_string = composition.serialize() + formula_string = formula(composition.total_composition()) + inst = DBGlycanComposition( + calculated_mass=mass, formula=formula_string, + composition=composition_string, + hypothesis_id=self.hypothesis_id) + if (counter + 1) % 100 == 0: + self.log(""Stored %d glycan compositions"" % counter) + self.session.add(inst) + self.session.flush() + counter += 1 + for structure_class in structure_classes: + structure_class = structure_class_lookup[structure_class] + acc.append(dict(glycan_id=inst.id, class_id=structure_class.id)) + if len(acc) % 100 == 0: + self.session.execute(GlycanCompositionToClass.insert(), acc) + acc = [] + if acc: + self.session.execute(GlycanCompositionToClass.insert(), acc) + acc = [] + self.session.commit() + self.log(""Stored %d glycan compositions"" % counter) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycan/glycosaminoglycan_linker_generation.py",".py","2830","113","from glypy import monosaccharides, GlycanComposition +from glypy.structure import ( + Modification, Glycan, Substituent) + + +def gag_linkers(): + xyl = monosaccharides.Xyl + gal = monosaccharides.Gal + xyl.add_monosaccharide(gal, 4, child_position=1) + gal2 = monosaccharides.Gal + gal.add_monosaccharide(gal2, 3, child_position=1) + hexa = monosaccharides.Hex + hexa.add_modification(Modification.Acidic, 6) + gal2.add_monosaccharide(hexa, 3, child_position=1) + hexnac = monosaccharides.HexNAc + hexa.add_monosaccharide(hexnac, 3, child_position=1) + enhexa = monosaccharides.Hex + enhexa.add_modification(Modification.Acidic, 6) + enhexa.add_modification(Modification.en, 2) + hexnac.add_monosaccharide(enhexa, 3, child_position=1) + base_linker = Glycan(xyl).reindex() + + variants = [{""substituents"": { + 5: ""sulfate"" + }}, { + ""monosaccharides"": { + 2: ""Fuc"" + } + }, { + ""monosaccharides"": { + 2: ""Fuc"" + }, + ""substituents"": { + 5: ""sulfate"" + } + }, { + ""monosaccharides"": { + 2: ""Fuc"" + }, + ""substituents"": { + 5: ""sulfate"", + 3: ""sulfate"" + } + }, { + ""substituents"": { + 1: ""phosphate"" + } + }, { + ""substituents"": { + 1: ""phosphate"", + 5: ""sulfate"" + } + }, { + ""substituents"": { + 1: ""phosphate"", + 3: ""sulfate"", + 5: ""sulfate"" + } + }, { + ""substituents"": { + 5: ""sulfate"" + } + }, { + ""substituents"": { + 3: ""sulfate"", + 5: ""sulfate"" + } + }, { + ""monosaccharides"": { + 2: ""NeuAc"" + } + }, { + ""monosaccharides"": { + 2: ""NeuAc"" + }, + ""substituents"": { + 5: ""sulfate"" + } + }, { + ""monosaccharides"": { + 2: ""NeuAc"" + }, + ""substituents"": { + 5: ""sulfate"", + 3: ""sulfate"" + } + }] + + linker_variants = [base_linker] + + for variant in variants: + linker = base_linker.clone() + + substituent_variant = variant.get(""substituents"", {}) + for position, subst in substituent_variant.items(): + parent = linker.get(position) + parent.add_substituent(Substituent(subst)) + + monosacch_variant = variant.get(""monosaccharides"", {}) + for position, mono in monosacch_variant.items(): + parent = linker.get(position) + child = monosaccharides[mono] + parent.add_monosaccharide(child, -1) + + linker.reindex() + linker_variants.append(linker) + + return linker_variants + + +def gag_linker_compositions(): + return [GlycanComposition.from_glycan(linker) for linker in gag_linkers()] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycan/glycan_permutations.py",".py","8909","247","from collections import defaultdict, Counter +import itertools + +from six import string_types as basestring + +import glypy +from glypy.structure.glycan_composition import FrozenGlycanComposition +from glypy.composition import formula +from glypy import ReducedEnd + +from .glycan_source import GlycanHypothesisSerializerBase +from glycresoft.serialize import ( + DatabaseBoundOperation, + GlycanComposition as DBGlycanComposition, + GlycanCompositionToClass) + + +def get_glycan_composition(glycan_composition): + try: + return glycan_composition.convert() + except AttributeError: + return glycan_composition + + +def linearize_composition(glycan_composition): + return [mr for mr, count in glycan_composition.items() for i in range(count)] + + +INF = float('inf') + + +class GlycanCompositionTransformerRule(object): + def __init__(self, modifier, constraints): + self.modifier = modifier + self.constraints = constraints + + def __repr__(self): + return ""%s(%r, %r)"" % ( + self.__class__.__name__, + self.modifier, self.constraints) + + def test(self, glycan_composition): + return self.constraints(glycan_composition) + + def apply(self, glycan_composition, i): + glycan_composition[self.modifier] = i + return glycan_composition + + def __eq__(self, other): + return self.modifier == other.modifier and self.constraints == other.constraints + + def __hash__(self): + return hash(self.modifier) + + +class SiteSpecificGlycanCompositionTransformerRule(object): + def __init__(self, target, modifier): + self.target = target + self.modifier = modifier + + def find_valid_sites(self, linear): + return [i for i, mr in enumerate(linear) if mr == self.target] + + def __repr__(self): + return ""%s(%r, %r)"" % ( + self.__class__.__name__, + self.target, self.modifier) + + def apply(self, glycan_composition, i): + glycan_composition[self.modifier] = i + return glycan_composition + + def __eq__(self, other): + return self.target == other.target and self.modifier == other.modifier + + def __hash__(self): + return hash(self.target) + + +class GlycanReductionTransformerRule(object): + def __init__(self, reduction): + if isinstance(reduction, ReducedEnd): + reduction = reduction.clone() + elif isinstance(reduction, glypy.Composition): + reduction = ReducedEnd(reduction.clone()) + elif isinstance(reduction, basestring): + reduction = ReducedEnd(glypy.Composition(reduction)) + self.reduction = reduction + + def apply(self, glycan_composition): + glycan_composition.reducing_end = self.reduction.clone() + return glycan_composition + + +def split_reduction_and_modification_rules(rule_list): + modification_rules = [] + reduction_rules = [] + for rule in rule_list: + if isinstance(rule, GlycanReductionTransformerRule): + reduction_rules.append(rule) + else: + modification_rules.append(rule) + return modification_rules, reduction_rules + + +def modification_series(variable_sites): + """"""Given a dictionary mapping between modification names and + an iterable of valid sites, create a dictionary mapping between + modification names and a list of valid sites plus the constant `None` + + Parameters + ---------- + variable_sites : dict + Description + + Returns + ------- + dict + Description + """""" + sites = defaultdict(list) + for mod, varsites in variable_sites.items(): + for site in varsites: + sites[site].append(mod) + for site in list(sites): + sites[site].append(None) + return sites + + +def site_modification_assigner(modification_sites_dict): + sites = modification_sites_dict.keys() + choices = modification_sites_dict.values() + for selected in itertools.product(*choices): + yield zip(sites, selected) + + +def simplify_assignments(assignments_generator): + distinct = set() + for assignments in assignments_generator: + distinct.add(frozenset(Counter(mod for site, mod in assignments if mod is not None).items())) + return distinct + + +def glycan_composition_permutations(glycan_composition, constant_modifications=None, variable_modifications=None): + if constant_modifications is None: + constant_modifications = [] + if variable_modifications is None: + variable_modifications = [] + + glycan_composition = FrozenGlycanComposition( + get_glycan_composition(glycan_composition)) + final_composition = FrozenGlycanComposition() + temporary_composition = FrozenGlycanComposition() + sequence = linearize_composition(glycan_composition) + + if not constant_modifications: + temporary_composition = glycan_composition.clone() + has_constant_reduction = False + else: + constant_modifications, constant_reduction = split_reduction_and_modification_rules( + constant_modifications) + for rule in constant_modifications: + extracted = rule.find_valid_sites(sequence) + for i, mr in enumerate(sequence): + if i in extracted: + final_composition[mr] += 1 + final_composition[rule.modifier] += 1 + else: + temporary_composition[mr] += 1 + sequence = linearize_composition(temporary_composition) + if constant_reduction: + has_constant_reduction = True + constant_reduction[0].apply(temporary_composition) + + variable_modifications, variable_reduction = split_reduction_and_modification_rules( + variable_modifications) + + mod_site_map = { + rule: rule.find_valid_sites(sequence) for rule in variable_modifications + } + assignments_generator = site_modification_assigner( + modification_series(mod_site_map)) + for assignments in simplify_assignments(assignments_generator): + result = temporary_composition.clone() + for mod, count in assignments: + mod.apply(result, count) + result += final_composition + if glycan_composition.reducing_end is not None: + result.reducing_end = glycan_composition.reducing_end.clone() + yield result + if not has_constant_reduction: + for rule in variable_reduction: + yield rule.apply(result.clone()) + + +class GlycanCompositionPermutationHypothesisSerializer(GlycanHypothesisSerializerBase): + def __init__(self, source_hypothesis_id, database_connection, constant_modifications=None, + variable_modifications=None, hypothesis_name=None): + super(GlycanCompositionPermutationHypothesisSerializer, self).__init__(database_connection, hypothesis_name) + self.source_hypothesis_id = source_hypothesis_id + self.constant_modifications = constant_modifications + self.variable_modifications = variable_modifications + + self.loader = None + self.transformer = None + + def make_pipeline(self): + self.loader = iter(DatabaseBoundOperation( + self._original_connection).query( + DBGlycanComposition).filter( + DBGlycanComposition.hypothesis_id == self.source_hypothesis_id).all()) + self.transformer = self.permuter(self.loader) + + def permuter(self, source_iterator): + for glycan_composition in source_iterator: + structure_classes = [sc.name for sc in glycan_composition.structure_classes] + for permutation in glycan_composition_permutations( + glycan_composition, self.constant_modifications, self.variable_modifications): + yield permutation, structure_classes + + def run(self): + self.make_pipeline() + structure_class_lookup = self.structure_class_loader + self.log(""Loading Glycan Compositions from Stream for %r"" % self.hypothesis) + + acc = [] + for composition, structure_classes in self.transformer: + mass = composition.mass() + composition_string = composition.serialize() + formula_string = formula(composition.total_composition()) + inst = DBGlycanComposition( + calculated_mass=mass, formula=formula_string, + composition=composition_string, + hypothesis_id=self.hypothesis_id) + self.session.add(inst) + self.session.flush() + for structure_class in structure_classes: + structure_class = structure_class_lookup[structure_class] + acc.append(dict(glycan_id=inst.id, class_id=structure_class.id)) + if len(acc) % 100 == 0: + self.session.execute(GlycanCompositionToClass.insert(), acc) + acc = [] + if acc: + self.session.execute(GlycanCompositionToClass.insert(), acc) + acc = [] + self.session.commit() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycan/convert_analysis.py",".py","4519","95","from glycresoft.serialize.hypothesis import GlycanHypothesis +from glycresoft.serialize.hypothesis.glycan import ( + GlycanComposition as DBGlycanComposition, + GlycanCombination, GlycanCombinationGlycanComposition) +from glycresoft.serialize import ( + DatabaseBoundOperation, Analysis, GlycanCompositionChromatogram, + IdentifiedGlycopeptide, Glycopeptide) + +from .glycan_source import ( + GlycanHypothesisSerializerBase, formula, GlycanCompositionToClass) + +from glypy import GlycanComposition + + +class GlycanAnalysisHypothesisSerializer(GlycanHypothesisSerializerBase): + def __init__(self, input_connection, analysis_id, hypothesis_name, output_connection=None): + if output_connection is None: + output_connection = input_connection + self.input_connection = DatabaseBoundOperation(input_connection) + self.output_connection = DatabaseBoundOperation(output_connection) + GlycanHypothesisSerializerBase.__init__(self, output_connection, hypothesis_name) + self.analysis_id = analysis_id + self.seen_cache = set() + + def extract_composition(self, glycan_chromatogram): + composition = GlycanComposition.parse(glycan_chromatogram.glycan_composition.serialize()) + if str(composition) in self.seen_cache: + return + self.seen_cache.add(str(composition)) + mass = composition.mass() + composition_string = composition.serialize() + formula_string = formula(composition.total_composition()) + inst = DBGlycanComposition( + calculated_mass=mass, formula=formula_string, + composition=composition_string, + hypothesis_id=self.hypothesis_id) + + self.output_connection.session.add(inst) + self.output_connection.session.flush() + db_obj = self.input_connection.query(DBGlycanComposition).get(glycan_chromatogram.composition.id) + for sc in db_obj.structure_classes: + self.output_connection.session.execute( + GlycanCompositionToClass.insert(), dict(glycan_id=inst.id, class_id=sc.id)) + self.output_connection.session.flush() + + def run(self): + q = self.input_connection.session.query(GlycanCompositionChromatogram).filter( + GlycanCompositionChromatogram.analysis_id == self.analysis_id) + for gc in q: + self.extract_composition(gc) + self.output_connection.session.commit() + + +class GlycopeptideAnalysisGlycanCompositionExtractionHypothesisSerializer(GlycanHypothesisSerializerBase): + def __init__(self, input_connection, analysis_id, hypothesis_name, output_connection=None): + if output_connection is None: + output_connection = input_connection + self.input_connection = DatabaseBoundOperation(input_connection) + self.output_connection = DatabaseBoundOperation(output_connection) + GlycanHypothesisSerializerBase.__init__(self, output_connection, hypothesis_name) + self.analysis_id = analysis_id + self.seen_cache = set() + + def get_all_compositions(self): + return self.input_connection.query(DBGlycanComposition).join(GlycanCombinationGlycanComposition).join( + Glycopeptide, + GlycanCombinationGlycanComposition.c.combination_id == Glycopeptide.glycan_combination_id).join( + IdentifiedGlycopeptide, IdentifiedGlycopeptide.structure_id == Glycopeptide.id).filter( + IdentifiedGlycopeptide.analysis_id == self.analysis_id) + + def extract_composition(self, db_obj): + composition = GlycanComposition.parse(db_obj.composition) + if str(composition) in self.seen_cache: + return + self.seen_cache.add(str(composition)) + mass = composition.mass() + composition_string = composition.serialize() + formula_string = formula(composition.total_composition()) + inst = DBGlycanComposition( + calculated_mass=mass, formula=formula_string, + composition=composition_string, + hypothesis_id=self.hypothesis_id) + self.output_connection.session.add(inst) + self.output_connection.session.flush() + for sc in db_obj.structure_classes: + self.output_connection.session.execute( + GlycanCompositionToClass.insert(), dict(glycan_id=inst.id, class_id=sc.id)) + self.output_connection.session.flush() + + def run(self): + q = self.get_all_compositions() + for gc in q: + self.extract_composition(gc) + self.output_connection.session.commit() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycan/__init__.py",".py","870","21","from .glycan_source import ( + TextFileGlycanHypothesisSerializer, GlycanTransformer, + TextFileGlycanCompositionLoader, + GlycanCompositionHypothesisMerger, + GlycanTypes, + named_reductions, + named_derivatizations) +from .constrained_combinatorics import ( + CombinatorialGlycanHypothesisSerializer, CombinatoricCompositionGenerator) +from .glycan_combinator import ( + GlycanCombinationSerializer, GlycanCombinationBuilder) +from .glyspace import ( + NGlycanGlyspaceHypothesisSerializer, OGlycanGlyspaceHypothesisSerializer, + TaxonomyFilter) +from .synthesis import ( + SynthesisGlycanHypothesisSerializer, ExistingGraphGlycanHypothesisSerializer, + GlycanCompositionEnzymeGraph, synthesis_register) +from .convert_analysis import ( + GlycanAnalysisHypothesisSerializer, + GlycopeptideAnalysisGlycanCompositionExtractionHypothesisSerializer) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycan/constrained_combinatorics.py",".py","10621","328","import re +from itertools import product +from collections import deque + +from glypy import GlycanComposition as MemoryGlycanComposition +from glypy.structure.glycan_composition import FrozenMonosaccharideResidue +from glypy.io.iupac import IUPACError +from glycresoft.serialize.hypothesis.glycan import GlycanComposition as DBGlycanComposition + +from glypy.composition import formula + +from .glycan_source import ( + GlycanTransformer, GlycanHypothesisSerializerBase, GlycanCompositionToClass, GlycanTypes, normalize_lookup) +from glycresoft.symbolic_expression import ( + ConstraintExpression, SymbolContext, SymbolNode, ExpressionNode, + ensuretext) + + +def descending_combination_counter(counter): + keys = counter.keys() + count_ranges = map(lambda lo_hi: range( + lo_hi[0], lo_hi[1] + 1), counter.values()) + for combination in product(*count_ranges): + yield dict(zip(keys, combination)) + + +def normalize_iupac_lite(string): + return str(FrozenMonosaccharideResidue.from_iupac_lite(string)) + + +class CombinatoricCompositionGenerator(object): + """""" + Summary + + Attributes + ---------- + constraints : list + Description + lower_bound : list + Description + residue_list : list + Description + rules_table : dict + Description + upper_bound : list + Description + """""" + @staticmethod + def build_rules_table(residue_list, lower_bound, upper_bound): + rules_table = {} + for i, residue in enumerate(residue_list): + lower = lower_bound[i] + upper = upper_bound[i] + rules_table[residue] = (lower, upper) + return rules_table + + def __init__(self, residue_list=None, lower_bound=None, upper_bound=None, constraints=None, rules_table=None, + structure_classifiers=None): + if structure_classifiers is None: + structure_classifiers = {GlycanTypes.n_glycan: is_n_glycan_classifier} + self.residue_list = list(map(normalize_iupac_lite, (residue_list or []))) + self.lower_bound = lower_bound or [] + self.upper_bound = upper_bound or [] + self.constraints = constraints or [] + self.rules_table = rules_table + self.structure_classifiers = structure_classifiers + + if len(self.constraints) > 0 and not isinstance(self.constraints[0], ConstraintExpression): + self.constraints = list( + map(ConstraintExpression.from_list, self.constraints)) + + if rules_table is None: + self._build_rules_table() + + self.normalize_rules_table() + for constraint in self.constraints: + self.normalize_symbols(constraint.expression) + + self._iter = None + + def normalize_rules_table(self): + rules_table = {} + for key, bounds in self.rules_table.items(): + rules_table[normalize_iupac_lite(key)] = bounds + self.rules_table = rules_table + + def normalize_symbols(self, expression): + symbols = list(expression.itersymbols()) + for node in symbols: + node.symbol = normalize_iupac_lite(node.symbol) + + def _build_rules_table(self): + rules_table = {} + for i, residue in enumerate(self.residue_list): + lower = self.lower_bound[i] + upper = self.upper_bound[i] + rules_table[residue] = (lower, upper) + self.rules_table = rules_table + return rules_table + + def generate(self): + for combin in descending_combination_counter(self.rules_table): + passed = True + combin = SymbolContext(combin) + structure_classes = [] + if sum(combin.values()) == 0: + continue + for constraint in self.constraints: + if not constraint(combin): + passed = False + break + if passed: + for name, classifier in self.structure_classifiers.items(): + if classifier(combin): + structure_classes.append(name) + try: + yield MemoryGlycanComposition(**combin.context), structure_classes + except IUPACError: + raise + + __iter__ = generate + + def __next__(self): + if self._iter is None: + self._iter = self.generate() + return next(self._iter) + + next = __next__ + + def __repr__(self): + return ""CombinatoricCompositionGenerator\n"" + repr(self.rules_table) + '\n' + repr(self.constraints) + + +class CombinatorialGlycanHypothesisSerializer(GlycanHypothesisSerializerBase): + def __init__(self, glycan_text_file, database_connection, reduction=None, derivatization=None, + hypothesis_name=None, glycan_type=None): + GlycanHypothesisSerializerBase.__init__(self, database_connection, hypothesis_name) + + self.glycan_file = glycan_text_file + self.glycan_type = glycan_type + self.reduction = reduction + self.derivatization = derivatization + + self.loader = None + self.transformer = None + + def make_pipeline(self): + rules, constraints = parse_rules_from_file(self.glycan_file) + classifiers = None + if self.glycan_type: + classifiers = {normalize_lookup(self.glycan_type): lambda x: True} + self.loader = CombinatoricCompositionGenerator( + rules_table=rules, constraints=constraints, structure_classifiers=classifiers) + self.transformer = GlycanTransformer(self.loader, self.reduction, self.derivatization) + + def run(self): + self.make_pipeline() + structure_class_lookup = self.structure_class_loader + acc = [] + self.log(""Generating Glycan Compositions from Symbolic Rules for %r"" % self.hypothesis) + counter = 0 + for composition, structure_classes in self.transformer: + mass = composition.mass() + composition_string = composition.serialize() + formula_string = formula(composition.total_composition()) + inst = DBGlycanComposition( + calculated_mass=mass, formula=formula_string, + composition=composition_string, + hypothesis_id=self.hypothesis_id) + counter += 1 + self.session.add(inst) + self.session.flush() + for structure_class in structure_classes: + structure_class = structure_class_lookup[structure_class] + acc.append(dict(glycan_id=inst.id, class_id=structure_class.id)) + if len(acc) % 100 == 0: + self.session.execute(GlycanCompositionToClass.insert(), acc) + acc = [] + if counter % 1000 == 0: + self.log(""%d glycan compositions created"" % (counter,)) + if acc: + self.session.execute(GlycanCompositionToClass.insert(), acc) + acc = [] + self.session.commit() + self.log(""Generated %d glycan compositions"" % counter) + + +def tryopen(obj): + if hasattr(obj, ""read""): + return obj + else: + return open(obj, 'rt') + + +def parse_rules_from_file(path): + """""" + Parse monosaccharide bounds and constraints from text file-like + object + + Parameters + ---------- + path : file-like or str + The file to be parsed + + Raises + ------ + Exception + Description + + Returns + ------- + rules_table: dict + A dict mapping Residue Name to (Lower Bound, Upper Bound) + constraints: list + A list of :class:`~.ConstraintExpression` objects + """""" + ranges = [] + constraints = [] + stream = tryopen(path) + + i = 0 + + def cast(parts): + return parts[0], int(parts[1]), int(parts[2]) + + for line in stream: + i += 1 + line = ensuretext(line) + + if line.startswith("";""): + continue + parts = re.split(r""\s+"", line.replace(""\n"", """")) + try: + if len(parts) == 3: + ranges.append(cast(parts)) + elif len(parts) == 1: + if parts[0] in [""\n"", ""\r"", """"]: + break + else: + raise Exception(""Could not interpret line '%r' at line %d"" % (parts, i)) + except Exception as e: + raise Exception(""Failed to interpret line %r at line %d (%r)"" % (parts, i, e)) + + for line in stream: + i += 1 + line = ensuretext(line) + if line.startswith("";""): + continue + line = line.replace(""\n"", """") + if line in [""\n"", ""\r"", """"]: + break + try: + constraints.append(ConstraintExpression.parse(line)) + except Exception as e: + raise Exception(""Failed to interpret line %r at line %d (%r)"" % (line, i, e)) + + rules_table = CombinatoricCompositionGenerator.build_rules_table( + *zip(*ranges)) + try: + stream.close() + except Exception: + pass + return rules_table, constraints + + +def write_rules(rules, writer): + for key, bounds in rules.items(): + lo, hi = bounds + writer.write(""%s %d %d\n"" % (key, lo, hi)) + return writer + + +def write_constraints(constraints, writer): + writer.write(""\n"") + for constraint in constraints: + writer.write(""%s\n"" % constraint) + return writer + + +class ClassificationConstraint(object): + """""" + Express a classification (label) of a solution by satisfaction + of a boolean Expression + + Attributes + ---------- + classification : str + The label to grant on satisfaction of `constraints` + constraint : ConstraintExpression + The constraint that must be satisfied. + """""" + + def __init__(self, classification, constraint): + self.classification = classification + self.constraint = constraint + + def __call__(self, context): + """""" + Test for satisfaction. + + Parameters + ---------- + context : SymbolContext + + Returns + ------- + bool + Whether the constraint is satisfied + """""" + return self.constraint(context) + + def __repr__(self): + return ""{}\n{}"".format(self.classification, self.constraint) + + +is_n_glycan_classifier = ClassificationConstraint( + ""N-Glycan"", ( + ConstraintExpression.from_list( + [""HexNAc"", "">="", ""2""]) & ConstraintExpression.from_list( + [""Hex"", "">="", ""3""])) +) + +is_o_glycan_classifier = ClassificationConstraint( + ""O-Glycan"", ((ConstraintExpression.from_list([""HexNAc"", "">="", ""1""]) & + ConstraintExpression.from_list([""Hex"", "">="", ""1""])) | + (ConstraintExpression.from_list([""HexNAc"", "">="", ""2""]))) +) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycan/glycan_combinator.py",".py","5068","146","import itertools +from collections import Counter, defaultdict + +from glypy.structure.glycan_composition import FrozenGlycanComposition +from glypy.composition import formula, Composition + +from glycresoft.serialize.hypothesis.glycan import ( + GlycanComposition, GlycanCombination, GlycanCombinationGlycanComposition) + +from glycresoft.serialize import DatabaseBoundOperation +from glycresoft.task import TaskBase + + +class GlycanCompositionRecord(object): + def __init__(self, db_glycan_composition): + self.id = db_glycan_composition.id + self.composition = db_glycan_composition.convert() + self._str = str(self.composition) + self._hash = hash(self._str) + self.mass = self.composition.mass() + self.elemental_composition = self.composition.total_composition() + + def __repr__(self): + return ""GlycanCompositionRecord(%d, %s)"" % (self.id, self.composition) + + def __hash__(self): + return self._hash + + def __eq__(self, other): + return self._str == other._str + + +class GlycanCombinationSpecification(object): + def __init__(self, class_combinations=None, default=1): + if class_combinations is None: + class_combinations = defaultdict(lambda: self.default) + self.default = default + self.class_combinations = class_combinations + + def __getitem__(self, class_spec): + return self.class_combinations[class_spec] + + +def merge_compositions_frozen(composition_list): + """"""Given a list of monosaccharide packed strings, + sum the monosaccharide counts across lists and return + the merged string + + Parameters + ---------- + composition_list : list of GlycanCompositionRecord + + Returns + ------- + FrozenGlycanComposition + """""" + first = FrozenGlycanComposition() + for comp_rec in composition_list: + first += comp_rec.composition + return first + + +class GlycanCombinationBuilder(object): + def __init__(self, glycan_compositions, max_size=1): + self.glycan_compositions = list(map(GlycanCompositionRecord, glycan_compositions)) + self.max_size = max_size + + def combinate(self, n=1): + j = 0 + for comb_compositions in itertools.combinations_with_replacement(self.glycan_compositions, n): + j += 1 + counts = Counter(comb_compositions) + merged = merge_compositions_frozen(comb_compositions) + composition = str(merged) + mass = sum(c.mass for c in comb_compositions) + elemental_composition = Composition() + for c in comb_compositions: + elemental_composition += c.elemental_composition + inst = GlycanCombination( + count=n, + calculated_mass=mass, + composition=composition, + formula=formula(elemental_composition)) + yield inst, counts + + def combinate_all(self): + for i in range(1, self.max_size + 1): + for data in self.combinate(i): + yield data + + +class GlycanCombinationSerializer(DatabaseBoundOperation, TaskBase): + def __init__(self, connection, source_hypothesis_id, target_hypothesis_id, max_size=1): + DatabaseBoundOperation.__init__(self, connection) + self.source_hypothesis_id = source_hypothesis_id + self.target_hypothesis_id = target_hypothesis_id + self.max_size = max_size + self.total_count = 0 + + def load_compositions(self): + return self.query(GlycanComposition).filter( + GlycanComposition.hypothesis_id == self.source_hypothesis_id).all() + + def generate(self): + compositions = self.load_compositions() + combinator = GlycanCombinationBuilder(compositions, self.max_size) + + relation_acc = [] + i = 0 + j = 0 + hypothesis_id = self.target_hypothesis_id + self.log(""... Building combinations for Hypothesis %d"" % hypothesis_id) + for comb, counts in combinator.combinate_all(): + comb.hypothesis_id = hypothesis_id + self.session.add(comb) + self.session.flush() + + for key, count in counts.items(): + relation_acc.append({ + ""glycan_id"": key.id, + ""count"": count, + ""combination_id"": comb.id + }) + + i += 1 + j += 1 + self.total_count += 1 + if i > 50000: + self.log(f""...... {j} combinations created"") + self.session.execute( + GlycanCombinationGlycanComposition.insert(), relation_acc) + i = 0 + relation_acc = [] + if relation_acc: + self.session.execute( + GlycanCombinationGlycanComposition.insert(), relation_acc) + self.session.commit() + + def run(self): + self.generate() + total = self.session.query( + GlycanCombination).filter( + GlycanCombination.hypothesis_id == self.target_hypothesis_id + ).count() + self.log(f""{total} Glycan Combinations Constructed."") +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycan/glyspace.py",".py","16910","464","import logging +try: + logger_to_silence = logging.getLogger(""rdflib"") + logger_to_silence.propagate = False + logger_to_silence.setLevel(""CRITICAL"") +except Exception: + pass + +import os +import hashlib +from collections import Counter + +from glypy.io import glycoct, glyspace +from glypy.structure.glycan import NamedGlycan +from glypy.structure.glycan_composition import GlycanComposition + +from rdflib.plugins.sparql.results import xmlresults + +from glycresoft.serialize import ( + GlycanComposition as DBGlycanComposition, + GlycanClass, + GlycanStructure, + GlycanHypothesis, + GlycanStructureToClass, GlycanCompositionToClass, + ReferenceDatabase, ReferenceAccessionNumber) + +from .glycan_source import ( + GlycanTransformer, GlycanHypothesisSerializerBase, + formula) + +from glycresoft.task import TaskBase + + +config = { + ""transient_store_directory"": None +} + + +def set_transient_store(path): + config[""transient_store_directory""] = path + + +def get_transient_store(): + return config[""transient_store_directory""] + + +class GlycanCompositionSerializationCache(object): + def __init__(self, session, hypothesis_id): + self.session = session + self.store = dict() + self.hypothesis_id = hypothesis_id + + def get(self, composition_string): + try: + match = self.store[composition_string] + return match + except KeyError: + composition = GlycanComposition.parse(composition_string) + mass = composition.mass() + formula_string = formula(composition.total_composition()) + db_obj = DBGlycanComposition( + calculated_mass=mass, + composition=composition_string, + formula=formula_string, + hypothesis_id=self.hypothesis_id) + self.store[composition_string] = db_obj + self.session.add(db_obj) + self.session.flush() + return db_obj + + def __getitem__(self, k): + return self.get(k) + + +o_glycan_query = """""" +SELECT DISTINCT ?saccharide ?glycoct ?taxon ?motif WHERE { + ?saccharide a glycan:Saccharide . + ?saccharide glycan:has_glycosequence ?sequence . + ?saccharide glycan:is_from_source ?taxon . + FILTER CONTAINS(str(?sequence), ""glycoct"") . + ?sequence glycan:has_sequence ?glycoct . + ?saccharide glycan:has_motif ?motif . + FILTER CONTAINS(str(?sequence), ""glycoct"") . + ?sequence glycan:has_sequence ?glycoct . + ?saccharide glycan:has_motif ?motif . + FILTER(?motif in (glycoinfo:G00032MO, glycoinfo:G00042MO, glycoinfo:G00034MO, + glycoinfo:G00036MO, glycoinfo:G00033MO, glycoinfo:G00038MO, + glycoinfo:G00040MO, glycoinfo:G00037MO, glycoinfo:G00044MO)) +} +"""""" + +restricted_o_glycan_query = """""" +SELECT DISTINCT ?saccharide ?glycoct ?taxon ?motif WHERE { + ?saccharide a glycan:Saccharide . + ?saccharide glycan:has_glycosequence ?sequence . + ?saccharide glycan:is_from_source ?taxon . + FILTER CONTAINS(str(?sequence), ""glycoct"") . + ?sequence glycan:has_sequence ?glycoct . + ?saccharide glycan:has_motif ?motif . + FILTER(?motif in (glycoinfo:G00032MO, glycoinfo:G00034MO)) +} +"""""" + + +n_glycan_query = """""" +SELECT DISTINCT ?saccharide ?glycoct ?taxon ?motif WHERE { + ?saccharide a glycan:Saccharide . + ?saccharide glycan:has_glycosequence ?sequence . + ?saccharide glycan:is_from_source ?taxon . + FILTER CONTAINS(str(?sequence), ""glycoct"") . + ?sequence glycan:has_sequence ?glycoct . + ?saccharide glycan:has_motif ?motif . + FILTER(?motif in (glycoinfo:G00026MO)) +} +"""""" + + +taxonomy_query_template = """""" +PREFIX up: +PREFIX taxondb: +SELECT ?taxon +FROM +WHERE +{ + ?taxon a up:Taxon . + { + ?taxon rdfs:subClassOf taxondb:%(taxon)s . + } +} +"""""" + + +motif_to_class_map = { + glyspace.URIRef(""http://rdf.glycoinfo.org/glycan/G00032MO""): ""O-Linked"", + glyspace.URIRef(""http://rdf.glycoinfo.org/glycan/G00042MO""): ""O-Linked"", + glyspace.URIRef(""http://rdf.glycoinfo.org/glycan/G00034MO""): ""O-Linked"", + glyspace.URIRef(""http://rdf.glycoinfo.org/glycan/G00036MO""): ""O-Linked"", + glyspace.URIRef(""http://rdf.glycoinfo.org/glycan/G00033MO""): ""O-Linked"", + glyspace.URIRef(""http://rdf.glycoinfo.org/glycan/G00038MO""): ""O-Linked"", + glyspace.URIRef(""http://rdf.glycoinfo.org/glycan/G00040MO""): ""O-Linked"", + glyspace.URIRef(""http://rdf.glycoinfo.org/glycan/G00037MO""): ""O-Linked"", + glyspace.URIRef(""http://rdf.glycoinfo.org/glycan/G00044MO""): ""O-Linked"", + glyspace.URIRef(""http://rdf.glycoinfo.org/glycan/G00026MO""): ""N-Linked"" +} + + +def parse_taxon(taxon_uri): + uri = str(taxon_uri) + taxon = uri.split(""/"")[-1].replace("".rdf"", """") + return taxon + + +class TaxonomyFilter(object): + def __init__(self, target_taxonomy, include_children=True): + if isinstance(target_taxonomy, (tuple, list, set)): + self.target_taxonomy = str(target_taxonomy) + self.include_children = include_children + self.filter_set = set(target_taxonomy) + else: + self.target_taxonomy = str(target_taxonomy) + self.include_children = include_children + self.filter_set = None + self.prepare_filter() + + def query_all_taxa(self): + query = taxonomy_query_template % {""taxon"": self.target_taxonomy} + up = glyspace.UniprotRDFClient() + result = up.query(query) + return {parse_taxon(o['taxon']) for o in result} | {str(self.target_taxonomy)} + + def prepare_filter(self): + if self.include_children: + self.filter_set = self.query_all_taxa() + else: + self.filter_set = set([self.target_taxonomy]) + + def __call__(self, structure, name, taxon, motif): + return taxon not in self.filter_set + + def __repr__(self): + if len(self.filter_set) > 10: + return ""TaxonomyFilter({%s, ...})"" % ("", "".join(map(repr, list(self.filter_set)[:10])),) + else: + return ""TaxonomyFilter({%s})"" % ("", "".join(map(repr, self.filter_set)),) + + +def is_not_human(structure, name, taxon, motif): + return taxon != ""9606"" + + +# TODO: Refactor database builders to include an +# instance of this object to delegate responsibility +# to for actually communicating with GlySpace +class GlyspaceQueryHandler(TaskBase): + def __init__(self, query, filter_functions=None): + if filter_functions is None: + filter_functions = [] + self.sparql = query + self.filter_functions = filter_functions + self.response = None + + def query(self): + return glyspace.query(self.sparql) + + def translate_response(self, response): + for name, glycosequence, taxon, motif in response: + taxon = parse_taxon(taxon) + try: + structure = glycoct.loads(glycosequence, structure_class=NamedGlycan) + structure.name = name + + passed = True + for func in self.filter_functions: + if func(structure, name=name, taxon=taxon, motif=motif): + passed = False + break + if not passed: + continue + + yield structure, motif_to_class_map[motif] + except glycoct.GlycoCTError as e: + continue + except Exception as e: + self.error(""Error in translate_response of %s"" % name, e) + continue + + def execute(self): + self.response = self.query() + return self.translate_response(self.response) + + +def detatch_monosaccharide_subgroups(composition, substituents=None): + if substituents is None: + substituents = [] + composition = GlycanComposition.parse(composition) + if not substituents: + return composition + + gc = GlycanComposition() + + for key, value in composition.items(): + node_substituents = [s for p, s in key.substituents()] + counts = Counter() + for node_sub in node_substituents: + for sub in substituents: + if node_sub.name == sub.name: + key.drop_substituent(-1, sub.name) + counts[sub.name] += 1 + gc[key] = value + for sub_key, count in counts.items(): + gc['@%s' % sub_key] += count * value + return gc + + +class GlyspaceGlycanStructureHypothesisSerializerBase(GlycanHypothesisSerializerBase): + def __init__(self, database_connection, hypothesis_name=None, reduction=None, derivatization=None, + filter_functions=None, simplify=False, substituents_to_detatch=None): + super(GlyspaceGlycanStructureHypothesisSerializerBase, self).__init__(database_connection, hypothesis_name) + if filter_functions is None: + filter_functions = [] + if substituents_to_detatch is None: + substituents_to_detatch = [] + self.reduction = reduction + self.derivatization = derivatization + self.loader = None + self.transformer = None + self.composition_cache = None + self.seen = dict() + self.filter_functions = filter_functions + self.simplify = simplify + self.substituents_to_detatch = substituents_to_detatch + self._glytoucan_reference_db = None + + def _get_sparql(self): + raise NotImplementedError() + + def _get_store_name(self): + raise NotImplementedError() + + detatch_monosaccharide_subgroups = staticmethod(detatch_monosaccharide_subgroups) + + def _store_result(self, response): + dir_path = get_transient_store() + if dir_path is not None: + file_path = os.path.join(dir_path, self._get_store_name()) + response.serialize(file_path) + + def execute_query(self): + sparql = self._get_sparql() + response = glyspace.query(sparql) + self._store_result(response) + return response + + def load_query_results(self): + dir_path = get_transient_store() + if dir_path is not None: + file_path = os.path.join(dir_path, self._get_store_name()) + if os.path.exists(file_path): + p = xmlresults.XMLResultParser() + results = p.parse(open(file_path)) + return results + else: + return None + else: + return None + + def translate_response(self, response): + for name, glycosequence, taxon, motif in response: + breakpoint() + # taxon = parse_taxon(taxon) + try: + structure = glycoct.loads(glycosequence, structure_class=NamedGlycan) + structure.name = name + + passed = True + for func in self.filter_functions: + if func(structure, name=name, taxon=taxon, motif=motif): + passed = False + break + if not passed: + continue + + yield structure, motif_to_class_map[motif] + except glycoct.GlycoCTError as e: + continue + except Exception as e: + self.error(""Error in translate_response of %s"" % name, e) + continue + + def load_structures(self): + self.log(""Querying GlySpace"") + sparql_response = self.load_query_results() + if sparql_response is None: + sparql_response = self.execute_query() + self.log(""Translating Response"") + return self.translate_response(sparql_response) + + def make_pipeline(self): + self.loader = self.load_structures() + self.transformer = GlycanTransformer(self.loader, self.reduction, self.derivatization) + + def handle_new_structure(self, structure, motif): + mass = structure.mass() + try: + structure_string = structure.serialize() + except Exception as e: + print(structure.name) + raise e + formula_string = formula(structure.total_composition()) + + glycan_comp = GlycanComposition.from_glycan(structure) + if self.simplify: + glycan_comp.drop_configurations() + glycan_comp.drop_stems() + glycan_comp.drop_positions() + glycan_comp = self.detatch_monosaccharide_subgroups(glycan_comp, self.substituents_to_detatch) + composition_string = glycan_comp.serialize() + + accn = ReferenceAccessionNumber.get( + self.session, structure.name, self._glytoucan_reference_db.id) + self.session.flush() + structure = GlycanStructure( + glycan_sequence=structure_string, + formula=formula_string, + composition=composition_string, + hypothesis_id=self.hypothesis_id, + calculated_mass=mass) + composition_obj = self.composition_cache[composition_string] + structure.glycan_composition_id = composition_obj.id + structure.references.append(accn) + self.session.add(structure) + self.session.flush() + structure_class = self.structure_class_loader[motif] + rel = dict(glycan_id=structure.id, class_id=structure_class.id) + self.session.execute(GlycanStructureToClass.insert(), rel) + self.seen[structure_string] = structure + + def handle_duplicate_structure(self, structure, motif): + db_structure = self.seen[structure.serialize()] + structure_class = self.structure_class_loader[motif] + if structure_class not in db_structure.structure_classes: + rel = dict(glycan_id=db_structure.id, class_id=structure_class.id) + self.session.execute(GlycanStructureToClass.insert(), rel) + self.session.flush() + + def propagate_composition_motifs(self): + pairs = self.query( + DBGlycanComposition.id, GlycanClass.id).join(GlycanStructure).join( + GlycanStructure.structure_classes).filter( + DBGlycanComposition.hypothesis_id == self.hypothesis_id).group_by( + DBGlycanComposition.id, GlycanClass.id).all() + for glycan_id, structure_class_id in pairs: + self.session.execute( + GlycanCompositionToClass.insert(), + dict(glycan_id=glycan_id, class_id=structure_class_id)) + self.session.commit() + + def run(self): + self.make_pipeline() + self._glytoucan_reference_db = ReferenceDatabase.get( + self.session, name='GlyTouCan', url='https://glytoucan.org/') + self.session.commit() + self.composition_cache = GlycanCompositionSerializationCache(self.session, self.hypothesis_id) + i = 0 + last = 0 + interval = 100 + for structure, motif in self.transformer: + if structure.serialize() in self.seen: + self.handle_duplicate_structure(structure, motif) + else: + self.handle_new_structure(structure, motif) + i += 1 + if i - last > interval: + self.session.commit() + last = i + self.session.commit() + self.propagate_composition_motifs() + self.log(""Stored %d glycan structures and %d glycan compositions"" % ( + self.session.query(GlycanStructure).filter( + GlycanStructure.hypothesis_id == self.hypothesis_id).count(), + self.session.query(DBGlycanComposition).filter( + DBGlycanComposition.hypothesis_id == self.hypothesis_id).count())) + + +class NGlycanGlyspaceHypothesisSerializer(GlyspaceGlycanStructureHypothesisSerializerBase): + def _get_sparql(self): + return n_glycan_query + + def _get_store_name(self): + return ""n-glycans-query.sparql.xml"" + + +class OGlycanGlyspaceHypothesisSerializer(GlyspaceGlycanStructureHypothesisSerializerBase): + def _get_sparql(self): + return o_glycan_query + + def _get_store_name(self): + return ""o-glycans-query.sparql.xml"" + + +class RestrictedOGlycanGlyspaceHypothesisSerializer(GlyspaceGlycanStructureHypothesisSerializerBase): + def _get_sparql(self): + return restricted_o_glycan_query + + def _get_store_name(self): + return ""restricted-o-glycans-query.sparql.xml"" + + +class UserSPARQLQueryGlySpaceHypothesisSerializer(GlycanHypothesisSerializerBase): + def __init__(self, database_connection, query, hypothesis_name=None, reduction=None, derivatization=None, + filter_functions=None, simplify=False, substituents_to_detatch=None): + super(UserSPARQLQueryGlySpaceHypothesisSerializer, self).__init__( + database_connection, hypothesis_name, reduction, derivatization, + filter_functions, simplify, substituents_to_detatch) + self._query = query + + def _get_sparql(self): + return self._query + + def _get_store_name(self): + sha1 = hashlib.new(""sha1"") + sha1.update(self._query) + return ""user-query-{}.sparql.xml"".format(sha1.hexdigest()) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycan/glycan_source.py",".py","14395","419","import re + +from uuid import uuid4 +from collections import OrderedDict + +from glycresoft.serialize.hypothesis import GlycanHypothesis +from glycresoft.serialize.hypothesis.glycan import ( + GlycanComposition as DBGlycanComposition, GlycanClass, + GlycanCompositionToClass, GlycanTypes) + +from glycresoft.serialize import DatabaseBoundOperation, func + +from glycresoft.database.builder.base import HypothesisSerializerBase + +from glypy.composition import composition_transform, formula +from glypy.structure import glycan_composition +from glypy.io import byonic, glyconnect +from glypy.utils import opener +from glypy import ReducedEnd + + +class TextFileGlycanCompositionLoader(object): + def __init__(self, file_object, dialect=None): + if dialect is None: + dialect = dispatching_dialect + self.file_object = file_object + self.current_line = 0 + self.dialect = dialect + + def _partition_line(self, line): + return self.dialect.parse_line(line) + + def _process_line(self): + line = next(self.file_object) + line = line.strip() + self.current_line += 1 + try: + while line == '': + line = next(self.file_object) + line = line.strip() + self.current_line += 1 + tokens = self._partition_line(line) + if len(tokens) == 1: + composition, structure_classes = tokens[0], () + elif len(tokens) == 2: + composition, structure_classes = tokens + structure_classes = [structure_classes] + else: + composition = tokens[0] + structure_classes = tokens[1:] + gc = self.dialect.parse_composition(composition) + except StopIteration: + raise + except Exception as e: + raise Exception(""Parsing Error %r occurred at line %d"" % (e, self.current_line)) + return gc, structure_classes + + def __next__(self): + return self._process_line() + + next = __next__ + + def __iter__(self): + return self + + def close(self): + self.file_object.close() + +class GlycanCompositionDialectError(Exception): + pass + + +class GlycanCompositionDialect(object): + name = 'iupaclite' + + def parse_line(self, line): + parts, offset, n = self.split_line(line) + # line is just glycan composition + if offset is None: + return parts + i = 0 + while (offset + i) < n: + c = line[offset + i] + if c.isspace(): + break + i += 1 + parts.append(line[:offset + i]) + parts.extend(t for t in re.split( + r""(?:\t|\s{2,})"", line[offset + i:]) if t) + return parts + + def split_line(self, line): + n = len(line) + try: + brace_close = line.index(""}"") + except ValueError: + raise GlycanCompositionDialectError() + parts = [] + # line is just glycan composition + if brace_close == n - 1: + parts.append(line) + return parts, None, n + offset = brace_close + 1 + return parts, offset, n + + def validate_composition(self, composition): + if not composition: + raise Exception() + for mono in composition: + if mono.mass() == 0.0: + raise ValueError( + ""Invalid glycan composition element %r, no known mass"") + return composition + + def parse_composition(self, composition): + result = glycan_composition.GlycanComposition.parse(composition) + result = self.validate_composition(result) + return result + + +class SimpleGlycanCompositionDialect(GlycanCompositionDialect): + + def split_line(self, line): + n = len(line) + sep = re.search(r""(\t+|\s{2,})"", line) + if sep is None: + raise GlycanCompositionDialectError() + else: + junction = sep.start() + parts = [] + offset = junction + return parts, offset, n + + def parse_composition(self, composition): + result = super(SimpleGlycanCompositionDialect, self).parse_composition(composition) + return result + + +class ByonicGlycanCompositionDialect(SimpleGlycanCompositionDialect): + name = 'byonic' + + def parse_composition(self, composition): + result = byonic.loads(composition).thaw() + result = self.validate_composition(result) + return result + + +class GlyconnectGlycanCompositionDialect(SimpleGlycanCompositionDialect): + name = 'glyconnect' + + def parse_composition(self, composition): + result = glyconnect.loads(composition).thaw() + result = self.validate_composition(result) + return result + + +dialects = OrderedDict([ + (""iupaclite"", GlycanCompositionDialect()), + (""byonic"", ByonicGlycanCompositionDialect()), + (""glyconnect"", GlyconnectGlycanCompositionDialect()) +]) + + +class DispatchingGlycanCompositionDialect(object): + def __init__(self, dialects): + self.dialects = dialects + + def parse_line(self, line): + for name, dialect in self.dialects.items(): + try: + return dialect.parse_line(line) + except GlycanCompositionDialectError: + continue + raise GlycanCompositionDialectError() + + def parse_composition(self, composition): + for name, dialect in self.dialects.items(): + try: + return dialect.parse_composition(composition) + except Exception as err: + continue + raise GlycanCompositionDialectError() + + +dispatching_dialect = DispatchingGlycanCompositionDialect(dialects) + + +_default_label_map = { + ""n glycan"": GlycanTypes.n_glycan, + ""n linked"": GlycanTypes.n_glycan, + ""o glycan"": GlycanTypes.o_glycan, + ""o linked"": GlycanTypes.o_glycan, + ""gag linker"": GlycanTypes.gag_linker +} + + +def normalize_lookup(string): + normalized_string = string.lower().replace(""-"", "" "").replace( + ""\"""", '').replace(""'"", '').strip().rstrip() + if normalized_string in _default_label_map: + return _default_label_map[normalized_string] + else: + return string + + +class GlycanClassLoader(object): + def __init__(self, session): + self.session = session + self.store = dict() + + def get(self, name): + name = normalize_lookup(name) + try: + return self.store[name] + except KeyError: + glycan_class = self.session.query(GlycanClass).filter(GlycanClass.name == name).first() + if glycan_class is None: + glycan_class = GlycanClass(name=name) + self.session.add(glycan_class) + self.session.flush() + self.store[name] = glycan_class + return glycan_class + + def __getitem__(self, name): + return self.get(name) + + +named_reductions = { + 'reduced': 'H2', + 'deuteroreduced': 'HH[2]', + '2ab': ""C7H8N2"", + '2aa': ""C7H7NO"", + 'apts': ""C16H11N1O8S3"", +} + + +named_derivatizations = { + ""permethylated"": ""methyl"", + ""peracetylated"": ""acetyl"" +} + + +class GlycanTransformer(object): + def __init__(self, glycan_source, reduction=None, derivatization=None): + self.glycan_source = glycan_source + self.reduction = reduction + self.derivatization = derivatization + + if reduction is not None and isinstance(reduction, str): + self.reduction = ReducedEnd(reduction) + + def _process_composition(self): + gc, structure_classes = next(self.glycan_source) + if self.reduction is not None and gc.reducing_end is None: + gc.reducing_end = self.reduction.clone() + if self.derivatization is not None: + gc = composition_transform.derivatize(gc, self.derivatization) + return gc, structure_classes + + def __next__(self): + return self._process_composition() + + next = __next__ + + def __iter__(self): + return self + + +class GlycanHypothesisSerializerBase(DatabaseBoundOperation, HypothesisSerializerBase): + def __init__(self, database_connection, hypothesis_name=None, uuid=None): + if uuid is None: + uuid = str(uuid4().hex) + DatabaseBoundOperation.__init__(self, database_connection) + self._hypothesis_name = hypothesis_name + self._hypothesis_id = None + self._hypothesis = None + self._structure_class_loader = None + self.uuid = uuid + + def make_structure_class_loader(self): + return GlycanClassLoader(self.session) + + @property + def structure_class_loader(self): + if self._structure_class_loader is None: + self._structure_class_loader = self.make_structure_class_loader() + return self._structure_class_loader + + def _construct_hypothesis(self): + if self._hypothesis_name is None: + self._hypothesis_name = self._make_name() + self._hypothesis = GlycanHypothesis(name=self._hypothesis_name, uuid=self.uuid) + + self.session.add(self._hypothesis) + self.session.commit() + + self._hypothesis_id = self._hypothesis.id + self._hypothesis_name = self._hypothesis.name + + def _make_name(self): + return ""GlycanHypothesis-"" + self.uuid + + +class TextFileGlycanHypothesisSerializer(GlycanHypothesisSerializerBase): + def __init__(self, glycan_text_file, database_connection, reduction=None, derivatization=None, + hypothesis_name=None): + GlycanHypothesisSerializerBase.__init__(self, database_connection, hypothesis_name) + + self.glycan_file = glycan_text_file + self.reduction = reduction + self.derivatization = derivatization + + self.loader = None + self.transformer = None + + def _make_name(self): + return ""TextFileGlycanHypothesis-"" + self.uuid + + def make_pipeline(self): + self.loader = TextFileGlycanCompositionLoader(opener(self.glycan_file, 'r')) + self.transformer = GlycanTransformer(self.loader, self.reduction, self.derivatization) + + def run(self): + self.make_pipeline() + structure_class_lookup = self.structure_class_loader + self.log(""Loading Glycan Compositions from Stream for %r"" % self.hypothesis) + + acc = [] + counter = 0 + for composition, structure_classes in self.transformer: + mass = composition.mass() + composition_string = composition.serialize() + formula_string = formula(composition.total_composition()) + inst = DBGlycanComposition( + calculated_mass=mass, formula=formula_string, + composition=composition_string, + hypothesis_id=self.hypothesis_id) + self.session.add(inst) + self.session.flush() + counter += 1 + for structure_class in structure_classes: + structure_class = structure_class_lookup[structure_class] + acc.append(dict(glycan_id=inst.id, class_id=structure_class.id)) + if len(acc) % 100 == 0: + self.session.execute(GlycanCompositionToClass.insert(), acc) + acc = [] + if acc: + self.session.execute(GlycanCompositionToClass.insert(), acc) + acc = [] + self.session.commit() + self.loader.close() + self.log(""Generated %d glycan compositions"" % counter) + + +class GlycanCompositionHypothesisMerger(GlycanHypothesisSerializerBase): + def __init__(self, database_connection, source_hypothesis_ids, hypothesis_name, uuid=None): + GlycanHypothesisSerializerBase.__init__( + self, database_connection, hypothesis_name, uuid=uuid) + self.source_hypothesis_ids = source_hypothesis_ids + + def stream_from_hypotheses(self, connection, hypothesis_id): + self.log(""Streaming from %s for hypothesis %d"" % (connection, hypothesis_id)) + connection = DatabaseBoundOperation(connection) + session = connection.session() + for db_composition in session.query(DBGlycanComposition).filter( + DBGlycanComposition.hypothesis_id == hypothesis_id): + structure_classes = list(db_composition.structure_classes) + if len(structure_classes) > 0: + yield db_composition, [sc.name for sc in db_composition.structure_classes] + else: + yield db_composition, [None] + + def extract_iterative(self): + for connection, hypothesis_id in self.source_hypothesis_ids: + for pair in self.stream_from_hypotheses(connection, hypothesis_id): + yield pair + + def run(self): + structure_class_lookup = self.structure_class_loader + acc = [] + seen = set() + composition_cache = dict() + counter = 0 + for db_composition, structure_classes in self.extract_iterative(): + counter += 1 + composition_string = db_composition.composition + novel_combinations = set() + for structure_class in structure_classes: + if (composition_string, structure_class) not in seen: + novel_combinations.add(structure_class) + if len(novel_combinations) == 0: + continue + try: + inst = composition_cache[composition_string] + except KeyError: + mass = db_composition.calculated_mass + formula_string = db_composition.formula + inst = DBGlycanComposition( + calculated_mass=mass, formula=formula_string, + composition=composition_string, + hypothesis_id=self.hypothesis_id) + self.session.add(inst) + self.session.flush() + composition_cache[composition_string] = inst + for structure_class in novel_combinations: + seen.add((composition_string, structure_class)) + if structure_class is None: + continue + structure_class = structure_class_lookup[structure_class] + acc.append(dict(glycan_id=inst.id, class_id=structure_class.id)) + if (len(acc) % 10000) == 0: + self.session.execute(GlycanCompositionToClass.insert(), acc) + acc = [] + if acc: + self.session.execute(GlycanCompositionToClass.insert(), acc) + acc = [] + self.session.commit() + assert len(seen) > 0 +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/builder/glycan/migrate.py",".py","2374","67","from uuid import uuid4 + +from glycresoft.serialize import ( + GlycanHypothesis, GlycanComposition, + DatabaseBoundOperation, GlycanCompositionToClass) + +from glycresoft.serialize.utils import get_uri_for_instance + +from .glycan_source import GlycanClassLoader + +from glycresoft.task import TaskBase + + +class GlycanHypothesisMigrator(DatabaseBoundOperation, TaskBase): + def __init__(self, database_connection): + DatabaseBoundOperation.__init__(self, database_connection) + self.hypothesis_id = None + self.glycan_composition_id_map = dict() + self._structure_class_loader = None + + def make_structure_class_loader(self): + return GlycanClassLoader(self.session) + + @property + def structure_class_loader(self): + if self._structure_class_loader is None: + self._structure_class_loader = self.make_structure_class_loader() + return self._structure_class_loader + + def migrate_hypothesis(self, hypothesis): + new_hypothesis = GlycanHypothesis( + name=hypothesis.name, + uuid=str(uuid4().hex), + status=hypothesis.status, + parameters=dict(hypothesis.parameters or {})) + new_hypothesis.parameters['original_uuid'] = hypothesis.uuid + new_hypothesis.parameters['copied_from'] = get_uri_for_instance(hypothesis) + self.session.add(new_hypothesis) + self.session.flush() + self.hypothesis_id = new_hypothesis.id + + def _migrate(self, obj): + self.session.add(obj) + self.session.flush() + new_id = obj.id + return new_id + + def commit(self): + self.session.commit() + + def migrate_glycan_composition(self, glycan_composition): + gc = glycan_composition + new_gc = GlycanComposition( + calculated_mass=gc.calculated_mass, + formula=gc.formula, + composition=gc.composition, + hypothesis_id=self.hypothesis_id) + new_id = self._migrate(new_gc) + self.glycan_composition_id_map[gc.id] = new_id + + class_types = [] + for glycan_class in gc.structure_classes: + local_glycan_class = self.structure_class_loader[glycan_class.name] + class_types.append({""glycan_id"": new_id, ""class_id"": local_glycan_class.id}) + if class_types: + self.session.execute(GlycanCompositionToClass.insert(), class_types) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/analysis/analysis_migration.py",".py","27327","680","import time + +from datetime import timedelta +from collections import defaultdict +from typing import DefaultDict, List, Optional, Sequence, Set, Tuple + +from glycresoft.structure.scan import ScanInformation +from glycresoft.trace.extract import ChromatogramExtractor + +from glypy.composition import formula + +from glycresoft.task import TaskBase +from glycresoft.chromatogram_tree import ( + ChromatogramFilter, + DisjointChromatogramSet, + Chromatogram +) + +from glycresoft.database.builder.glycan.migrate import ( + GlycanHypothesisMigrator) + +from glycresoft.database.builder.glycopeptide.migrate import ( + GlycopeptideHypothesisMigrator, + Glycopeptide, + Peptide, + Protein, + GlycanCombination) + +from glycresoft.serialize import ( + AnalysisTypeEnum, + ChromatogramSolutionMassShiftedToChromatogramSolution) + +from glycresoft.tandem.glycopeptide.identified_structure import ( + IdentifiedGlycopeptide as MemoryIdentifiedGlycopeptide) +from glycresoft.scoring.chromatogram_solution import ChromatogramSolution + +from glycresoft.serialize.utils import toggle_indices +from glycresoft.serialize.hypothesis import GlycanComposition +from glycresoft.serialize import DatabaseBoundOperation +from glycresoft.serialize.serializer import AnalysisSerializer + +from glycresoft.serialize.spectrum import ( + SampleRun, + MSScan, + DeconvolutedPeak, + PrecursorInformation) + +from ms_deisotope.data_source import ChargeNotProvided +from ms_deisotope.output.common import SampleRun as MemorySampleRun + +def slurp(session, model, ids): + ids = sorted(ids) + total = len(ids) + last = 0 + step = 100 + results = [] + while last < total: + results.extend(session.query(model).filter( + model.id.in_(ids[last:last + step]))) + last += step + return results + + +def fetch_scans_used_in_chromatogram(chromatogram_set: List[Chromatogram], + extractor: ChromatogramExtractor) -> List[ScanInformation]: + scan_ids = set() + for chroma in chromatogram_set: + scan_ids.update(chroma.scan_ids) + + tandem_solutions = getattr(chroma, ""tandem_solutions"", []) + for tsm in tandem_solutions: + scan_ids.add(tsm.scan.id) + scan_ids.add(tsm.scan.precursor_information.precursor_scan_id) + + scans = [] + with extractor.toggle_peak_loading(): + for scan_id in scan_ids: + scans.append( + ScanInformation.from_scan(extractor.get_scan_header_by_id(scan_id)) + ) + return sorted(scans, key=lambda x: (x.ms_level, x.index)) + + +def fetch_glycan_compositions_from_chromatograms(chromatogram_set: Sequence[ChromatogramSolution], + glycan_db: DatabaseBoundOperation) -> List[GlycanComposition]: + ids = set() + for chroma in chromatogram_set: + if chroma.composition: + ids.add(chroma.composition.id) + glycan_compositions = [] + for glycan_id in ids: + gc = glycan_db.query(GlycanComposition).get(glycan_id) + glycan_compositions.append(gc) + return glycan_compositions + + +def update_glycan_chromatogram_composition_ids(hypothesis_migration, + glycan_chromatograms: Sequence[ChromatogramSolution]): + mapping = dict() + tandem_mapping = defaultdict(list) + for chromatogram in glycan_chromatograms: + if chromatogram.composition is None: + continue + mapping[chromatogram.composition.id] = chromatogram.composition + for match in getattr(chromatogram, 'tandem_solutions', []): + tandem_mapping[match.target.id].append(match.target) + + for key, value in mapping.items(): + value.id = hypothesis_migration.glycan_composition_id_map[value.id] + for key, group in tandem_mapping.items(): + for value in group: + value.id = hypothesis_migration.glycan_composition_id_map[key] + + +class SampleMigrator(DatabaseBoundOperation, TaskBase): + def __init__(self, connection): + DatabaseBoundOperation.__init__(self, connection) + self.sample_run_id = None + self.ms_scan_id_map = dict() + self.peak_id_map = dict() + + def _migrate(self, obj): + self.session.add(obj) + self.session.flush() + new_id = obj.id + return new_id + + def commit(self): + self.session.commit() + + def clear(self): + self.peak_id_map.clear() + self.ms_scan_id_map.clear() + + def migrate_sample_run(self, sample_run): + new_sample_run = SampleRun( + name=sample_run.name, + uuid=sample_run.uuid, + sample_type=sample_run.sample_type, + completed=sample_run.completed + ) + new_id = self._migrate(new_sample_run) + self.sample_run_id = new_id + + def scan_id(self, ms_scan) -> str: + if ms_scan is None: + return None + try: + scan_id = ms_scan.scan_id + except AttributeError: + scan_id = ms_scan.id + return scan_id + + def peak_id(self, peak, scan_id) -> Tuple[str, DeconvolutedPeak]: + try: + if peak.id: + peak_id = (scan_id, peak.convert()) + except AttributeError: + peak_id = (scan_id, peak) + return peak_id + + def migrate_precursor_information(self, prec_info): + try: + # prec_id = self.scan_id(prec_info.precursor) + prec_id = prec_info.precursor_scan_id + except KeyError as err: + prec_id = None + self.log(""Unable to locate precursor scan with ID %r"" % (err , )) + # prod_id = self.scan_id(prec_info.product) + prod_id = prec_info.product_scan_id + charge = prec_info.charge + if charge == ChargeNotProvided: + charge = 0 + new_info = PrecursorInformation( + sample_run_id=self.sample_run_id, + # precursor may be missing + precursor_id=self.ms_scan_id_map.get(prec_id), + product_id=self.ms_scan_id_map[prod_id], + neutral_mass=prec_info.neutral_mass, + charge=charge, + intensity=prec_info.intensity) + return self._migrate(new_info) + + def migrate_ms_scan(self, ms_scan): + if ms_scan is None: + return + scan_id = self.scan_id(ms_scan) + new_scan = MSScan._serialize_scan(ms_scan, self.sample_run_id) + try: + new_scan.info.update(dict(ms_scan.info)) + except AttributeError: + pass + new_id = self._migrate(new_scan) + self.ms_scan_id_map[scan_id] = new_id + if ms_scan.precursor_information: + self.migrate_precursor_information( + ms_scan.precursor_information) + + def migrate_peak(self, peak, scan_id): + new_scan_id = self.ms_scan_id_map[scan_id] + new_peak = DeconvolutedPeak.serialize(peak) + new_peak.scan_id = new_scan_id + new_id = self._migrate(new_peak) + peak_id = self.peak_id(peak, scan_id) + self.peak_id_map[peak_id] = new_id + + +class AnalysisMigrationBase(DatabaseBoundOperation, TaskBase): + sample_run: MemorySampleRun + chromatogram_extractor: ChromatogramExtractor + + _seed_analysis_name: str + _analysis_serializer: Optional[AnalysisSerializer] + _sample_migrator: Optional[SampleMigrator] + + def __init__(self, connection: str, analysis_name: str, + sample_run: MemorySampleRun, + chromatogram_extractor: ChromatogramExtractor): + DatabaseBoundOperation.__init__(self, connection) + + self.sample_run = sample_run + self.chromatogram_extractor = chromatogram_extractor + + self._seed_analysis_name = analysis_name + self._analysis_serializer = None + self._sample_migrator = None + + @property + def analysis(self): + return self._analysis_serializer.analysis + + def set_analysis_type(self, type_string: str): + self._analysis_serializer.analysis.analysis_type = type_string + self._analysis_serializer.session.add(self.analysis) + self._analysis_serializer.session.commit() + + def set_parameters(self, parameters: dict): + self._analysis_serializer.analysis.parameters = parameters + self._analysis_serializer.session.add(self.analysis) + self._analysis_serializer.commit() + + def fetch_peaks(self, chromatogram_set: Sequence[Chromatogram]) -> DefaultDict[str, Set[DeconvolutedPeak]]: + scan_peak_map = defaultdict(set) + for chroma in chromatogram_set: + if chroma is None: + continue + for node in chroma: + for peak in node.peaks: + scan_peak_map[node.scan_id].add(peak) + return scan_peak_map + + def fetch_scans(self) -> List[ScanInformation]: + raise NotImplementedError() + + def migrate_sample(self): + self.log(""... Loading Scans"") + scans = self.fetch_scans() + self._sample_migrator = SampleMigrator(self._original_connection) + self._sample_migrator.migrate_sample_run(self.sample_run) + + self.log(""... Migrating Scans"") + for scan in sorted(scans, key=lambda x: x.ms_level): + self._sample_migrator.migrate_ms_scan(scan) + + scan_peak_map = self.fetch_peaks(self.chromatogram_set) + self.log(""... Migrating Peaks"") + for scan_id, peaks in scan_peak_map.items(): + for peak in peaks: + self._sample_migrator.migrate_peak(peak, scan_id) + + self._sample_migrator.commit() + + def migrate_hypothesis(self): + raise NotImplementedError() + + def create_analysis(self): + raise NotImplementedError() + + def run(self): + self.log(""Migrating Hypothesis"") + self.migrate_hypothesis() + self.log(""Migrating Sample Run"") + self.migrate_sample() + self.log(""Creating Analysis Record"") + self.create_analysis() + + +class GlycanCompositionChromatogramAnalysisSerializer(AnalysisMigrationBase): + _glycan_hypothesis_migrator: Optional[GlycanHypothesisMigrator] + glycan_db: DatabaseBoundOperation + chromatogram_set: ChromatogramFilter + + def __init__(self, connection, analysis_name, sample_run, + chromatogram_set, glycan_db, + chromatogram_extractor): + AnalysisMigrationBase.__init__( + self, connection, analysis_name, sample_run, + chromatogram_extractor) + self._glycan_hypothesis_migrator = None + + self.glycan_db = glycan_db + self.chromatogram_set = ChromatogramFilter(chromatogram_set) + self._index_chromatogram_set() + + def _index_chromatogram_set(self): + for i, chroma in enumerate(self.chromatogram_set): + chroma.id = i + + @property + def analysis(self): + return self._analysis_serializer.analysis + + def fetch_scans(self): + scans = fetch_scans_used_in_chromatogram( + self.chromatogram_set, self.chromatogram_extractor) + return scans + + def migrate_hypothesis(self): + self._glycan_hypothesis_migrator = GlycanHypothesisMigrator( + self._original_connection) + self._glycan_hypothesis_migrator.migrate_hypothesis( + self.glycan_db.hypothesis) + for glycan_composition in fetch_glycan_compositions_from_chromatograms( + self.chromatogram_set, self.glycan_db): + self._glycan_hypothesis_migrator.migrate_glycan_composition( + glycan_composition) + self._glycan_hypothesis_migrator.commit() + + def locate_mass_shift_reference_solution(self, chromatogram): + if chromatogram.used_as_mass_shift: + for key, mass_shift in chromatogram.used_as_mass_shift: + disjoint_set_for_key = self.chromatogram_set.key_map[key] + if not isinstance(disjoint_set_for_key, DisjointChromatogramSet): + disjoint_set_for_key = DisjointChromatogramSet(disjoint_set_for_key) + hit = disjoint_set_for_key.find_overlap(chromatogram) + if hit is not None: + yield hit, mass_shift + + def _get_solution_db_id_by_reference(self, ref_id): + return self._analysis_serializer._chromatogram_solution_id_map[ref_id] + + def _get_mass_shift_id(self, mass_shift): + return self._analysis_serializer._mass_shift_cache.serialize(mass_shift).id + + def express_mass_shift_relation(self, chromatogram: Chromatogram): + try: + source_id = self._get_solution_db_id_by_reference(chromatogram.id) + except KeyError as e: + self.error( + f""Chromatogram not registered: {e} -> {chromatogram}"") + seen = set() + for related_solution, mass_shift in self.locate_mass_shift_reference_solution( + chromatogram): + if related_solution.id in seen: + continue + else: + seen.add(related_solution.id) + try: + referenced_id = self._get_solution_db_id_by_reference(related_solution.id) + mass_shift_id = self._get_mass_shift_id(mass_shift) + self._analysis_serializer.session.execute( + ChromatogramSolutionMassShiftedToChromatogramSolution.__table__.insert(), + { + ""mass_shifted_solution_id"": source_id, + ""owning_solution_id"": referenced_id, + ""mass_shift_id"": mass_shift_id + }) + except KeyError as e: + self.error( + f""Failed to express mass shift relation: {e} -> {mass_shift} @ {chromatogram}"") + continue + + def create_analysis(self): + self._analysis_serializer = AnalysisSerializer( + self._original_connection, + analysis_name=self._seed_analysis_name, + sample_run_id=self._sample_migrator.sample_run_id) + + self._analysis_serializer.set_analysis_type(AnalysisTypeEnum.glycan_lc_ms.name) + + update_glycan_chromatogram_composition_ids( + self._glycan_hypothesis_migrator, + self.chromatogram_set) + + self._analysis_serializer.set_peak_lookup_table(self._sample_migrator.peak_id_map) + + n = len(self.chromatogram_set) + i = 0 + + for chroma in self.chromatogram_set: + i += 1 + if i % 100 == 0: + self.log(""%0.2f%% of Chromatograms Saved (%d/%d)"" % ( + i * 100. / n, i, n)) + if chroma.composition is not None: + self._analysis_serializer.save_glycan_composition_chromatogram_solution( + chroma) + else: + self._analysis_serializer.save_unidentified_chromatogram_solution( + chroma) + + for chroma in self.chromatogram_set: + if chroma.chromatogram.used_as_mass_shift: + self.express_mass_shift_relation(chroma) + + self._analysis_serializer.commit() + + +class GlycopeptideMSMSAnalysisSerializer(AnalysisMigrationBase): + + + _glycopeptide_hypothesis_migrator: GlycopeptideHypothesisMigrator + _glycopeptide_ids: Set[int] + + _identified_glycopeptide_set: List[MemoryIdentifiedGlycopeptide] + _unassigned_chromatogram_set: List[Chromatogram] + + + def __init__(self, connection, analysis_name, sample_run, + identified_glycopeptide_set, unassigned_chromatogram_set, + glycopeptide_db, chromatogram_extractor): + AnalysisMigrationBase.__init__( + self, connection, analysis_name, sample_run, chromatogram_extractor) + + self._glycopeptide_hypothesis_migrator = None + + self.glycopeptide_db = glycopeptide_db + self._identified_glycopeptide_set = identified_glycopeptide_set + + self._unassigned_chromatogram_set = unassigned_chromatogram_set + self._glycopeptide_ids = None + + self.aggregate_glycopeptide_ids() + + def aggregate_glycopeptide_ids(self): + """"""Accumulate a set of all unique structure IDs over all spectrum matches. + + Returns + ------- + set + """""" + aggregate = set() + for gp in self._identified_glycopeptide_set: + for solution_set in gp.spectrum_matches: + for match in solution_set: + aggregate.add(match.target.id) + self._glycopeptide_ids = aggregate + + def update_glycopeptide_ids(self): + '''Build a mapping from searched hypothesis structure ID to saved subset structure + ID, ensuring that each object has its new ID assigned exactly once. + + The use of :func:`id` here is to ensure that exactness. + ''' + hypothesis_migration = self._glycopeptide_hypothesis_migrator + identified_glycopeptide_set = self._identified_glycopeptide_set + mapping = defaultdict(dict) + for glycopeptide in identified_glycopeptide_set: + mapping[glycopeptide.structure.id][id( + glycopeptide.structure)] = glycopeptide.structure + for solution_set in glycopeptide.spectrum_matches: + for match in solution_set: + mapping[match.target.id][id(match.target)] = match.target + for key, instances in mapping.items(): + for value in instances.values(): + try: + value.id = hypothesis_migration.glycopeptide_id_map[value.id] + except KeyError: + self.log(f""Could not find a mapping from ID {value.id} for {value} "" + ""in the new keyspace, reconstructing to recover..."") + value.id = self._migrate_single_glycopeptide(value) + + @property + def chromatogram_set(self): + return [ + gp.chromatogram for gp in self._identified_glycopeptide_set + ] + list(self._unassigned_chromatogram_set) + + def migrate_hypothesis(self): + start = time.time() + self._glycopeptide_hypothesis_migrator = GlycopeptideHypothesisMigrator( + self._original_connection) + self._glycopeptide_hypothesis_migrator.migrate_hypothesis( + self.glycopeptide_db.hypothesis) + + self.log(""... Migrating Glycans"") + glycan_compositions, glycan_combinations = self.fetch_glycan_compositions( + self._glycopeptide_ids) + + for i, gc in enumerate(glycan_compositions): + if i % 1000 == 0 and i: + self.log(""...... Migrating Glycan %d"" % (i, )) + self._glycopeptide_hypothesis_migrator.migrate_glycan_composition(gc) + for i, gc in enumerate(glycan_combinations): + if i % 1000 == 0 and i: + self.log(""...... Migrating Glycan Combination %d"" % (i, )) + self._glycopeptide_hypothesis_migrator.migrate_glycan_combination(gc) + + self.log(""... Loading Proteins and Peptides from Glycopeptides"") + peptides = self.fetch_peptides(self._glycopeptide_ids) + proteins = self.fetch_proteins(peptides) + self.log(""... Migrating Proteins (%d)"" % (len(proteins), )) + n = len(proteins) + index_toggler = toggle_indices(self._glycopeptide_hypothesis_migrator.session, Protein) + index_toggler.drop() + for i, protein in enumerate(proteins): + if i % 5000 == 0 and i: + self.log(""...... Migrating Protein %d/%d (%0.2f%%) %s"" % (i, n, i * 100.0 / n, protein.name)) + self._glycopeptide_hypothesis_migrator.migrate_protein(protein) + proteins = [] + index_toggler.create() + index_toggler = toggle_indices( + self._glycopeptide_hypothesis_migrator.session, Peptide) + index_toggler.drop() + n = len(peptides) + self.log(""... Migrating Peptides (%d)"" % (n, )) + self._glycopeptide_hypothesis_migrator.migrate_peptides_bulk(peptides) + index_toggler.create() + peptides = [] + + glycopeptides = self.fetch_glycopeptides(self._glycopeptide_ids) + + index_toggler = toggle_indices(self._glycopeptide_hypothesis_migrator.session, Glycopeptide) + index_toggler.drop() + n = len(glycopeptides) + self.log(""... Migrating Glycopeptides (%d)"" % (n, )) + self._glycopeptide_hypothesis_migrator.migrate_glycopeptide_bulk(glycopeptides) + index_toggler.create() + self._glycopeptide_hypothesis_migrator.commit() + elapsed = timedelta(seconds=time.time()) - timedelta(seconds=start) + self.log(f""... Hypothesis migration time {elapsed}"") + + def fetch_scans(self): + scan_ids = set() + precursor_ids = dict() + with self.chromatogram_extractor.toggle_peak_loading(): + for glycopeptide in self._identified_glycopeptide_set: + if glycopeptide.chromatogram is not None: + scan_ids.update(glycopeptide.chromatogram.scan_ids) + for msms in glycopeptide.spectrum_matches: + scan_ids.add(msms.scan.id) + try: + scan_ids.add(precursor_ids[msms.scan.id]) + except KeyError: + precursor_ids[msms.scan.id] = self.chromatogram_extractor.get_scan_header_by_id( + msms.scan.id).precursor_information.precursor_scan_id + scan_ids.add(precursor_ids[msms.scan.id]) + scans = [] + for scan_id in scan_ids: + if scan_id is not None: + try: + scans.append(ScanInformation.from_scan(self.chromatogram_extractor.get_scan_header_by_id(scan_id))) + except KeyError: + self.log(""Could not locate scan for ID %r"" % (scan_id, )) + return sorted(scans, key=lambda x: (x.ms_level, x.index)) + + def _get_glycan_combination_for_glycopeptide(self, glycopeptide_id: int) -> int: + gc_comb_id = self.glycopeptide_db.query( + Glycopeptide.glycan_combination_id).filter( + Glycopeptide.id == glycopeptide_id) + return gc_comb_id[0] + + def fetch_glycan_compositions(self, glycopeptide_ids: Set[int]) -> Tuple[List[GlycanComposition], + List[GlycanCombination]]: + glycan_compositions = dict() + glycan_combinations = dict() + + glycan_combination_ids = set() + for glycopeptide_id in glycopeptide_ids: + gc_comb_id = self._get_glycan_combination_for_glycopeptide(glycopeptide_id) + glycan_combination_ids.add(gc_comb_id) + + for i in glycan_combination_ids: + gc_comb = self.glycopeptide_db.query(GlycanCombination).get(i) + glycan_combinations[gc_comb.id] = gc_comb + + for composition in gc_comb.components: + glycan_compositions[composition.id] = composition + + return list(glycan_compositions.values()), list(glycan_combinations.values()) + + def _get_peptide_id_for_glycopeptide(self, glycopeptide_id: int) -> int: + db_glycopeptide = self.glycopeptide_db.query(Glycopeptide).get(glycopeptide_id) + return db_glycopeptide.peptide_id + + def fetch_peptides(self, glycopeptide_ids: Set[int]) -> List[Peptide]: + peptides = set() + for glycopeptide_id in glycopeptide_ids: + peptide_id = self._get_peptide_id_for_glycopeptide(glycopeptide_id) + peptides.add(peptide_id) + + return slurp(self.glycopeptide_db, Peptide, peptides) + + def fetch_proteins(self, peptide_set: List[Peptide]) -> List[Protein]: + proteins = set() + for peptide in peptide_set: + proteins.add(peptide.protein_id) + return slurp(self.glycopeptide_db, Protein, proteins) + + def fetch_glycopeptides(self, glycopeptide_ids: Set[int]) -> List[Glycopeptide]: + return slurp(self.glycopeptide_db, Glycopeptide, glycopeptide_ids) + + def _migrate_single_glycopeptide(self, glycopeptide: Glycopeptide) -> int: + """""" + Stupendously slow if used in bulk, intended for recovering from cases where + a single glycopeptide somehow slipped through the cracks. + """""" + gp = self.glycopeptide_db.query(Glycopeptide).get(id) + self._glycopeptide_hypothesis_migrator.migrate_glycopeptide(gp) + return self._glycopeptide_hypothesis_migrator.glycopeptide_id_map[glycopeptide.id] + + def create_analysis(self): + self._analysis_serializer = AnalysisSerializer( + self._original_connection, + analysis_name=self._seed_analysis_name, + sample_run_id=self._sample_migrator.sample_run_id) + + self._analysis_serializer.set_analysis_type( + AnalysisTypeEnum.glycopeptide_lc_msms.name) + + self._analysis_serializer.set_peak_lookup_table( + self._sample_migrator.peak_id_map) + + # Patch the in-memory objects to be mapped through to the new database keyspace + self.update_glycopeptide_ids() + + # Free up memory from the glycopeptide identity map + self._glycopeptide_hypothesis_migrator.clear() + self._analysis_serializer.save_glycopeptide_identification_set( + self._identified_glycopeptide_set) + + for chroma in self._unassigned_chromatogram_set: + self._analysis_serializer.save_unidentified_chromatogram_solution( + chroma) + + self.log(""Committing Analysis"") + self._analysis_serializer.commit() + + +class DynamicGlycopeptideMSMSAnalysisSerializer(GlycopeptideMSMSAnalysisSerializer): + def _get_glycan_combination_for_glycopeptide(self, glycopeptide_id) -> int: + return glycopeptide_id.glycan_combination_id + + def _get_peptide_id_for_glycopeptide(self, glycopeptide_id) -> int: + return glycopeptide_id.peptide_id + + def fetch_glycopeptides(self, glycopeptide_ids) -> List[Glycopeptide]: + aggregate = dict() + for gp in self._identified_glycopeptide_set: + for solution_set in gp.spectrum_matches: + for match in solution_set: + aggregate[match.target.id] = match.target + out = [] + for i, obj in enumerate(aggregate.values(), 1): + inst = Glycopeptide( + id=obj.id, + peptide_id=obj.id.peptide_id, + glycan_combination_id=obj.id.glycan_combination_id, + protein_id=obj.id.protein_id, + hypothesis_id=obj.id.hypothesis_id, + glycopeptide_sequence=obj.get_sequence(), + calculated_mass=obj.total_mass, + formula=formula(obj.total_composition())) + out.append(inst) + return out + + def _migrate_single_glycopeptide(self, glycopeptide: Glycopeptide) -> int: + inst = Glycopeptide( + id=glycopeptide.id, + peptide_id=glycopeptide.id.peptide_id, + glycan_combination_id=glycopeptide.id.glycan_combination_id, + protein_id=glycopeptide.id.protein_id, + hypothesis_id=glycopeptide.id.hypothesis_id, + glycopeptide_sequence=glycopeptide.get_sequence(), + calculated_mass=glycopeptide.total_mass, + formula=formula(glycopeptide.total_composition())) + self._glycopeptide_hypothesis_migrator.migrate_glycopeptide(inst) + self._glycopeptide_hypothesis_migrator.commit() + return self._glycopeptide_hypothesis_migrator.glycopeptide_id_map[glycopeptide.id] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/database/analysis/__init__.py",".py","335","12","from .analysis_migration import ( + GlycanCompositionChromatogramAnalysisSerializer, + GlycopeptideMSMSAnalysisSerializer, + DynamicGlycopeptideMSMSAnalysisSerializer) + + +__all__ = [ + ""GlycopeptideMSMSAnalysisSerializer"", + ""DynamicGlycopeptideMSMSAnalysisSerializer"", + ""GlycanCompositionChromatogramAnalysisSerializer"" +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/grid_search.py",".py","25377","696","from collections import OrderedDict, namedtuple +import re +from typing import Dict, List, Tuple + +import numpy as np + +from scipy import sparse + +from matplotlib import pyplot as plt + +from ms_deisotope.feature_map.profile_transform import peak_indices +from glycresoft.composition_distribution_model.observation import GlycanCompositionSolutionRecord + +from glycresoft.task import log_handle +from glycresoft.database.composition_network.graph import CompositionGraph + +from .constants import DEFAULT_RHO +from .laplacian_smoothing import LaplacianSmoothingModel + + +class NetworkReduction(object): + r""""""A mapping-like ordered data structure that maps score thresholds to + :class:`NetworkTrimmingSolution` instances produced at that score. Used + for selecting the optimal smoothing factor :math:`\lambda` and during the + grid search for finding the optimal score threshold. + + Attributes + ---------- + store : :class:`~.OrderedDict` + The storage mapping score to solution + """""" + + store: OrderedDict + _invalidated: bool + + def __init__(self, store=None): + if store is None: + store = OrderedDict() + self.store = store + self._invalidated = True + self._resort() + + def getkey(self, key): + """"""Get the solution whose score threshold matches ``key`` + + Parameters + ---------- + key : float + The score threshold + + Returns + ------- + :class:`NetworkTrimmingSolution` + """""" + return self.store[key] + + def getindex(self, ix): + """"""Get the ``ix``th solution, regardless of threshold value + + Parameters + ---------- + ix : int + The index to return + + Returns + ------- + :class:`NetworkTrimmingSolution` + """""" + return self.getkey(list(self.store.keys())[ix]) + + def searchkey(self, value): + """"""Search for the solution whose score threshold + is closest to ``value`` + + Parameters + ---------- + value : float + The threshold to search for + + Returns + ------- + :class:`NetworkTrimmingSolution` + """""" + if self._invalidated: + self._resort() + array = list(self.store.keys()) + ix = self.binsearch(array, value) + key = array[ix] + return self.getkey(key) + + def put(self, key, value): + self.store[key] = value + self._invalidated = True + + def _resort(self): + self.store = OrderedDict((key, self[key]) for key in sorted(self.store.keys())) + self._invalidated = False + + def __getitem__(self, key): + return self.getkey(key) + + def __setitem__(self, key, value): + self.put(key, value) + + def __iter__(self): + return iter(self.store.values()) + + def __len__(self): + return len(self.store) + + @staticmethod + def binsearch(array, value): + lo = 0 + hi = len(array) + i = 0 + while (hi - lo) != 0: + i = (hi + lo) // 2 + x = array[i] + if abs(x - value) < 1e-3: + return i + elif (hi - lo) == 1: + return i + elif x < value: + lo = i + elif x > value: + hi = i + return i + + def plot(self, ax=None, **kwargs): + if ax is None: + fig, ax = plt.subplots(1) + x = self.store.keys() + y = [v.optimal_lambda for v in self.store.values()] + ax.plot(x, y, **kwargs) + xbound = ax.get_xlim() + ybound = ax.get_ylim() + ax.scatter(x, y) + ax.set_xlim(*xbound) + ax.set_ylim(*ybound) + ax.set_xlabel(r""$S_o$ Threshold"", fontsize=18) + ax.set_ylabel(r""Optimal $\lambda$"", fontsize=18) + return ax + + def minimum_threshold_for_lambda(self, lmbda_target): + best = None + for value in reversed(self.store.values()): + if best is None: + best = value + continue + if abs(best.optimal_lambda - lmbda_target) >= abs(value.optimal_lambda - lmbda_target): + if value.threshold < best.threshold: + best = value + return best + + def press_weighted_mean_threshold(self): + vals = list(self) + return np.average(np.array( + [v.threshold for v in vals]), weights=np.array( + [v.press_residuals.min() for v in vals])) + + def keys(self): + return self.store.keys() + + +class NetworkTrimmingSearchSolution(object): + r""""""Hold all the information for the grid search over the smoothing factor + :math:`\lambda` at score threshold :attr:`threshold`. + + Attributes + ---------- + lambda_values : :class:`np.ndarray` + The :math:`\lambda` searched over + minimum_residuals : float + The smallest PRESS residuals + model : :class:`~.LaplacianSmoothingModel` + The smoothing model used for producing these estimates + network : :class:`~.CompositionGraph` + The network structure retained at :attr:`threshold` + observed : list + The graph nodes considered observed at this threshold + optimal_lambda : float + The best :math:`\lambda` value selected by minimizing the PRESS + optimal_tau : :class:`np.ndarray` + The value of :math:`\tau` for the best value of :math:`\lambda` + press_residuals : :class:`np.ndarray` + The PRESS at each value of :math:`\lambda` + taus : list + The :class:`np.ndarray` for each value of :math:`\lambda` + threshold : float + The score threshold used to produce this trimmed network + updated : bool + Whether or not this model has changed since the last threshold + """""" + + threshold: float + updated: bool + observed: List[GlycanCompositionSolutionRecord] + + minimum_residuals: float + press_residuals: np.ndarray + + optimal_lambda: float + lambda_values: np.ndarray + + optimal_tau: np.ndarray + taus: List[np.ndarray] + + model: LaplacianSmoothingModel + network: CompositionGraph + + + + def __init__(self, threshold, lambda_values, press_residuals, network, observed=None, + updated=None, taus=None, model=None): + self.threshold = threshold + self.lambda_values = lambda_values + self.press_residuals = press_residuals + self.network = network + self.taus = taus + optimal_ix = np.argmin(self.press_residuals) + self.optimal_lambda = self.lambda_values[optimal_ix] + self.optimal_tau = self.taus[optimal_ix] + self.minimum_residuals = self.press_residuals.min() + self.observed = observed + self.updated = updated + self.model = model + + @property + def n_kept(self): + return len(self.network) + + @property + def n_edges(self): + return len(self.network.edges) + + @property + def opt_lambda(self): + return self.optimal_lambda + + def __repr__(self): + min_press = min(self.press_residuals) + opt_lambda = self.optimal_lambda + return ""NetworkTrimmingSearchSolution(%f, %d, %0.3f -> %0.3e)"" % ( + self.threshold, self.n_kept, opt_lambda, min_press) + + def copy(self): + dup = self.__class__( + self.threshold, + self.lambda_values.copy(), + self.press_residuals.copy(), + self.network.clone(), + self.observed.copy(), + list(self.updated), + list(self.taus), + self.model) + return dup + + def plot(self, ax=None, **kwargs): + if ax is None: + fig, ax = plt.subplots(1) + ax.plot(self.lambda_values, self.press_residuals, **kwargs) + ax.set_xlabel(r""$\lambda$"") + ax.set_ylabel(r""Summed $PRESS$ Residual"") + return ax + + +GridSearchSolution = namedtuple(""GridSearchSolution"", ( + ""tau_sequence"", ""tau_magnitude"", ""thresholds"", ""apexes"", + ""target_thresholds"")) + + + +class GridPointTextCodec(object): + version_code = 1 + + def __init__(self, cls_type=None): + if cls_type is None: + cls_type = GridPointSolution + self.cls_type = cls_type + + def load(self, fp): + state = ""BETWEEN"" + threshold = 0 + lmbda = 0 + tau = [] + belongingness_matrix = [] + variance_matrix_tags = {} + neighborhood_names = [] + node_names = [] + version_code = self.version_code + + for line_number, line in enumerate(fp): + line = line.strip(""\n\r"") + if line.startswith("";version=""): + version_code = int(line.split(""="", 1)[1]) + if line.startswith("";""): + continue + if line.startswith(""threshold:""): + threshold = float(line.split("":"")[1]) + if state in (""TAU"", ""BELONG""): + state = ""BETWEEN"" + elif line.startswith(""lambda:""): + lmbda = float(line.split("":"")[1]) + if state in (""TAU"", ""BELONG""): + state = ""BETWEEN"" + elif line.startswith(""tau:""): + state = ""TAU"" + elif line.startswith(""belongingness:""): + state = ""BELONG"" + elif line.startswith(""variance:""): + state = ""VARIANCE"" + elif line.startswith(""\t"") or line.startswith("" ""): + if state == ""TAU"": + try: + _, name, value = re.split(r""\t|\s{2,}"", line) + except ValueError as e: + print(line_number, line) + raise e + tau.append(float(value)) + neighborhood_names.append(name) + elif state == ""BELONG"": + try: + _, name, values = re.split(r""\t|\s{2,}"", line) + except ValueError as e: + print(line_number, line) + raise e + belongingness_matrix.append([float(t) for t in values.split("","")]) + node_names.append(name) + elif state == 'VARIANCE': + try: + _, tag, values = re.split(r""\t|\s{2,}"", line) + values = list(map(float, values.split("",""))) + variance_matrix_tags[tag] = values + except ValueError as e: + print(line_number, line) + raise e + else: + state = ""BETWEEN"" + if variance_matrix_tags: + vmat_shape = [int(p) for p in variance_matrix_tags['shape']] + variance_matrix = np.zeros(vmat_shape) + row_ix = np.array(variance_matrix_tags['rows'], dtype=int) + col_ix = np.array(variance_matrix_tags['cols'], dtype=int) + variance_matrix[row_ix, col_ix] = variance_matrix_tags['data'] + else: + variance_matrix = None + + return self.cls_type(threshold, lmbda, np.array(tau, dtype=np.float64), + np.array(belongingness_matrix, dtype=np.float64), + neighborhood_names=neighborhood_names, + node_names=node_names, variance_matrix=variance_matrix) + + def dump(self, obj, fp): + fp.write("";version=%s\n"" % self.version_code) + fp.write(""threshold: %f\n"" % (obj.threshold,)) + fp.write(""lambda: %f\n"" % (obj.lmbda,)) + fp.write(""tau:\n"") + for i, t in enumerate(obj.tau): + fp.write(""\t%s\t%f\n"" % (obj.neighborhood_names[i], t,)) + fp.write(""belongingness:\n"") + for g, row in enumerate(obj.belongingness_matrix): + fp.write(""\t%s\t"" % (obj.node_names[g])) + for i, a_ij in enumerate(row): + if i != 0: + fp.write("","") + fp.write(""%f"" % (a_ij,)) + fp.write(""\n"") + fp.write(""variance:\n"") + var_coords = sparse.coo_matrix(obj.variance_matrix) + fp.write('\tshape\t%s\n' % (','.join(map(str, var_coords.shape)))) + fp.write(""\trow\t%s\n"" % (','.join(map(str, var_coords.row)))) + fp.write(""\tcol\t%s\n"" % (','.join(map(str, var_coords.col)))) + fp.write(""\tdata\t%s\n"" % (','.join(map(str, var_coords.data)))) + return fp + + +class GridPointSolution(object): + threshold: float + lmbda: float + + tau: np.ndarray + belongingness_matrix: np.ndarray + variance_matrix: np.ndarray + + # Label arrays + neighborhood_names: np.ndarray + node_names: np.ndarray + + def __init__(self, threshold, lmbda, tau, belongingness_matrix, neighborhood_names, node_names, + variance_matrix=None): + if variance_matrix is None: + variance_matrix = np.identity(len(node_names), dtype=np.float64) + self.threshold = threshold + self.lmbda = lmbda + self.tau = np.array(tau, dtype=np.float64) + self.belongingness_matrix = np.array(belongingness_matrix, dtype=np.float64) + self.neighborhood_names = np.array(neighborhood_names) + self.node_names = np.array(node_names) + self.variance_matrix = np.array(variance_matrix, dtype=np.float64) + + def __eq__(self, other): + ac = np.allclose + match = ac(self.threshold, other.threshold) and ac(self.lmbda, other.lmbda) and ac( + self.tau, other.tau) and ac(self.belongingness_matrix, other.belongingness_matrix) and ac( + self.variance_matrix, other.variance_matrix) + if not match: + return match + match = np.all(self.node_names == other.node_names) and np.all( + self.neighborhood_names == other.neighborhood_names) + return match + + def __ne__(self, other): + return not (self == other) + + def __repr__(self): + return ""GridPointSolution(threshold=%0.3f, lmbda=%0.3f, tau=%r)"" % ( + self.threshold, self.lmbda, self.tau) + + def clone(self): + return self.__class__( + self.threshold, + self.lmbda, + self.tau.copy(), + self.belongingness_matrix.copy(), + self.neighborhood_names.copy(), + self.node_names.copy(), + self.variance_matrix.copy()) + + def reindex(self, model: LaplacianSmoothingModel): + node_indices, node_names = self._build_node_index_map(model) + tau_indices = self._build_neighborhood_index_map(model) + + self.belongingness_matrix = self.belongingness_matrix[node_indices, :][:, tau_indices] + self.tau = self.tau[tau_indices] + self.variance_matrix = self.variance_matrix[node_indices, node_indices] + + self.neighborhood_names = model.neighborhood_names + self.node_names = node_names + + def _build_node_index_map(self, model: LaplacianSmoothingModel) -> Tuple[List[int], List[str]]: + name_to_new_index: Dict[str, int] = dict() + name_to_old_index: Dict[str, int] = dict() + for i, node_name in enumerate(self.node_names): + name_to_old_index[node_name] = i + name_to_new_index[node_name] = model.network[node_name].index + assert len(name_to_new_index) == len(self.node_names) + ordering = [None for i in range(len(self.node_names))] + new_name_order = [None for i in range(len(self.node_names))] + for name, new_index in name_to_new_index.items(): + old_index = name_to_old_index[name] + ordering[new_index] = old_index + new_name_order[new_index] = name + for x in ordering: + assert x is not None + return ordering, new_name_order + + def _build_neighborhood_index_map(self, model: LaplacianSmoothingModel) -> List[int]: + tau_indices = [model.neighborhood_names.index(name) for name in self.neighborhood_names] + return tau_indices + + def dump(self, fp, codec=None): + if codec is None: + codec = GridPointTextCodec() + codec.dump(self, fp) + return fp + + @classmethod + def load(cls, fp, codec=None): + if codec is None: + codec = GridPointTextCodec(cls) + inst = codec.load(fp) + return inst + + +class NetworkSmoothingModelSolutionBase(object): + def __init__(self, model): + self.model = model + + def _get_default_solution(self, *args, **kwargs): + raise NotImplementedError() + + def estimate_phi_observed(self, solution=None, remove_threshold=True, rho=DEFAULT_RHO): + if solution is None: + solution = self._get_default_solution(rho=rho) + if remove_threshold: + self.model.reset() + return self.model.optimize_observed_scores( + solution.lmbda, solution.belongingness_matrix[self.model.obs_ix, :].dot(solution.tau)) + + def estimate_phi_missing(self, solution=None, remove_threshold=True, observed_scores=None): + if solution is None: + solution = self._get_default_solution() + if remove_threshold: + self.model.reset() + if observed_scores is None: + observed_scores = self.estimate_phi_observed( + solution=solution, remove_threshold=False) + t0 = self.model.A0.dot(solution.tau) + tm = self.model.Am.dot(solution.tau) + return self.model.compute_missing_scores(observed_scores, t0, tm) + + def annotate_network(self, solution=None, remove_threshold=True, include_missing=True): + if solution is None: + solution = self._get_default_solution() + if remove_threshold: + self.model.reset() + observed_scores = self.estimate_phi_observed(solution, remove_threshold=False) + + if include_missing: + missing_scores = self.estimate_phi_missing( + solution, remove_threshold=False, + observed_scores=observed_scores) + + network = self.model.network.clone() + network.neighborhoods = self.model.neighborhood_walker.neighborhoods.clone() + for i, ix in enumerate(self.model.obs_ix): + network[ix].score = observed_scores[i] + + if include_missing: + for i, ix in enumerate(self.model.miss_ix): + network[ix].score = missing_scores[i] + network[ix].marked = True + + return network + + +class ThresholdSelectionGridSearch(NetworkSmoothingModelSolutionBase): + def __init__(self, model, network_reduction=None, apex_threshold=0.95, threshold_bias=4.0): + super(ThresholdSelectionGridSearch, self).__init__(model) + self.network_reduction = network_reduction + self.apex_threshold = apex_threshold + self.threshold_bias = float(threshold_bias) + if self.threshold_bias < 1: + raise ValueError(""Threshold Bias must be 1 or greater"") + + def _get_default_solution(self, *args, **kwargs): + return self.average_solution(*args, **kwargs) + + def has_reduction(self): + return self.network_reduction is not None and bool(self.network_reduction) + + def explore_grid(self): + if self.network_reduction is None: + self.network_reduction = self.model.find_threshold_and_lambda( + rho=DEFAULT_RHO, threshold_step=0.1, fit_tau=True) + log_handle.log(""... Exploring Grid Landscape"") + stack = [] + tau_magnitude = [] + thresholds = [] + + for level in self.network_reduction: + thresholds.append(level.threshold) + + # Pull the distribution slightly to the right + bias_shift = 1 - (1 / self.threshold_bias) + # Reduces the influence of the threshold + bias_scale = self.threshold_bias + + for level in self.network_reduction: + stack.append(np.array(level.taus).mean(axis=0)) + tau_magnitude.append( + np.abs(level.optimal_tau).sum() * ( + (level.threshold / bias_scale) + bias_shift) + ) + tau_magnitude = np.array(tau_magnitude) + if len(tau_magnitude) == 0: + # No solutions, so these will be empty + return GridSearchSolution(stack, tau_magnitude, thresholds, np.array([]), thresholds) + elif len(tau_magnitude) <= 2: + apex = np.argmax(tau_magnitude) + elif len(tau_magnitude) > 2: + apex = peak_indices(tau_magnitude) + if len(apex) == 0: + apex = np.array([np.argmax(tau_magnitude)]) + + thresholds = np.array(thresholds) + apex_threshold = tau_magnitude[apex].max() * self.apex_threshold + if apex_threshold != 0: + apex = apex[(tau_magnitude[apex] > apex_threshold)] + else: + # The tau threshold may be 0, in which case any point will do, but this + # solution carries no generalization. + apex = apex[(tau_magnitude[apex] >= apex_threshold)] + target_thresholds = [t for t in thresholds[apex]] + solution = GridSearchSolution(stack, tau_magnitude, thresholds, apex, target_thresholds) + log_handle.log(""... %d Candidate Solutions"" % (len(target_thresholds),)) + return solution + + def _get_solution_states(self): + solution = self.explore_grid() + states = [] + for i, t in enumerate(solution.target_thresholds): + states.append(self.network_reduction.searchkey(t)) + return states + + def _get_estimate_for_state(self, state, rho=DEFAULT_RHO, lmbda=None): + # Get optimal value of lambda based on + # the PRESS for this group + if lmbda is None: + i = np.argmin(state.press_residuals) + lmbda = state.lambda_values[i] + + # Removes rows from A0 + self.model.set_threshold(state.threshold) + + tau = self.model.estimate_tau_from_S0(rho, lmbda) + A = self.model.normalized_belongingness_matrix.copy() + + # Restore removed rows from A0 + self.model.remove_belongingness_patch() + + variance_matrix = np.identity(len(self.model.network)) * 0 + variance_matrix[self.model.obs_ix, self.model.obs_ix] = np.diag(self.model.variance_matrix) + + return GridPointSolution(state.threshold, lmbda, tau, A, + self.model.neighborhood_names, + self.model.node_names, + variance_matrix=variance_matrix) + + def get_solutions(self, rho=DEFAULT_RHO, lmbda=None): + states = self._get_solution_states() + solutions = [self._get_estimate_for_state( + state, rho=rho, lmbda=lmbda) for state in states] + self.model.reset() + return solutions + + def average_solution(self, rho=DEFAULT_RHO, lmbda=None): + solutions = self.get_solutions(rho=rho, lmbda=lmbda) + if len(solutions) == 0: + return None + tau_acc = np.zeros_like(solutions[0].tau) + lmbda_acc = 0 + thresh_acc = 0 + # variance_matrix = np.zeros_like() + A = np.zeros_like(solutions[0].belongingness_matrix) + for sol in solutions: + thresh_acc += sol.threshold + tau_acc += sol.tau + lmbda_acc += sol.lmbda + A += sol.belongingness_matrix + n = len(solutions) + thresh_acc /= n + tau_acc /= n + lmbda_acc /= n + A /= n + # A = ProportionMatrixNormalization.normalize(A, self.model._belongingness_normalization) + variance_matrix = np.identity(len(self.model.network)) * 0 + variance_matrix[self.model.obs_ix, self.model.obs_ix] = np.diag(self.model.variance_matrix) + average_solution = GridPointSolution( + thresh_acc, lmbda_acc, tau_acc, A, + self.model.neighborhood_names, self.model.node_names, + variance_matrix=variance_matrix) + return average_solution + + def plot(self, ax=None): + if ax is None: + fig, ax = plt.subplots(1) + solution = self.explore_grid() + ax.plot(solution.thresholds, solution.tau_magnitude) + ax.scatter( + solution.thresholds[solution.apexes], + solution.tau_magnitude[solution.apexes]) + ax.set_xlabel(""Threshold"", fontsize=18) + ax.set_ylabel(""Criterion"", fontsize=18) + ax.set_title(""Locate Ideal Threshold\nBy Maximizing ${\\bar \\tau_j}$"", fontsize=28) + ax.set_xticks([x_ for i, x_ in enumerate(solution.thresholds) if i % 5 == 0]) + ax.set_xticklabels([""%0.2f"" % x_ for i, x_ in enumerate(solution.thresholds) if i % 5 == 0], rotation=90) + return ax + + def plot_thresholds(self, ax=None): + if ax is None: + fig, ax = plt.subplots(1) + solution = self.explore_grid() + ax = self.network_reduction.plot(ax) + ax.vlines(solution.thresholds[solution.apexes], 0, 1, color='red') + ax.set_title(""Selected Estimation Points for ${\\bar \\tau}$"", fontsize=28) + return ax + + def fit(self, rho=DEFAULT_RHO, lmbda=None): + solution = self.average_solution(rho=rho, lmbda=lmbda) + if solution is None: + raise ValueError(""Could not fit model. No acceptable solution found."") + return NetworkSmoothingModelFit(self.model, solution) + + +class NetworkSmoothingModelFit(NetworkSmoothingModelSolutionBase): + def __init__(self, model, solution): + super(NetworkSmoothingModelFit, self).__init__(model) + self.solution = solution + + def _get_default_solution(self, *args, **kwargs): + return self.solution + + def __repr__(self): + return ""{self.__class__.__name__}({self.model}, {self.solution})"".format(self=self) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/observation.py",".py","5415","152","from collections import defaultdict, OrderedDict + +import numpy as np +from scipy import linalg + + +class GlycanCompositionSolutionRecord(object): + def __init__(self, glycan_composition, score, total_signal=1.0): + self.glycan_composition = glycan_composition + self.score = score + self.internal_score = self.score + self.total_signal = total_signal + + def __eq__(self, other): + if other is None: + return False + match = self.glycan_composition == other.glycan_composition + if not match: + return match + match = np.isclose(self.score, other.score) + if not match: + return match + match = np.isclose(self.total_signal, other.total_signal) + return match + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return hash(self.glycan_composition) + + @classmethod + def from_chromatogram(cls, solution): + return cls(solution.glycan_composition, solution.score, + solution.total_signal) + + def __repr__(self): + return (""{self.__class__.__name__}({self.glycan_composition}, "" + ""{self.score}, {self.total_signal})"").format(self=self) + + +def is_diagonal(m): + if m.shape[0] != m.shape[1]: + return False + return (np.count_nonzero(m) - np.count_nonzero(np.diag(m))) == 0 + + +class ObservationWeightState(object): + def __init__(self, raw_scores, weight_matrix, observed_indices, size): + self.raw_scores = np.array(raw_scores) + self.weight_matrix = weight_matrix + self.observed_indices = observed_indices + self.size = size + self.variance_matrix = None + self.left_inverse_weight_matrix = None + self.inverse_variance_matrix = None + self.weighted_scores = None + if len(self.raw_scores) == 0: + self.empty() + else: + self.transform() + + def empty(self): + self.variance_matrix = np.array([[]]) + self.left_inverse_weight_matrix = np.array([[]]) + self.inverse_variance_matrix = np.array([[]]) + self.weighted_scores = np.array([]) + + def transform(self): + # This is necessary when the weight matrix is not a square matrix (e.g. the identity matrix) + # and it is *very slow*. Consider fast-pathing the identity matrix case. + w = self.weight_matrix.T.dot(self.weight_matrix) + if is_diagonal(w): + winv = np.diag([1 / i if i != 0 else i for i in np.diag(w)]) + else: + winv = linalg.pinv(w) + self.left_inverse_weight_matrix = winv.dot(self.weight_matrix.T) + self.variance_matrix = self.left_inverse_weight_matrix.dot(self.left_inverse_weight_matrix.T) + self.inverse_variance_matrix = w + self.weighted_scores = self.left_inverse_weight_matrix.dot(self.raw_scores) + self.weighted_scores = self.weighted_scores[np.nonzero(self.weighted_scores)] + + def expand_variance_matrix(self): + V = np.zeros((self.size, self.size)) + V[self.observed_indices, self.observed_indices] = np.diag(self.variance_matrix) + return V + + +class VariableObservationAggregation(object): + def __init__(self, network): + self.aggregation = defaultdict(list) + self.network = network + + def collect(self, observations): + for obs in observations: + self.aggregation[obs.glycan_composition].append(obs) + + def reset(self): + self.aggregation = defaultdict(list) + + @property + def total_observations(self): + q = 0 + for key, values in self.aggregation.items(): + q += len(values) + return q + + def iterobservations(self): + for key, values in sorted(self.aggregation.items(), key=lambda x: self.network[x[0]].index): + for val in values: + yield val + + def observed_indices(self): + indices = {self.network[obs.glycan_composition].index for obs in self.iterobservations()} + return np.array(sorted(indices)) + + def calculate_weight(self, observation): + return 1 + + def build_weight_matrix(self): + q = self.total_observations + p = len(self.network) + weights = np.zeros((q, p)) + for i, obs in enumerate(self.iterobservations()): + weights[i, self.network[obs.glycan_composition].index] = self.calculate_weight(obs) + return weights + + def estimate_summaries(self): + E = self.build_weight_matrix() + scores = [r.score for r in self.iterobservations()] + return ObservationWeightState(scores, E, self.observed_indices(), len(self.network)) + + def build_records(self): + observation_weights = self.estimate_summaries() + indices = self.observed_indices() + nodes = self.network[indices] + records = [] + indices = [] + for i, node in enumerate(nodes): + rec = GlycanCompositionSolutionRecord( + node.glycan_composition, observation_weights.weighted_scores[i], + sum([rec.total_signal for rec in self.aggregation[node.glycan_composition]]), + ) + records.append(rec) + indices.append(node.index) + return records, observation_weights + + +class AbundanceWeightedObservationAggregation(VariableObservationAggregation): + def calculate_weight(self, observation): + return np.log10(observation.total_signal) / np.log10(1e6) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/prior_distribution.py",".py","3465","113","import numpy as np + +from glycresoft.task import TaskBase + + +class PriorBuilder(object): + + def __init__(self, network): + self.network = network + self.value = np.zeros(len(network)) + + def bias(self, target, v): + ix = self.network[target].index + self.value[ix] += v + return self + + def common(self, v): + self.value += v + return self + + def __getitem__(self, i): + ix = self.network[i].index + return self.value[ix] + + +class CompositionDistributionFit(object): + + def __init__(self, pi, network): + self.pi = pi + self.network = network + + def index_of(self, composition): + return self.network[composition].index + + def __getitem__(self, composition): + return self.pi[self.index_of(composition)] + + def __iter__(self): + for i in range(len(self)): + yield self.network[i], self.pi[i] + + def __len__(self): + return len(self.network) + + def __repr__(self): + return ""CompositionDistributionFit()"" + + +class CompositionDistributionUpdater(TaskBase): + etol = 1e-6 + + def __init__(self, network, solutions, prior=0.01, common_weight=1., precision_scale=1.): + self.network = network + self.solutions = solutions + self.common_weight = common_weight + self.precision_scale = precision_scale + if isinstance(prior, (int, float)): + prior = np.ones(len(network)) * prior + self.prior = prior * precision_scale + common_weight + + # Dirichlet Mean + self.pi0 = self.prior / self.prior.sum() + + self.sol_map = { + sol.composition: sol.score for sol in solutions if sol.composition is not None} + + self.observations = np.array( + [self.sol_map.get(node.composition.serialize(), 0) for node in network.nodes]) + self.iterations = 0 + + def index_of(self, composition): + return self.network[composition].index + + def convergence(self, pi_next, pi_last): + d = np.abs(pi_last).sum() + v = (np.abs(pi_next - pi_last).sum()) / d + return v + + def update_pi(self, pi_array): + pi2 = np.zeros_like(pi_array) + total_score_pi = (self.observations * pi_array).sum() + total_w = ((self.prior - 1).sum() + 1) + for i in range(len(self.prior)): + pi2[i] = ((self.prior[i] - 1) + (self.observations[i] * + pi_array[i]) / total_score_pi) / total_w + assert pi2[i] >= 0, (self.prior[i], pi_array[i]) + return pi2 + + def optimize_pi(self, pi, maxiter=100, **kwargs): + pi_last = pi + pi_next = self.update_pi(pi_last) + + self.iterations = 0 + converging = float('inf') + while converging > self.etol and self.iterations < maxiter: + self.iterations += 1 + if self.iterations % 100 == 0: + self.log(""%f, %d"" % (converging, self.iterations)) + pi_last = pi_next + pi_next = self.update_pi(pi_last) + converging = self.convergence(pi_next, pi_last) + if converging < self.etol: + self.log(""Converged in %d iterations"" % self.iterations) + else: + self.log(""Failed to converge in %d iterations (%f)"" % + (self.iterations, converging)) + + return pi_next + + def fit(self, **kwargs): + return CompositionDistributionFit( + self.optimize_pi(self.pi0, **kwargs), self.network) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/__init__.py",".py","2324","87","from glycresoft.composition_distribution_model.constants import ( + DEFAULT_LAPLACIAN_REGULARIZATION, + DEFAULT_RHO, + RESET_THRESHOLD_VALUE, + NORMALIZATION) + +from glycresoft.composition_distribution_model.graph import ( + laplacian_matrix, + adjacency_matrix, + degree_matrix, + weighted_laplacian_matrix, + weighted_adjacency_matrix, + weighted_degree_matrix, + BlockLaplacian, + network_indices, + scale_network, + assign_network, + make_blocks) + +from glycresoft.composition_distribution_model.laplacian_smoothing import ( + LaplacianSmoothingModel, + ProportionMatrixNormalization, + GroupBelongingnessMatrix, + MatrixEditIndex, + MatrixEditInstruction, + BelongingnessMatrixPatcher) + +from glycresoft.composition_distribution_model.grid_search import ( + NetworkReduction, + NetworkTrimmingSearchSolution, + GridSearchSolution, + GridPointSolution, + ThresholdSelectionGridSearch) + + +from glycresoft.composition_distribution_model.observation import ( + GlycanCompositionSolutionRecord, + VariableObservationAggregation, + AbundanceWeightedObservationAggregation, + ObservationWeightState) + + +from glycresoft.composition_distribution_model.glycome_network_smoothing import ( + GlycomeModel, + smooth_network) + + +from glycresoft.composition_distribution_model.utils import display_table + + +__all__ = [ + ""DEFAULT_LAPLACIAN_REGULARIZATION"", + ""DEFAULT_RHO"", + ""RESET_THRESHOLD_VALUE"", + ""NORMALIZATION"", + ""laplacian_matrix"", + ""adjacency_matrix"", + ""degree_matrix"", + ""weighted_laplacian_matrix"", + ""weighted_adjacency_matrix"", + ""weighted_degree_matrix"", + ""BlockLaplacian"", + ""network_indices"", + ""scale_network"", + ""assign_network"", + ""make_blocks"", + ""LaplacianSmoothingModel"", + ""ProportionMatrixNormalization"", + ""GroupBelongingnessMatrix"", + ""MatrixEditIndex"", + ""MatrixEditInstruction"", + ""BelongingnessMatrixPatcher"", + ""NetworkReduction"", + ""NetworkTrimmingSearchSolution"", + ""GridSearchSolution"", + ""GridPointSolution"", + ""ThresholdSelectionGridSearch"", + ""GlycomeModel"", + ""GlycanCompositionSolutionRecord"", + ""VariableObservationAggregation"", + ""AbundanceWeightedObservationAggregation"", + ""NeighborhoodPrior"", + ""smooth_network"", + ""display_table"", + ""ObservationWeightState"" +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/glycome_network_smoothing.py",".py","20184","439","import logging + +import numpy as np + +from glypy import GlycanComposition + +from glycresoft.database.composition_network import ( + CompositionGraphNode, NeighborhoodWalker) + +from glycresoft.task import log_handle + +from .constants import ( + DEFAULT_LAPLACIAN_REGULARIZATION, + NORMALIZATION, + DEFAULT_RHO, + RESET_THRESHOLD_VALUE) + +from .laplacian_smoothing import LaplacianSmoothingModel, ProportionMatrixNormalization + +from .graph import ( + BlockLaplacian, + assign_network, + network_indices, + weighted_laplacian_matrix) + +from .grid_search import ( + NetworkReduction, + NetworkTrimmingSearchSolution, + ThresholdSelectionGridSearch) + +from .observation import ( + GlycanCompositionSolutionRecord, + VariableObservationAggregation) + +from .utils import fast_positive_definite_inverse + +logger = logging.getLogger(""glycresoft.glycome_network_smoothing"") +logger.addHandler(logging.NullHandler()) + + +def _has_glycan_composition(x): + try: + gc = x.glycan_composition + return gc is not None + except AttributeError: + return False + + +class GlycomeModel(LaplacianSmoothingModel): + """"""An implementation of the Glycan Network Smoothing by Laplacian Regularization. + + Attributes + ---------- + block_L: :class:`~.BlockLaplacian` + The block-oriented version of the Weighted Laplacian matrix of :attr:`network` + network: :class:`~.CompositionGraph` + A graph of glycan compositions that has been annotated by their observation confidence. + This network may be pruned during the course of model fitting. The original network is + always available under :attr:`_network`. + observed_compositions: list of :class:`~.GlycanCompositionSolutionRecord` + The observed and scored glycan compositions. These may not be unique, and will be + summarized prior to being projected onto the network by :attr:`observation_aggregator`. + This list may be truncated during the course of model fitting. The original list is always + available under :attr:`_observed_compositions`. + threshold: float + The current threshold applied to the observed score. This value may change during model + fitting. + belongingness_matrix: np.ndarray[float, ndim=2] + A C by N matrix where C is the number of glycan compositions in the network and N is the + number of neighborhoods over the network, with the value at [i, j] corresponding to how much + C_i belongs to N_j. This value is not normalized, see :attr:`normalized_belongingness_matrix`. + normalized_belongingness_matrix: np.ndarray[float, ndim=2] + A normalized version of :attr:`belongingness_matrix`, which follows the normalization paradigm + given by :attr:`_belongingness_normalization` + A0: :class:`np.ndarray[float, ndim=2]` + The subset of :attr:`normalized_belongingness_matrix` corresponding to :attr:`observed_compositions` + Am: :class:`np.ndarray[float, ndim=2]` + The subset of :attr:`normalized_belongingness_matrix` corresponding to nodes in :attr:`network` that + are not in :attr:`observed_compositions` + S0: :class:`np.ndarray[float]` + The summarized scores of the observed nodes in :attr:`network` + C0: list of :class:`CompositionGraphNode` + The observed nodes in :attr:`network` + obs_ix: :class:`np.ndarray[int]` + The indices into :attr:`network` that were observed + miss_ix: :class:`np.ndarray[int]` + The indices into :attr:`network` that were not observed + summarized_state: :class:`~.ObservationWeightState` + A helper intermediary which holds the transformation from :attr:`observed_compositions` + to :attr:`S0`, :attr:`variance_matrix` and :attr:`inverse_variance_matrix` + variance_matrix: :class:`np.ndarray[float, ndim=2]` + The variance of the observed scores, as estimated by :attr:`observation_aggregator` + from :attr:`observed_compositions`. + inverse_variance_matrix: :class:`np.ndarray[float, ndim=2]` + The inverse of :attr:`variance_matrix`, computed separately for efficiency. + """""" + def __init__(self, observed_compositions, network, belongingness_matrix=None, + regularize=DEFAULT_LAPLACIAN_REGULARIZATION, + belongingness_normalization=NORMALIZATION, + observation_aggregator=VariableObservationAggregation): + self.observation_aggregator = observation_aggregator + observed_compositions = [ + o for o in observed_compositions if _has_glycan_composition(o) and o.score > 0] + self._observed_compositions = observed_compositions + self._configure_with_network(network) + if len(self.miss_ix) == 0: + self._network.add_node(CompositionGraphNode(GlycanComposition(), -1), reindex=True) + self._configure_with_network(self._network) + + self.block_L = BlockLaplacian(self.network, regularize=regularize) + self.threshold = self.block_L.threshold + + # Initialize Names + self.normalized_belongingness_matrix = None + self.A0 = None + self._belongingness_normalization = None + self.S0 = np.array([]) + self.C0 = [] + self.variance_matrix = None + self.inverse_variance_matrix = None + + # Expensive Step + if belongingness_matrix is None: + self.belongingness_matrix = self.build_belongingness_matrix() + else: + self.belongingness_matrix = np.array(belongingness_matrix) + + # Normalize and populate + self.normalize_belongingness(belongingness_normalization) + self._populate(self._observed_compositions) + + def _configure_with_network(self, network): + self._network = network + self.network = assign_network(network.clone(), self._observed_compositions) + + self.neighborhood_walker = NeighborhoodWalker(self.network) + + self.neighborhood_names = self.neighborhood_walker.neighborhood_names() + self.node_names = [str(node) for node in self._network] + + self.obs_ix, self.miss_ix = network_indices(self.network) + + def __reduce__(self): + return self.__class__, ( + self._observed_compositions, self._network, self.belongingness_matrix, + self.block_L.regularize, self._belongingness_normalization, + self.observation_aggregator) + + def _populate(self, observations): + var_agg = self.observation_aggregator(self._network) + var_agg.collect(observations) + aggregated_observations, summarized_state = var_agg.build_records() + self.network = assign_network(self._network.clone(), aggregated_observations) + self.obs_ix, self.miss_ix = network_indices(self.network) + + self.A0 = self.normalized_belongingness_matrix[self.obs_ix, :] + self.Am = self.normalized_belongingness_matrix[self.miss_ix, :] + self.S0 = np.array([g.score for g in self.network[self.obs_ix]]) + self.C0 = ([g for g in self.network[self.obs_ix]]) + self.summarized_state = summarized_state + self.variance_matrix = np.diag(summarized_state.variance_matrix[self.obs_ix, self.obs_ix]) + self.inverse_variance_matrix = np.diag(summarized_state.inverse_variance_matrix[self.obs_ix, self.obs_ix]) + + def set_threshold(self, threshold): + accepted = [ + g for g in self._observed_compositions if g.score > threshold] + if len(accepted) == 0: + raise ValueError(""Threshold %f produces an empty observed set"" % (threshold,)) + self._populate(accepted) + self.block_L = BlockLaplacian(self.network, threshold=threshold, regularize=self.block_L.regularize) + self.threshold = self.block_L.threshold + + def reset(self): + self.set_threshold(RESET_THRESHOLD_VALUE) + + def normalize_belongingness(self, method=NORMALIZATION): + self.normalized_belongingness_matrix = ProportionMatrixNormalization.normalize( + self.belongingness_matrix, method) + self._belongingness_normalization = method + self.A0 = self.normalized_belongingness_matrix[self.obs_ix, :] + + def apply_belongingness_patch(self): + updated_belongingness = self.get_belongingness_patch() + self.normalized_belongingness_matrix = updated_belongingness + self.A0 = self.normalized_belongingness_matrix[self.obs_ix, :] + + def remove_belongingness_patch(self): + self.normalized_belongingness_matrix = ProportionMatrixNormalization.normalize( + self.belongingness_matrix, self._belongingness_normalization) + self.A0 = self.normalized_belongingness_matrix[self.obs_ix, :] + + def sample_tau(self, rho, lmda): + sigma_est = np.std(self.S0) + mu_tau = self.estimate_tau_from_S0(rho, lmda) + return np.random.multivariate_normal(mu_tau, np.eye(len(mu_tau)).dot(sigma_est ** 2)) + + def sample_phi_given_tau(self, tau, lmda): + return np.random.multivariate_normal(self.A0.dot(tau), (1. / lmda) * self.L_oo_inv) + + def find_optimal_lambda(self, rho, lambda_max=1, step=0.01, threshold=0.0001, fit_tau=True, + drop_missing=True, renormalize_belongingness=NORMALIZATION): + obs = [] + missed = [] + network = self.network.clone() + for node in network: + if node.score < threshold: + missed.append(node) + node.marked = True + else: + obs.append(node.score) + lambda_values = np.arange(0.01, lambda_max, step) + press = [] + if drop_missing: + for node in missed: + network.remove_node(node, limit=5) + # The network passed into LaplacianSmoothingModel will have its indices changed, + # and will not match the ordering of the belongingness matrix, so make sure the + # observed indices are aligned. + obs_ix, _miss_ix = network_indices(network) + wpl = weighted_laplacian_matrix(network) + lum = LaplacianSmoothingModel( + network, self.normalized_belongingness_matrix[obs_ix, :], threshold, + neighborhood_walker=self.neighborhood_walker, + belongingness_normalization=renormalize_belongingness, + variance_matrix=self.variance_matrix) + ident = np.eye(wpl.shape[0]) + for lambd in lambda_values: + if fit_tau: + tau = lum.estimate_tau_from_S0(rho, lambd) + else: + tau = np.zeros(self.A0.shape[1]) + T = lum.optimize_observed_scores(lambd, lum.A0.dot(tau)) + A = ident + lambd * wpl + # H = np.linalg.inv(A) + H = fast_positive_definite_inverse(A) + press_value = sum( + ((obs - T) / (1 - (np.diag(H) - np.finfo(float).eps))) ** 2) / len(obs) + press.append(press_value) + return lambda_values, np.array(press) + + def find_threshold_and_lambda(self, rho, lambda_max=1., lambda_step=0.02, threshold_start=0., + threshold_step=0.2, fit_tau=True, drop_missing=True, + renormalize_belongingness=NORMALIZATION): + r'''Iterate over score thresholds and smoothing factors (lambda), sampling points + from the parameter grid and computing the PRESS residual at each point. + + This produces a :class:`NetworkReduction` data structure recording the results for + later local maximum detection. + + Parameters + ---------- + rho: float + The scale of the variance of the observed score + lambda_max: float + The maximum value of lambda to consider on the grid + lambda_step: float + The size of the change in lambda at each iteration + threshold_start: float + The minimum observed score threshold to start the grid search at + threshold_step: float + The size of the change in the observed score threshold at each iteration + fit_tau: bool + Whether or not to estimate :math:`\tau` for each iteration when computing + the PRESS + drop_missing: bool + Whether or not to remove nodes from the graph which are not observed above + the threshold, restructuring the graph, which in turn changes the Laplacian. + renormalize_belongingness: str + A string constant which names the belongingness normalization technique to + use. + + Returns + ------- + :class:`NetworkReduction`: + The recorded grid of sampled points and snapshots of the model at each point + ''' + solutions = NetworkReduction() + limit = max(self.S0) + start = max(min(self.S0) - 1e-3, threshold_start) + current_network = self.network.clone() + thresholds = np.arange(start, limit, threshold_step) + last_solution = None + last_raw_observations = None + last_aggregate = None + for i_threshold, threshold in enumerate(thresholds): + if i_threshold % 10 == 0: + logger.info(""... Threshold = %r (%0.2f%%)"" % ( + threshold, (100.0 * i_threshold / len(thresholds)))) + # Aggregate the raw observations into averaged, variance reduced records + # and annotate the network with these new scores + raw_observations = [c for c in self._observed_compositions if c.score > threshold] + + # cache on the explicit raw observations used because the step size may be smaller than + # the next highest difference, and aggregating observations can be expensive. There is + # no solution to the general problem as it calls for inverting a potentially large matrix + # to only be used in this loop. + if raw_observations == last_raw_observations: + observations, summarized_state, obs_ix = last_aggregate # pylint: disable=unpacking-non-sequence + else: + agg = self.observation_aggregator(self.network) + agg.collect(raw_observations) + + observations, summarized_state = agg.build_records() + obs_ix = agg.observed_indices() + last_aggregate = (observations, summarized_state, obs_ix) + last_raw_observations = raw_observations + + # Extract pre-calculated variance matrices + variance_matrix = summarized_state.variance_matrix + inverse_variance_matrix = summarized_state.inverse_variance_matrix + variance_matrix = np.diag(variance_matrix[obs_ix, obs_ix]) + inverse_variance_matrix = np.diag(inverse_variance_matrix[obs_ix, obs_ix]) + + # clear the scores from the network + current_network = current_network.clone() + for node in current_network: + node.score = 0 + node.internal_score = 0 + + # assign aggregated scores to the network + network = assign_network(current_network, observations) + + # Filter the network, marking nodes for removal and recording observed + # nodes for future use. + obs = [] + missed = [] + for i, node in enumerate(network): + if node.score < threshold: + missed.append(node) + node.marked = True + else: + obs.append(node.score) + if len(obs) == 0: + break + obs = np.array(obs) + press = [] + + if drop_missing: + # drop nodes whose score does not exceed the threshold + for node in missed: + network.remove_node(node, limit=5) + + if last_solution is not None: + # If after pruning the network, no new nodes have been removed, + # the optimal solution won't have changed from previous iteration + # so just reuse the solution + if last_solution.network == network: + current_solution = last_solution.copy() + current_solution.threshold = threshold + solutions[threshold] = current_solution + last_solution = current_solution + current_network = network + continue + wpl = weighted_laplacian_matrix(network) + ident = np.eye(wpl.shape[0]) + + # The network passed into LaplacianSmoothingModel will have its indices changed, + # and will not match the ordering of the belongingness matrix, so make sure the + # observed indices are aligned. + lum = LaplacianSmoothingModel( + network, self.normalized_belongingness_matrix[obs_ix, :], threshold, + neighborhood_walker=self.neighborhood_walker, + belongingness_normalization=renormalize_belongingness, + variance_matrix=variance_matrix, + inverse_variance_matrix=inverse_variance_matrix) + updates = [] + taus = [] + lambda_values = np.arange(0.01, lambda_max, lambda_step) + for lambd in lambda_values: + if fit_tau: + tau = lum.estimate_tau_from_S0(rho, lambd) + else: + tau = np.zeros(self.A0.shape[1]) + T = lum.optimize_observed_scores(lambd, lum.A0.dot(tau)) + A = ident + lambd * wpl + + # H = np.linalg.inv(A) + H = fast_positive_definite_inverse(A) + diag_H = np.diag(H) + if len(diag_H) != len(T): + diag_H = diag_H[lum.obs_ix] + assert len(diag_H) == len(T) + + press_value = sum( + ((obs - T) / (1 - (diag_H - np.finfo(float).eps))) ** 2) / len(obs) + press.append(press_value) + updates.append(T) + taus.append(tau) + current_solution = NetworkTrimmingSearchSolution( + threshold, lambda_values, np.array(press), network, np.array(obs), + updates, taus, lum) + + solutions[threshold] = current_solution + last_solution = current_solution + current_network = network + return solutions + + +def smooth_network(network, observed_compositions, threshold_step=0.5, apex_threshold=0.95, + belongingness_matrix=None, rho=DEFAULT_RHO, lambda_max=1, + include_missing=False, lmbda=None, model_state=None, + observation_aggregator=VariableObservationAggregation, + belongingness_normalization=NORMALIZATION, annotate_network=True): + convert = GlycanCompositionSolutionRecord.from_chromatogram + observed_compositions = [ + convert(o) for o in observed_compositions if _has_glycan_composition(o)] + model = GlycomeModel( + observed_compositions, network, + belongingness_matrix=belongingness_matrix, + observation_aggregator=observation_aggregator, + belongingness_normalization=belongingness_normalization) + # Deadlock? + logger.info(""... Begin Model Fitting"") + if model_state is None: + reduction = model.find_threshold_and_lambda( + rho=rho, threshold_step=threshold_step, + lambda_max=lambda_max) + if len(reduction) == 0: + logger.info(""... No Network Reduction Found"") + return None, None, None + search = ThresholdSelectionGridSearch(model, reduction, apex_threshold) + params = search.average_solution(lmbda=lmbda) + if params is None: + logger.info(""... No Acceptable Solution. Could not fit model."") + return None, None, None + else: + search = ThresholdSelectionGridSearch(model, None, apex_threshold) + model_state.reindex(model) + params = model_state + if lmbda is not None: + params.lmbda = lmbda + if annotate_network: + logger.info(""... Projecting Solution Onto Network"") + annotated_network = search.annotate_network(params, include_missing=include_missing) + else: + annotated_network = None + + return annotated_network, search, params +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/constants.py",".py","112","6"," +DEFAULT_LAPLACIAN_REGULARIZATION = 1.0 +DEFAULT_RHO = 0.1 +RESET_THRESHOLD_VALUE = 1e-3 +NORMALIZATION = 'colrow' +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/utils.py",".py","1420","48","from __future__ import print_function + +import numpy as np +from scipy.linalg import lapack + + +def display_table(names, values, sigfig=3, filter_empty=1, print_fn=None): + if print_fn is None: + print_fn = print + values = np.array(values) + maxlen = len(max(names, key=len)) + 2 + fstring = (""%%0.%df"" % sigfig) + for i in range(len(values)): + if values[i, :].sum() or not filter_empty: + print_fn(names[i].ljust(maxlen) + ('|'.join([fstring % f for f in values[i, :]]))) + + +# Cholesky decomposition-based inverse based upon +# https://stackoverflow.com/a/58719188/1137920 + +inds_cache = {} + + +def _upper_triangular_to_symmetric(ut: np.ndarray): + n = ut.shape[0] + try: + inds = inds_cache[n] + except KeyError: + inds = np.tri(n, k=-1, dtype=bool) + inds_cache[n] = inds + ut[inds] = ut.T[inds] + + +def fast_positive_definite_inverse(M: np.ndarray) -> np.ndarray: + if M.size == 0: + return np.zeros_like(M) + + # Compute the Cholesky decomposition of a symmetric positive-definite matrix + cholesky, info = lapack.dpotrf(M) + if info != 0: + raise ValueError('dpotrf failed on input {}'.format(M)) + # Compute the inverse of `M` from its Cholesky decomposition + inv, info = lapack.dpotri(cholesky) + if info != 0: + raise ValueError('dpotri failed on input {}'.format(cholesky)) + _upper_triangular_to_symmetric(inv) + return inv +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/laplacian_smoothing.py",".py","16924","453","# -*- coding: utf-8 -*- + +from collections import namedtuple, OrderedDict +from typing import List, Tuple + +from six import string_types as basestring + +import numpy as np +from scipy import linalg +from matplotlib import pyplot as plt + +from glypy import GlycanComposition +from glycopeptidepy.structure.glycan import GlycanCompositionProxy + +from glycresoft.database.composition_network import ( + NeighborhoodWalker, CompositionGraphNode, CompositionGraph) + +from .constants import DEFAULT_LAPLACIAN_REGULARIZATION, NORMALIZATION +from .graph import network_indices, BlockLaplacian + + +class LaplacianSmoothingModel(object): + r'''A model that uses a graphical representation of a set of related entities + to estimate a connectedness-aware version of a quality score :math:`s`. + + The `Graph Laplacian `_ is used + to summarize the connectedness of nodes in the graph. + + Related subgraphs are further organized into neighborhoods, as defined by + :attr:`neighborhood_walker`'s rules. These groups are expected to trend together, + sharing a parameter :math:`\tau`. A single vertex in the graph can belong to multiple + neighborhoods to different extents, having a belongingness weight for each neighborhood + encoded in a belongingness matrix :math:`\mathbf{A}`. + ''' + + network: CompositionGraph + neighborhood_walker: NeighborhoodWalker + + belongingness_matrix: np.ndarray + variance_matrix: np.ndarray + inverse_variance_matrix: np.ndarray + + block_L: BlockLaplacian + obs_ix: np.ndarray + miss_ix: np.ndarray + + S0: np.ndarray + A0: np.ndarray + Am: np.ndarray + + C0: List[CompositionGraphNode] + + threshold: float + regularize: float + + _belongingness_normalization: str + + def __init__(self, network, belongingness_matrix, threshold, + regularize=DEFAULT_LAPLACIAN_REGULARIZATION, neighborhood_walker=None, + belongingness_normalization=NORMALIZATION, variance_matrix=None, + inverse_variance_matrix=None): + self.network = network + + if neighborhood_walker is None: + self.neighborhood_walker = NeighborhoodWalker(self.network) + else: + self.neighborhood_walker = neighborhood_walker + + self.belongingness_matrix = belongingness_matrix + self.threshold = threshold + + self.obs_ix, self.miss_ix = network_indices(self.network, self.threshold) + self.block_L = BlockLaplacian( + self.network, threshold, regularize=regularize) + + self.S0 = np.array([node.score for node in self.network[self.obs_ix]]) + self.A0 = belongingness_matrix[self.obs_ix, :] + self.Am = belongingness_matrix[self.miss_ix, :] + self.C0 = [node for node in self.network[self.obs_ix]] + + self._belongingness_normalization = belongingness_normalization + if variance_matrix is None: + variance_matrix = np.eye(len(self.S0)) + self.variance_matrix = variance_matrix + if inverse_variance_matrix is None: + inverse_variance_matrix = np.eye(len(self.S0)) + self.inverse_variance_matrix = inverse_variance_matrix + + def __reduce__(self): + return self.__class__, ( + self.network, self.belongingness_matrix, self.threshold, + self.block_L.regularize, self.neighborhood_walker, + self._belongingness_normalization, self.variance_matrix, + self.inverse_variance_matrix) + + @property + def L_mm_inv(self) -> np.ndarray: + return self.block_L.L_mm_inv + + @property + def L_oo_inv(self) -> np.ndarray: + return self.block_L.L_oo_inv + + def optimize_observed_scores(self, lmda: float, t0: np.ndarray=0) -> np.ndarray: + blocks = self.block_L + # Here, V_inv is the inverse of V, which is the inverse of the variance matrix + V_inv = self.variance_matrix + L = lmda * V_inv.dot(blocks[""oo""] - blocks[""om""].dot(self.L_mm_inv).dot(blocks[""mo""])) + B = np.identity(len(self.S0)) + L + return np.linalg.inv(B).dot(self.S0 - t0) + t0 + + def compute_missing_scores(self, observed_scores: np.ndarray, t0=0., tm=0.) -> np.ndarray: + blocks = self.block_L + return -linalg.inv(blocks['mm']).dot(blocks['mo']).dot(observed_scores - t0) + tm + + def compute_projection_matrix(self, lmbda) -> np.ndarray: + A = np.eye(self.L_oo_inv.shape[0]) + self.L_oo_inv * (1. / lmbda) + H = np.linalg.pinv(A) + return H + + def compute_press(self, observed: np.ndarray, updated: np.ndarray, projection_matrix: np.ndarray) -> np.ndarray: + press = np.sum(((observed - updated) / ( + 1 - (np.diag(projection_matrix) - np.finfo(float).eps))) ** 2) / len(observed) + return press + + def estimate_tau_from_S0(self, rho: float, lmda: float, sigma2: float=1.0) -> np.ndarray: + X = ((rho / sigma2) * self.variance_matrix) + ( + (1. / (lmda * sigma2)) * self.L_oo_inv) + self.A0.dot(self.A0.T) + X = np.linalg.pinv(X) + return self.A0.T.dot(X).dot(self.S0) + + def estimate_phi_given_S_parameters(self, lmbda: float, tau: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + r""""""Estimate the parameters of the conditional distribution :math:`\phi|s` + according to [1]_. + + Notes + ----- + According to [1]_, given + .. math:: + + y | \theta_1 \sim & \mathcal{N}\left(\mathbf{A_1}\theta_1, \mathbf{C_1}\right) \\ + + \theta_1 \sim & \mathcal{N}\left(\mathbf{A_2}\theta_2, \mathbf{C_2}\right) \\ + + \theta_1 | y \sim & \mathcal{N}\left(\mathbf{B}b, \mathbf{B}\right) \\ + + \mathbf{B^{-1}} = & \mathbf{C_2}^{-1} + \mathbf{A_1}^t\mathbf{C_1}^{-1}\mathbf{A_1} \\ + b = & \mathbf{A_1}^t\mathbf{C_1}^{-1}y + \mathbf{C_2}^{-1}\mathbf{A_2}\theta_2 + + In terms of the network smoothing model, this translates to + + .. math:: + + \mathbf{B^{-1}} = & \lambda\mathbf{L} + \tilde{A}^t\Sigma^{-1}\tilde{A}\\ + = & \lambda \mathbf{L} + \begin{bmatrix} \Sigma_{oo}^{-1} & 0 \\ 0 & 0 \end{bmatrix} \\ + + b = & \tilde{A}^t\Sigma^{-1}s + \lambda\mathbf{L}\mathbf{A}\tau \\ + = & \begin{bmatrix}\Sigma_{oo}^{-1}s \\ 0\end{bmatrix} + \lambda\begin{bmatrix}L_{oo}A\tau_o + + L_{om}A\tau_m \\L_{mo}A\tau_o + L_{mm}A\tau_m\end{bmatrix}\\\\ + + Parameters + ---------- + lmbda : float + The smoothing factor + tau : np.ndarray + The mean of :math:`\phi`, :math:`\mathbf{A}\tau` + + Returns + ------- + Bb: np.ndarray + The mean vector of :math:`\phi|s` + B: np.ndarray: + The variance matrix of :math:`\phi|s` + + References + ---------- + .. [1] Lindley, D. V., & Smith, A. F. M. (1972). Bayes Estimates for the Linear Model. + Royal Statistical Society, 34(1), 1–41. + """""" + B_inv = lmbda * self.block_L.matrix + B_inv[self.obs_ix, self.obs_ix] += np.diag(self.inverse_variance_matrix) + B = linalg.inv(B_inv) + + Alts = np.zeros(len(self.network)) + Alts[self.obs_ix] = self.S0.dot(self.inverse_variance_matrix) + lambda_Lw_Atau = lmbda * self.block_L.matrix.dot(self.normalized_belongingness_matrix.dot(tau)) + b = Alts + lambda_Lw_Atau + phi_given_s = np.dot(B, b) + return phi_given_s, B + + def build_belongingness_matrix(self) -> np.ndarray: + belongingness_matrix = self.neighborhood_walker.build_belongingness_matrix() + return belongingness_matrix + + def get_belongingness_patch(self) -> np.ndarray: + updated_belongingness = BelongingnessMatrixPatcher.patch(self) + updated_belongingness = ProportionMatrixNormalization.normalize( + updated_belongingness, self._belongingness_normalization) + return updated_belongingness + + def apply_belongingness_patch(self): + updated_belongingness = self.get_belongingness_patch() + self.belongingness_matrix = updated_belongingness + self.A0 = self.belongingness_matrix[self.obs_ix, :] + + +class SmoothedScoreSample(object): + def __init__(self, model, lmbda, tau, size=10000, random_state=None): + if random_state is None: + random_state = np.random.RandomState() + self.model = model + self.lmbda = lmbda + self.tau = tau + self.size = size + self.Bb, self.B = self.model.estimate_phi_given_S_parameters(lmbda, tau) + self.B_inv = np.linalg.pinv(self.B) + self.random_state = random_state + self.samples = np.array([]) + self.resample() + + def resample(self): + self.samples = self.random_state.multivariate_normal(self.Bb, self.B, size=self.size) + # alternatively, sample unit variance scaled by the cholesky decomposition of the covariance + # matrix to get the sample variance + # C = linalg.cholesky(self.B) + # self.samples = np.array( + # [self.Bb + C.T.dot(self.random_state.normal(size=C.shape[0])) for i in range(self.size)]) + return self + + def _get_index(self, glycan_composition): + node = self.model.network[glycan_composition] + index = node.index + return index + + def _score_index(self, index): + return self.Bb[index] + + def _gaussian_pdf(self, x, mu, sigma, sigma_inv): + d = (x - mu) + e = np.exp((-0.5 * (d) * sigma_inv * d)) + return e / np.sqrt(2 * np.pi * sigma) + + def score(self, glycan_composition): + index = self._get_index(glycan_composition) + return self._score_index(index) + + def plot_distribution(self, glycan_composition, ax=None): + if ax is None: + fig, ax = plt.subplots(1) + index = self._get_index(glycan_composition) + node = self.model.network[index] + s = self.samples[:, index] + bins = np.arange(0, self.Bb[index] * 2, .1) + ax.hist(s, bins=bins, alpha=0.5, density=True, label=""%s (%f)"" % (node, self.score(glycan_composition))) + ax.set_xlabel(r""Resampled $\phi$"", fontsize=24) + ax.set_ylabel(""Density"", fontsize=24) + return ax + + +class ProportionMatrixNormalization(object): + def __init__(self, matrix): + self.matrix = np.array(matrix) + + def normalize_columns(self): + self.matrix = self.matrix / self.matrix.sum(axis=0) + + def normalize_rows(self): + normalizer = self.matrix.sum(axis=1).reshape((-1, 1)) + normalizer[normalizer == 0] = 1e-6 + self.matrix = self.matrix / normalizer + + def normalize_columns_and_rows(self): + self.normalize_columns() + self.clean() + self.normalize_rows() + + def normalize_columns_scaled(self, scaler=2.0): + self.normalize_columns() + self.matrix = self.matrix * scaler + + def clean(self): + self.matrix[np.isnan(self.matrix)] = 0.0 + + def __array__(self): + return self.matrix + + @classmethod + def normalize(cls, matrix, method='colrow'): + self = cls(matrix) + if method == 'col': + self.normalize_columns() + elif method == 'row': + self.normalize_rows() + elif method == 'colrow': + self.normalize_columns_and_rows() + elif method is not None and method.startswith(""col"") and method[3:4].isdigit(): + scale = float(method[3:]) + self.normalize_columns_scaled(scale) + elif method == 'none' or method is None: + pass + else: + raise ValueError(""Unknown Normalization Method %r"" % method) + self.clean() + return self.matrix + + +class GroupBelongingnessMatrix(object): + _node_like = (basestring, CompositionGraphNode, + GlycanComposition, GlycanCompositionProxy) + + @classmethod + def from_model(cls, model, normalized=True): + if normalized: + mat = model.normalized_belongingness_matrix + else: + mat = model.belongingness_matrix + groups = model.neighborhood_walker.neighborhood_names() + members = model.network.nodes + return cls(mat, groups, members) + + def __init__(self, belongingness_matrix, groups, members): + self.belongingness_matrix = np.array(belongingness_matrix) + self.groups = [str(x) for x in groups] + self.members = [str(x) for x in members] + self._column_indices = OrderedDict([(k, i) for i, k in enumerate(self.groups)]) + self._member_indices = OrderedDict([(k, i) for i, k in enumerate(self.members)]) + + def _column_indices_by_name(self, names): + if isinstance(names, basestring): + names = [names] + indices = [self._column_indices[n] for n in names] + return indices + + def _member_indices_by_name(self, names): + if isinstance(names, self._node_like): + names = [names] + indices = [self._member_indices[n] for n in names] + return indices + + def _coerce_member(self, names): + if isinstance(names, self._node_like): + names = [names] + return names + + def _coerce_column(self, names): + if isinstance(names, basestring): + names = [names] + return names + + def get(self, rows=None, cols=None): + matrix = self.belongingness_matrix + if rows is not None: + rows = self._coerce_member(rows) + row_ix = self._member_indices_by_name(rows) + matrix = matrix[row_ix, :] + else: + rows = self.members + if cols is not None: + cols = self._coerce_column(cols) + col_ix = self._column_indices_by_name(cols) + matrix = matrix[:, col_ix] + else: + cols = self.groups + return self.__class__(matrix, cols, rows) + + def getindex(self, rows=None, cols=None): + if rows is not None: + rows = self._coerce_member(rows) + row_ix = self._member_indices_by_name(rows) + else: + row_ix = None + if cols is not None: + cols = self._coerce_column(cols) + col_ix = self._column_indices_by_name(cols) + else: + col_ix = None + return row_ix, col_ix + + def __getitem__(self, ij): + return self.belongingness_matrix[ij] + + def __setitem__(self, ij, val): + self.belongingness_matrix[ij] = val + + def __array__(self): + return np.array(self.belongingness_matrix) + + def __repr__(self): + column_label_width = max(map(len, self.groups)) + row_label_width = max(map(len, self.members)) + rows = [] + top_row = [' ' * row_label_width] + for col in self.groups: + top_row.append(col.center(column_label_width)) + rows.append('|'.join(top_row)) + for i, member in enumerate(self.members): + row = [member.ljust(row_label_width)] + vals = self.belongingness_matrix[i, :] + for val in vals: + row.append((""%0.3f"" % val).center(column_label_width)) + rows.append(""|"".join(row)) + return '\n'.join(rows) + + +MatrixEditIndex = namedtuple(""MatrixEditIndex"", (""row_index"", ""col_index"", ""action"")) +MatrixEditInstruction = namedtuple(""MatrixEditInstruction"", (""composition"", ""neighborhood"", ""action"")) + + +class BelongingnessMatrixPatcher(object): + def __init__(self, model): + self.model = model + self.A0 = model.A0 + self.belongingness_matrix = GroupBelongingnessMatrix.from_model( + model, normalized=False) + + def find_singleton_neighborhoods(self): + n_cols = self.A0.shape[1] + edits = [] + for i in range(n_cols): + # We have a neighborhood with only one member + col = self.A0[:, i] + mask = col > 0 + if mask.sum() == 1: + j = np.argmax(mask) + edit = MatrixEditIndex(j, i, 'delete') + edits.append(edit) + return edits + + def transform_index_to_key(self, edits): + neighborhood_names = self.model.neighborhood_walker.neighborhood_names() + out = [] + for edit in edits: + key = str(self.model.C0[edit.row_index]) + neighborhood = neighborhood_names[edit.col_index] + out.append(MatrixEditInstruction(key, neighborhood, edit.action)) + return out + + def patch_belongingness_matrix(self, edits): + gbm = self.belongingness_matrix + instructions = self.transform_index_to_key(edits) + for instruction in instructions: + ij = gbm.getindex(instruction.composition, instruction.neighborhood) + if instruction.action == 'delete': + gbm[ij] = 0 + return gbm + + @classmethod + def patch(cls, model): + inst = cls(model) + targets = inst.find_singleton_neighborhoods() + out = inst.patch_belongingness_matrix(targets) + return np.array(out) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/graph.py",".py","5483","175","from typing import Dict +import numpy as np +from scipy import linalg + +from glycresoft.database.composition_network.graph import CompositionGraph + +from .constants import DEFAULT_LAPLACIAN_REGULARIZATION +from .utils import fast_positive_definite_inverse + +def adjacency_matrix(network): + A = np.zeros((len(network), len(network))) + for edge in network.edges: + i, j = edge.node1.index, edge.node2.index + A[i, j] = 1 + A[j, i] = 1 + for i in range(A.shape[0]): + A[i, i] = 0 + return A + + +def weighted_adjacency_matrix(network): + A = np.zeros((len(network), len(network))) + A[:] = 1. / float('inf') + for edge in network.edges: + i, j = edge.node1.index, edge.node2.index + A[i, j] = edge.weight + A[j, i] = edge.weight + for i in range(A.shape[0]): + A[i, i] = 0 + return A + + +def degree_matrix(network): + degrees = [len(n.edges) for n in network] + return np.diag(degrees) + + +def weighted_degree_matrix(network): + degrees = [sum(e.weight for e in n.edges) for n in network] + return np.diag(degrees) + + +def laplacian_matrix(network): + return degree_matrix(network) - adjacency_matrix(network) + + +def weighted_laplacian_matrix(network): + return weighted_degree_matrix(network) - weighted_adjacency_matrix(network) + + +def assign_network(network, observed, copy=True): + if copy: + network = network.clone() + solution_map = {} + for case in observed: + if case.glycan_composition is None: + continue + s = solution_map.get(case.glycan_composition) + if s is None or s.score < case.score: + solution_map[case.glycan_composition] = case + + for node in network.nodes: + node.score = 0 + + for composition, solution in solution_map.items(): + try: + node = network[composition] + node.score = solution.score + except KeyError: + # Not all exact compositions have nodes + continue + return network + + +def network_indices(network, threshold=0.0001): + missing = [] + observed = [] + for node in network: + if node.score < threshold: + missing.append(node.index) + else: + observed.append(node.index) + return np.array(observed, dtype=int), np.array(missing, dtype=int) + + +def make_blocks(network, observed, threshold=0.0001, regularize=DEFAULT_LAPLACIAN_REGULARIZATION): + network = assign_network(network, observed) + return BlockLaplacian(network, threshold, regularize) + + +def _reference_compute_missing_scores(blocks, observed_scores, t0=0., tm=0.): + return -linalg.inv(blocks['mm']).dot(blocks['mo']).dot(observed_scores - t0) + tm + + +def _reference_optimize_observed_scores(blocks, lmbda, observed_scores, t0=0.): + S = lmbda * (blocks[""oo""] - blocks[""om""].dot(linalg.inv( + blocks['mm'])).dot(blocks[""mo""])) + B = np.eye(len(observed_scores)) + S + return linalg.inv(B).dot(observed_scores - t0) + t0 + + +def scale_network(network, maximum): + relmax = max([n.score for n in network.nodes]) + for node in network.nodes: + node.score = node.score / relmax * maximum + return network + + +def _key_from_memory(data: np.ndarray): + return bytes(data.data) + + +class BlockLaplacian(object): + regularize: float + threshold: float + + obs_ix: np.ndarray + miss_ix: np.ndarray + + matrix: np.ndarray + blocks: Dict[str, np.ndarray] + L_mm_inv: np.ndarray + L_oo_inv: np.ndarray + + def __init__(self, network=None, threshold=0.0001, regularize=1.0): + self.regularize = regularize + self.threshold = threshold + if network is not None: + self._build_from_network(network) + + def _build_from_network(self, network: CompositionGraph): + structure_matrix = weighted_laplacian_matrix(network) + structure_matrix = structure_matrix + (np.eye( + structure_matrix.shape[0]) * self.regularize) + observed_indices, missing_indices = network_indices(network, self.threshold) + + self.obs_ix = observed_indices + self.miss_ix = missing_indices + + self.matrix = structure_matrix + # Compute Schur Complement + if network.cache_state: + key = _key_from_memory(self.obs_ix) + if key in network.cache_state: + self.blocks, self.L_mm_inv, self.L_oo_inv = network.cache_state[key] + else: + self._complement() + network.cache_state[key] = self.blocks, self.L_mm_inv, self.L_oo_inv + else: + self._complement() + + def _blocks_from(self, matrix): + oo_block = matrix[self.obs_ix, :][:, self.obs_ix] + om_block = matrix[self.obs_ix, :][:, self.miss_ix] + mo_block = matrix[self.miss_ix, :][:, self.obs_ix] + mm_block = matrix[self.miss_ix, :][:, self.miss_ix] + return {""oo"": oo_block, ""om"": om_block, ""mo"": mo_block, ""mm"": mm_block} + + def _complement(self): + '''Compute the Schur complement of the observed/unobserved blocked Laplacian + matrix. + ''' + self.blocks = self._blocks_from(self.matrix) + self.L_mm_inv = fast_positive_definite_inverse(self['mm']) + self.L_oo_inv = np.linalg.pinv( + self[""oo""] - (self['om'].dot(self.L_mm_inv).dot(self['mo']))) + + def __getitem__(self, k): + return self.blocks[k] + + def __repr__(self): + return ""BlockLaplacian(%s)"" % (', '.join({ + ""%s: %r"" % (k, v.shape) for k, v in self.blocks.items() + })) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/site_model/glycosite_model.py",".py","4991","163","import json +import io + +from typing import Dict, List, NamedTuple + +import numpy as np + +from glypy.structure.glycan_composition import HashableGlycanComposition + +MINIMUM = 1e-4 + + +glycan_composition_cache = dict() +decoy_glycan_cache = dict() + +def parse_glycan_composition(string: str) -> HashableGlycanComposition: + try: + return glycan_composition_cache[string] + except KeyError: + gc = HashableGlycanComposition.parse(string) + glycan_composition_cache[string] = gc + return gc + + +def to_decoy_glycan(string: str) -> HashableGlycanComposition: + try: + return decoy_glycan_cache[string] + except KeyError: + gc = HashableGlycanComposition.parse(string) + gc[""#decoy#""] = 2 + decoy_glycan_cache[string] = gc + return gc + + +def is_decoy_glycan(string): + return ""#decoy#"" in string + + +class GlycanPriorRecord(NamedTuple): + score: float + matched: bool + + +try: + from glycresoft._c.composition_distribution_model.utils import GlycanPriorRecord +except ImportError: + pass + + +class GlycosylationSiteModel(object): + protein_name: str + position: int + site_distribution: Dict[str, float] + lmbda: float + glycan_map: Dict[HashableGlycanComposition, GlycanPriorRecord] + + def __init__(self, protein_name, position, site_distribution, lmbda, glycan_map): + self.protein_name = protein_name + self.position = position + self.site_distribution = site_distribution + self.lmbda = lmbda + self.glycan_map = glycan_map + + def __getitem__(self, key: HashableGlycanComposition) -> float: + return self.glycan_map[key][0] + + def get_record(self, key: HashableGlycanComposition) -> GlycanPriorRecord: + try: + return self.glycan_map[key] + except KeyError: + return GlycanPriorRecord(MINIMUM, False) + + def __eq__(self, other): + if self.protein_name != other.protein_name: + return False + if self.position != other.position: + return False + if not np.isclose(self.lmbda, other.lmbda): + return False + if self.site_distribution != other.site_distribution: + return False + if self.glycan_map != other.glycan_map: + return False + return True + + def __ne__(self, other): + return not (self == other) + + def to_dict(self): + d = {} + d['protein_name'] = self.protein_name + d['position'] = self.position + d['lmbda'] = self.lmbda + d['site_distribution'] = dict(**self.site_distribution) + d['glycan_map'] = { + str(k): (v.score, v.matched) for k, v in self.glycan_map.items() + } + return d + + @classmethod + def from_dict(cls, d: dict): + name = d['protein_name'] + position = d['position'] + lmbda = d['lmbda'] + try: + site_distribution = d['site_distribution'] + except KeyError: + site_distribution = d['tau'] + glycan_map = d['glycan_map'] + glycan_map = { + parse_glycan_composition(k): GlycanPriorRecord(v[0], v[1]) + for k, v in glycan_map.items() + } + inst = cls(name, position, site_distribution, lmbda, glycan_map) + return inst + + def pack(self, inplace=True): + if inplace: + self._pack() + return self + return self.copy()._pack() + + def _pack(self): + new_map = {} + for key, value in self.glycan_map.items(): + if value.score > MINIMUM: + new_map[key] = value + self.glycan_map = new_map + return self + + def __repr__(self): + template = ('{self.__class__.__name__}({self.protein_name!r}, {self.position}, ' + '{site_distribution}, {self.lmbda}, <{glycan_map_size} Glycans>)') + glycan_map_size = len(self.glycan_map) + site_distribution = {k: v for k, + v in self.site_distribution.items() if v > 0.0} + return template.format(self=self, glycan_map_size=glycan_map_size, site_distribution=site_distribution) + + def copy(self, deep=False): + dup = self.__class__( + self.protein_name, self.position, self.site_distribution, self.lmbda, self.glycan_map) + if deep: + dup.site_distribution = dup.site_distribution.copy() + dup.glycan_map = dup.glycan_map.copy() + return dup + + def clone(self, *args, **kwargs): + return self.copy(*args, **kwargs) + + def observed_glycans(self, threshold=0): + return {k: v.score for k, v in self.glycan_map.items() if v.matched and v.score > threshold} + + @classmethod + def load(cls, fh: io.TextIOBase) -> List['GlycosylationSiteModel']: + site_dicts = json.load(fh) + site_models = [cls.from_dict(d) for d in site_dicts] + return site_models + + @classmethod + def dump(cls, instances, fh: io.TextIOBase): + site_dicts = [d.to_dict() for d in instances] + json.dump(site_dicts, fh) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/site_model/__init__.py",".py","433","5","from .glycosite_model import GlycanPriorRecord, GlycosylationSiteModel, glycan_composition_cache +from .glycoprotein_model import GlycoproteinSiteSpecificGlycomeModel, ReversedProteinSiteReflectionGlycoproteinSiteSpecificGlycomeModel +from .glycoproteome_model import GlycoproteomeModel, SubstringGlycoproteomeModel, GlycoproteomePriorAnnotator +from .builder import GlycosylationSiteModelBuilder, GlycoproteinSiteModelBuildingWorkflow +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/site_model/builder.py",".py","33990","797","import time +import json +import logging + +from collections import defaultdict, deque, namedtuple + +import multiprocessing +from multiprocessing.pool import ThreadPool +from multiprocessing import Process, Event, JoinableQueue +from multiprocessing.managers import RemoteError + +from queue import Empty as QueueEmptyException +from threading import RLock, Condition, Thread + +import numpy as np + +from glycresoft import serialize +from glycresoft.task import TaskBase, IPCLoggingManager + +from glycresoft.database import ( + GlycanCompositionDiskBackedStructureDatabase, GlycopeptideDiskBackedStructureDatabase) + + +from glycresoft.database.composition_network import NeighborhoodWalker, make_n_glycan_neighborhoods +from glycresoft.composition_distribution_model import ( + smooth_network, display_table, VariableObservationAggregation, + GlycanCompositionSolutionRecord, GlycomeModel) +from glycresoft.models import GeneralScorer, get_feature + + +from .glycosite_model import GlycanPriorRecord, GlycosylationSiteModel +from .glycoprotein_model import ProteinStub + +_default_chromatogram_scorer = GeneralScorer.clone() +_default_chromatogram_scorer.add_feature(get_feature(""null_charge"")) + +logger = logging.getLogger(""glycresoft.glycosite_model"") +logger.addHandler(logging.NullHandler()) + + +def _truncate_name(name, limit=30): + if len(name) > limit: + return name[:limit - 3] + '...' + return name + + + +class FakeLock: + def __enter__(self): + return self + + def __exit__(self, *args, **kwargs): + pass + + +EmptySite = namedtuple(""EmptySite"", (""position"", ""protein_name"")) + + +class GlycosylationSiteModelBuilder(TaskBase): + _timeout_per_unit = 300 + + def __init__(self, glycan_graph, chromatogram_scorer=None, belongingness_matrix=None, + unobserved_penalty_scale=None, lambda_limit=0.2, + require_multiple_observations=True, + observation_aggregator=None, n_threads=1): + if observation_aggregator is None: + observation_aggregator = VariableObservationAggregation + if chromatogram_scorer is None: + chromatogram_scorer = _default_chromatogram_scorer + if unobserved_penalty_scale is None: + unobserved_penalty_scale = 1.0 + + self.network = glycan_graph + if not self.network.neighborhoods: + self.network.neighborhoods = make_n_glycan_neighborhoods() + + self.chromatogram_scorer = chromatogram_scorer + self.belongingness_matrix = belongingness_matrix + self.observation_aggregator = observation_aggregator + self.require_multiple_observations = require_multiple_observations + self.unobserved_penalty_scale = unobserved_penalty_scale + self.lambda_limit = lambda_limit + + if self.belongingness_matrix is None: + self.belongingness_matrix = self.build_belongingness_matrix() + + self.site_models = [] + self.n_threads = n_threads + self._lock = RLock() if self.n_threads > 1 else FakeLock() + self._concurrent_jobs = 0 + if self.n_threads > 1: + self.thread_pool = ThreadPool(n_threads) + else: + self.thread_pool = None + + def build_belongingness_matrix(self): + network = self.network + neighborhood_walker = NeighborhoodWalker( + network, network.neighborhoods) + belongingness_matrix = neighborhood_walker.build_belongingness_matrix() + return belongingness_matrix + + def _transform_glycopeptide(self, glycopeptide, evaluate_chromatograms=False): + gp = glycopeptide + if evaluate_chromatograms: + ms1_score = self.chromatogram_scorer.logitscore(gp.chromatogram) + else: + ms1_score = gp.ms1_score + return GlycanCompositionSolutionRecord(gp.glycan_composition, ms1_score, gp.total_signal) + + def prepare_glycoprotein(self, glycoprotein, evaluate_chromatograms=False): + prepared = [] + for i, site in enumerate(glycoprotein.site_map['N-Linked'].sites): + gps_for_site = glycoprotein.site_map[ + 'N-Linked'][glycoprotein.site_map['N-Linked'].sites[i]] + gps_for_site = [ + gp for gp in gps_for_site if gp.chromatogram is not None] + + self.log('... %d Identified Glycopeptides At Site %d for %s' % + (len(gps_for_site), site, _truncate_name(glycoprotein.name, ))) + + glycopeptides = [ + gp for gp in gps_for_site if gp.chromatogram is not None] + records = [] + for gp in glycopeptides: + records.append(self._transform_glycopeptide( + gp, evaluate_chromatograms)) + prepared.append((records, site, ProteinStub(glycoprotein.name))) + return prepared + + def add_glycoprotein(self, glycoprotein, evaluate_chromatograms=False): + async_results = [] + sites_to_log = [] + for i, site in enumerate(glycoprotein.site_map['N-Linked'].sites): + gps_for_site = glycoprotein.site_map[ + 'N-Linked'][glycoprotein.site_map['N-Linked'].sites[i]] + gps_for_site = [ + gp for gp in gps_for_site if gp.chromatogram is not None] + + self.log('... %d Identified Glycopeptides At Site %d for %s' % + (len(gps_for_site), site, _truncate_name(glycoprotein.name, ))) + + glycopeptides = [ + gp for gp in gps_for_site if gp.chromatogram is not None] + records = [] + for gp in glycopeptides: + records.append(self._transform_glycopeptide( + gp, evaluate_chromatograms)) + + if self.n_threads == 1: + self.fit_site_model(records, site, glycoprotein) + else: + sites_to_log.append(site) + with self._lock: + self._concurrent_jobs += 1 + async_results.append( + self.thread_pool.apply_async(self.fit_site_model, (records, site, glycoprotein, ))) + if async_results: + time.sleep(20) + for i, result in enumerate(async_results): + if not result.ready(): + self.log(""... Waiting for Result from Site %d of %s"" % ( + sites_to_log[i], _truncate_name(glycoprotein.name, ))) + result.get(self._timeout_per_unit * self.n_threads + 20) + with self._lock: + self._concurrent_jobs -= 1 + with self._lock: + self.log(""... Finished Fitting %s, %d Tasks Pending"" % ( + _truncate_name(glycoprotein.name), self._concurrent_jobs)) + + def _get_learnable_cases(self, observations): + learnable_cases = [rec for rec in observations if rec.score > 1] + if not learnable_cases: + return [] + if self.require_multiple_observations: + agg = VariableObservationAggregation(self.network) + agg.collect(learnable_cases) + recs, var = agg.build_records() + # TODO: Rewrite to avoid using VariableObservationAggregation because calculation + # of the variance matrix is expensive. + # + # Use VariableObservationAggregation algorithm to collect the glycan + # composition observations according to the network definition of multiple + # observations, and then extract the observed indices along the diagonal + # of the variance matrix. + # + # Those indices which are equal to 1.0 are those + # where the glycan composition was only observed once, according to the + # transformation VariableObservationAggregation carries out when estimating + # the variance of each glycan composition observed. + rec_variance = np.diag(var.variance_matrix)[var.observed_indices] + stable_cases = set( + [gc.glycan_composition for gc, v in zip(recs, rec_variance) if v != 1.0]) + self.log(""... %d Stable Glycan Compositions"" % ( + len(stable_cases))) + if len(stable_cases) == 0: + stable_cases = set([gc.glycan_composition for gc in recs]) + self.log(""... No Stable Cases Found. Using %d Glycan Compositions"" % ( + len(stable_cases), )) + if len(stable_cases) == 0: + return [] + else: + stable_cases = { + case.glycan_composition for case in learnable_cases} + learnable_cases = [ + rec for rec in learnable_cases + if rec.score > 1 and rec.glycan_composition in stable_cases + ] + return learnable_cases + + def fit_site_model(self, observations, site, glycoprotein): + learnable_cases = self._get_learnable_cases(observations) + + if not learnable_cases: + return None + + acc = defaultdict(list) + for case in learnable_cases: + acc[case.glycan_composition].append(case) + log_buffer = [] + log_buffer.append(""... %d Glycan Compositions for Site %d of %s"" % ( + len(acc), site, _truncate_name(glycoprotein.name, ))) + # for key, value in sorted(acc.items(), key=lambda x: x[0].mass()): + # log_buffer.append(""... %s: [%s]"" % ( + # key, + # ', '.join([""%0.2f"" % f for f in sorted( + # [r.score for r in value])]) + # )) + # self.log('\n'.join(log_buffer)) + + fitted_network, search_result, params = smooth_network( + self.network, learnable_cases, + belongingness_matrix=self.belongingness_matrix, + observation_aggregator=VariableObservationAggregation, + annotate_network=False) + if params is None: + self.log(""Skipping Site %d of %s"" % + (site, _truncate_name(glycoprotein.name))) + return None + self.log(""... Site %d of %s Lambda: %f"" % + (site, _truncate_name(glycoprotein.name), params.lmbda,)) + display_table([x.name for x in self.network.neighborhoods], + np.array(params.tau).reshape((-1, 1))) + updated_params = params.clone() + updated_params.lmbda = min(self.lambda_limit, params.lmbda) + self.log(""... Projecting Solution Onto Network for Site %d of %s"" % + (site, _truncate_name(glycoprotein.name))) + fitted_network = search_result.annotate_network(updated_params) + for node in fitted_network: + if node.marked: + node.score *= self.unobserved_penalty_scale + + site_distribution = dict( + zip([x.name for x in self.network.neighborhoods], updated_params.tau.tolist())) + glycan_map = { + str(node.glycan_composition): GlycanPriorRecord(node.score, not node.marked) + for node in fitted_network + } + site_model = GlycosylationSiteModel( + glycoprotein.name, + site, + site_distribution, + updated_params.lmbda, + glycan_map) + self.site_models.append(site_model.pack()) + return site_model + + def save_models(self, path): + with open(path, 'wt') as fh: + prepared = [] + for site in sorted(self.site_models, key=lambda x: (x.protein_name, x.position)): + prepared.append(site.to_dict()) + json.dump(prepared, fh) + + +class GlycositeModelBuildingProcess(Process): + process_name = ""glycosylation-site-modeler"" + + def __init__(self, builder, input_queue, output_queue, producer_done_event, output_done_event, log_handler): + Process.__init__(self) + self.builder = builder + self.input_queue = input_queue + self.output_queue = output_queue + self.producer_done_event = producer_done_event + self.output_done_event = output_done_event + self.log_handler = log_handler + + def all_work_done(self): + """"""A helper method to encapsulate :attr:`output_done_event`'s ``is_set`` + method. + + Returns + ------- + bool + """""" + return self.output_done_event.is_set() + + def log(self, message): + """"""Send a normal logging message via :attr:`log_handler` + + Parameters + ---------- + message : str + The message to log + """""" + logger.info(message) + + def debug(self, message): + """"""Send a debugging message via :attr:`log_handler` + + Parameters + ---------- + message : str + The message to log + """""" + logger.debug(message) + + def handle_item(self, observations, site, glycoprotein): + model = self.builder.fit_site_model(observations, site, glycoprotein) + if model is None: + model = EmptySite(site, glycoprotein.name) + self.output_queue.put(model) + # Do not accumulate models within the process + self.builder.site_models = [] + + def task(self): + """"""The worker process's main loop where it will poll for new work items, + process incoming work items and send them back to the master process. + """""" + has_work = True + self.items_handled = 0 + strikes = 0 + self.log_handler.add_handler() + while has_work: + try: + observations, site, glycoprotein = self.input_queue.get(True, 5) + self.input_queue.task_done() + strikes = 0 + except QueueEmptyException: + if self.producer_done_event.is_set(): + has_work = False + break + else: + strikes += 1 + if strikes % 1000 == 0: + self.log(""... %d iterations without work for %r"" % + (strikes, self)) + continue + self.items_handled += 1 + try: + self.handle_item(observations, site, glycoprotein) + except Exception: + import traceback + message = ""An error occurred while processing %r of %r on %r:\n%s"" % ( + site, glycoprotein.name, self, traceback.format_exc()) + self.log(message) + break + self.cleanup() + + def cleanup(self): + self.output_done_event.set() + + def run(self): + new_name = getattr(self, 'process_name', None) + if new_name is not None: + TaskBase().try_set_process_name(new_name) + # The task might actually use the same logger from different threads + # which causes a deadlock. This ""fixes"" that. by writing directly to STDOUT + # at the cost of not being able to write to file instead. + # TaskBase.log_to_stdout() + self.output_done_event.clear() + try: + self.task() + except Exception: + import traceback + self.log(""An exception occurred while executing %r.\n%s"" % ( + self, traceback.format_exc())) + self.cleanup() + + +class GlycoproteinSiteModelBuildingWorkflowBase(TaskBase): + def __init__(self, analyses, glycopeptide_database, glycan_database, + unobserved_penalty_scale=None, lambda_limit=0.2, + require_multiple_observations=True, observation_aggregator=None, + output_path=None, n_threads=None, q_value_threshold=0.05, + network=None, include_decoy_glycans=True): + if observation_aggregator is None: + observation_aggregator = VariableObservationAggregation + if unobserved_penalty_scale is None: + unobserved_penalty_scale = 1.0 + + self.q_value_threshold = q_value_threshold + self.analyses = analyses + self.glycopeptide_database = glycopeptide_database + self.glycan_database = glycan_database + + self.unobserved_penalty_scale = unobserved_penalty_scale + self.lambda_limit = lambda_limit + + self.require_multiple_observations = require_multiple_observations + self.observation_aggregator = observation_aggregator + + self.output_path = output_path + self.network = network + self.include_decoy_glycans = include_decoy_glycans + + @classmethod + def from_paths(cls, analysis_paths_and_ids, glycopeptide_hypothesis_path, glycopeptide_hypothesis_id, + glycan_hypothesis_path, glycan_hypothesis_id, unobserved_penalty_scale=None, + lambda_limit=0.2, require_multiple_observations=True, observation_aggregator=None, + output_path=None, n_threads=4, q_value_threshold=0.05, network=None, include_decoy_glycans=True): + gp_db = GlycopeptideDiskBackedStructureDatabase( + glycopeptide_hypothesis_path, glycopeptide_hypothesis_id) + gc_db = GlycanCompositionDiskBackedStructureDatabase( + glycan_hypothesis_path, glycan_hypothesis_id) + + analyses = [serialize.AnalysisDeserializer(conn, analysis_id=an_id) + for conn, an_id in analysis_paths_and_ids] + inst = cls( + analyses, gp_db, gc_db, unobserved_penalty_scale=unobserved_penalty_scale, + lambda_limit=lambda_limit, require_multiple_observations=require_multiple_observations, + observation_aggregator=observation_aggregator, output_path=output_path, + n_threads=n_threads, q_value_threshold=q_value_threshold, network=network, + include_decoy_glycans=include_decoy_glycans + ) + return inst + + def count_glycosites(self, glycoproteins): + n_sites = sum(len(gp.site_map['N-Linked']) for gp in glycoproteins) + return n_sites + + def make_glycan_network(self): + if self.network is None: + network = self.glycan_database.glycan_composition_network + else: + network = self.network + if self.include_decoy_glycans: + network = network.augment_with_decoys() + network.create_edges() + + model = GlycomeModel([], network) + belongingness_matrix = model.belongingness_matrix + network.neighborhoods = model.neighborhood_walker.neighborhoods + return network, belongingness_matrix + + def load_identified_glycoproteins_from_analysis(self, analysis): + if not isinstance(analysis, serialize.Analysis): + analysis = analysis.analysis + idgps = analysis.aggregate_identified_glycoproteins( + analysis.identified_glycopeptides.filter( + serialize.IdentifiedGlycopeptide.q_value <= self.q_value_threshold)) + return idgps + + def build_reference_protein_map(self): + proteins = list(self.glycopeptide_database.proteins) + index = {p.name: p for p in proteins} + return index + + def aggregate_identified_glycoproteins(self): + acc = defaultdict(list) + n = len(self.analyses) + for i, analysis in enumerate(self.analyses, 1): + self.log(""... Loading Glycopeptides for %s (%d/%d)"" % + (analysis.name, i, n)) + for idgp in self.load_identified_glycoproteins_from_analysis(analysis): + acc[idgp.name].append(idgp) + result = [] + self.log(""Merging Glycoproteins Across Replicates"") + n = float(len(acc)) + i = 1.0 + last = 0.1 + should_log = False + for name, duplicates in acc.items(): + if i / n > last: + should_log = True + last += 0.1 + if i % 100 == 0: + should_log = True + if should_log: + self.log(""... Merging %s (%d/%d, %0.2f%%)"" % + (name, i, n, i * 100.0 / n)) + should_log = False + agg = duplicates[0] + result.append(agg.merge(*duplicates[1:])) + i += 1 + return result + + def _fit_glycoprotein_site_models(self, glycoproteins, builder): + raise NotImplementedError() + + def _init_builder(self, network, belongingness_matrix): + builder = GlycosylationSiteModelBuilder( + network, belongingness_matrix=belongingness_matrix, + unobserved_penalty_scale=self.unobserved_penalty_scale, + lambda_limit=self.lambda_limit, + require_multiple_observations=self.require_multiple_observations, + observation_aggregator=self.observation_aggregator, + n_threads=self.n_threads) + return builder + + def run(self): + self.log(""Building Belongingness Matrix"") + network, belongingness_matrix = self.make_glycan_network() + + builder = self._init_builder(network, belongingness_matrix) + + self.log(""Aggregating Glycoproteins"") + glycoproteins = self.aggregate_identified_glycoproteins() + glycoproteins = sorted( + glycoproteins, + key=lambda x: len(x.identified_glycopeptides), + reverse=True) + + self._fit_glycoprotein_site_models(glycoproteins, builder) + + self.log(""Saving Models"") + if self.output_path is not None: + builder.save_models(self.output_path) + + +class ThreadedGlycoproteinSiteModelBuildingWorkflow(GlycoproteinSiteModelBuildingWorkflowBase): + _timeout_per_unit_site = 300 + + def __init__(self, analyses, glycopeptide_database, glycan_database, + unobserved_penalty_scale=None, lambda_limit=0.2, + require_multiple_observations=True, observation_aggregator=None, + output_path=None, n_threads=4, q_value_threshold=0.05, network=None, include_decoy_glycans=True): + super(ThreadedGlycoproteinSiteModelBuildingWorkflow, self).__init__( + analyses, glycopeptide_database, glycan_database, + unobserved_penalty_scale, lambda_limit, + require_multiple_observations, observation_aggregator, + output_path, q_value_threshold=q_value_threshold, network=network, + include_decoy_glycans=include_decoy_glycans + ) + + self.n_threads = n_threads + self.thread_pool = ThreadPool(self.n_threads) + self._lock = RLock() + self._count_barrier = Condition() + self._concurrent_jobs = 0 + + def thread_pool_saturated(self, ratio=1.0): + with self._lock: + jobs = self._concurrent_jobs + return (jobs / float(self.n_threads)) >= ratio + + def _add_glycoprotein(self, glycoprotein, builder, k_sites): + # Acquire the condition lock, then wait until the thread pool is empty + # enough to do some work, then release the condition lock and do the work + self._count_barrier.acquire() + while self.thread_pool_saturated(): + self._count_barrier.wait() + self._count_barrier.release() + + with self._lock: + self._concurrent_jobs += k_sites + + # This should block until all site model fitting finishes. + builder.add_glycoprotein(glycoprotein) + + with self._lock: + self._concurrent_jobs -= k_sites + + # Acquire the condition lock, wake up the next thread waiting, and release + # the condition lock + self._count_barrier.acquire() + self._count_barrier.notify() + self._count_barrier.release() + + def _fit_glycoprotein_site_models(self, glycoproteins, builder): + n = len(glycoproteins) + n_sites = self.count_glycosites(glycoproteins) + k_sites_acc = 0 + self.log( + ""Analyzing %d glycoproteins with %d occupied N-glycosites"" % (n, n_sites)) + result_collector = deque() + for i, gp in enumerate(glycoproteins, 1): + k_sites = len(gp.site_map[""N-Linked""]) + k_sites_acc += k_sites + self.log(""Building Model for \""%s\"" with %d occupied N-glycosites %d/%d (%0.2f%%, %0.2f%% sites)"" % ( + _truncate_name(gp.name), k_sites, i, n, i * 100.0 / n, k_sites_acc * 100.0 / n_sites)) + if self.n_threads == 1: + builder.add_glycoprotein(gp) + else: + with self._lock: + result = self.thread_pool.apply_async( + self._add_glycoprotein, (gp, builder, k_sites)) + result_collector.append((result, gp, k_sites)) + # sleep briefly to allow newly queued task to start + time.sleep(1) + # If the thread pool is full, we'll stop enqueuing new jobs and wait for it to clear out + if self.thread_pool_saturated(): + while self.thread_pool_saturated(): + running_result, running_gp, running_gp_k_sites = result_collector.popleft() + while running_result.ready() and result_collector: + # get will re-raise errors if they occurred. + running_result.get() + running_result, running_gp, running_gp_k_sites = result_collector.popleft() + if not running_result.ready(): + self.log(""... Awaiting %s with %d Sites"" % ( + _truncate_name(running_gp.name), running_gp_k_sites)) + running_result.get( + self._timeout_per_unit_site * running_gp_k_sites * self.n_threads) + + # Now drain any pending tasks. + while result_collector: + running_result, running_gp, running_gp_k_sites = result_collector.popleft() + while running_result.ready() and result_collector: + # get will re-raise errors if they occurred. + running_result.get() + running_result, running_gp, running_gp_k_sites = result_collector.popleft() + if not running_result.ready(): + self.log(""... Awaiting %s with %d Sites"" % ( + _truncate_name(running_gp.name), running_gp_k_sites)) + running_result.get( + self._timeout_per_unit_site * running_gp_k_sites * self.n_threads) + + +class MultiprocessingGlycoproteinSiteModelBuildingWorkflow(GlycoproteinSiteModelBuildingWorkflowBase): + + def __init__(self, analyses, glycopeptide_database, glycan_database, + unobserved_penalty_scale=None, lambda_limit=0.2, + require_multiple_observations=True, observation_aggregator=None, + output_path=None, n_threads=4, q_value_threshold=0.05, network=None, + include_decoy_glycans=True): + super(MultiprocessingGlycoproteinSiteModelBuildingWorkflow, self).__init__( + analyses, glycopeptide_database, glycan_database, + unobserved_penalty_scale, lambda_limit, + require_multiple_observations, observation_aggregator, + output_path, q_value_threshold=q_value_threshold, network=network, + include_decoy_glycans=include_decoy_glycans + ) + + self.builder = None + + self.input_queue = JoinableQueue(1000) + self.output_queue = JoinableQueue(1000) + self.input_done_event = Event() + self.n_threads = 1 + self.n_workers = n_threads + self.workers = [] + self._has_remote_error = False + self.ipc_manager = IPCLoggingManager() + + def prepare_glycoprotein_for_dispatch(self, glycoprotein, builder): + prepared = builder.prepare_glycoprotein(glycoprotein) + return prepared + + def feed_queue(self, glycoproteins, builder): + n = len(glycoproteins) + n_sites = self.count_glycosites(glycoproteins) + self.log( + ""Analyzing %d glycoproteins with %d occupied N-glycosites"" % (n, n_sites)) + i_site = 0 + for glycoprotein in glycoproteins: + prepared = self.prepare_glycoprotein_for_dispatch(glycoprotein, builder) + for work_item in prepared: + i_site += 1 + self.input_queue.put(work_item) + if i_site % 50 == 0 and i_site != 0: + self.input_queue.join() + self.input_done_event.set() + + def _handle_local(self, glycoproteins, builder, seen): + for glycoprotein in glycoproteins: + prepared = self.prepare_glycoprotein_for_dispatch( + glycoprotein, builder) + for records, site, protein_stub in prepared: + key = (protein_stub.name, site) + if key in seen: + continue + else: + seen[key] = -1 + model = builder.fit_site_model(records, site, protein_stub) + if model is not None: + self.builder.site_models.append(model) + + def make_workers(self): + for _i in range(self.n_workers): + worker = GlycositeModelBuildingProcess( + self.builder, self.input_queue, self.output_queue, + producer_done_event=self.input_done_event, + output_done_event=Event(), + log_handler=self.ipc_manager.sender()) + self.workers.append(worker) + worker.start() + + def clear_pool(self): + for _i, worker in enumerate(self.workers): + exitcode = worker.exitcode + if exitcode != 0 and exitcode is not None: + self.log(""... Worker Process %r had exitcode %r"" % (worker, exitcode)) + try: + worker.join(1) + except AttributeError: + pass + if worker.is_alive(): + self.debug(""... Worker Process %r is still alive and incomplete"" % (worker, )) + worker.terminate() + + def all_workers_finished(self): + """"""Check if all worker processes have finished. + """""" + worker_still_busy = False + assert self.workers + for worker in self.workers: + try: + is_done = worker.all_work_done() + if not is_done: + worker_still_busy = True + break + except (RemoteError, KeyError): + worker_still_busy = True + self._has_remote_error = True + break + return not worker_still_busy + + def _fit_glycoprotein_site_models(self, glycoproteins, builder): + self.builder = builder + feeder_thread = Thread(target=self.feed_queue, args=(glycoproteins, builder)) + feeder_thread.daemon = True + feeder_thread.start() + self.make_workers() + n_sites = self.count_glycosites(glycoproteins) + seen = dict() + strikes = 0 + start_time = time.time() + i = 0 + has_work = True + while has_work: + try: + site_model = self.output_queue.get(True, 3) + self.output_queue.task_done() + key = (site_model.protein_name, site_model.position) + seen[(key)] = i + if key in seen: + self.debug( + ""...... Duplicate Results For %s. First seen at %r, now again at %r"" % ( + key, seen[key], i, )) + else: + seen[key] = i + i += 1 + strikes = 0 + if i % 1 == 0: + self.log( + ""...... Processed %d sites (%0.2f%%)"" % (i, i * 100. / n_sites)) + if not isinstance(site_model, EmptySite): + self.builder.site_models.append(site_model) + except QueueEmptyException: + if len(seen) == n_sites: + has_work = False + # do worker life cycle management here + elif self.all_workers_finished(): + if len(seen) == n_sites: + has_work = False + else: + strikes += 1 + if strikes % 25 == 0: + self.log( + ""...... %d cycles without output (%d/%d, %0.2f%% Done)"" % ( + strikes, len(seen), n_sites, len(seen) * 100. / n_sites)) + self.debug(""...... Processes"") + for worker in self.workers: + self.debug(""......... %r"" % (worker,)) + self.debug(""...... IPC Manager: %r"" % (self.ipc_manager,)) + if strikes > 150: + self.log(""Too much time has elapsed waiting for final results, finishing locally."") + self._handle_local(glycoproteins, builder, seen) + else: + strikes += 1 + if strikes % 50 == 0: + self.log( + ""...... %d cycles without output (%d/%d, %0.2f%% Done, %d children still alive)"" % ( + strikes, len(seen), n_sites, len( + seen) * 100. / n_sites, + len(multiprocessing.active_children()) - 1)) + try: + input_queue_size = self.input_queue.qsize() + except Exception: + input_queue_size = -1 + is_feeder_done = self.input_done_event.is_set() + self.log(""...... Input Queue Status: %r. Is Feeder Done? %r"" % ( + input_queue_size, is_feeder_done)) + if strikes > 150: + self.log(""Too much time has elapsed waiting for workers, finishing locally."") + self._handle_local(glycoproteins, builder, seen) + continue + self.clear_pool() + self.ipc_manager.stop() + feeder_thread.join() + dispatcher_end = time.time() + self.log(""... Dispatcher Finished (%0.3g sec.)"" % + (dispatcher_end - start_time)) + + +GlycoproteinSiteModelBuildingWorkflow = MultiprocessingGlycoproteinSiteModelBuildingWorkflow +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/site_model/glycoproteome_model.py",".py","7182","184","import re +import io +import warnings + +from typing import Dict, List, Optional, Mapping + +from glycopeptidepy.structure.parser import strip_modifications +from glypy.structure.glycan_composition import HashableGlycanComposition + +from glycresoft.structure import LRUMapping + +from glycresoft.structure.structure_loader import FragmentCachingGlycopeptide +from glycresoft.tandem.spectrum_match import SpectrumMatchClassification as StructureClassification + +from .glycosite_model import MINIMUM, GlycosylationSiteModel +from .glycoprotein_model import ( + GlycoproteinSiteSpecificGlycomeModel, + ReversedProteinSiteReflectionGlycoproteinSiteSpecificGlycomeModel +) + + +class GlycoproteomeModelBase(object): + __slots__ = () + def score(self, glycopeptide: FragmentCachingGlycopeptide, + glycan_composition: Optional[HashableGlycanComposition]=None) -> float: + raise NotImplementedError() + + @classmethod + def bind_to_hypothesis(cls, session, site_models, hypothesis_id=1, fuzzy=True, + site_model_cls=GlycoproteinSiteSpecificGlycomeModel) -> 'GlycoproteomeModelBase': + inst = cls( + site_model_cls.bind_to_hypothesis( + session, site_models, hypothesis_id, fuzzy)) + return inst + + +class GlycoproteomeModel(GlycoproteomeModelBase): + glycoprotein_models: Dict[int, GlycoproteinSiteSpecificGlycomeModel] + + def __init__(self, glycoprotein_models): + if isinstance(glycoprotein_models, Mapping): + self.glycoprotein_models = dict(glycoprotein_models) + else: + self.glycoprotein_models = { + ggm.id: ggm for ggm in glycoprotein_models + } + + def relabel_proteins(self, name_to_id_map: Dict[str, int]): + remapped = {} + for ggm in self.glycoprotein_models.values(): + try: + new_id = name_to_id_map[ggm.name] + remapped[new_id] = ggm + except KeyError: + warnings.warn( + ""No mapping for %r, it will be omitted"" % (ggm.name, )) + self.glycoprotein_models = remapped + + def stub_proteins(self): + for model in self.glycoprotein_models.values(): + model.stub_protein() + + def find_model(self, glycopeptide: FragmentCachingGlycopeptide): + if glycopeptide.protein_relation is None: + return None + protein_id = glycopeptide.protein_relation.protein_id + glycoprotein_model = self.glycoprotein_models.get(protein_id) + return glycoprotein_model + + def score(self, glycopeptide: FragmentCachingGlycopeptide, + glycan_composition: Optional[HashableGlycanComposition]=None) -> float: + glycoprotein_model = self.find_model(glycopeptide) + if glycoprotein_model is None: + score = MINIMUM + else: + score = glycoprotein_model.score(glycopeptide, glycan_composition) + return score + + +class SubstringGlycoproteomeModel(GlycoproteomeModelBase): + sequence_to_model: Dict[str, GlycoproteinSiteSpecificGlycomeModel] + + def __init__(self, models, cache_size=2**15): + self.models = models + self.sequence_to_model = { + str(model.protein): model for model in models.values() + } + self.peptide_to_protein = LRUMapping(cache_size) + + def get_models(self, glycopeptide: FragmentCachingGlycopeptide) -> List[GlycoproteinSiteSpecificGlycomeModel]: + out = [] + seq = strip_modifications(glycopeptide) + if seq in self.peptide_to_protein: + return list(self.peptide_to_protein[seq]) + pattern = re.compile(seq) + for case in self.sequence_to_model: + if seq in case: + bounds = pattern.finditer(case) + for match in bounds: + protein_model = self.sequence_to_model[case] + site_models = protein_model.find_sites_in( + match.start(), match.end()) + out.append(site_models) + self.peptide_to_protein[seq] = tuple(out) + return out + + def find_proteins(self, glycopeptide: FragmentCachingGlycopeptide) -> List[GlycoproteinSiteSpecificGlycomeModel]: + out = [] + seq = strip_modifications(glycopeptide) + for case in self.sequence_to_model: + if seq in case: + out.append(self.sequence_to_model[case]) + return out + + def score(self, glycopeptide: FragmentCachingGlycopeptide, + glycan_composition: Optional[HashableGlycanComposition]=None) -> float: + if glycan_composition is None: + glycan_composition = glycopeptide.glycan_composition + models = self.get_models(glycopeptide) + if len(models) == 0: + return MINIMUM + sites = models[0] + if len(sites) == 0: + return MINIMUM + try: + acc = [] + for site in sites: + try: + rec = site.glycan_map[glycan_composition] + acc.append(rec.score) + except KeyError: + pass + return max(sum(acc) / len(acc), MINIMUM) if acc else MINIMUM + except IndexError: + return MINIMUM + + def __call__(self, glycopeptide): + return self.get_models(glycopeptide) + + +class GlycoproteomePriorAnnotator(object): + target_model: GlycoproteomeModel + decoy_model: GlycoproteomeModel + + @classmethod + def load(cls, target_session, decoy_session, fh: io.TextIOBase, hypothesis_id=1, fuzzy=True): + site_models = GlycosylationSiteModel.load(fh) + target_model = GlycoproteomeModel.bind_to_hypothesis( + target_session, + site_models, + hypothesis_id=hypothesis_id, + fuzzy=fuzzy) + decoy_model = GlycoproteomeModel.bind_to_hypothesis( + decoy_session, + site_models, + hypothesis_id=hypothesis_id, + fuzzy=fuzzy, + site_model_cls=ReversedProteinSiteReflectionGlycoproteinSiteSpecificGlycomeModel) + target_model.stub_proteins() + decoy_model.stub_proteins() + return cls(target_model, decoy_model) + + def __init__(self, target_model, decoy_model): + self.target_model = target_model + self.decoy_model = decoy_model + + def select_model(self, glycopeptide: FragmentCachingGlycopeptide, + structure_type: StructureClassification) -> GlycoproteomeModel: + if structure_type & StructureClassification.decoy_peptide_target_glycan: + return self.decoy_model + else: + return self.target_model + + def score_glycan(self, glycopeptide: FragmentCachingGlycopeptide, + structure_type: StructureClassification, + model: GlycoproteomeModel) -> float: + # Treat decoy glycans identical + gc = glycopeptide.glycan_composition + return model.score(glycopeptide, gc) + + def score(self, glycopeptide: FragmentCachingGlycopeptide, structure_type: StructureClassification) -> float: + model = self.select_model(glycopeptide, structure_type) + return self.score_glycan(glycopeptide, structure_type, model) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/composition_distribution_model/site_model/glycoprotein_model.py",".py","8166","234","import warnings +import io + +from collections import defaultdict +from typing import Dict, Iterable, List, Optional, Union + + +from glycopeptidepy.structure.parser import strip_modifications +from glycopeptidepy.utils.collectiontools import groupby + +from glypy.structure.glycan_composition import HashableGlycanComposition + +from glycresoft import serialize +from glycresoft.structure import PeptideProteinRelation, FragmentCachingGlycopeptide +from glycresoft.database.builder.glycopeptide.proteomics.fasta import DeflineSuffix +from glycresoft.database.builder.glycopeptide.proteomics.sequence_tree import SuffixTree + + +from .glycosite_model import MINIMUM, GlycosylationSiteModel + + +class ProteinStub(object): + __slots__ = ('name', 'id', 'glycosylation_sites') + + name: str + id: int + glycosylation_sites: List[int] + + def __init__(self, name, id=None, glycosylation_sites=None): + self.name = name + self.id = id + self.glycosylation_sites = glycosylation_sites + + def __getstate__(self): + out = { + 'name': self.name, + 'id': self.id, + 'glycosylation_sites': self.glycosylation_sites + } + return out + + def __setstate__(self, state): + self.name = state['name'] + self.id = state['id'] + self.glycosylation_sites = state['glycosylation_sites'] + + def __repr__(self): + return ""{self.__class__.__name__}({self.name!r}, {self.id!r}, {self.glycosylation_sites!r})"".format(self=self) + + @classmethod + def from_protein(cls, protein): + return cls(protein.name, protein.id) + + +def _make_name_suffix_lookup(proteins: Iterable[ProteinStub]): + tree = SuffixTree() + for prot in proteins: + name = prot.name + tree.add_ngram(DeflineSuffix(name, name)) + return tree + + +class GlycoproteinSiteSpecificGlycomeModel(object): + __slots__ = ('protein', '_glycosylation_sites') + + protein: ProteinStub + _glycosylation_sites: List[GlycosylationSiteModel] + + def __init__(self, protein, glycosylation_sites=None): + self.protein = protein + self._glycosylation_sites = [] + self.glycosylation_sites = glycosylation_sites + + def __getstate__(self): + return { + ""protein"": self.protein, + ""_glycosylation_sites"": self._glycosylation_sites + } + + def __setstate__(self, state): + self.protein = state['protein'] + self._glycosylation_sites = state['_glycosylation_sites'] + + def __eq__(self, other): + if other is None: + return False + return (self.protein == other.protein) and (self.glycosylation_sites == other.glycosylation_sites) + + def __ne__(self, other): + return not self == other + + @property + def glycosylation_sites(self) -> List[GlycosylationSiteModel]: + return self._glycosylation_sites + + @glycosylation_sites.setter + def glycosylation_sites(self, glycosylation_sites): + self._glycosylation_sites = sorted( + glycosylation_sites or [], key=lambda x: x.position) + + def __getitem__(self, i) -> GlycosylationSiteModel: + return self.glycosylation_sites[i] + + def __len__(self): + return len(self.glycosylation_sites) + + @property + def id(self): + return self.protein.id + + @property + def name(self): + return self.protein.name + + def find_sites_in(self, start: int, end: int) -> List[GlycosylationSiteModel]: + spans = [] + for site in self.glycosylation_sites: + if start <= site.position <= end: + spans.append(site) + elif end < site.position: + break + return spans + + def _guess_sites_from_sequence(self, sequence: str): + prot_seq = str(self.protein) + query_seq = strip_modifications(sequence) + try: + start = prot_seq.index(query_seq) + end = start + len(query_seq) + return PeptideProteinRelation(start, end, self.protein.id, self.protein.hypothesis_id) + except ValueError: + return None + + def score(self, glycopeptide: FragmentCachingGlycopeptide, + glycan_composition: Optional[HashableGlycanComposition]=None) -> float: + if glycan_composition is None: + glycan_composition = glycopeptide.glycan_composition + pr = glycopeptide.protein_relation + sites = self.find_sites_in(pr.start_position, pr.end_position) + if len(sites) > 1: + score_acc = 0.0 + warnings.warn( + ""Multiple glycosylation sites are not (yet) supported. Using average instead"") + for site in sites: + try: + rec = site.glycan_map[glycan_composition] + score_acc += (rec.score) + except KeyError: + score_acc += (MINIMUM) + return score_acc / len(sites) + try: + site = sites[0] + try: + rec = site.glycan_map[glycan_composition] + except KeyError: + return MINIMUM + return rec.score + except IndexError: + return MINIMUM + + @classmethod + def bind_to_hypothesis(cls, session, + site_models: List[GlycosylationSiteModel], + hypothesis_id: int=1, + fuzzy: bool=True) -> Dict[int, 'GlycoproteinSiteSpecificGlycomeModel']: + by_protein_name = defaultdict(list) + for site in site_models: + by_protein_name[site.protein_name].append(site) + protein_models = {} + proteins = session.query(serialize.Protein).filter( + serialize.Protein.hypothesis_id == hypothesis_id).all() + protein_name_map = {prot.name: prot for prot in proteins} + tree = None + for protein_name, sites in by_protein_name.items(): + try: + protein = protein_name_map[protein_name] + except KeyError: + if fuzzy: + if tree is None: + tree = _make_name_suffix_lookup(proteins) + labels = list(tree.subsequences_of(protein_name)) + if not labels: + continue + protein = protein_name_map[labels[0].original] + else: + continue + model = cls(protein, sites) + protein_models[model.id] = model + return protein_models + + def __repr__(self): + template = ""{self.__class__.__name__}({self.name}, {self.glycosylation_sites})"" + return template.format(self=self) + + @classmethod + def load(cls, fh: io.TextIOBase, + session=None, + hypothesis_id: int = 1, + fuzzy: bool = True) -> Union[List['GlycoproteinSiteSpecificGlycomeModel'], + Dict[int, 'GlycoproteinSiteSpecificGlycomeModel']]: + site_models = GlycosylationSiteModel.load(fh) + if session is not None: + return cls.bind_to_hypothesis(session, site_models, hypothesis_id, fuzzy) + by_protein_name = groupby(site_models, lambda x: x.protein_name) + result = [] + for name, models in by_protein_name.items(): + result.append(cls(ProteinStub(name), models)) + return result + + def stub_protein(self): + self.protein = ProteinStub.from_protein(self.protein) + + + +class ReversedProteinSiteReflectionGlycoproteinSiteSpecificGlycomeModel(GlycoproteinSiteSpecificGlycomeModel): + __slots__ = () + + @property + def glycosylation_sites(self): + return self._glycosylation_sites + + @glycosylation_sites.setter + def glycosylation_sites(self, glycosylation_sites: List[GlycosylationSiteModel]): + temp = [] + if isinstance(self.protein, ProteinStub): + raise TypeError(""Cannot create a reflected glycosite model with a ProteinStub"") + n = len(str(self.protein)) + for site in glycosylation_sites: + site = site.copy() + site.position = n - site.position - 1 + temp.append(site) + self._glycosylation_sites = sorted( + temp or [], key=lambda x: x.position) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/models/features.py",".py","391","21","from glycresoft.structure import KeyTransformingDecoratorDict + + +def transform_key(key): + return key.replace(""-"", ""_"") + + +ms1_model_features = KeyTransformingDecoratorDict(transform_key) + + +def register_feature(name, feature): + ms1_model_features[name] = feature + + +def available_features(): + return list(ms1_model_features) + + +def get_feature(name): + return ms1_model_features[name] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/models/mass_shift_models.py",".py","4003","101","from glycresoft.scoring import ( + DummyFeature, + MassScalingMassShiftScoringModel) + +from glycresoft.scoring.base import ( + degree_of_sialylation, + CompositionDispatchingModel) + +from .utils import make_model_loader +from .features import register_feature + + +load_model = make_model_loader(MassScalingMassShiftScoringModel) + +AmmoniumMassShiftFeature = load_model(""ammonium_adduct_model"") +MethylLossFeature = load_model(""methyl_loss_adduct_model"") + + +register_feature(""permethylated_ammonium_adducts"", AmmoniumMassShiftFeature) +register_feature(""methyl_loss"", MethylLossFeature) + + +class PermethylatedAmmoniumAndMethylLossModel(DummyFeature): + def __init__(self, boosting=True): + DummyFeature.__init__( + self, name=self.__class__.__name__, feature_type=""mass_shift_score"") + self.ammonium = AmmoniumMassShiftFeature + self.methyl_loss = MethylLossFeature + self.boosting = boosting + + def score(self, chromatogram, *args, **kwargs): + methyl_score = self.methyl_loss.score(chromatogram) + # the methyl loss scoring model is < 0.2 if only a loss + # was matched, 0.5 if only unmodified was matched, and + # > 0.5 if both unmodified and a loss was matched. + # + # to make this scorer pass through directly to the ammonium + # model when there was no methyl loss detected, either the + # case where unmodified is detecteded should map to essentially + # 1.0 or the case where no loss is registered + methyl_score *= 2 + if not self.boosting: + if methyl_score > 1: + methyl_score = 1 + # there was no methyl loss + if methyl_score < 1e-3: + methyl_score = 1 + # elif methyl_score > 1: + # methyl_score = 1 + score = methyl_score * self.ammonium.score(chromatogram) + if score > 1: + score = 1 - 1e-3 + return score + + +PermethylatedAmmoniumAndMethylLossFeature = PermethylatedAmmoniumAndMethylLossModel() + +register_feature( + ""permethylated_ammonium_adducts_methyl_loss"", + PermethylatedAmmoniumAndMethylLossFeature) + + +AsialoFormateMassShiftFeature = load_model(""asialo_formate_adduct_model"") +MonosialoFormateMassShiftFeature = load_model(""monosialo_formate_adduct_model"") +DisialoFormateMassShiftFeature = load_model(""disialo_formate_adduct_model"") +TrisialoFormateMassShiftFeature = load_model(""trisialo_formate_adduct_model"") +TetrasialoFormateMassShiftFeature = load_model(""tetrasialo_formate_adduct_model"") + +_GeneralizedFormateMassShiftModelTable = CompositionDispatchingModel({ + lambda x: degree_of_sialylation(x) == 0: AsialoFormateMassShiftFeature, + lambda x: degree_of_sialylation(x) == 1: MonosialoFormateMassShiftFeature, + lambda x: degree_of_sialylation(x) == 2: DisialoFormateMassShiftFeature, + lambda x: degree_of_sialylation(x) == 3: TrisialoFormateMassShiftFeature, + lambda x: degree_of_sialylation(x) > 3: TetrasialoFormateMassShiftFeature +}, AsialoFormateMassShiftFeature) + + +class GeneralizedFormateMassShiftModel(DummyFeature): + def __init__(self): + DummyFeature.__init__( + self, name=self.__class__.__name__, feature_type=""mass_shift_score"") + self.table = _GeneralizedFormateMassShiftModelTable + + def score(self, chromatogram, *args, **kwargs): + score = self.table.score(chromatogram, *args, **kwargs) + # This feature can easily be 1.0 under certain conditions, which + # leads to undesirable score inflation. The maximum contribution + # this should have is capped to 0.7 (logit(0.7) = 0.8472) which + # should not lead to many more assignments being retained while + # still penalizing inappropriate formate adduction states + return min(score, 0.7) + + +# pickle loading alias +GeneralizedFormateAdductModel = GeneralizedFormateMassShiftModel + +GeneralizedFormateMassShiftFeature = GeneralizedFormateMassShiftModel() + + +register_feature(""formate_adduct_model"", GeneralizedFormateMassShiftFeature) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/models/__init__.py",".py","697","20","import sys + +from .features import (ms1_model_features, register_feature, available_features, get_feature) +from .charge_models import GeneralScorer +from . import mass_shift_models +from .mass_shift_models import ( + AmmoniumMassShiftFeature, MethylLossFeature, + PermethylatedAmmoniumAndMethylLossFeature, + GeneralizedFormateMassShiftFeature) + +# pickle loading alias +sys.modules['glycresoft.models.adduct_models'] = mass_shift_models + +__all__ = [ + ""ms1_model_features"", ""register_feature"", ""available_features"", + ""get_feature"", + ""GeneralScorer"", ""AmmoniumMassShiftFeature"", ""MethylLossFeature"", + ""PermethylatedAmmoniumAndMethylLossFeature"", ""GeneralizedFormateMassShiftFeature"" +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/models/charge_models.py",".py","850","30","from glycresoft.scoring.base import ( + CompositionDispatchingModel, + is_sialylated, + DummyFeature) + +from glycresoft.scoring import ( + MassScalingChargeStateScoringModel, ChromatogramScorer) + +from .utils import make_model_loader +from .features import register_feature + + +load_model = make_model_loader(MassScalingChargeStateScoringModel) + + +SialylatedChargeModel = load_model(""sialylated_charge_model"") +UnsialylatedChargeModel = load_model(""unsialylated_charge_model"") + +GeneralizedChargeScoringModel = CompositionDispatchingModel({ + is_sialylated: SialylatedChargeModel, + lambda x: not is_sialylated(x): UnsialylatedChargeModel +}, SialylatedChargeModel) + + +GeneralScorer = ChromatogramScorer() +GeneralScorer.add_feature(GeneralizedChargeScoringModel) + + +register_feature(""null_charge"", DummyFeature(""null_charge_model"", ""charge_count"")) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/models/utils.py",".py","308","12","import codecs +import pkg_resources + + +def make_model_loader(model_type): + def load_model(model_name): + stream = codecs.getreader(""utf-8"")( + pkg_resources.resource_stream( + __name__, ""data/%s.json"" % model_name)) + return model_type.load(stream) + return load_model +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/models/data/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/_c/cythonizer.py",".py","65","4","import setuptools +from Cython.Build.Cythonize import main +main() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/_c/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/_c/chromatogram_tree/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/_c/composition_network/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/_c/scoring/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/_c/database/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/_c/composition_distribution_model/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/_c/structure/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/_c/tandem/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/structure/probability.py",".py","26358","776","from array import ArrayType as array +from concurrent.futures import ThreadPoolExecutor + +from typing import Dict, Optional, Protocol, Union, List + +import numpy as np +from numpy.typing import ArrayLike + +from scipy import stats +from scipy.special import logsumexp + +try: + from matplotlib import pyplot as plt +except ImportError: + pass + + +class KMeans(object): + k: int + means: np.ndarray + + def __init__(self, k, means=None): + self.k = k + self.means = np.array(means) if means is not None else None + + @classmethod + def fit(cls, X: np.ndarray, k: int, initial_mus: Optional[np.ndarray]=None): + if initial_mus is not None: + mus = initial_mus + else: + mus = np.sort(np.random.choice(X, k)) + inst = cls(k, mus) + inst.estimate(X) + return inst + + @classmethod + def from_json(cls, state: Dict) -> 'KMeans': + return cls(state['k'], state['means']) + + def to_json(self) -> Dict: + return { + ""k"": int(self.k), + ""means"": [float(m) for m in self.means] + } + + def estimate(self, X: np.ndarray, maxiter: int=1000, tol: float=1e-6): + for i in range(maxiter): + distances = [] + for k in range(self.k): + diff = (X - self.means[k]) + dist = np.sqrt((diff * diff)) + distances.append(dist) + distances = np.vstack(distances).T + cluster_assignments = np.argmin(distances, axis=1) + new_means = [] + for k in range(self.k): + new_means.append( + np.mean(X[cluster_assignments == k])) + new_means = np.array(new_means) + new_means[np.isnan(new_means)] = 0.0 + diff = (self.means - new_means) + dist = np.sqrt((diff * diff).sum()) / self.k + self.means = new_means + # Always sort the means so that ordering is consistent + self.means.sort() + if dist < tol: + break + else: + pass + + def score(self, x: Union[float, np.ndarray]) -> np.ndarray: + x = np.asanyarray(x) + if x.ndim < 2: + x = x.reshape((-1, 1)) + delta = np.abs(self.means - x) + score = 1 - delta + norm = score.sum(axis=1)[:, None] + 1e-13 + score /= norm + return score + + def predict(self, x: Union[float, np.ndarray]) -> np.ndarray: + scores = self.score(x) + return np.argmax(scores, axis=1) + + +class MixtureBase(object): + n_components: int + + def __init__(self, n_components): + self.n_components + + def to_json(self) -> Dict: + return {} + + @classmethod + def from_json(cls, state) -> 'MixtureBase': + raise NotImplementedError() + + def loglikelihood(self, X) -> float: + out = logsumexp(self.logpdf(X), axis=1).sum() + return out + + def bic(self, X) -> float: + '''Calculate the Bayesian Information Criterion + for selecting the most parsimonious number of components. + ''' + return np.log(X.size) * (self.n_components * 3 - 1) - (2 * (self.loglikelihood(X))) + + def logpdf(self, X: np.ndarray, weighted: float=True) -> np.ndarray: + out = np.array( + [self._logpdf(X, k) + for k in range(self.n_components)]).T + if weighted: + out += np.log(self.weights) + return out + + def pdf(self, X: np.ndarray, weighted: float = True) -> np.ndarray: + return np.exp(self.logpdf(X, weighted=weighted)) + + def score(self, X: np.ndarray) -> np.ndarray: + return self.pdf(X).sum(axis=1) + + def responsibility(self, X: np.ndarray) -> np.ndarray: + '''Also called the posterior probability, as these are the + probabilities associating each element of X with each component + ''' + acc = np.zeros((X.shape[0], self.n_components)) + for k in range(self.n_components): + acc[:, k] = np.log(self.weights[k]) + self._logpdf(X, k) + total = logsumexp(acc, axis=1)[:, None] + # compute the ratio of the density to the total in log-space, then + # exponentiate to return to linear space + out = np.exp(acc - total) + return out + + +class GaussianMixture(MixtureBase): + mus: np.ndarray + sigmas: np.ndarray + weights: np.ndarray + + def __init__(self, mus, sigmas, weights): + self.mus = np.array(mus) + self.sigmas = np.array(sigmas) + self.weights = np.array(weights) + self.n_components = len(weights) + + @classmethod + def from_json(cls, state: Dict) -> 'GaussianMixture': + return cls(state['mus'], state['sigmas'], state['weights']) + + def to_json(self) -> Dict: + return { + ""mus"": [float(m) for m in self.mus], + ""sigmas"": [float(m) for m in self.sigmas], + ""weights"": [float(m) for m in self.weights] + } + + def __repr__(self): + template = ""{self.__class__.__name__}({self.mus}, {self.sigmas}, {self.weights})"" + return template.format(self=self) + + def _logpdf(self, X: np.ndarray, k: int) -> np.ndarray: + '''Computes the log-space density for `X` using the `k`th + component of the mixture + ''' + return stats.norm.logpdf(X, self.mus[k], self.sigmas[k]) + + @classmethod + def fit(cls, X: np.ndarray, n_components: int, maxiter: int=1000, tol: float=1e-5, deterministic: bool=True) -> 'GaussianMixture': + if not deterministic: + mus = KMeans.fit(X, n_components).means + else: + mus = (np.max(X) / (n_components + 1)) * np.arange(1, n_components + 1) + assert not np.any(np.isnan(mus)) + sigmas = np.var(X) * np.ones_like(mus) + weights = np.ones_like(mus) / n_components + inst = cls(mus, sigmas, weights) + inst.estimate(X, maxiter=maxiter, tol=tol) + return inst + + def _update_params_for(self, X: np.ndarray, k: int, responsibility: np.ndarray, new_mus: np.ndarray, + new_sigmas: np.ndarray, new_weights: np.ndarray): + # The expressions for each partial derivative may be useful for understanding + # portions of this block. + # See http://www.notenoughthoughts.net/posts/normal-log-likelihood-gradient.html + g = responsibility[:, k] + N_k = g.sum() + # Begin specialization for Gaussian distributions + diff = X - self.mus[k] + mu_k = g.dot(X) / N_k + new_mus[k] = mu_k + sigma_k = (g * diff).dot(diff.T) / N_k + 1e-6 + new_sigmas[k] = np.sqrt(sigma_k) + new_weights[k] = N_k + + def estimate(self, X: np.ndarray, maxiter: int=1000, tol: float=1e-5): + for i in range(maxiter): + # E-step + responsibility = self.responsibility(X) + + # M-step + new_mus = np.zeros_like(self.mus) + new_sigmas = np.zeros_like(self.sigmas) + prev_loglikelihood = self.loglikelihood(X) + new_weights = np.zeros_like(self.weights) + + for k in range(self.n_components): + self._update_params_for(X, k, responsibility, new_mus, new_sigmas, new_weights) + + new_weights /= new_weights.sum() + self.mus = new_mus + self.sigmas = new_sigmas + self.weights = new_weights + new_loglikelihood = self.loglikelihood(X) + delta_fit = (prev_loglikelihood - new_loglikelihood) / new_loglikelihood + if abs(delta_fit) < tol: + break + else: + pass + + @property + def domain(self): + return [ + self.mus.min() - self.sigmas.max() * 4, + self.mus.max() + self.sigmas.max() * 4 + ] + + def plot(self, ax=None, **kwargs): + if ax is None: + fig, ax = plt.subplots(1) + X = np.arange(*self.domain, step=0.01) + Y = np.exp(self.logpdf(X, True)) + ax.plot(X, np.sum(Y, axis=1), **kwargs) + return ax + + +a = 0.0 +b = float('inf') +phi_a = stats.norm.pdf(a) +phi_b = stats.norm.pdf(b) +Z = stats.norm.cdf(b) - stats.norm.cdf(a) + + +def _truncnorm_mean(X): + mu = X.mean() + sigma = np.std(X) + return mu + (phi_a / Z) * sigma + + +def _truncnorm_std(X): + sigma2 = np.var(X) + return np.sqrt(sigma2 * (1 + a * phi_a / Z - (phi_a / Z) ** 2)) + + +def truncnorm_pdf(x, mu, sigma): + scalar = np.isscalar(x) + if scalar: + x = np.array([x]) + mask = (a <= x) & (x <= b) + out = np.zeros_like(x) + + numerator = stats.norm.pdf((x[mask] - mu) / sigma) + denominator = stats.norm.cdf( + (b - mu) / sigma) - stats.norm.cdf((a - mu) / sigma) + out[mask] = 1 / sigma * numerator / denominator + if scalar: + out = out[0] + return out + + +def truncnorm_logpdf(x, mu, sigma): + return np.log(truncnorm_pdf(x, mu, sigma)) + + +class _TruncatedNormalMixin(object): + + def _logpdf(self, X: np.ndarray, k: int) -> np.ndarray: + '''Computes the log-space density for `X` using the `k`th + component of the mixture + ''' + result = truncnorm_logpdf( + X, self.mus[k], self.sigmas[k]) + return result + + def _update_params_for(self, X, k, responsibility, new_mus, new_sigmas, new_weights): + # The expressions for each partial derivative may be useful for understanding + # portions of this block. + # See http://www.notenoughthoughts.net/posts/normal-log-likelihood-gradient.html + g = responsibility[:, k] + N_k = g.sum() + + # Begin specialization for the truncated Gaussian distributions + diff = X - self.mus[k] + + unconstrained_mu_k = g.dot(X) / N_k + unconstrained_sigma_k = np.sqrt((g * diff).dot(diff.T) / N_k + 1e-6) + mu_k = unconstrained_mu_k + (phi_a / Z) * unconstrained_sigma_k + sigma_k = np.sqrt(unconstrained_sigma_k ** 2 * (1 + a * phi_a / Z - (phi_a / Z) ** 2)) + + new_mus[k] = mu_k + new_sigmas[k] = np.sqrt(sigma_k) + new_weights[k] = N_k + + +class TruncatedGaussianMixture(_TruncatedNormalMixin, GaussianMixture): + @classmethod + def fit(cls, X, n_components, maxiter=1000, tol=1e-5, deterministic=True) -> 'TruncatedGaussianMixture': + if not deterministic: + mus = KMeans.fit(X, n_components).means + else: + mus = (np.max(X) / (n_components + 1)) * \ + np.arange(0, n_components + 1) + mus[0] = 0.0 + assert not np.any(np.isnan(mus)) + sigmas = np.var(X) * np.ones_like(mus) + weights = np.ones_like(mus) / n_components + inst = cls(mus, sigmas, weights) + inst.estimate(X, maxiter=maxiter, tol=tol) + return inst + + +class GammaMixtureBase(MixtureBase): + shapes: np.ndarray + scales: np.ndarray + weights: np.ndarray + + def __init__(self, shapes, scales, weights): + self.shapes = np.array(shapes) + self.scales = np.array(scales) + self.weights = np.array(weights) + self.n_components = len(weights) + + @classmethod + def from_json(cls, state: Dict) -> 'GammaMixtureBase': + return cls(state['shapes'], state['scales'], state['weights']) + + def to_json(self) -> Dict: + return { + ""shapes"": [float(m) for m in self.shapes], + ""scales"": [float(m) for m in self.scales], + ""weights"": [float(m) for m in self.weights] + } + + def __repr__(self): + template = ""{self.__class__.__name__}({self.shapes}, {self.scales}, {self.weights})"" + return template.format(self=self) + + def _logpdf(self, X: np.ndarray, k: int) -> np.ndarray: + """""" + Computes the log-space density for `X` using the `k`th + component of the mixture + """""" + return stats.gamma.logpdf(X, a=self.shapes[k], scale=self.scales[k]) + + def plot(self, ax=None, **kwargs): + if ax is None: + fig, ax = plt.subplots(1) + X = np.arange(*self.domain, step=0.01) + Y = np.exp(self.logpdf(X, True)) + ax.plot(X, np.sum(Y, axis=1), **kwargs) + return ax + + @property + def domain(self): + return [ + 1e-6, + 100.0 + ] + + @classmethod + def fit(cls, X: np.ndarray, n_components: int, maxiter: int=100, tol: float=1e-5, deterministic: bool=True) -> 'GammaMixtureBase': + shapes, scales, weights = cls.initial_parameters(X, n_components, deterministic=deterministic) + inst = cls(shapes, scales, weights) + inst.estimate(X, maxiter=maxiter, tol=tol) + return inst + + +class IterativeGammaMixture(GammaMixtureBase): + '''An iterative approximation of a mixture Gamma distributions + based on the Gaussian distribution. May not converge to the optimal + solution, and if so, it converges slowly. + + Derived from pGlyco's FDR estimation method + ''' + @staticmethod + def initial_parameters(X, n_components, deterministic=True): + mu = np.median(X) / (n_components + 1) * np.arange(1, n_components + 1) + sigma = np.ones(n_components) * np.var(X) + shapes = mu ** 2 / sigma + scales = sigma / mu + weights = np.ones(n_components) + weights /= weights.sum() + return shapes, scales, weights + + def estimate(self, X: np.ndarray, maxiter=100, tol=1e-5): + prev_loglikelihood = self.loglikelihood(X) + for i in range(maxiter): + # E-Step + responsibility = self.responsibility(X) + + # M-Step + new_weights = responsibility.sum(axis=0) / responsibility.sum() + mu = responsibility.T.dot(X) / responsibility.T.sum(axis=1) + 1e-6 + sigma = np.array( + [responsibility[:, i].dot((X - mu[i]) ** 2 / np.sum(responsibility[:, i])) + for i in range(self.n_components)]) + 1e-6 + new_shapes = mu ** 2 / sigma + new_scales = sigma / mu + self.shapes = new_shapes + self.scales = new_scales + self.weights = new_weights + + new_loglikelihood = self.loglikelihood(X) + delta_fit = (prev_loglikelihood - new_loglikelihood) / new_loglikelihood + if abs(delta_fit) < tol: + break + else: + pass + + +GammaMixture = IterativeGammaMixture + + +class GaussianMixtureWithPriorComponent(GaussianMixture): + prior: MixtureBase + + def __init__(self, mus, sigmas, prior, weights): + self.mus = np.array(mus) + self.sigmas = np.array(sigmas) + self.prior = prior + self.weights = np.array(weights) + self.n_components = len(weights) + + def to_json(self) -> Dict: + state = super().to_json() + state['prior'] = self.prior.to_json() + state['prior_type'] = self.prior.__class__.__name__ + return state + + @classmethod + def from_json(cls, state: Dict) -> 'GaussianMixtureWithPriorComponent': + # TODO: Need to derive the type object of the prior from its name + # prior_type_name = state['prior_type'] + prior = GammaMixtureBase.from_json(state['prior']) + return cls(state['mus'], state['sigmas'], prior, state['weights']) + + def _logpdf(self, X, k): + if k == self.n_components - 1: + return np.log(np.exp(self.prior.logpdf(X, weighted=False)).dot(self.prior.weights)) + else: + return super(GaussianMixtureWithPriorComponent, self)._logpdf(X, k) + + @classmethod + def fit(cls, X: np.ndarray, n_components: int, prior: MixtureBase, maxiter=1000, tol=1e-5, deterministic=True) -> 'GaussianMixtureWithPriorComponent': + if not deterministic: + mus = KMeans.fit(X, n_components).means + else: + mus = (np.max(X) / (n_components + 1)) * np.arange(1, n_components + 1) + assert not np.any(np.isnan(mus)) + sigmas = np.var(X) * np.ones_like(mus) + weights = np.ones(n_components + 1) / (n_components + 1) + inst = cls(mus, sigmas, prior, weights) + inst.estimate(X, maxiter=maxiter, tol=tol) + return inst + + def estimate(self, X: np.ndarray, maxiter=1000, tol=1e-5): + for i in range(maxiter): + # E-step + responsibility = self.responsibility(X) + + # M-step + new_mus = np.zeros_like(self.mus) + new_sigmas = np.zeros_like(self.sigmas) + prev_loglikelihood = self.loglikelihood(X) + new_weights = np.zeros_like(self.weights) + for k in range(self.n_components - 1): + self._update_params_for( + X, k, responsibility, new_mus, new_sigmas, new_weights) + + new_weights = responsibility.sum(axis=0) / responsibility.sum() + self.mus = new_mus + self.sigmas = new_sigmas + self.weights = new_weights + new_loglikelihood = self.loglikelihood(X) + delta_fit = (prev_loglikelihood - new_loglikelihood) / new_loglikelihood + if abs(delta_fit) < tol: + break + else: + pass + + def plot(self, ax=None, **kwargs): + ax = super(GaussianMixtureWithPriorComponent, self).plot(ax=ax, **kwargs) + X = np.arange(self.prior.domain[0], self.mus.max() + self.sigmas.max() * 4, 0.01) + Y = self.prior.score(X) * self.weights[-1] + ax.plot(X, Y, **kwargs) + return ax + + +class TruncatedGaussianMixtureWithPriorComponent(_TruncatedNormalMixin, GaussianMixtureWithPriorComponent): + + @classmethod + def fit(cls, X, n_components, prior, maxiter=1000, tol=1e-5, deterministic=True) -> 'TruncatedGaussianMixtureWithPriorComponent': + if not deterministic: + mus = KMeans.fit(X, n_components).means + else: + mus = (np.max(X) / (n_components + 1)) * \ + np.arange(1, n_components + 1) + assert not np.any(np.isnan(mus)) + mus[0] = 0.0 + sigmas = np.var(X) * np.ones_like(mus) + weights = np.ones(n_components + 1) / (n_components + 1) + inst = cls(mus, sigmas, prior, weights) + inst.estimate(X, maxiter=maxiter, tol=tol) + return inst + + def _logpdf(self, X, k): + if k == self.n_components - 1: + return np.log(np.exp(self.prior.logpdf(X, weighted=False)).dot(self.prior.weights)) + else: + return _TruncatedNormalMixin._logpdf(self, X, k) + + def _update_params_for(self, X, k, responsibility, new_mus, new_sigmas, new_weights): + # The expressions for each partial derivative may be useful for understanding + # portions of this block. + # See http://www.notenoughthoughts.net/posts/normal-log-likelihood-gradient.html + g = responsibility[:, k] + N_k = g.sum() + # Begin specialization for Gaussian distributions + diff = X - self.mus[k] + if k == 0: + mu_k = 0.0 + else: + mu_k = g.dot(X) / N_k + new_mus[k] = mu_k + sigma_k = (g * diff).dot(diff.T) / N_k + 1e-6 + new_sigmas[k] = np.sqrt(sigma_k) + new_weights[k] = N_k + + +class PredictorBase(Protocol): + def predict(self, value: Union[float, ArrayLike]) -> Union[float, ArrayLike]: + ... + + +class KDModel(PredictorBase): + positive_probabilities: array + negative_probabilities: array + values: array + + positive_prior: float + + positive_kernel_fit: stats.gaussian_kde + negative_kernel_fit: stats.gaussian_kde + + def __init__(self, + positive_prior: float=None, + positive_probabilities: array=None, + negative_probabilities: array=None, + values: array=None): + if positive_probabilities is None: + positive_probabilities = array('d') + if negative_probabilities is None: + negative_probabilities = array('d') + if values is None: + values = array('d') + if positive_prior is None: + positive_prior = 0.5 + + self.positive_probabilities = positive_probabilities + self.negative_probabilities = negative_probabilities + self.values = values + + self.positive_prior = positive_prior + + self.positive_kernel_fit = None + self.negative_kernel_fit = None + + def add(self, prob: float, val: float): + self.positive_probabilities.append(prob) + self.negative_probabilities.append(1 - prob) + self.values.append(val) + + def fit(self, maxiter: int=10): + lastprobsum = self.update() + + i = 0 + while i < maxiter: + probsum = self.update() + i += 1 + if abs(probsum - lastprobsum) < 0.001: + break + lastprobsum = probsum + + def update_fits(self): + self.positive_kernel_fit = GaussianKDE( + self.values, weights=self.positive_probabilities) + self.negative_kernel_fit = GaussianKDE( + self.values, weights=self.negative_probabilities) + + def update(self): + self.update_fits() + probs = self.predict(self.values) + count = len(probs) + probsum = np.sum(probs) + self.positive_prior = probsum / count + self.positive_probabilities = probs + self.negative_probabilities = 1 - probs + return probsum + + def predict(self, value: float) -> float: + if self.positive_kernel_fit is None: + raise TypeError(""Cannot predict with a model that has not been fit yet"") + + p = self.predict_positive(value) + n = self.predict_negative(value) + + pos_prior = self.positive_prior + neg_prior = 1 - pos_prior + return (p * pos_prior) / ((p * pos_prior) + (n * neg_prior)) + + def predict_positive(self, value: float) -> float: + return self.positive_kernel_fit.pdf(value) + + def predict_negative(self, value: float) -> float: + return self.negative_kernel_fit.pdf(value) + + +class GaussianKDE(stats.gaussian_kde): + '''To control overriding methods, use a derived class''' + pass + + +KDE_USE_THREADS = True +try: + from glycresoft._c.structure.probability import evaluate_gaussian_kde + GaussianKDE.evaluate = evaluate_gaussian_kde +except ImportError as err: + print(err) + KDE_USE_THREADS = False + + +class MultiKDModel(PredictorBase): + models: List[KDModel] + values: List[array] + positive_prior: float + + use_threads: bool + thread_pool: Optional[ThreadPoolExecutor] + + def __init__(self, + positive_prior: float=None, + models: List[KDModel]=None, + values: array=None, + use_threads: bool=KDE_USE_THREADS): + if positive_prior is None: + positive_prior = 0.5 + if models is None: + models = [] + if values is None: + values = [array('d') for m in models] + self.models = models + self.positive_prior = positive_prior + self.values = values + self.use_threads = use_threads + self.thread_pool = None + if self.use_threads: + self.thread_pool = ThreadPoolExecutor() + + def __getstate__(self): + state = { + 'positive_prior': self.positive_prior, + 'models': self.models, + 'values': self.values, + } + return state + + def __setstate__(self, state): + self.positive_prior = state['positive_prior'] + self.models = state['models'] + self.values = state['values'] + + def __reduce__(self): + return self.__class__, (), self.__getstate__() + + def add_model(self, model: KDModel): + self.models.append(model) + self.values.append(model.values) + + def add(self, prob: float, values: List[float]): + for val, mod, valn in zip(values, self.models, self.values): + mod.add(prob, val) + valn.append(val) + + def update_fits(self): + for model in self.models: + model.update_fits() + + def close_thread_pool(self): + if self.use_threads: + if self.thread_pool is not None: + self.thread_pool.shutdown() + self.thread_pool = None + self.use_threads = False + + def create_thread_pool(self): + self.use_threads = True + self.thread_pool = ThreadPoolExecutor() + + def update(self): + self.update_fits() + probs = self.predict(self.values) + count = len(probs) + probsum = np.sum(probs) + self.positive_prior = probsum / count + for mod in self.models: + mod.positive_probabilities = probs + mod.negative_probabilities = 1 - probs + return probsum + + def predict_positive(self, values: List[float]) -> float: + acc = 0 + if self.use_threads: + jobs = [] + for mod, val in zip(self.models, values): + jobs.append(self.thread_pool.submit(mod.positive_kernel_fit.evaluate, val)) + + for job in jobs: + acc += np.log(job.result()) + else: + for mod, val in zip(self.models, values): + acc += np.log(mod.positive_kernel_fit.evaluate(val)) + return np.exp(acc) + + def predict_negative(self, values: List[float]) -> float: + acc = 0 + if self.use_threads: + jobs = [] + for mod, val in zip(self.models, values): + jobs.append(self.thread_pool.submit( + mod.negative_kernel_fit.evaluate, val)) + + for job in jobs: + acc += np.log(job.result()) + else: + for mod, val in zip(self.models, values): + acc += np.log(mod.negative_kernel_fit.evaluate(val)) + return np.exp(acc) + + def predict(self, values: List[float]) -> float: + if self.use_threads: + p_fut = self.thread_pool.submit(self.predict_positive, values) + n_fut = self.thread_pool.submit(self.predict_negative, values) + p = p_fut.result() + n = n_fut.result() + else: + p = self.predict_positive(values) + n = self.predict_negative(values) + + pos_prior = self.positive_prior + neg_prior = 1 - pos_prior + return (p * pos_prior) / ((p * pos_prior) + (n * neg_prior)) + + def fit(self, maxiter: int=10, convergence: float=0.001): + lastprobsum = self.update() + delta = float('inf') + i = 1 + while i < maxiter: + probsum = self.update() + i += 1 + delta = abs(probsum - lastprobsum) + if delta < convergence: + break + lastprobsum = probsum + return i, delta +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/structure/scan.py",".py","6022","202","from typing import Optional, Union +from weakref import WeakValueDictionary + +from ms_deisotope.data_source import ProcessedScan, PrecursorInformation, ActivationInformation, Scan +from ms_deisotope.data_source import ProcessedRandomAccessScanSource + + +class ScanStub(object): + """"""A stub for holding precursor information and + giving a Scan-like interface for accessing just that + information. Provides a serialized-like interface + which clients can use to load the real scan. + + Attributes + ---------- + id : str + The scan ID for the proxied scan + precursor_information : :class:`~.PrecursorInformation` + The information describing the relevant + metadata for scheduling when and where this + scan should be processed, where actual loading + will occur. + source : :class:`~.RandomAccessScanSource` + A resource to use to load scans with by scan id. + """""" + + id: str + precursor_information: PrecursorInformation + source: Optional[ProcessedRandomAccessScanSource] + + def __init__(self, precursor_information: PrecursorInformation, source: ProcessedRandomAccessScanSource): + self.id = precursor_information.product_scan_id + self.precursor_information = precursor_information + self.source = source + + def detatch(self) -> 'ScanStub': + self.source = None + self.precursor_information.source = None + return self + + def unbind(self): + return self.detatch() + + def bind(self, source): + self.source = source + self.precursor_information.source = source + return self + + @property + def scan_id(self): + return self.id + + def convert(self, *args, **kwargs) -> Union[ProcessedScan, Scan]: + try: + return self.source.get_scan_by_id(self.id) + except AttributeError: + raise KeyError(self.id) + + def __repr__(self): + template = ""{self.__class__.__name__}({self.precursor_information.neutral_mass}, {self.precursor_information})"" + return template.format(self=self) + + +class ScanWrapperBase(object): + __slots__ = [] + + scan: Union[ProcessedScan, Scan] + + @property + def scan_id(self): + self.requires_scan() + return self.scan.scan_id + + @property + def precursor_ion_mass(self): + self.requires_scan() + neutral_mass = self.scan.precursor_information.extracted_neutral_mass + if neutral_mass == 0: + neutral_mass = self.scan.precursor_information.neutral_mass + return neutral_mass + + @property + def scan_time(self): + self.requires_scan() + return self.scan.scan_time + + @property + def precursor_information(self): + self.requires_scan() + return self.scan.precursor_information + + def requires_scan(self): + if self.scan is None: + raise ValueError(""%s is detatched from Scan"" % (self.__class__.__name__)) + + @property + def ms_level(self): + self.requires_scan() + return self.scan.ms_level + + @property + def index(self): + self.requires_scan() + return self.scan.index + + @property + def activation(self): + self.requires_scan() + return self.scan.activation + + @property + def deconvoluted_peak_set(self): + self.requires_scan() + return self.scan.deconvoluted_peak_set + + @property + def peak_set(self): + self.requires_scan() + return self.scan.peak_set + + @property + def arrays(self): + self.requires_scan() + return self.scan.arrays + + @property + def annotations(self): + self.requires_scan() + return self.scan.annotations + + +class ScanInformation(object): + """"""A carrier of scan-level metadata that does not include peak data to reduce space + consumption. + """""" + + __slots__ = (""id"", ""index"", ""scan_time"", ""ms_level"", + ""precursor_information"", ""activation"", + ""title"", ""__weakref__"") + + id: str + index: int + scan_time: float + ms_level: int + precursor_information: PrecursorInformation + activation: ActivationInformation + title: str + + def __init__(self, scan_id, index, scan_time, ms_level, precursor_information, activation=None, title=None): + self.id = scan_id + self.index = index + self.scan_time = scan_time + self.ms_level = ms_level + self.precursor_information = precursor_information + self.activation = activation + self.title = title + + def __reduce__(self): + return self.__class__, (self.id, self.index, self.scan_time, self.ms_level, + self.precursor_information, self.activation, self.title) + + @property + def scan_id(self): + return self.id + + @classmethod + def from_scan(cls, scan): + return cls( + scan.scan_id, scan.index, scan.scan_time, scan.ms_level, + scan.precursor_information, scan.activation, scan.title) + + def __repr__(self): + template = (""{self.__class__.__name__}({self.id}, {self.index}, {self.scan_time}, "" + ""{self.ms_level}, {self.precursor_information}, {self.activation}, {self.title})"") + return template.format(self=self) + + +class ScanInformationLoader(object): + scan_loader: ProcessedRandomAccessScanSource + + def __init__(self, scan_loader): + self.scan_loader = scan_loader + self.cache = WeakValueDictionary() + + def get_scan_by_id(self, scan_id): + try: + return self.cache[scan_id] + except KeyError: + scan = self.scan_loader.get_scan_by_id(scan_id) + info = ScanInformation.from_scan(scan) + self.cache[scan_id] = info + return info + + +def top_n_peaks(scan: ProcessedScan, n: int=300) -> ProcessedScan: + scan = scan.clone(deep=True) + peaks = scan.deconvoluted_peak_set.__class__(sorted( + scan.deconvoluted_peak_set, key=lambda x: x.intensity, reverse=True)[:n]) + peaks.reindex() + scan.deconvoluted_peak_set = peaks + return scan +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/structure/lru.py",".py","4814","187","class LRUNode(object): + + def __init__(self, data, forward, backward): + self.data = data + self.forward = forward + self.backward = backward + + def __hash__(self): + return hash(self.data) + + def __eq__(self, other): + return self.data == other.data + + def __repr__(self): + return ""LRUNode(%s)"" % self.data + + +class LRUCache(object): + + def __init__(self): + self.head = LRUNode(None, None, None) + self.head.forward = self.head + self.head.backward = self.head + self._mapping = dict() + + def move_node_up(self, node): + was_head_lru = self.head.backward is self.head + if was_head_lru: + raise ValueError(""Head cannot be LRU"") + mover_forward = node.forward + mover_backward = node.backward + + pushed = self.head.forward + # If the most-recently used node is being moved up, + # short-circuit + if pushed == node: + return + # If the node being moved up happens to form a cycle with + # the head node, (which should technically be handled by the + # above short-circuit) don't make any changes as this will + # lead to a detached head node. + if mover_backward is self.head and mover_forward is self.head: + return + mover_backward.forward = mover_forward + mover_forward.backward = mover_backward + + pushed.backward = node + + node.backward = self.head + node.forward = pushed + + self.head.forward = node + now_head_lru = self.head.backward is self.head + if now_head_lru: + raise ValueError(""Head became LRU!"") + + def add_node(self, data): + if data in self._mapping: + self.hit_node(data) + return + node = LRUNode(data, None, None) + + pushed = self.head.forward + self.head.forward = node + node.backward = self.head + node.forward = pushed + pushed.backward = node + + self._mapping[node.data] = node + + def get_least_recently_used(self): + lru = self.head.backward + if lru is self.head: + raise ValueError(""Head node cannot be LRU!"") + return lru.data + + def hit_node(self, k): + out = self._mapping[k] + self.move_node_up(out) + + def unspool(self): + chain = [] + current = self.head + while current.forward is not self.head: + chain.append(current) + current = current.forward + chain.append(current) + return chain + + def remove_node(self, data): + # print(""Removing "", data, id(data)) + node = self._mapping[data] + fwd = node.forward + # assert fwd is not node + bck = node.backward + # assert bck is not node + fwd.backward = bck + bck.forward = fwd + self._mapping.pop(data) + # assert node not in self.unspool()[1:] + # print(""Removed"") + + def clear(self): + self.head = LRUNode(None, None, None) + self.head.forward = self.head + self.head.backward = self.head + self._mapping.clear() + + +try: + from glycresoft._c.structure.lru import LRUCache, LRUNode +except ImportError: + pass + + +class LRUMapping(object): + def __init__(self, max_size=512): + self.max_size = max_size + self.store = dict() + self.lru = LRUCache() + + def __getitem__(self, key): + value = self.store[key] + self.lru.hit_node(key) + return value + + def __setitem__(self, key, value): + self.lru.add_node(key) + self.store[key] = value + self._check_size() + + def __delitem__(self, key): + del self.store[key] + self.lru.remove_node(key) + + def _check_size(self): + n = len(self.store) + while n > self.max_size: + key = self.lru.get_least_recently_used() + self.store.pop(key) + self.lru.remove_node(key) + n -= 1 + + def __contains__(self, key): + contained = key in self.store + return contained + + def __iter__(self): + return iter(self.store) + + def __len__(self): + return len(self.store) + + def keys(self): + return self.store.keys() + + def values(self): + return self.store.values() + + def items(self): + return self.store.items() + + def get(self, key, default=None): + try: + value = self[key] + return value + except KeyError: + return default + + def pop(self, key, default=None): + try: + value = self[key] + del self[key] + return value + except KeyError: + return default + + def clear(self): + self.store.clear() + self.lru.clear() + + +try: + from glycresoft._c.structure.lru import LRUMapping +except ImportError: + pass +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/structure/__init__.py",".py","1131","43","from .lru import LRUCache, LRUNode, LRUMapping +from .structure_loader import ( + CachingGlycanCompositionParser, + CachingGlycopeptideParser, + FragmentCachingGlycopeptide, + PeptideProteinRelation, + DecoyFragmentCachingGlycopeptide, + SequenceReversingCachingGlycopeptideParser, + GlycopeptideCache, + CachingPeptideParser, + PeptideDatabaseRecord,) + +from .scan import ( + ScanStub, + ScanWrapperBase, + ScanInformation, + ScanInformationLoader) +from .fragment_match_map import FragmentMatchMap, SpectrumGraph +from .utils import KeyTransformingDecoratorDict + + +__all__ = [ + ""LRUNode"", + ""LRUCache"", + ""LRUMapping"", + ""CachingGlycanCompositionParser"", + ""CachingGlycopeptideParser"", + ""CachingPeptideParser"", + ""FragmentCachingGlycopeptide"", + ""PeptideProteinRelation"", + ""DecoyFragmentCachingGlycopeptide"", + ""SequenceReversingCachingGlycopeptideParser"", + ""GlycopeptideCache"", + ""ScanStub"", + ""ScanWrapperBase"", + ""ScanInformation"", + ""ScanInformationLoader"", + ""FragmentMatchMap"", + ""SpectrumGraph"", + ""KeyTransformingDecoratorDict"", + ""PeptideDatabaseRecord"", +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/structure/structure_loader.py",".py","33603","954","import operator + +from collections import defaultdict, namedtuple +from functools import partial + +from typing import Any, Callable, ClassVar, Dict, Iterable, Type, Union, Optional, Tuple, List + +import numpy as np + +from ms_deisotope.peak_dependency_network.intervals import SpanningMixin + +from glycopeptidepy.structure.composition import Composition +from glycopeptidepy.structure.sequence import PeptideSequence +from glycopeptidepy.structure.parser import sequence_tokenizer +from glycopeptidepy.algorithm import reverse_preserve_sequon +from glycopeptidepy.structure.glycan import HashableGlycanComposition, GlycanCompositionWithOffsetProxy +from glycopeptidepy.structure.fragmentation_strategy import StubGlycopeptideStrategy, EXDFragmentationStrategy +from glycopeptidepy.structure.fragment import SimpleFragment, FragmentBase, PeptideFragment, StubFragment + +from .lru import LRUCache + +try: + from glycopeptidepy.structure.fragmentation_strategy.peptide import CachingEXDFragmentationStrategy +except ImportError: + CachingEXDFragmentationStrategy = EXDFragmentationStrategy + +CachingEXDFragmentationStrategy = EXDFragmentationStrategy + + + + +class GlycanCompositionCache(Dict[str, HashableGlycanComposition]): + pass + + +class CachingGlycanCompositionParser(object): + cache: GlycanCompositionCache + cache_size: int + lru: LRUCache + + def __init__(self, cache_size=4000): + self.cache = GlycanCompositionCache() + self.cache_size = cache_size + self.lru = LRUCache() + + def _check_cache_valid(self): + lru = self.lru + while len(self.cache) > self.cache_size: + key = lru.get_least_recently_used() + lru.remove_node(key) + value = self.cache.pop(key) + try: + value.clear_caches() + except AttributeError: + pass + + def _make_new_value(self, struct) -> HashableGlycanComposition: + value = HashableGlycanComposition.parse(struct.composition) + value.id = struct.id + return value + + def _populate_cache(self, struct, key: str) -> HashableGlycanComposition: + self._check_cache_valid() + value = self._make_new_value(struct) + self.cache[key] = value + self.lru.add_node(key) + return value + + def _extract_key(self, struct) -> str: + return struct.composition + + def parse(self, struct) -> HashableGlycanComposition: + struct_key = self._extract_key(struct) + try: + seq = self.cache[struct_key] + self.lru.hit_node(struct_key) + return seq + except KeyError: + return self._populate_cache(struct, struct_key) + + def __call__(self, value: str) -> HashableGlycanComposition: + return self.parse(value) + + +class TextHashableGlycanCompositionParser(object): + cache: Dict[str, HashableGlycanComposition] + size: int + + def __init__(self, size=int(2**16)): + # self.cache = LRUMapping(size) + self.cache = {} + self.size = size + + def _parse(self, text: str) -> HashableGlycanComposition: + return HashableGlycanComposition.parse(text) + + def parse(self, text: str) -> GlycanCompositionWithOffsetProxy: + try: + return GlycanCompositionWithOffsetProxy(self.cache[text]) + except KeyError: + inst = self._parse(text) + if len(self.cache) > self.size and self.size != -1: + self.cache.popitem() + self.cache[text] = inst + return GlycanCompositionWithOffsetProxy(inst) + + def __call__(self, text: str): + return self.parse(text) + + +_glycan_parser = TextHashableGlycanCompositionParser() + +hashable_glycan_glycopeptide_parser = partial( + sequence_tokenizer, glycan_parser_function=_glycan_parser) + + +class GlycanFragmentCache(object): + cache: Dict[str, List[SimpleFragment]] + + def __init__(self): + self.cache = dict() + + def get_oxonium_ions(self, glycopeptide: PeptideSequence) -> List[SimpleFragment]: + key = str(glycopeptide.glycan) + try: + return self.cache[key] + except KeyError: + oxonium_ions = list(glycopeptide._glycan_fragments()) + self.cache[key] = oxonium_ions + return oxonium_ions + + def __call__(self, glycopeptide: PeptideSequence) -> List[SimpleFragment]: + return self.get_oxonium_ions(glycopeptide) + + def update(self, source): + if isinstance(source, dict): + self.cache.update(source) + else: + self.cache.update(source.cache) + + def populate(self, glycan_composition_iterator: Iterable[HashableGlycanComposition]): + # A template peptide sequence which won't matter + peptide = PeptideSequence(""PEPTIDE"") + # Pretend to support the backdoor method + peptide._glycan_fragments = peptide.glycan_fragments + # Attach each glycan composition to the peptide and + # calculate oxonium ions and cache them ahead of time. + for gc in glycan_composition_iterator: + gc = gc.clone() + peptide.glycan = gc + self(peptide) + + +oxonium_ion_cache = GlycanFragmentCache() + + +class PeptideProteinRelation(SpanningMixin): + __slots__ = [""protein_id"", ""hypothesis_id""] + + start: float + end: float + protein_id: int + hypothesis_id: int + + def __init__(self, start_position, end_position, protein_id, hypothesis_id): # pylint: disable=super-init-not-called + self.start = start_position + self.end = end_position + self.protein_id = protein_id + self.hypothesis_id = hypothesis_id + + @property + def start_position(self) -> int: + return int(self.start) + + @start_position.setter + def start_position(self, value: int): + self.start = value + + @property + def end_position(self) -> int: + return int(self.end) + + @end_position.setter + def end_position(self, value: int): + self.end = value + + def __repr__(self): + return ""PeptideProteinRelation(%d, %d, %r, %r)"" % ( + self.start_position, self.end_position, self.protein_id, self.hypothesis_id) + + def __iter__(self): + yield self.start_position + yield self.end_position + yield self.protein_id + yield self.hypothesis_id + + def __reduce__(self): + return self.__class__, tuple(self) + + def __eq__(self, other): + return (self.start_position == other.start_position and + self.end_position == other.end_position and + self.protein_id == other.protein_id and + self.hypothesis_id == other.hypothesis_id) + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return hash((self.start_position, self.end_position)) + + +class NamedPeptideProteinRelation(PeptideProteinRelation): + __slots__ = (""protein_name"", ) + + protein_name: str + + def __init__(self, start_position, end_position, protein_id, hypothesis_id, protein_name=None): + super(NamedPeptideProteinRelation, self).__init__( + start_position, end_position, protein_id, hypothesis_id) + self.protein_name = protein_name + + def __iter__(self): + yield self.start_position + yield self.end_position + yield self.protein_id + yield self.hypothesis_id + yield self.protein_name + + def __reduce__(self): + return self.__class__, tuple(self) + + def __eq__(self, other): + coords = (self.start_position == other.start_position and + self.end_position == other.end_position) + if coords: + if self.protein_name is not None: + try: + coords = self.protein_name == other.protein_name + except AttributeError: + coords = self.protein_id == other.protein_id + else: + coords = self.protein_id == other.protein_id + return coords + + +# Add a new default attribute value to the parent class so all future instances +# of the parent class (and all sub-classes) have a fallback value. +PeptideSequence.glycan_prior = 0.0 + + +class GlycopeptideFragmentCachingContext(object): + __slots__ = ('store', ) + + store: Dict[Tuple[str, tuple, frozenset], List[FragmentBase]] + + def __init__(self, store=None): + if store is None: + store = {} + self.store = store + + def peptide_backbone_fragment_key(self, target, args, kwargs): + key = (""get_fragments"", args, frozenset(kwargs.items())) + return key + + def stub_fragment_key(self, target, args, kwargs): + key = ('stub_fragments', args, frozenset(kwargs.items()), ) + return key + + def __getitem__(self, key): + return self.store[key] + + def __setitem__(self, key, value): + self.store[key] = value + + def keys(self): + return self.store.keys() + + def values(self): + return self.store.values() + + def items(self): + return self.store.items() + + def clear(self): + self.store.clear() + + def bind(self, target: 'FragmentCachingGlycopeptide') -> 'FragmentCachingGlycopeptide': + target.fragment_caches = self + return target + + def unbind(self, target: 'FragmentCachingGlycopeptide'): + target.fragment_caches = self.__class__() + return target + + def __call__(self, target: 'FragmentCachingGlycopeptide') -> 'FragmentCachingGlycopeptide': + return self.bind(target) + + def _make_target_key(self, key): + # value = key[-1] + # as_target_peptide = StructureClassification[int(value) ^ 1] + # new_key = key[:-1] + (as_target_peptide, ) + # return new_key + return None + + +try: + from glycresoft._c.structure.structure_loader import peptide_backbone_fragment_key + GlycopeptideFragmentCachingContext.peptide_backbone_fragment_key = peptide_backbone_fragment_key +except ImportError: + pass + + +class GlycanAwareGlycopeptideFragmentCachingContext(GlycopeptideFragmentCachingContext): + def stub_fragment_key(self, target, args, kwargs): + tid = target.id + key = ('stub_fragments', args, frozenset( + kwargs.items()), tid.glycan_combination_id, tid.structure_type) + return key + + def _make_target_key(self, key): + from glycresoft.tandem.glycopeptide.dynamic_generation.search_space import StructureClassification + value = key[-1] + as_target_peptide = StructureClassification[int(value) ^ 1] + new_key = key[:-1] + (as_target_peptide, ) + return new_key + +try: + from glycresoft._c.structure.structure_loader import GlycopeptideFragmentCachingContext, GlycanAwareGlycopeptideFragmentCachingContext +except ImportError as err: + print(err) + + +class FragmentCachingGlycopeptide(PeptideSequence): + __slots__ = ('fragment_caches', 'protein_relation', 'id', 'glycan_prior') + + fragment_caches: GlycopeptideFragmentCachingContext + protein_relation: PeptideProteinRelation + id: Union[int, Any] + glycan_prior: float + + _exd_glycan_channel = None + + def __init__(self, *args, **kwargs): + kwargs.setdefault('parser_function', hashable_glycan_glycopeptide_parser) + super(FragmentCachingGlycopeptide, self).__init__(*args, **kwargs) + self.fragment_caches = GlycopeptideFragmentCachingContext() + self.protein_relation = None + self.id = None + self.glycan_prior = 0.0 + + def __reduce__(self): + return self.__class__, (str(self), ), self.__getstate__() + + def __getstate__(self): + state = {} + state['protein_relation'] = self.protein_relation + state['id'] = self.id + state['glycan_prior'] = self.glycan_prior + return state + + def __setstate__(self, state): + self.protein_relation = state['protein_relation'] + self.id = state['id'] + self.glycan_prior = state.get('glycan_prior', 0.0) + + def __eq__(self, other): + try: + return (self.protein_relation == other.protein_relation) and ( + super(FragmentCachingGlycopeptide, self).__eq__(other)) + except AttributeError: + return super(FragmentCachingGlycopeptide, self).__eq__(other) + + __hash__ = PeptideSequence.__hash__ + + def __ne__(self, other): + return not self == other + + def _make_exd_glycan_channel(self): + is_all_core = True + tokens = [] + for i, g in self.glycosylation_manager.items(): + if not g.rule.is_core: + is_all_core = False + tokens.append((i, str(g))) + tokens.sort() + if is_all_core: + tokens.append(str(self.glycan_composition)) + return tuple(tokens) + + def get_fragments(self, *args, **kwargs) -> List[PeptideFragment]: # pylint: disable=arguments-differ + strategy = kwargs.get('strategy') + if strategy == EXDFragmentationStrategy: + kwargs['strategy'] = CachingEXDFragmentationStrategy + if strategy is not None: + if issubclass(strategy, EXDFragmentationStrategy): + if self._exd_glycan_channel is None: + self._exd_glycan_channel = self._make_exd_glycan_channel() + kwargs.setdefault(""glycan_channel"", self._exd_glycan_channel) + key = self.fragment_caches.peptide_backbone_fragment_key(self, args, kwargs) + if key in self.fragment_caches: + return self.fragment_caches[key] + else: + result = list(super(FragmentCachingGlycopeptide, self).get_fragments(*args, **kwargs)) + self.fragment_caches[key] = result + return result + + def stub_fragments(self, *args, **kwargs) -> List[StubFragment]: # pylint: disable=arguments-differ + kwargs.setdefault(""strategy"", CachingStubGlycopeptideStrategy) + key = self.fragment_caches.stub_fragment_key(self, args, kwargs) + if key in self.fragment_caches: + return self.fragment_caches[key] + else: + result = super(FragmentCachingGlycopeptide, self).stub_fragments(*args, **kwargs).stub_fragments() + self.fragment_caches[key] = result + return result + + def _glycan_fragments(self) -> List[SimpleFragment]: + return list(super(FragmentCachingGlycopeptide, self).glycan_fragments(oxonium=True)) + + def glycan_fragments(self, *args, **kwargs) -> List[SimpleFragment]: # pylint: disable=arguments-differ + return oxonium_ion_cache(self) + + def clear_caches(self): + self.fragment_caches = GlycopeptideFragmentCachingContext() + + def clone(self, *args, **kwargs): # pylint: disable=arguments-differ + share_cache = kwargs.pop(""share_cache"", True) + new = super(FragmentCachingGlycopeptide, self).clone(*args, **kwargs) + new.id = self.id + new.protein_relation = self.protein_relation + # Intentionally share caches with offspring + if share_cache: + new.fragment_caches = self.fragment_caches + return new + + def __repr__(self): + return str(self) + + +KeyTuple = namedtuple(""KeyTuple"", ['id', 'sequence']) + + +class GlycopeptideCache(object): + sequence_map: Dict[str, FragmentCachingGlycopeptide] + key_map: Dict[KeyTuple, str] + + def __init__(self): + self.sequence_map = dict() + self.key_map = dict() + + def __getitem__(self, key: KeyTuple) -> FragmentCachingGlycopeptide: + try: + result = self.key_map[key] + return result + except KeyError: + value = self.sequence_map[key.sequence] + value = value.clone() + self.key_map[key] = value + return value + + def __setitem__(self, key: KeyTuple, value: FragmentCachingGlycopeptide): + self.key_map[key] = value + self.sequence_map[key.sequence] = value + + def __len__(self): + return len(self.key_map) + + def pop(self, key: KeyTuple): + self.key_map.pop(key) + return self.sequence_map.pop(key.sequence, None) + + +class CachingGlycopeptideParser(object): + __slots__ = ('cache', 'cache_size', 'lru', 'churn', 'sequence_cls') + + cache: GlycopeptideCache + cache_size: int + lru: LRUCache + churn: int + sequence_cls: Type[FragmentCachingGlycopeptide] + + def __init__(self, cache_size=4000, sequence_cls=FragmentCachingGlycopeptide): + self.cache = GlycopeptideCache() + self.cache_size = cache_size + self.lru = LRUCache() + self.churn = 0 + self.sequence_cls = sequence_cls + + def _check_cache_valid(self): + lru = self.lru + while len(self.cache) > self.cache_size: + self.churn += 1 + key = lru.get_least_recently_used() + lru.remove_node(key) + value = self.cache.pop(key) + try: + value.clear_caches() + except AttributeError: + pass + + def _make_new_value(self, struct): + value = self.sequence_cls(struct.glycopeptide_sequence) + value.id = struct.id + value.protein_relation = PeptideProteinRelation( + struct.start_position, struct.end_position, + struct.protein_id, struct.hypothesis_id) + return value + + def _populate_cache(self, struct, key: KeyTuple): + self._check_cache_valid() + value = self._make_new_value(struct) + self.cache[key] = value + self.lru.add_node(key) + return value + + def _extract_key(self, struct): + return KeyTuple(struct.id, struct.glycopeptide_sequence) + + def parse(self, struct): + struct_key = self._extract_key(struct) + try: + seq = self.cache[struct_key] + self.lru.hit_node(struct_key) + return seq + except KeyError: + return self._populate_cache(struct, struct_key) + + def __call__(self, value): + return self.parse(value) + + +class CachingPeptideParser(CachingGlycopeptideParser): + __slots__ = () + + def _make_new_value(self, struct): + value = self.sequence_cls(struct.modified_peptide_sequence) + value.id = struct.id + value.protein_relation = PeptideProteinRelation( + struct.start_position, struct.end_position, + struct.protein_id, struct.hypothesis_id) + return value + + def _extract_key(self, struct): + return KeyTuple(struct.id, struct.modified_peptide_sequence) + + +class DecoyEXDFragmentationStrategy(CachingEXDFragmentationStrategy): + shared_composition_fragment_cache_ambiguous = defaultdict(dict) + shared_composition_fragment_combination_cache_ambiguous = defaultdict( + dict + ) + + def _get_glycan_composition_fragments(self, modification, series: str, position: int): + fragments = super()._get_glycan_composition_fragments(modification, series, position) + shifts = DecoyFragmentCachingGlycopeptide.get_random_shifts_for( + self.peptide.glycan.mass(), + len(fragments), + 1.0, + 30.0 + ) + shifted = [] + for (frag, shift) in zip(fragments, shifts): + frag = frag.clone() + frag.mass += shift + shifted.append(frag) + return shifted + + +class DecoyFragmentCachingGlycopeptide(FragmentCachingGlycopeptide): + _random_shift_cache = dict() + + @classmethod + def get_random_shifts_for(cls, mass: float, n: int, low: float=1.0, high: float=30.0) -> np.ndarray: + seed = int(round(mass)) + key = (seed, n) + try: + return cls._random_shift_cache[key] + except KeyError: + rng = np.random.RandomState(seed) + rand_deltas = rng.uniform(low, high, n) + cls._random_shift_cache[key] = rand_deltas + return rand_deltas + + def _permute_stub_masses(self, stub_fragments: List[StubFragment], kwargs: Dict, do_clone: bool=False, + min_shift_size: int = 1) -> List[StubFragment]: + random_low = kwargs.get('random_low', 1.0) + random_high = kwargs.get(""random_high"", 30.0) + n = len(stub_fragments) + rand_deltas = self.get_random_shifts_for( + self.glycan_composition.mass(), + n, random_low, random_high) + + stub_fragments = self._clone_and_shift_stub_fragments( + stub_fragments, rand_deltas, do_clone, min_shift_size) + return stub_fragments + + @staticmethod + def _clone_and_shift_stub_fragments(stubs: List[StubFragment], rand_deltas: np.ndarray, + do_clone: bool=True, min_shift_size: int=1) -> List[StubFragment]: + i = 0 + if do_clone: + result = [] + for frag in stubs: + if do_clone: + frag = frag.clone() + if frag.glycosylation_size > min_shift_size: + delta = rand_deltas[i] + i += 1 + frag.mass += delta + if do_clone: + result.append(frag) + if do_clone: + return result + return stubs + + def get_fragments(self, *args, **kwargs) -> List[PeptideFragment]: + strat = kwargs.get(""strategy"") + if strat is not None and issubclass(strat, EXDFragmentationStrategy): + kwargs['strategy'] = DecoyEXDFragmentationStrategy + return super().get_fragments(*args, **kwargs) + + def stub_fragments(self, *args, **kwargs): + kwargs.setdefault(""strategy"", CachingStubGlycopeptideStrategy) + key = self.fragment_caches.stub_fragment_key(self, args, kwargs) + if key in self.fragment_caches: + return self.fragment_caches[key] + else: + result = list( + # Directly call the superclass method of FragmentCachingGlycopeptide as we + # do not need to go through a preliminary round of cache key construction and + # querying. + super(FragmentCachingGlycopeptide, self).stub_fragments( # pylint: disable=bad-super-call + *args, **kwargs)) + result = self._permute_stub_masses(result, kwargs, min_shift_size=1) + self.fragment_caches[key] = result + return result + + @classmethod + def from_target(cls, target: FragmentCachingGlycopeptide): + inst = cls() + if target._glycosylation_manager.aggregate is not None: + glycan = target._glycosylation_manager.aggregate.clone() + glycan.composition_offset = Composition(""H2O"") + else: + glycan = None + inst._init_from_components( + target.sequence, glycan, + target.n_term.modification, + target.c_term.modification) + try: + inst.id = target.id + inst.protein_relation = target.protein_relation + except AttributeError: + inst.protein_relation = None + # Intentionally share caches with offspring + inst.fragment_caches = inst.fragment_caches.__class__( + {k: v for k, v in target.fragment_caches.items() if 'stub_fragments' not in k}) + return inst + + +try: + from glycresoft._c.structure.structure_loader import ( + clone_and_shift_stub_fragments as _clone_and_shift_stub_fragments + ) + DecoyFragmentCachingGlycopeptide._clone_and_shift_stub_fragments = staticmethod( + _clone_and_shift_stub_fragments) +except ImportError: + pass + + +class CachingStubGlycopeptideStrategy(StubGlycopeptideStrategy): + _cache: ClassVar[Dict[Tuple, List]] = dict() + _o_glycan_cache: ClassVar[Dict[Tuple, List]] = dict() + + def n_glycan_composition_fragments(self, glycan, core_count=1, iteration_count=0): + key = (glycan.serialize(), core_count, iteration_count, self.extended | self.extended_fucosylation << 1) + try: + value = self._cache[key] + return value + except KeyError: + value = super(CachingStubGlycopeptideStrategy, self).n_glycan_composition_fragments( + glycan, core_count, iteration_count) + self._cache[key] = value + return value + + def o_glycan_composition_fragments(self, glycan, core_count=1, iteration_count=0): + key = (glycan.serialize(), core_count, iteration_count, self.extended | self.extended_fucosylation << 1) + try: + value = self._o_glycan_cache[key] + return value + except KeyError: + value = super(CachingStubGlycopeptideStrategy, self).o_glycan_composition_fragments( + glycan, core_count, iteration_count) + self._o_glycan_cache[key] = value + return value + + @classmethod + def update(cls, source): + cls._cache.update(source) + + @classmethod + def populate(cls, glycan_composition_iterator, **kwargs): + inst = cls(None, **kwargs) + for gc in glycan_composition_iterator: + gc = gc.clone() + inst.n_glycan_composition_fragments(gc, 1, 0) + + @classmethod + def get_cache(cls): + return cls._cache + + +class SequenceReversingCachingGlycopeptideParser(CachingGlycopeptideParser): + __slots__ = () + + def _make_new_value(self, struct): + value = self.sequence_cls(str(reverse_preserve_sequon(struct.glycopeptide_sequence))) + value.id = struct.id + value.protein_relation = PeptideProteinRelation( + struct.start_position, struct.end_position, + struct.protein_id, struct.hypothesis_id) + return value + + +class GlycopeptideDatabaseRecord(object): + __slots__ = [ + ""id"", ""calculated_mass"", + ""glycopeptide_sequence"", + ""protein_id"", + ""start_position"", + ""end_position"", + ""peptide_mass"", + ""hypothesis_id"" + ] + + def __init__(self, id, calculated_mass, glycopeptide_sequence, protein_id, + start_position, end_position, peptide_mass, hypothesis_id): + self.id = id + self.calculated_mass = calculated_mass + self.glycopeptide_sequence = glycopeptide_sequence + self.protein_id = protein_id + self.start_position = start_position + self.end_position = end_position + self.peptide_mass = peptide_mass + self.hypothesis_id = hypothesis_id + + def __reduce__(self): + return self.__class__, (self.id, self.calculated_mass, self.glycopeptide_sequence, self.protein_id, + self.start_position, self.end_position, self.peptide_mass, self.hypothesis_id) + + def __repr__(self): + template = ( + ""{self.__class__.__name__}(id={self.id}, calculated_mass={self.calculated_mass}, "" + ""glycopeptide_sequence={self.glycopeptide_sequence}, protein_id={self.protein_id}, "" + ""start_position={self.start_position}, end_position={self.end_position}, "" + ""peptide_mass={self.peptide_mass}, hypothesis_id={self.hypothesis_id}, "") + return template.format(self=self) + + +class PeptideDatabaseRecordBase(object): + __slots__ = ['id', ""calculated_mass"", ""modified_peptide_sequence"", ""protein_id"", ""start_position"", ""end_position"", + ""hypothesis_id"", ""n_glycosylation_sites"", ""o_glycosylation_sites"", ""gagylation_sites""] + + id: int + calculated_mass: float + modified_peptide_sequence: str + protein_id: int + start_position: int + end_position: int + hypothesis_id: int + + n_glycosylation_sites: List[int] + o_glycosylation_sites: List[int] + gagylation_sites: List[int] + + def __hash__(self): + return hash(self.modified_peptide_sequence) + + def __eq__(self, other): + if other is None: + return False + if self.id != other.id: + return False + if self.protein_id != other.protein_id: + return False + if abs(self.calculated_mass - other.calculated_mass) > 1e-3: + return False + if self.start_position != other.start_position: + return False + if self.end_position != other.end_position: + return False + if self.hypothesis_id != other.hypothesis_id: + return False + if self.n_glycosylation_sites != other.n_glycosylation_sites: + return False + if self.o_glycosylation_sites != other.o_glycosylation_sites: + return False + if self.gagylation_sites != other.gagylation_sites: + return False + return True + + def __ne__(self, other): + return not (self == other) + + def has_glycosylation_sites(self): + return (len(self.n_glycosylation_sites) + len(self.o_glycosylation_sites) + len(self.gagylation_sites)) > 0 + + @classmethod + def from_record(cls, record): + return cls(**record) + + +try: + from glycresoft._c.structure.structure_loader import PeptideDatabaseRecordBase +except ImportError: + pass + +class PeptideDatabaseRecord(PeptideDatabaseRecordBase): + __slots__ = () + + id: Any + calculated_mass: float + modified_peptide_sequence: str + protein_id: int + start_position: int + end_position: int + hypothesis_id: int + n_glycosylation_sites: Tuple[int] + o_glycosylation_sites: Tuple[int] + gagylation_sites: Tuple[int] + + @classmethod + def unshare_sites(cls, records: List['PeptideDatabaseRecord']): + site_share_cache = {} + for rec in records: + if rec.n_glycosylation_sites in site_share_cache: + rec.n_glycosylation_sites = site_share_cache[rec.n_glycosylation_sites] + else: + rec.n_glycosylation_sites = site_share_cache[rec.n_glycosylation_sites] = tuple( + rec.n_glycosylation_sites) + + if rec.o_glycosylation_sites in site_share_cache: + rec.o_glycosylation_sites = site_share_cache[rec.o_glycosylation_sites] + else: + rec.o_glycosylation_sites = site_share_cache[rec.o_glycosylation_sites] = tuple( + rec.o_glycosylation_sites) + + if rec.gagylation_sites in site_share_cache: + rec.gagylation_sites = site_share_cache[rec.gagylation_sites] + else: + rec.gagylation_sites = site_share_cache[rec.gagylation_sites] = tuple( + rec.gagylation_sites) + + def __init__(self, id, calculated_mass, modified_peptide_sequence, protein_id, start_position, end_position, + hypothesis_id, n_glycosylation_sites, o_glycosylation_sites, gagylation_sites): + self.id = id + self.calculated_mass = calculated_mass + self.modified_peptide_sequence = modified_peptide_sequence + self.protein_id = protein_id + self.start_position = start_position + self.end_position = end_position + self.hypothesis_id = hypothesis_id + self.n_glycosylation_sites = tuple(n_glycosylation_sites) + self.o_glycosylation_sites = tuple(o_glycosylation_sites) + self.gagylation_sites = tuple(gagylation_sites) + + def convert(self): + peptide = FragmentCachingGlycopeptide(self.modified_peptide_sequence) + peptide.id = self.id + rel = PeptideProteinRelation( + self.start_position, self.end_position, self.protein_id, self.hypothesis_id) + peptide.protein_relation = rel + return peptide + + def __repr__(self): + fields = ', '.join([""%s=%r"" % (n, getattr(self, n)) for n in [ + 'id', ""calculated_mass"", ""modified_peptide_sequence"", ""protein_id"", ""start_position"", ""end_position"", + ""hypothesis_id"", ""n_glycosylation_sites"", ""o_glycosylation_sites"", ""gagylation_sites""]]) + return ""{self.__class__.__name__}({fields})"".format(self=self, fields=fields) + + +class LazyGlycopeptide(object): + __slots__ = (""sequence"", ""id"", ""protein_relation"") + + sequence: str + id: Any + protein_relation: PeptideProteinRelation + + def __init__(self, sequence, id, protein_relation=None): + self.sequence = sequence + self.id = id + self.protein_relation = protein_relation + + def convert(self, sequence_cls: Optional[Type]=None) -> FragmentCachingGlycopeptide: + if sequence_cls is None: + sequence_cls = FragmentCachingGlycopeptide + inst = sequence_cls(self.sequence) + inst.id = self.id + inst.protein_relation = self.protein_relation + return inst + + def __iter__(self): + for pos in self.convert(): + yield pos + + def __getitem__(self, i): + return self.convert()[i] + + def __len__(self): + result = hashable_glycan_glycopeptide_parser(self.sequence) + return len(result[0]) + + @property + def glycan_composition(self): + result = hashable_glycan_glycopeptide_parser(self.sequence) + glycan_composition = result[2] + return glycan_composition + + def __repr__(self): + return ""{self.__class__.__name__}({self.sequence}, {self.id})"".format(self=self) + + def __str__(self): + return str(self.sequence) + + def __eq__(self, other): + return self.sequence == other.sequence and self.id == other.id + + def __hash__(self): + return hash(self.sequence) + + +class GlycanCompositionDeltaCache(object): + storage: Dict[Tuple[HashableGlycanComposition, HashableGlycanComposition], HashableGlycanComposition] + + op: Callable[[HashableGlycanComposition, HashableGlycanComposition], HashableGlycanComposition] + + def __init__(self, storage=None, op=None): + if op is None: + op = operator.sub + if storage is None: + storage = {} + self.storage = storage + self.op = op + + def __call__(self, x: HashableGlycanComposition, y: HashableGlycanComposition) -> HashableGlycanComposition: + key = (x, y) + try: + return self.storage[key] + except KeyError: + delta = self.op(x, y) + self.storage[key] = delta + return delta +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/structure/fragment_match_map.py",".py","13271","433","from typing import Any, List, Optional, Sequence, Set, Tuple, Union, Generic, TypeVar, DefaultDict, Iterable + +from collections import defaultdict + +import numpy as np + +import ms_deisotope +from glycopeptidepy.structure.fragment import FragmentBase + + +K = TypeVar(""K"") +V = TypeVar(""V"") + + + +class PeakFragmentPair(object): + __slots__ = [""peak"", ""fragment"", ""fragment_name"", ""_hash""] + + peak: ms_deisotope.DeconvolutedPeak + fragment: Union[FragmentBase, Any] + fragment_name: str + _hash: int + + def __init__(self, peak, fragment): + self.peak = peak + self.fragment = fragment + self.fragment_name = fragment.name + self._hash = hash(self.peak) + + def __eq__(self, other): + return (self.peak == other.peak) and (self.fragment_name == other.fragment_name) + + def __hash__(self): + return self._hash + + def __reduce__(self): + return self.__class__, (self.peak, self.fragment) + + def clone(self): + return self.__class__(self.peak, self.fragment) + + def __repr__(self): + return ""PeakFragmentPair(%r, %r)"" % (self.peak, self.fragment) + + def __iter__(self): + yield self.peak + yield self.fragment + + def mass_accuracy(self): + return (self.peak.neutral_mass - self.fragment.mass) / self.fragment.mass + + +class _FragmentIndexBase(Generic[K, V]): + _mapping: DefaultDict[K, List[V]] + fragment_set: Iterable[PeakFragmentPair] + + def __init__(self, fragment_set): + self.fragment_set = fragment_set + self._mapping = None + + @property + def mapping(self): + if self._mapping is None: + self._create_mapping() + return self._mapping + + def invalidate(self): + self._mapping = None + + def __getitem__(self, key): + return self.mapping[key] + + def __iter__(self): + return iter(self.mapping) + + def items(self): + return self.mapping.items() + + def keys(self): + return self.mapping.keys() + + def values(self): + return self.mapping.values() + + def __len__(self): + return len(self.mapping) + + def __contains__(self, key): + return key in self.mapping + + def __str__(self): + return str(self.mapping) + + +class ByFragmentIndex(_FragmentIndexBase[Union[FragmentBase, Any], ms_deisotope.DeconvolutedPeak]): + + def _create_mapping(self): + self._mapping = defaultdict(list) + for peak_fragment_pair in self.fragment_set: + self._mapping[peak_fragment_pair.fragment].append( + peak_fragment_pair.peak) + + +class ByPeakIndex(_FragmentIndexBase[ms_deisotope.DeconvolutedPeak, Union[FragmentBase, Any]]): + + def _create_mapping(self): + self._mapping = defaultdict(list) + for peak_fragment_pair in self.fragment_set: + self._mapping[peak_fragment_pair.peak].append( + peak_fragment_pair.fragment) + + +class FragmentMatchMap(object): + members: Set[PeakFragmentPair] + by_fragment: ByFragmentIndex + by_peak: ByPeakIndex + + def __init__(self): + self.members = set() + self.by_fragment = ByFragmentIndex(self) + self.by_peak = ByPeakIndex(self) + + def add(self, peak: Union[ms_deisotope.DeconvolutedPeak, PeakFragmentPair], + fragment: Optional[Union[FragmentBase, Any]]=None): + if fragment is not None: + peak = PeakFragmentPair(peak, fragment) + if peak not in self.members: + self.members.add(peak) + self.by_peak.invalidate() + self.by_fragment.invalidate() + + def pairs_by_name(self, name: str) -> List[PeakFragmentPair]: + pairs = [] + for pair in self: + if pair.fragment_name == name: + pairs.append(pair) + return pairs + + def fragments_for(self, peak): + return self.by_peak[peak] + + def peaks_for(self, fragment): + return self.by_fragment[fragment] + + def __eq__(self, other): + return self.members == other.members + + def __ne__(self, other): + return self.members != other.members + + def __iter__(self): + return iter(self.members) + + def __len__(self): + return len(self.members) + + def items(self): + for peak, fragment in self.members: + yield fragment, peak + + def values(self): + for pair in self.members: + yield pair.peak + + def fragments(self): + fragments = set() + for peak_pair in self: + fragments.add(peak_pair.fragment) + return fragments + + def remove_fragment(self, fragment): + peaks = self.peaks_for(fragment) + for peak in peaks: + self.members.remove(PeakFragmentPair(peak, fragment)) + self.by_fragment.invalidate() + self.by_peak.invalidate() + + def remove_peak(self, peak): + fragments = self.fragments_for(peak) + for fragment in fragments: + self.members.remove(PeakFragmentPair(peak, fragment)) + self.by_peak.invalidate() + self.by_fragment.invalidate() + + def copy(self): + inst = self.__class__() + for case in self.members: + inst.add(case) + return inst + + def clone(self): + return self.copy() + + def __repr__(self): + return ""FragmentMatchMap(%s)"" % (', '.join( + f.name for f in self.fragments()),) + + def clear(self): + self.members.clear() + self.by_fragment.invalidate() + self.by_peak.invalidate() + + +def count_peaks_shared(reference: FragmentMatchMap, alternate: FragmentMatchMap) -> Tuple[Set[int], Set[int], Set[int]]: + ref_peaks = {p.index.neutral_mass for p in reference.by_peak.keys()} + alt_peaks = {p.index.neutral_mass for p in alternate.by_peak.keys()} + + shared = ref_peaks & alt_peaks + + ref_peaks_ = ref_peaks - alt_peaks + alt_peaks_ = alt_peaks - ref_peaks + + return shared, ref_peaks_, alt_peaks_ + + +def intensity_from_peak_indices(spectrum: Sequence[ms_deisotope.DeconvolutedPeak], indices: Iterable[int]) -> float: + return sum([spectrum[i].intensity for i in indices]) + + +class PeakPairTransition(object): + start: ms_deisotope.DeconvolutedPeak + end: ms_deisotope.DeconvolutedPeak + annotation: Any + key: Tuple[int, int] + + _hash: int + + def __init__(self, start, end, annotation): + self.start = start + self.end = end + self.annotation = annotation + # The indices of the start peak and end peak + self.key = (self.start.index.neutral_mass, self.end.index.neutral_mass) + self._hash = hash(self.key) + + def __eq__(self, other): + if self.key != other.key: + return False + elif self.start != other.start: + return False + elif self.end != other.end: + return False + elif self.annotation != other.annotation: + return False + return True + + def __iter__(self): + yield self.start + yield self.end + yield self.annotation + + def __hash__(self): + return self._hash + + def __repr__(self): + return (""{self.__class__.__name__}({self.start.neutral_mass:0.3f} "" + ""-{self.annotation}-> {self.end.neutral_mass:0.3f})"").format(self=self) + + +class SpectrumGraph(object): + def __init__(self): + self.transitions = set() + self.by_first = defaultdict(list) + self.by_second = defaultdict(list) + + def add(self, p1, p2, annotation): + p1, p2 = sorted((p1, p2), key=lambda x: x.index.neutral_mass) + trans = PeakPairTransition(p1, p2, annotation) + self.transitions.add(trans) + self.by_first[trans.key[0]].append(trans) + self.by_second[trans.key[1]].append(trans) + + def __iter__(self): + return iter(self.transitions) + + def __len__(self): + return len(self.transitions) + + def __repr__(self): + return ""{self.__class__.__name__}({size})"".format( + self=self, size=len(self.transitions)) + + def _get_maximum_index(self): + try: + trans = max(self.transitions, key=lambda x: x.key[1]) + return trans.key[1] + except ValueError: + return 0 + + def adjacency_matrix(self): + n = self._get_maximum_index() + 1 + A = np.zeros((n, n)) + for trans in self.transitions: + A[trans.key] = 1 + return A + + def topological_sort(self, adjacency_matrix=None): + if adjacency_matrix is None: + adjacency_matrix = self.adjacency_matrix() + else: + adjacency_matrix = adjacency_matrix.copy() + + waiting = set() + for i in range(adjacency_matrix.shape[0]): + # Check for incoming edges. If no incoming + # edges, add to the waiting set + if adjacency_matrix[:, i].sum() == 0: + waiting.add(i) + ordered = list() + while waiting: + ix = waiting.pop() + ordered.append(ix) + outgoing_edges = adjacency_matrix[ix, :] + indices_of_neighbors = np.nonzero(outgoing_edges)[0] + # For each outgoing edge + for neighbor_ix in indices_of_neighbors: + # Remove the edge + adjacency_matrix[ix, neighbor_ix] = 0 + # Test for incoming edges + if (adjacency_matrix[:, neighbor_ix] == 0).all(): + waiting.add(neighbor_ix) + if adjacency_matrix.sum() > 0: + raise ValueError(""%d edges left over"" % (adjacency_matrix.sum(),)) + else: + return ordered + + def path_lengths(self): + adjacency_matrix = self.adjacency_matrix() + distances = np.zeros(self._get_maximum_index() + 1) + for ix in self.topological_sort(): + incoming_edges = np.nonzero(adjacency_matrix[:, ix])[0] + if incoming_edges.shape[0] == 0: + distances[ix] = 0 + else: + longest_path_so_far = distances[incoming_edges].max() + distances[ix] = longest_path_so_far + 1 + return distances + + def paths_starting_at(self, ix): + paths = [] + for trans in self.by_first[ix]: + paths.append([trans]) + finished_paths = [] + while True: + extended_paths = [] + for path in paths: + terminal = path[-1] + edges = self.by_first[terminal.key[1]] + if not edges: + finished_paths.append(path) + for trans in edges: + extended_paths.append(path + [trans]) + paths = extended_paths + if len(paths) == 0: + break + return self.transitive_closure(finished_paths) + + def paths_ending_at(self, ix): + paths = [] + for trans in self.by_second[ix]: + paths.append([trans]) + finished_paths = [] + while True: + extended_paths = [] + for path in paths: + terminal = path[0] + edges = self.by_second[terminal.key[0]] + if not edges: + finished_paths.append(path) + for trans in edges: + extended_paths.append([trans] + path) + paths = extended_paths + if len(paths) == 0: + break + return self.transitive_closure(finished_paths) + + def transitive_closure(self, paths): + # precompute node_sets for each path + node_sets = {} + for i, path in enumerate(paths): + # track all nodes by index in this path in node_set + node_set = set() + for node in path: + # add the start node index and end node index to the + # set of nodes on this path + node_set.update(node.key) + node_sets[i] = (node_set, len(path)) + keep = [] + node_sets_items = list(node_sets.items()) + for i, path in enumerate(paths): + node_set, length = node_sets[i] + is_enclosed = False + for key, value_pair in node_sets_items: + # attempting to be clever here seems to cost more + # time than it saves. + if key == i: + continue + other_node_set, other_length = value_pair + if node_set < other_node_set: + is_enclosed = True + break + if not is_enclosed: + keep.append(path) + return sorted(keep, key=len, reverse=True) + + def longest_paths(self, limit=-1): + # get all distinct paths + paths = [] + for ix in np.argsort(self.path_lengths())[::-1]: + segment = self.paths_ending_at(ix) + paths.extend(segment) + # remove redundant paths + paths = self.transitive_closure(paths) + if limit > 0: + if len(paths) > limit: + break + elif len(segment) == 0: + break + return paths + + +try: + has_c = True + _PeakFragmentPair = PeakFragmentPair + _PeakPairTransition = PeakPairTransition + _SpectrumGraph = SpectrumGraph + _FragmentMatchMap = FragmentMatchMap + + from glycresoft._c.structure.fragment_match_map import ( + PeakFragmentPair, PeakPairTransition, SpectrumGraph, FragmentMatchMap) +except ImportError: + has_c = False +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/structure/utils.py",".py","1424","47","from glycopeptidepy.utils.collectiontools import decoratordict +from ms_deisotope.utils import LRUDict + + +class KeyTransformingDecoratorDict(decoratordict): + def __init__(self, transform, *args, **kwargs): + self.transform = transform + super(KeyTransformingDecoratorDict, self).__init__(*args, **kwargs) + + def __getitem__(self, key): + return super(KeyTransformingDecoratorDict, self).__getitem__(self.transform(key)) + + def __setitem__(self, key, value): + key = self.transform(key) + super(KeyTransformingDecoratorDict, self).__setitem__(key, value) + + def __contains__(self, key): + key = self.transform(key) + return dict.__contains__(self, key) + + def keys(self, transform=None): + if transform is None: + transform = self.transform + return TransformingView(transform, super(KeyTransformingDecoratorDict, self).keys()) + + +class TransformingView(object): + def __init__(self, transform, values): + self.transform = transform + self.values = tuple(map(self.transform, values)) + + def __contains__(self, key): + key = self.transform(key) + return key in self.values + + def __iter__(self): + return iter(self.values) + + def __repr__(self): + return ""TransformingView%r"" % (self.values,) + + def __len__(self): + return len(self.values) + + def __getitem__(self, i): + return self.values[i] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/structure/denovo.py",".py","20937","598","import math + +import itertools +from collections import defaultdict +from typing import Any, DefaultDict, Dict, Iterator, List, Set, Tuple, TYPE_CHECKING, Optional + +from glycresoft.chromatogram_tree.mass_shift import MassShiftBase + +from ms_deisotope import DeconvolutedPeak +from ms_deisotope.data_source import ProcessedScan + +try: + from collections.abc import Sequence +except ImportError: + from collections import Sequence + +from glypy.structure.glycan_composition import FrozenMonosaccharideResidue, HashableGlycanComposition + +from glycresoft.chromatogram_tree import Unmodified + +from .fragment_match_map import SpectrumGraph, PeakPairTransition + +if TYPE_CHECKING: + from glycresoft.database.mass_collection import NeutralMassDatabase + +hexnac = FrozenMonosaccharideResidue.from_iupac_lite(""HexNAc"") +hexose = FrozenMonosaccharideResidue.from_iupac_lite(""Hex"") +xylose = FrozenMonosaccharideResidue.from_iupac_lite(""Xyl"") +fucose = FrozenMonosaccharideResidue.from_iupac_lite(""Fuc"") +neuac = FrozenMonosaccharideResidue.from_iupac_lite(""NeuAc"") +neugc = FrozenMonosaccharideResidue.from_iupac_lite(""NeuGc"") + + +def collect_glycan_composition_from_annotations(path: 'Path') -> HashableGlycanComposition: + gc = HashableGlycanComposition() + for edge in path: + if isinstance(edge.annotation, tuple): + for part in edge.annotation: + gc[part] += 1 + else: + gc[edge.annotation] += 1 + if path.end_node is not None: + if isinstance(path.end_node, tuple): + for part in path.end_node: + gc[part] += 1 + else: + gc[path.end_node] += 1 + return gc + + +class MassWrapper(object): + '''An adapter class to make types whose mass calculation is a method + (:mod:`glypy` dynamic graph components) compatible with code where the + mass calculation is an attribute (:mod:`glycopeptidepy` objects and + most things here) + + Hashes and compares as :attr:`obj` + + Attributes + ---------- + obj: object + The wrapped object + mass: float + The mass of :attr:`obj` + ''' + obj: Any + mass: float + + def __init__(self, obj, mass=None): + self.obj = obj + if mass is not None: + self.mass = mass + else: + try: + # object's mass is a method + self.mass = obj.mass() + except TypeError: + # object's mass is a plain attribute + self.mass = obj.mass + + def __repr__(self): + if isinstance(self.obj, tuple): + filling = ', '.join(tuple(map(str, self.obj))) + else: + filling = str(self.obj) + + return f""{self.__class__.__name__}({filling})"" + + def __eq__(self, other): + return self.obj == other + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash(self.obj) + + def __lt__(self, other): + return self.mass < other.mass + + def __gt__(self, other): + return self.mass > other.mass + + +default_components = (hexnac, hexose, xylose, fucose, neuac, neugc) + + +class PeakGroup(object): + """""" + An adapter for a collection of :class:`~.DeconvolutedPeak` objects which share + the same approximate neutral mass that looks like a single :class:`~.DeconvolutedPeak` + object for edge-like calculations with :class:`EdgeGroup`. + + Attributes + ---------- + peaks: tuple + A tuple of the *unique* peaks forming this group + neutral_mass: float + The intensity weighted average neutral mass of the peaks in this group + intensity: float + The sum of the intensities of the peaks in this group + """""" + peaks: Tuple[DeconvolutedPeak] + neutral_mass: float + intensity: float + + def __init__(self, peaks): + self.peaks = tuple(sorted(set(peaks), key=lambda x: (x.neutral_mass, x.charge))) + self.neutral_mass = 0.0 + self.intensity = 0.0 + self._hash = hash((p.index.neutral_mass for p in self.peaks)) + self._initialize() + + def _initialize(self): + neutral_mass_acc = 0.0 + intensity = 0.0 + for peak in self.peaks: + neutral_mass_acc += peak.neutral_mass * peak.intensity + intensity += peak.intensity + self.intensity = intensity + self.neutral_mass = neutral_mass_acc / intensity + + def __eq__(self, other): + return self.peaks == other.peaks + + def __hash__(self): + return self._hash + + def __getitem__(self, i: int) -> DeconvolutedPeak: + return self.peaks[i] + + def __len__(self): + return len(self.peaks) + + def __repr__(self): + template = ""{self.__class__.__name__}({self.neutral_mass}, {self.intensity}, {size})"" + return template.format(self=self, size=len(self)) + + +class EdgeGroup(object): + """""" + An adapter for a collection of :class:`~.PeakPairTransition` objects which all belong to + different :class:`Path` objects that share the same annotation sequence and approximate start + and end mass. + + Attributes + ---------- + start: PeakGroup + The peaks that make up the starting mass for this edge group + end: PeakGroup + The peaks that make up the ending mass for this edge group + annotation: object + The common annotation for members of this group + """""" + + start: PeakGroup + annotation: Any + end: PeakGroup + + _transitions: List[PeakPairTransition] + _hash: int + + def __init__(self, transitions): + self._transitions = transitions + self.start = None + self.end = None + self._hash = None + self.annotation = self._transitions[0].annotation + self._initialize_by_transitions() + + def __hash__(self): + return self._hash + + def __eq__(self, other: 'EdgeGroup'): + if other is None: + return False + return self.start == other.start and self.end == other.end and self.annotation == other.annotation + + def __ne__(self, other): + return not self == other + + def __getitem__(self, i): + return self._transitions[i] + + def __len__(self): + return len(self._transitions) + + def _initialize_by_transitions(self): + if self._transitions: + starts = [edge.start for edge in self._transitions] + ends = [edge.end for edge in self._transitions] + self.start = PeakGroup(starts) + self.end = PeakGroup(ends) + self._hash = hash((self.start.peaks[0].index.neutral_mass, + self.end.peaks[0].index.neutral_mass)) + else: + self._hash = hash(()) + + @classmethod + def from_combination(cls, start: PeakGroup, end: PeakGroup, annotation: MassWrapper): + return cls([PeakPairTransition(start_peak, end_peak, annotation) + for start_peak, end_peak in itertools.product(start, end)]) + + @classmethod + def aggregate(cls, paths): + edges = [] + n = len(paths) + if n == 0: + return [] + m = len(paths[0]) + for i in range(m): + group = [] + for j in range(n): + group.append(paths[j][i]) + edges.append(group) + return paths[0].__class__([cls(g) for g in edges]) + + def __repr__(self): + return (""{self.__class__.__name__}({self.start.neutral_mass:0.3f} "" + ""-{self.annotation}-> {self.end.neutral_mass:0.3f})"").format(self=self) + + +def collect_paths(paths: List['Path'], error_tolerance: float=1e-5) -> List[List['Path']]: + """""" + Group together paths which share the same annotation sequence and approximate + start and end masses. + + Parameters + ---------- + paths: :class:`list` + A list of :class:`Path` objects to group + + Returns + ------- + :class:`list` of :class:`list` of :class:`Path` objects + """""" + groups = defaultdict(list) + if not paths: + return [] + for path in paths: + key = tuple(e.annotation for e in path) + groups[key].append(path) + result = [] + for key, block_members in groups.items(): + block_members = sorted(block_members, key=lambda x: x.start_mass) + current_path = block_members[0] + members = [current_path] + for path in block_members[1:]: + if abs(current_path.start_mass - path.start_mass) / path.start_mass < error_tolerance: + members.append(path) + else: + result.append(members) + current_path = path + members = [current_path] + result.append(members) + return result + + +def score_path(path: 'Path') -> float: + if not path: + return 0 + acc = math.log10(path.transitions[0].start.intensity) + for edge in path.transitions: + acc += math.log10(edge.end.intensity) + return acc + + +class Path(object): + """""" + Represent a single contiguous sequence of :class:`~.PeakPairTransition` objects + forming a sequence tag, or a path along the edges of a peak graph. + + Attributes + ---------- + transitions: :class:`list` of :class:`~.PeakPairTransition` + The edges connecting pairs of peaks. + total_signal: float + The total signal captured by this path + start_mass: float + The lowest mass among all peaks in the path + end_mass: float + The highest mass among all peaks in the path + """""" + + transitions: List[PeakPairTransition] + total_signal: float + start_mass: float + end_mass: float + + start_node: Optional[Any] + end_node: Optional[Any] + + _peaks_used: Optional[Set[DeconvolutedPeak]] + _edges_used: Optional[DefaultDict[Tuple[DeconvolutedPeak, DeconvolutedPeak], List[Any]]] + + def __init__(self, edge_list, start_node=None, end_node=None): + self.transitions = edge_list + self.total_signal = self._total_signal() + self.start_mass = self[0].start.neutral_mass + self.end_mass = self[-1].end.neutral_mass + self.start_node = start_node + self.end_node = end_node + self._peaks_used = None + self._edges_used = None + + def copy(self) -> 'Path': + return self.__class__(self.transitions, self.start_node, self.end_node) + + @property + def peaks(self): + if self._peaks_used is None: + self._peaks_used = self._build_peaks_set() + return self._peaks_used + + def _build_peaks_set(self) -> PeakPairTransition: + peaks = set() + for edge in self: + peaks.add(edge.end) + peaks.add(self[0].start) + return peaks + + def _build_edges_used(self) -> DefaultDict[Tuple[DeconvolutedPeak, DeconvolutedPeak], List[Any]]: + mapping = defaultdict(list) + for edge in self: + mapping[edge.start, edge.end].append(edge) + return mapping + + def __contains__(self, edge: PeakPairTransition): + return self.has_edge(edge, True) + + def has_edge(self, edge: PeakPairTransition, match_annotation: bool=False) -> bool: + if self._edges_used is None: + self._edges_used = self._build_edges_used() + key = (edge.start, edge.end) + if key in self._edges_used: + edges = self._edges_used[key] + if match_annotation: + for e in edges: + if e == edge: + return True + return False + else: + for e in edges: + if e.key != edge.key: + continue + if e.start != edge.start: + continue + if e.end != edge.end: + continue + return True + return False + + def has_peak(self, peak: DeconvolutedPeak) -> bool: + if self._peaks_used is None: + self._peaks_used = self._build_peaks_set() + return peak in self._peaks_used + + def has_peaks(self, peaks_set: Set[DeconvolutedPeak]) -> bool: + if self._peaks_used is None: + self._peaks_used = self._build_peaks_set() + return peaks_set & self._peaks_used + + def __iter__(self) -> Iterator[PeakPairTransition]: + return iter(self.transitions) + + def __getitem__(self, i): + return self.transitions[i] + + def __len__(self): + return len(self.transitions) + + def _total_signal(self) -> float: + total = 0.0 + for edge in self: + total += edge.end.intensity + total += self[0].start.intensity + return total + + def __repr__(self): + transitions = '->'.join(_format_annotation(e.annotation) + for e in self) + if self.start_node is not None: + transitions = f""{_format_annotation(self.start_node)}:-{transitions}"" + if self.end_node is not None: + transitions = f""{transitions}-:{_format_annotation(self.end_node)}"" + return f""{self.__class__.__name__}({transitions}, {self.total_signal:0.4e}, {self.start_mass}, {self.end_mass})"" + + +def _format_annotation(annot: Any): + return '[%s]' % ', '.join(map(str, annot)) if isinstance(annot, tuple) else str(annot) + + +class PathSet(Sequence): + def __init__(self, paths, ordered=False): + self.paths = (sorted(paths, key=lambda x: x.start_mass) + if not ordered else paths) + + def __getitem__(self, i): + return self.paths[i] + + def __len__(self): + return len(self.paths) + + def __repr__(self): + return ""%s(%s)"" % (self.__class__.__name__, str(self.paths)[1:-1]) + + def _repr_pretty_(self, p, cycle): + with p.group(9, ""%s(["" % self.__class__.__name__, ""])""): + for i, path in enumerate(self): + if i: + p.text("","") + p.breakable() + p.pretty(path) + + def is_path_disjoint(self, path): + for p in self: + if p.has_peaks(path.peaks): + return False + return True + + def threshold(self, topn=100): + return self.__class__(sorted(self, key=lambda x: x.total_signal, reverse=True)[:topn]) + + +class PathFinder(object): + components: List[MassWrapper] + product_error_tolerance: float + merge_paths: bool + precursor_error_tolerance: float + gap_completion_lookup: Dict[int, 'NeutralMassDatabase[MassWrapper]'] + _gap_completion_mass_range: Dict[int, Tuple[float, float]] + + def __init__(self, components=None, + product_error_tolerance: float=1e-5, + merge_paths: bool=True, + precursor_error_tolerance: float=1e-5): + if components is None: + components = default_components + self.components = list(map(MassWrapper, components)) + self.product_error_tolerance = product_error_tolerance + self.merge_paths = merge_paths + self.precursor_error_tolerance = precursor_error_tolerance + self.gap_completion_lookup = {} + self._gap_completion_mass_range = {} + + def build_graph(self, scan: ProcessedScan, mass_shift: MassShiftBase=Unmodified) -> SpectrumGraph: + graph = SpectrumGraph() + has_tandem_shift = abs(mass_shift.tandem_mass) > 0 + for peak in scan.deconvoluted_peak_set: + for component in self.components: + for other_peak in scan.deconvoluted_peak_set.all_peaks_for( + peak.neutral_mass + component.mass, self.product_error_tolerance): + graph.add(peak, other_peak, component.obj) + if has_tandem_shift: + for other_peak in scan.deconvoluted_peak_set.all_peaks_for( + peak.neutral_mass + component.mass + mass_shift.tandem_mass, + self.product_error_tolerance): + graph.add(peak, other_peak, component.obj) + return graph + + def paths_from_graph(self, graph: SpectrumGraph, limit: int=200) -> List[Path]: + paths = [] + min_start_mass = min(c.mass for c in self.components) + 1 + for path in graph.longest_paths(limit=limit): + path = Path(path) + if path.start_mass < min_start_mass: + continue + paths.append(path) + return paths + + def aggregate_paths(self, paths: List['Path']) -> DefaultDict[Tuple[Any], List['Path']]: + groups = defaultdict(list) + for path in paths: + key = tuple(e.annotation for e in path) + groups[key].append(path) + return groups + + def collect_paths(self, paths: List['Path'], error_tolerance: float = 1e-5) -> List[List['Path']]: + """""" + Group together paths which share the same annotation sequence and approximate + start and end masses. + + Parameters + ---------- + paths: :class:`list` + A list of :class:`Path` objects to group + + Returns + ------- + :class:`list` of :class:`list` of :class:`Path` objects + """""" + if not paths: + return [] + groups = self.aggregate_paths(paths) + result = [] + for _key, block_members in groups.items(): + block_members = sorted(block_members, key=lambda x: x.start_mass) + current_path = block_members[0] + members = [current_path] + for path in block_members[1:]: + if abs(current_path.start_mass - path.start_mass) / path.start_mass < error_tolerance: + members.append(path) + else: + result.append(members) + current_path = path + members = [current_path] + result.append(members) + result = [EdgeGroup.aggregate(block) for block in result] + return result + + def paths(self, scan: ProcessedScan, mass_shift: MassShiftBase=Unmodified, limit: int=200) -> List[Path]: + graph = self.build_graph(scan, mass_shift) + paths = self.paths_from_graph(graph, limit) + if self.merge_paths: + paths = self.collect_paths(paths, self.precursor_error_tolerance) + return paths + + def _fill_gap_size_bin(self, size: int): + combos = [] + for items in itertools.combinations_with_replacement(self.components, size): + step = MassWrapper(tuple(v.obj for v in items), sum([v.mass for v in items])) + combos.append(step) + from glycresoft.database.mass_collection import NeutralMassDatabase + return NeutralMassDatabase(combos, lambda x: x.mass) + + def gap_bin_entries(self, size: int) -> 'NeutralMassDatabase[MassWrapper]': + if size not in self.gap_completion_lookup: + self.gap_completion_lookup[size] = self._fill_gap_size_bin(size) + masses = [m.mass for m in self.gap_completion_lookup[size]] + self._gap_completion_mass_range[size] = (min(masses), max(masses)) + return self.gap_completion_lookup[size] + + def complete_paths(self, paths: List[Path], max_gap_size: int = 2) -> List[Path]: + from glycresoft.database.mass_collection import NeutralMassDatabase + by_front = NeutralMassDatabase(paths, lambda x: x.start_mass) + by_end = NeutralMassDatabase(paths, lambda x: x.end_mass) + max_gap_size = 2 + extensions = [] + + for path in by_end: + for i in range(1, max_gap_size + 1): + spacers = self.gap_bin_entries(i) + for candidate in spacers: + suffixes = by_front.search_mass_ppm( + path.end_mass + candidate.mass, self.product_error_tolerance) + for suffix in suffixes: + extensions.append(Path( + list(path) + [EdgeGroup.from_combination( + path[-1].end, suffix[0].start, candidate.obj)] + list(suffix), + path.start_node, + suffix.end_node, + )) + return extensions + paths + + def complete_precursor(self, scan: ProcessedScan, + path: Path, + mass_shift: MassShiftBase=Unmodified, + max_gap_size: int=3) -> List[Path]: + precursor_mass = scan.precursor_information.neutral_mass + leftover_mass: float = precursor_mass - (path.end_mass + mass_shift.mass) + candidates: List[MassWrapper] = [] + for i in range(1, max_gap_size + 1): + candidates.extend( + self.gap_bin_entries(i).search_mass( + leftover_mass, error_tolerance=0.2)) + result = [] + for candidate in candidates: + proposed_mass = candidate.mass + path.end_mass + mass_shift.mass + if abs(proposed_mass - precursor_mass) / precursor_mass <= self.precursor_error_tolerance: + completed = path.copy() + completed.end_node = candidate.obj + result.append(completed) + if not result: + result = [path] + return result + + +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/structure/enums.py",".py","1301","41","from glypy.utils import Enum + + +class SpectrumMatchClassification(Enum): + target_peptide_target_glycan = 0 + target_peptide_decoy_glycan = 1 + decoy_peptide_target_glycan = 2 + decoy_peptide_decoy_glycan = decoy_peptide_target_glycan | target_peptide_decoy_glycan + + +class AnalysisTypeEnum(Enum): + glycopeptide_lc_msms = 0 + glycan_lc_ms = 1 + + +class GlycopeptideSearchStrategy(Enum): + target_internal_decoy_competition = ""target-internal-decoy-competition"" + target_decoy_competition = ""target-decoy-competition"" + multipart_target_decoy_competition = ""multipart-target-decoy-competition"" + + +AnalysisTypeEnum.glycopeptide_lc_msms.add_name(""Glycopeptide LC-MS/MS"") +AnalysisTypeEnum.glycan_lc_ms.add_name(""Glycan LC-MS"") + + +class GlycopeptideFDREstimationStrategy(Enum): + multipart_gamma_gaussian_mixture = 0 + peptide_fdr = 1 + glycan_fdr = 2 + glycopeptide_fdr = 3 + peptide_or_glycan = 4 + + +GlycopeptideFDREstimationStrategy.multipart_gamma_gaussian_mixture.add_name( + ""multipart"") +GlycopeptideFDREstimationStrategy.multipart_gamma_gaussian_mixture.add_name( + ""joint"") +GlycopeptideFDREstimationStrategy.peptide_fdr.add_name(""peptide"") +GlycopeptideFDREstimationStrategy.glycan_fdr.add_name(""glycan"") +GlycopeptideFDREstimationStrategy.peptide_or_glycan.add_name('any') +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/workflow.py",".py","1624","51","from typing import Optional, Sequence, Iterable, TypeVar + +from glycresoft.task import TaskBase + +from .spectrum_match.solution_set import SpectrumSolutionSet +from .target_decoy import TargetDecoySet + + +T = TypeVar('T') + + +def chunkiter(collection: Sequence[T], size: int=200) -> Iterable[Sequence[T]]: + i = 0 + while collection[i:(i + size)]: + yield collection[i:(i + size)] + i += size + + +def format_identification(spectrum_solution: SpectrumSolutionSet) -> str: + return ""%s:%0.3f:(%0.3f) ->\n%s"" % ( + spectrum_solution.scan.id, + spectrum_solution.scan.precursor_information.neutral_mass, + spectrum_solution.best_solution().score, + str(spectrum_solution.best_solution().target)) + + +def format_identification_batch(group: Iterable[SpectrumSolutionSet], n: int) -> str: + representers = dict() + group = sorted(group, key=lambda x: x.score, reverse=True) + for ident in group: + key = str(ident.best_solution().target) + if key in representers: + continue + else: + representers[key] = ident + to_represent = sorted( + representers.values(), key=lambda x: x.score, reverse=True) + return '\n'.join(map(format_identification, to_represent[:n])) + + +class SearchEngineBase(TaskBase): + + def search(self, precursor_error_tolerance: float=1e-5, + simplify: bool=True, + batch_size: int=500, + limit: Optional[int]=None, *args, **kwargs) -> TargetDecoySet: + raise NotImplementedError() + + def estimate_fdr(self, *args, **kwargs) -> TargetDecoySet: + raise NotImplementedError() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/temp_store.py",".py","7177","249","from csv import reader, writer +import os +import glob +import tempfile +import shutil + +from glypy.utils import uid + +from six import text_type, binary_type, PY3 + +from .spectrum_match import SpectrumMatch, SpectrumSolutionSet +from .ref import SpectrumReference, TargetReference + + +class TempFileManager(object): + def __init__(self, base_directory=None): + if base_directory is None: + base_directory = tempfile.mkdtemp(prefix=""glycresoft_tmp_"") + else: + try: + os.makedirs(base_directory) + except OSError: + if os.path.exists(base_directory) and os.path.isdir(base_directory): + pass + else: + raise + self.base_directory = base_directory + self.cache = {} + + def get(self, key=None): + if key is None: + _key = """" + else: + _key = key + if key in self.cache: + return self.cache[key] + name = ""%s_%x"" % (_key, uid()) + path = os.path.join(self.base_directory, name) + self.cache[key] = path + return path + + def clear(self): + shutil.rmtree(self.base_directory) + + def dir(self, pattern='*'): + return glob.glob(os.path.join(self.base_directory, pattern)) + + def __repr__(self): + return ""TempFileManager(%r)"" % self.base_directory + + +class FileWrapperBase(object): + def flush(self): + self.handle.flush() + + def close(self): + self.handle.close() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + + +class SpectrumSolutionSetWriter(FileWrapperBase): + def __init__(self, sink, manager): + self.manager = manager + self.counter = 0 + self.sink = sink + self._init_writer() + + def _init_writer(self): + try: + if PY3: + self.handle = open(self.sink, 'wt', newline='') + else: + self.handle = open(self.sink, 'wb') + except Exception: + if hasattr(self.sink, 'write'): + self.handle = self.sink + else: + raise + self.writer = writer(self.handle) + + def write(self, solution_set): + self.manager.put_scan(solution_set.scan) + if PY3: + values = [solution_set.scan.id] + for spectrum_match in solution_set: + self.manager.put_mass_shift(spectrum_match.mass_shift) + for val in spectrum_match.pack(): + if not isinstance(val, str): + val = str(val) + values.append(val) + self.writer.writerow(values) + else: + values = [solution_set.scan.id] + for spectrum_match in solution_set: + self.manager.put_mass_shift(spectrum_match.mass_shift) + values.extend(spectrum_match.pack()) + self.writer.writerow(list(map(bytes, values))) + self.counter += 1 + + def write_all(self, iterable): + for item in iterable: + self.write(item) + self.flush() + + def extend(self, iterable): + self.write_all(iterable) + + def append(self, solution_set): + self.write(solution_set) + + def __len__(self): + return self.counter + + +class SpectrumSolutionSetReader(FileWrapperBase): + def __init__(self, source, manager, target_resolver=None, spectrum_match_type=SpectrumMatch): + self.manager = manager + self.source = source + self.target_resolver = target_resolver + self.spectrum_match_type = spectrum_match_type or SpectrumMatch + self._init_reader() + + def _init_reader(self): + try: + if PY3: + self.handle = open(self.source, 'rt') + else: + self.handle = open(self.source, 'rb') + except Exception: + if hasattr(self.source, 'read'): + self.handle = self.source + else: + raise + self.reader = reader(self.handle) + + def resolve_scan(self, scan_id): + return self.manager.get_scan(scan_id) + + def resolve_target(self, target_id): + if self.target_resolver is None: + return self.manager.get_target(target_id) + else: + return self.target_resolver(target_id) + + def resolve_mass_shift(self, mass_shift_name): + mass_shift = self.manager.get_mass_shift(mass_shift_name) + return mass_shift + + def handle_line(self): + row = next(self.reader) + scan_id = str(row[0]) + spectrum_reference = self.resolve_scan(scan_id) + i = 1 + n = len(row) + members = [] + while i < n: + match, i = self.spectrum_match_type.unpack(row, spectrum_reference, self, i) + members.append(match) + result = SpectrumSolutionSet(spectrum_reference, members) + return result + + def __next__(self): + return self.handle_line() + + next = __next__ + + def __iter__(self): + return self + + +class SpectrumSolutionResolver(object): + def __init__(self): + self.mass_shift_by_name = dict() + self.target_cache = dict() + self.scan_cache = dict() + + def clear(self): + self.scan_cache.clear() + self.target_cache.clear() + + def put_scan(self, scan): + self.scan_cache[scan.id] = scan + + def get_scan(self, scan_id): + try: + return self.scan_cache[scan_id] + except KeyError: + return SpectrumReference(scan_id, None) + + def put_mass_shift(self, mass_shift): + self.mass_shift_by_name[mass_shift.name] = mass_shift + + def get_mass_shift(self, name): + return self.mass_shift_by_name[name] + + def get_target(self, id): + try: + return self.target_cache[id] + except KeyError: + ref = TargetReference(id) + self.target_cache[id] = ref + return ref + + +class SpectrumMatchStore(SpectrumSolutionResolver): + _reader_type = SpectrumSolutionSetReader + _writer_type = SpectrumSolutionSetWriter + + def __init__(self, tempfile_manager=None): + if tempfile_manager is None: + tempfile_manager = TempFileManager() + self.temp_manager = tempfile_manager + super(SpectrumMatchStore, self).__init__() + + def clear(self): + self.temp_manager.clear() + super(SpectrumMatchStore, self).clear() + + def writer(self, key): + return self._writer_type(self.temp_manager.get(key), self) + + def reader(self, key, target_resolver=None): + return self._reader_type(self.temp_manager.get(key), self, target_resolver=target_resolver) + + +class FileBackedSpectrumMatchCollection(object): + def __init__(self, store, key, target_resolver=None): + self.store = store + self.key = key + self.target_resolver = target_resolver + self._size = None + + def __iter__(self): + return self.store.reader(self.key, self.target_resolver) + + def __len__(self): + if self._size is not None: + return self._size + i = 0 + for row in self: + i += 1 + self._size = i + return self._size +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/oxonium_ions.py",".py","10611","320","from collections import defaultdict +from typing import Any, DefaultDict, Dict, FrozenSet, Iterable, List, Tuple, Union, MutableSequence +from statistics import median + +from dataclasses import dataclass, field + +from glycopeptidepy import PeptideSequence +from glycopeptidepy.structure.fragment import SimpleFragment + +from glypy.structure.glycan_composition import FrozenMonosaccharideResidue, Composition + +from glycresoft.tandem.glycopeptide.core_search import GlycanCombinationRecord + +from ms_deisotope.peak_set import DeconvolutedPeakSet + + +class _mass_wrapper(object): + + def __init__(self, mass, annotation=None): + self.value = mass + self.annotation = annotation if annotation is not None else mass + + def mass(self, *args, **kwargs): + return self.value + + def __repr__(self): + return ""MassWrapper(%f, %s)"" % (self.value, self.annotation) + + +_hexnac = FrozenMonosaccharideResidue.from_iupac_lite(""HexNAc"") +_hexose = FrozenMonosaccharideResidue.from_iupac_lite(""Hex"") +_neuac = FrozenMonosaccharideResidue.from_iupac_lite('NeuAc') +_neugc = FrozenMonosaccharideResidue.from_iupac_lite(""NeuGc"") +_water = Composition(""H2O"").mass + +_standard_oxonium_ions = [ + _hexnac, + _hexose, + _mass_wrapper(_hexose.mass() - _water), + _neuac, + _mass_wrapper(_neuac.mass() - _water), + FrozenMonosaccharideResidue.from_iupac_lite(""Fuc""), + _mass_wrapper(_hexnac.mass() - Composition(""C2H6O3"").mass), + _mass_wrapper(_hexnac.mass() - Composition(""CH6O3"").mass), + _mass_wrapper(_hexnac.mass() - Composition(""C2H4O2"").mass), + _mass_wrapper(_hexnac.mass() - _water), + _mass_wrapper(_hexnac.mass() - Composition(""H4O2"").mass) +] + +standard_oxonium_ions = _standard_oxonium_ions[:] + +_gscore_oxonium_ions = [ + _hexnac, + _mass_wrapper(_hexnac.mass() - Composition(""C2H6O3"").mass), + _mass_wrapper(_hexnac.mass() - Composition(""CH6O3"").mass), + _mass_wrapper(_hexnac.mass() - Composition(""C2H4O2"").mass), + _mass_wrapper(_hexnac.mass() - _water), + _mass_wrapper(_hexnac.mass() - Composition(""H4O2"").mass) +] + + +class OxoniumIonScanner(object): + + def __init__(self, ions_to_search=None): + if ions_to_search is None: + ions_to_search = _standard_oxonium_ions + self.ions_to_search = ions_to_search + + def scan(self, peak_list, charge=0, error_tolerance=2e-5, minimum_mass=0): + matches = [] + for ion in self.ions_to_search: + if ion.mass() < minimum_mass: + continue + match = peak_list.has_peak( + ion.mass(charge=charge), error_tolerance) + if match is not None: + matches.append(match) + return matches + + def ratio(self, peak_list, charge=0, error_tolerance=2e-5, minimum_mass=0): + try: + maximum = max(p.intensity for p in peak_list) + except ValueError: + return 0 + n = len([i for i in self.ions_to_search if i.mass() > minimum_mass]) + if n == 0: + return 0 + oxonium = sum( + p.intensity / maximum for p in self.scan( + peak_list, charge, error_tolerance, minimum_mass)) + return oxonium / n + + def __call__(self, peak_list, charge=0, error_tolerance=2e-5, minimum_mass=0): + return self.ratio(peak_list, charge, error_tolerance, minimum_mass) + + +oxonium_detector = OxoniumIonScanner() +gscore_scanner = OxoniumIonScanner(_gscore_oxonium_ions) + + +class SignatureSpecification(object): + __slots__ = ('components', 'masses', '_hash', '_is_compound') + + def __init__(self, components, masses): + self.components = tuple( + FrozenMonosaccharideResidue.from_iupac_lite(k) for k in components) + self.masses = tuple(masses) + self._hash = hash(self.components) + self._is_compound = len(self.masses) > 1 + + def __getitem__(self, i): + return self.components[i] + + def __iter__(self): + return iter(self.components) + + def __hash__(self): + return self._hash + + def __eq__(self, other): + return self.components == other.components + + def __repr__(self): + return ""{self.__class__.__name__}({self.components}, {self.masses})"".format(self=self) + + def is_expected(self, glycan_composition): + is_expected = glycan_composition._getitem_fast(self.components[0]) != 0 + if is_expected and self._is_compound: + is_expected = all(glycan_composition._getitem_fast( + k) != 0 for k in self.components) + return is_expected + + def count_of(self, glycan_composition): + limit = float('inf') + for component in self: + cnt = glycan_composition._getitem_fast(component) + if cnt < limit: + limit = cnt + return limit + + def peak_of(self, spectrum, error_tolerance): + best_peak = None + best_signal = -1 + for mass in self.masses: + peaks = spectrum.all_peaks_for(mass, error_tolerance) + for peak in peaks: + if peak.intensity > best_signal: + best_peak = peak + best_signal = peak.intensity + return best_peak + + +try: + _has_c = True + from glycresoft._c.tandem.oxonium_ions import SignatureSpecification +except ImportError: + _has_c = False + + +single_signatures = { + SignatureSpecification((str(_neuac), ), [ + _neuac.mass(), + _neuac.mass() - _water + ]): 0.5, + SignatureSpecification((str(_neugc), ), [ + _neugc.mass(), + _neugc.mass() - _water + ]): 0.5, +} + + +compound_signatures = { + SignatureSpecification(('@phosphate', 'Hex'), [ + 242.01915393925, + 224.00858925555, + ]): 0.5, + SignatureSpecification((""@acetyl"", ""NeuAc""), [ + 333.10598119017, + 315.09541650647 + ]): 0.5 +} + + +class OxoniumIndex(object): + '''An index for quickly matching all oxonium ions against a spectrum and efficiently mapping them + back to individual glycan compositions. + ''' + fragments: List[SimpleFragment] + fragment_index: DefaultDict[str, List[int]] + glycan_to_index: Dict[str, int] + index_to_glycan: Dict[int, Union[str, List[str]]] + + def __init__(self, fragments=None, fragment_index=None, glycan_to_index=None): + self.fragments = fragments or [] + self.fragment_index = defaultdict(list, fragment_index or {}) + self.glycan_to_index = glycan_to_index or {} + self.index_to_glycan = {v: k for k, v in self.glycan_to_index.items()} + + def _make_glycopeptide_stub(self, glycan_composition) -> PeptideSequence: + p = PeptideSequence(""P%s"" % glycan_composition) + return p + + def build_index(self, glycan_composition_records: List[GlycanCombinationRecord], **kwargs): + fragments = {} + fragment_index = defaultdict(list) + glycan_index = {} + for gc_rec in glycan_composition_records: + glycan_index[gc_rec.composition] = gc_rec.id + + p = self._make_glycopeptide_stub(gc_rec.composition) + for frag in p.glycan_fragments(**kwargs): + fragments[frag.name] = frag + fragment_index[frag.name].append(gc_rec.id) + + self.glycan_to_index = glycan_index + self.fragment_index = fragment_index + self.fragments = sorted(fragments.values(), key=lambda x: x.mass) + self.index_to_glycan = {v: k for k, v in self.glycan_to_index.items()} + self.simplify() + + def match(self, spectrum: DeconvolutedPeakSet, error_tolerance: float) -> DefaultDict[int, List[Tuple[SimpleFragment, float]]]: + match_index = defaultdict(list) + for fragment in self.fragments: + peak = spectrum.has_peak(fragment.mass, error_tolerance) + if peak is not None: + for key in self.fragment_index[fragment.name]: + match_index[key].append((fragment, peak.index.neutral_mass)) + return match_index + + def simplify(self): + id_to_frag_group = defaultdict(set) + for f, members in self.fragment_index.items(): + for member in members: + id_to_frag_group[member].add(f) + + groups = defaultdict(list) + for member, group in id_to_frag_group.items(): + groups[frozenset(group)].append(member) + + counter = 0 + new_fragment_index = defaultdict(list) + new_glycan_index = {} + for frag_group, members in groups.items(): + new_id = counter + counter += 1 + for frag in frag_group: + new_fragment_index[frag].append(new_id) + for member in members: + new_glycan_index[self.index_to_glycan[member]] = new_id + + self.glycan_to_index = new_glycan_index + self.fragment_index = new_fragment_index + self.index_to_glycan = defaultdict(list) + for k, v in self.glycan_to_index.items(): + self.index_to_glycan[v].append(k) + + +try: + from glycresoft._c.tandem.oxonium_ions import OxoniumIndex, SignatureIonIndex, SignatureIonIndexMatch +except ImportError: + SignatureIonIndex = object + SignatureIonIndexMatch = object + + +@dataclass(frozen=True) +class OxoniumFilterState: + scan_id: str + g_score: float = field(hash=False) + g_score_pass: bool + oxonium_ions: FrozenSet[str] + + +@dataclass +class OxoniumFilterReport(MutableSequence[OxoniumFilterState]): + records: List[OxoniumFilterState] = field(default_factory=list) + + def copy(self): + return self.__class__(self.records.copy()) + + def __getitem__(self, i): + return self.records[i] + + def __setitem__(self, i, v): + self.records[i] = v + + def __delitem__(self, i): + del self.records[i] + + def append(self, value: OxoniumFilterState): + self.records.append(value) + + def extend(self, values: Iterable[OxoniumFilterState]): + self.records.extend(values) + + def insert(self, index: int, value: OxoniumFilterState): + self.records.insert(index, value) + + def __len__(self): + return len(self.records) + + def __iter__(self): + return iter(self.records) + + def prepare_report(self): + passing: List[OxoniumFilterState] = [] + failing = [] + passing_scores= [] + for rec in self: + if rec.g_score_pass: + passing.append(rec) + passing_scores.append(rec.g_score) + else: + failing.append(rec) + { + ""n_passing"": len(passing), + ""n_failing"": len(failing), + ""passing_distribution"": passing_scores, + ""passing_median_score"": median(passing_scores) if passing_scores else None + } +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/coelute.py",".py","7597","186","from typing import Any, Callable, Dict, List, Tuple, Type, NamedTuple + +from ms_deisotope.data_source import ProcessedRandomAccessScanSource, ProcessedScan + +from glycresoft.task import TaskBase + +from glycresoft.chromatogram_tree import Chromatogram, ChromatogramFilter, MassShift, mass_shift + + +from glycresoft.tandem.target_decoy import FDREstimatorBase + +from glycresoft.tandem.glycopeptide.identified_structure import IdentifiedGlycopeptide + +from glycresoft.tandem.spectrum_match.spectrum_match import MultiScoreSpectrumMatch, SpectrumMatch, SpectrumMatcherBase +from glycresoft.tandem.spectrum_match import SpectrumSolutionSet, MultiScoreSpectrumSolutionSet + + +class CoElutionCandidate(NamedTuple): + reference: IdentifiedGlycopeptide + extensions: List[Chromatogram] + ms2_spectra: List[MultiScoreSpectrumMatch] + mass_shift: MassShift + + def merge(self, scan_id_to_solution_set: Dict[str, SpectrumSolutionSet]) -> Tuple[IdentifiedGlycopeptide, List[IdentifiedGlycopeptide]]: + ssets = {} + to_drop = [] + existing_matches = {sset.scan.scan_id for sset in self.reference.spectrum_matches} + for gpsm in self.ms2_spectra: + sset = None + if gpsm.scan_id in scan_id_to_solution_set: + sset = scan_id_to_solution_set[gpsm.scan_id] + sset.append(gpsm) + else: + sset = MultiScoreSpectrumSolutionSet(gpsm.scan, [gpsm]) + scan_id_to_solution_set[gpsm.scan_id] = sset + if gpsm.scan_id not in existing_matches: + ssets[gpsm.scan.scan_id] = sset + + for part in self.extensions: + if not isinstance(part, IdentifiedGlycopeptide): + self.reference.chromatogram.merge_in_place(part, node_type=self.mass_shift) + else: + to_drop.append(part) + self.reference.chromatogram.merge_in_place( + part.chromatogram, node_type=self.mass_shift) + self.reference.tandem_solutions.extend(ssets.values()) + return self.reference, to_drop + + +class CoElutionAdductFinder(TaskBase): + scan_loader: ProcessedRandomAccessScanSource + chromatograms: ChromatogramFilter + + msn_scoring_model: Type[SpectrumMatcherBase] + msn_evaluation_args: Dict[str, Any] + fdr_estimator: FDREstimatorBase + + scan_id_to_solution_set: Dict[str, SpectrumSolutionSet] + threshold_fn: Callable[[SpectrumMatch], bool] + + def __init__(self, scan_loader: ProcessedRandomAccessScanSource, + chromatograms: ChromatogramFilter, + msn_scoring_model: SpectrumMatcherBase, + msn_evaluation_args: Dict[str, Any], + fdr_estimator: FDREstimatorBase, + scan_id_to_solution_set: Dict[str, SpectrumSolutionSet], + threshold_fn: Callable[[SpectrumMatch], bool]=lambda x: x.q_value < 0.05): + self.scan_loader = scan_loader + self.chromatograms = chromatograms + + self.msn_scoring_model = msn_scoring_model + self.msn_evaluation_args = msn_evaluation_args + + self.fdr_estimator = fdr_estimator + self.threshold_fn = threshold_fn + + self.scan_id_to_solution_set = scan_id_to_solution_set + + def find_coeluting( + self, + reference: IdentifiedGlycopeptide, + mass: float, + error_tolerance: float = 2e-5, + ) -> List[Chromatogram]: + alternates = [ + alt for alt in self.chromatograms.find_all_by_mass(mass, error_tolerance) + if reference.overlaps_in_time(alt) + ] + return alternates + + def find_ms2_spectra_for_chromatogram(self, chromatogram: Chromatogram, + error_tolerance: float) -> List[ProcessedScan]: + pinfos = self.scan_loader.msms_for( + chromatogram.weighted_neutral_mass, + error_tolerance, + start_time=chromatogram.start_time - 3, + end_time=chromatogram.end_time + 3, + ) + return [p.product for p in pinfos] + + def evaluate_msn_spectra(self, reference: IdentifiedGlycopeptide, + adduct: MassShift, + product_spectra: List[ProcessedScan]) -> List[MultiScoreSpectrumMatch]: + acc = [] + expects_tandem_shift = adduct.tandem_mass != 0 + for product in product_spectra: + match: SpectrumMatcherBase = self.msn_scoring_model.evaluate( + product, + reference.structure, + mass_shift=adduct, + **self.msn_evaluation_args + ) + + modified_peaks = [] + for pfp in match.solution_map: + chem_shift = pfp.fragment.chemical_shift + if chem_shift and chem_shift.name == adduct.name: + modified_peaks.append(pfp) + + if expects_tandem_shift and not modified_peaks: + continue + + match: MultiScoreSpectrumMatch = MultiScoreSpectrumMatch.from_match_solution(match) + + self.fdr_estimator.score_all([match]) + if product.scan_id in self.scan_id_to_solution_set: + sset = self.scan_id_to_solution_set[product.scan_id] + alt_match = sset.best_solution() + if alt_match.score > match.score: + continue + + if self.threshold_fn(match): + acc.append(match) + return acc + + def process_candidates(self, identified_structures: List[IdentifiedGlycopeptide], + candidate_updates: List[CoElutionCandidate]) -> List[IdentifiedGlycopeptide]: + to_remove = set() + updated_identifications = [] + + for update_candidate in candidate_updates: + updated, dropped = update_candidate.merge(self.scan_id_to_solution_set) + to_remove.update(dropped) + updated_identifications.append(updated) + + for idgp_to_remove in to_remove: + identified_structures.remove(idgp_to_remove) + return identified_structures + + def coeluting_adduction_candidates( + self, + identified_structures: List[IdentifiedGlycopeptide], + adduct: MassShift, + error_tolerance: float = 1e-5, + ) -> List[CoElutionCandidate]: + results = [] + n = len(identified_structures) + for i, ref in enumerate(identified_structures): + if i % 250 == 0: + self.log(f""{i}/{n} ({i / n * 100.0:0.2f}%) {len(results)} cases found"") + if ref.chromatogram is None: + continue + alts = self.find_coeluting( + ref, + ref.weighted_neutral_mass + adduct.mass, + error_tolerance + ) + tandem_candidates: List[ProcessedScan] = [] + for alt in alts: + tandem_candidates.extend( + self.find_ms2_spectra_for_chromatogram(alt, error_tolerance)) + acc = self.evaluate_msn_spectra(ref, adduct, tandem_candidates) + if acc: + results.append( + CoElutionCandidate(ref, alts, acc, adduct)) + return results + + def handle_adduct(self, identified_structures: List[IdentifiedGlycopeptide], + adduct: MassShift, + error_tolerance: float = 1e-5) -> List[IdentifiedGlycopeptide]: + candidates = self.coeluting_adduction_candidates( + identified_structures, adduct, error_tolerance) + identified_structures = self.process_candidates( + identified_structures, candidates) + return identified_structures +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/identified_structure.py",".py","12021","370","'''A set of base implementations for summarizing identified structures +with both MS1 and MSn. +''' +from typing import Any, List, Optional, Set +import numpy as np + +from glycresoft.chromatogram_tree import get_chromatogram, ArithmeticMapping, ChromatogramInterface +from glycresoft.serialize.chromatogram import ChromatogramSolution +from glycresoft.tandem.spectrum_match.solution_set import SpectrumSolutionSet +from glycresoft.tandem.spectrum_match.spectrum_match import FDRSet, ScoreSet, SpectrumMatch + +from .chromatogram_mapping import TandemSolutionsWithoutChromatogram, TargetType + + +class IdentifiedStructure(object): + """"""A base class for summarizing structures identified by tandem MS + and matched to MS1 signal. + + Attributes + ---------- + structure: object + The structure object identified. + spectrum_matches: :class:`list` of :class:`~.SolutionSet` + The MSn spectra that were matched. This is a list of solution sets, + so other structures may be present, and in the case of multi-score + matches, they may even appear to score higher. + chromatogram: :class:`~.ChromatogramSolution` + The MS1 signal over time matched. + ms2_score: float + The best MSn identification score. Usually the highest score amongst + all spectra matched. + q_value: float + The best FDR estimate for this structure. Always the lowest amongst + all spectra matched. + ms1_score: float + The score of :attr:`chromatogram`, or :const:`0` if it is :const:`None`. + total_signal: float + The total abundance of :attr:`chromatogram`. + shared_with: list + Other :class:`IdentifiedStructure` instances which match the same signal. + """""" + + structure: TargetType + + chromatogram: ChromatogramSolution + + spectrum_matches: List[SpectrumSolutionSet] + _best_spectrum_match: Optional[SpectrumMatch] + + ms1_score: float + ms2_score: float + q_value: float + + charge_states: Set[int] + shared_with: List + + def __init__(self, structure, spectrum_matches, chromatogram, shared_with=None): + if shared_with is None: + shared_with = [] + self.structure = structure + self.spectrum_matches = spectrum_matches + self.chromatogram = chromatogram + self._best_spectrum_match = None + self.ms2_score = None + self.q_value = None + self._find_best_spectrum_match() + self.ms1_score = chromatogram.score if chromatogram is not None else 0 + self.charge_states = chromatogram.charge_states if chromatogram is not None else { + psm.scan.precursor_information.charge for psm in spectrum_matches + } + self.shared_with = shared_with + + def clone(self): + dup = self.__class__( + self.structure, + [sset.clone() for sset in self.spectrum_matches], + self.chromatogram.clone(), + self.shared_with[:]) + return dup + + def is_multiscore(self): + """"""Check whether this match has been produced by summarizing a multi-score + match, rather than a single score match. + + Returns + ------- + bool + """""" + try: + return self.spectrum_matches[0].is_multiscore() + except IndexError: + return False + + @property + def score_set(self) -> ScoreSet: + """"""The :class:`~.ScoreSet` of the best MS/MS match + + Returns + ------- + :class:`~.ScoreSet` + """""" + if not self.is_multiscore(): + return None + best_match = self._best_spectrum_match + if best_match is None: + return None + return best_match.score_set + + @property + def best_spectrum_match(self): + return self._best_spectrum_match + + @property + def q_value_set(self) -> FDRSet: + """"""The :class:`~.FDRSet` of the best MS/MS match + + Returns + ------- + :class:`~.FDRSet` + """""" + if not self.is_multiscore(): + return None + best_match = self._best_spectrum_match + if best_match is None: + return None + return best_match.q_value_set + + @property + def key(self): + return self.chromatogram.key + + def _find_best_spectrum_match(self): + is_multiscore = self.is_multiscore() + best_match = None + if is_multiscore: + best_score = -float('inf') + best_q_value = float('inf') + else: + best_score = -float('inf') + for solution_set in self.spectrum_matches: + try: + match = solution_set.solution_for(self.structure) + if is_multiscore: + q_value = match.q_value + if q_value <= best_q_value: + q_delta = abs(best_q_value - q_value) + best_q_value = q_value + if q_delta > 0.001: + best_score = match.score + best_match = match + else: + score = match.score + if score > best_score: + best_score = score + best_match = match + else: + score = match.score + if score > best_score: + best_score = score + best_match = match + except KeyError: + continue + if best_match is None: + self._best_spectrum_match = None + self.ms2_score = 0 + self.q_value = 1.0 + else: + self._best_spectrum_match = best_match + self.ms2_score = best_match.score + self.q_value = best_match.q_value + return best_match + + @property + def neutral_mass(self): + return self.observed_neutral_mass + + @property + def observed_neutral_mass(self): + try: + return self.chromatogram.neutral_mass + except AttributeError: + return self.spectrum_matches[0].scan.precursor_information.neutral_mass + + @property + def weighted_neutral_mass(self): + try: + return self.chromatogram.weighted_neutral_mass + except AttributeError: + return self.observed_neutral_mass + + @property + def start_time(self) -> float: + try: + return self.chromatogram.start_time + except AttributeError: + return None + + @property + def end_time(self) -> float: + try: + return self.chromatogram.end_time + except AttributeError: + return None + + @property + def apex_time(self) -> float: + try: + return self.chromatogram.apex_time + except AttributeError: + return None + + def as_arrays(self): + try: + return self.chromatogram.as_arrays() + except AttributeError: + return np.array([]), np.array([]) + + @property + def integrated_abundance(self): + if self.chromatogram is None: + return 0 + return self.chromatogram.integrated_abundance + + def integrate(self): + if self.chromatogram is None: + return 0 + return self.chromatogram.integrate() + + @property + def total_signal(self): + if self.chromatogram is None: + return 0 + return self.chromatogram.total_signal + + @property + def mass_shifts(self): + try: + return self.chromatogram.mass_shifts + except AttributeError: + shifts = set() + for solution in self.tandem_solutions: + try: + sm = solution.solution_for(self.structure) + shifts.add(sm.mass_shift) + except KeyError: + continue + return list(shifts) + + def mass_shift_signal_fractions(self): + try: + return self.chromatogram.mass_shift_signal_fractions() + except AttributeError: + return ArithmeticMapping() + + def __repr__(self): + return ""IdentifiedStructure(%s, %0.3f, %0.3f, %0.3e)"" % ( + self.structure, self.ms2_score, self.ms1_score, self.total_signal) + + def get_chromatogram(self): + return self.chromatogram + + def is_distinct(self, other): + return get_chromatogram(self).is_distinct(get_chromatogram(other)) + + @property + def tandem_solutions(self): + return self.spectrum_matches + + @tandem_solutions.setter + def tandem_solutions(self, value): + self.spectrum_matches = value + + def mass_shift_tandem_solutions(self): + mapping = ArithmeticMapping() + for sm in self.tandem_solutions: + try: + mapping[sm.solution_for(self.structure).mass_shift] += 1 + except KeyError: + continue + return mapping + + @property + def glycan_composition(self): + return self.structure.glycan_composition + + def __eq__(self, other): + try: + structure_eq = self.structure == other.structure + if structure_eq: + chromatogram_eq = self.chromatogram == other.chromatogram + if chromatogram_eq: + spectrum_matches_eq = self.spectrum_matches == other.spectrum_matches + return spectrum_matches_eq + return False + except AttributeError: + return False + + def __hash__(self): + return hash((self.structure, self.chromatogram)) + + def __iter__(self): + if self.chromatogram is None: + return iter(()) + return iter(self.chromatogram) + + def __len__(self): + if self.chromatogram is None: + return 0 + return len(self.chromatogram) + + def __getitem__(self, i): + if self.chromatogram is None: + raise IndexError(i) + return self.chromatogram[i] + + def overlaps_in_time(self, x): + if self.chromatogram is None: + return False + return self.chromatogram.overlaps_in_time(x) + + @property + def composition(self): + return self.chromatogram.composition + + def has_scan(self, scan_id: str) -> bool: + return any([sset.scan_id == scan_id for sset in self.tandem_solutions]) + + def get_scan(self, scan_id: str) -> SpectrumMatch: + for sset in self.tandem_solutions: + if sset.scan_id == scan_id: + return sset + raise KeyError(scan_id) + + def has_chromatogram(self): + return self.chromatogram is not None + +ChromatogramInterface.register(IdentifiedStructure) + + +def extract_identified_structures(tandem_annotated_chromatograms, threshold_fn, result_type=IdentifiedStructure): + identified_structures = [] + unassigned = [] + + for chroma in tandem_annotated_chromatograms: + if chroma.composition is not None: + if hasattr(chroma, 'entity'): + try: + representers = chroma.representative_solutions + if representers is None: + representers = chroma.most_representative_solutions(threshold_fn) + except AttributeError: + representers = chroma.most_representative_solutions(threshold_fn) + bunch = [] + if isinstance(chroma, TandemSolutionsWithoutChromatogram): + chromatogram_entry = None + else: + chromatogram_entry = chroma + for representer in representers: + ident = result_type(representer.solution, chroma.tandem_solutions, + chromatogram_entry, []) + bunch.append(ident) + for i, ident in enumerate(bunch): + ident.shared_with = bunch[:i] + bunch[i + 1:] + identified_structures.extend(bunch) + else: + unassigned.append(chroma) + else: + unassigned.append(chroma) + return identified_structures, unassigned +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/spectrum_evaluation.py",".py","13955","347","import os +import functools + +from typing import List, Mapping, Optional, TYPE_CHECKING + +from glycresoft.chromatogram_tree.mass_shift import MassShift + +from ms_deisotope import isotopic_shift +from ms_deisotope.data_source import ProcessedScan + +from glycresoft.task import TaskBase +from glycresoft.chromatogram_tree import Unmodified + + +from .process_dispatcher import ( + IdentificationProcessDispatcher, + SolutionHandler, + MultiScoreSolutionHandler, + MultiScoreSolutionPacker, + SequentialIdentificationProcessor) + +from .workload import WorkloadManager, DEFAULT_WORKLOAD_MAX +from .spectrum_match import ( + MultiScoreSpectrumSolutionSet, + SpectrumSolutionSet) + + +if TYPE_CHECKING: + from glycresoft.database.mass_collection import SearchableMassCollection + + +def group_by_precursor_mass(scans, window_size=1.5e-5): + scans = sorted( + scans, key=lambda x: x.precursor_information.extracted_neutral_mass, + reverse=True) + groups = [] + if len(scans) == 0: + return groups + current_group = [scans[0]] + last_scan = scans[0] + for scan in scans[1:]: + delta = abs( + (scan.precursor_information.extracted_neutral_mass - + last_scan.precursor_information.extracted_neutral_mass + ) / last_scan.precursor_information.extracted_neutral_mass) + if delta > window_size: + groups.append(current_group) + current_group = [scan] + else: + current_group.append(scan) + last_scan = scan + groups.append(current_group) + return groups + + +class TandemClusterEvaluatorBase(TaskBase): + tandem_cluster: List[ProcessedScan] + structure_database: ""SearchableMassCollection"" + verbose: bool + n_processes: int + mass_shifts: List[MassShift] + probing_range_for_missing_precursors: int + mass_shift_map: Mapping[str, MassShift] + batch_size: int + trust_precursor_fits: bool + + neutron_offset = isotopic_shift() + solution_set_type = SpectrumSolutionSet + + def __init__(self, tandem_cluster, scorer_type, structure_database, verbose=False, + n_processes=1, ipc_manager=None, probing_range_for_missing_precursors=3, + mass_shifts=None, batch_size=DEFAULT_WORKLOAD_MAX, trust_precursor_fits=True): + if mass_shifts is None: + mass_shifts = [Unmodified] + self.tandem_cluster = tandem_cluster + self.scorer_type = scorer_type + self.structure_database = structure_database + self.verbose = verbose + self.n_processes = n_processes + self.ipc_manager = ipc_manager + self.probing_range_for_missing_precursors = probing_range_for_missing_precursors + self.mass_shifts = mass_shifts + self.mass_shift_map = { + m.name: m for m in self.mass_shifts + } + self.batch_size = batch_size + self.trust_precursor_fits = trust_precursor_fits + + def _mark_hit(self, match): + return self.structure_database.mark_hit(match) + + def _mark_batch(self): + return self.structure_database.mark_batch() + + def search_database_for_precursors(self, mass: float, precursor_error_tolerance: float=1e-5): + return self.structure_database.search_mass_ppm(mass, precursor_error_tolerance) + + def find_precursor_candidates(self, scan: ProcessedScan, error_tolerance: float=1e-5, + probing_range: int=0, mass_shift: Optional[MassShift]=None): + if mass_shift is None: + mass_shift = Unmodified + hits = [] + intact_mass = scan.precursor_information.extracted_neutral_mass + for i in range(probing_range + 1): + query_mass = intact_mass - (i * self.neutron_offset) - mass_shift.mass + hits.extend( + map(self._mark_hit, + self.search_database_for_precursors(query_mass, error_tolerance))) + return hits + + def score_one(self, scan: ProcessedScan, precursor_error_tolerance=1e-5, + mass_shifts: List[MassShift]=None, **kwargs) -> SpectrumSolutionSet: + """"""Search one MSn scan against the database and score all candidate matches + + Parameters + ---------- + scan : ms_deisotope.ProcessedScan + The MSn scan to search + precursor_error_tolerance : float, optional + The mass error tolerance for the precursor + mass_shifts : Iterable of MassShift, optional + The set of MassShifts to consider. Defaults to (Unmodified,) + **kwargs + Keyword arguments passed to :meth:`evaluate` + + Returns + ------- + SpectrumSolutionSet + The set of solutions for the searched scan + """""" + if mass_shifts is None: + mass_shifts = (Unmodified,) + solutions = [] + + if (not scan.precursor_information.defaulted and self.trust_precursor_fits): + probe = 0 + else: + probe = self.probing_range_for_missing_precursors + hits = [] + for mass_shift in mass_shifts: + hits.extend(self.find_precursor_candidates( + scan, precursor_error_tolerance, probing_range=probe, + mass_shift=mass_shift)) + self._mark_batch() + for structure in hits: + result = self.evaluate( + scan, structure, mass_shift=mass_shift, **kwargs) + solutions.append(result) + out = self.solution_set_type( + scan, solutions).sort().select_top() + return out + + def score_all(self, precursor_error_tolerance: float=1e-5, + simplify: bool=False, **kwargs) -> List[SpectrumSolutionSet]: + """"""Search and score all scans in :attr:`tandem_cluster` + + Parameters + ---------- + precursor_error_tolerance : float, optional + The mass error tolerance for the precursor + simplify : bool, optional + Whether or not to call :meth:`.SpectrumSolutionSet.simplify` on each + scan's search result. + **kwargs + Keyword arguments passed to :meth:`evaluate` + + Returns + ------- + list of SpectrumSolutionSet + """""" + out = [] + + # loop over mass_shifts so that sequential queries deals with similar masses to + # make better use of the database's cache + for mass_shift in sorted(self.mass_shifts, key=lambda x: x.mass): + # make iterable for score_one API + mass_shift = (mass_shift,) + for scan in self.tandem_cluster: + solutions = self.score_one( + scan, precursor_error_tolerance, + mass_shifts=mass_shift, + **kwargs) + if len(solutions) > 0: + out.append(solutions) + if simplify: + for case in out: + case.simplify() + case.select_top() + return out + + def evaluate(self, scan: ProcessedScan, structure, *args, **kwargs): + """"""Computes the quality of the match between ``scan`` + and the component fragments of ``structure``. + + To be overridden by implementing classes. + + Parameters + ---------- + scan : ms_deisotope.ProcessedScan + The scan to evaluate + structure : object + An object representing a structure (peptide, glycan, glycopeptide) + to produce fragments from and search against ``scan`` + *args + Propagated + **kwargs + Propagated + + Returns + ------- + SpectrumMatcherBase + """""" + raise NotImplementedError() + + def _map_scans_to_hits(self, scans: List[ProcessedScan], precursor_error_tolerance: float=1e-5) -> WorkloadManager: + groups = group_by_precursor_mass( + scans, precursor_error_tolerance * 1.5) + + workload = WorkloadManager() + + i = 0 + n = len(scans) + report_interval = 0.25 * n if n < 2000 else 0.1 * n + last_report = report_interval + self.log(""... Begin Collecting Hits"") + for mass_shift in sorted(self.mass_shifts, key=lambda x: x.mass): + self.log(""... Mapping For %s"" % (mass_shift.name,)) + i = 0 + last_report = report_interval + for group in groups: + if len(group) == 0: + continue + i += len(group) + report = False + if i > last_report: + report = True + self.log( + ""...... Mapping %0.2f%% of spectra (%d/%d) %0.4f"" % ( + i * 100. / n, i, n, + group[0].precursor_information.extracted_neutral_mass)) + while last_report < i and report_interval != 0: + last_report += report_interval + j = 0 + for scan in group: + workload.add_scan(scan) + + # For a sufficiently dense database or large value of probe, this + # could easily throw the mass interval cache scheme into hysteresis. + # If this does occur, instead of doing this here, we could search all + # defaulted precursors afterwards. + if not scan.precursor_information.defaulted and self.trust_precursor_fits: + probe = 0 + else: + probe = self.probing_range_for_missing_precursors + hits = self.find_precursor_candidates( + scan, precursor_error_tolerance, probing_range=probe, + mass_shift=mass_shift) + for hit in hits: + j += 1 + workload.add_scan_hit(scan, hit, mass_shift.name) + if report: + self.log(""...... Mapping Segment Done. (%d spectrum-pairs)"" % (j,)) + self._mark_batch() + return workload + + def _get_solution_handler(self): + if issubclass(self.solution_set_type, MultiScoreSpectrumSolutionSet): + handler_tp = MultiScoreSolutionHandler + score_set_type = self.scorer_type.get_score_set_type() + packer = MultiScoreSolutionPacker(score_set_type) + handler_tp = functools.partial(handler_tp, packer=packer) + else: + handler_tp = SolutionHandler + return handler_tp + + def _transform_matched_collection(self, solution_set_collection: List[SpectrumSolutionSet], + *args, **kwargs) -> List[SpectrumSolutionSet]: + '''This helper method can be used to re-write the target + attribute of spectrm matches. By default, it is a no-op. + + Returns + ------- + :class:`list` of :class:`SpectrumSolutionSet` + ''' + return solution_set_collection + + def _evaluate_hit_groups_single_process(self, workload: WorkloadManager, *args, **kwargs) -> Mapping[str, List]: + batch_size, scan_map, hit_map, hit_to_scan_map, scan_hit_type_map, hit_group_map = workload + handler_tp = self._get_solution_handler() + processor = SequentialIdentificationProcessor( + self, + self.mass_shift_map, + evaluation_args=kwargs, + solution_handler_type=handler_tp) + processor.process(scan_map, hit_map, hit_to_scan_map, + scan_hit_type_map, hit_group_map) + return processor.scan_solution_map + + def collect_scan_solutions(self, scan_solution_map: Mapping[str, List], + scan_map: Mapping[str, ProcessedScan], + *args, **kwags) -> List[SpectrumSolutionSet]: + result_set = [] + for scan_id, solutions in scan_solution_map.items(): + if len(solutions) == 0: + continue + scan = scan_map[scan_id] + out = self.solution_set_type(scan, solutions).sort() + # This is necessary to reduce the degree to which junk matches need to have their targets re-built + out.select_top() + if len(out) == 0: + continue + result_set.append(out) + self._transform_matched_collection(result_set, *args, **kwags) + return result_set + + @property + def _worker_specification(self): + raise NotImplementedError() + + def _evaluate_hit_groups_multiple_processes(self, workload: WorkloadManager, **kwargs): + batch_size, scan_map, hit_map, hit_to_scan, scan_hit_type_map, hit_group_map = workload + worker_type, init_args = self._worker_specification + handler_tp = self._get_solution_handler() + dispatcher = IdentificationProcessDispatcher( + worker_type, self.scorer_type, evaluation_args=kwargs, init_args=init_args, + n_processes=self.n_processes, ipc_manager=self.ipc_manager, + mass_shift_map=self.mass_shift_map, solution_handler_type=handler_tp) + return dispatcher.process(scan_map, hit_map, hit_to_scan, scan_hit_type_map, hit_group_map) + + def evaluate_hit_groups(self, batch, **kwargs) -> Mapping[str, List]: + if self.n_processes == 1 or len(batch.hit_map) < 2500: + return self._evaluate_hit_groups_single_process( + batch, **kwargs) + else: + return self._evaluate_hit_groups_multiple_processes( + batch, **kwargs) + + def score_bunch(self, scans: List[ProcessedScan], + precursor_error_tolerance: float=1e-5, **kwargs) -> List[SpectrumSolutionSet]: + workload = self._map_scans_to_hits( + scans, precursor_error_tolerance) + solutions = [] + for batch in workload.batches(self.batch_size): + scan_solution_map = self.evaluate_hit_groups(batch, **kwargs) + solutions += self.collect_scan_solutions(scan_solution_map, batch.scan_map) + return solutions +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/workload.py",".py","17268","474","import os +import warnings + +from typing import ( + IO, Any, Dict, DefaultDict, + Iterable, Iterator, List, + Set, Tuple, Optional, + Union, Hashable, NamedTuple +) +from collections import defaultdict + +from ms_deisotope.data_source import ProcessedScan + +from glycresoft.chromatogram_tree import Unmodified + +from .spectrum_graph import ScanGraph + + +HitID = Hashable +GroupID = Hashable +DBHit = Any + +WorkloadT = Union['WorkloadManager', 'WorkloadBatch'] + +# This number is overriden in spectrum_evaluation +# DEFAULT_WORKLOAD_MAX = 25e6 +DEFAULT_WORKLOAD_MAX = -1 +DEFAULT_WORKLOAD_MAX = float(os.environ.get(""GLYCRESOFTDEFAULTWORKLOADMAX"", DEFAULT_WORKLOAD_MAX)) + + +class WorkloadManager(object): + """"""An object that tracks the co-dependence of multiple query MSn + scans on the same hit structures. + + By only dealing with a part of the entire workload at a time, the + database search engine can avoid holding very large numbers of temporary + objects in memory while waiting for related computations finish in + random order. + + Attributes + ---------- + hit_map : dict + hit structure id to the structure object + hit_to_scan_map : defaultdict(list) + Maps hit structure id to a list of scan ids it matched + scan_hit_type_map : defaultdict(str) + Maps a scan id, hit structure id pair to the name of the mass + shift type used to complete the match + scan_map : dict + Maps scan id to :class:`ms_deisotope.ProcessedScan` object + scan_to_hit_map : defaultdict(list) + Maps scan id to the structures it hit + """""" + + scan_map: Dict[str, ProcessedScan] + hit_map: Dict[HitID, DBHit] + hit_to_scan_map: DefaultDict[HitID, List[str]] + scan_to_hit_map: DefaultDict[str, List[HitID]] + scan_hit_type_map: DefaultDict[Tuple[str, HitID], str] + hit_group_map: DefaultDict[GroupID, Set[HitID]] + + _scan_graph: Optional[ScanGraph] + + def __init__(self): + self.scan_map = dict() + self.hit_map = dict() + self.hit_to_scan_map = defaultdict(list) + self.scan_to_hit_map = defaultdict(list) + self.scan_hit_type_map = defaultdict(lambda: Unmodified.name) + self._scan_graph = None + self.hit_group_map = defaultdict(set) + + def clear(self): + self.scan_map.clear() + self.hit_map.clear() + self.hit_to_scan_map.clear() + self.scan_to_hit_map.clear() + self.scan_hit_type_map.clear() + self.hit_group_map.clear() + self._scan_graph = None + + def pack(self): + """""" + Drop any scans that haven't been matched to a database hit. + + Returns + ------- + WorkloadManager + """""" + unmatched_scans = set(self.scan_map) - set(self.scan_to_hit_map) + for k in unmatched_scans: + self.scan_map.pop(k, None) + return self + + def update(self, other: 'WorkloadManager'): + self.scan_map.update(other.scan_map) + self.hit_map.update(other.hit_map) + self.merge_hit_to_scan_map(other) + self.merge_scan_to_hit_map(other) + self.merge_hit_group_map(other) + self.scan_hit_type_map.update(other.scan_hit_type_map) + self._scan_graph = None + + def merge_hit_to_scan_map(self, other: 'WorkloadManager'): + """"""Merge the :attr:`hit_to_scan_map` of another :class:`WorkloadManager` + object into this one, adding non-redundant pairs. + + Parameters + ---------- + other : :class:`WorkloadManager` + The other workload manager to merge in. + """""" + for hit_id, scans in other.hit_to_scan_map.items(): + already_present = {scan.id for scan in self.hit_to_scan_map[hit_id]} + for scan in scans: + if scan.id not in already_present: + self.hit_to_scan_map[hit_id].append(scan) + self.scan_hit_type_map[scan.id, hit_id] = other.scan_hit_type_map[scan.id, hit_id] + + def merge_scan_to_hit_map(self, other: 'WorkloadManager'): + """"""Merge the :attr:`scan_to_hit_map` of another :class:`WorkloadManager` + object into this one, adding non-redundant pairs. + + Parameters + ---------- + other : :class:`WorkloadManager` + The other workload manager to merge in. + """""" + for scan_id, hit_ids in other.scan_to_hit_map.items(): + already_present = set(self.scan_to_hit_map[scan_id]) + for hit_id in hit_ids: + if hit_id not in already_present: + self.scan_to_hit_map[scan_id].append(hit_id) + self.scan_hit_type_map[scan_id, hit_id] = other.scan_hit_type_map[scan_id, hit_id] + + def merge_hit_group_map(self, other: 'WorkloadManager'): + for group_key, members in other.hit_group_map.items(): + self.hit_group_map[group_key].update(members) + + def add_scan(self, scan: ProcessedScan): + """"""Register a Scan-like object for tracking + + Parameters + ---------- + scan : Scan-like + """""" + self.scan_map[scan.id] = scan + + def add_scan_hit(self, scan: ProcessedScan, hit: DBHit, hit_type: str=Unmodified.name): + """"""Register a matching relationship between ``scan`` and ``hit`` + with a mass shift of type ``hit_type`` + + Parameters + ---------- + scan : Scan-like + The scan that was matched + hit : StructureRecord-like + The structure that was matched + hit_type : str, optional + The name of the :class:`.MassShift` that was used to + bridge the total mass of the match. + """""" + self.hit_map[hit.id] = hit + self.hit_to_scan_map[hit.id].append(scan) + self.scan_to_hit_map[scan.id].append(hit.id) + self.scan_hit_type_map[scan.id, hit.id] = hit_type + + def build_scan_graph(self, recompute=False) -> ScanGraph: + """""" + Constructs a graph of scans where scans + with common hits are conneted by an edge. + + This can be used to determine the set of scans + which all depend upon the same structures and + so should be processed together to minimize the + amount of work done to recompute fragments. + + Parameters + ---------- + recompute : bool, optional + If recompute is True, the graph will be built + from scratch, ignoring the cached copy if it + exists. + + Returns + ------- + ScanGraph + """""" + if self._scan_graph is not None and not recompute: + return self._scan_graph + graph = ScanGraph(self.scan_map.values()) + for key, values in self.hit_to_scan_map.items(): + values = sorted(values, key=lambda x: x.index) + for i, scan in enumerate(values): + for other in values[i + 1:]: + graph.add_edge_between(scan.id, other.id, key) + self._scan_graph = graph + return graph + + def compute_workloads(self) -> List[Tuple]: + """""" + Determine how much work is needed to evaluate all matches + to a set of common scans. + + Construct a dependency graph relating scans and hit + structures using :meth:`build_scan_graph` and build connected components. + + Returns + ------- + list + A list of tuples, each tuple containing a connected component and + the number of comparisons contained in that component. + """""" + graph = self.build_scan_graph() + components = graph.connected_components() + workloads = [] + for m in components: + workloads.append((m, sum([len(c.edges) for c in m]))) + return workloads + + def total_work_required(self, workloads=None): + """""" + Compute the total amount of work required to + resolve this complete workload + + Returns + ------- + int + The amount of work contained in this load, or 1 + if the workload is empty. + """""" + return sum(map(len, self.scan_to_hit_map.values())) + + def log_workloads(self, handle: IO[str], workloads: Optional[List['WorkloadBatch']]=None): + """""" + Writes the current workload graph cluster sizes to a text file + for diagnostic purposes + + Parameters + ---------- + handle : file-like + The file to write the workload graph cluster sizes to + workloads : list, optional + The precomputed workload graph clusters. If None, they will + be computed with :meth:`compute_workloads` + """""" + if workloads is None: + workloads = self.compute_workloads() + workloads = sorted(workloads, key=lambda x: x[0][0].precursor_information.neutral_mass, + reverse=True) + for scans, load in workloads: + handle.write(""Work: %d Comparisons\n"" % (load,)) + for scan_node in scans: + handle.write(""%s\t%f\t%d\n"" % ( + scan_node.id, + scan_node.precursor_information.neutral_mass, + len(scan_node.edges))) + + def __iter__(self): + yield self.total_size + yield self.scan_map + yield self.hit_map + yield self.hit_to_scan_map + yield self.scan_hit_type_map + yield self.hit_group_map + + def __eq__(self, other: WorkloadT): + if self.hit_map != other.hit_map: + return False + elif self.scan_map != other.scan_map: + return False + elif self.scan_hit_type_map != other.scan_hit_type_map: + return False + elif self.hit_to_scan_map != other.hit_to_scan_map: + return False + elif self.hit_group_map != other.hit_group_map: + return False + return True + + def __ne__(self, other): + return not (self == other) + + @property + def total_size(self): + """"""Compute the total amount of work required to + resolve this complete workload + + Returns + ------- + int + The amount of work contained in this load, or 1 + if the workload is empty. + """""" + return sum(map(len, self.scan_to_hit_map.values())) + + @property + def scan_count(self): + """"""Return the number of scans in this workload + + Returns + ------- + int + """""" + return len(self.scan_map) + + @property + def hit_count(self): + """"""Return the number of structures in this workload + + Returns + ------- + int + """""" + return len(self.hit_map) + + def __repr__(self): + template = 'WorkloadManager(scan_map_size={}, hit_map_size={}, total_cross_product={})' + rendered = template.format( + len(self.scan_map), len(self.hit_map), + self.total_size) + return rendered + + def batches(self, max_size: Optional[int]=None, ignore_groups: bool=False) -> Iterator['WorkloadBatch']: + """"""Partition the workload into batches of approximately + ``max_size`` comparisons. + + This guarantee is only approximate because a batch will + only be broken at the level of a scan. + + Parameters + ---------- + max_size : float, optional + The maximum size of a workload + + Yields + ------ + WorkloadBatch + self-contained work required for a set of related scans + whose total work is approximately ``max_size`` + """""" + if max_size is None: + max_size = DEFAULT_WORKLOAD_MAX + elif max_size <= 0: + max_size = float('inf') + + if max_size == float('inf'): + current_scan_map = self.scan_map.copy() + current_hit_map = self.hit_map.copy() + current_hit_to_scan_map = {k: [v.id for v in vs] for k, vs in self.hit_to_scan_map.items()} + current_scan_hit_type_map = self.scan_hit_type_map.copy() + current_hit_group_map = self.hit_group_map.copy() + batch = WorkloadBatch( + self.total_size, current_scan_map, + current_hit_map, current_hit_to_scan_map, + current_scan_hit_type_map, current_hit_group_map) + if batch.batch_size: + yield batch + return + + current_batch_size = 0 + current_scan_map = dict() + current_hit_map = dict() + current_hit_to_scan_map = defaultdict(list) + current_scan_hit_type_map = defaultdict(lambda: Unmodified.name) + current_hit_group_map = defaultdict(set) + + if self.hit_group_map and not ignore_groups: + source = sorted(self.hit_group_map.items()) + batch_index = 0 + for group_id, hit_ids in source: + current_hit_group_map[group_id] = hit_ids + for hit_id in hit_ids: + current_hit_map[hit_id] = self.hit_map[hit_id] + for scan in self.hit_to_scan_map[hit_id]: + scan_id = scan.id + current_scan_map[scan_id] = self.scan_map[scan_id] + current_hit_to_scan_map[hit_id].append(scan_id) + current_scan_hit_type_map[ + scan_id, hit_id] = self.scan_hit_type_map[scan_id, hit_id] + current_batch_size += 1 + + if current_batch_size > max_size: + batch = WorkloadBatch( + current_batch_size, current_scan_map, + current_hit_map, current_hit_to_scan_map, + current_scan_hit_type_map, current_hit_group_map) + if batch.batch_size / max_size > 2: + warnings.warn(""Batch %d has size %d, %0.3f%% larger than threshold"" % ( + batch_index, batch.batch_size, batch.batch_size * 100. / max_size)) + batch_index += 1 + current_batch_size = 0 + current_scan_map = dict() + current_hit_map = dict() + current_hit_to_scan_map = defaultdict(list) + current_scan_hit_type_map = defaultdict( + lambda: Unmodified.name) + current_hit_group_map = defaultdict(set) + if batch.batch_size: + yield batch + else: + source = sorted( + self.scan_map.items(), + key=lambda x: x[1].precursor_information.neutral_mass) + batch_index = 0 + for scan_id, scan in source: + current_scan_map[scan_id] = scan + for hit_id in self.scan_to_hit_map[scan_id]: + current_hit_map[hit_id] = self.hit_map[hit_id] + current_hit_to_scan_map[hit_id].append(scan_id) + current_scan_hit_type_map[ + scan_id, hit_id] = self.scan_hit_type_map[scan_id, hit_id] + current_batch_size += 1 + + if current_batch_size > max_size: + batch = WorkloadBatch( + current_batch_size, current_scan_map, + current_hit_map, current_hit_to_scan_map, + current_scan_hit_type_map, current_hit_group_map) + if batch.batch_size / max_size > 2: + warnings.warn(""Batch %d has size %d, %0.3f%% larger than threshold"" % ( + batch_index, batch.batch_size, batch.batch_size * 100. / max_size)) + batch_index += 1 + current_batch_size = 0 + current_scan_map = dict() + current_hit_map = dict() + current_hit_to_scan_map = defaultdict(list) + current_scan_hit_type_map = defaultdict(lambda: Unmodified.name) + current_hit_group_map = defaultdict(set) + if batch.batch_size: + yield batch + + if current_batch_size > 0: + batch = WorkloadBatch( + current_batch_size, current_scan_map, + current_hit_map, current_hit_to_scan_map, + current_scan_hit_type_map, current_hit_group_map) + if batch.batch_size: + yield batch + + @classmethod + def merge(cls, workloads: Iterable[WorkloadT]): + total = cls() + for inst in workloads: + total.update(inst) + return total + + def mass_range(self) -> Tuple[float, float]: + lo = float('inf') + hi = 0 + for scan in self.scan_map.values(): + mass = scan.precursor_information.neutral_mass + if mass < lo: + lo = mass + if mass > hi: + hi = mass + return (lo, hi) + + +class WorkloadBatch(NamedTuple): + + batch_size: int + scan_map: Dict[str, ProcessedScan] + hit_map: Dict[HitID, DBHit] + hit_to_scan_map: DefaultDict[HitID, List[str]] + scan_hit_type_map: DefaultDict[Tuple[str, HitID], str] + hit_group_map: DefaultDict[GroupID, Set[HitID]] + + def clear(self): + self.scan_map.clear() + self.hit_map.clear() + self.hit_to_scan_map.clear() + self.scan_hit_type_map.clear() + self.hit_group_map.clear() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/spectrum_graph.py",".py","9207","328","from collections import defaultdict + +from typing import Any, Dict, Generic, List, Tuple, TypeVar + +import numpy as np + +from ms_deisotope.data_source import ProcessedScan + + +T = TypeVar('T') + + +class MassWrapper(Generic[T]): + obj: T + mass: float + + def __init__(self, obj, mass): + self.obj = obj + self.mass = mass + + def __repr__(self): + return ""MassWrapper(%s, %f)"" % (self.obj, self.mass) + + +class NodeBase(object): + def __init__(self, index: int): + self.index = index + self._hash = hash(self.index) + self.edges = EdgeSet() + + def __hash__(self): + return self._hash + + def __eq__(self, other): + return self.index == other.index + + def has_incoming_edge(self): + for edge in self.edges: + if edge.is_incoming(self): + return True + return False + + +class EdgeSet(object): + store: Dict[Tuple[NodeBase, NodeBase], 'GraphEdgeBase'] + + def __init__(self, store=None): + if store is None: + store = dict() + self.store = store + + def edge_to(self, node1: NodeBase, node2: NodeBase): + if node2.index < node1.index: + node1, node2 = node2, node1 + return self.store.get((node1, node2)) + + def add(self, edge: 'GraphEdgeBase'): + self.store[edge.node1, edge.node2] = edge + + def remove(self, edge: 'GraphEdgeBase'): + self.store.pop((edge.node1, edge.node2)) + + def __len__(self): + return len(self.store) + + def __iter__(self): + return iter(self.store.values()) + + def __repr__(self): + template = '{self.__class__.__name__}({self.store})' + return template.format(self=self) + + +class AnnotatedMultiEdgeSet(EdgeSet): + def __init__(self, store=None): + if store is None: + store = defaultdict(dict) + EdgeSet.__init__(self, store) + + def __iter__(self): + for subgroup in self.store.values(): + for edge in subgroup.values(): + yield edge + + def add(self, edge): + self.store[edge.node1, edge.node2][edge.annotation] = edge + + def __len__(self): + return sum(map(len, self.store.values())) + + def __repr__(self): + template = '{self.__class__.__name__}({self.store})' + return template.format(self=self) + + +class GraphEdgeBase(object): + __slots__ = [""node1"", ""node2"", ""_hash"", ""_str"", ""indices""] + + node1: NodeBase + node2: NodeBase + indices: Tuple[int, int] + + def __init__(self, node1, node2): + self.node1 = node1 + self.node2 = node2 + + self.indices = (self.node1.index, self.node2.index) + + self._hash = self._make_hash() + self._str = self._make_str() + + node1.edges.add(self) + node2.edges.add(self) + + def _make_hash(self): + return hash((self.node1, self.node2)) + + def _make_str(self): + return ""GraphEdge(%s)"" % ', '.join(map(str, (self.node1, self.node2))) + + def __getitem__(self, key: NodeBase): + if key == self.node1: + return self.node2 + elif key == self.node2: + return self.node1 + else: + raise KeyError(key) + + def is_incoming(self, node: NodeBase): + if node is self.node2: + return True + elif node is self.node1: + return False + else: + return False + + def _traverse(self, node): + return self.node1 if node is self.node2 else self.node2 + + def __eq__(self, other): + return self._str == other._str + + def __str__(self): + return self._str + + def __repr__(self): + return self._str + + def __hash__(self): + return self._hash + + def __reduce__(self): + return self.__class__, (self.node1, self.node2,) + + def copy_for(self, node1: NodeBase, node2: NodeBase): + return self.__class__(node1, node2,) + + def remove(self): + try: + self.node1.edges.remove(self) + except KeyError: + pass + try: + self.node2.edges.remove(self) + except KeyError: + pass + + +NodeT = TypeVar('NodeT', bound=NodeBase) + +class GraphBase(Generic[NodeT]): + edges: EdgeSet + nodes: List[NodeT] + + def __init__(self, edges=None): + if edges is None: + edges = EdgeSet() + self.edges = edges + self.nodes = [] + + def __iter__(self): + return iter(self.nodes) + + def __getitem__(self, i): + node = self.nodes[i] + return node + + def __len__(self): + return len(self.nodes) + + def adjacency_matrix(self): + N = len(self) + A = np.zeros((N, N), dtype=np.uint8) + for edge in self.edges: + A[edge.indices] = 1 + return A + + def topological_sort(self, adjacency_matrix: np.ndarray = None) -> List[NodeT]: + if adjacency_matrix is None: + adjacency_matrix = self.adjacency_matrix() + else: + adjacency_matrix = adjacency_matrix.copy() + waiting = set() + for i in range(adjacency_matrix.shape[0]): + # Check for incoming edges. If no incoming + # edges, add to the waiting set + if adjacency_matrix[:, i].sum() == 0: + waiting.add(i) + + ordered = list() + while waiting: + ix = waiting.pop() + node = self[ix] + ordered.append(node) + # Get the set of outgoing edge terminal indices + outgoing_edges = adjacency_matrix[ix, :] + indices_of_neighbors = np.nonzero(outgoing_edges)[0] + # For each outgoing edge + for neighbor_ix in indices_of_neighbors: + # Remove the edge + adjacency_matrix[ix, neighbor_ix] = 0 + # Test for incoming edges + if (adjacency_matrix[:, neighbor_ix] == 0).all(): + waiting.add(neighbor_ix) + if adjacency_matrix.sum() > 0: + raise ValueError(""%d edges left over"" % (adjacency_matrix.sum(),)) + else: + return ordered + + def path_lengths(self): + adjacency_matrix = self.adjacency_matrix() + distances = np.zeros(len(self)) + for node in self.topological_sort(): + incoming_edges = np.nonzero(adjacency_matrix[:, node.index])[0] + if incoming_edges.shape[0] == 0: + distances[node.index] = 0 + else: + longest_path_so_far = distances[incoming_edges].max() + distances[node.index] = longest_path_so_far + 1 + return distances + + def connected_components(self) -> List[List[NodeT]]: + pool = set(self.nodes) + components = [] + + i = 0 + while pool: + i += 1 + current_component = set() + visited = set() + node = pool.pop() + current_component.add(node) + j = 0 + while current_component: + j += 1 + node = current_component.pop() + visited.add(node) + for edge in node.edges: + if edge.node1 not in visited and edge.node1 in pool: + current_component.add(edge.node1) + pool.remove(edge.node1) + if edge.node2 not in visited and edge.node2 in pool: + current_component.add(edge.node2) + pool.remove(edge.node2) + components.append(list(visited)) + return components + + +class ScanNode(NodeBase): + scan: ProcessedScan + + def __init__(self, scan, index): + self.scan = scan + NodeBase.__init__(self, index) + self.edges = AnnotatedMultiEdgeSet() + + @property + def id(self): + return self.scan.id + + @property + def precursor_information(self): + return self.scan.precursor_information + + def __repr__(self): + return ""ScanNode(%s)"" % (self.scan.id,) + + +class ScanGraphEdge(GraphEdgeBase): + __slots__ = [""annotation""] + + def __init__(self, node1, node2, annotation): + self.annotation = annotation + GraphEdgeBase.__init__(self, node1, node2) + + def _make_hash(self): + return hash((self.node1, self.node2, self.annotation)) + + def _make_str(self): + return ""ScanGraphEdge(%s)"" % ', '.join(map(str, (self.node1, self.node2, self.annotation))) + + def __reduce__(self): + return self.__class__, (self.node1, self.node2, self.annotation) + + def copy_for(self, node1, node2): + return self.__class__(node1, node2, self.annotation) + + +class ScanGraph(GraphBase[ScanNode]): + scans: List[ProcessedScan] + node_map: Dict[str, ScanNode] + + def __init__(self, scans): + GraphBase.__init__(self) + self.scans = scans + self.nodes = [ScanNode(scan, i) for i, scan in enumerate(scans)] + self.node_map = {node.scan.id: node for node in self.nodes} + self.edges = AnnotatedMultiEdgeSet() + + def get_node_by_id(self, scan_id: str): + return self.node_map[scan_id] + + def add_edge_between(self, scan_id1: str, scan_id2: str, annotation=None): + node1 = self.get_node_by_id(scan_id1) + node2 = self.get_node_by_id(scan_id2) + edge = ScanGraphEdge(node1, node2, annotation) + self.edges.add(edge) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/ref.py",".py","871","33","class SpectrumReference(object): + def __init__(self, scan_id, precursor_information=None): + self.scan_id = scan_id + self.precursor_information = precursor_information + + @property + def id(self): + return self.scan_id + + def __eq__(self, other): + try: + return (self.scan_id == other.scan_id) and ( + self.precursor_information == other.precursor_information) + except AttributeError: + return self.scan_id == str(other) + + def __str__(self): + return str(self.scan_id) + + def __hash__(self): + return hash(self.scan_id) + + def __repr__(self): + return ""SpectrumReference({self.id})"".format(self=self) + + +class TargetReference(object): + def __init__(self, id): + self.id = id + + def __repr__(self): + return ""TargetReference({self.id})"".format(self=self) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/localize.py",".py","11521","276","import math + +from array import array +from typing import Any, DefaultDict, List, Tuple, Callable, NamedTuple, Union, Dict, Optional, Counter +from glycresoft.structure.scan import ScanStub, ScanWrapperBase, ScanInformation +from glycresoft.tandem.ref import SpectrumReference + +from ms_deisotope.data_source import ProcessedScan +from ms_deisotope.output import ProcessedMzMLLoader + +from glycopeptidepy.structure import PeptideSequence, Modification, ModificationRule + +from glycresoft.task import TaskBase +from glycresoft.structure import FragmentCachingGlycopeptide +from glycresoft.structure.probability import KDModel, MultiKDModel + +from glycresoft.tandem.peptide.scoring import localize + +from glycresoft.tandem.spectrum_match import SpectrumMatch, SpectrumSolutionSet, LocalizationScore + +from glypy.structure.glycan_composition import HashableGlycanComposition + + +class PeptideGroupToken(NamedTuple): + peptide: PeptideSequence + modifications: Tuple[Tuple[Union[Modification, ModificationRule], int]] + glycan_composition: HashableGlycanComposition + + def __eq__(self, other: 'PeptideGroupToken'): + if not self.peptide.base_sequence_equality(other.peptide): + return False + if self.glycan_composition != other.glycan_composition: + return False + if self.modifications != other.modifications: + return False + return True + + def __ne__(self, other: 'PeptideGroupToken'): + return not self == other + + def __hash__(self): + code = hash(self.glycan_composition) & hash(self.modifications) + code &= len(self.peptide) + code &= hash(self.peptide[0].symbol) + return code + + +SolutionsBin = Tuple[List[SpectrumMatch], PeptideGroupToken] +EvaluatedSolutionBins = Tuple[List[SpectrumMatch], + List[localize.PTMProphetEvaluator]] + +ScanOrRef = Union[ProcessedScan, ScanStub, + SpectrumReference, ScanWrapperBase, ScanInformation] + + +class LocalizationGroup(NamedTuple): + spectrum_matches: List[SpectrumMatch] + localization_matches: List[localize.PTMProphetEvaluator] + + +class EvaluatedSolutionBins(NamedTuple): + solution_set: SpectrumSolutionSet + groups: List[LocalizationGroup] + + @property + def scan_id(self): + return self.solution_set.scan.scan_id + + +class ModificationLocalizationSearcher(TaskBase): + error_tolerance: float + threshold_fn: Callable[[SpectrumMatch], bool] + restricted_modifications: Dict[str, ModificationRule] + model: Optional[MultiKDModel] + + def __init__(self, + threshold_fn: Callable[[SpectrumMatch], + bool] = lambda x: x.q_value < 0.05, + error_tolerance: float = 2e-5, + restricted_modifications: Optional[Dict[str, ModificationRule]] = None, + model: Optional[MultiKDModel]=None): + if restricted_modifications is None: + restricted_modifications = {} + self.threshold_fn = threshold_fn + self.error_tolerance = error_tolerance + self.restricted_modifications = restricted_modifications + self.model = model + + def get_modifications_for_peptide(self, peptide: FragmentCachingGlycopeptide) -> Tuple[Tuple[Tuple[Modification, int]], + HashableGlycanComposition]: + modifications = Counter() + for position in peptide: + if position.modifications: + mod = position.modifications[0].rule + if mod.name in self.restricted_modifications: + mod = self.restricted_modifications[mod.name] + modifications[mod] += 1 + modifications = list(modifications.items()) + modifications.sort(key=lambda x: x[0].name) + glycan = None + if peptide.glycan_composition: + glycan = peptide.glycan_composition + return tuple(modifications), glycan + + def find_overlapping_localization_solutions(self, solution_set: SpectrumSolutionSet) -> List[Tuple[List[SpectrumMatch], + PeptideGroupToken]]: + if isinstance(solution_set, SpectrumMatch): + solution_set = [solution_set] + bins: List[Tuple[List[SpectrumMatch], + PeptideGroupToken]] = [] + for sm in solution_set: + if not self.threshold_fn(sm): + continue + target: FragmentCachingGlycopeptide = sm.target + mod_signature, glycan = self.get_modifications_for_peptide(target) + token = PeptideGroupToken(target, mod_signature, glycan) + for solution_bin, bin_token in bins: + if bin_token == token: + solution_bin.append(sm) + break + else: + bins.append(([sm], token)) + return bins + + def process_localization_bin(self, + scan: ProcessedScan, + modification_group_token: PeptideGroupToken) -> List[localize.PTMProphetEvaluator]: + solutions = [] + scan_description = ScanInformation.from_scan(scan) + for mod_sig, count in modification_group_token.modifications: + el = localize.PTMProphetEvaluator( + scan, + modification_group_token.peptide, + modification_rule=mod_sig, + modification_count=count + ) + el.score_arrangements( + error_tolerance=self.error_tolerance + ) + # At this point we don't need the full scan representation anymore, + # so we can drop the peaks later. + el.scan = scan_description + solutions.append(el) + return solutions + + def get_training_instances(self, solutions: List[EvaluatedSolutionBins]) -> List[localize.PTMProphetEvaluator]: + candidates = [] + for sset_bin in solutions: + for sol in sset_bin.groups: + for loc in sol.localization_matches: + if len(loc.peptidoforms) > 1: + candidates.append(loc) + return candidates + + def train_ptm_prophet(self, training_instances: List[localize.PTMProphetEvaluator], + maxiter: int = 150) -> MultiKDModel: + o_scores = array('d') + m_scores = array('d') + for inst in training_instances: + for scores in inst.solution_for_site.values(): + if not math.isfinite(scores.o_score) or not math.isfinite(scores.m_score): + continue + o_scores.append(scores.o_score) + m_scores.append(scores.m_score) + + while len(o_scores) < 2: + o_scores.append(0.99) + m_scores.append(0.99) + o_scores.append(0.5) + m_scores.append(0.5) + + prophet = MultiKDModel(0.5, [KDModel(), KDModel()]) + for o, m in zip(o_scores, m_scores): + prophet.add(o, [o, m]) + + self.log(""Begin fitting localization score model"") + try: + it, delta = prophet.fit(maxiter) + except ValueError as err: + self.log(f""Failed to fit localization model: {err}"") + self.model = None + return None + if it < maxiter: + self.log( + f""Localization score model converged after {it} iterations"") + else: + self.log( + f""The localization model failed to converge after {it} iterations ({delta})"") + self.model = prophet + if prophet is not None: + prophet.close_thread_pool() + return prophet + + def _select_top_isoform_in_bin(self, sol: LocalizationGroup, prophet: Optional[MultiKDModel]=None): + isoform_scores: DefaultDict[str, + List[LocalizationScore]] = DefaultDict(list) + isoform_weights: DefaultDict[str, float] = DefaultDict(float) + for loc in sol.localization_matches: + seen = set() + for iso, scores, weight in loc.score_isoforms(prophet=prophet): + key = str(iso.peptide) + if key in seen: + continue + isoform_scores[key].extend(scores) + isoform_weights[key] += weight + + max_weight = max(isoform_weights.values()) + for psm in sol.spectrum_matches: + key = str(psm.target) + if key in isoform_scores: + psm.localizations = isoform_scores[key] + if abs(isoform_weights[key] - max_weight) > 1e-2 and psm.best_match: + psm.best_match = False + psm.valid = False + self.log(f""... Invalidating {psm.target}@{psm.scan_id}"") + + def select_top_isoforms(self, solutions: List[List[EvaluatedSolutionBins]], prophet: Optional[MultiKDModel]=None): + if prophet is None: + prophet = self.model + for sset_bin in solutions: + for sol in sset_bin.groups: + self._select_top_isoform_in_bin(sol, prophet=prophet) + + def process_solution_set(self, solution_set: SpectrumSolutionSet) -> EvaluatedSolutionBins: + solution_bins = self.find_overlapping_localization_solutions( + solution_set) + scan = self.resolve_spectrum(solution_set) + solutions = [LocalizationGroup(solution_bin, self.process_localization_bin(scan, signature)) + for solution_bin, signature in solution_bins] + return EvaluatedSolutionBins(solution_set, solutions) + + def resolve_spectrum(self, scan_ref: ScanOrRef) -> ProcessedScan: + if isinstance(scan_ref, ScanWrapperBase): + scan_ref = scan_ref.scan + if isinstance(scan_ref, ProcessedScan): + return scan_ref + raise TypeError(type(scan_ref)) + + def with_scan_loader(self, scan_loader): + dup = ScanLoadingModificationLocalizationSearcher( + scan_loader, self.threshold_fn, self.error_tolerance, self.restricted_modifications) + dup.model = self.model + return dup + + + +class ScanLoadingModificationLocalizationSearcher(ModificationLocalizationSearcher): + scan_loader: ProcessedMzMLLoader + + def __init__(self, scan_loader: ProcessedMzMLLoader, + threshold_fn: Callable[[SpectrumMatch], bool]=lambda x: x.q_value < 0.05, + error_tolerance: float = 2e-5, + restricted_modifications: Optional[Dict[str, ModificationRule]] = None, + model: Optional[MultiKDModel]=None): + self.scan_loader = scan_loader + super().__init__(threshold_fn, error_tolerance, restricted_modifications, model) + + def __reduce__(self): + return self.__class__, (None, self.threshold_fn, self.error_tolerance, self.restricted_modifications) + + def resolve_spectrum(self, scan_ref: ScanOrRef) -> ProcessedScan: + if isinstance(scan_ref, ScanWrapperBase): + scan_ref = scan_ref.scan + if isinstance(scan_ref, ProcessedScan): + return scan_ref + if self.scan_loader is None: + raise TypeError(""Cannot load spectrum by reference when the `scan_loader` attribute is not set"") + return self.scan_loader.get_scan_by_id(scan_ref.scan_id) + + def simplify(self): + return ModificationLocalizationSearcher( + self.threshold_fn, + self.error_tolerance, + self.restricted_modifications, + self.model) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/reporter.py",".py","75","1","from ms_deisotope.qc.signature import TMTReporterExtractor, ReporterIonInfo","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/process_dispatcher.py",".py","35","2","from .evaluation_dispatch import * +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/chromatogram_graph.py",".py","1842","43","from collections import defaultdict + +from glycopeptidepy.structure import sequence + +from glycresoft.chromatogram_tree.relation_graph import ( + ChromatogramGraph, ChromatogramGraphEdge, ChromatogramGraphNode) + + +class GlycopeptideChromatogramGraphNode(ChromatogramGraphNode): + def __init__(self, chromatogram, index, edges=None): + super(GlycopeptideChromatogramGraphNode, self).__init__(chromatogram, index, edges) + self.backbone = None + if chromatogram.composition: + if hasattr(chromatogram, 'entity'): + entity = chromatogram.entity + self.backbone = entity.get_sequence(include_glycan=False) + + +class GlycopeptideChromatogramGraph(ChromatogramGraph): + def __init__(self, chromatograms): + self.sequence_map = defaultdict(list) + super(GlycopeptideChromatogramGraph, self).__init__(chromatograms) + + def _construct_graph_nodes(self, chromatograms): + nodes = [] + for i, chroma in enumerate(chromatograms): + node = (GlycopeptideChromatogramGraphNode(chroma, i)) + nodes.append(node) + if node.chromatogram.composition: + self.enqueue_seed(node) + self.assignment_map[node.chromatogram.composition] = node + if node.backbone is not None: + self.sequence_map[node.backbone].append(node) + return nodes + + def find_edges(self, node, query_width=2., transitions=None, **kwargs): + super(GlycopeptideChromatogramGraph, self).find_edges(node, query_width, transitions) + if node.backbone is not None: + for other_node in self.sequence_map[node.backbone]: + ppm_error = 0 + rt_error = node.center - other_node.center + ChromatogramGraphEdge(node, other_node, 'backbone', ppm_error, rt_error) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/core_search.py",".py","49920","1232","# -*- coding: utf-8 -*- + +import logging +import warnings + +from collections import namedtuple, defaultdict + +from typing import Any, DefaultDict, Dict, Generic, Optional, List, Set, Tuple, TypeVar, Union, Sequence + +import numpy as np + +from ms_deisotope.data_source import ProcessedScan +from ms_deisotope.peak_set import DeconvolutedPeak + +from glypy.structure.glycan_composition import FrozenMonosaccharideResidue, HashableGlycanComposition, GlycanComposition +from glypy.utils.enum import EnumValue + +from glycopeptidepy.structure.fragment import StubFragment +from glycopeptidepy.structure.fragmentation_strategy import StubGlycopeptideStrategy, _AccumulatorBag +from glycopeptidepy.structure.fragmentation_strategy.glycan import GlycanCompositionFragment + + +from glycresoft.chromatogram_tree.mass_shift import MassShift +from glycresoft.serialize import GlycanCombination, GlycanTypes +from glycresoft.database.disk_backed_database import PPMQueryInterval +from glycresoft.chromatogram_tree import Unmodified +from glycresoft.structure.denovo import PathSet, PathFinder, Path + +logger = logging.getLogger(""glycresoft.core_search"") + + +hexnac = FrozenMonosaccharideResidue.from_iupac_lite(""HexNAc"") +hexose = FrozenMonosaccharideResidue.from_iupac_lite(""Hex"") +xylose = FrozenMonosaccharideResidue.from_iupac_lite(""Xyl"") +fucose = FrozenMonosaccharideResidue.from_iupac_lite(""Fuc"") +dhex = FrozenMonosaccharideResidue.from_iupac_lite(""dHex"") +neuac = FrozenMonosaccharideResidue.from_iupac_lite(""NeuAc"") +neugc = FrozenMonosaccharideResidue.from_iupac_lite(""NeuGc"") + + +def approximate_internal_size_of_glycan(glycan_composition): + terminal_groups = glycan_composition._getitem_fast(neuac) +\ + glycan_composition._getitem_fast(neugc) + side_groups = glycan_composition._getitem_fast(fucose) + glycan_composition._getitem_fast(dhex) + n = sum(glycan_composition.values()) + n -= terminal_groups + if side_groups > 1: + n -= 1 + return n + + +def glycan_side_group_count(glycan_composition): + side_groups = glycan_composition._getitem_fast( + fucose) + glycan_composition._getitem_fast(dhex) + return side_groups + + +def isclose(a, b, rtol=1e-05, atol=1e-08): + return abs(a - b) <= atol + rtol * abs(b) + + +default_components = (hexnac, hexose, xylose, fucose,) + + +class CoreMotifFinder(PathFinder): + minimum_peptide_mass: float + + def __init__(self, components=None, product_error_tolerance=1e-5, minimum_peptide_mass=350.): + if components is None: + components = default_components + super().__init__(components, product_error_tolerance, False) + self.minimum_peptide_mass = minimum_peptide_mass + + def find_n_linked_core(self, groups: DefaultDict[Any, List], min_size=1): + sequence = [hexnac, hexnac, hexose, hexose, hexose] + expected_n = len(sequence) + terminals = dict() + + for label, paths in groups.items(): + label_i = 0 + expected_i = 0 + path_n = len(label) + while label_i < path_n and expected_i < expected_n: + edge = label[label_i] + label_i += 1 + expected = sequence[expected_i] + if expected == edge: + expected_i += 1 + elif edge == fucose or edge == dhex: + continue + else: + break + if expected_i >= min_size: + for path in paths: + last_path = terminals.get(path[0].start) + if last_path is None: + terminals[path[0].start] = path + else: + terminals[path[0].start] = max((path, last_path), key=lambda x: x.total_signal) + return PathSet(terminals.values()) + + def find_o_linked_core(self, groups: DefaultDict[Any, List], min_size=1): + sequence = [(hexnac, hexose), (hexnac, hexose, fucose,), (hexnac, hexose, fucose,)] + expected_n = len(sequence) + terminals = dict() + + for label, paths in groups.items(): + label_i = 0 + expected_i = 0 + path_n = len(label) + while label_i < path_n and expected_i < expected_n: + edge = label[label_i] + label_i += 1 + expected = sequence[expected_i] + if edge in expected: + expected_i += 1 + else: + break + if expected_i >= min_size: + for path in paths: + last_path = terminals.get(path[0].start) + if last_path is None: + terminals[path[0].start] = path + else: + terminals[path[0].start] = max((path, last_path), key=lambda x: x.total_signal) + return PathSet(terminals.values()) + + def find_gag_linker_core(self, groups: DefaultDict[Any, List], min_size=1): + sequence = [xylose, hexose, hexose, ] + expected_n = len(sequence) + terminals = dict() + + for label, paths in groups.items(): + label_i = 0 + expected_i = 0 + path_n = len(label) + while label_i < path_n and expected_i < expected_n: + edge = label[label_i] + label_i += 1 + expected = sequence[expected_i] + if expected == edge: + expected_i += 1 + elif edge == fucose: + continue + else: + break + if expected_i >= min_size: + for path in paths: + last_path = terminals.get(path[0].start) + if last_path is None: + terminals[path[0].start] = path + else: + terminals[path[0].start] = max((path, last_path), key=lambda x: x.total_signal) + return PathSet(terminals.values()) + + def estimate_peptide_mass(self, scan: ProcessedScan, topn: int=100, mass_shift: MassShift=Unmodified, + query_mass: Optional[float] = None, + simplify: bool = True) -> Union[List[float], List[Tuple[float, List[Path]]]]: + graph = self.build_graph(scan, mass_shift=mass_shift) + paths = self.paths_from_graph(graph) + groups = self.aggregate_paths(paths) + + n_linked_paths = self.find_n_linked_core(groups) + o_linked_paths = self.find_o_linked_core(groups) + gag_linker_paths = self.find_gag_linker_core(groups) + peptide_masses = [] + + has_tandem_shift = abs(mass_shift.tandem_mass) > 0 + + # TODO: split the different motif masses up according to core type efficiently + # but for now just lump them all together + for path in n_linked_paths: + if path.start_mass < self.minimum_peptide_mass: + continue + peptide_masses.append((path.start_mass, path)) + if has_tandem_shift: + peptide_masses.append((path.start_mass - mass_shift.tandem_mass, path)) + for path in o_linked_paths: + if path.start_mass < self.minimum_peptide_mass: + continue + peptide_masses.append((path.start_mass, path)) + if has_tandem_shift: + peptide_masses.append((path.start_mass - mass_shift.tandem_mass, path)) + for path in gag_linker_paths: + if path.start_mass < self.minimum_peptide_mass: + continue + peptide_masses.append((path.start_mass, path)) + if has_tandem_shift: + peptide_masses.append((path.start_mass - mass_shift.tandem_mass, path)) + peptide_masses.sort(key=lambda x: x[0]) + result = [] + paths_for = [] + last = 0 + for m, path in peptide_masses: + if abs(last - m) < 1e-3: + if not simplify: + paths_for.append(path) + continue + if simplify: + result.append(m) + else: + paths_for = [path] + result.append((m, paths_for)) + last = m + return result[:topn] + + def build_peptide_filter(self, scan, error_tolerance=1e-5, mass_shift=Unmodified, query_mass=None): + peptide_masses = self.estimate_peptide_mass( + scan, mass_shift=mass_shift, query_mass=query_mass, simplify=True) + + out = [] + if len(peptide_masses) == 0: + return IntervalFilter([]) + last = PPMQueryInterval(peptide_masses[0], error_tolerance) + for point in peptide_masses[1:]: + interval = PPMQueryInterval(point, error_tolerance) + if interval.overlaps(last): + last.extend(interval) + else: + out.append(last) + last = interval + out.append(last) + return IntervalFilter(out) + + +class CoarseStubGlycopeptideFragment(object): + __slots__ = ['key', 'is_core', 'mass'] + + def __init__(self, key, mass, is_core): + self.key = key + self.mass = mass + self.is_core = is_core + + def __eq__(self, other): + try: + return self.key == other.key and self.is_core == other.is_core + except AttributeError: + return self.key == other + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return hash(int(self.mass)) + + def __lt__(self, other): + return self.mass < other.mass + + def __gt__(self, other): + return self.mass > other.mass + + def __reduce__(self): + return self.__class__, (self.key, self.mass, self.is_core) + + def __repr__(self): + return ""%s(%s, %f, %r)"" % ( + self.__class__.__name__, + self.key, self.mass, self.is_core + ) + + +class GlycanCombinationRecordBase(object): + __slots__ = ['id', 'dehydrated_mass', 'composition', 'count', 'glycan_types', + 'size', ""_fragment_cache"", ""internal_size_approximation"", ""_hash"", + 'fragment_set_properties'] + + id: int + dehydrated_mass: float + composition: GlycanComposition + count: int + glycan_types: List[EnumValue] + size: int + _fragment_cache: Dict[EnumValue, List] + internal_size_approximation: int + _hash: int + fragment_set_properties: dict + + def is_n_glycan(self) -> bool: + return GlycanTypes.n_glycan in self.glycan_types + + def is_o_glycan(self) -> bool: + return GlycanTypes.o_glycan in self.glycan_types + + def is_gag_linker(self) -> bool: + return GlycanTypes.gag_linker in self.glycan_types + + def get_n_glycan_fragments(self) -> List[CoarseStubGlycopeptideFragment]: + if GlycanTypes.n_glycan not in self._fragment_cache: + strategy = StubGlycopeptideStrategy(None, extended=True) + shifts = strategy.n_glycan_composition_fragments( + self.composition, 1, 0) + fragment_structs = [] + for shift in shifts: + if shift[""key""]['HexNAc'] <= 2 and shift[""key""][""Hex""] <= 3: + is_core = True + else: + is_core = False + fragment_structs.append( + CoarseStubGlycopeptideFragment( + shift['key'], shift['mass'], is_core)) + self._fragment_cache[GlycanTypes.n_glycan] = sorted( + set(fragment_structs)) + return self._fragment_cache[GlycanTypes.n_glycan] + else: + return self._fragment_cache[GlycanTypes.n_glycan] + + def get_o_glycan_fragments(self) -> List[CoarseStubGlycopeptideFragment]: + if GlycanTypes.o_glycan not in self._fragment_cache: + strategy = StubGlycopeptideStrategy(None, extended=True) + shifts = strategy.o_glycan_composition_fragments( + self.composition, 1, 0) + fragment_structs = [] + for shift in shifts: + shift['key'] = _AccumulatorBag(shift['key']) + fragment_structs.append( + CoarseStubGlycopeptideFragment( + shift['key'], shift['mass'], True)) + self._fragment_cache[GlycanTypes.o_glycan] = sorted( + set(fragment_structs)) + return self._fragment_cache[GlycanTypes.o_glycan] + else: + return self._fragment_cache[GlycanTypes.o_glycan] + + def get_gag_linker_glycan_fragments(self) -> List[CoarseStubGlycopeptideFragment]: + if GlycanTypes.gag_linker not in self._fragment_cache: + strategy = StubGlycopeptideStrategy(None, extended=True) + shifts = strategy.gag_linker_composition_fragments( + self.composition, 1, 0) + fragment_structs = [] + for shift in shifts: + shift['key'] = _AccumulatorBag(shift['key']) + fragment_structs.append( + CoarseStubGlycopeptideFragment( + shift['key'], shift['mass'], True)) + self._fragment_cache[GlycanTypes.gag_linker] = sorted( + set(fragment_structs)) + return self._fragment_cache[GlycanTypes.gag_linker] + else: + return self._fragment_cache[GlycanTypes.gag_linker] + + def clear(self): + self._fragment_cache.clear() + +try: + _GlycanCombinationRecordBase = GlycanCombinationRecordBase + from glycresoft._c.tandem.core_search import GlycanCombinationRecordBase +except ImportError as err: + print(err) + pass + + +class GlycanCombinationRecord(GlycanCombinationRecordBase): + """"""Represent a glycan combination compactly in memory + + Attributes + ---------- + composition : :class:`~.HashableGlycanComposition` + The glycan combination's composition in monosaccharide units + count : int + The number of distinct glycans this combination contains + dehydrated_mass : float + The total mass shift applied to a peptide when this combination is attached + to it + glycan_types : list + The types of glycans combined to make this entity + """""" + + __slots__ = () + + @classmethod + def from_combination(cls, combination): + inst = cls( + id=combination.id, + dehydrated_mass=combination.dehydrated_mass(), + composition=combination.convert(), + count=combination.count, + glycan_types=tuple(set([ + c.name for component_classes in combination.component_classes + for c in component_classes])), + ) + return inst + + @classmethod + def from_hypothesis(cls, session, hypothesis_id): + query = session.query(GlycanCombination).filter( + GlycanCombination.hypothesis_id == hypothesis_id).group_by( + GlycanCombination.composition, GlycanCombination.count).order_by( + GlycanCombination.dehydrated_mass()) # pylint: disable=no-value-for-parameter + candidates = query.all() + out = [] + for candidate in candidates: + out.append(cls.from_combination(candidate)) + return out + + def _to_dict(self): + return { + ""id"": self.id, + ""dehydrated_mass"": self.dehydrated_mass, + ""composition"": str(self.composition), + ""count"": self.count, + ""glycan_types"": list(map(str, self.glycan_types)), + } + + @classmethod + def _from_dict(cls, d): + d['composition'] = HashableGlycanComposition.parse(d['composition']) + d['glycan_types'] = [GlycanTypes[t] for t in d['glycan_types']] + return cls(**d) + + def __init__(self, id, dehydrated_mass, composition, count, glycan_types): + self.id = id + self.dehydrated_mass = dehydrated_mass + self.composition = composition + self.size = sum(composition.values()) + self.internal_size_approximation = self._approximate_total_size() + self.side_group_count = glycan_side_group_count(self.composition) + self.count = count + self.glycan_types = list(glycan_types) + self._fragment_cache = dict() + self._hash = hash(self.composition) + self.fragment_set_properties = dict() + + def __eq__(self, other): + return (self.composition == other.composition) and (self.count == other.count) and ( + self.glycan_types == other.glycan_types) + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return self._hash + + def _approximate_total_size(self): + return approximate_internal_size_of_glycan(self.composition) + + def __reduce__(self): + return ( + GlycanCombinationRecord, + (self.id, self.dehydrated_mass, self.composition, self.count, self.glycan_types), + self.__getstate__() + ) + + def __getstate__(self): + return { + ""fragment_set_properties"": self.fragment_set_properties + } + + def __setstate__(self, state): + self.fragment_set_properties = state['fragment_set_properties'] + + def __repr__(self): + return ""GlycanCombinationRecord(%s, %d)"" % (self.composition, self.count) + + +class CoarseStubGlycopeptideMatch(object): + def __init__(self, key, mass, shift_mass, peaks_matched): + self.key = key + self.mass = mass + self.shift_mass = shift_mass + self.peaks_matched = peaks_matched + + def __reduce__(self): + return self.__class__, (self.key, self.mass, self.shift_mass, self.peaks_matched) + + def __repr__(self): + return ""%s(%s, %f, %f, %r)"" % ( + self.__class__.__name__, + self.key, self.mass, self.shift_mass, self.peaks_matched + ) + + +class CoarseGlycanMatch(object): + def __init__(self, matched_fragments, n_matched, n_theoretical, core_matched, core_theoretical): + self.fragment_matches = list(matched_fragments) + self.n_matched = n_matched + self.n_theoretical = n_theoretical + self.core_matched = core_matched + self.core_theoretical = core_theoretical + + def __iter__(self): + yield self.matched_fragments + yield self.n_matched + yield self.n_theoretical + yield self.core_matched + yield self.core_theoretical + + def estimate_peptide_mass(self): + weighted_mass_acc = 0.0 + weight_acc = 0.0 + + for fmatch in self.fragment_matches: + fmass = fmatch.shift_mass + for peak in fmatch.peaks_matched: + weighted_mass_acc += (peak.neutral_mass - fmass) * peak.intensity + weight_acc += peak.intensity + if weight_acc == 0: + return -1 + return weighted_mass_acc / weight_acc + + def __repr__(self): + template = ( + ""{self.__class__.__name__}({self.n_matched}, {self.n_theoretical}, "" + ""{self.core_matched}, {self.core_theoretical})"") + return template.format(self=self) + + +class GlycanCoarseScorerBase(object): + product_error_tolerance: float + fragment_weight: float + core_weight: float + + def __init__(self, product_error_tolerance=1e-5, fragment_weight=0.56, core_weight=0.42): + self.product_error_tolerance = product_error_tolerance + self.fragment_weight = fragment_weight + self.core_weight = core_weight + + def _match_fragments(self, scan, peptide_mass, shifts, mass_shift_tandem_mass=0.0): + fragment_matches = [] + core_matched = 0.0 + core_theoretical = 0.0 + has_tandem_shift = abs(mass_shift_tandem_mass) > 0 + for shift in shifts: + if shift.is_core: + is_core = True + core_theoretical += 1 + else: + is_core = False + target_mass = shift.mass + peptide_mass + hits = scan.deconvoluted_peak_set.all_peaks_for(target_mass, self.product_error_tolerance) + if hits: + if is_core: + core_matched += 1 + fragment_matches.append((shift.key, target_mass, hits)) + if has_tandem_shift: + shifted_mass = target_mass + mass_shift_tandem_mass + hits = scan.deconvoluted_peak_set.all_peaks_for( + shifted_mass, self.product_error_tolerance) + if hits: + if is_core: + core_matched += 1 + fragment_matches.append( + CoarseStubGlycopeptideMatch( + shift.key, shifted_mass, shift.mass + mass_shift_tandem_mass, hits)) + + return CoarseGlycanMatch( + fragment_matches, float(len(fragment_matches)), float(len(shifts)), core_matched, core_theoretical) + + # consider adding the internal size approximation to this method and it's Cython implementation. + def _calculate_score(self, glycan_match): + ratio_fragments = (glycan_match.n_matched / glycan_match.n_theoretical) + ratio_core = glycan_match.core_matched / glycan_match.core_theoretical + coverage = (ratio_fragments ** self.fragment_weight) * (ratio_core ** self.core_weight) + score = 0 + for fmatch in glycan_match.fragment_matches: + mass = fmatch.mass + for peak in fmatch.matches: + score += np.log(peak.intensity) * (1 - (np.abs(peak.neutral_mass - mass) / mass) ** 4) * coverage + return score + + def _n_glycan_match_stubs(self, scan, peptide_mass, glycan_combination, mass_shift_tandem_mass=0.0): + shifts = glycan_combination.get_n_glycan_fragments() + return self._match_fragments(scan, peptide_mass, shifts, mass_shift_tandem_mass) + + def _o_glycan_match_stubs(self, scan, peptide_mass, glycan_combination, mass_shift_tandem_mass=0.0): + shifts = glycan_combination.get_o_glycan_fragments() + return self._match_fragments(scan, peptide_mass, shifts, mass_shift_tandem_mass) + + def _gag_match_stubs(self, scan, peptide_mass, glycan_combination, mass_shift_tandem_mass=0.0): + shifts = glycan_combination.get_gag_linker_glycan_fragments() + return self._match_fragments(scan, peptide_mass, shifts, mass_shift_tandem_mass) + +try: + _GlycanCoarseScorerBase = GlycanCoarseScorerBase + from glycresoft._c.tandem.core_search import GlycanCoarseScorerBase +except ImportError: + pass + + +_GlycanMatchResult = namedtuple('GlycanMatchResult', ( + 'peptide_mass', 'score', 'match', 'glycan_size', 'glycan_types', + 'recalibrated_peptide_mass')) + + +class GlycanMatchResult(_GlycanMatchResult): + __slots__ = () + + @property + def fragment_match_count(self): + match = self.match + if match is None: + return 0 + return match.n_matched + + +def group_by_score(matches, threshold=1e-2): + matches = sorted(matches, key=lambda x: x.score, reverse=True) + groups = [] + if len(matches) == 0: + return groups + current_group = [matches[0]] + last_match = matches[0] + for match in matches[1:]: + delta = abs(match.score - last_match.score) + if delta > threshold: + groups.append(current_group) + current_group = [match] + else: + current_group.append(match) + last_match = match + groups.append(current_group) + return groups + + +def flatten(groups): + return [b for a in groups for b in a] + + +SolutionType = TypeVar(""SolutionType"") + + +class GlycanFilteringPeptideMassEstimatorBase(Generic[SolutionType]): + use_denovo_motif: bool + motif_finder: CoreMotifFinder + glycan_combination_db: List[GlycanCombinationRecord] + minimum_peptide_mass: float + use_recalibrated_peptide_mass: float + + def __init__(self, glycan_combination_db, product_error_tolerance=1e-5, + fragment_weight=0.56, core_weight=0.42, minimum_peptide_mass=500.0, + use_denovo_motif=False, components=None, + use_recalibrated_peptide_mass=False): + if not isinstance(glycan_combination_db[0], GlycanCombinationRecord): + glycan_combination_db = [GlycanCombinationRecord.from_combination(gc) + for gc in glycan_combination_db] + self.use_denovo_motif = use_denovo_motif + self.motif_finder = CoreMotifFinder( + components, product_error_tolerance) + self.glycan_combination_db = sorted( + glycan_combination_db, key=lambda x: (x.dehydrated_mass, x.id)) + self.minimum_peptide_mass = minimum_peptide_mass + self.use_recalibrated_peptide_mass = use_recalibrated_peptide_mass + super(GlycanFilteringPeptideMassEstimatorBase, self).__init__( + product_error_tolerance, fragment_weight, core_weight) + + def match(self, scan: ProcessedScan, mass_shift=Unmodified, query_mass=None) -> List[SolutionType]: + raise NotImplementedError() + + def estimate_peptide_mass(self, scan: ProcessedScan, + topn: int=150, + threshold: float=-1, + min_fragments: int=0, + mass_shift: MassShift=Unmodified, + simplify: bool=True, + query_mass: Optional[float] = None) -> Union[List[float], List[SolutionType]]: + '''Given an scan, estimate the possible peptide masses using the connected glycan database and + mass differences from the precursor mass. + + Parameters + ---------- + scan : ProcessedScan + The deconvoluted scan to search + topn : int, optional + The number of solutions to return, sorted by quality descending + threshold : float, optional + The minimum match score to allow a returned solution to have. + min_fragments : int, optional + The minimum number of matched fragments to require a solution to have, independent + of score. + mass_shift : MassShift, optional + The mass shift to apply to + ''' + out = self.match(scan, mass_shift=mass_shift, query_mass=query_mass) + out = [x for x in out if x.score > + threshold and x.fragment_match_count >= min_fragments] + groups = group_by_score(out) + out = flatten(groups[:topn]) + if simplify: + return [x.peptide_mass for x in out] + return out + + def glycan_for_peptide_mass(self, scan: ProcessedScan, peptide_mass: float) -> List[GlycanCombinationRecord]: + matches = [] + try: + glycan_mass = scan.precursor_information.neutral_mass - peptide_mass + except AttributeError: + glycan_mass = scan - peptide_mass + for glycan_record in self.glycan_combination_db: + if abs(glycan_record.dehydrated_mass - glycan_mass) / glycan_mass < self.product_error_tolerance: + matches.append(glycan_record) + elif glycan_mass > glycan_record.dehydrated_mass: + break + return matches + + def build_peptide_filter(self, scan: ProcessedScan, + error_tolerance: Optional[float] = None, + mass_shift: MassShift = Unmodified, + query_mass: Optional[float] = None) -> 'IntervalFilter': + if error_tolerance is None: + error_tolerance = self.product_error_tolerance + peptide_masses = self.estimate_peptide_mass( + scan, mass_shift=mass_shift, query_mass=query_mass) + peptide_masses = [PPMQueryInterval( + p, error_tolerance) for p in peptide_masses] + if self.use_denovo_motif: + path_masses = self.motif_finder.build_peptide_filter( + scan, error_tolerance, mass_shift=mass_shift) + peptide_masses.extend(path_masses) + peptide_masses.sort(key=lambda x: x.center) + + if len(peptide_masses) == 0: + return IntervalFilter([]) + out = IntervalFilter(peptide_masses) + out.compress() + return out + + +class GlycanFilteringPeptideMassEstimator( + GlycanFilteringPeptideMassEstimatorBase[GlycanMatchResult], GlycanCoarseScorerBase): + def n_glycan_coarse_score(self, scan: ProcessedScan, + glycan_combination: GlycanCombinationRecord, + mass_shift: MassShift = Unmodified, + peptide_mass: Optional[float] = None) -> Tuple[float, CoarseGlycanMatch]: + '''Calculates a ranking score from N-glycopeptide stub-glycopeptide fragments. + + This method is derived from the technique used in pGlyco2 [1]. + + References + ---------- + [1] Liu, M.-Q., Zeng, W.-F., Fang, P., Cao, W.-Q., Liu, C., Yan, G.-Q., … Yang, P.-Y. (2017). + pGlyco 2.0 enables precision N-glycoproteomics with comprehensive quality control and + one-step mass spectrometry for intact glycopeptide identification. Nature Communications, + 8(1), 438. https://doi.org/10.1038/s41467-017-00535-2 + ''' + if peptide_mass is None: + peptide_mass = ( + scan.precursor_information.neutral_mass - glycan_combination.dehydrated_mass + ) - mass_shift.mass + if peptide_mass < 0: + return -1e6, None + glycan_match = self._n_glycan_match_stubs( + scan, peptide_mass, glycan_combination, mass_shift_tandem_mass=mass_shift.tandem_mass) + score = self._calculate_score(glycan_match) + return score, glycan_match + + def o_glycan_coarse_score(self, scan: ProcessedScan, + glycan_combination: GlycanCombinationRecord, + mass_shift: MassShift = Unmodified, + peptide_mass: Optional[float] = None) -> Tuple[float, CoarseGlycanMatch]: + '''Calculates a ranking score from O-glycopeptide stub-glycopeptide fragments. + + This method is derived from the technique used in pGlyco2 [1]. + + References + ---------- + [1] Liu, M.-Q., Zeng, W.-F., Fang, P., Cao, W.-Q., Liu, C., Yan, G.-Q., … Yang, P.-Y. (2017). + pGlyco 2.0 enables precision N-glycoproteomics with comprehensive quality control and + one-step mass spectrometry for intact glycopeptide identification. Nature Communications, + 8(1), 438. https://doi.org/10.1038/s41467-017-00535-2 + ''' + if peptide_mass is None: + peptide_mass = ( + scan.precursor_information.neutral_mass - glycan_combination.dehydrated_mass + ) - mass_shift.mass + if peptide_mass < 0: + return -1e6, None + glycan_match = self._o_glycan_match_stubs( + scan, peptide_mass, glycan_combination, mass_shift_tandem_mass=mass_shift.tandem_mass) + score = self._calculate_score(glycan_match) + return score, glycan_match + + def gag_coarse_score(self, scan: ProcessedScan, + glycan_combination: GlycanCombinationRecord, + mass_shift: MassShift = Unmodified, + peptide_mass: Optional[float] = None) -> Tuple[float, CoarseGlycanMatch]: + '''Calculates a ranking score from GAG linker glycopeptide stub-glycopeptide fragments. + + This method is derived from the technique used in pGlyco2 [1]. + + References + ---------- + [1] Liu, M.-Q., Zeng, W.-F., Fang, P., Cao, W.-Q., Liu, C., Yan, G.-Q., … Yang, P.-Y. (2017). + pGlyco 2.0 enables precision N-glycoproteomics with comprehensive quality control and + one-step mass spectrometry for intact glycopeptide identification. Nature Communications, + 8(1), 438. https://doi.org/10.1038/s41467-017-00535-2 + ''' + if peptide_mass is None: + peptide_mass = ( + scan.precursor_information.neutral_mass - glycan_combination.dehydrated_mass + ) - mass_shift.mass + if peptide_mass < 0: + return -1e6, None + glycan_match = self._gag_match_stubs( + scan, peptide_mass, glycan_combination, mass_shift_tandem_mass=mass_shift.tandem_mass) + score = self._calculate_score(glycan_match) + return score, glycan_match + + def match(self, scan, mass_shift=Unmodified, query_mass=None) -> List[GlycanMatchResult]: + output = [] + if query_mass is None: + intact_mass = scan.precursor_information.neutral_mass + else: + intact_mass = query_mass + threshold_mass = (intact_mass + 1) - self.minimum_peptide_mass + for glycan_combination in self.glycan_combination_db: + # Stop searching when the peptide mass would be below the minimum peptide mass + if threshold_mass < glycan_combination.dehydrated_mass: + break + peptide_mass = ( + intact_mass - glycan_combination.dehydrated_mass + ) - mass_shift.mass + best_score = 0 + best_match = None + type_to_score = {} + if glycan_combination.is_n_glycan(): + score, match = self.n_glycan_coarse_score( + scan, glycan_combination, mass_shift=mass_shift, peptide_mass=peptide_mass) + type_to_score[GlycanTypes.n_glycan] = (score, match) + if score > best_score: + best_score = score + best_match = match + if glycan_combination.is_o_glycan(): + score, match = self.o_glycan_coarse_score( + scan, glycan_combination, mass_shift=mass_shift, peptide_mass=peptide_mass) + type_to_score[GlycanTypes.o_glycan] = (score, match) + if score > best_score: + best_score = score + best_match = match + if glycan_combination.is_gag_linker(): + score, match = self.gag_coarse_score( + scan, glycan_combination, mass_shift=mass_shift, peptide_mass=peptide_mass) + type_to_score[GlycanTypes.gag_linker] = (score, match) + if score > best_score: + best_score = score + best_match = match + + if best_match is not None: + recalibrated_peptide_mass = best_match.estimate_peptide_mass() + if recalibrated_peptide_mass > 0: + if abs(recalibrated_peptide_mass - peptide_mass) > 0.5: + warnings.warn(""Re-estimated peptide mass error is large: %f vs %f"" % ( + peptide_mass, recalibrated_peptide_mass)) + else: + recalibrated_peptide_mass = 0 + result = GlycanMatchResult( + peptide_mass, + best_score, best_match, glycan_combination.size, type_to_score, recalibrated_peptide_mass) + output.append(result) + output = sorted(output, key=lambda x: x.score, reverse=1) + return output + + +class IntervalFilter(Sequence): + def __init__(self, intervals): + self.intervals = intervals + + def test(self, mass): + for i in self.intervals: + if mass in i: + return True + return False + + def __getitem__(self, i): + return self.intervals[i] + + def __len__(self): + return len(self.intervals) + + def __call__(self, mass): + return self.test(mass) + + def compress(self): + if len(self) == 0: + return self + out = [] + last = self[0] + for interval in self[1:]: + if interval.overlaps(last): + last.extend(interval) + else: + out.append(last) + last = interval + out.append(last) + self.intervals = out + return self + + +try: + has_c = True + _IntervalFilter = IntervalFilter + _CoarseStubGlycopeptideFragment = CoarseStubGlycopeptideFragment + _CoarseGlycanMatch = CoarseGlycanMatch + from glycresoft._c.structure.intervals import IntervalFilter + from glycresoft._c.tandem.core_search import ( + CoarseStubGlycopeptideFragment, CoarseGlycanMatch, GlycanMatchResult, + GlycanFilteringPeptideMassEstimator_match) + + GlycanFilteringPeptideMassEstimator.match = GlycanFilteringPeptideMassEstimator_match +except ImportError: + has_c = False + + +class IndexGlycanCompositionFragment(GlycanCompositionFragment): + __slots__ = ('index', 'name') + + index: int + name: str + + def __init__(self, mass, composition, key, is_extended=False): + self.mass = mass + self.composition = composition + self.key = key + self.is_extended = is_extended + self._hash_key = -1 + self.index = -1 + self.name = None + + def __reduce__(self): + return self.__class__, (self.mass, self.composition, self.key, self.is_extended), self.__getstate__() + + def __getstate__(self): + return { + ""index"": self.index, + ""name"": self.name, + ""_hash_key"": self._hash_key + } + + def __setstate__(self, state): + self.index = state['index'] + self.name = state['name'] + self._hash_key = state['_hash_key'] + + +class ComplementFragment(object): + __slots__ = ('mass', 'keys') + + mass: float + keys: List[Tuple[IndexGlycanCompositionFragment, int, Any]] + + def __init__(self, mass, keys=None): + self.mass = mass + self.keys = keys or [] + + def __repr__(self): + return ""{self.__class__.__name__}({self.mass})"".format(self=self) + + +GlycanTypes_n_glycan = GlycanTypes.n_glycan +GlycanTypes_o_glycan = GlycanTypes.o_glycan +GlycanTypes_gag_linker = GlycanTypes.gag_linker + + +class PartialGlycanSolution(object): + __slots__ = (""peptide_mass"", ""score"", ""core_matches"", ""fragment_matches"", ""glycan_index"") + + peptide_mass: float + score: float + core_matches: Set[int] + fragment_matches: Set[int] + glycan_index: int + + def __init__(self, peptide_mass=-1, score=0, core_matches=None, fragment_matches=None, glycan_index=-1): + if core_matches is None: + core_matches = set() + if fragment_matches is None: + fragment_matches = set() + self.peptide_mass = peptide_mass + self.score = score + self.core_matches = core_matches + self.fragment_matches = fragment_matches + self.glycan_index = glycan_index + + def __repr__(self): + template = (""{self.__class__.__name__}({self.peptide_mass}, {self.score}, "" + ""{self.core_matches}, {self.fragment_matches}, {self.glycan_index})"") + return template.format(self=self) + + @property + def fragment_match_count(self): + return len(self.fragment_matches) + + +class GlycanFragmentIndex(object): + '''A fast and sparse in-memory fragment ion index for quickly matching peaks against multiple + glycan composition complements. + + Based upon the complement ion indexing strategy described in [1]_. + + Attributes + ---------- + members : :class:`list` of :class:`GlycanCombinationRecord` + The glycan composition combinations in this index. + unique_fragments : :class:`dict`[:class:`str`, :class:`dict`[:class:`str`, :class:`IndexGlycanCompositionFragment`]] + An internment table for each glycosylation type mapping fragment name to glycan composition fragments + fragment_index : :class:`dict`[:class:`int`, :class:`list`[:class:`ComplementFragment`]] + A sparse index mapping :attr:`resolution` scaled masses to bins. The mass values and binned + fragments are complements of true fragments. + counter : int + A counter to assign each unique fragment a unique integer index. + fragment_weight : float + A scoring parameter to weight overall coverage with. + core_weight : float + A scoring parameter to weight core motif coverage with. + resolution : float + A scaling factor to convert real masses into truncated bin indices. + + + References + ---------- + ..[1] Zeng, W., Cao, W., Liu, M., He, S., & Yang, P. (2021). Precise, Fast and + Comprehensive Analysis of Intact Glycopeptides and Monosaccharide-Modifications with pGlyco3. + Bioarxiv. https://doi.org/https://doi.org/10.1101/2021.02.06.430063 + ''' + + members: List[GlycanCombinationRecord] + unique_fragments: DefaultDict[str, Dict[str, IndexGlycanCompositionFragment]] + fragment_index: DefaultDict[int, List[ComplementFragment]] + counter: int + + core_weight: float + fragment_weight: float + + resolution: float + lower_bound: float + upper_bound: float + + + def __init__(self, members=None, fragment_weight=0.56, core_weight=0.42, resolution=100): + self.members = members or [] + self.unique_fragments = defaultdict(dict) + self._fragments = [] + self.fragment_index = defaultdict(list) + self.counter = 0 + self.fragment_weight = fragment_weight + self.core_weight = core_weight + self.lower_bound = float('inf') + self.upper_bound = 0 + self.resolution = resolution + + def _intern(self, fragment: StubFragment, glycosylation_type: str) -> IndexGlycanCompositionFragment: + key = str(HashableGlycanComposition(fragment.key)) + try: + return self.unique_fragments[glycosylation_type][key] + except KeyError: + fragment = IndexGlycanCompositionFragment( + fragment.mass, None, fragment.key, not fragment.is_core) + self.unique_fragments[glycosylation_type][key] = fragment + fragment.name = key + fragment.index = self.counter + self._fragments.append(fragment) + self.counter += 1 + return fragment + + def _get_fragments(self, gcr: GlycanCombinationRecord, glycosylation_type: str) -> List[StubFragment]: + if glycosylation_type == GlycanTypes_n_glycan: + return gcr.get_n_glycan_fragments() + elif glycosylation_type == GlycanTypes_o_glycan: + return gcr.get_o_glycan_fragments() + elif glycosylation_type == GlycanTypes_gag_linker: + return gcr.get_gag_linker_glycan_fragments() + else: + raise ValueError(glycosylation_type) + + def build(self): + self.members.sort(key=lambda x: (x.dehydrated_mass, x.id)) + self.fragment_index.clear() + j = 0 + low = float('inf') + high = 0 + for i, member in enumerate(self.members): + mass = member.dehydrated_mass + n_core = 0 + n_frags = 0 + for glycosylation_type in member.glycan_types: + for frag in self._get_fragments(member, glycosylation_type): + frag = self._intern(frag, glycosylation_type) + if not frag.is_extended: + n_core += 1 + n_frags += 1 + d = mass - frag.mass + if d < 0: + d = 0 + if high < d: + high = d + if low > d: + low = d + key = int(d * self.resolution) + for comp in self.fragment_index[key]: + if abs(comp.mass - d) <= 1e-3: + comp.keys.append((frag, i, glycosylation_type)) + break + else: + self.fragment_index[key].append(ComplementFragment(d, [(frag, i, glycosylation_type)])) + j += 1 + + member.fragment_set_properties[glycosylation_type] = (n_core, n_frags) + member.clear() + self.lower_bound = low + self.upper_bound = high + return j + + def _match_fragments(self, delta_mass: float, peak: DeconvolutedPeak, + error_tolerance: float, result: Dict[int, Dict[str, PartialGlycanSolution]]): + key = int(delta_mass * self.resolution) + width = int(peak.neutral_mass * error_tolerance * self.resolution) + 1 + for off in range(-width, width + 1): + for comp_frag in self.fragment_index[key + off]: + if abs(comp_frag.mass - delta_mass) / peak.neutral_mass <= error_tolerance: + for frag, i, glycosylation_type in comp_frag.keys: + sol = result[i][glycosylation_type] + sol.score += np.log10(peak.intensity) * ( + 1 - ((abs(delta_mass - comp_frag.mass) / peak.neutral_mass) / error_tolerance) ** 4) + if not frag.is_extended: + sol.core_matches.add(frag.index) + sol.fragment_matches.add(frag.index) + + def match(self, scan: ProcessedScan, error_tolerance: float=1e-5, + mass_shift: MassShift=Unmodified, query_mass: Optional[float]=None) -> List[PartialGlycanSolution]: + if query_mass is None: + precursor_mass: float = scan.precursor_information.neutral_mass + else: + precursor_mass = query_mass + + mass_shift_mass = mass_shift.mass + mass_shift_tandem_mass = mass_shift.tandem_mass + + result: DefaultDict[int, DefaultDict[str, PartialGlycanSolution]] = defaultdict( + lambda: defaultdict(PartialGlycanSolution)) + for peak in scan.deconvoluted_peak_set: + d = (precursor_mass - peak.neutral_mass - mass_shift_mass) + self._match_fragments(d, peak, error_tolerance, result) + if mass_shift_tandem_mass != 0: + d = (precursor_mass - peak.neutral_mass - mass_shift_mass + mass_shift_tandem_mass) + self._match_fragments(d, peak, error_tolerance, result) + + out = [] + for i, glycosylation_type_to_solutions in result.items(): + rec = self.members[i] + best_score = -float('inf') + best_solution = None + for glycosylation_type, sol in glycosylation_type_to_solutions.items(): + n_core, n_frag = rec.fragment_set_properties[glycosylation_type] + coverage = (len(sol.core_matches) * 1.0 / n_core) ** self.core_weight * ( + len(sol.fragment_matches) * 1.0 / n_frag) ** self.fragment_weight + sol.score *= coverage + sol.peptide_mass = precursor_mass - rec.dehydrated_mass - mass_shift_mass + sol.glycan_index = i + if best_score < sol.score and sol.peptide_mass > 0: + best_score = sol.score + best_solution = sol + if best_solution is not None: + out.append(sol) + + out.sort(key=lambda x: x.score, reverse=True) + return out + + +try: + _GlycanFragmentIndex = GlycanFragmentIndex + _IndexGlycanCompositionFragment = IndexGlycanCompositionFragment + _ComplementFragment = ComplementFragment + _PartialGlycanSolution = PartialGlycanSolution + from glycresoft._c.tandem.core_search import ( + GlycanFragmentIndex, + IndexGlycanCompositionFragment, ComplementFragment, PartialGlycanSolution) +except ImportError: + pass + + +class _adapt(object): + def __init__(self, *args, **kwargs): + pass + + +class IndexedGlycanFilteringPeptideMassEstimator(GlycanFilteringPeptideMassEstimatorBase[PartialGlycanSolution], + _adapt): + """""" + An inverted complement search index for quickly searching for estimating peptide backbone masses + and glycans to go with them. + + Examples + -------- + + .. code-block:: python + + from glycresoft.tandem.glycopeptide.core_search import ( + GlycanCombinationRecord, IndexedGlycanFilteringPeptideMassEstimator) + from glycresoft import serialize + + def make_glycan_index(db_path, glycan_hypothesis_id, product_error_tolerance: float=2e-5): + # Or any object that has a `session` attribute could be used instead of making one here + db_conn = serialize.DatabaseBoundOperation(db_path) + # This is the set of *all* glycan combinations for that hypothesis. + glycan_combinations = GlycanCombinationRecord.from_hypothesis(db_conn, glycan_hypothesis_id) + search_index = IndexedGlycanFilteringPeptideMassEstimator( + glycan_combinations, product_error_tolerance=product_error_tolerance) + return search_index + + db_path = ... # magically get a database path + scan = ... # magically get a `ProcessedScan` to demonstrate on + + search_index = make_glycan_index(db_path, 1) + peptide_backbone_mass_candidates = search_index.match(scan) + for rec in peptide_backbone_mass_candidates: + candidate_glycans = search_index.glycan_for_peptide_mass(scan, rec.peptide_mass) + print(rec, candidate_glycans) + """""" + product_error_tolerance: float + fragment_weight: float + core_weight: float + + def __init__(self, glycan_combination_db, product_error_tolerance=1e-5, + fragment_weight=0.56, core_weight=0.42, minimum_peptide_mass=500.0, + use_denovo_motif=False, components=None, + use_recalibrated_peptide_mass=False): + super(IndexedGlycanFilteringPeptideMassEstimator, self).__init__( + glycan_combination_db, product_error_tolerance, fragment_weight, core_weight, + minimum_peptide_mass, use_denovo_motif, components, use_recalibrated_peptide_mass) + self.product_error_tolerance = product_error_tolerance + self.fragment_weight = fragment_weight + self.core_weight = core_weight + self.index = GlycanFragmentIndex( + self.glycan_combination_db, fragment_weight=fragment_weight, core_weight=core_weight) + self.index.build() + + def match(self, scan: ProcessedScan, mass_shift: MassShift=Unmodified, + query_mass: Optional[float]=None) -> List[PartialGlycanSolution]: + return self.index.match( + scan, + error_tolerance=self.product_error_tolerance, + mass_shift=mass_shift, + query_mass=query_mass) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/__init__.py",".py","889","30","from .scoring import ( + BinomialSpectrumMatcher, TargetDecoyAnalyzer, + CoverageWeightedBinomialScorer, LogIntensityScorer) + +from .matcher import GlycopeptideMatcher + +from .glycopeptide_matcher import ( + GlycopeptideDatabaseSearchIdentifier, + ExclusiveGlycopeptideDatabaseSearchComparer, + GlycopeptideDatabaseSearchComparer) + + +from .dynamic_generation import ( + MultipartGlycopeptideIdentifier, PeptideDatabaseProxyLoader, + make_memory_database_proxy_resolver) + + +__all__ = [ + ""BinomialSpectrumMatcher"", ""TargetDecoyAnalyzer"", + ""CoverageWeightedBinomialScorer"", ""LogIntensityScorer"", + + ""GlycopeptideDatabaseSearchIdentifier"", + ""ExclusiveGlycopeptideDatabaseSearchComparer"", + ""GlycopeptideDatabaseSearchComparer"", + ""GlycopeptideMatcher"", + + ""MultipartGlycopeptideIdentifier"", ""PeptideDatabaseProxyLoader"", + ""make_memory_database_proxy_resolver"", +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/identified_structure.py",".py","12738","411","from collections import defaultdict + +from glycopeptidepy.structure.sequence import ( + _n_glycosylation, + _o_glycosylation, + _gag_linker_glycosylation) + +from glycopeptidepy.structure.glycan import ( + GlycosylationType) + +from ..identified_structure import IdentifiedStructure, extract_identified_structures as _extract_identified_structures + +from glycresoft.structure import FragmentCachingGlycopeptide, PeptideProteinRelation + + +class IdentifiedGlycopeptide(IdentifiedStructure): + structure: FragmentCachingGlycopeptide + protein_relation: PeptideProteinRelation + q_value: float + + def __init__(self, structure, spectrum_matches, chromatogram, shared_with=None): + super(IdentifiedGlycopeptide, self).__init__( + structure, spectrum_matches, chromatogram, shared_with) + self.q_value = min(s.q_value for s in self.spectrum_matches) + self.protein_relation = self.structure.protein_relation + + @property + def start_position(self): + return self.protein_relation.start_position + + @property + def end_position(self): + return self.protein_relation.end_position + + def is_multiply_glycosylated(self): + return self.structure.is_multiply_glycosylated() + + def __repr__(self): + return ""IdentifiedGlycopeptide(%s, %0.3f, %0.3f, %0.3e)"" % ( + self.structure, self.ms2_score, self.ms1_score, self.total_signal) + + def overlaps(self, other) -> bool: + return self.protein_relation.overlaps(other.protein_relation) + + def spans(self, position) -> bool: + return position in self.protein_relation + + @property + def localizations(self): + return self.best_spectrum_match.localizations + + +class AmbiguousGlycopeptideGroup(object): + def __init__(self, members=None): + if members is None: + members = [] + self.members = list(members) + + def ambiguous_with(self, glycopeptide): + for member in self: + if not member.is_distinct(glycopeptide): + return True + return False + + def add(self, glycopeptide): + self.members.append(glycopeptide) + + def __iter__(self): + return iter(self.members) + + def __len__(self): + return len(self.members) + + def __getitem__(self, i): + return self.members[i] + + def __repr__(self): + return ""{s.__class__.__name__}({size})"".format(s=self, size=len(self)) + + def __contains__(self, other): + return other in self.members + + @classmethod + def aggregate(cls, glycopeptides): + groups = [] + no_chromatogram = [] + for glycopeptide in glycopeptides: + if glycopeptide.chromatogram is None: + no_chromatogram.append(cls([glycopeptide])) + else: + for group in groups: + if group.ambiguous_with(glycopeptide): + group.add(glycopeptide) + break + else: + groups.append(cls([glycopeptide])) + return groups + no_chromatogram + + +core_type_map = { + GlycosylationType.n_linked: _n_glycosylation, + GlycosylationType.o_linked: _o_glycosylation, + GlycosylationType.glycosaminoglycan: _gag_linker_glycosylation +} + + +def indices_of_glycosylation(glycopeptide, glycosylation_type=GlycosylationType.n_linked): + i = 0 + out = [] + + core_type = core_type_map[glycosylation_type] + + for res, mods in glycopeptide: + if mods and core_type in mods: + out.append(i) + i += 1 + return out + + +def protein_indices_for_glycosites(glycopeptide, glycosylation_type=GlycosylationType.n_linked): + protein_relation = glycopeptide.protein_relation + return [ + site + protein_relation.start_position for site in + indices_of_glycosylation(glycopeptide, glycosylation_type) + ] + + +class GlycopeptideIndex(object): + def __init__(self, members=None): + if members is None: + members = [] + self.members = list(members) + + def append(self, member): + self.members.append(member) + + def extend(self, members): + self.members.extend(members) + + def __iter__(self): + return iter(self.members) + + def __getitem__(self, i): + return self.members[i] + + def __setitem__(self, i, v): + self.members[i] = v + + def __len__(self): + return len(self.members) + + def with_glycan_composition(self, composition): + return GlycopeptideIndex([member for member in self if member.glycan_composition == composition]) + + def __repr__(self): + return repr(self.members) + + def _repr_pretty_(self, p, cycle): + return p.pretty(self.members) + + +class SiteMap(object): + def __init__(self, store=None): + if store is None: + store = defaultdict(GlycopeptideIndex) + self.store = store + + def __getitem__(self, key): + return self.store[key] + + def __setitem__(self, key, value): + self.store[key] = value + + @property + def sites(self): + return sorted(self.store.keys()) + + def get(self, key, default=None): + return self.store.get(key, default) + + def __iter__(self): + return iter(self.store.items()) + + def items(self): + return self.store.items() + + def keys(self): + return sorted(self.store.keys()) + + def values(self): + return self.store.values() + + def __contains__(self, i): + return i in self.store + + def __len__(self): + return len(self.store) + + def __repr__(self): + return repr(self.store) + + def _repr_pretty_(self, p, cycle): + return p.pretty(self.store) + + def copy(self): + dup = self.__class__() + for key, values in self.items(): + dup[key].extend(values) + return dup + + def merge(self, other): + dup = self.copy() + for key, values in other.items(): + dup[key].extend(values) + return dup + + +class HeterogeneityMap(object): + def __init__(self): + self.store = defaultdict(lambda: defaultdict(float)) + + def __getitem__(self, key): + return self.store[key] + + def __setitem__(self, key, value): + self.store[key] = defaultdict(float, value) + + def __iter__(self): + return iter(self.store) + + def keys(self): + return self.store.keys() + + def values(self): + return self.store.values() + + def items(self): + return self.store.items() + + def get(self, key, default=None): + return self.store.get(key, default) + + def pop(self, key): + return self.store.pop(key) + + def copy(self): + dup = self.__class__() + for key, value in self.items(): + dup[key] = value.copy() + return dup + + def merge(self, other): + dup = self.copy() + for site_key, values in other.items(): + for gc_key, abund in values.items(): + dup[site_key][gc_key] += abund + return dup + + +class IdentifiedGlycoprotein(object): + glycosylation_types = [ + GlycosylationType.n_linked, + GlycosylationType.o_linked, + GlycosylationType.glycosaminoglycan + ] + + def __init__(self, protein, identified_glycopeptides): + self.name = protein.name + try: + self.id = protein.id + except AttributeError: + self.id = self.name + self.protein_sequence = protein.protein_sequence + self.n_glycan_sequon_sites = protein.n_glycan_sequon_sites + self.o_glycan_sequon_sites = protein.o_glycan_sequon_sites + self.glycosaminoglycan_sequon_sites = protein.glycosaminoglycan_sequon_sites + self.identified_glycopeptides = identified_glycopeptides + self.ambiguous_groups = [ + a for a in AmbiguousGlycopeptideGroup.aggregate(identified_glycopeptides) + if len(a) > 1 + ] + self._site_map = defaultdict(SiteMap) + self.microheterogeneity_map = HeterogeneityMap() + for glycotype in self.glycosylation_types: + self._map_glycopeptides_to_glycosites(glycotype) + + def __len__(self): + return len(self.protein_sequence) + + def __eq__(self, other): + if self.name != other.name: + return False + elif self.protein_sequence != other.protein_sequence: + return False + elif self.identified_glycopeptides != other.identified_glycopeptides: + return False + return True + + def __ne__(self, other): + return not self == other + + def copy(self): + dup = self.__class__(self, self.identified_glycopeptides[:]) + return dup + + def merge(self, *other): + glycopeptides = list(self.identified_glycopeptides) + for o in other: + glycopeptides.extend(o.identified_glycopeptides) + dup = self.__class__(self, glycopeptides) + return dup + + @property + def glycosylation_sites(self): + return self.n_glycan_sequon_sites + + def glycosylation_sites_for(self, glycosylation_type, occupied=False): + sites = self._get_site_list_for(glycosylation_type) + if not occupied: + return sites + out = [] + for site in sites: + if site not in self.site_map[glycosylation_type]: + continue + out.append(site) + return out + + def _get_site_list_for(self, glycosylation_type): + if glycosylation_type == GlycosylationType.n_linked: + return self.n_glycan_sequon_sites + elif glycosylation_type == GlycosylationType.o_linked: + return self.o_glycan_sequon_sites + elif glycosylation_type == GlycosylationType.glycosaminoglycan: + return self.glycosaminoglycan_sequon_sites + else: + raise KeyError(""Glycosylation type %r not known"" % (glycosylation_type,)) + + def _aggregate_buckets(self, site_map, glycosylation_type=GlycosylationType.n_linked): + microheterogeneity_map = defaultdict(lambda: defaultdict(float)) + for site in self._get_site_list_for(glycosylation_type): + buckets = self._accumulate_glycan_composition_abundance_within_site(site, site_map) + microheterogeneity_map[site] = buckets + return microheterogeneity_map + + def _map_glycopeptides_to_glycosites(self, glycosylation_type=GlycosylationType.n_linked): + site_map = SiteMap() + for gp in self.identified_glycopeptides: + sites = set(protein_indices_for_glycosites(gp.structure, glycosylation_type)) + for site in self._get_site_list_for(glycosylation_type): + if site in sites: + site_map[site].append(gp) + sites.remove(site) + # Deal with left-overs + for site in sites: + site_map[site].append(gp) + + self._site_map[glycosylation_type] = site_map + self.microheterogeneity_map[glycosylation_type] = self._aggregate_buckets(site_map, glycosylation_type) + + def _accumulate_glycan_composition_abundance_within_site(self, site, site_map): + buckets = defaultdict(float) + if site not in site_map: + return buckets + for gp in site_map[site]: + buckets[str(gp.glycan_composition)] += gp.total_signal + return buckets + + def __repr__(self): + site_list = defaultdict(lambda: defaultdict(int)) + for key, site_map in self._site_map.items(): + for site, members in site_map.items(): + site_list[site][key] = len(members) + prefix_map = {} + for key in site_list: + prefix_map[key] = self.protein_sequence[key] + + string_form = [] + for site, observed in sorted(site_list.items()): + prefix = prefix_map[site] + components = [observed[k] for k in self._site_map] + if sum(components) == 0: + continue + string_form.append(""%d%s=(%s)"" % (site, prefix, ', '.join(map(str, components)))) + + return ""IdentifiedGlycoprotein(%s, %s)"" % ( + self.name, ""[%s]"" % ', '.join(string_form)) + + @property + def site_map(self): + return self._site_map + + @classmethod + def aggregate(cls, glycopeptides, index=None): + agg = defaultdict(list) + for gp in glycopeptides: + agg[gp.protein_relation.protein_id].append(gp) + + if index is None: + return agg + + out = [] + for protein_id, group in agg.items(): + out.append( + IdentifiedGlycoprotein(index[protein_id], group)) + return out + + +def extract_identified_structures(tandem_annotated_chromatograms, threshold_fn=lambda x: x.q_value < 0.05): + return _extract_identified_structures( + tandem_annotated_chromatograms, threshold_fn, result_type=IdentifiedGlycopeptide) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/glycopeptide_matcher.py",".py","17934","398","from multiprocessing import Manager as IPCManager + +from glycresoft.chromatogram_tree.chromatogram import GlycopeptideChromatogram +from glycresoft.chromatogram_tree import Unmodified +from glycresoft.task import TaskBase + +from glycresoft.structure import ( + CachingGlycopeptideParser, + SequenceReversingCachingGlycopeptideParser) + + +from ..target_decoy import GroupwiseTargetDecoyAnalyzer, TargetDecoySet +from .core_search import GlycanCombinationRecord, GlycanFilteringPeptideMassEstimator + +from ..temp_store import TempFileManager, SpectrumMatchStore +from ..chromatogram_mapping import ChromatogramMSMSMapper +from ..workflow import (format_identification_batch, chunkiter, SearchEngineBase) + +from ..oxonium_ions import OxoniumFilterReport, OxoniumFilterState + +from .matcher import ( + TargetDecoyInterleavingGlycopeptideMatcher, + ComparisonGlycopeptideMatcher) + + +class GlycopeptideResolver(object): + def __init__(self, database, parser=None): + if parser is None: + parser = CachingGlycopeptideParser() + self.database = database + self.parser = parser + self.cache = dict() + + def resolve(self, id): + try: + return self.cache[id] + except KeyError: + record = self.database.get_record(id) + structure = self.parser(record) + self.cache[id] = structure + return structure + + def __call__(self, id): + return self.resolve(id) + + +class GlycopeptideDatabaseSearchIdentifier(SearchEngineBase): + def __init__(self, tandem_scans, scorer_type, structure_database, scan_id_to_rt=lambda x: x, + minimum_oxonium_ratio=0.05, scan_transformer=lambda x: x, mass_shifts=None, + n_processes=5, file_manager=None, use_peptide_mass_filter=True, + probing_range_for_missing_precursors=3, trust_precursor_fits=True, + permute_decoy_glycans=False): + if file_manager is None: + file_manager = TempFileManager() + elif isinstance(file_manager, str): + file_manager = TempFileManager(file_manager) + if mass_shifts is None: + mass_shifts = [] + if Unmodified not in mass_shifts: + mass_shifts = [Unmodified] + mass_shifts + self.tandem_scans = sorted( + tandem_scans, key=lambda x: x.precursor_information.extracted_neutral_mass, reverse=True) + self.scorer_type = scorer_type + self.structure_database = structure_database + self.scan_id_to_rt = scan_id_to_rt + self.minimum_oxonium_ratio = minimum_oxonium_ratio + self.mass_shifts = mass_shifts + self.permute_decoy_glycans = permute_decoy_glycans + + self.probing_range_for_missing_precursors = probing_range_for_missing_precursors + self.trust_precursor_fits = trust_precursor_fits + + self.use_peptide_mass_filter = use_peptide_mass_filter + self._peptide_mass_filter = None + + self.scan_transformer = scan_transformer + + self.n_processes = n_processes + self.ipc_manager = IPCManager() + + self.file_manager = file_manager + self.spectrum_match_store = SpectrumMatchStore(self.file_manager) + + def _make_evaluator(self, bunch): + evaluator = TargetDecoyInterleavingGlycopeptideMatcher( + bunch, self.scorer_type, self.structure_database, + minimum_oxonium_ratio=self.minimum_oxonium_ratio, + n_processes=self.n_processes, + ipc_manager=self.ipc_manager, + mass_shifts=self.mass_shifts, + peptide_mass_filter=self._peptide_mass_filter, + probing_range_for_missing_precursors=self.probing_range_for_missing_precursors, + trust_precursor_fits=self.trust_precursor_fits, + permute_decoy_glycans=self.permute_decoy_glycans) + return evaluator + + def prepare_scan_set(self, scan_set): + if hasattr(scan_set[0], 'convert'): + out = [] + # Account for cases where the scan may be mentioned in the index, but + # not actually present in the MS data + for o in scan_set: + try: + scan = (self.scorer_type.load_peaks(o)) + if len(scan.deconvoluted_peak_set) > 0: + out.append(scan) + except KeyError: + self.log(""Missing Scan: %s"" % (o.id,)) + scan_set = out + out = [] + unconfirmed_precursors = [] + for scan in scan_set: + try: + scan.deconvoluted_peak_set = self.scan_transformer( + scan.deconvoluted_peak_set) + if len(scan.deconvoluted_peak_set) > 0: + if scan.precursor_information.defaulted: + unconfirmed_precursors.append(scan) + else: + out.append(scan) + except AttributeError: + self.log(""Missing Scan: %s"" % (scan.id,)) + continue + return out, unconfirmed_precursors + + def _make_peptide_mass_filter(self, error_tolerance=1e-5): + hypothesis_id = self.structure_database.hypothesis_id + glycan_combination_list = GlycanCombinationRecord.from_hypothesis( + self.structure_database.session, hypothesis_id) + if len(glycan_combination_list) == 0: + self.log(""No glycan combinations were found"") + raise ValueError(""No glycan combinations were found"") + peptide_filter = GlycanFilteringPeptideMassEstimator( + glycan_combination_list, product_error_tolerance=error_tolerance) + return peptide_filter + + def format_work_batch(self, bunch, count, total): + ratio = ""%d/%d (%0.3f%%)"" % (count, total, (count * 100. / total)) + info = bunch[0].precursor_information + try: + try: + precursor = info.precursor + if hasattr(precursor, ""scan_id""): + name = precursor.scan_id + else: + name = precursor.id + except (KeyError, AttributeError): + if hasattr(bunch[0], ""scan_id""): + name = bunch[0].scan_id + else: + name = bunch[0].id + except Exception: + name = """" + + if isinstance(info.charge, (int, float)): + batch_header = ""%s: %f (%s%r)"" % ( + name, info.neutral_mass, ""+"" if info.charge > 0 else ""-"", abs( + info.charge)) + else: + batch_header = ""%s: %f (%s)"" % ( + name, info.neutral_mass, ""?"") + return ""Begin Batch"", batch_header, ratio + + def search(self, precursor_error_tolerance=1e-5, simplify=True, batch_size=500, *args, **kwargs): + target_hits = self.spectrum_match_store.writer(""targets"") + decoy_hits = self.spectrum_match_store.writer(""decoys"") + + total = len(self.tandem_scans) + count = 0 + + if self.use_peptide_mass_filter: + self._peptide_mass_filter = self._make_peptide_mass_filter( + kwargs.get(""error_tolerance"", 1e-5)) + oxonium_report = OxoniumFilterReport() + self.log(""Writing Matches To %r"" % (self.file_manager,)) + for scan_collection in chunkiter(self.tandem_scans, batch_size): + count += len(scan_collection) + for item in self.format_work_batch(scan_collection, count, total): + self.log(""... %s"" % item) + scan_collection, unconfirmed_precursors = self.prepare_scan_set(scan_collection) + self.log(""... %d Unconfirmed Precursor Spectra"" % (len(unconfirmed_precursors,))) + self.log(""... Spectra Extracted"") + # TODO: handle unconfirmed_precursors differently here? + evaluator = self._make_evaluator(scan_collection + unconfirmed_precursors) + t, d = evaluator.score_all( + precursor_error_tolerance=precursor_error_tolerance, + simplify=simplify, *args, **kwargs) + self.log(""... Spectra Searched"") + target_hits.extend(o for o in t if o.score > 0.5) + decoy_hits.extend(o for o in d if o.score > 0.5) + t = sorted(t, key=lambda x: x.score, reverse=True) + self.log(""...... Total Matches So Far: %d Targets, %d Decoys\n%s"" % ( + len(target_hits), len(decoy_hits), format_identification_batch(t, 10))) + + # clear these lists as they may be quite large and we don't need them around for the + # next iteration + t = [] + d = [] + oxonium_report.extend(evaluator.oxonium_ion_report) + + self.log('Search Done') + target_hits.close() + decoy_hits.close() + self._clear_database_cache() + + self.log(""Reloading Spectrum Matches"") + target_hits, decoy_hits = self._load_stored_matches(len(target_hits), len(decoy_hits)) + return TargetDecoySet(target_hits, decoy_hits) + + def _clear_database_cache(self): + self.structure_database.clear_cache() + + def _load_stored_matches(self, target_count, decoy_count): + target_resolver = GlycopeptideResolver(self.structure_database, CachingGlycopeptideParser(int(1e6))) + decoy_resolver = GlycopeptideResolver(self.structure_database, SequenceReversingCachingGlycopeptideParser(int(1e6))) + + loaded_target_hits = [] + for i, solset in enumerate(self.spectrum_match_store.reader(""targets"", target_resolver)): + if i % 5000 == 0: + self.log(""Loaded %d/%d Targets (%0.3g%%)"" % (i, target_count, (100. * i / target_count))) + loaded_target_hits.append(solset) + loaded_decoy_hits = [] + for i, solset in enumerate(self.spectrum_match_store.reader(""decoys"", decoy_resolver)): + if i % 5000 == 0: + self.log(""Loaded %d/%d Decoys (%0.3g%%)"" % (i, decoy_count, (100. * i / decoy_count))) + loaded_decoy_hits.append(solset) + return TargetDecoySet(loaded_target_hits, loaded_decoy_hits) + + def estimate_fdr(self, target_hits, decoy_hits, with_pit=False, *args, **kwargs): + self.log(""Running Target Decoy Analysis with %d targets and %d decoys"" % ( + len(target_hits), len(decoy_hits))) + + def over_10_aa(x): + return len(x.target) >= 10 + + def under_10_aa(x): + return len(x.target) < 10 + + grouping_fns = [over_10_aa, under_10_aa] + + tda = GroupwiseTargetDecoyAnalyzer( + [x.best_solution() for x in target_hits], + [x.best_solution() for x in decoy_hits], *args, with_pit=with_pit, + grouping_functions=grouping_fns, + grouping_labels=[""Long Peptide"", ""Short Peptide""], + **kwargs) + tda.q_values() + for sol in target_hits: + for hit in sol: + tda.score(hit) + sol.q_value = sol.best_solution().q_value + for sol in decoy_hits: + for hit in sol: + tda.score(hit) + sol.q_value = sol.best_solution().q_value + return tda + + def map_to_chromatograms(self, chromatograms, tandem_identifications, + precursor_error_tolerance=1e-5, threshold_fn=lambda x: x.q_value < 0.05, + entity_chromatogram_type=GlycopeptideChromatogram): + self.log(""Mapping MS/MS Identifications onto Chromatograms"") + self.log(""%d Chromatograms"" % len(chromatograms)) + # if len(chromatograms) == 0: + # self.log(""No Chromatograms Extracted!"") + # return chromatograms, tandem_identifications + mapper = ChromatogramMSMSMapper( + chromatograms, precursor_error_tolerance, self.scan_id_to_rt) + self.log(""Assigning Solutions"") + mapper.assign_solutions_to_chromatograms(tandem_identifications) + self.log(""Distributing Orphan Spectrum Matches"") + mapper.distribute_orphans(threshold_fn=threshold_fn) + self.log(""Selecting Most Representative Matches"") + mapper.assign_entities(threshold_fn, entity_chromatogram_type=entity_chromatogram_type) + return mapper.chromatograms, mapper.orphans + + +class GlycopeptideDatabaseSearchComparer(GlycopeptideDatabaseSearchIdentifier): + def __init__(self, tandem_scans, scorer_type, target_database, decoy_database, scan_id_to_rt=lambda x: x, + minimum_oxonium_ratio=0.05, scan_transformer=lambda x: x, mass_shifts=None, + n_processes=5, file_manager=None, use_peptide_mass_filter=True, + probing_range_for_missing_precursors=3, trust_precursor_fits=True, + permute_decoy_glycans=False): + self.target_database = target_database + self.decoy_database = decoy_database + super(GlycopeptideDatabaseSearchComparer, self).__init__( + tandem_scans, scorer_type, self.target_database, scan_id_to_rt, + minimum_oxonium_ratio, scan_transformer, mass_shifts, n_processes, + file_manager, use_peptide_mass_filter, + probing_range_for_missing_precursors=probing_range_for_missing_precursors, + trust_precursor_fits=trust_precursor_fits, permute_decoy_glycans=permute_decoy_glycans) + + def _clear_database_cache(self): + self.target_database.clear_cache() + self.decoy_database.clear_cache() + + def _make_evaluator(self, bunch): + evaluator = ComparisonGlycopeptideMatcher( + bunch, self.scorer_type, + target_structure_database=self.target_database, + decoy_structure_database=self.decoy_database, + minimum_oxonium_ratio=self.minimum_oxonium_ratio, + n_processes=self.n_processes, + ipc_manager=self.ipc_manager, + mass_shifts=self.mass_shifts, + peptide_mass_filter=self._peptide_mass_filter, + probing_range_for_missing_precursors=self.probing_range_for_missing_precursors, + trust_precursor_fits=self.trust_precursor_fits, + permute_decoy_glycans=self.permute_decoy_glycans) + return evaluator + + def estimate_fdr(self, target_hits, decoy_hits, with_pit=False, *args, **kwargs): + self.log(""Running Target Decoy Analysis with %d targets and %d decoys"" % ( + len(target_hits), len(decoy_hits))) + + database_ratio = float(len(self.target_database)) / len(self.decoy_database) + + def over_10_aa(x): + return len(x.target) >= 10 + + def under_10_aa(x): + return len(x.target) < 10 + + grouping_fns = [over_10_aa, under_10_aa] + + tda = GroupwiseTargetDecoyAnalyzer( + [x.best_solution() for x in target_hits], + [x.best_solution() for x in decoy_hits], *args, with_pit=with_pit, + database_ratio=database_ratio, grouping_functions=grouping_fns, + grouping_labels=[""Long Peptide"", ""Short Peptide""], + **kwargs) + + tda.q_values() + for sol in target_hits: + for hit in sol: + tda.score(hit) + sol.q_value = sol.best_solution().q_value + for sol in decoy_hits: + for hit in sol: + tda.score(hit) + sol.q_value = sol.best_solution().q_value + return tda + + def _load_stored_matches(self, target_count, decoy_count): + target_resolver = GlycopeptideResolver(self.target_database, CachingGlycopeptideParser(int(1e6))) + decoy_resolver = GlycopeptideResolver(self.decoy_database, CachingGlycopeptideParser(int(1e6))) + + loaded_target_hits = [] + for i, solset in enumerate(self.spectrum_match_store.reader(""targets"", target_resolver)): + if i % 5000 == 0: + self.log(""Loaded %d/%d Targets (%0.3g%%)"" % (i, target_count, (100. * i / target_count))) + loaded_target_hits.append(solset) + loaded_decoy_hits = [] + for i, solset in enumerate(self.spectrum_match_store.reader(""decoys"", decoy_resolver)): + if i % 5000 == 0: + self.log(""Loaded %d/%d Decoys (%0.3g%%)"" % (i, decoy_count, (100. * i / decoy_count))) + loaded_decoy_hits.append(solset) + return TargetDecoySet(loaded_target_hits, loaded_decoy_hits) + + +class ExclusiveGlycopeptideDatabaseSearchComparer(GlycopeptideDatabaseSearchComparer): + def estimate_fdr(self, target_hits, decoy_hits, with_pit=False, *args, **kwargs): + accepted_targets, accepted_decoys = self._find_best_match_for_each_scan(target_hits, decoy_hits) + tda = super(ExclusiveGlycopeptideDatabaseSearchComparer, self).estimate_fdr( + accepted_targets, accepted_decoys, with_pit=with_pit, *args, **kwargs) + for sol in target_hits: + for hit in sol: + tda.score(hit) + sol.q_value = sol.best_solution().q_value + for sol in decoy_hits: + for hit in sol: + tda.score(hit) + sol.q_value = sol.best_solution().q_value + return tda + + def _find_best_match_for_each_scan(self, target_hits, decoy_hits): + winning_targets = [] + winning_decoys = [] + + target_map = {t.scan.id: t for t in target_hits} + decoy_map = {t.scan.id: t for t in decoy_hits} + scan_ids = set(target_map) | set(decoy_map) + for scan_id in scan_ids: + target_sol = target_map.get(scan_id) + decoy_sol = decoy_map.get(scan_id) + if target_sol is None: + winning_decoys.append(decoy_sol) + elif decoy_sol is None: + winning_targets.append(target_sol) + else: + if target_sol.score == decoy_sol.score: + winning_targets.append(target_sol) + winning_decoys.append(decoy_sol) + elif target_sol.score > decoy_sol.score: + winning_targets.append(target_sol) + else: + winning_decoys.append(decoy_sol) + return winning_targets, winning_decoys +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/matcher.py",".py","23954","511","import pickle +import threading + +from collections import OrderedDict +from queue import Queue as ThreadQueue + +from glycresoft.chromatogram_tree import Unmodified + +from glycresoft.structure import ( + CachingGlycopeptideParser, + SequenceReversingCachingGlycopeptideParser, + FragmentCachingGlycopeptide, + DecoyFragmentCachingGlycopeptide) +from glycresoft.structure.structure_loader import GlycanAwareGlycopeptideFragmentCachingContext, GlycopeptideFragmentCachingContext + +from ..spectrum_evaluation import TandemClusterEvaluatorBase, DEFAULT_WORKLOAD_MAX +from ..process_dispatcher import SpectrumIdentificationWorkerBase +from ..oxonium_ions import gscore_scanner, OxoniumFilterState, OxoniumFilterReport + + +class ParserClosure(object): + def __init__(self, parser_type, sequence_cls): + self.parser_type = parser_type + self.sequence_cls = sequence_cls + + def __call__(self): + return self.parser_type(sequence_cls=self.sequence_cls) + + +class GlycopeptideSpectrumGroupEvaluatorMixin(object): + __slots__ = () + + def create_evaluation_context(self, subgroup) -> GlycopeptideFragmentCachingContext: + return GlycanAwareGlycopeptideFragmentCachingContext() + + def construct_cache_subgroups(self, work_order): + record_by_id = {} + subgroups = [] + for key, order in work_order['work_orders'].items(): + record = order[0] + record_by_id[record.id] = record + structure = self.parser(record) + for group in subgroups: + # This works when the localized modification is a core (N-Glycosylation, O-Glycosylation), but + # will break down if there is a fully defined glycan (composition or structure). Those will need + # to be handled differently, especially considering ExD-type dissociation where they will actually + # matter. + if structure.modified_sequence_equality(group[0]): + group.append(structure) + break + else: + subgroups.append([structure]) + subgroups = [ + sorted([record_by_id[structure.id] + for structure in subgroup], + key=lambda x: x.id.structure_type) + if len(subgroup) > 1 else [record_by_id[structure.id] for structure in subgroup] + for subgroup in subgroups + ] + return subgroups + + +class GlycopeptideIdentificationWorker(GlycopeptideSpectrumGroupEvaluatorMixin, SpectrumIdentificationWorkerBase): + process_name = 'glycopeptide-identification-worker' + + def __init__(self, input_queue, output_queue, producer_done_event, consumer_done_event, + scorer_type, evaluation_args, spectrum_map, mass_shift_map, log_handler, + parser_type, solution_packer, cache_seeds=None): + if cache_seeds is None: + cache_seeds = {} + SpectrumIdentificationWorkerBase.__init__( + self, input_queue, output_queue, producer_done_event, consumer_done_event, + scorer_type, evaluation_args, spectrum_map, mass_shift_map, + log_handler=log_handler, solution_packer=solution_packer) + self.parser = parser_type() + self.cache_seeds = cache_seeds + + def evaluate(self, scan, structure, evaluation_context=None, *args, **kwargs): + target = self.parser(structure) + if evaluation_context is not None: + evaluation_context(target) + matcher = self.scorer_type.evaluate(scan, target, *args, **kwargs) + return matcher + + def before_task(self): + if self.cache_seeds is None: + return + cache_seeds = self.cache_seeds + if isinstance(cache_seeds, (str, bytes)): + cache_seeds = pickle.loads(cache_seeds) + + oxonium_cache_seed = cache_seeds.get('oxonium_ion_cache') + if oxonium_cache_seed is not None: + oxonium_cache_seed = pickle.loads(oxonium_cache_seed) + from glycresoft.structure.structure_loader import oxonium_ion_cache + oxonium_ion_cache.update(oxonium_cache_seed) + + +class PeptideMassFilteringDatabaseSearchMixin(object): + + def find_precursor_candidates(self, scan, error_tolerance=1e-5, probing_range=0, + mass_shift=None): + if mass_shift is None: + mass_shift = Unmodified + peptide_filter = None + hits = [] + intact_mass = scan.precursor_information.extracted_neutral_mass + for i in range(probing_range + 1): + query_mass = intact_mass - (i * self.neutron_offset) - mass_shift.mass + unfiltered_matches = self.search_database_for_precursors(query_mass, error_tolerance) + if self.peptide_mass_filter: + peptide_filter = self.peptide_mass_filter.build_peptide_filter( + scan, self.peptide_mass_filter.product_error_tolerance, mass_shift=mass_shift, + query_mass=intact_mass - (i * self.neutron_offset)) + hits.extend(map(self._mark_hit, [match for match in unfiltered_matches if peptide_filter( + match.peptide_mass)])) + else: + hits.extend(map(self._mark_hit, unfiltered_matches)) + return hits + + +class GlycopeptideMatcher(GlycopeptideSpectrumGroupEvaluatorMixin, PeptideMassFilteringDatabaseSearchMixin, TandemClusterEvaluatorBase): + def __init__(self, tandem_cluster, scorer_type, structure_database, parser_type=None, + n_processes=5, ipc_manager=None, probing_range_for_missing_precursors=3, + mass_shifts=None, batch_size=DEFAULT_WORKLOAD_MAX, peptide_mass_filter=None, + trust_precursor_fits=True, cache_seeds=None, sequence_type=None): + if parser_type is None: + parser_type = self._default_parser_type() + if sequence_type is None: + sequence_type = self._default_sequence_type() + super(GlycopeptideMatcher, self).__init__( + tandem_cluster, scorer_type, structure_database, verbose=False, n_processes=n_processes, + ipc_manager=ipc_manager, + probing_range_for_missing_precursors=probing_range_for_missing_precursors, + mass_shifts=mass_shifts, batch_size=batch_size, trust_precursor_fits=trust_precursor_fits) + self.peptide_mass_filter = peptide_mass_filter + self.parser_type = parser_type + self.sequence_type = sequence_type + self.parser = None + self.reset_parser() + self.cache_seeds = cache_seeds + + def _default_sequence_type(self): + return FragmentCachingGlycopeptide + + def _default_parser_type(self): + return CachingGlycopeptideParser + + def reset_parser(self): + self.parser = self.parser_type(sequence_cls=self.sequence_type) + + def evaluate(self, scan, structure, evaluation_context=None, *args, **kwargs): + target = self.parser(structure) + if evaluation_context is not None: + evaluation_context(target) + matcher = self.scorer_type.evaluate(scan, target, *args, **kwargs) + return matcher + + def _transform_matched_collection(self, solution_set_collection, cache=None, *args, **kwargs): + if cache is None: + cache = {} + for solution_set in solution_set_collection: + for sm in solution_set: + target = sm.target + if target.id in cache: + sm.target = cache[target.id] + else: + sm.target = cache[target.id] = self.parser(target) + return solution_set_collection + + @property + def _worker_specification(self): + return GlycopeptideIdentificationWorker, { + ""parser_type"": ParserClosure(self.parser_type, self.sequence_type), + ""cache_seeds"": self.cache_seeds + } + + +class SequenceReversingDecoyGlycopeptideMatcher(GlycopeptideMatcher): + def _default_parser_type(self): + return SequenceReversingCachingGlycopeptideParser + + +class GlycanFragmentPermutingDecoyGlycopeptideMatcher(GlycopeptideMatcher): + def _default_sequence_type(self): + return DecoyFragmentCachingGlycopeptide + + +class SequenceReversingGlycanFragmentPermutingGlycopeptideMatcher(GlycopeptideMatcher): + def _default_sequence_type(self): + return DecoyFragmentCachingGlycopeptide + + def _default_parser_type(self): + return SequenceReversingCachingGlycopeptideParser + + +class TargetDecoyInterleavingGlycopeptideMatcher(GlycopeptideSpectrumGroupEvaluatorMixin, + PeptideMassFilteringDatabaseSearchMixin, + TandemClusterEvaluatorBase): + '''Searches a single database against all spectra, where targets are + database matches, and decoys are the reverse of the individual target + glycopeptides. + + A spectrum has a best target match and a best decoy match tracked + separately. + + This means that targets and decoys share the same glycan composition and + peptide backbone mass, and ergo share stub glycopeptides. This may not produce + ""random"" enough decoy matches. + ''' + def __init__(self, tandem_cluster, scorer_type, structure_database, minimum_oxonium_ratio=0.05, + n_processes=5, ipc_manager=None, probing_range_for_missing_precursors=3, + mass_shifts=None, batch_size=DEFAULT_WORKLOAD_MAX, peptide_mass_filter=None, + trust_precursor_fits=True, cache_seeds=None, permute_decoy_glycans=False): + super(TargetDecoyInterleavingGlycopeptideMatcher, self).__init__( + tandem_cluster, scorer_type, structure_database, verbose=False, + n_processes=n_processes, ipc_manager=ipc_manager, + probing_range_for_missing_precursors=probing_range_for_missing_precursors, + mass_shifts=mass_shifts, batch_size=batch_size, + trust_precursor_fits=trust_precursor_fits) + self.tandem_cluster = tandem_cluster + self.scorer_type = scorer_type + self.structure_database = structure_database + self.minimum_oxonium_ratio = minimum_oxonium_ratio + self.peptide_mass_filter = peptide_mass_filter + self.permute_decoy_glycans = permute_decoy_glycans + self.target_evaluator = GlycopeptideMatcher( + [], self.scorer_type, self.structure_database, n_processes=n_processes, + ipc_manager=ipc_manager, + probing_range_for_missing_precursors=probing_range_for_missing_precursors, + mass_shifts=mass_shifts, peptide_mass_filter=peptide_mass_filter, + trust_precursor_fits=trust_precursor_fits, cache_seeds=cache_seeds) + + decoy_matcher_type = SequenceReversingDecoyGlycopeptideMatcher + if self.permute_decoy_glycans: + decoy_matcher_type = SequenceReversingGlycanFragmentPermutingGlycopeptideMatcher + + self.decoy_evaluator = decoy_matcher_type( + [], self.scorer_type, self.structure_database, n_processes=n_processes, + ipc_manager=ipc_manager, + probing_range_for_missing_precursors=probing_range_for_missing_precursors, + mass_shifts=mass_shifts, peptide_mass_filter=peptide_mass_filter, + trust_precursor_fits=trust_precursor_fits, cache_seeds=cache_seeds) + self.oxonium_ion_report = OxoniumFilterReport() + + def filter_for_oxonium_ions(self, error_tolerance=1e-5, **kwargs): + keep = [] + for scan in self.tandem_cluster: + minimum_mass = 0 + if scan.acquisition_information: + try: + scan_windows = scan.acquisition_information[0] + window = scan_windows[0] + minimum_mass = window.lower + except IndexError: + pass + try: + ratio = gscore_scanner( + peak_list=scan.deconvoluted_peak_set, error_tolerance=error_tolerance, + minimum_mass=minimum_mass) + except Exception: + self.error(""An error occurred while calculating the G-score for \""%s\"""" % scan.id) + ratio = 0 + self.oxonium_ion_report.append( + OxoniumFilterState( + scan.id, + ratio, + ratio >= self.minimum_oxonium_ratio, + frozenset() + ) + ) + scan.oxonium_score = ratio + if ratio >= self.minimum_oxonium_ratio: + keep.append(scan) + else: + self.debug(""... Skipping scan %s with G-score %f"" % (scan.id, ratio)) + self.tandem_cluster = keep + + def score_one(self, scan, precursor_error_tolerance=1e-5, *args, **kwargs): + target_result = self.target_evaluator.score_one(scan, precursor_error_tolerance, *args, **kwargs) + decoy_result = self.decoy_evaluator.score_one(scan, precursor_error_tolerance, *args, **kwargs) + return target_result, decoy_result + + def score_bunch(self, scans, precursor_error_tolerance=1e-5, simplify=True, *args, **kwargs): + # Map scans to target database + workload = self.target_evaluator._map_scans_to_hits( + scans, precursor_error_tolerance) + # Evaluate mapped target hits + target_solutions = [] + total_work = workload.total_work_required() + if total_work == 0: + total_work = 1 + running_total_work = 0 + for i, batch in enumerate(workload.batches(self.batch_size)): + self.log(""... Batch %d (%d/%d) %0.2f%%"" % ( + i + 1, running_total_work + batch.batch_size, total_work, + ((running_total_work + batch.batch_size) * 100.) / float(total_work))) + target_scan_solution_map = self.target_evaluator.evaluate_hit_groups( + batch, *args, **kwargs) + running_total_work += batch.batch_size + # Aggregate and reduce target solutions + temp = self.target_evaluator.collect_scan_solutions(target_scan_solution_map, batch.scan_map) + if simplify: + temp = [case for case in temp if len(case) > 0] + for case in temp: + try: + case.simplify() + case.select_top() + except IndexError: + self.log(""Failed to simplify %r"" % (case.scan.id,)) + raise + else: + temp = [case for case in temp if len(case) > 0] + target_solutions += temp + + # Reuse mapped hits from target database using the decoy evaluator + # since this assumes that the decoys will be direct reversals of + # target sequences. The decoy evaluator will handle the reversals. + decoy_solutions = [] + running_total_work = 0 + for i, batch in enumerate(workload.batches(self.batch_size)): + self.log(""... Batch %d (%d/%d) %0.2f%%"" % ( + i + 1, running_total_work + batch.batch_size, total_work, + ((running_total_work + batch.batch_size) * 100.) / float(total_work))) + + decoy_scan_solution_map = self.decoy_evaluator.evaluate_hit_groups( + batch, *args, **kwargs) + # Aggregate and reduce target solutions + temp = self.decoy_evaluator.collect_scan_solutions(decoy_scan_solution_map, batch.scan_map) + if simplify: + temp = [case for case in temp if len(case) > 0] + for case in temp: + try: + case.simplify() + case.select_top() + except IndexError: + self.log(""Failed to simplify %r"" % (case.scan.id,)) + raise + else: + temp = [case for case in temp if len(case) > 0] + decoy_solutions += temp + running_total_work += batch.batch_size + return target_solutions, decoy_solutions + + def score_all(self, precursor_error_tolerance=1e-5, simplify=False, *args, **kwargs): + target_out = [] + decoy_out = [] + + self.filter_for_oxonium_ions(**kwargs) + target_out, decoy_out = self.score_bunch( + self.tandem_cluster, precursor_error_tolerance, + simplify=simplify, *args, **kwargs) + if simplify: + for case in target_out: + case.simplify() + case.select_top() + for case in decoy_out: + case.simplify() + case.select_top() + target_out = [x for x in target_out if len(x) > 0] + decoy_out = [x for x in decoy_out if len(x) > 0] + return target_out, decoy_out + + +class CompetativeTargetDecoyInterleavingGlycopeptideMatcher(TargetDecoyInterleavingGlycopeptideMatcher): + '''A variation of :class:`TargetDecoyInterleavingGlycopeptideMatcher` where + a spectrum can have only one match which is either a target or a decoy. + ''' + def score_bunch(self, scans, precursor_error_tolerance=1e-5, simplify=True, *args, **kwargs): + target_solutions, decoy_solutions = super( + CompetativeTargetDecoyInterleavingGlycopeptideMatcher, self).score_bunch( + scans, precursor_error_tolerance, simplify, *args, **kwargs) + target_solutions = OrderedDict([(s.scan.id, s) for s in target_solutions]) + decoy_solutions = OrderedDict([(s.scan.id, s) for s in target_solutions]) + + remove_target = [] + for key in target_solutions: + try: + if target_solutions[key].score > decoy_solutions[key].score: + decoy_solutions.pop(key) + else: + remove_target.append(key) + except KeyError: + pass + for key in remove_target: + target_solutions.pop(key) + return list(target_solutions.values()), list(decoy_solutions.values()) + + +class ComparisonGlycopeptideMatcher(TargetDecoyInterleavingGlycopeptideMatcher): + '''A variation of :class:`TargetDecoyInterleavingGlycopeptideMatcher` where + targets and decoys are drawn from separate hypotheses, and decoys are taken + verbatim from their database without be reversed. + ''' + def __init__(self, tandem_cluster, scorer_type, target_structure_database, decoy_structure_database, + minimum_oxonium_ratio=0.05, n_processes=5, ipc_manager=None, + probing_range_for_missing_precursors=3, mass_shifts=None, + batch_size=DEFAULT_WORKLOAD_MAX, peptide_mass_filter=None, + trust_precursor_fits=True, cache_seeds=None, permute_decoy_glycans=False): + super(ComparisonGlycopeptideMatcher, self).__init__( + tandem_cluster, scorer_type, target_structure_database, + n_processes=n_processes, ipc_manager=ipc_manager, + probing_range_for_missing_precursors=probing_range_for_missing_precursors, + mass_shifts=mass_shifts, batch_size=batch_size, peptide_mass_filter=peptide_mass_filter, + trust_precursor_fits=trust_precursor_fits, cache_seeds=cache_seeds, + permute_decoy_glycans=permute_decoy_glycans) + + self.tandem_cluster = tandem_cluster + self.scorer_type = scorer_type + + self.target_structure_database = target_structure_database + self.decoy_structure_database = decoy_structure_database + + self.minimum_oxonium_ratio = minimum_oxonium_ratio + + self.target_evaluator = GlycopeptideMatcher( + [], self.scorer_type, self.target_structure_database, + n_processes=n_processes, ipc_manager=ipc_manager, + probing_range_for_missing_precursors=probing_range_for_missing_precursors, + mass_shifts=mass_shifts, peptide_mass_filter=peptide_mass_filter, + trust_precursor_fits=trust_precursor_fits) + + decoy_matcher_type = GlycopeptideMatcher + if self.permute_decoy_glycans: + decoy_matcher_type = GlycanFragmentPermutingDecoyGlycopeptideMatcher + self.decoy_evaluator = decoy_matcher_type( + [], self.scorer_type, self.decoy_structure_database, + n_processes=n_processes, ipc_manager=ipc_manager, + probing_range_for_missing_precursors=probing_range_for_missing_precursors, + mass_shifts=mass_shifts, peptide_mass_filter=peptide_mass_filter, + trust_precursor_fits=trust_precursor_fits) + + def score_bunch(self, scans, precursor_error_tolerance=1e-5, simplify=True, *args, **kwargs): + # Map scans to target database + self.log(""... Querying Targets"") + waiting_task_results = ThreadQueue() + + def decoy_query_task(): + self.log(""... Querying Decoys"") + workload = self.decoy_evaluator._map_scans_to_hits( + scans, precursor_error_tolerance) + waiting_task_results.put(workload) + + workload = self.target_evaluator._map_scans_to_hits( + scans, precursor_error_tolerance) + + # Execute the potentially disk-heavy task in the background while + # evaluating the target spectrum matches. + decoy_query_thread = threading.Thread(target=decoy_query_task) + decoy_query_thread.start() + + # Evaluate mapped target hits + target_solutions = [] + workload_graph = workload.compute_workloads() + total_work = workload.total_work_required(workload_graph) + running_total_work = 0 + + for i, batch in enumerate(workload.batches(self.batch_size)): + running_total_work += batch.batch_size + self.log(""... Batch %d (%d/%d) %0.2f%%"" % ( + i + 1, running_total_work, total_work, + (100. * running_total_work) / total_work)) + + target_scan_solution_map = self.target_evaluator.evaluate_hit_groups( + batch, *args, **kwargs) + # Aggregate and reduce target solutions + temp = self.target_evaluator.collect_scan_solutions( + target_scan_solution_map, batch.scan_map) + temp = [case for case in temp if len(case) > 0] + if simplify: + for case in temp: + try: + case.simplify() + case.select_top() + except IndexError: + self.log(""Failed to simplify %r"" % (case.scan.id,)) + raise + target_solutions.extend(temp) + + self.debug(""... Waiting For Decoy Mapping"") + decoy_query_thread.join() + # workload = self.decoy_evaluator._map_scans_to_hits( + # scans, precursor_error_tolerance) + workload = waiting_task_results.get() + # Evaluate mapped target hits + decoy_solutions = [] + workload_graph = workload.compute_workloads() + total_work = workload.total_work_required(workload_graph) + running_total_work = 0 + for i, batch in enumerate(workload.batches(self.batch_size)): + running_total_work += batch.batch_size + self.log(""... Batch %d (%d/%d) %0.2f%%"" % ( + i + 1, running_total_work, total_work, + (100. * running_total_work) / total_work)) + + decoy_scan_solution_map = self.decoy_evaluator.evaluate_hit_groups( + batch, *args, **kwargs) + # Aggregate and reduce decoy solutions + temp = self.decoy_evaluator.collect_scan_solutions(decoy_scan_solution_map, batch.scan_map) + temp = [case for case in temp if len(case) > 0] + if simplify: + for case in temp: + try: + case.simplify() + case.select_top() + except IndexError: + self.log(""Failed to simplify %r"" % (case.scan.id,)) + raise + decoy_solutions.extend(temp) + return target_solutions, decoy_solutions +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/scoring/precursor_mass_accuracy.py",".py","1494","58","import math +import numpy as np + + +sqrt2pi = np.sqrt(2 * np.pi) + + +def gauss(x, mu, sigma): + return np.exp(-((x - mu) ** 2) / (2 * sigma ** 2)) / (sigma * sqrt2pi) + + +class MassAccuracyModel(object): + + @classmethod + def fit(cls, matches): + obs = [x.best_solution().precursor_mass_accuracy() for x in matches if len(x) > 0] + mu = np.mean(obs) + sigma = np.std(obs) + return cls(mu, sigma) + + def __init__(self, mu, sigma, scale=1e6): + self.mu = mu + self.sigma = sigma + self.scale = scale + self.mu *= self.scale + self.sigma *= self.scale + + def _sample(self): + return self.score(self._interval(n_std=3)) + + def _interval(self, n_std=3): + w = self.sigma * n_std + return np.arange(self.mu - w, self.mu + w, 1) / self.scale + + def score(self, error): + return gauss(self.scale * error, self.mu, self.sigma) + + def __call__(self, error): + return self.score(error) + + def __repr__(self): + return ""MassAccuracyModel(%e, %e)"" % (self.mu / self.scale, self.sigma / self.scale) + + +class MassAccuracyMixin(object): + accuracy_bias = MassAccuracyModel(0, 5e-6) + + def _precursor_mass_accuracy_score(self): + offset, error = self.determine_precursor_offset(include_error=True) + mass_accuracy = -10 * math.log10(1 - self.accuracy_bias(error)) + return mass_accuracy + + +try: + from glycresoft._c.tandem.tandem_scoring_helpers import gauss +except ImportError: + pass +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/scoring/simple_score.py",".py","9347","212","import numpy as np + +from glycresoft.structure import FragmentMatchMap + +from glycresoft.tandem.glycopeptide.core_search import approximate_internal_size_of_glycan + +from .base import ( + GlycopeptideSpectrumMatcherBase, ChemicalShift, EXDFragmentationStrategy, + HCDFragmentationStrategy, IonSeries) + +from .glycan_signature_ions import GlycanCompositionSignatureMatcher + + +class SimpleCoverageScorer(GlycopeptideSpectrumMatcherBase): + backbone_weight = 0.5 + glycosylated_weight = 0.5 + stub_weight = 0.2 + + def __init__(self, scan, sequence, mass_shift=None): + super(SimpleCoverageScorer, self).__init__(scan, sequence, mass_shift) + self._score = None + self.solution_map = FragmentMatchMap() + self.glycosylated_n_term_ion_count = 0 + self.glycosylated_c_term_ion_count = 0 + + @property + def glycosylated_b_ion_count(self): + return self.glycosylated_n_term_ion_count + + @glycosylated_b_ion_count.setter + def glycosylated_b_ion_count(self, value): + self.glycosylated_n_term_ion_count = value + + @property + def glycosylated_y_ion_count(self): + return self.glycosylated_c_term_ion_count + + @glycosylated_y_ion_count.setter + def glycosylated_y_ion_count(self, value): + self.glycosylated_c_term_ion_count = value + + def _match_backbone_series(self, series, error_tolerance=2e-5, masked_peaks=None, strategy=None, + include_neutral_losses=False): + if strategy is None: + strategy = HCDFragmentationStrategy + # Assumes that fragmentation proceeds from the start of the ladder (series position 1) + # which means that if the last fragment could be glycosylated then the next one will be + # but if the last fragment wasn't the next one might be. + previous_position_glycosylated = False + for frags in self.get_fragments(series, strategy=strategy, include_neutral_losses=include_neutral_losses): + glycosylated_position = previous_position_glycosylated + for frag in frags: + if not glycosylated_position: + glycosylated_position |= frag.is_glycosylated + for peak in self.spectrum.all_peaks_for(frag.mass, error_tolerance): + if peak.index.neutral_mass in masked_peaks: + continue + self.solution_map.add(peak, frag) + if glycosylated_position: + if series.direction > 0: + self.glycosylated_n_term_ion_count += 1 + else: + self.glycosylated_c_term_ion_count += 1 + previous_position_glycosylated = glycosylated_position + + def _compute_coverage_vectors(self): + n_term_ions = np.zeros(len(self.target)) + c_term_ions = np.zeros(len(self.target)) + stub_count = 0 + glycosylated_n_term_ions = set() + glycosylated_c_term_ions = set() + + for frag in self.solution_map.fragments(): + series = frag.get_series() + if series in (IonSeries.b, IonSeries.c): + n_term_ions[frag.position] = 1 + if frag.is_glycosylated: + glycosylated_n_term_ions.add((series, frag.position)) + elif series in (IonSeries.y, IonSeries.z): + c_term_ions[frag.position] = 1 + if frag.is_glycosylated: + glycosylated_c_term_ions.add((series, frag.position)) + elif series == IonSeries.stub_glycopeptide: + stub_count += 1 + + n_term_ions[0] = 0 + return n_term_ions, c_term_ions, stub_count, len(glycosylated_n_term_ions), len(glycosylated_c_term_ions) + + def _compute_glycosylated_coverage(self, glycosylated_n_term_ions, glycosylated_c_term_ions): + ladders = 0. + numer = 0.0 + denom = 0.0 + if self.glycosylated_n_term_ion_count > 0: + numer += glycosylated_n_term_ions + denom += self.glycosylated_n_term_ion_count + ladders += 1. + if self.glycosylated_c_term_ion_count > 0: + numer += glycosylated_c_term_ions + denom += self.glycosylated_c_term_ion_count + ladders += 1. + if denom == 0.0: + return 0.0 + return numer / denom + + def _get_internal_size(self, glycan_composition): + return approximate_internal_size_of_glycan(glycan_composition) + + def compute_coverage(self): + (n_term_ions, c_term_ions, stub_count, + glycosylated_n_term_ions, + glycosylated_c_term_ions) = self._compute_coverage_vectors() + + mean_coverage = np.mean(np.log2(n_term_ions + c_term_ions[::-1] + 1) / np.log2(3)) + + glycosylated_coverage = self._compute_glycosylated_coverage( + glycosylated_n_term_ions, + glycosylated_c_term_ions) + + stub_fraction = min(stub_count, 3) / 3. + + return mean_coverage, glycosylated_coverage, stub_fraction + + @classmethod + def get_params(self, backbone_weight=None, glycosylated_weight=None, stub_weight=None, **kwargs): + if backbone_weight is None: + backbone_weight = self.backbone_weight + if glycosylated_weight is None: + glycosylated_weight = self.glycosylated_weight + if stub_weight is None: + stub_weight = self.stub_weight + return backbone_weight, glycosylated_weight, stub_weight, kwargs + + def calculate_score(self, backbone_weight=None, glycosylated_weight=None, stub_weight=None, **kwargs): + if backbone_weight is None: + backbone_weight = self.backbone_weight + if glycosylated_weight is None: + glycosylated_weight = self.glycosylated_weight + if stub_weight is None: + stub_weight = self.stub_weight + score = self._coverage_score(backbone_weight, glycosylated_weight, stub_weight) + self._score = score + return score + + def _coverage_score(self, backbone_weight=None, glycosylated_weight=None, stub_weight=None): + if backbone_weight is None: + backbone_weight = self.backbone_weight + if glycosylated_weight is None: + glycosylated_weight = self.glycosylated_weight + if stub_weight is None: + stub_weight = self.stub_weight + mean_coverage, glycosylated_coverage, stub_fraction = self.compute_coverage() + score = (((mean_coverage * backbone_weight) + (glycosylated_coverage * glycosylated_weight)) * ( + 1 - stub_weight)) + (stub_fraction * stub_weight) + return score + + +class SignatureAwareCoverageScorer(SimpleCoverageScorer, GlycanCompositionSignatureMatcher): + def __init__(self, scan, sequence, mass_shift=None, *args, **kwargs): + super(SignatureAwareCoverageScorer, self).__init__(scan, sequence, mass_shift, *args, **kwargs) + + def match(self, error_tolerance=2e-5, *args, **kwargs): + GlycanCompositionSignatureMatcher.match(self, error_tolerance=error_tolerance, **kwargs) + masked_peaks = set() + include_neutral_losses = kwargs.get(""include_neutral_losses"", False) + extended_glycan_search = kwargs.get(""extended_glycan_search"", False) + + if self.mass_shift.tandem_mass != 0: + chemical_shift = ChemicalShift( + self.mass_shift.name, self.mass_shift.tandem_composition) + else: + chemical_shift = None + + is_hcd = self.is_hcd() + is_exd = self.is_exd() + if not is_hcd and not is_exd: + is_hcd = True + # handle glycan fragments from collisional dissociation + if is_hcd: + self._match_oxonium_ions(error_tolerance, masked_peaks=masked_peaks) + self._match_stub_glycopeptides(error_tolerance, masked_peaks=masked_peaks, + chemical_shift=chemical_shift, + extended_glycan_search=extended_glycan_search) + # handle N-term + if is_hcd and not is_exd: + self._match_backbone_series( + IonSeries.b, error_tolerance, masked_peaks, HCDFragmentationStrategy, include_neutral_losses) + elif is_exd: + self._match_backbone_series( + IonSeries.b, error_tolerance, masked_peaks, EXDFragmentationStrategy, include_neutral_losses) + self._match_backbone_series( + IonSeries.c, error_tolerance, masked_peaks, EXDFragmentationStrategy, include_neutral_losses) + + # handle C-term + if is_hcd and not is_exd: + self._match_backbone_series( + IonSeries.y, error_tolerance, masked_peaks, HCDFragmentationStrategy, include_neutral_losses) + elif is_exd: + self._match_backbone_series( + IonSeries.y, error_tolerance, masked_peaks, EXDFragmentationStrategy, include_neutral_losses) + self._match_backbone_series( + IonSeries.z, error_tolerance, masked_peaks, EXDFragmentationStrategy, include_neutral_losses) + return self + + +try: + from glycresoft._c.tandem.tandem_scoring_helpers import ( + _compute_coverage_vectors, SimpleCoverageScorer_match_backbone_series) + SimpleCoverageScorer._compute_coverage_vectors = _compute_coverage_vectors + SimpleCoverageScorer._match_backbone_series = SimpleCoverageScorer_match_backbone_series +except ImportError: + pass +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/scoring/pair_amino_acids_scoring.py",".py","6196","163","from collections import Counter + +from itertools import chain +import math + +from .base import GlycopeptideSpectrumMatcherBase +from glycresoft.structure import FragmentMatchMap + +from glycopeptidepy.structure.fragment import IonSeries + + +def flatten(iterable): + return [a for b in iterable for a in b] + + +class FrequencyCounter(object): + def __init__(self): + self.observed_pairs = Counter() + self.observed_n_term = Counter() + self.observed_c_term = Counter() + self.observed_sequences = Counter() + + self.possible_pairs = Counter() + self.possible_n_term = Counter() + self.possible_c_term = Counter() + + self.series = tuple(""by"") + + def add_sequence(self, glycopeptide): + self.observed_sequences[glycopeptide] += 1 + + def add_fragment(self, fragment): + n_term, c_term = fragment.flanking_amino_acids + self.observed_pairs[n_term, c_term] += 1 + self.observed_n_term[n_term] += 1 + self.observed_c_term[c_term] += 1 + + def total_possible_outcomes(self): + possible_pairs = Counter() + possible_n_term = Counter() + possible_c_term = Counter() + for seq, count in self.observed_sequences.items(): + for series in self.series: + for fragment in flatten(seq.get_fragments(series)): + n_term, c_term = fragment.flanking_amino_acids + possible_pairs[n_term, c_term] += count + possible_n_term[n_term] += count + possible_c_term[c_term] += count + + self.possible_pairs = possible_pairs + self.possible_n_term = possible_n_term + self.possible_c_term = possible_c_term + + def process_match(self, spectrum_match): + for case in spectrum_match.solution_map: + if case.series == 'b' or case.series == 'y': + self.add_fragment(case) + self.add_sequence(spectrum_match.target) + + def n_term_probability(self, residue=None): + if residue is not None: + return self.observed_n_term[residue] / float(self.possible_n_term[residue]) + else: + return {r: self.n_term_probability(r) for r in self.observed_n_term} + + def c_term_probability(self, residue=None): + if residue is not None: + return self.observed_c_term[residue] / float(self.possible_c_term[residue]) + else: + return {r: self.c_term_probability(r) for r in self.observed_c_term} + + def pair_probability(self, pair=None): + if pair is not None: + pair = tuple(pair) + return self.observed_pairs[pair] / float(self.possible_pairs[pair]) + else: + return {r: self.pair_probability(r) for r in self.observed_pairs} + + def residue_probability(self, residue=None): + if residue is not None: + return (self.observed_n_term[residue] + self.observed_c_term[residue]) / float( + self.possible_n_term[residue] + self.possible_c_term[residue]) + else: + return {r: self.residue_probability(r) for r in (set(self.observed_c_term) | set(self.observed_n_term))} + + @classmethod + def fit(cls, spectrum_match_set): + inst = cls() + for match in spectrum_match_set: + inst.process_match(match) + inst.total_possible_outcomes() + return inst + + +class FrequencyScorer(GlycopeptideSpectrumMatcherBase): + def __init__(self, scan, sequence, model=None, mass_shift=None): + super(FrequencyScorer, self).__init__(scan, sequence, mass_shift) + self._score = None + self.solution_map = FragmentMatchMap() + self.glycosylated_b_ion_count = 0 + self.glycosylated_y_ion_count = 0 + self.model = model + + def match(self, error_tolerance=2e-5): + solution_map = FragmentMatchMap() + spectrum = self.spectrum + + n_glycosylated_b_ions = 0 + for frags in self.target.get_fragments('b'): + glycosylated_position = False + for frag in frags: + glycosylated_position |= frag.is_glycosylated + peak = spectrum.has_peak(frag.mass, error_tolerance) + if peak: + solution_map.add(peak, frag) + if glycosylated_position: + n_glycosylated_b_ions += 1 + + n_glycosylated_y_ions = 0 + for frags in self.target.get_fragments('y'): + glycosylated_position = False + for frag in frags: + glycosylated_position |= frag.is_glycosylated + peak = spectrum.has_peak(frag.mass, error_tolerance) + if peak: + solution_map.add(peak, frag) + if glycosylated_position: + n_glycosylated_y_ions += 1 + for frag in self.target.stub_fragments(extended=True): + peak = spectrum.has_peak(frag.mass, error_tolerance) + if peak: + solution_map.add(peak, frag) + + self.glycosylated_b_ion_count = n_glycosylated_b_ions + self.glycosylated_y_ion_count = n_glycosylated_y_ions + self.solution_map = solution_map + return solution_map + + def _compute_total(self): + total = 0. + for frags in chain(self.target.get_fragments('b'), self.target.get_fragments('y')): + for frag in frags: + n_term, c_term = frag.flanking_amino_acids + score = self.frequency_counter.n_term_probability( + n_term) * self.frequency_counter.c_term_probability(c_term) + total += score * 0.5 + return total + + def _score_backbone(self): + total = self._compute_total() + observed = 0.0 + track_site = set() + for frag in self.solution_map.fragments(): + if (frag.series == 'b') or (frag.series == 'y'): + position = frag.position + n_term, c_term = frag.flanking_amino_acids + score = self.model.n_term_probability( + n_term) * self.model.c_term_probability(c_term) + weight = 0.6 if position not in track_site else 0.4 + track_site.add(position) + observed += score * weight + return observed / total +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/scoring/glycan_signature_ions.py",".py","6290","160","import itertools +from operator import attrgetter +import numpy as np + +from glycopeptidepy.structure.glycan import GlycanCompositionProxy + +from glycresoft.structure import SpectrumGraph +from glycresoft.task import log_handle + +from glycresoft.tandem.oxonium_ions import single_signatures, compound_signatures + +from .base import GlycopeptideSpectrumMatcherBase + + +keyfn = attrgetter(""intensity"") + + +class GlycanCompositionSignatureMatcher(GlycopeptideSpectrumMatcherBase): + minimum_intensity_ratio_threshold = 0.025 + + def __init__(self, scan, target, mass_shift=None): + super(GlycanCompositionSignatureMatcher, self).__init__(scan, target, mass_shift) + self._init_signature_matcher() + + def _init_signature_matcher(self): + self.glycan_composition = self._copy_glycan_composition() + self.expected_matches = dict() + self.unexpected_matches = dict() + self.maximum_intensity = float('inf') + + def _copy_glycan_composition(self): + return GlycanCompositionProxy(self.target.glycan_composition) + + signatures = single_signatures + compound_signatures = compound_signatures + all_signatures = single_signatures.copy() + all_signatures.update(compound_signatures) + + def match(self, error_tolerance=2e-5, rare_signatures=False, *args, **kwargs): + if len(self.spectrum) == 0: + return + + gc = self.glycan_composition + annotations = self.scan.annotations + if ""signature_index_match"" in annotations: + signature_index = annotations['signature_index_match'] + record = signature_index.record_for(gc) + if record is not None: + self.maximum_intensity = signature_index.base_peak_intensity + self.expected_matches = record.expected_matches + self.unexpected_matches = record.unexpected_matches + return + else: + log_handle.log(""No signature ion index entry found for %s in %s"" % (gc, self.scan_id)) + self.maximum_intensity = self.base_peak() + spectrum = self.spectrum + + for mono in self.signatures: + is_expected = mono.is_expected(self.glycan_composition) + peak = mono.peak_of(spectrum, error_tolerance) + if peak is None: + if is_expected: + self.expected_matches[mono] = None + continue + if is_expected: + self.expected_matches[mono] = peak + else: + self.unexpected_matches[mono] = peak + + if rare_signatures: + for compound in self.compound_signatures: + is_expected = compound.is_expected(self.glycan_composition) + peak = compound.peak_of(spectrum, error_tolerance) + if peak is None: + if is_expected: + self.expected_matches[compound] = None + continue + if is_expected: + self.expected_matches[compound] = peak + else: + self.unexpected_matches[compound] = peak + + def _find_peak_pairs(self, error_tolerance=2e-5, include_compound=False, *args, **kwargs): + peak_set = self.spectrum + if len(peak_set) == 0: + return [] + pairs = SpectrumGraph() + minimum_intensity_threshold = 0.01 + blocks = [(part, part.mass()) for part in self.glycan_composition] + if include_compound: + compound_blocks = list(itertools.combinations(self.target, 2)) + compound_blocks = [(block, sum(part.mass() for part in block)) + for block in compound_blocks] + blocks.extend(compound_blocks) + + max_peak = self.maximum_intensity + threshold = max_peak * minimum_intensity_threshold + + for peak in peak_set: + if peak.intensity < threshold or peak.neutral_mass < 150: + continue + for block, mass in blocks: + for other in peak_set.all_peaks_for(peak.neutral_mass + mass, error_tolerance): + if other.intensity < threshold: + continue + pairs.add(peak, other, block) + self.spectrum_graph = pairs + return pairs + + def estimate_missing_ion_importance(self, key) -> float: + count = key.count_of(self.glycan_composition) + weight = self.all_signatures[key] + return min(weight * count, 0.99) + + def _signature_ion_score(self) -> float: + penalty = 0.0 + for key, peak in self.unexpected_matches.items(): + ratio = peak.intensity / self.maximum_intensity + if ratio < self.minimum_intensity_ratio_threshold: + continue + x = 1 - ratio + if x <= 0: + component = 20 + else: + component = -10 * np.log10(x) + if np.isnan(component): + component = 20 + penalty += component + for key, peak in self.expected_matches.items(): + matched = peak is not None + if matched: + ratio = peak.intensity / self.maximum_intensity + if ratio < self.minimum_intensity_ratio_threshold: + matched = False + if not matched: + importance = self.estimate_missing_ion_importance(key) + x = 1 - importance + if x <= 0: + component = 20 + else: + component = -10 * np.log10(x) + if np.isnan(component): + component = 20 + penalty += component + return -penalty + + def calculate_score(self, *args, **kwargs): + self._score = self._signature_ion_score() + return self._score + + def oxonium_ion_utilization(self, threshold: float=0.05) -> float: + utilization = 0.0 + for signature, matched in self.expected_matches.items(): + if matched is None or ((matched.intensity / self.maximum_intensity) < threshold): + comp = 10 * np.log10(1 - self.estimate_missing_ion_importance(signature)) + if np.isnan(comp): + comp = -20 + utilization += comp + return utilization +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/scoring/__init__.py",".py","1193","21","from .binomial_score import BinomialSpectrumMatcher +from glycresoft.tandem import target_decoy +from glycresoft.tandem.target_decoy import (TargetDecoyAnalyzer, GroupwiseTargetDecoyAnalyzer) +from .precursor_mass_accuracy import MassAccuracyModel, MassAccuracyMixin +from .simple_score import SimpleCoverageScorer +from .coverage_weighted_binomial import ( + CoverageWeightedBinomialScorer, ShortPeptideCoverageWeightedBinomialScorer, + CoverageWeightedBinomialModelTree) +from .intensity_scorer import (LogIntensityScorer, LogIntensityModelTree, + HyperscoreScorer, FullSignaturePenalizedLogIntensityScorer) +from .base import SpectrumMatcherBase, GlycopeptideSpectrumMatcherBase + + +__all__ = [ + ""BinomialSpectrumMatcher"", ""target_decoy"", ""TargetDecoyAnalyzer"", ""GroupwiseTargetDecoyAnalyzer"", + ""MassAccuracyModel"", ""MassAccuracyMixin"", ""SimpleCoverageScorer"", ""CoverageWeightedBinomialScorer"", + ""ShortPeptideCoverageWeightedBinomialScorer"", ""CoverageWeightedBinomialModelTree"", + ""GlycopeptideSpectrumMatcherBase"", ""SpectrumMatcherBase"", + ""LogIntensityScorer"", ""LogIntensityModelTree"", ""HyperscoreScorer"", ""FullSignaturePenalizedLogIntensityScorer"" +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/scoring/coverage_weighted_binomial.py",".py","3542","80","import math + +from .base import ( + ChemicalShift, ModelTreeNode, EXDFragmentationStrategy, + HCDFragmentationStrategy, IonSeries) +from .binomial_score import BinomialSpectrumMatcher, StubIgnoringBinomialSpectrumMatcher +from .simple_score import SimpleCoverageScorer, SignatureAwareCoverageScorer +from .precursor_mass_accuracy import MassAccuracyMixin + + +class CoverageWeightedBinomialScorer(BinomialSpectrumMatcher, SignatureAwareCoverageScorer, MassAccuracyMixin): + + def __init__(self, scan, sequence, mass_shift=None): + super(CoverageWeightedBinomialScorer, self).__init__(scan, sequence, mass_shift) + + def _match_backbone_series(self, series, error_tolerance=2e-5, masked_peaks=None, strategy=None, + include_neutral_losses=False): + if strategy is None: + strategy = HCDFragmentationStrategy + previous_position_glycosylated = False + for frags in self.get_fragments(series, strategy=strategy, include_neutral_losses=include_neutral_losses): + glycosylated_position = previous_position_glycosylated + self.n_theoretical += 1 + for frag in frags: + if not glycosylated_position: + glycosylated_position |= frag.is_glycosylated + for peak in self.spectrum.all_peaks_for(frag.mass, error_tolerance): + if peak.index.neutral_mass in masked_peaks: + continue + self.solution_map.add(peak, frag) + if glycosylated_position: + if series.direction > 0: + self.glycosylated_n_term_ion_count += 1 + else: + self.glycosylated_c_term_ion_count += 1 + previous_position_glycosylated = glycosylated_position + + def match(self, error_tolerance=2e-5, *args, **kwargs): + return SignatureAwareCoverageScorer.match(self, error_tolerance=error_tolerance, *args, **kwargs) + + def calculate_score(self, error_tolerance=2e-5, backbone_weight=None, glycosylated_weight=None, + stub_weight=None, *args, **kwargs): + bin_score = BinomialSpectrumMatcher.calculate_score( + self, error_tolerance=error_tolerance) + coverage_score = SimpleCoverageScorer.calculate_score( + self, backbone_weight, glycosylated_weight, stub_weight) + mass_accuracy = self._precursor_mass_accuracy_score() + signature_component = self._signature_ion_score() + self._score = bin_score * coverage_score + mass_accuracy + signature_component + return self._score + + +class ShortPeptideCoverageWeightedBinomialScorer(CoverageWeightedBinomialScorer): + stub_weight = 0.65 + + +def _short_peptide_test(scan, target, *args, **kwargs): + return len(target) < 10 + + +CoverageWeightedBinomialModelTree = ModelTreeNode(CoverageWeightedBinomialScorer, { + _short_peptide_test: ModelTreeNode(ShortPeptideCoverageWeightedBinomialScorer, {}), +}) + + +try: + from glycresoft._c.tandem.tandem_scoring_helpers import CoverageWeightedBinomialScorer_match_backbone_series + CoverageWeightedBinomialScorer._match_backbone_series = CoverageWeightedBinomialScorer_match_backbone_series +except ImportError: + pass + + +class StubIgnoringCoverageWeightedBinomialScorer(CoverageWeightedBinomialScorer): + def _sanitize_solution_map(self): + san = list() + for pair in self.solution_map: + if pair.fragment.series not in (""oxonium_ion"", ""stub_glycopeptide""): + san.append(pair) + return san +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/scoring/peak_vector.py",".py","4155","125","from typing import DefaultDict, Dict, Tuple + +from array import ArrayType as array + +import numpy as np + +from ms_deisotope.data_source import ProcessedScan +from glycresoft.structure import FragmentCachingGlycopeptide + + +from glycresoft.tandem.spectrum_match.spectrum_match import ScanMatchManagingMixin + + +class PeakFragmentVector(ScanMatchManagingMixin): + scan: ProcessedScan + target: FragmentCachingGlycopeptide + error_tolerance: float + max_charge: int + charge_vectors: DefaultDict[int, array] + + def __init__(self, scan: ProcessedScan, target: FragmentCachingGlycopeptide, + error_tolerance: float=2e-5, max_charge: int=2): + super().__init__(scan, target) + self.error_tolerance = error_tolerance + self.max_charge = max_charge + self.charge_vectors = DefaultDict(lambda: array('d')) + self.build() + + def build_for_series(self, ion_series): + zs = np.ones(self.max_charge) + for frags in self.target.get_fragments(ion_series): + for frag in frags: + zs[:] = 0 + for peak in self.scan.deconvoluted_peak_set.all_peaks_for(frag.mass, self.error_tolerance): + z = abs(peak.charge) + if z > self.max_charge: + continue + zs[z - 1] = peak.intensity + for z, i in enumerate(zs, 1): + self.charge_vectors[z].append(i) + + def build(self): + if self.is_hcd(): + self.build_for_series('b') + self.build_for_series('y') + if self.is_exd(): + self.build_for_series('c') + self.build_for_series('z') + + def flatten(self): + acc = array('d') + for k, v in self.charge_vectors.items(): + acc.extend(v) + return np.asarray(acc) + + def correlate(self, other: 'PeakFragmentVector') -> float: + xy = 0 + xx = 0 + yy = 0 + for z in range(1, self.max_charge + 1): + x = np.asarray(self.charge_vectors[z]) + y = np.asarray(other.charge_vectors[z]) + xy += x.dot(y) + xx += x.dot(x) + yy += y.dot(y) + return xy / (np.sqrt(xx) * np.sqrt(yy)) + + def __repr__(self) -> str: + return f""{self.__class__.__name__}({self.target})"" + + +class GlycanPeakFragmentVector(ScanMatchManagingMixin): + scan: ProcessedScan + target: FragmentCachingGlycopeptide + error_tolerance: float + max_charge: int + fragment_map: Dict[Tuple[str, int], float] + total: float + + def __init__(self, scan, target, error_tolerance: float=2e-5, max_charge: int = None): + super().__init__(scan, target) + if max_charge is None: + max_charge = self.precursor_information.charge + self.max_charge = max_charge + self.error_tolerance = error_tolerance + self.total = 0.0 + self.fragment_map = {} + self.build() + + def build(self): + total = 0.0 + for frag in self.target.stub_fragments(extended=True, extended_fucosylation=True): + for peak in self.scan.deconvoluted_peak_set.all_peaks_for(frag.mass, self.error_tolerance): + key = str(frag.glycosylation), peak.charge + if key in self.fragment_map: + self.fragment_map[key] += peak.intensity + else: + self.fragment_map[key] = peak.intensity + total += peak.intensity + self.total = total + + def correlate(self, other: 'GlycanPeakFragmentVector'): + xy = 0 + xx = 0 + yy = 0 + keyspace = self.fragment_map.keys() | other.fragment_map.keys() + for k in keyspace: + x = self.fragment_map.get(k, 0) + y = other.fragment_map.get(k, 0) + xy += x * y + xx += x ** 2 + yy += y ** 2 + return xy / (np.sqrt(xx) * np.sqrt(yy)) + + def __repr__(self) -> str: + return f""{self.__class__.__name__}({self.target})"" + + +try: + from glycresoft._c.tandem.tandem_scoring_helpers import correlate_fragment_map + + GlycanPeakFragmentVector.correlate = correlate_fragment_map +except ImportError: + pass +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/scoring/intensity_scorer.py",".py","8204","189","import math +import numpy as np + +from glycopeptidepy.structure.fragment import IonSeries + +from .base import ModelTreeNode +from .precursor_mass_accuracy import MassAccuracyMixin +from .simple_score import SignatureAwareCoverageScorer + + +class LogIntensityScorer(SignatureAwareCoverageScorer, MassAccuracyMixin): + + _peptide_score = None + _glycan_score = None + + def __init__(self, scan, sequence, mass_shift=None, *args, **kwargs): + super(LogIntensityScorer, self).__init__(scan, sequence, mass_shift, *args, **kwargs) + + def calculate_score(self, error_tolerance=2e-5, peptide_weight=0.65, *args, **kwargs) -> float: + glycan_weight = 1 - peptide_weight + combo_score = self.peptide_score(error_tolerance, *args, **kwargs) * peptide_weight +\ + self.glycan_score(error_tolerance, *args, **kwargs) * glycan_weight + mass_accuracy = self._precursor_mass_accuracy_score() + signature_component = self._signature_ion_score() + self._score = combo_score + mass_accuracy + signature_component + return self._score + + def calculate_peptide_score(self, error_tolerance=2e-5, peptide_coverage_weight=1.0, *args, **kwargs) -> float: + total = 0 + series_set = {IonSeries.b, IonSeries.y, IonSeries.c, IonSeries.z} + seen = set() + for peak_pair in self.solution_map: + peak = peak_pair.peak + if peak_pair.fragment.get_series() in series_set: + seen.add(peak.index.neutral_mass) + total += np.log10(peak.intensity) * (1 - (abs(peak_pair.mass_accuracy()) / error_tolerance) ** 4) + n_term, c_term = self._compute_coverage_vectors()[:2] + coverage_score = ((n_term + c_term[::-1])).sum() / float((2 * len(self.target) - 1)) + score = total * coverage_score ** peptide_coverage_weight + if np.isnan(score): + return 0 + return score + + def calculate_glycan_score(self, error_tolerance=2e-5, glycan_core_weight=0.4, glycan_coverage_weight=0.5, + fragile_fucose=False, extended_glycan_search=False, *args, **kwargs) -> float: + seen = set() + series = IonSeries.stub_glycopeptide + if not extended_glycan_search: + theoretical_set = list(self.target.stub_fragments(extended=True)) + else: + theoretical_set = list(self.target.stub_fragments(extended=True, extended_fucosylation=True)) + core_fragments = set() + for frag in theoretical_set: + if not frag.is_extended: + core_fragments.add(frag.name) + + total = 0 + core_matches = set() + extended_matches = set() + + for peak_pair in self.solution_map: + if peak_pair.fragment.series != series: + continue + fragment_name = peak_pair.fragment.base_name() + if fragment_name in core_fragments: + core_matches.add(fragment_name) + else: + extended_matches.add(fragment_name) + peak = peak_pair.peak + if peak.index.neutral_mass not in seen: + seen.add(peak.index.neutral_mass) + total += np.log10(peak.intensity) * (1 - (abs(peak_pair.mass_accuracy()) / error_tolerance) ** 4) + glycan_composition = self.target.glycan_composition + n = self._get_internal_size(glycan_composition) + k = 2.0 + if not fragile_fucose: + side_group_count = self._glycan_side_group_count( + glycan_composition) + if side_group_count > 0: + k = 1.0 + d = max(n * np.log(n) / k, n) + core_coverage = ((len(core_matches) * 1.0) / len(core_fragments)) ** glycan_core_weight + extended_coverage = min(float(len(core_matches) + len(extended_matches)) / d, 1.0) ** glycan_coverage_weight + score = total * core_coverage * extended_coverage + self._glycan_coverage = core_coverage * extended_coverage + glycan_prior = self.target.glycan_prior + score += self._glycan_coverage * glycan_prior + if np.isnan(score): + return 0 + return score + + def peptide_score(self, error_tolerance=2e-5, peptide_coverage_weight=1.0, *args, **kwargs) -> float: + if self._peptide_score is None: + self._peptide_score = self.calculate_peptide_score(error_tolerance, peptide_coverage_weight, *args, **kwargs) + return self._peptide_score + + def glycan_score(self, error_tolerance=2e-5, glycan_core_weight=0.4, glycan_coverage_weight=0.5, + *args, **kwargs) -> float: + if self._glycan_score is None: + self._glycan_score = self.calculate_glycan_score( + error_tolerance, glycan_core_weight, glycan_coverage_weight, *args, **kwargs) + return self._glycan_score + + +try: + from glycresoft._c.tandem.tandem_scoring_helpers import calculate_peptide_score, calculate_glycan_score + LogIntensityScorer.calculate_peptide_score = calculate_peptide_score + LogIntensityScorer.calculate_glycan_score = calculate_glycan_score +except ImportError: + pass + + +class LogIntensityScorerReweighted(LogIntensityScorer): + def peptide_score(self, error_tolerance=2e-5, peptide_coverage_weight=0.7, *args, **kwargs): + if self._peptide_score is None: + self._peptide_score = self.calculate_peptide_score( + error_tolerance, peptide_coverage_weight, *args, **kwargs) + return self._peptide_score + + def peptide_coverage(self): + return self._calculate_peptide_coverage_no_glycosylated() + +try: + from glycresoft._c.tandem.tandem_scoring_helpers import calculate_peptide_score_no_glycosylated + LogIntensityScorerReweighted.calculate_peptide_score = calculate_peptide_score_no_glycosylated +except ImportError: + pass + + +class ShortPeptideLogIntensityScorer(LogIntensityScorer): + stub_weight = 0.65 + + +def _short_peptide_test(scan, target, *args, **kwargs): + return len(target) < 10 + + +LogIntensityModelTree = ModelTreeNode(LogIntensityScorer, { + _short_peptide_test: ModelTreeNode(ShortPeptideLogIntensityScorer, {}), +}) + + +class FullSignaturePenalizedLogIntensityScorer(LogIntensityScorer): + def calculate_glycan_score(self, error_tolerance=2e-5, core_weight=0.4, coverage_weight=0.5, + fragile_fucose=True, extended_glycan_search=False, *args, **kwargs): + score = super(FullSignaturePenalizedLogIntensityScorer, self).calculate_glycan_score( + error_tolerance, core_weight, coverage_weight, fragile_fucose=fragile_fucose, + extended_glycan_search=extended_glycan_search, *args, **kwargs) + signature_component = self._signature_ion_score() + return score + signature_component + + +class HyperscoreScorer(SignatureAwareCoverageScorer, MassAccuracyMixin): + + def _calculate_hyperscore(self, *args, **kwargs): + n_term_intensity = 0 + c_term_intensity = 0 + stub_intensity = 0 + n_term = 0 + c_term = 0 + stub_count = 0 + for peak, fragment in self.solution_map: + if fragment.series == ""oxonium_ion"": + continue + elif fragment.series == IonSeries.stub_glycopeptide: + stub_count += 1 + stub_intensity += peak.intensity + elif fragment.series in (IonSeries.b, IonSeries.c): + n_term += 1 + n_term_intensity += peak.intensity + elif fragment.series in (IonSeries.y, IonSeries.z): + c_term += 1 + c_term_intensity += peak.intensity + hyper = 0 + factors = [math.factorial(n_term), math.factorial(c_term), math.factorial(stub_count), + stub_intensity, n_term_intensity, c_term_intensity] + for f in factors: + hyper += math.log(f) + + return hyper + + def calculate_score(self, error_tolerance=2e-5, *args, **kwargs): + hyperscore = self._calculate_hyperscore(error_tolerance, *args, **kwargs) + mass_accuracy = self._precursor_mass_accuracy_score() + signature_component = self._signature_ion_score() + self._score = hyperscore + mass_accuracy + signature_component + + return self._score +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/scoring/binomial_score.py",".py","11239","327","# -*- coding: utf-8 -*- + +''' +Much of this logic is derived from: + + Risk, B. A., Edwards, N. J., & Giddings, M. C. (2013). A peptide-spectrum scoring system + based on ion alignment, intensity, and pair probabilities. Journal of Proteome Research, + 12(9), 4240–7. http://doi.org/10.1021/pr400286p +''' + + +import numpy as np +from scipy.special import comb +from decimal import Decimal +import math + +from glycopeptidepy.utils.memoize import memoize + +from .base import ( + GlycopeptideSpectrumMatcherBase, ChemicalShift, EXDFragmentationStrategy, + HCDFragmentationStrategy, IonSeries) +from glycresoft.structure import FragmentMatchMap + + +@memoize(100000000000) +def binomial_pmf(n, i, p): + try: + return comb(n, i, exact=True) * (p ** i) * ((1 - p) ** (n - i)) + except OverflowError: + dn = Decimal(n) + di = Decimal(i) + dp = Decimal(p) + x = math.factorial(dn) / (math.factorial(di) * math.factorial(dn - di)) + return float(x * dp ** di * ((1 - dp) ** (dn - di))) + + +@memoize(100000000000) +def binomial_tail_probability(n, k, p): + total = 0.0 + for i in range(k, n): + v = binomial_pmf(n, i, p) + if np.isnan(v): + continue + total += v + return total + + +def binomial_fragments_matched(total_product_ion_count, count_product_ion_matches, ion_tolerance, + precursor_mass): + p = np.exp((np.log(ion_tolerance) + np.log(2)) + + np.log(count_product_ion_matches) - np.log(precursor_mass)) + return binomial_tail_probability(total_product_ion_count, count_product_ion_matches, p) + + +def median_sorted(numbers): + n = len(numbers) + if n == 0: + return (n - 1) // 2, 0 + elif n % 2 == 0: + return (n - 1) // 2, (numbers[(n - 1) // 2] + numbers[((n - 1) // 2) + 1]) / 2. + else: + return (n - 1) // 2, numbers[(n - 1) // 2] + + +def medians(array): + array.sort() + offset, m1 = median_sorted(array) + offset += 1 + i, m2 = median_sorted(array[offset:]) + offset += i + 1 + i, m3 = median_sorted(array[offset:]) + offset += i + 1 + i, m4 = median_sorted(array[offset:]) + return m1, m2, m3, m4 + + +def _counting_tiers(peak_list, matched_peaks, total_product_ion_count): + intensity_list = np.array([p.intensity for p in peak_list]) + m1, m2, m3, m4 = medians(intensity_list) + + matched_intensities = np.array( + [p.intensity for p, _ in matched_peaks]) + counts = dict() + next_count = (matched_intensities > m1).sum() + counts[1] = next_count + + next_count = (matched_intensities > m2).sum() + counts[2] = next_count + + next_count = (matched_intensities > m3).sum() + counts[3] = next_count + + next_count = (matched_intensities > m4).sum() + counts[4] = next_count + return counts + + +def _intensity_tiers(peak_list, matched_peaks, total_product_ion_count): + intensity_list = np.array([p.intensity for p in peak_list]) + m1, m2, m3, m4 = medians(intensity_list) + + matched_intensities = np.array( + [p.intensity for p, _ in matched_peaks]) + counts = dict() + last_count = total_product_ion_count + next_count = (matched_intensities > m1).sum() + if last_count == 0: + counts[1] = 1.0 + elif last_count == next_count: + counts[1] = binomial_tail_probability(last_count, next_count - 1, 0.5) + else: + counts[1] = binomial_tail_probability(last_count, next_count, 0.5) + last_count = next_count + + next_count = (matched_intensities > m2).sum() + if last_count == 0: + counts[2] = 1.0 + elif last_count == next_count: + counts[2] = binomial_tail_probability(last_count, next_count - 1, 0.5) + else: + counts[2] = binomial_tail_probability(last_count, next_count, 0.5) + last_count = next_count + + next_count = (matched_intensities > m3).sum() + if last_count == 0: + counts[3] = 1.0 + elif last_count == next_count: + counts[3] = binomial_tail_probability(last_count, next_count - 1, 0.5) + else: + counts[3] = binomial_tail_probability(last_count, next_count, 0.5) + + last_count = next_count + + next_count = (matched_intensities > m4).sum() + if last_count == 0: + counts[4] = 1.0 + elif last_count == next_count: + counts[4] = binomial_tail_probability(last_count, next_count - 1, 0.5) + else: + counts[4] = binomial_tail_probability(last_count, next_count, 0.5) + return counts + + +def _score_tiers(peak_list, matched_peaks, total_product_ion_count): + intensity_list = np.array([p.score for p in peak_list]) + m1, m2, m3, m4 = medians(intensity_list) + + matched_intensities = np.array( + [p.score for match, p in matched_peaks.items()]) + counts = dict() + last_count = total_product_ion_count + next_count = (matched_intensities > m1).sum() + if last_count == 0: + counts[1] = 1.0 + elif last_count == next_count: + counts[1] = binomial_tail_probability(last_count, next_count - 1, 0.5) + else: + counts[1] = binomial_tail_probability(last_count, next_count, 0.5) + last_count = next_count + + next_count = (matched_intensities > m2).sum() + if last_count == 0: + counts[2] = 1.0 + elif last_count == next_count: + counts[2] = binomial_tail_probability(last_count, next_count - 1, 0.5) + else: + counts[2] = binomial_tail_probability(last_count, next_count, 0.5) + last_count = next_count + + next_count = (matched_intensities > m3).sum() + if last_count == 0: + counts[3] = 1.0 + elif last_count == next_count: + counts[3] = binomial_tail_probability(last_count, next_count - 1, 0.5) + else: + counts[3] = binomial_tail_probability(last_count, next_count, 0.5) + + last_count = next_count + + next_count = (matched_intensities > m4).sum() + if last_count == 0: + counts[4] = 1.0 + elif last_count == next_count: + counts[4] = binomial_tail_probability(last_count, next_count - 1, 0.5) + else: + counts[4] = binomial_tail_probability(last_count, next_count, 0.5) + return counts + + +def binomial_intensity(peak_list, matched_peaks, total_product_ion_count): + if len(matched_peaks) == 0: + return np.exp(0) + counts = _intensity_tiers(peak_list, matched_peaks, total_product_ion_count) + + prod = 0 + for k, v in counts.items(): + if v == 0: + v = 1e-20 + prod += np.log(v) + return np.exp(prod) + + +def calculate_precursor_mass(spectrum_match): + precursor_mass = spectrum_match.target.total_composition().mass + return precursor_mass + + +class BinomialSpectrumMatcher(GlycopeptideSpectrumMatcherBase): + + def __init__(self, scan, target, mass_shift=None): + super(BinomialSpectrumMatcher, self).__init__(scan, target, mass_shift) + self.solution_map = FragmentMatchMap() + self._init_binomial() + + def _init_binomial(self): + self._sanitized_spectrum = set(self.spectrum) + self.n_theoretical = 0 + + def _match_oxonium_ions(self, error_tolerance=2e-5, masked_peaks=None): + if masked_peaks is None: + masked_peaks = set() + val = super(BinomialSpectrumMatcher, self)._match_oxonium_ions( + error_tolerance=error_tolerance, masked_peaks=masked_peaks) + self._sanitized_spectrum -= {self.spectrum[i] for i in masked_peaks} + return val + + def _match_backbone_series(self, series, error_tolerance=2e-5, masked_peaks=None, strategy=None, + include_neutral_losses=False): + if strategy is None: + strategy = HCDFragmentationStrategy + for frags in self.get_fragments(series, strategy=strategy, include_neutral_losses=include_neutral_losses): + # Should this be on the level of position, or the level of the individual fragment ions? + # At the level of position, this makes missing only glycosylated or unglycosylated ions + # less punishing, while at the level of the fragment makes more sense by the definition + # of the geometric mass accuracy interpretation. + # + # Using the less severe case to be less pessimistic + self.n_theoretical += 1 + for frag in frags: + for peak in self.spectrum.all_peaks_for(frag.mass, error_tolerance): + if peak.index.neutral_mass in masked_peaks: + continue + self.solution_map.add(peak, frag) + + def _sanitize_solution_map(self): + san = list() + for pair in self.solution_map: + if pair.fragment.series != ""oxonium_ion"": + san.append(pair) + return san + + def _compute_average_window_size(self, error_tolerance=2e-5): + average_window_size = ( + (self.target.peptide_composition( + ).mass) / 3.) * error_tolerance * 2 + return average_window_size + + def _fragment_matched_binomial(self, error_tolerance=2e-5): + precursor_mass = calculate_precursor_mass(self) + + fragment_match_component = binomial_fragments_matched( + self.n_theoretical, + len(self._sanitize_solution_map()), + self._compute_average_window_size(error_tolerance), + precursor_mass + ) + if fragment_match_component < 1e-170: + fragment_match_component = 1e-170 + return fragment_match_component + + def _intensity_component_binomial(self): + intensity_component = binomial_intensity( + self._sanitized_spectrum, + self._sanitize_solution_map(), + self.n_theoretical) + + if intensity_component < 1e-170: + intensity_component = 1e-170 + return intensity_component + + def _binomial_score(self, error_tolerance=2e-5, *args, **kwargs): + precursor_mass = calculate_precursor_mass(self) + + solution_map = self._sanitize_solution_map() + n_matched = len(solution_map) + if n_matched == 0 or len(self._sanitized_spectrum) == 0: + return 0 + + fragment_match_component = binomial_fragments_matched( + self.n_theoretical, + len(solution_map), + self._compute_average_window_size(error_tolerance), + precursor_mass + ) + + if fragment_match_component < 1e-170: + fragment_match_component = 1e-170 + + intensity_component = binomial_intensity( + self._sanitized_spectrum, + solution_map, + self.n_theoretical) + + if intensity_component < 1e-170: + intensity_component = 1e-170 + score = -np.log10(intensity_component) + -np.log10(fragment_match_component) + + if np.isinf(score): + print(""infinite score"", self.scan, self.target, intensity_component, fragment_match_component, self.scan) + + return score + + def calculate_score(self, error_tolerance=2e-5, *args, **kwargs): + score = self._binomial_score(error_tolerance) + self._score = score + return score + + +class StubIgnoringBinomialSpectrumMatcher(BinomialSpectrumMatcher): + + def _sanitize_solution_map(self): + san = list() + for pair in self.solution_map: + if pair.fragment.series not in (""oxonium_ion"", ""stub_glycopeptide""): + san.append(pair) + return san +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/scoring/base.py",".py","12730","270","import math +from typing import List, Mapping, Optional, Set, Tuple, Type, Union + + +from glycopeptidepy import PeptideSequence +from glycopeptidepy.structure.fragment import ChemicalShift, IonSeries, FragmentBase +from glycopeptidepy.structure.fragmentation_strategy import EXDFragmentationStrategy, HCDFragmentationStrategy, PeptideFragmentationStrategyBase + +from glycresoft.structure.fragment_match_map import FragmentMatchMap +from glycresoft.structure.structure_loader import FragmentCachingGlycopeptide +from ..core_search import glycan_side_group_count +from ...spectrum_match import SpectrumMatcherBase, ModelTreeNode + + +class GlycopeptideSpectrumMatcherBase(SpectrumMatcherBase): + target: Union[FragmentCachingGlycopeptide, PeptideSequence] + + _peptide_Y_ion_utilization: Optional[Tuple[float, int, int]] = None + _glycan_score: Optional[float] = None + _peptide_score: Optional[float] = None + _glycan_coverage: Optional[float] = None + _peptide_coverage: Optional[float] = None + + solution_map: FragmentMatchMap + + def _theoretical_mass(self) -> float: + return self.target.total_mass + + def _match_oxonium_ions(self, error_tolerance: float=2e-5, masked_peaks: Optional[Set[int]]=None) -> Set[int]: + '''Note: This method is masked by a Cython implementation + ''' + if masked_peaks is None: + masked_peaks = set() + for frag in self.target.glycan_fragments( + all_series=False, allow_ambiguous=False, + include_large_glycan_fragments=False, + maximum_fragment_size=4): + peak = self.spectrum.has_peak(frag.mass, error_tolerance) + if peak and peak.index.neutral_mass not in masked_peaks: + self.solution_map.add(peak, frag) + masked_peaks.add(peak.index.neutral_mass) + return masked_peaks + + def _match_stub_glycopeptides(self, error_tolerance: float=2e-5, + masked_peaks: Optional[Set[int]]=None, + chemical_shift: Optional[ChemicalShift]=None, + extended_glycan_search: bool=False) -> Set[int]: + if masked_peaks is None: + masked_peaks = set() + if not extended_glycan_search: + fragments = self.target.stub_fragments(extended=True) + else: + fragments = self.target.stub_fragments(extended=True, extended_fucosylation=True) + for frag in fragments: + for peak in self.spectrum.all_peaks_for(frag.mass, error_tolerance): + # should we be masking these? peptides which have amino acids which are + # approximately the same mass as a monosaccharide unit at ther terminus + # can produce cases where a stub ion and a backbone fragment match the + # same peak. + # + masked_peaks.add(peak.index.neutral_mass) + self.solution_map.add(peak, frag) + if chemical_shift is not None: + shifted_mass = frag.mass + self.mass_shift.tandem_mass + for peak in self.spectrum.all_peaks_for(shifted_mass, error_tolerance): + masked_peaks.add(peak.index.neutral_mass) + shifted_frag = frag.clone() + shifted_frag.chemical_shift = chemical_shift + shifted_frag.name += ""+ %s"" % (self.mass_shift.name,) + self.solution_map.add(peak, shifted_frag) + return masked_peaks + + def get_fragments(self, series: IonSeries, + strategy: Optional[Type[PeptideFragmentationStrategyBase]]=None, + **kwargs) -> List[List[FragmentBase]]: + fragments = self.target.get_fragments(series, strategy=strategy) + return fragments + + def _match_backbone_series(self, series: IonSeries, error_tolerance: float=2e-5, + masked_peaks: Optional[Set[int]]=None, + strategy: Optional[Type[PeptideFragmentationStrategyBase]] = None, + include_neutral_losses: bool=False): + if strategy is None: + strategy = HCDFragmentationStrategy + if masked_peaks is None: + masked_peaks = set() + for frags in self.get_fragments(series, strategy=strategy, include_neutral_losses=include_neutral_losses): + for frag in frags: + for peak in self.spectrum.all_peaks_for(frag.mass, error_tolerance): + if peak.index.neutral_mass in masked_peaks: + continue + self.solution_map.add(peak, frag) + + def match(self, error_tolerance: float=2e-5, *args, **kwargs): + masked_peaks = set() + include_neutral_losses = kwargs.get(""include_neutral_losses"", False) + extended_glycan_search = kwargs.get(""extended_glycan_search"", False) + if self.mass_shift.tandem_mass != 0: + chemical_shift = ChemicalShift( + self.mass_shift.name, self.mass_shift.tandem_composition) + else: + chemical_shift = None + + is_hcd = self.is_hcd() + is_exd = self.is_exd() + if not is_hcd and not is_exd: + is_hcd = True + # handle glycan fragments from collisional dissociation + if is_hcd: + self._match_oxonium_ions(error_tolerance, masked_peaks=masked_peaks) + self._match_stub_glycopeptides(error_tolerance, masked_peaks=masked_peaks, + chemical_shift=chemical_shift, + extended_glycan_search=extended_glycan_search) + + # handle N-term + if is_hcd and not is_exd: + self._match_backbone_series( + IonSeries.b, error_tolerance, masked_peaks, HCDFragmentationStrategy, include_neutral_losses) + elif is_exd: + self._match_backbone_series( + IonSeries.b, error_tolerance, masked_peaks, EXDFragmentationStrategy, + include_neutral_losses) + self._match_backbone_series( + IonSeries.c, error_tolerance, masked_peaks, EXDFragmentationStrategy, + include_neutral_losses) + + # handle C-term + if is_hcd and not is_exd: + self._match_backbone_series( + IonSeries.y, error_tolerance, masked_peaks, HCDFragmentationStrategy, + include_neutral_losses) + elif is_exd: + self._match_backbone_series( + IonSeries.y, error_tolerance, masked_peaks, EXDFragmentationStrategy, + include_neutral_losses) + self._match_backbone_series( + IonSeries.z, error_tolerance, masked_peaks, EXDFragmentationStrategy, + include_neutral_losses) + + return self + + def peptide_score(self, *args, **kwargs) -> float: + if self._peptide_score is None: + self._peptide_score = self.calculate_peptide_score(*args, **kwargs) + return self._peptide_score + + def calculate_peptide_score(self, *args, **kwargs) -> float: + return 0 + + def glycan_score(self, *args, **kwargs) -> float: + if self._glycan_score is None: + self._glycan_score = self.calculate_glycan_score(*args, **kwargs) + return self._glycan_score + + def _glycan_side_group_count(self, glycan_composition: Mapping) -> int: + return glycan_side_group_count(glycan_composition) + + def _calculate_glycan_coverage(self, core_weight: float=0.4, + coverage_weight: float=0.5, + fragile_fucose: bool=False, + extended_glycan_search: bool=False) -> float: + seen = set() + series = IonSeries.stub_glycopeptide + if not extended_glycan_search: + theoretical_set = list(self.target.stub_fragments(extended=True)) + else: + theoretical_set = list(self.target.stub_fragments(extended=True, extended_fucosylation=True)) + core_fragments = set() + for frag in theoretical_set: + if not frag.is_extended: + core_fragments.add(frag.name) + + core_matches = set() + extended_matches = set() + + for peak_pair in self.solution_map: + if peak_pair.fragment.series != series: + continue + elif peak_pair.fragment_name in core_fragments: + core_matches.add(peak_pair.fragment_name) + else: + extended_matches.add(peak_pair.fragment_name) + peak = peak_pair.peak + if peak.index.neutral_mass not in seen: + seen.add(peak.index.neutral_mass) + glycan_composition = self.target.glycan_composition + n = self._get_internal_size(glycan_composition) + m = len(theoretical_set) + k = 2.0 + if not fragile_fucose: + side_group_count = self._glycan_side_group_count(glycan_composition) + if side_group_count > 0: + k = 1.0 + d = min(max(n * math.log(n) / k, n), m) + core_coverage = ((len(core_matches) * 1.0) / + len(core_fragments)) ** core_weight + extended_coverage = min( + float(len(core_matches) + len(extended_matches)) / d, 1.0) ** coverage_weight + coverage = core_coverage * extended_coverage + self._glycan_coverage = coverage + return coverage + + def glycan_coverage(self, core_weight: float=0.4, + coverage_weight: float=0.5, + fragile_fucose:bool=False, + extended_glycan_search:bool=False, + *args, **kwargs) -> float: + if self._glycan_coverage is not None: + return self._glycan_coverage + self._glycan_coverage = self._calculate_glycan_coverage( + core_weight, coverage_weight, fragile_fucose=fragile_fucose, + extended_glycan_search=extended_glycan_search, *args, **kwargs) + return self._glycan_coverage + + def peptide_coverage(self) -> float: + return self._calculate_peptide_coverage() + + def calculate_glycan_score(self, *args, **kwargs) -> float: + return 0 + + def count_peptide_Y_ion_utilization(self) -> Tuple[float, int, int, float]: + if self._peptide_Y_ion_utilization is not None: + return self._peptide_Y_ion_utilization + weight = 0.0 + stub_count = 0 + peptide_backbone_count = 0 + total_utilization = 0.0 + for pfp in self.solution_map: + frag_series = pfp.fragment.series + if frag_series != ""oxonium_ion"": + total_utilization += pfp.peak.intensity + if frag_series == ""stub_glycopeptide"": + stub_count += 1 + weight += math.log10(pfp.peak.intensity) + elif frag_series.int_code <= IonSeries.z.int_code: + peptide_backbone_count += 1 + self._peptide_Y_ion_utilization = weight, stub_count, peptide_backbone_count, total_utilization + return self._peptide_Y_ion_utilization + + def oxonium_ion_utilization(self): + return 0.0 + + def get_auxiliary_data(self): + data = super(GlycopeptideSpectrumMatcherBase, self).get_auxiliary_data() + data['score'] = self.score + data['glycan_score'] = self.glycan_score() + data['peptide_score'] = self.peptide_score() + data['glycan_coverage'] = self.glycan_coverage() + data['n_peaks'] = len(self.spectrum) + data['n_fragment_matches'] = len(self.solution_map) + (data['stub_glycopeptide_intensity_utilization'], + data['n_stub_glycopeptide_matches'], + data['peptide_backbone_matches']) = self.count_peptide_Y_ion_utilization() + return data + +try: + from glycresoft._c.tandem.tandem_scoring_helpers import ( + _match_oxonium_ions, _match_stub_glycopeptides, + _calculate_glycan_coverage, _compute_glycan_coverage_from_metrics, + _calculate_peptide_coverage, _calculate_peptide_coverage_no_glycosylated, + count_peptide_Y_ion_utilization) + GlycopeptideSpectrumMatcherBase._match_oxonium_ions = _match_oxonium_ions + GlycopeptideSpectrumMatcherBase._match_stub_glycopeptides = _match_stub_glycopeptides + GlycopeptideSpectrumMatcherBase._calculate_glycan_coverage = _calculate_glycan_coverage + GlycopeptideSpectrumMatcherBase._compute_glycan_coverage_from_metrics = _compute_glycan_coverage_from_metrics + GlycopeptideSpectrumMatcherBase._calculate_peptide_coverage = _calculate_peptide_coverage + GlycopeptideSpectrumMatcherBase._calculate_peptide_coverage_no_glycosylated = _calculate_peptide_coverage_no_glycosylated +except ImportError: + pass +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/dynamic_generation/journal.py",".py","21880","601","'''Implementation for journal file reading and writing to serialize +glycopeptide spectrum match information to disk during processing. +''' +import os +import io +import csv +import json +import gzip + +from multiprocessing import Event, JoinableQueue + +from collections import defaultdict +from operator import attrgetter +from typing import Any, Callable, DefaultDict, Dict, List, Optional, Set, Type, Union, TYPE_CHECKING, BinaryIO + + +import numpy as np + +from glycresoft.chromatogram_tree.mass_shift import MassShiftBase + +try: + from pyzstd import ZstdFile +except ImportError: + ZstdFile = None + +from glycopeptidepy.utils import collectiontools + +from ms_deisotope.output import ProcessedMSFileLoader + +from glycresoft.task import TaskBase, TaskExecutionSequence, Empty + +from glycresoft.structure.structure_loader import ( + PeptideProteinRelation, LazyGlycopeptide) +from glycresoft.structure.scan import ScanInformation, ScanInformationLoader +from glycresoft.structure.lru import LRUMapping +from glycresoft.chromatogram_tree import Unmodified + +from glycresoft.tandem.ref import SpectrumReference +from glycresoft.tandem.spectrum_match import ( + MultiScoreSpectrumMatch, MultiScoreSpectrumSolutionSet, ScoreSet, FDRSet) + +from .search_space import glycopeptide_key_t, StructureClassification + +if TYPE_CHECKING: + from glycresoft.serialize import Analysis, AnalysisDeserializer + from ms_deisotope.data_source import RandomAccessScanSource + + +def _zstdopen(path, mode='w'): + handle = ZstdFile(path, mode=mode.replace('t', 'b')) + return io.TextIOWrapper(handle, encoding='utf8') + + +def _zstwrap(fh, mode='w'): + handle = ZstdFile(fh, mode=mode) + return io.TextIOWrapper(handle, encoding='utf8') + + +def _gzopen(path, mode='w'): + handle = gzip.open(path, mode=mode.replace('t', 'b')) + return io.TextIOWrapper(handle, encoding='utf8') + + +def _gzwrap(fh, mode='w'): + handle = gzip.GzipFile(fileobj=fh, mode=mode) + return io.TextIOWrapper(handle, encoding='utf8') + + +if ZstdFile is None: + _file_opener = _gzopen + _file_wrapper = _gzwrap +else: + _file_opener = _zstdopen + _file_wrapper = _zstwrap + + +class JournalFileWriter(TaskBase): + """"""A task for writing glycopeptide spectrum matches to a TSV-formatted + journal file. This format is an intermediary result, and will contain many + random or non-useful matches. + + """""" + + path: os.PathLike + handle: io.TextIOWrapper + + include_auxiliary: bool + include_fdr: bool + writer: csv.writer + spectrum_counter: int + solution_counter: int + + score_columns: List[str] + + def __init__(self, path, include_fdr=False, include_auxiliary=False, score_columns: List[str]=None): + if score_columns is None: + score_columns = ScoreSet.field_names() + self.path = path + if not hasattr(path, 'write'): + self.handle = _file_opener(path, 'wb') + else: + self.handle = _file_wrapper(self.path, 'w') + self.include_fdr = include_fdr + self.include_auxiliary = include_auxiliary + self.spectrum_counter = 0 + self.solution_counter = 0 + + self.score_columns = score_columns + + self.writer = csv.writer(self.handle, delimiter='\t') + self.write_header() + + def _get_headers(self): + names = [ + 'scan_id', + 'precursor_mass_accuracy', + 'peptide_start', + 'peptide_end', + 'peptide_id', + 'protein_id', + 'hypothesis_id', + 'glycan_combination_id', + 'match_type', + 'site_combination_index', + 'glycosylation_type', + 'glycopeptide_sequence', + 'mass_shift', + ] + names.extend(self.score_columns) + if self.include_fdr: + names.extend([ + ""peptide_q_value"", + ""glycan_q_value"", + ""glycopeptide_q_value"", + ""total_q_value"" + ]) + if self.include_auxiliary: + names.append(""auxiliary"") + return names + + def write_header(self): + self.writer.writerow(self._get_headers()) + + def _prepare_fields(self, psm: MultiScoreSpectrumMatch) -> List[str]: + error = (psm.target.total_mass - psm.precursor_information.neutral_mass + ) / psm.precursor_information.neutral_mass + fields = ([psm.scan_id, error, ] + list(psm.target.id) + [ + psm.target, + psm.mass_shift.name, + ]) + fields.extend(psm.score_set.values()) + if self.include_fdr: + q_value_set = psm.q_value_set + if q_value_set is None: + fdr_fields = [ + 1, 1, 1, 1 + ] + else: + fdr_fields = [ + q_value_set.peptide_q_value, + q_value_set.glycan_q_value, + q_value_set.glycopeptide_q_value, + q_value_set.total_q_value + ] + fields.extend(fdr_fields) + if self.include_auxiliary: + fields.append(json.dumps(psm.get_auxiliary_data(), sort_keys=True)) + fields = [str(f) for f in fields] + return fields + + def write(self, psm: MultiScoreSpectrumMatch): + self.solution_counter += 1 + self.writer.writerow(self._prepare_fields(psm)) + + def writeall(self, solution_sets: List[MultiScoreSpectrumSolutionSet]): + for solution_set in solution_sets: + self.spectrum_counter += 1 + for solution in solution_set: + self.write(solution) + self.flush() + + def flush(self): + self.handle.flush() + + def close(self): + self.handle.close() + + +class JournalingConsumer(TaskExecutionSequence): + journal_file: JournalFileWriter + in_queue: JoinableQueue + in_done_event: Event + done_event: Event + + def __init__(self, journal_file, in_queue, in_done_event): + self.journal_file = journal_file + self.in_queue = in_queue + self.in_done_event = in_done_event + self.done_event = self._make_event() + + def run(self): + has_work = True + while has_work and not self.error_occurred(): + try: + solutions = self.in_queue.get(True, 5) + self.journal_file.writeall(solutions) + # Only log if something changed. + if solutions: + self.debug(""... Handled %d spectra with %d solutions so far"" % ( + self.journal_file.spectrum_counter, self.journal_file.solution_counter)) + except Empty: + if self.in_done_event.is_set(): + has_work = False + break + self.done_event.set() + + def close_stream(self): + self.journal_file.close() + + +def parse_float(value: str) -> float: + value = float(value) + if np.isnan(value): + return 0 + return value + + +try: + _parse_float = parse_float + from glycresoft._c.tandem.tandem_scoring_helpers import parse_float +except ImportError: + pass + + +class JournalFileIndex(TaskBase): + def __init__(self, path): + self.path = path + self.scan_ids = set() + self.glycopeptides = set() + self.build_index() + + def build_index(self): + reader = self.open() + for row in reader: + self.scan_ids.add(row['scan_id']) + self.glycopeptides.add(row['glycopeptide_sequence']) + + def has_scan(self, scan_id: str) -> bool: + return scan_id in self.scan_ids + + def has_glycopeptide(self, glycopeptide: str) -> bool: + return glycopeptide in self.glycopeptides + + def __repr__(self): + return f""{self.__class__.__name__}({self.path})"" + + def __contains__(self, key: str): + return self.has_glycopeptide(key) or self.has_scan(key) + + def open(self): + if not hasattr(self.path, 'read') and not hasattr(self.path, 'open'): + handle = _file_opener(self.path, 'rt') + elif hasattr(self.path, 'open'): + handle = _file_wrapper(self.path.open(raw=True), 'r') + else: + handle = _file_wrapper(self.path, 'r') + reader = csv.DictReader(handle, delimiter='\t') + return reader + + def collect_for_scan_id(self, scan_id: str): + reader = self.open() + for row in reader: + if scan_id == row['scan_id']: + yield row + + +class JournalFileReader(TaskBase): + path: os.PathLike + handle: io.TextIOBase + reader: csv.DictReader + + glycopeptide_cache: LRUMapping + mass_shift_map: Dict[str, MassShiftBase] + scan_loader: Optional[ScanInformationLoader] + include_fdr: bool + + score_set_type: Type + score_columns: List[str] + + def __init__(self, path, cache_size=2 ** 16, mass_shift_map=None, scan_loader=None, + include_fdr=False, score_set_type=None): + if mass_shift_map is None: + mass_shift_map = {Unmodified.name: Unmodified} + else: + mass_shift_map.setdefault(Unmodified.name, Unmodified) + if score_set_type is None: + score_set_type = ScoreSet + self.path = path + if not hasattr(path, 'read'): + self.handle = _file_opener(path, 'rt') + else: + self.handle = _file_wrapper(self.path, 'r') + self.reader = csv.DictReader(self.handle, delimiter='\t') + self.glycopeptide_cache = LRUMapping(cache_size or 2 ** 12) + self.mass_shift_map = mass_shift_map + self.scan_loader = scan_loader + self.include_fdr = include_fdr + + self.score_set_type = score_set_type + self.score_columns = score_set_type.field_names() + for name in ScoreSet.field_names(): + self.score_columns.remove(name) + + def _build_key(self, row) -> glycopeptide_key_t: + glycopeptide_id_key = glycopeptide_key_t( + int(row['peptide_start']), int(row['peptide_end']), int( + row['peptide_id']), int(row['protein_id']), + int(row['hypothesis_id']), int(row['glycan_combination_id']), + StructureClassification[row['match_type']], + int(row['site_combination_index']), row.get('glycosylation_type')) + return glycopeptide_id_key + + def _build_protein_relation(self, glycopeptide_id_key: glycopeptide_key_t) -> PeptideProteinRelation: + return PeptideProteinRelation( + glycopeptide_id_key.start_position, glycopeptide_id_key.end_position, + glycopeptide_id_key.protein_id, glycopeptide_id_key.hypothesis_id) + + def glycopeptide_from_row(self, row: Dict) -> LazyGlycopeptide: + glycopeptide_id_key = self._build_key(row) + if glycopeptide_id_key in self.glycopeptide_cache: + return self.glycopeptide_cache[glycopeptide_id_key] + if glycopeptide_id_key.structure_type & StructureClassification.target_peptide_decoy_glycan.value: + glycopeptide = LazyGlycopeptide(row['glycopeptide_sequence'], glycopeptide_id_key) + else: + glycopeptide = LazyGlycopeptide(row['glycopeptide_sequence'], glycopeptide_id_key) + glycopeptide.protein_relation = self._build_protein_relation(glycopeptide_id_key) + self.glycopeptide_cache[glycopeptide_id_key] = glycopeptide + return glycopeptide + + def _build_score_set(self, row) -> ScoreSet: + score_set_entries = [ + parse_float(row['total_score']), + parse_float(row['peptide_score']), + parse_float(row['glycan_score']), + float(row['glycan_coverage']), + float(row['stub_glycopeptide_intensity_utilization']), + float(row['oxonium_ion_intensity_utilization']), + int(row['n_stub_glycopeptide_matches']), + float(row.get('peptide_coverage', 0.0)), + float(row.get('total_signal_utilization', 0.0)) + ] + for name in self.score_columns: + score_set_entries.append(parse_float(row.get(name, '0.0'))) + + score_set = self.score_set_type(*score_set_entries) + return score_set + + def _build_fdr_set(self, row) -> FDRSet: + fdr_set = FDRSet( + float(row['total_q_value']), + float(row['peptide_q_value']), + float(row['glycan_q_value']), + float(row['glycopeptide_q_value'])) + return fdr_set + + def _make_mass_shift(self, row) -> MassShiftBase: + mass_shift = self.mass_shift_map[row['mass_shift']] + return mass_shift + + def _make_scan(self, row) -> Union[SpectrumReference, ScanInformation]: + if self.scan_loader is None: + scan = SpectrumReference(row['scan_id']) + else: + scan = self.scan_loader.get_scan_by_id(row['scan_id']) + return scan + + def spectrum_match_from_row(self, row) -> MultiScoreSpectrumMatch: + glycopeptide = self.glycopeptide_from_row(row) + scan = self._make_scan(row) + fdr_set = None + if self.include_fdr: + fdr_set = self._build_fdr_set(row) + score_set = self._build_score_set(row) + mass_shift = self._make_mass_shift(row) + match = MultiScoreSpectrumMatch( + scan, glycopeptide, score_set, mass_shift=mass_shift, + q_value_set=fdr_set, + match_type=str(glycopeptide.id.structure_type)) + return match + + def __iter__(self): + return self + + def __next__(self) -> MultiScoreSpectrumMatch: + return self.spectrum_match_from_row(next(self.reader)) + + def next(self): + return self.__next__() + + def close(self): + self.handle.close() + + +def isclose(a, b, rtol=1e-05, atol=1e-08): + return abs(a - b) <= atol + rtol * abs(b) + + +class SolutionSetGrouper(TaskBase): + """""" + Partition multi-score glycopeptide identificatins into groups + according to either glycopeptide target/decoy classification (:attr:`match_type_groups`) + or by best match to a given scan and target/decoy classification (:attr:`exclusive_match_groups`) + + """""" + # All the matches of all match types for every spectrum in no particular order + spectrum_matches: List[MultiScoreSpectrumMatch] + # The set of all scan IDs + spectrum_ids: Set[str] + # The set of all scan IDs where a target is the best match + target_owned_spectrum_ids: Set[str] + # The spectrum solution sets for each target classification group + match_type_groups: Dict[StructureClassification, List[MultiScoreSpectrumSolutionSet]] + # The set of all spectrum matches that are the best scoring match for their scan in a specific + # match type. This is used for FDR estimation. + exclusive_match_groups: DefaultDict[StructureClassification, + List[MultiScoreSpectrumMatch]] + + def __init__(self, spectrum_matches): + self.spectrum_matches = list(spectrum_matches) + self.spectrum_ids = set() + self.target_owned_spectrum_ids = set() + self.match_type_groups = self._collect(self.spectrum_matches) + self.exclusive_match_groups = self._exclusive() + + def __getitem__(self, key): + return self.exclusive_match_groups[key] + + def __iter__(self): + return iter(self.exclusive_match_groups.items()) + + def _by_scan_id(self): + acc = [] + for by_scan in collectiontools.groupby(self.spectrum_matches, lambda x: x.scan.id).values(): + scan = by_scan[0].scan + self.spectrum_ids.add(scan.scan_id) + ss = MultiScoreSpectrumSolutionSet(scan, by_scan) + ss.sort() + acc.append(ss) + acc.sort(key=lambda x: x.scan.id) + return acc + + def _collect( + self, spectrum_matches: List[MultiScoreSpectrumMatch] + ) -> Dict[StructureClassification, List[MultiScoreSpectrumSolutionSet]]: + + match_type_getter = attrgetter('match_type') + groups = collectiontools.groupby(spectrum_matches, match_type_getter) + by_scan_groups = {} + for group, members in groups.items(): + acc = [] + for by_scan in collectiontools.groupby(members, lambda x: x.scan.id).values(): + scan = by_scan[0].scan + self.spectrum_ids.add(scan.scan_id) + ss = MultiScoreSpectrumSolutionSet(scan, by_scan) + ss.sort() + acc.append(ss) + acc.sort(key=lambda x: x.scan.id) + by_scan_groups[group] = acc + return by_scan_groups + + def _exclusive( + self, score_getter: Callable[[MultiScoreSpectrumMatch], float] = None, min_value: float = 0 + ) -> DefaultDict[StructureClassification, List[MultiScoreSpectrumMatch]]: + if score_getter is None: + score_getter = attrgetter('score') + groups = collectiontools.groupby( + self.spectrum_matches, lambda x: x.scan.id) + by_match_type = defaultdict(list) + for scan_id, members in groups.items(): + top_match = max(members, key=score_getter) + top_score = score_getter(top_match) + seen = set() + for match in members: + if (isclose(top_score, score_getter(match)) and score_getter(match) > min_value + and match.match_type not in seen): + seen.add(match.match_type) + by_match_type[match.match_type].append(match) + if match.match_type == StructureClassification.target_peptide_target_glycan: + self.target_owned_spectrum_ids.add(scan_id) + for _group_label, matches in by_match_type.items(): + matches.sort(key=lambda x: (x.scan.id, score_getter(x))) + return by_match_type + + @property + def target_matches(self) -> List[MultiScoreSpectrumMatch]: + try: + return list( + filter( + lambda x: x.scan.id in self.target_owned_spectrum_ids, + self.match_type_groups[StructureClassification.target_peptide_target_glycan] + ) + ) + # return self.match_type_groups[StructureClassification.target_peptide_target_glycan] + except KeyError: + return [] + + @property + def decoy_matches(self) -> List[MultiScoreSpectrumMatch]: + try: + return self.match_type_groups[StructureClassification.decoy_peptide_target_glycan] + except KeyError: + return [] + + def target_count(self): + return len(self.target_matches) + + def decoy_count(self): + return len(self.decoy_matches) + + +class JournalSetLoader(TaskBase): + """"""A helper class to load a list of journal file fragments + into a single cohesive result, as from a previously compiled + analysis's bundled journal file shards. + """""" + + journal_files: List[Union[BinaryIO, os.PathLike, str]] + journal_reader_args: Dict[str, Any] + scan_loader: Union['RandomAccessScanSource', ScanInformationLoader] + mass_shift_map: Dict[str, MassShiftBase] + solutions: List[MultiScoreSpectrumSolutionSet] + + @classmethod + def from_analysis(cls, analysis: Union[""Analysis"", ""AnalysisDeserializer""], + scan_loader: Optional['RandomAccessScanSource']=None, + stub_wrapping: bool=True, + score_set_type: Optional[Type[ScoreSet]]=None, + **journal_reader_args): + from glycresoft.serialize import AnalysisDeserializer + if isinstance(analysis, AnalysisDeserializer): + analysis = analysis.analysis + mass_shift_map = { + m.name: m for m in analysis.parameters['mass_shifts']} + if scan_loader is None: + scan_loader = ProcessedMSFileLoader( + analysis.parameters['sample_path']) + if stub_wrapping: + stub_loader = ScanInformationLoader(scan_loader) + else: + stub_loader = scan_loader + if score_set_type is None: + score_set_type = analysis.parameters[ + 'tandem_scoring_model'].get_score_set_type() + return cls([f.open(raw=True) for f in analysis.files], stub_loader, mass_shift_map, + score_set_type=score_set_type, **journal_reader_args) + + def __init__(self, journal_files, scan_loader, mass_shift_map=None, **journal_reader_args): + if mass_shift_map is None: + mass_shift_map = {Unmodified.name: Unmodified} + self.journal_files = journal_files + self.journal_reader_args = journal_reader_args + self.scan_loader = scan_loader + self.mass_shift_map = mass_shift_map + self.solutions = [] + + def load(self): + n = len(self.journal_files) + for i, journal_path in enumerate(self.journal_files, 1): + self.log(""... Reading Journal Shard %s, %d/%d"" % + (journal_path, i, n)) + self._load_identifications_from_journal(journal_path, self.solutions) + self.log(""Partitioning Spectrum Matches..."") + return SolutionSetGrouper(self.solutions) + + def __iter__(self): + if not self.solutions: + self.load() + return iter(self.solutions) + + def _load_identifications_from_journal(self, journal_path: Union[BinaryIO, os.PathLike, str], + accumulator: Optional[List[MultiScoreSpectrumSolutionSet]]=None): + if accumulator is None: + accumulator = [] + reader = enumerate( + JournalFileReader( + journal_path, + scan_loader=self.scan_loader, + mass_shift_map=self.mass_shift_map, + **self.journal_reader_args), + len(accumulator)) + i = float(len(accumulator)) + should_log = False + for i, sol in reader: + if i % 100000 == 0: + should_log = True + if should_log: + self.log(""... %d Solutions Loaded"" % (i, )) + should_log = False + accumulator.append(sol) + return accumulator +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/dynamic_generation/peptide_graph.py",".py","10693","264","from typing import Dict, List, Optional, Sequence, Set, Tuple, Union +from dataclasses import dataclass, field + +import numpy as np + +from glycresoft.chromatogram_tree.mass_shift import MassShift, Unmodified +from glycresoft.structure.denovo import Path +from glycresoft.structure.scan import ScanStub +from glycresoft.structure.structure_loader import FragmentCachingGlycopeptide + +from ms_deisotope import isotopic_shift +from ms_deisotope.data_source import ProcessedScan + +from glycresoft.tandem.oxonium_ions import ( + OxoniumIndex, + SignatureSpecification, + gscore_scanner, + single_signatures, + compound_signatures +) + +from glycresoft.database.mass_collection import NeutralMassDatabase, MassObject + +from ..core_search import GlycanCombinationRecord, IndexedGlycanFilteringPeptideMassEstimator, CoreMotifFinder + +from .search_space import PeptideMassFilterBase + + +@dataclass +class PeptideMassNode: + peptide_mass: float + mass_shift: float + delta_mass: float + scan_id: str + glycan_score: float + + +@dataclass(frozen=True) +class PeptideEdge: + structure: FragmentCachingGlycopeptide + nodes: Tuple['SpectrumNode', 'SpectrumNode'] = field(hash=False) + similarity: float = field(compare=False, hash=False, default=0.0) + coverage: float = field(compare=False, hash=False, default=0.0) + + +@dataclass +class SpectrumNode: + scan: Union[ProcessedScan, ScanStub] + precursor_mass: float + peptide_masses: NeutralMassDatabase[PeptideMassNode] + signatures: Dict[SignatureSpecification, float] + oxonium_score: float + + @property + def scan_id(self): + return self.scan.id + + def load(self): + if isinstance(self.scan, ScanStub): + self.scan = self.scan.convert() + return self + + def unload(self): + if isinstance(self.scan, ProcessedScan): + self.scan = ScanStub(self.scan.precursor_information, self.scan.source) + return self + + @property + def deconvoluted_peak_set(self): + return self.load().deconvoluted_peak_set + + def overlaps(self, other: 'SpectrumNode') -> List[Tuple[PeptideMassNode, PeptideMassNode]]: + return intersecting_peptide_masses(self.peptide_masses, other.peptide_masses) + + +@dataclass +class IdentifiedSpectrumNode(SpectrumNode): + structure: FragmentCachingGlycopeptide + + +# Glycan averagose mass +AVERAGE_MONOMER_MASS: float = 185.5677185226898 + + +def score_path(path: Path, delta_mass: float) -> float: + n = delta_mass / AVERAGE_MONOMER_MASS + k = 2.0 + d = np.log(n) * n / k + return np.log10([p.intensity for p in path.peaks]).sum() / d + + +def merge_peptide_nodes_database_denovo(database_nodes: List[PeptideMassNode], + denovo_nodes: List[PeptideMassNode], error_tolerance: float=5e-6) -> List[PeptideMassNode]: + accumulator = [] + + db_i = 0 + denovo_i = 0 + db_n = len(database_nodes) + denovo_n = len(denovo_nodes) + + while db_i < db_n and denovo_i < denovo_n: + db_node = database_nodes[db_i] + denovo_node = denovo_nodes[denovo_i] + if abs(db_node.peptide_mass - denovo_node.peptide_mass) / denovo_node.peptide_mass <= error_tolerance: + accumulator.append(db_node) + db_i += 1 + denovo_i += 1 + elif db_node.peptide_mass < denovo_node.peptide_mass: + accumulator.append(db_node) + db_i += 1 + else: + accumulator.append(denovo_node) + denovo_i += 1 + + accumulator.extend(denovo_nodes[denovo_i:]) + accumulator.extend(database_nodes[db_i:]) + return accumulator + + +def intersecting_peptide_masses(query_nodes: Sequence[PeptideMassNode], + reference_nodes: Sequence[PeptideMassNode], + error_tolerance: float=5e-6) -> List[Tuple[PeptideMassNode, PeptideMassNode]]: + accumulator = [] + + query_i = 0 + reference_i = 0 + query_n = len(query_nodes) + reference_n = len(reference_nodes) + + checkpoint = None + + while query_i < query_n and reference_i < reference_n: + query_node = query_nodes[query_i] + reference_node = reference_nodes[reference_i] + if abs(query_node.peptide_mass - reference_node.peptide_mass) / reference_node.peptide_mass <= error_tolerance: + accumulator.append((query_node, reference_node)) + if checkpoint is None: + checkpoint = reference_i + reference_i += 1 + elif query_node.peptide_mass < reference_node.peptide_mass: + if checkpoint is not None and query_i < (query_n - 1) and abs(query_node.peptide_mass - query_nodes[query_i + 1].peptide_mass) / query_node.peptide_mass < error_tolerance: + reference_i = checkpoint + checkpoint = None + query_i += 1 + else: + reference_i += 1 + return accumulator + + +class PeptideGraphBuilder(PeptideMassFilterBase): + motif_finder: CoreMotifFinder + signatures: Dict[SignatureSpecification, float] + + def __init__(self, glycan_compositions, product_error_tolerance=0.00002, glycan_score_threshold=0.1, + min_fragments=2, peptide_masses_per_scan=100, probing_range_for_missing_precursors=3, + trust_precursor_fits=True, fragment_weight=0.56, core_weight=1.42, oxonium_ion_index=None, + signature_ion_index=None, oxonium_ion_threshold: float = 0.05, signatures: List[SignatureSpecification]=None): + super().__init__(glycan_compositions, product_error_tolerance, glycan_score_threshold, min_fragments, + peptide_masses_per_scan, probing_range_for_missing_precursors, trust_precursor_fits, + fragment_weight, core_weight, oxonium_ion_index, signature_ion_index, oxonium_ion_threshold) + if signatures is None: + signatures = signature_ion_index.signatures if signature_ion_index is not None else list( + single_signatures.keys()) + self.motif_finder = CoreMotifFinder(self.monosaccharides, self.product_error_tolerance) + self.signatures = signatures + + def collect_denovo_peptide_nodes(self, scan: ProcessedScan, mass_shifts: Optional[List[MassShift]]=None): + if mass_shifts is None: + mass_shifts = [Unmodified] + if not scan.precursor_information.defaulted and self.trust_precursor_fits: + probe = 0 + else: + probe = self.probing_range_for_missing_precursors + precursor_mass = scan.precursor_information.neutral_mass + nodes = [] + for i in range(probe + 1): + neutron_shift = self.neutron_shift * i + for mass_shift in mass_shifts: + mass_shift_mass = mass_shift.mass + intact_mass = precursor_mass - mass_shift_mass - neutron_shift + for (peptide_mass, paths) in self.motif_finder.estimate_peptide_mass( + scan, + topn=self.peptide_masses_per_scan, + mass_shift=mass_shift, + simplify=False, + query_mass=precursor_mass - neutron_shift, + ): + + if len(paths[0].peaks) < (self.min_fragments + 1): + continue + + delta_mass = intact_mass - peptide_mass + nodes.append( + PeptideMassNode(peptide_mass, mass_shift, delta_mass, + scan.id, score_path(paths[0], delta_mass)) + ) + nodes.sort(key=lambda x: x.peptide_mass) + return nodes + + def collect_database_peptide_nodes(self, scan: ProcessedScan, mass_shifts: Optional[List[MassShift]]=None): + if mass_shifts is None: + mass_shifts = [Unmodified] + if not scan.precursor_information.defaulted and self.trust_precursor_fits: + probe = 0 + else: + probe = self.probing_range_for_missing_precursors + precursor_mass = scan.precursor_information.neutral_mass + nodes = [] + for i in range(probe + 1): + neutron_shift = self.neutron_shift * i + for mass_shift in mass_shifts: + mass_shift_mass = mass_shift.mass + intact_mass = precursor_mass - mass_shift_mass - neutron_shift + for peptide_mass_pred in self.peptide_mass_predictor.estimate_peptide_mass( + scan, + topn=self.peptide_masses_per_scan, + mass_shift=mass_shift, + threshold=self.glycan_score_threshold, + min_fragments=self.min_fragments, + simplify=False, + query_mass=precursor_mass - neutron_shift, + ): + peptide_mass = peptide_mass_pred.peptide_mass + nodes.append( + PeptideMassNode(peptide_mass, mass_shift, intact_mass - peptide_mass, scan.id, peptide_mass_pred.score) + ) + nodes.sort(key=lambda x: x.peptide_mass) + return nodes + + def handle_scan(self, scan: ProcessedScan, mass_shifts: Optional[List[MassShift]] = None): + if mass_shifts is None: + mass_shifts = [Unmodified] + nodes = self.collect_database_peptide_nodes(scan, mass_shifts) + nodes.sort(key=lambda x: x.peptide_mass) + denovo_nodes = self.collect_denovo_peptide_nodes(scan, mass_shifts) + denovo_nodes.sort(key=lambda x: x.peptide_mass) + nodes = merge_peptide_nodes_database_denovo( + nodes, denovo_nodes, self.product_error_tolerance) + signature_intensities = {} + if len(scan.deconvoluted_peak_set) > 0: + base_peak_intensity: float = scan.base_peak.deconvoluted().intensity + else: + base_peak_intensity: float = 1.0 + for sig in self.signatures: + peak = sig.peak_of(scan.deconvoluted_peak_set, self.product_error_tolerance) + if peak is not None: + signature_intensities[sig] = peak.intensity / base_peak_intensity + else: + signature_intensities[sig] = 0.0 + oxonium_score = gscore_scanner(scan.deconvoluted_peak_set) + return SpectrumNode( + scan, + scan.precursor_information.neutral_mass, + NeutralMassDatabase(nodes, lambda x: x.peptide_mass), + signature_intensities, + oxonium_score + ) + + +_PeptideMassNode = PeptideMassNode +_intersecting_peptide_masses = intersecting_peptide_masses + +from glycresoft._c.tandem.peptide_graph import PeptideMassNode, intersecting_peptide_masses +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/dynamic_generation/workflow.py",".py","32405","788","import os +import multiprocessing +import threading +import ctypes +import datetime +import zlib +import pickle + +from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, OrderedDict +from multiprocessing.managers import SyncManager +from queue import Queue + + + +from ms_deisotope.output.common import LCMSMSQueryInterfaceMixin +from ms_deisotope.data_source import ProcessedRandomAccessScanSource + +from glycresoft import serialize +from glycresoft.serialize.hypothesis.hypothesis import GlycopeptideHypothesis + + +from glycresoft.tandem.spectrum_match.solution_set import MultiScoreSpectrumSolutionSet +from glycresoft.tandem.spectrum_match.spectrum_match import MultiScoreSpectrumMatch, SpectrumMatch + +from glycresoft.task import ( + TaskBase, Pipeline, + TaskExecutionSequence, + make_shared_memory_manager, + IPCLoggingManager, LoggingHandlerToken) + +from glycresoft.chromatogram_tree import Unmodified, MassShift + +from glycresoft.structure import ScanStub + +from glycresoft.database import disk_backed_database, mass_collection +from glycresoft.structure.structure_loader import PeptideDatabaseRecord +from glycresoft.structure.scan import ScanInformationLoader +from glycresoft.composition_distribution_model.site_model import ( + GlycoproteomePriorAnnotator) + +from glycresoft.tandem.oxonium_ions import OxoniumIndex, SignatureIonIndex, single_signatures, compound_signatures + +from glycresoft.chromatogram_tree.chromatogram import Chromatogram, GlycopeptideChromatogram +from ...chromatogram_mapping import ( + ChromatogramMSMSMapper, + TandemAnnotatedChromatogram, + TandemSolutionsWithoutChromatogram +) +from ...temp_store import TempFileManager +from ...spectrum_evaluation import group_by_precursor_mass +from ...spectrum_match import SpectrumMatchClassification +from ...workflow import SearchEngineBase + +from ..scoring import LogIntensityScorer, GlycopeptideSpectrumMatcherBase + +from .journal import ( + JournalFileWriter, + JournalFileReader, + JournalingConsumer, + SolutionSetGrouper) + +from .search_space import ( + PeptideGlycosylator, + PredictiveGlycopeptideSearch, + GlycanCombinationRecord, + StructureClassification) + +from .searcher import ( + SpectrumBatcher, + BatchMapper, + SemaphoreBoundMatcherExecutor, + SemaphoreBoundMapperExecutor) + +from .multipart_fdr import GlycopeptideFDREstimator, GlycopeptideFDREstimationStrategy + + +def make_memory_database_proxy_resolver(path, n_glycan=None, o_glycan=None, hypothesis_id=1): + if n_glycan is None or o_glycan is None: + config = _determine_database_contents(path, hypothesis_id) + if o_glycan is None: + o_glycan = config['o_glycan'] + if n_glycan is None: + n_glycan = config['n_glycan'] + loader = PeptideDatabaseProxyLoader(path, n_glycan, o_glycan, hypothesis_id) + # Make it possible to load the session here without loading the peptides + proxy = mass_collection.MassCollectionProxy( + loader, loader.session_resolver, hypothesis_id, loader.hypothesis_resolver) + return proxy + + +def make_disk_backed_peptide_database(path, hypothesis_id=1, **kwargs): + peptide_db = disk_backed_database.PeptideDiskBackedStructureDatabase( + path, cache_size=100, hypothesis_id=hypothesis_id) + peptide_db = mass_collection.TransformingMassCollectionAdapter( + peptide_db, PeptideDatabaseRecord.from_record) + return peptide_db + + +class FetchManyIterator(object): + def __init__(self, cursor, batch_size=1000000): + self.cursor = cursor + self.batch_size = batch_size + + def __iter__(self): + result_set = self.cursor.fetchmany(self.batch_size) + while result_set: + for x in result_set: + yield x + result_set = self.cursor.fetchmany(self.batch_size) + + +class PeptideDatabaseProxyLoader(TaskBase): + path: os.PathLike + n_glycan: bool + o_glycan: bool + hypothesis_id: int + + def __init__(self, path, n_glycan=True, o_glycan=True, hypothesis_id=1): + self.path = path + self.n_glycan = n_glycan + self.o_glycan = o_glycan + self.hypothesis_id = hypothesis_id + self._source_database = None + + @staticmethod + def determine_database_glycan_types(path, hypothesis_id=1): + return _determine_database_contents(path, hypothesis_id=hypothesis_id) + + @property + def source_database(self): + if self._source_database is None: + self._source_database = disk_backed_database.PeptideDiskBackedStructureDatabase( + self.path, hypothesis_id=self.hypothesis_id) + return self._source_database + + def session_resolver(self): + return self.source_database.session + + def hypothesis_resolver(self) -> GlycopeptideHypothesis: + return self.source_database.hypothesis + + def __reduce__(self): + return self.__class__, (self.path, self.n_glycan, self.o_glycan, self.hypothesis_id) + + def __call__(self): + db = disk_backed_database.PeptideDiskBackedStructureDatabase( + self.path, hypothesis_id=self.hypothesis_id) + if self.n_glycan and self.o_glycan: + filter_level = 0 + elif self.n_glycan: + filter_level = 1 + elif self.o_glycan: + filter_level = 2 + else: + raise ValueError(""Cannot determine how to filter peptides"") + peptides = [] + + self.log(""... Loading peptides from %r:%r"" % (self.path, self.hypothesis_id)) + start = datetime.datetime.now() + if filter_level == 1: + has_sites = db.has_protein_sites() + # This is an old database, have to do a full scan. + if not has_sites: + q = db.having_glycosylation_site() + iterator = FetchManyIterator(db.session.execute(q)) + else: + # Fast path for N-glycosylation sites which are marked, but where the bounds + # aren't precise so the if statements are still needed. + q = db.spanning_n_glycosylation_site() + iterator = FetchManyIterator(db.session.execute(q)) + else: + q = db.having_glycosylation_site() + iterator = FetchManyIterator(db.session.execute(q)) + seen = set() + for r in iterator: + rec = PeptideDatabaseRecord.from_record(r) + if rec.id in seen: + self.log(""Converted Peptide %d more than once!"" % rec.id) + seen.add(rec.id) + if filter_level == 1 and rec.n_glycosylation_sites: + peptides.append(rec) + elif filter_level == 2 and rec.o_glycosylation_sites: + peptides.append(rec) + elif filter_level == 0 and rec.has_glycosylation_sites(): + peptides.append(rec) + db.session.remove() + PeptideDatabaseRecord.unshare_sites(peptides) + end = datetime.datetime.now() + elapsed = (end - start).total_seconds() + self.log(""... %0.2f seconds elapsed. Loaded %d peptides"" % (elapsed, len(peptides))) + mem_db = disk_backed_database.InMemoryPeptideStructureDatabase(peptides, db) + return mem_db + + +def _determine_database_contents(path, hypothesis_id=1): + db = disk_backed_database.PeptideDiskBackedStructureDatabase( + path, hypothesis_id=hypothesis_id) + glycan_classes = db.query( + serialize.GlycanCombination, + serialize.GlycanClass.name).join( + serialize.GlycanCombination.components).join( + serialize.GlycanComposition.structure_classes).group_by( + serialize.GlycanClass.name).all() + glycan_classes = { + pair[1] for pair in glycan_classes + } + n_glycan = serialize.GlycanTypes.n_glycan in glycan_classes + o_glycan = (serialize.GlycanTypes.o_glycan in glycan_classes or + serialize.GlycanTypes.gag_linker in glycan_classes) + return { + 'n_glycan': n_glycan, + 'o_glycan': o_glycan + } + + +def make_peptide_glycosylator(path, hypothesis_id: int = 1, target_peptide: bool=True) -> PeptideGlycosylator: + peptide_db = make_memory_database_proxy_resolver(path, hypothesis_id=hypothesis_id) + gp_hypothesis: GlycopeptideHypothesis = peptide_db.session.query( + GlycopeptideHypothesis).get(hypothesis_id) + + glycan_recs = GlycanCombinationRecord.from_hypothesis( + peptide_db.session, gp_hypothesis.glycan_hypothesis_id) + + generator = PeptideGlycosylator( + peptide_db, + glycan_recs, + default_structure_type=StructureClassification.target_peptide_target_glycan if target_peptide else + StructureClassification.decoy_peptide_target_glycan) + return generator + + +def make_predictive_glycopeptide_search(path, hypothesis_id: int=1, + target_peptide: bool=True, + product_error_tolerance: float=2e-5, + glycan_score_threshold: float=1.0, + probing_range_for_missing_precursors: int=3, + peptide_masses_per_scan: int=100, + oxonium_ion_threshold: float=0.05) -> PredictiveGlycopeptideSearch: + + generator = make_peptide_glycosylator( + path, hypothesis_id=hypothesis_id, target_peptide=target_peptide) + + if glycan_score_threshold > 0: + min_fragments = 2 + else: + min_fragments = 0 + + predictive_search = PredictiveGlycopeptideSearch( + generator, + product_error_tolerance=product_error_tolerance, + glycan_score_threshold=glycan_score_threshold, + min_fragments=min_fragments, + probing_range_for_missing_precursors=probing_range_for_missing_precursors, + trust_precursor_fits=True, + peptide_masses_per_scan=peptide_masses_per_scan, + oxonium_ion_threshold=oxonium_ion_threshold) + + return predictive_search + + +class MultipartGlycopeptideIdentifier(SearchEngineBase): + precursor_error_tolerance: float + product_error_tolerance: float + batch_size: int + fdr_estimation_strategy: GlycopeptideFDREstimationStrategy + scorer_type: Type[GlycopeptideSpectrumMatcherBase] + evaluation_kwargs: Dict[str, Any] + mass_shifts: List[MassShift] + probing_range_for_missing_precursors: int + trust_precursor_fits: bool + glycan_score_threshold: float + oxonium_threshold: float + peptide_masses_per_scan: int + + ipc_manager: SyncManager + file_manager: TempFileManager + journal_path: str + journal_path_collection: List[str] + + target_peptide_db: mass_collection.SearchableMassCollectionWrapper + decoy_peptide_db: mass_collection.SearchableMassCollectionWrapper + glycosylation_site_models_path: str + + cache_seeds: Any + + tandem_scans: List[ScanStub] + scan_loader: Union[ProcessedRandomAccessScanSource, + LCMSMSQueryInterfaceMixin] + + n_processes: int + + def __init__(self, + tandem_scans, + scorer_type, + target_peptide_db, + decoy_peptide_db, + scan_loader, + mass_shifts=None, + n_processes=6, + evaluation_kwargs=None, + ipc_manager=None, + file_manager=None, + probing_range_for_missing_precursors=3, + trust_precursor_fits=True, + glycan_score_threshold=1.0, + peptide_masses_per_scan=60, + fdr_estimation_strategy=None, + glycosylation_site_models_path=None, + cache_seeds=None, + oxonium_threshold: float=0.05, + **kwargs): + if fdr_estimation_strategy is None: + fdr_estimation_strategy = GlycopeptideFDREstimationStrategy.multipart_gamma_gaussian_mixture + if scorer_type is None: + scorer_type = LogIntensityScorer + if evaluation_kwargs is None: + evaluation_kwargs = {} + if mass_shifts is None: + mass_shifts = [] + if Unmodified not in mass_shifts: + mass_shifts = [Unmodified] + list(mass_shifts) + if file_manager is None: + file_manager = TempFileManager() + elif isinstance(file_manager, str): + file_manager = TempFileManager(file_manager) + if ipc_manager is None: + ipc_manager = make_shared_memory_manager() + if isinstance(target_peptide_db, str): + target_peptide_db = self.build_default_disk_backed_db_wrapper(target_peptide_db) + if isinstance(decoy_peptide_db, str): + decoy_peptide_db = self.build_default_disk_backed_db_wrapper(decoy_peptide_db) + + self.tandem_scans = tandem_scans + self.scan_loader = scan_loader + + self.scorer_type = scorer_type + self.fdr_estimation_strategy = GlycopeptideFDREstimationStrategy[fdr_estimation_strategy] + + self.target_peptide_db = target_peptide_db + self.decoy_peptide_db = decoy_peptide_db + + self.probing_range_for_missing_precursors = probing_range_for_missing_precursors + self.trust_precursor_fits = trust_precursor_fits + + self.glycan_score_threshold = glycan_score_threshold + self.peptide_masses_per_scan = peptide_masses_per_scan + + self.precursor_error_tolerance = 5e-6 + self.product_error_tolerance = 2e-5 + self.batch_size = 1000 + + self.mass_shifts = mass_shifts + + self.evaluation_kwargs = evaluation_kwargs + self.evaluation_kwargs.update(kwargs) + + self.n_processes = n_processes + self.ipc_manager = ipc_manager + self.cache_seeds = cache_seeds + + self.file_manager = file_manager + self.journal_path = self.file_manager.get('glycopeptide-match-journal') + self.journal_path_collection = [] + self.glycosylation_site_models_path = glycosylation_site_models_path + + self.oxonium_threshold = oxonium_threshold + + @classmethod + def build_default_disk_backed_db_wrapper(cls, path, **kwargs): + peptide_db = make_disk_backed_peptide_database(path, **kwargs) + return peptide_db + + @classmethod + def build_default_memory_backed_db_wrapper(cls, path, **kwargs): + peptide_db = make_memory_database_proxy_resolver(path, **kwargs) + return peptide_db + + def build_scan_groups(self): + if self.tandem_scans is None: + pinfos = self.scan_loader.precursor_information() + self.tandem_scans = [ScanStub(pinfo, self.scan_loader) for pinfo in pinfos] + groups = group_by_precursor_mass(self.tandem_scans, 1e-4) + return groups + + def build_predictive_searchers(self): + glycan_combinations = GlycanCombinationRecord.from_hypothesis( + self.target_peptide_db.session, self.target_peptide_db.hypothesis_id) + + if self.glycan_score_threshold > 0: + min_fragments = 2 + else: + min_fragments = 0 + + glycan_prior_model = None + if self.glycosylation_site_models_path is not None: + self.log(""Loading glycosylation site scoring models from %r"" % self.glycosylation_site_models_path) + glycan_prior_model = GlycoproteomePriorAnnotator.load( + self.target_peptide_db.session, + self.decoy_peptide_db.session, + open(self.glycosylation_site_models_path, 'rt')) + + expand_combinatorics = True + + generator = PeptideGlycosylator( + self.target_peptide_db, + glycan_combinations, + default_structure_type=StructureClassification.target_peptide_target_glycan, + glycan_prior_model=glycan_prior_model, + expand_combinatorics=expand_combinatorics + ) + target_predictive_search = PredictiveGlycopeptideSearch( + generator, + product_error_tolerance=self.product_error_tolerance, + glycan_score_threshold=self.glycan_score_threshold, + min_fragments=min_fragments, + probing_range_for_missing_precursors=self.probing_range_for_missing_precursors, + trust_precursor_fits=self.trust_precursor_fits, + peptide_masses_per_scan=self.peptide_masses_per_scan, + oxonium_ion_threshold=self.oxonium_threshold) + + generator = PeptideGlycosylator( + self.decoy_peptide_db, + glycan_combinations, + default_structure_type=StructureClassification.decoy_peptide_target_glycan, + glycan_prior_model=glycan_prior_model, + expand_combinatorics=expand_combinatorics + ) + decoy_predictive_search = PredictiveGlycopeptideSearch( + generator, + product_error_tolerance=self.product_error_tolerance, + glycan_score_threshold=self.glycan_score_threshold, + min_fragments=min_fragments, + probing_range_for_missing_precursors=self.probing_range_for_missing_precursors, + trust_precursor_fits=self.trust_precursor_fits, + peptide_masses_per_scan=self.peptide_masses_per_scan, + oxonium_ion_threshold=self.oxonium_threshold) + return target_predictive_search, decoy_predictive_search + + def run_branching_identification_pipeline(self, scan_groups): + (target_predictive_search, + decoy_predictive_search) = self.build_predictive_searchers() + + spectrum_batcher = SpectrumBatcher( + scan_groups, + Queue(10), + max_scans_per_workload=self.batch_size) + + spectrum_batcher.start(daemon=True) + + common_queue = multiprocessing.Queue(5) + label_to_batch_queue = { + ""target"": common_queue, + ""decoy"": common_queue, + } + + ipc_logger = IPCLoggingManager() + + mapping_batcher = BatchMapper( + # map labels to be loaded in the mapper executor to avoid repeatedly + # serializing the databases. + [ + ('target', 'target'), + ('decoy', 'decoy') + ], + spectrum_batcher.out_queue, + label_to_batch_queue, + spectrum_batcher.done_event, + precursor_error_tolerance=self.precursor_error_tolerance, + mass_shifts=self.mass_shifts) + mapping_batcher.done_event = multiprocessing.Event() + mapping_batcher.start(daemon=True) + + execution_branches: List['IdentificationWorker'] = [] + scorer_type_payload = zlib.compress(pickle.dumps(self.scorer_type, -1), 9) + predictive_search_payload = zlib.compress( + pickle.dumps( + (target_predictive_search, decoy_predictive_search), -1), 9) + + for i in range(self.n_processes): + journal_path_for = self.file_manager.get('glycopeptide-match-journal-%d' % (i)) + self.journal_path_collection.append(journal_path_for) + done_event_for = multiprocessing.Event() + branch = IdentificationWorker( + ""IdentificationWorker-%d"" % i, + self.ipc_manager.address, + common_queue, + mapping_batcher.done_event, + journal_path_for, + done_event_for, + self.scan_loader, + target_predictive_search=predictive_search_payload, + decoy_predictive_search=None, + scorer_type=scorer_type_payload, + evaluation_kwargs=self.evaluation_kwargs, + error_tolerance=self.product_error_tolerance, + cache_seeds=self.cache_seeds, + mass_shifts=self.mass_shifts, + log_handler=ipc_logger.sender(), + ) + execution_branches.append(branch) + # Clear these big blobs from the parent process, we no longer need them + del scorer_type_payload + del predictive_search_payload + pipeline = Pipeline([ + spectrum_batcher, + mapping_batcher, + ] + execution_branches) + + for branch in execution_branches: + try: + branch.start(process=True, daemon=True) + except Exception as err: + self.log(f""... Error {err} occurred during worker startup"") + + # At this point, all the components have started already, but + # to let the Pipeline object setup its ""started"" invariants, call + # `start` again, which is a no-op for already-started task sequences. + pipeline.start(daemon=True) + pipeline.join() + ipc_logger.stop() + had_error = pipeline.error_occurred() + if had_error: + message = ""%d unrecoverable error%s occured during search!"" % ( + had_error, 's' if had_error > 1 else '') + pipeline.stop() + common_queue.close() + common_queue.cancel_join_thread() + self.log(""Terminating search pipeline"") + for branch in execution_branches: + branch.kill_process() + raise Exception(message) + total = 0 + for branch in execution_branches: + total += branch.results_processed.value + return total + + def _load_identifications_from_journal( + self, journal_path: os.PathLike, + total_solutions_count: int, + accumulator: Optional[List[MultiScoreSpectrumMatch]]=None) -> List[MultiScoreSpectrumMatch]: + if accumulator is None: + accumulator = [] + + with self.scan_loader.toggle_peak_loading(): + reader = enumerate(JournalFileReader( + journal_path, + scan_loader=ScanInformationLoader(self.scan_loader), + mass_shift_map={m.name: m for m in self.mass_shifts}, + score_set_type=self.scorer_type.get_score_set_type()), + len(accumulator)) + i = float(len(accumulator)) + try: + # Get the nearest progress checkpoint + last = round(i / total_solutions_count, 1) + except ZeroDivisionError: + last = 0.1 + should_log = False + for i, sol in reader: + if i * 1.0 / total_solutions_count > last: + should_log = True + last += 0.1 + elif i % 100000 == 0 and i > 1: + should_log = True + if should_log: + self.log(""... %d/%d Solutions Loaded (%0.2f%%)"" % ( + i, total_solutions_count, i * 100.0 / total_solutions_count)) + should_log = False + accumulator.append(sol) + return accumulator + + def search(self, precursor_error_tolerance: float=1e-5, + simplify: bool=True, + batch_size: int=500, **kwargs) -> SolutionSetGrouper: + self.evaluation_kwargs.update(kwargs) + self.product_error_tolerance = self.evaluation_kwargs.pop('error_tolerance', 2e-5) + self.precursor_error_tolerance = precursor_error_tolerance + self.batch_size = batch_size + + self.log(""Building Scan Groups..."") + scan_groups = self.build_scan_groups() + self.log(""{:d} Scans, {:d} Scan Groups"".format( + len(self.tandem_scans), len(scan_groups))) + self.log(""Running Identification Pipeline..."") + start_time = datetime.datetime.now() + total_solutions_count = self.run_branching_identification_pipeline(scan_groups) + end_time = datetime.datetime.now() + self.log(""Database Search Complete, %s Elapsed"" % (end_time - start_time)) + self.log(""Loading Spectrum Matches From Journal..."") + solutions = [] + n = len(self.journal_path_collection) + for i, journal_path in enumerate(self.journal_path_collection, 1): + self.log(""... Reading Journal Shard %s, %d/%d"" % (journal_path, i, n)) + self._load_identifications_from_journal(journal_path, total_solutions_count, solutions) + self.log(""Partitioning Spectrum Matches..."") + groups = SolutionSetGrouper(solutions) + return groups + + def estimate_fdr(self, glycopeptide_spectrum_match_groups: SolutionSetGrouper, + *args, **kwargs) -> Tuple[SolutionSetGrouper, GlycopeptideFDREstimator]: + keys = [SpectrumMatchClassification[i] for i in range(4)] + g = glycopeptide_spectrum_match_groups + self.log(""Running Target Decoy Analysis with %d targets and %d/%d/%d decoys"" % ( + len(g[keys[0]]), len(g[keys[1]]), len(g[keys[2]]), len(g[keys[3]]))) + peptide_fdr_estimator = self.scorer_type.get_fdr_model_for_dimension('peptide') + estimator = GlycopeptideFDREstimator( + glycopeptide_spectrum_match_groups, + self.fdr_estimation_strategy, + peptide_fdr_estimator=peptide_fdr_estimator) + groups: SolutionSetGrouper = estimator.start() + self.log(""Rebuilding Targets"") + cache = {} + target_match_sets = groups.target_matches + n = len(target_match_sets) + for i, target_match_set in enumerate(target_match_sets): + if i % 10000 == 0 and i: + self.log(""... Rebuilt %d Targets (%0.2f%%)"" % (i, i * 100.0 / n)) + for target_match in target_match_set: + if target_match.target.id in cache: + target_match.target = cache[target_match.target.id] + else: + target_match.target = cache[target_match.target.id] = target_match.target.convert() + cache.clear() + return groups, estimator + + def map_to_chromatograms( + self, + chromatograms: List[Chromatogram], + tandem_identifications: List[MultiScoreSpectrumSolutionSet], + precursor_error_tolerance: float=1e-5, + threshold_fn: Callable[[SpectrumMatch], bool]=lambda x: x.q_value < 0.05, + entity_chromatogram_type: Type[GlycopeptideChromatogram]=GlycopeptideChromatogram + ) -> Tuple[List[TandemAnnotatedChromatogram], List[TandemSolutionsWithoutChromatogram]]: + self.log(""Mapping MS/MS Identifications onto Chromatograms"") + self.log(""%d Chromatograms"" % len(chromatograms)) + mapper = ChromatogramMSMSMapper( + chromatograms, precursor_error_tolerance, + self.scan_loader.convert_scan_id_to_retention_time) + self.log(""Assigning Solutions"") + mapper.assign_solutions_to_chromatograms(tandem_identifications) + self.log(""Distributing Orphan Spectrum Matches"") + mapper.distribute_orphans(threshold_fn=threshold_fn) + self.log(""Selecting Most Representative Matches"") + mapper.assign_entities(threshold_fn, entity_chromatogram_type=entity_chromatogram_type) + return mapper.chromatograms, mapper.orphans + + +class IdentificationWorker(TaskExecutionSequence): + name: str + ipc_manager_address: Union[str, Tuple[str, int]] + + input_batch_queue: multiprocessing.Queue + input_done_event: multiprocessing.Event + + done_event: multiprocessing.Event + + journal_path: os.PathLike + scan_loader: Union[ProcessedRandomAccessScanSource, + LCMSMSQueryInterfaceMixin] + + target_predictive_search: PredictiveGlycopeptideSearch + decoy_predictive_search: PredictiveGlycopeptideSearch + + n_processes: int + scorer_type: Type[GlycopeptideSpectrumMatcherBase] + + scorer_type: Type[GlycopeptideSpectrumMatcherBase] + evaluation_kwargs: Dict[str, Any] + error_tolerance: float + cache_seeds: Any + mass_shifts: List[MassShift] + + log_handler: LoggingHandlerToken + + def __init__(self, name, ipc_manager_address, input_batch_queue, input_done_event, + journal_path, done_event, + # Mapping Executor Parameters + scan_loader=None, target_predictive_search=None, decoy_predictive_search=None, + # Matching Executor Parameters + n_processes=1, scorer_type=None, evaluation_kwargs=None, error_tolerance=None, + cache_seeds=None, mass_shifts=None, + log_handler=None): + self.name = name + self.ipc_manager_address = ipc_manager_address + self.input_batch_queue = input_batch_queue + self.input_done_event = input_done_event + self.journal_path = journal_path + self.done_event = done_event + + # Mapping Executor + self.scan_loader = scan_loader + self.target_predictive_search = target_predictive_search + self.decoy_predictive_search = decoy_predictive_search + + # Matching Executor + self.n_processes = n_processes + self.scorer_type = scorer_type + self.evaluation_kwargs = evaluation_kwargs + self.error_tolerance = error_tolerance + self.cache_seeds = cache_seeds + self.mass_shifts = mass_shifts + self.results_processed = multiprocessing.Value(ctypes.c_uint64) + self.log_handler = log_handler + + def _get_repr_details(self): + props = [""name=%r"" % self.name, ""pid=%r"" % multiprocessing.current_process().pid] + return ', '.join(props) + + def _name_for_execution_sequence(self): + return self.name + + def run(self): + self.try_set_process_name(""glycresoft-identification"") + self.log_handler.add_handler() + ipc_manager = SyncManager(self.ipc_manager_address) + ipc_manager.connect() + lock = threading.RLock() + # Late loading of the compressed serialized scorer type to avoid balooning + # the parent process + if isinstance(self.scorer_type, (str, bytes)): + self.scorer_type = pickle.loads(zlib.decompress(self.scorer_type)) + if isinstance(self.target_predictive_search, (str, bytes)): + self.target_predictive_search, self.decoy_predictive_search = pickle.loads( + zlib.decompress(self.target_predictive_search)) + + oxonium_ion_index = OxoniumIndex() + oxonium_ion_index.build_index( + self.target_predictive_search.peptide_glycosylator.glycan_combinations, oxonium=True) + + signatures = list(single_signatures) + if self.evaluation_kwargs.get(""rare_signatures""): + signatures.extend(compound_signatures) + signature_index = SignatureIonIndex(signatures) + signature_index.build_index( + self.target_predictive_search.peptide_glycosylator.glycan_combinations) + + self.target_predictive_search.oxonium_ion_index = oxonium_ion_index + self.target_predictive_search.signature_ion_index = signature_index + self.decoy_predictive_search.oxonium_ion_index = oxonium_ion_index + self.decoy_predictive_search.signature_ion_index = signature_index + + mapping_executor = SemaphoreBoundMapperExecutor( + lock, + OrderedDict([ + ('target', self.target_predictive_search), + ('decoy', self.decoy_predictive_search) + ]), + self.scan_loader, + self.input_batch_queue, + Queue(5), + self.input_done_event, + ) + matching_executor = SemaphoreBoundMatcherExecutor( + lock, + mapping_executor.out_queue, + Queue(5), + mapping_executor.done_event, + scorer_type=self.scorer_type, + ipc_manager=ipc_manager, + n_processes=self.n_processes, + mass_shifts=self.mass_shifts, + evaluation_kwargs=self.evaluation_kwargs, + error_tolerance=self.error_tolerance, + cache_seeds=self.cache_seeds + ) + + journal_writer = JournalFileWriter( + self.journal_path, score_columns=self.scorer_type.get_score_set_type().field_names()) + journal_consumer = JournalingConsumer( + journal_writer, + matching_executor.out_queue, + matching_executor.done_event) + journal_consumer.done_event = self.done_event + + pipeline = Pipeline([ + mapping_executor, + matching_executor, + journal_consumer, + ]) + pipeline.start(daemon=True) + pipeline.join() + if pipeline.error_occurred(): + self.log(""An error occurred while executing %s"" % (self, )) + self.set_error_occurred() + journal_writer.close() + self.results_processed.value = journal_writer.solution_counter + self.log(""%s has finished. %d solutions calculated."" % + (self, journal_writer.solution_counter, )) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/dynamic_generation/__init__.py",".py","1048","27","from .search_space import ( + PeptideGlycosylator, GlycanCombinationRecord, + StructureClassification, glycopeptide_key_t, + GlycoformGeneratorBase, DynamicGlycopeptideSearchBase, + PredictiveGlycopeptideSearch, IterativeGlycopeptideSearch, + Record, Parser, IdKeyMaker) + +from .multipart_fdr import (GlycopeptideFDREstimationStrategy, GlycopeptideFDREstimator) + +from .workflow import ( + MultipartGlycopeptideIdentifier, PeptideDatabaseProxyLoader, + make_memory_database_proxy_resolver, make_disk_backed_peptide_database) + + +__all__ = [ + ""PeptideGlycosylator"", ""GlycanCombinationRecord"", + ""StructureClassification"", ""glycopeptide_key_t"", + ""GlycoformGeneratorBase"", ""DynamicGlycopeptideSearchBase"", + ""PredictiveGlycopeptideSearch"", ""IterativeGlycopeptideSearch"", + ""Record"", ""Parser"", 'IdKeyMaker', + + ""GlycopeptideFDREstimationStrategy"", ""GlycopeptideFDREstimator"", + + ""MultipartGlycopeptideIdentifier"", ""PeptideDatabaseProxyLoader"", + ""make_memory_database_proxy_resolver"", 'make_disk_backed_peptide_database', +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/dynamic_generation/search_space.py",".py","38249","989","import os +import operator +import logging +import struct +import ctypes + +from typing import Dict, List, Optional, Set + +from collections import namedtuple, defaultdict + +from glycopeptidepy import PeptideSequence, GlycosylationType +from glycopeptidepy.structure.glycan import GlycanCompositionWithOffsetProxy +from glycopeptidepy.structure.sequence import ( + _n_glycosylation, + _o_glycosylation, + _gag_linker_glycosylation, +) + +from glypy.structure.glycan_composition import FrozenMonosaccharideResidue +from glypy.utils.enum import EnumValue + +from ms_deisotope import isotopic_shift +from ms_deisotope.data_source import ProcessedScan + +from glycresoft.chromatogram_tree.mass_shift import MassShift +from glycresoft.serialize.hypothesis.glycan import GlycanTypes + +from glycresoft.task import LoggingMixin + +from glycresoft.chromatogram_tree import Unmodified + +from glycresoft.structure.lru import LRUMapping +from glycresoft.structure import ( + FragmentCachingGlycopeptide, + DecoyFragmentCachingGlycopeptide, + PeptideProteinRelation, +) +from glycresoft.structure.structure_loader import ( + CachingStubGlycopeptideStrategy, + PeptideDatabaseRecord, +) + +from glycresoft.tandem.oxonium_ions import ( + OxoniumIndex, + SignatureIonIndex, + SignatureIonIndexMatch, + gscore_scanner, +) + +from glycresoft.composition_distribution_model.site_model import GlycoproteomePriorAnnotator + +from glycresoft.database import intervals +from glycresoft.database.mass_collection import NeutralMassDatabase, SearchableMassCollection +from glycresoft.database.builder.glycopeptide.common import limiting_combinations + +from glycresoft.structure.enums import SpectrumMatchClassification as StructureClassification + +from ...workload import WorkloadManager +from ..core_search import GlycanCombinationRecord, IndexedGlycanFilteringPeptideMassEstimator + + +logger = logging.Logger(""glycresoft.dynamic_generation"") + + +debug_mode = bool(os.environ.get(""GLYCRESOFTDEBUG"")) + + +_glycopeptide_key_t = namedtuple( + ""glycopeptide_key"", + ( + ""start_position"", + ""end_position"", + ""peptide_id"", + ""protein_id"", + ""hypothesis_id"", + ""glycan_combination_id"", + ""structure_type"", + ""site_combination_index"", + ""glycosylation_type"", + ), +) + + +class glycopeptide_key_t_base(_glycopeptide_key_t): + __slot__ = () + + def copy(self, structure_type=None): + if structure_type is None: + structure_type = self.structure_type + return self._replace(structure_type=structure_type) + + def as_dict(self, stringify=False): + d = {} + for i, label in enumerate(self._fields): + d[label] = str(self[i]) if stringify else self[i] + return d + + +MonosaccharideResidues = Set[FrozenMonosaccharideResidue] +GlycanCombinationRecords = List[GlycanCombinationRecord] + +# try: +# from glycresoft._c.structure.structure_loader import glycopeptide_key as glycopeptide_key_t_base +# except ImportError: +# pass + +# The site_combination_index slot is necessary to distinguish alternative arrangements of +# the same combination of glycans on the same amino acid sequence. The placeholder value +# used for unassigned glycosite combination permutations, the maximum value that fits in +# an unsigned 4 byte integer (L signifier in struct spec). This means defines the upper +# limit on the number of distinct combinations that can be uniquely addressed is +# 2 ** 32 - 1 (4294967295). +# +# Note that the glycoform generators all use (circa 2018) :func:`~.limiting_combinations`, +# which only produces the first 100 iterations to avoid producing too many permutations of +# O-glycans. +placeholder_permutation = ctypes.c_uint32(-1).value + +TT = StructureClassification.target_peptide_target_glycan + + +class glycopeptide_key_t(glycopeptide_key_t_base): + __slots__ = () + + start_position: int + end_position: int + peptide_id: int + protein_id: int + hypothesis_id: int + glycan_combination_id: int + structure_type: EnumValue + site_combination_index: int + glycosylation_type: str + + struct_spec = struct.Struct(""!LLLLLLLL"") + + def serialize(self): + return self.struct_spec.pack(*self) + + @classmethod + def parse(cls, binary): + return cls(*cls.struct_spec.unpack(binary)) + + def to_decoy_glycan(self) -> ""glycopeptide_key_t"": + structure_type = self.structure_type + new_tp = StructureClassification[ + structure_type | StructureClassification.target_peptide_decoy_glycan + ] + return self.copy(new_tp) + + def is_decoy(self) -> bool: + return self.structure_type != 0 + + +CORE_TO_GLYCOSYLATION_TYPE = { + _n_glycosylation: GlycanTypes.n_glycan, + _o_glycosylation: GlycanTypes.o_glycan, + _gag_linker_glycosylation: GlycanTypes.gag_linker, +} + + +class GlycoformGeneratorBase(LoggingMixin): + glycan_combinations: NeutralMassDatabase[GlycanCombinationRecord] + _peptide_cache: LRUMapping + default_structure_type: StructureClassification + glycan_prior_model: GlycoproteomePriorAnnotator + expand_combinatorics: bool + + @classmethod + def from_hypothesis(cls, session, hypothesis_id, **kwargs): + """"""Build a glycan combination index from a :class:`~.GlycanHypothesis` + + Parameters + ---------- + session: :class:`DatabaseBoundOperation` + The database connection to use to load glycan combinations. + hypothesis_id: int + The id key of the :class:`~.GlycanHypothesis` to build from + + Returns + ------- + :class:`GlycoformGeneratorBase` + """""" + glycan_combinations = GlycanCombinationRecord.from_hypothesis(session, hypothesis_id) + return cls(glycan_combinations, **kwargs) + + def __init__( + self, + glycan_combinations, + cache_size=None, + default_structure_type=TT, + expand_combinatorics: bool = True, + *args, + **kwargs + ): + if not isinstance(glycan_combinations, SearchableMassCollection): + glycan_combinations = NeutralMassDatabase( + list(glycan_combinations), operator.attrgetter(""dehydrated_mass"") + ) + if cache_size is None: + cache_size = 2**15 + else: + cache_size = int(cache_size) + self.glycan_combinations = glycan_combinations + self._peptide_cache = LRUMapping(cache_size) + self._cache_hit = 0 + self._cache_miss = 0 + self.default_structure_type = default_structure_type + self.glycan_prior_model = kwargs.pop(""glycan_prior_model"", None) + self.expand_combinatorics = expand_combinatorics + super(GlycoformGeneratorBase, self).__init__(*args, **kwargs) + + def handle_glycan_combination( + self, + peptide_obj: PeptideSequence, + peptide_record: PeptideDatabaseRecord, + glycan_combination: GlycanCombinationRecord, + glycosylation_sites: List[int], + core_type: GlycosylationType, + ) -> List[""Record""]: + glycosylation_type = CORE_TO_GLYCOSYLATION_TYPE[core_type] + key = self._make_key(peptide_record, glycan_combination, glycosylation_type) + if key in self._peptide_cache: + self._cache_hit += 1 + return self._peptide_cache[key] + self._cache_miss += 1 + protein_relation = PeptideProteinRelation( + key.start_position, key.end_position, key.protein_id, key.hypothesis_id + ) + glycosylation_sites_unoccupied = set(glycosylation_sites) + for site in list(glycosylation_sites_unoccupied): + if peptide_obj[site][1]: + glycosylation_sites_unoccupied.remove(site) + + site_combinations = list( + limiting_combinations( + glycosylation_sites_unoccupied, + glycan_combination.count, + 100 if self.expand_combinatorics else 1 + ) + ) + + result_set = [None for i in site_combinations] + for i, site_set in enumerate(site_combinations): + glycoform = peptide_obj.clone(share_cache=False) + glycoform.id = key._replace(site_combination_index=i) + glycoform.glycan = GlycanCompositionWithOffsetProxy(glycan_combination.composition) + for site in site_set: + glycoform.add_modification(site, core_type.name) + glycoform.protein_relation = protein_relation + if self.glycan_prior_model is not None: + glycoform.glycan_prior = self.glycan_prior_model.score( + glycoform, key.structure_type + ) + result_set[i] = glycoform + result_set = Record.build(result_set) + self._peptide_cache[key] = result_set + return result_set + + def _make_key( + self, + peptide_record: PeptideDatabaseRecord, + glycan_combination: GlycanCombinationRecord, + glycosylation_type: str, + structure_type: StructureClassification = None, + ) -> glycopeptide_key_t: + if structure_type is None: + structure_type = self.default_structure_type + key = glycopeptide_key_t( + peptide_record.start_position, + peptide_record.end_position, + peptide_record.id, + peptide_record.protein_id, + peptide_record.hypothesis_id, + glycan_combination.id, + structure_type, + placeholder_permutation, + glycosylation_type, + ) + return key + + def handle_n_glycan(self, peptide_obj, peptide_record, glycan_combination): + if glycan_combination.size < 5: + return [] + return self.handle_glycan_combination( + peptide_obj, + peptide_record, + glycan_combination, + peptide_record.n_glycosylation_sites, + _n_glycosylation, + ) + + def handle_o_glycan(self, peptide_obj, peptide_record, glycan_combination): + return self.handle_glycan_combination( + peptide_obj, + peptide_record, + glycan_combination, + peptide_record.o_glycosylation_sites, + _o_glycosylation, + ) + + def handle_gag_linker(self, peptide_obj, peptide_record, glycan_combination): + return self.handle_glycan_combination( + peptide_obj, + peptide_record, + glycan_combination, + peptide_record.gagylation_sites, + _gag_linker_glycosylation, + ) + + def reset_cache(self, **kwargs): + self._cache_hit = 0 + self._cache_miss = 0 + self._peptide_cache.clear() + + def reset(self, **kwargs): + self.reset_cache(**kwargs) + + +class PeptideGlycosylator(GlycoformGeneratorBase): + peptides: NeutralMassDatabase + peptide_to_group_id: Dict[int, List[int]] + + def __init__( + self, + peptide_records, + glycan_combinations, + cache_size=2**16, + default_structure_type=TT, + *args, + **kwargs + ): + super(PeptideGlycosylator, self).__init__( + glycan_combinations, + default_structure_type=default_structure_type, + cache_size=cache_size, + *args, + **kwargs + ) + if not isinstance(peptide_records, SearchableMassCollection): + peptide_records = NeutralMassDatabase(peptide_records) + self.peptides = peptide_records + self.peptide_to_group_id = None + + def build_peptide_groups(self): + peptide_groups = defaultdict(list) + for peptide in self.peptides: + peptide_groups[peptide.modified_peptide_sequence].append(peptide.id) + + sequence_to_group_id = {} + for i, key in enumerate(peptide_groups): + sequence_to_group_id[key] = i + + peptide_to_group_id = {} + for peptide in self.peptides: + peptide_to_group_id[peptide.id] = sequence_to_group_id[ + peptide.modified_peptide_sequence + ] + sequence_to_group_id.clear() + peptide_groups.clear() + self.peptide_to_group_id = peptide_to_group_id + + def filter_glycan_proposals_by_signature_ions( + self, + glycan_combinations: GlycanCombinationRecords, + signature_ion_match_index: SignatureIonIndexMatch, + ) -> GlycanCombinationRecords: + """"""Remove any glycans for which an expected signature ion is absent (or where the best matching peak is + less than 1% of the base peak). Requires the signature ion index is initialized. + """""" + result = [] + for glycan in glycan_combinations: + rec = signature_ion_match_index.record_for(glycan.composition) + if rec.expected_matches: + miss = 0 + for _sig, peak in rec.expected_matches.items(): + if peak is None: + miss += 1 + elif peak.intensity / signature_ion_match_index.base_peak_intensity < 0.01: + miss += 1 + if miss: + continue + result.append(glycan) + return result + + def handle_peptide_mass( + self, + peptide_mass: float, + intact_mass: float, + error_tolerance: float = 1e-5, + signature_ion_match_index: SignatureIonIndexMatch = None, + ) -> List[""Record""]: + peptide_records = self.peptides.search_mass_ppm(peptide_mass, error_tolerance) + glycan_mass = intact_mass - peptide_mass + glycan_combinations = self.glycan_combinations.search_mass_ppm(glycan_mass, error_tolerance) + if signature_ion_match_index: + glycan_combinations = self.filter_glycan_proposals_by_signature_ions( + glycan_combinations, signature_ion_match_index + ) + result_set = [] + for peptide in peptide_records: + self._combinate(peptide, glycan_combinations, result_set) + return result_set + + def _combinate( + self, + peptide: PeptideDatabaseRecord, + glycan_combinations: GlycanCombinationRecords, + result_set: Optional[List[""Record""]] = None, + ) -> List[""Record""]: + if result_set is None: + result_set = [] + peptide_obj = peptide.convert() + for glycan_combination in glycan_combinations: + for tp in glycan_combination.glycan_types: + tp = GlycosylationType[tp] + if tp is GlycosylationType.n_linked: + result_set.extend( + self.handle_n_glycan(peptide_obj.clone(), peptide, glycan_combination) + ) + elif tp is GlycosylationType.o_linked: + result_set.extend( + self.handle_o_glycan(peptide_obj.clone(), peptide, glycan_combination) + ) + elif tp is GlycosylationType.glycosaminoglycan: + result_set.extend( + self.handle_gag_linker(peptide_obj.clone(), peptide, glycan_combination) + ) + return result_set + + def generate_crossproduct(self, lower_bound=0, upper_bound=float(""inf"")): + minimum_peptide_mass = max(lower_bound - self.glycan_combinations.highest_mass, 0) + maximum_peptide_mass = max(upper_bound - self.glycan_combinations.lowest_mass, 0) + peptides = self.peptides.search_between( + max(minimum_peptide_mass - 10, 0), maximum_peptide_mass + ) + for peptide in peptides: + if not peptide.has_glycosylation_sites(): + continue + glycan_mass_limit = upper_bound - peptide.calculated_mass + if glycan_mass_limit < 0: + continue + minimum_glycan_mass = max(lower_bound - peptide.calculated_mass, 0) + glycan_combinations = self.glycan_combinations.search_between( + minimum_glycan_mass, glycan_mass_limit + 10 + ) + for solution in self._combinate(peptide, glycan_combinations): + total_mass = solution.total_mass + if total_mass < lower_bound or total_mass > upper_bound: + continue + yield solution + + def reset(self, **kwargs): + super(PeptideGlycosylator, self).reset(**kwargs) + self.peptides.reset(**kwargs) + + +class DynamicGlycopeptideSearchBase(LoggingMixin): + neutron_shift = isotopic_shift() + + def handle_scan_group( + self, + group: List, + precursor_error_tolerance: float = 1e-5, + mass_shifts: Optional[List[MassShift]] = None, + ): + raise NotImplementedError() + + def reset(self, **kwargs): + self.peptide_glycosylator.reset(**kwargs) + + def construct_peptide_groups(self, workload: WorkloadManager): + if self.peptide_glycosylator.peptide_to_group_id is None: + self.peptide_glycosylator.build_peptide_groups() + workload.hit_group_map.clear() + for hit in workload.hit_map.values(): + workload.hit_group_map[ + self.peptide_glycosylator.peptide_to_group_id[hit.id.peptide_id] + ].add(hit.id) + + +class PeptideMassFilterBase: + peptide_glycosylator: PeptideGlycosylator + product_error_tolerance: float + glycan_score_threshold: float + min_fragments: int + peptide_mass_predictor: IndexedGlycanFilteringPeptideMassEstimator + peptide_masses_per_scan: int + probing_range_for_missing_precursors: int + trust_precursor_fits: bool + oxonium_ion_index: OxoniumIndex + signature_ion_index: SignatureIonIndex + oxonium_ion_threshold: float + + monosaccharides: MonosaccharideResidues + + neutron_shift: float = isotopic_shift() + + def __init__( + self, + glycan_compositions: GlycanCombinationRecords, + product_error_tolerance: float=2e-5, + glycan_score_threshold: float=0.1, + min_fragments: int=2, + peptide_masses_per_scan: int=100, + probing_range_for_missing_precursors: int=3, + trust_precursor_fits: bool=True, + fragment_weight: float=0.56, + core_weight: float = 1.42, + oxonium_ion_index: Optional[OxoniumIndex]=None, + signature_ion_index: Optional[SignatureIonIndex]=None, + oxonium_ion_threshold: float = 0.05 + ): + # Intentionally use a larger core_weight here than in the real scoring function to + # prefer solutions with more core fragments, but not to discard them later? + if min_fragments is None: + min_fragments = 2 + self.product_error_tolerance = product_error_tolerance + self.glycan_score_threshold = glycan_score_threshold + self.min_fragments = int(min_fragments) + self.peptide_mass_predictor = IndexedGlycanFilteringPeptideMassEstimator( + glycan_compositions, + product_error_tolerance=product_error_tolerance, + fragment_weight=fragment_weight, + core_weight=core_weight, + ) + self.monosaccharides = self._monosaccharides_from_records(glycan_compositions) + self.peptide_masses_per_scan = peptide_masses_per_scan + self.probing_range_for_missing_precursors = probing_range_for_missing_precursors + self.trust_precursor_fits = trust_precursor_fits + self.oxonium_ion_index = oxonium_ion_index + self.signature_ion_index = signature_ion_index + self.oxonium_ion_threshold = oxonium_ion_threshold + + def _monosaccharides_from_records(self, glycan_combinations: GlycanCombinationRecords) -> MonosaccharideResidues: + residues = set() + for rec in glycan_combinations: + residues.update(rec.composition) + return {FrozenMonosaccharideResidue.from_iupac_lite(str(x)) for x in residues} + + +class PredictiveGlycopeptideSearch(PeptideMassFilterBase, DynamicGlycopeptideSearchBase): + peptide_glycosylator: PeptideGlycosylator + + def __init__( + self, + peptide_glycosylator, + product_error_tolerance=2e-5, + glycan_score_threshold=0.1, + min_fragments=2, + peptide_masses_per_scan=100, + probing_range_for_missing_precursors=3, + trust_precursor_fits=True, + fragment_weight=0.56, + core_weight=1.42, + oxonium_ion_index=None, + signature_ion_index=None, + oxonium_ion_threshold: float=0.05 + ): + self.peptide_glycosylator = peptide_glycosylator + super().__init__( + self.peptide_glycosylator.glycan_combinations, + product_error_tolerance=product_error_tolerance, + glycan_score_threshold=glycan_score_threshold, + min_fragments=min_fragments, + peptide_masses_per_scan=peptide_masses_per_scan, + probing_range_for_missing_precursors=probing_range_for_missing_precursors, + trust_precursor_fits=trust_precursor_fits, + fragment_weight=fragment_weight, + core_weight=core_weight, + oxonium_ion_index=oxonium_ion_index, + signature_ion_index=signature_ion_index, + oxonium_ion_threshold=oxonium_ion_threshold) + + def handle_scan_group( + self, + group: List[ProcessedScan], + precursor_error_tolerance: float = 1e-5, + mass_shifts: Optional[List[MassShift]] = None, + workload: Optional[WorkloadManager] = None, + ): + if mass_shifts is None or not mass_shifts: + mass_shifts = [Unmodified] + if workload is None: + workload = WorkloadManager() + + glycan_score_threshold = self.glycan_score_threshold + min_fragments = self.min_fragments + estimate_peptide_mass = self.peptide_mass_predictor.estimate_peptide_mass + handle_peptide_mass = self.peptide_glycosylator.handle_peptide_mass + peptide_masses_per_scan = self.peptide_masses_per_scan + for scan in group: + if gscore_scanner(scan) < self.oxonium_ion_threshold: + continue + workload.add_scan(scan) + signature_ion_matches: SignatureIonIndexMatch = None + + if self.oxonium_ion_index: + scan.annotations[""oxonium_index_match""] = self.oxonium_ion_index.match( + scan.deconvoluted_peak_set, self.product_error_tolerance + ) + if self.signature_ion_index: + signature_ion_matches = scan.annotations[ + ""signature_index_match"" + ] = self.signature_ion_index.match( + scan.deconvoluted_peak_set, self.product_error_tolerance + ) + n_glycopeptides = 0 + n_peptide_masses = 0 + if not scan.precursor_information.defaulted and self.trust_precursor_fits: + probe = 0 + else: + probe = self.probing_range_for_missing_precursors + precursor_mass = scan.precursor_information.neutral_mass + for i in range(probe + 1): + neutron_shift = self.neutron_shift * i + for mass_shift in mass_shifts: + seen = set() + mass_shift_name = mass_shift.name + mass_shift_mass = mass_shift.mass + intact_mass = precursor_mass - mass_shift_mass - neutron_shift + for peptide_mass_pred in estimate_peptide_mass( + scan, + topn=peptide_masses_per_scan, + mass_shift=mass_shift, + threshold=glycan_score_threshold, + min_fragments=min_fragments, + simplify=False, + query_mass=precursor_mass - neutron_shift, + ): + peptide_mass = peptide_mass_pred.peptide_mass + n_peptide_masses += 1 + for candidate in handle_peptide_mass( + peptide_mass, + intact_mass, + self.product_error_tolerance, + signature_ion_match_index=signature_ion_matches, + ): + n_glycopeptides += 1 + key = (candidate.id, mass_shift_name) + mass_threshold_passed = ( + abs(intact_mass - candidate.total_mass) / intact_mass + ) <= precursor_error_tolerance + # What if it could be an N- or O-glycopeptide? Does this block the + # same glycan from being treated as both? + if key in seen: + continue + seen.add(key) + if mass_threshold_passed: + workload.add_scan_hit(scan, candidate, mass_shift_name) + return workload + + +DEFAULT_THRESHOLD_CACHE_TOTAL_COUNT = 1e5 + + +class IterativeGlycopeptideSearch(DynamicGlycopeptideSearchBase): + total_mass_getter = operator.attrgetter(""total_mass"") + + def __init__( + self, + peptide_glycosylator, + product_error_tolerance=2e-5, + cache_size=2, + threshold_cache_total_count=DEFAULT_THRESHOLD_CACHE_TOTAL_COUNT, + ): + self.peptide_glycosylator = peptide_glycosylator + self.product_error_tolerance = product_error_tolerance + self.interval_cache = intervals.LRUIntervalSet(max_size=cache_size) + self.threshold_cache_total_count = threshold_cache_total_count + + def _make_new_glycopeptides_for_interval(self, lower_bound, upper_bound): + generator = self.peptide_glycosylator.generate_crossproduct(lower_bound, upper_bound) + generator = NeutralMassDatabase(list(generator), self.total_mass_getter) + return intervals.ConcatenateMassIntervalNode(generator) + + def _upkeep_memory_intervals(self, lower_bound=0, upper_bound=float(""inf"")): + """"""Perform routine maintainence of the interval cache, ensuring its size does not + exceed the upper limit + """""" + n = len(self.interval_cache) + if n > 1: + while ( + len(self.interval_cache) > 1 + and self.interval_cache.total_count > self.threshold_cache_total_count + ): + logger.info( + ""Upkeep Memory Intervals %d %d"", + self.interval_cache.total_count, + len(self.interval_cache), + ) + self.interval_cache.remove_lru_interval() + n = len(self.interval_cache) + if n == 1 and self.interval_cache.total_count > self.threshold_cache_total_count: + segment = self.interval_cache[0] + segment.constrain(lower_bound, upper_bound) + + def get_glycopeptides(self, lower_bound, upper_bound): + self._upkeep_memory_intervals(lower_bound, upper_bound) + q = intervals.QueryIntervalBase((lower_bound + upper_bound) / 2.0, lower_bound, upper_bound) + match = self.interval_cache.find_interval(q) + if match is not None: + logger.debug(""Nearest interval %r"", match) + # We are completely contained in an existing interval, so just + # use that one. + if match.contains_interval(q): + logger.debug(""Query interval %r was completely contained in %r"", q, match) + return match.group + # We overlap with an extending interval, so we should populate + # the new one and merge them. + elif match.overlaps(q): + q2 = q.difference(match) + logger.debug( + ""Query interval partially overlapped, creating disjoint interval %r"", q2 + ) + match = self.interval_cache.extend_interval( + match, self._make_new_glycopeptides_for_interval(q2.start, q2.end) + ) + return match.group + # We might need to insert a new interval + else: + logger.debug(""Query interval %r did not overlap with %r"", q, match) + return self._insert_interval(q.start, q.end) + else: + logger.debug(""Query interval %r did not overlap with %r"", q, match) + return self._insert_interval(q.start, q.end) + + def _insert_interval(self, lower_bound, upper_bound): + node = self._make_new_glycopeptides_for_interval(lower_bound, upper_bound) + logger.debug(""New Node: %r"", node) + # We won't insert this node if it is empty. + if len(node.group) == 0: + return node.group + nearest_interval = self.interval_cache.find_interval(node) + # Should an insert be performed if the query just didn't overlap well + # with the database? + if nearest_interval is None: + # No nearby interval, so we should insert + logger.debug(""No nearby interval for %r"", node) + self.interval_cache.insert_interval(node) + return node.group + elif nearest_interval.overlaps(node): + logger.debug(""Nearest interval %r overlaps this %r"", nearest_interval, node) + nearest_interval = self.interval_cache.extend_interval(nearest_interval, node) + return nearest_interval.group + elif not nearest_interval.contains_interval(node): + logger.debug(""Nearest interval %r didn't contain this %r"", nearest_interval, node) + # Nearby interval didn't contain this interval + self.interval_cache.insert_interval(node) + return node.group + else: + # Situation unclear. + # Not worth inserting, so just return the group + logger.info(""Unknown Condition Overlap %r / %r"" % (node, nearest_interval)) + return nearest_interval.group + + def handle_scan_group( + self, group, precursor_error_tolerance=1e-5, mass_shifts=None, workload=None + ): + if mass_shifts is None or not mass_shifts: + mass_shifts = [Unmodified] + if workload is None: + workload = WorkloadManager() + + group = NeutralMassDatabase(group, lambda x: x.precursor_information.neutral_mass) + lo_mass = group.lowest_mass + hi_mass = group.highest_mass + shifts = [m.mass for m in mass_shifts] + + lo_shift = min(shifts) - 0.5 + hi_shift = max(shifts) + 0.5 + + lower_bound = lo_mass + lo_shift + lower_bound = lower_bound - (lower_bound * precursor_error_tolerance) + + upper_bound = hi_mass + hi_shift + upper_bound = upper_bound + (upper_bound * precursor_error_tolerance) + + id_to_scan = {} + for scan in group: + id_to_scan[scan.id] = scan + logger.info(""\nQuerying between %f and %f"", lower_bound, upper_bound) + candidates = self.get_glycopeptides(lower_bound, upper_bound) + logger.info( + ""Interval from %f to %f contained %d candidates"", + lower_bound, + upper_bound, + len(candidates), + ) + for scan in group: + for mass_shift in mass_shifts: + intact_mass = scan.precursor_information.neutral_mass - mass_shift.mass + for candidate in candidates.search_mass_ppm(intact_mass, precursor_error_tolerance): + workload.add_scan_hit(scan, candidate, mass_shift.name) + return workload + + +class CompoundGlycopeptideSearch(object): + def __init__(self, glycopeptide_searchers=None): + if glycopeptide_searchers is None: + glycopeptide_searchers = [] + self.glycopeptide_searchers = list(glycopeptide_searchers) + + def add(self, glycopeptide_searcher): + self.glycopeptide_searchers.append(glycopeptide_searcher) + + def handle_scan_group( + self, group, precursor_error_tolerance=1e-5, mass_shifts=None, workload=None + ): + if mass_shifts is None: + mass_shifts = [Unmodified] + if workload is None: + workload = WorkloadManager() + for searcher in self.glycopeptide_searchers: + searcher.handle_scan_group( + group, precursor_error_tolerance, mass_shifts, workload=workload + ) + return workload + + +class Record(object): + __slots__ = (""glycopeptide"", ""id"", ""total_mass"", ""glycan_prior"") + + glycopeptide: str + id: glycopeptide_key_t + total_mass: float + glycan_prior: float + + def __init__(self, glycopeptide: FragmentCachingGlycopeptide = None): + if glycopeptide is not None: + self.glycopeptide = str(glycopeptide) + self.id = glycopeptide.id + self.total_mass = glycopeptide.total_mass + self.glycan_prior = glycopeptide.glycan_prior + else: + self.glycopeptide = """" + self.id = None + self.total_mass = 0 + self.glycan_prior = 0.0 + + def __repr__(self): + return ""Record(%s)"" % self.glycopeptide + + def __getstate__(self): + return (self.glycopeptide, self.id, self.total_mass, self.glycan_prior) + + def __setstate__(self, state): + self.glycopeptide, self.id, self.total_mass, self.glycan_prior = state + + def __eq__(self, other): + if other is None: + return False + return (self.glycopeptide == other.glycopeptide) and (self.id == other.id) + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + return hash(self.id) + + def convert(self) -> FragmentCachingGlycopeptide: + if self.id.structure_type.value & StructureClassification.target_peptide_decoy_glycan.value: + structure = SharedCacheAwareDecoyFragmentCachingGlycopeptide(self.glycopeptide) + else: + structure = FragmentCachingGlycopeptide(self.glycopeptide) + structure.id = self.id + structure.glycan_id = self.id.glycan_combination_id + structure.glycan_prior = self.glycan_prior + return structure + + def serialize(self): + id_bytes = self.id.serialize() + mass_bytes = struct.pack(""!d"", self.total_mass) + seq = (self.glycopeptide).encode(""utf8"") + encoded = id_bytes + mass_bytes + seq + return encoded + + @classmethod + def parse(cls, bytestring): + offset = glycopeptide_key_t.struct_spec.size + rec_id = glycopeptide_key_t.parse(bytestring[:offset]) + mass = struct.unpack(""!d"", bytestring[offset : offset + 8]) + seq = bytestring[offset + 8 :].decode(""utf8"") + inst = cls() + inst.id = rec_id + inst.total_mass = mass + inst.glycopeptide = seq + return inst + + @classmethod + def build(cls, glycopeptides: List[FragmentCachingGlycopeptide]) -> List[""Record""]: + return [cls(p) for p in glycopeptides] + + def copy(self, structure_type=None) -> ""Record"": + if structure_type is None: + structure_type = self.id.structure_type + inst = self.__class__() + inst.id = self.id.copy(structure_type) + inst.glycopeptide = self.glycopeptide + inst.total_mass = self.total_mass + return inst + + def to_decoy_glycan(self) -> ""Record"": + inst = self.__class__() + inst.id = self.id.to_decoy_glycan() + inst.glycopeptide = self.glycopeptide + inst.total_mass = self.total_mass + return inst + + +class SharedCacheAwareDecoyFragmentCachingGlycopeptide(DecoyFragmentCachingGlycopeptide): + def stub_fragments(self, *args, **kwargs): + kwargs.setdefault(""strategy"", CachingStubGlycopeptideStrategy) + key = self.fragment_caches.stub_fragment_key(self, args, kwargs) + if key in self.fragment_caches: + return self.fragment_caches[key] + target_key = self.fragment_caches._make_target_key(key) + if target_key in self.fragment_caches: + result = self.fragment_caches[target_key] + do_clone = True + else: + do_clone = False + result = list( + # Directly call the superclass method of FragmentCachingGlycopeptide as we + # do not need to go through a preliminary round of cache key construction and + # querying. + super( + FragmentCachingGlycopeptide, self + ).stub_fragments( # pylint: disable=bad-super-call + *args, **kwargs + ) + ) + result = self._permute_stub_masses(result, kwargs, do_clone=do_clone, min_shift_size=1) + self.fragment_caches[key] = result + return result + + +class Parser(object): + def __init__(self, max_size=2**12, **kwargs): + self.cache = LRUMapping(max_size) + + def __call__(self, record): + key = record.id + if key in self.cache: + return self.cache[key] + else: + struct = record.convert() + self.cache[key] = struct + return struct + + +class IdKeyMaker(object): + """"""Build an id-key structure for a glycopeptide with a new + glycan composition given a glycopeptide of the same peptide + backbone. + """""" + + def __init__(self, valid_glycans): + self.valid_glycans = valid_glycans + self.lookup_map = {g: g.id for g in self.valid_glycans} + + def make_id_controlled_structures(self, structure, references): + glycan_id = self.lookup_map[structure.glycan_composition] + result = [] + for reference in references: + ref_key = reference.id + alt_key = glycopeptide_key_t( + ref_key.start_position, + ref_key.end_position, + ref_key.peptide_id, + ref_key.protein_id, + ref_key.hypothesis_id, + glycan_id, + ref_key.structure_type, + ref_key.site_combination_index, + # TODO: Does this needs to be generic over all glycosylation types of + # glycan_id if it could span multiple, or will we assume that all alternatives + # will be in references? + ref_key.glycosylation_type, + ) + alt = structure.clone() + alt.id = alt_key + alt.protein_relation = reference.protein_relation + result.append(alt) + return result + + def __call__(self, structure, references): + return self.make_id_controlled_structures(structure, references) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/dynamic_generation/searcher.py",".py","21301","588","import time + +from queue import Empty, Full, Queue +from typing import List, Optional, Tuple, Type, Union, Dict, Set, TYPE_CHECKING + +from glycresoft.chromatogram_tree.mass_shift import MassShiftBase + +from ms_deisotope.data_source import ProcessedScan, ProcessedRandomAccessScanSource +# from ms_deisotope.output import ProcessedMSFileLoader + +from glycresoft.structure.scan import ScanStub +from glycresoft.tandem.glycopeptide.scoring.base import GlycopeptideSpectrumMatcherBase + +from glycresoft.task import TaskExecutionSequence +from glycresoft.chromatogram_tree import Unmodified + +from .search_space import ( + Parser, + PredictiveGlycopeptideSearch) + +from ...workload import WorkloadManager +from ...spectrum_match.solution_set import MultiScoreSpectrumSolutionSet + +from ..scoring import LogIntensityScorer +from ..matcher import GlycopeptideMatcher + +if TYPE_CHECKING: + from multiprocessing.managers import SyncManager + from multiprocessing.synchronize import Event as MPEvent + +Full: Exception + +class MultiScoreGlycopeptideMatcher(GlycopeptideMatcher): + solution_set_type = MultiScoreSpectrumSolutionSet + + +def IsTask(cls): + return cls + + +def workload_grouping( + chunks: List[List[ProcessedScan]], + max_scans_per_workload: int=500, + starting_index: int=0) -> Tuple[List[List[ProcessedScan]], int]: + """""" + Gather together precursor mass batches of tandem mass spectra into a unit + batch, starting from index ``starting_index``. + + Parameters + ---------- + chunks : List[List[:class:`~.ProcessedScan`]] + The precursor mass batched spectra + max_scans_per_workload : int + The total number of scans to include in a unit batch. This is a soft + upper bound, a unit batch may have more than this if the next precursor + mass batch is too large, but no additional batches will be added after + that. + starting_index : int + The offset into ``chunks`` to start collecting batches from + + Returns + ------- + unit_batch : List[List[:class:`~.ProcessedScan`]] + The batch of precursor mass batches + ending_index : int + The offset into ``chunks`` that the next round should + start from. + """""" + workload = [] + total_scans_in_workload = 0 + i = starting_index + n = len(chunks) + while total_scans_in_workload < max_scans_per_workload and i < n: + chunk = chunks[i] + workload.append(chunk) + total_scans_in_workload += len(chunk) + i += 1 + return workload, i + + +class SpectrumBatcher(TaskExecutionSequence): + """""" + Break a big list of scans into precursor mass batched blocks of + spectrum groups with an approximate maximum size. Feeds raw workloads + into the pipeline. + """""" + groups: List + out_queue: Queue + max_scans_per_workload: int + + def __init__(self, groups, out_queue, max_scans_per_workload=250): + self.groups = groups + self.max_scans_per_workload = max_scans_per_workload + self.out_queue = out_queue + self.done_event = self._make_event() + + def generate(self): + groups = self.groups + max_scans_per_workload = self.max_scans_per_workload + group_n = len(groups) + group_i = 0 + while group_i < group_n: + group_i_prev = group_i + chunk, group_i = workload_grouping(groups, max_scans_per_workload, group_i) + yield chunk, group_i_prev, group_n + + def run(self): + for batch in self.generate(): + if self.error_occurred(): + break + while not self.error_occurred(): + try: + self.out_queue.put(batch, True, 5) + break + except Full: + pass + self.done_event.set() + + +class BatchMapper(TaskExecutionSequence): + """""" + Wrap scan groups from :class:`SpectrumBatcher` in :class:`StructureMapper` tasks + and ships them to an appropriate work queue (usually another process). + + .. note:: + The StructureMapper could be applied with or without a database bound to it, + and for an IPC consumer the database should not be bound, only labeled. + """""" + + search_groups: List[List[ProcessedScan]] + precursor_error_tolerance: float + mass_shifts: List[MassShiftBase] + + in_queue: Queue + out_queue: Dict[str, Queue] + in_done_event: 'MPEvent' + done_event: 'MPEvent' + + def __init__(self, search_groups, in_queue, out_queue, in_done_event, + precursor_error_tolerance=5e-6, mass_shifts=None): + if mass_shifts is None: + mass_shifts = [Unmodified] + if not isinstance(out_queue, dict): + for label, _group in search_groups: + out_queue = {label: out_queue} + self.search_groups = search_groups + self.precursor_error_tolerance = precursor_error_tolerance + self.mass_shifts = mass_shifts + self.in_queue = in_queue + self.out_queue = out_queue + self.in_done_event = in_done_event + self.done_event = self._make_event() + + def out_queue_for_label(self, label): + return self.out_queue[label] + + def execute_task(self, task: Tuple[List[List[ProcessedScan]], int, int]): + chunk, group_i_prev, group_n = task + for label, search_group in self.search_groups: + task = StructureMapper( + chunk, group_i_prev, group_n, search_group, + precursor_error_tolerance=self.precursor_error_tolerance, + mass_shifts=self.mass_shifts) + task.label = label + # Introduces a thread safety issue? + task.unbind_scans() + while not self.error_occurred(): + try: + self.out_queue_for_label(label).put(task, True, 5) + break + except Full: + pass + + def run(self): + has_work = True + while has_work and not self.error_occurred(): + try: + task = self.in_queue.get(True, 5) + self.execute_task(task) + except Empty: + if self.in_done_event.is_set(): + has_work = False + break + self.done_event.set() + + +@IsTask +class StructureMapper(TaskExecutionSequence[WorkloadManager]): + """""" + Map spectra against the database using a precursor filtering search strategy, + generating a task graph of spectrum-structure-mass_shift relationships, a + :class:`~.WorkloadManager` instance. + """""" + + chunk: List[List[ProcessedScan]] + group_i: int + group_n: int + predictive_search: Union[PredictiveGlycopeptideSearch, str] + precursor_error_tolerance: float + mass_shifts: List[MassShiftBase] + seen: Set[str] + + def __init__(self, chunk, group_i, group_n, predictive_search, precursor_error_tolerance=5e-6, + mass_shifts=None): + if mass_shifts is None: + mass_shifts = [Unmodified] + self.chunk = chunk + self.group_i = group_i + self.group_n = group_n + self.predictive_search = predictive_search + self.seen = set() + self.mass_shifts = mass_shifts + self.precursor_error_tolerance = precursor_error_tolerance + + def bind_scans(self, source: ProcessedRandomAccessScanSource): + for group in self.chunk: + for scan in group: + scan.bind(source) + + def unbind_scans(self): + for group in self.chunk: + for scan in group: + scan.unbind() + + def get_scan_source(self): + for group in self.chunk: + for scan in group: + return scan.source + + def _log_cache(self): + if False: + predictive_search = self.predictive_search + hits = predictive_search.peptide_glycosylator._cache_hit + misses = predictive_search.peptide_glycosylator._cache_miss + total = hits + misses + if total > 5000: + self.log(""... Cache Performance: %d / %d (%0.2f%%)"" % (hits, total, hits / float(total) * 100.0)) + + def _prepare_scan(self, scan: Union[ScanStub, ProcessedScan]) -> ProcessedScan: + try: + return scan.convert() + except AttributeError: + if isinstance(scan, ProcessedScan): + return scan + else: + raise + + def map_structures(self) -> WorkloadManager: + counter = 0 + workload = WorkloadManager() + predictive_search = self.predictive_search + start = time.time() + total_work = 0 + lo_min = float('inf') + hi_max = 0 + for i, group in enumerate(self.chunk): + lo = float('inf') + hi = 0 + temp = [] + for g in group: + g = self._prepare_scan(g) + if g.id in self.seen: + raise ValueError(""Repeated Scan %r"" % g.id) + self.seen.add(g.id) + counter += 1 + mass = g.precursor_information.neutral_mass + temp.append(g) + if lo > mass: + lo = mass + if hi < mass: + hi = mass + group = temp + solutions = predictive_search.handle_scan_group( + group, mass_shifts=self.mass_shifts, precursor_error_tolerance=self.precursor_error_tolerance) + total_work += solutions.total_work_required() + if i % 500 == 0 and i != 0: + self.log('... Mapped Group %d (%0.2f%%) %0.3f-%0.3f with %d Items (%d Total)' % ( + i + self.group_i, i * 100.0 / len(self.chunk), lo, hi, + solutions.total_work_required(), total_work)) + lo_min = min(lo_min, lo) + hi_max = max(hi_max, hi) + workload.update(solutions) + end = time.time() + if counter: + self.debug(""... Mapping Completed %0.3f-%0.3f (%0.2f sec.)"" % + (lo_min, hi_max, end - start)) + self._log_cache() + predictive_search.reset() + return workload + + def add_decoy_glycans(self, workload: WorkloadManager) -> WorkloadManager: + items = list(workload.hit_map.items()) + for hit_id, record in items: + record = record.to_decoy_glycan() + for scan in workload.hit_to_scan_map[hit_id]: + hit_type = workload.scan_hit_type_map[scan.id, hit_id] + workload.add_scan_hit(scan, record, hit_type) + return workload + + def run(self) -> WorkloadManager: + workload = self.map_structures() + workload.pack() + self.add_decoy_glycans(workload) + self.predictive_search.construct_peptide_groups(workload) + return workload + + +class MapperExecutor(TaskExecutionSequence): + """"""This task executor consumes batches of precursor mass-grouped spectra, + and produces batches of glycopeptides matched to spectra. + + Its task type is :class:`StructureMapper` + + """""" + + scan_loader: ProcessedRandomAccessScanSource + predictive_searchers: Dict[str, PredictiveGlycopeptideSearch] + + in_queue: Queue + out_queue: Queue + in_done_event: ""MPEvent"" + done_event: ""MPEvent"" + + def __init__(self, predictive_searchers, scan_loader, in_queue, out_queue, in_done_event): + self.in_queue = in_queue + self.out_queue = out_queue + self.in_done_event = in_done_event + self.done_event = self._make_event() + self.scan_loader = scan_loader + self.predictive_searchers = predictive_searchers + + def execute_task(self, mapper_task: StructureMapper) -> 'SpectrumMatcher': + self.scan_loader.reset() + # In case this came from a labeled batch mapper and not + # attached to an actual dynamic glycopeptide generator + batch_label = None + label = mapper_task.predictive_search + if isinstance(label, str): + batch_label = label + mapper_task.predictive_search = self.predictive_searchers[label] + + mapper_task.bind_scans(self.scan_loader) + workload = mapper_task() + self.scan_loader.reset() + matcher_task = SpectrumMatcher( + workload, + mapper_task.group_i, + mapper_task.group_n, + batch_label=batch_label) + return matcher_task + + def run(self): + has_work = True + strikes = 0 + while has_work and not self.error_occurred(): + try: + mapper_task = self.in_queue.get(True, 5) + matcher_task = self.execute_task(mapper_task) + while not self.error_occurred(): + try: + self.out_queue.put(matcher_task, True, 5) + break + except Full: + pass + # Detach the scans from the scan source again. + mapper_task.unbind_scans() + + except Empty: + strikes += 1 + if strikes % 50 == 0 and strikes: + self.log(""... %d iterations without new batches on %s, done event: %s"" % ( + strikes, self, self.in_done_event.is_set())) + if self.in_done_event.is_set(): + has_work = False + break + self.done_event.set() + + +class SemaphoreBoundMapperExecutor(MapperExecutor): + def __init__(self, semaphore, predictive_searchers, scan_loader, in_queue, out_queue, + in_done_event, tracking_directory=None): + super(SemaphoreBoundMapperExecutor, self).__init__( + predictive_searchers, scan_loader, + in_queue, out_queue, in_done_event) + self.semaphore = semaphore + + def execute_task(self, mapper_task): + with self.semaphore: + result = super(SemaphoreBoundMapperExecutor, self).execute_task(mapper_task) + return result + + +@IsTask +class SpectrumMatcher(TaskExecutionSequence[List[MultiScoreSpectrumSolutionSet]]): + """"""Actually execute the spectrum matching specified in a :class:`~.WorkloadManager`. + + .. note:: + This task may spin up additional processes if :attr:`n_processes` is greater than + 1, but it must be ~4 or better usually to have an appreciable speedup compared to + a executing the matching in serial. IPC communication is expensive, no matter what. + """""" + + workload: WorkloadManager + group_i: int + group_n: int + scorer_type: Type[GlycopeptideSpectrumMatcherBase] + ipc_manager: 'SyncManager' + batch_label: Optional[str] + + n_processes: int + mass_shifts: List[MassShiftBase] + evaluation_kwargs: Dict + cache_seeds: Optional[Dict] + + def __init__(self, workload, group_i, group_n, scorer_type=None, + ipc_manager=None, n_processes=6, mass_shifts=None, + evaluation_kwargs=None, cache_seeds=None, + batch_label: Optional[str]=None, + **kwargs): + if scorer_type is None: + scorer_type = LogIntensityScorer + if evaluation_kwargs is None: + evaluation_kwargs = {} + self.workload = workload + self.group_i = group_i + self.group_n = group_n + self.batch_label = batch_label + + self.mass_shifts = mass_shifts + self.scorer_type = scorer_type + self.evaluation_kwargs = evaluation_kwargs + self.evaluation_kwargs.update(kwargs) + + self.ipc_manager = ipc_manager + self.n_processes = n_processes + self.cache_seeds = cache_seeds + + def score_spectra(self) -> List[MultiScoreSpectrumSolutionSet]: + matcher = MultiScoreGlycopeptideMatcher( + [], self.scorer_type, None, Parser, + ipc_manager=self.ipc_manager, + n_processes=self.n_processes, + mass_shifts=self.mass_shifts, + cache_seeds=self.cache_seeds) + + target_solutions = [] + lo, hi = self.workload.mass_range() + batches = list(self.workload.batches(matcher.batch_size)) + if self.workload.total_size: + label = '' + if self.batch_label: + label = self.batch_label.title() + ' ' + self.log( + f""... {label}{max((self.group_i - 1), 0) * 100.0 / self.group_n:0.2f}% "" + f""({lo:0.2f}-{hi:0.2f}) {self.workload}"") + + + n_batches = len(batches) + running_total_work = 0 + total_work = self.workload.total_work_required() + self.workload.clear() + for i, batch in enumerate(batches): + if batch.batch_size == 0: + batch.clear() + continue + if n_batches > 1: + self.log(""... Batch %d (%d/%d) %0.2f%%"" % ( + i + 1, running_total_work + batch.batch_size, total_work, + ((running_total_work + batch.batch_size) * 100.) / float(total_work + 1))) + running_total_work += batch.batch_size + target_scan_solution_map = matcher.evaluate_hit_groups( + batch, **self.evaluation_kwargs) + + temp = matcher.collect_scan_solutions( + target_scan_solution_map, batch.scan_map) + temp = [case for case in temp if len(case) > 0] + for case in temp: + case.simplify() + # Don't run the select top filters for consistency. They seemed to + # influence reproducibility. + target_solutions.extend(temp) + batch.clear() + + if batches: + label = '' + if self.batch_label: + label = self.batch_label.title() + ' ' + self.log(f""... Finished {label}{max(self.group_i - 1, 0) * 100.0 / self.group_n:0.2f}%"" + f"" ({lo:0.2f}-{hi:0.2f})"") + return target_solutions + + def run(self): + solution_sets = self.score_spectra() + return solution_sets + + +class MatcherExecutor(TaskExecutionSequence): + """"""This task executor consumes mappings from glycopeptide to scan and runs spectrum + matching, scoring each glycopeptide against their matched spectra. It produces scored + spectrum matches. + + This type complements :class:`MapperExecutor` + + Its task type is :class:`SpectrumMatcher` + """""" + + in_queue: Queue + out_queue: Queue + in_done_event: 'MPEvent' + done_event: 'MPEvent' + ipc_manager: 'SyncManager' + + scorer_type: Type[GlycopeptideSpectrumMatcherBase] + + n_processes: int + mass_shifts: List[MassShiftBase] + evaluation_kwargs: Dict + cache_seeds: Optional[Dict] + + def __init__(self, in_queue, out_queue, in_done_event, scorer_type=None, ipc_manager=None, + n_processes=6, mass_shifts=None, evaluation_kwargs=None, cache_seeds=None, + **kwargs): + if scorer_type is None: + scorer_type = LogIntensityScorer + if evaluation_kwargs is None: + evaluation_kwargs = {} + + self.in_queue = in_queue + self.out_queue = out_queue + self.in_done_event = in_done_event + self.done_event = self._make_event() + + self.mass_shifts = mass_shifts + self.scorer_type = scorer_type + self.evaluation_kwargs = evaluation_kwargs + self.evaluation_kwargs.update(kwargs) + + self.n_processes = n_processes + self.ipc_manager = ipc_manager + self.cache_seeds = cache_seeds + + def configure_task(self, matcher_task: SpectrumMatcher): + matcher_task.ipc_manager = self.ipc_manager + matcher_task.n_processes = self.n_processes + matcher_task.scorer_type = self.scorer_type + matcher_task.evaluation_kwargs = self.evaluation_kwargs + matcher_task.mass_shifts = self.mass_shifts + matcher_task.mass_shift_map = {m.name: m for m in self.mass_shifts} + return matcher_task + + def execute_task(self, matcher_task): + matcher_task = self.configure_task(matcher_task) + solutions = matcher_task() + return solutions + + def run(self): + has_work = True + while has_work and not self.error_occurred(): + try: + matcher_task: SpectrumMatcher = self.in_queue.get(True, 3) + solutions = self.execute_task(matcher_task) + while not self.error_occurred(): + try: + self.out_queue.put(solutions, True, 5) + break + except Full: + pass + except Empty: + if self.in_done_event.is_set(): + has_work = False + break + self.done_event.set() + + +class SemaphoreBoundMatcherExecutor(MatcherExecutor): + def __init__(self, semaphore, in_queue, out_queue, in_done_event, scorer_type=None, + ipc_manager=None, n_processes=6, mass_shifts=None, evaluation_kwargs=None, + cache_seeds=None, **kwargs): + super(SemaphoreBoundMatcherExecutor, self).__init__( + in_queue, out_queue, in_done_event, scorer_type, ipc_manager, + n_processes, mass_shifts, evaluation_kwargs, cache_seeds=cache_seeds, **kwargs) + self.semaphore = semaphore + + def execute_task(self, matcher_task): + with self.semaphore: + result = super(SemaphoreBoundMatcherExecutor, self).execute_task(matcher_task) + return result +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/dynamic_generation/multipart_fdr.py",".py","29989","731","# -*- coding: utf8 -*- +'''This module implements techniques derived from the pGlyco2 +FDR estimation procedure described in: + +[1] Liu, M.-Q., Zeng, W.-F., Fang, P., Cao, W.-Q., Liu, C., Yan, G.-Q., … Yang, P.-Y. + (2017). pGlyco 2.0 enables precision N-glycoproteomics with comprehensive quality + control and one-step mass spectrometry for intact glycopeptide identification. + Nature Communications, 8(1), 438. https://doi.org/10.1038/s41467-017-00535-2 +[2] Zeng, W.-F., Liu, M.-Q., Zhang, Y., Wu, J.-Q., Fang, P., Peng, C., … Yang, P. (2016). + pGlyco: a pipeline for the identification of intact N-glycopeptides by using HCD- + and CID-MS/MS and MS3. Scientific Reports, 6(April), 25102. https://doi.org/10.1038/srep25102 +''' +from typing import Dict, List, Optional, Tuple, Type, Union +import numpy as np + +from glypy.structure.glycan_composition import GlycanComposition +from glypy.utils.enum import EnumValue + +try: + from matplotlib import pyplot as plt +except ImportError: + pass + +from glycresoft.task import TaskBase + +from glycresoft.structure.enums import GlycopeptideFDREstimationStrategy +from glycresoft.tandem.spectrum_match.spectrum_match import FDRSet, MultiScoreSpectrumMatch, SpectrumMatch +from glycresoft.tandem.spectrum_match.solution_set import MultiScoreSpectrumSolutionSet, SpectrumSolutionSet +from glycresoft.tandem.target_decoy import ( + NearestValueLookUp, + PeptideScoreTargetDecoyAnalyzer, + FDREstimatorBase, + PeptideScoreSVMModel +) +from glycresoft.tandem.glycopeptide.core_search import approximate_internal_size_of_glycan + +from .mixture import ( + GammaMixture, GaussianMixture, GaussianMixtureWithPriorComponent, + MixtureBase, TruncatedGaussianMixture, TruncatedGaussianMixtureWithPriorComponent) + +from .journal import SolutionSetGrouper + + +def noop(*args, **kwargs): + pass + + +def interpolate_from_zero(nearest_value_map: NearestValueLookUp, zero_value: float=1.0) -> NearestValueLookUp: + smallest = nearest_value_map.items[0] + X = np.linspace(0, smallest[0]) + Y = np.interp(X, [0, smallest[0]], [zero_value, smallest[1]]) + pairs = list(zip(X, Y)) + pairs.extend(nearest_value_map.items) + return nearest_value_map.__class__(pairs) + + +class FiniteMixtureModelFDREstimatorBase(FDREstimatorBase): + decoy_scores: np.ndarray + target_scores: np.ndarray + decoy_mixture: Optional[MixtureBase] + target_mixture: Optional[MixtureBase] + fdr_map: Optional[NearestValueLookUp] + + def __init__(self, decoy_scores, target_scores): + self.decoy_scores = np.array(decoy_scores) + self.target_scores = np.array(target_scores) + self.decoy_mixture = None + self.target_mixture = None + self.fdr_map = None + + def estimate_posterior_error_probability(self, X: np.ndarray) -> np.ndarray: + return self.target_mixture.prior.score(X) * self.pi0 / self.target_mixture.score(X) + + def get_count_for_fdr(self, q_value: float): + target_scores = self.target_scores + target_scores = np.sort(target_scores) + fdr = np.sort(self.estimate_fdr())[::-1] + if len(fdr) == 0: + return 0, 0 + ii = np.where(fdr < q_value)[0] + if len(ii) == 0: + return float('inf'), 0 + i = ii[0] + score_for_fdr = target_scores[i] + target_counts = (target_scores >= score_for_fdr).sum() + return score_for_fdr, target_counts + + @property + def pi0(self): + return self.target_mixture.weights[-1] + + def plot_mixture(self, ax=None): + if ax is None: + fig, ax = plt.subplots(1) + X = np.arange(1, max(self.target_scores), 0.1) + ax.plot(X, + np.exp(self.target_mixture.logpdf(X)).sum(axis=1)) + for col in np.exp(self.target_mixture.logpdf(X)).T: + ax.plot(X, col, linestyle='--') + ax.hist(self.target_scores, bins=100, density=1, alpha=0.15) + return ax + + def plot(self, ax=None): + if ax is None: + fig, ax = plt.subplots(1) + + dmin = 0 + dmax = 1 + tmin = 0 + tmax = 1 + if len(self.target_scores): + tmin = self.target_scores.min() + tmax = self.target_scores.max() + if len(self.decoy_scores): + dmin = self.decoy_scores.min() + dmax = self.decoy_scores.max() + points = np.linspace( + min(tmin, dmin), + max(tmax, dmax), + 10000) + target_scores = np.sort(self.target_scores) + target_counts = [(self.target_scores >= i).sum() for i in points] + decoy_counts = [(self.decoy_scores >= i).sum() for i in points] + fdr = self.estimate_fdr(target_scores) + at_5_percent = np.where(fdr < 0.05)[0][0] + at_1_percent = np.where(fdr < 0.01)[0][0] + line1 = ax.plot(points, target_counts, + label='Target', color='steelblue') + line2 = ax.plot(points, decoy_counts, label='Decoy', color='coral') + line4 = ax.vlines(target_scores[at_5_percent], 0, np.max( + target_counts), linestyle='--', color='green', lw=0.75, label='5% FDR') + line5 = ax.vlines(target_scores[at_1_percent], 0, np.max( + target_counts), linestyle='--', color='skyblue', lw=0.75, label='1% FDR') + ax.set_ylabel(""# Matches Retained"") + ax.set_xlabel(""Score"") + ax2 = ax.twinx() + ax2.set_ylabel(""FDR"") + line3 = ax2.plot(target_scores, fdr, label='FDR', + color='grey', linestyle='--') + ax.legend( + [line1[0], line2[0], line3[0], line4, line5], + ['Target', 'Decoy', 'FDR', '5% FDR', '1% FDR'], frameon=False) + + lo, hi = ax.get_ylim() + lo = max(lo, 0) + ax.set_ylim(lo, hi) + lo, hi = ax2.get_ylim() + ax2.set_ylim(0, hi) + + lo, hi = ax.get_xlim() + ax.set_xlim(-1, hi) + lo, hi = ax2.get_xlim() + ax2.set_xlim(-1, hi) + return ax + + def fit(self, max_components: int=10, + max_target_components: Optional[int]=None, + max_decoy_components: Optional[int]=None) -> NearestValueLookUp: + if not max_target_components: + max_target_components = max_components + if not max_decoy_components: + max_decoy_components = max_components + self.estimate_decoy_distributions(max_decoy_components) + self.estimate_target_distributions(max_target_components) + fdr = self.estimate_fdr(self.target_scores) + self.fdr_map = NearestValueLookUp(zip(self.target_scores, fdr)) + # Since 0 is not in the domain of the model, we need to include it by interpolating from 1 to the smallest + # fitted value. + if self.fdr_map.items[0][0] > 0: + self.fdr_map = interpolate_from_zero(self.fdr_map) + return self.fdr_map + + def estimate_fdr(self, X: np.ndarray=None) -> np.ndarray: + if X is None: + X = self.target_scores + X_ = np.array(sorted(X, reverse=True)) + pep = self.estimate_posterior_error_probability(X_) + # The FDR is the expected value of PEP, or the average PEP in this case. + # The expression below is a cumulative mean (the cumulative sum divided + # by the number of elements in the sum) + fdr = np.cumsum(pep) / np.arange(1, len(X_) + 1) + # Use searchsorted on the ascending ordered version of X_ + # to find the indices of the origin values of X, then map + # those into the ascending ordering of the FDR vector to get + # the FDR estimates of the original X + fdr[np.isnan(fdr)] = 1.0 + fdr_descending = fdr[::-1] + for i in range(1, fdr_descending.shape[0]): + if fdr_descending[i - 1] < fdr_descending[i]: + fdr_descending[i] = fdr_descending[i - 1] + fdr = fdr_descending[::-1] + fdr = fdr[::-1][np.searchsorted(X_[::-1], X)] + return fdr + + def _select_best_number_of_components(self, max_components: int, + fitter: Type[MixtureBase], + scores: np.ndarray, **kwargs) -> MixtureBase: + models = [] + bics = [] + for i in range(1, max_components + 1): + self.debug(""Fitting %d Components"" % (i,)) + iteration_kwargs = kwargs.copy() + iteration_kwargs['n_components'] = i + model = fitter(scores, **iteration_kwargs) + bic = model.bic(scores) + models.append(model) + bics.append(bic) + self.debug(""BIC: %g"" % (bic,)) + i = np.argmin(bics) + self.debug(""Selected %d Components"" % (i + 1,)) + return models[i] + + def estimate_decoy_distributions(self, max_components: int=10): + raise NotImplementedError() + + def estimate_target_distributions(self, max_components: int=10) -> MixtureBase: + n = len(self.target_scores) + np.random.seed(n) + if n < 10: + self.log(""Too few target observations"") + self.target_mixture = GaussianMixtureWithPriorComponent( + [1.0], [1.0], self.decoy_mixture, [0.5, 0.5]) + return self.target_mixture + self.target_mixture = self._select_best_number_of_components( + max_components, + GaussianMixtureWithPriorComponent.fit, + self.target_scores, + prior=self.decoy_mixture, + deterministic=True) + return self.target_mixture + + def score(self, spectrum_match: Union[SpectrumMatch, float], assign: bool = False) -> float: + return self.fdr_map[ + spectrum_match.score + if isinstance(spectrum_match, SpectrumMatch) + else spectrum_match] + + +class FiniteMixtureModelFDREstimatorSeparated(FiniteMixtureModelFDREstimatorBase): + decoy_model_type = GammaMixture + target_model_type = GaussianMixture + + def estimate_decoy_distributions(self, max_components: int = 10): + n = len(self.decoy_scores) + np.random.seed(n) + if n < 10: + self.log(""Too few decoy observations"") + self.decoy_mixture = self.decoy_model_type( + [1.0], [1.0], [1.0]) + return self.decoy_mixture + + self.decoy_mixture = self._select_best_number_of_components( + max_components, self.decoy_model_type.fit, self.decoy_scores) + return self.decoy_mixture + + def estimate_target_distributions(self, max_components: int = 10): + n = len(self.target_scores) + np.random.seed(n) + if n < 10: + self.log(""Too few target observations"") + self.target_mixture = self.target_model_type( + [1.0], [1.0], [1.0]) + return self.target_mixture + self.target_mixture = self._select_best_number_of_components( + max_components, + GaussianMixture.fit, + self.target_scores, + deterministic=True) + return self.target_mixture + + def estimate_posterior_error_probability(self, X: np.ndarray) -> np.ndarray: + d = self.decoy_mixture.score(X) + t = self.target_mixture.score(X) + pi0 = self.pi0 + return (pi0 * d) / (pi0 * d + (1 - pi0) * t) + + def get_count_for_fdr(self, q_value): + target_scores = self.target_scores + target_scores = np.sort(target_scores) + fdr = np.sort(self.estimate_fdr())[::-1] + + i = np.where(fdr < q_value)[0][0] + score_for_fdr = target_scores[i] + target_counts = (target_scores >= score_for_fdr).sum() + return score_for_fdr, target_counts + + @property + def pi0(self): + pi0 = len(self.decoy_scores) / len(self.target_scores) + return pi0 + + +class FiniteMixtureModelFDREstimatorDecoyGamma(FiniteMixtureModelFDREstimatorBase): + + def estimate_decoy_distributions(self, max_components=10): + n = len(self.decoy_scores) + np.random.seed(n) + if n < 10: + self.log(""Too few decoy observations"") + self.decoy_mixture = GammaMixture([1.0], [1.0], [1.0]) + return self.decoy_mixture + + self.decoy_mixture = self._select_best_number_of_components( + max_components, GammaMixture.fit, self.decoy_scores) + return self.decoy_mixture + + +class FiniteMixtureModelFDREstimatorDecoyGaussian(FiniteMixtureModelFDREstimatorBase): + + def estimate_decoy_distributions(self, max_components=10): + n = len(self.decoy_scores) + np.random.seed(n) + if n < 10: + self.log(""Too few decoy observations"") + self.decoy_mixture = GaussianMixture([1.0], [1.0], [1.0]) + return self.decoy_mixture + + self.decoy_mixture = self._select_best_number_of_components( + max_components, GaussianMixture.fit, self.decoy_scores) + return self.decoy_mixture + + +FiniteMixtureModelFDREstimator = FiniteMixtureModelFDREstimatorDecoyGamma + + +class FiniteMixtureModelFDREstimatorHalfGaussian(FiniteMixtureModelFDREstimatorBase): + + def estimate_decoy_distributions(self, max_components=10): + n = len(self.decoy_scores) + np.random.seed(n) + if n < 10: + self.log(""Too few decoy observations"") + self.decoy_mixture = TruncatedGaussianMixture([0], [1.0], [1.0]) + return self.decoy_mixture + + self.decoy_mixture = self._select_best_number_of_components( + max_components, TruncatedGaussianMixture.fit, self.decoy_scores) + return self.decoy_mixture + + def estimate_target_distributions(self, max_components=10): + n = len(self.target_scores) + np.random.seed(n) + if n < 10: + self.log(""Too few target observations"") + self.target_mixture = TruncatedGaussianMixtureWithPriorComponent( + [0.0], [1.0], self.decoy_mixture, [0.5, 0.5]) + return self.target_mixture + self.target_mixture = self._select_best_number_of_components( + max_components, + TruncatedGaussianMixtureWithPriorComponent.fit, + self.target_scores, + prior=self.decoy_mixture, + deterministic=True) + return self.target_mixture + + +class MultivariateMixtureModel(FDREstimatorBase): + models: List[FiniteMixtureModelFDREstimatorBase] + + def __init__(self, models): + self.models = models + + def __iter__(self): + return iter(self.models) + + def __getitem__(self, i): + return self.models[i] + + def __len__(self): + return len(self.models) + + def is_combined(self, mixture_model): + tm = mixture_model.target_mixture + if hasattr(tm, 'prior'): + return True + return False + + def _compute_per_feature_probabilities(self, X: List[np.ndarray] = None) -> Tuple[np.ndarray, np.ndarray]: + if X is None: + X = [m.target_scores for m in self.models] + + decoy_series = [] + target_series = [] + for i, (model, x) in enumerate(zip(self.models, X)): + if self.is_combined(model): + decoy_p = model.decoy_mixture.score(x) + w_decoy = model.pi0 + target_decoy_p = model.target_mixture.score(x) + target_p = (target_decoy_p - w_decoy * decoy_p) + decoy_p *= w_decoy + else: + decoy_p = model.decoy_mixture.score(x) + target_p = model.target_mixture.score(x) + decoy_series.append(decoy_p) + target_series.append(target_p) + return decoy_series, target_series + + def estimate_pi0(self, X: List[np.ndarray]=None) -> Tuple[float, np.ndarray, np.ndarray]: + decoy_series, target_series = self._compute_per_feature_probabilities(X) + decoy = np.prod(decoy_series, axis=0) + target = np.prod(target_series, axis=0) + return (decoy / (decoy + target)).mean(), decoy, target + + def _compute_overlap_probabilities(self, decoy_series: List[np.ndarray], + target_series: List[np.ndarray], + pi0s: List[float]) -> List[np.ndarray]: + mixed_terms = [] + for i, d in enumerate(decoy_series): + for j, t in enumerate(target_series): + if i != j: + mixed_terms.append(d * t / (1 - pi0s[j]) * pi0s[j]) + return mixed_terms + + def estimate_posterior_error_probability(self, X: List[np.ndarray] = None, correlated: bool=False) -> np.ndarray: + if X is None: + X = [m.target_scores for m in self.models] + + decoy_series, target_series = self._compute_per_feature_probabilities(X) + if correlated: + # mixed_terms = self._compute_overlap_probabilities( + # decoy_series, target_series, [m.pi0 for m in self]) + raise NotImplementedError(""Correlated features are not implemented"") + + decoy = np.prod(decoy_series, axis=0) + target = np.prod(target_series, axis=0) + if self.is_combined(self.models[0]): + pass + else: + pi_0 = self.models[0].pi0 + decoy *= pi_0 + target *= (1 - pi_0) + if not correlated: + return decoy / (target + decoy) + raise NotImplementedError(""Correlated features are not implemented"") + + def estimate_fdr(self, X: List[np.ndarray] = None, correlated: bool=False): + if X is None: + X = [m.target_scores for m in self.models] + X = np.stack(X, axis=-1) + X_ = X[np.lexsort(X[:, ::-1].T)[::-1], :] + pep = self.estimate_posterior_error_probability(list(X_.T)) + fdr = np.cumsum(pep) / np.arange(1, len(X_) + 1) + fdr[np.isnan(fdr)] = 1.0 + fdr_descending = fdr[::-1] + for i in range(1, fdr_descending.shape[0]): + if fdr_descending[i - 1] < fdr_descending[i]: + fdr_descending[i] = fdr_descending[i - 1] + fdr = fdr_descending[::-1] + fdr = fdr[::-1][np.searchsorted(X_[::-1, 0], X[:, 0])] + return fdr + + def fit(self, correlated: bool = False, *args, **kwargs) -> NearestValueLookUp: + fdr = self.estimate_fdr(correlated=correlated) + self.fdr_map = NearestValueLookUp( + zip(self.models[0].target_scores, fdr)) + # Since 0 is not in the domain of the model, we need to include it by + # interpolating from 1 to the smallest fitted value. + if self.fdr_map.items[0][0] > 0: + self.fdr_map = interpolate_from_zero(self.fdr_map) + return self.fdr_map + + def get_count_for_fdr(self, q_value): + target_scores = self.models[0].target_scores + target_scores = np.sort(target_scores) + fdr = np.sort(self.estimate_fdr())[::-1] + + i = np.where(fdr < q_value)[0][0] + score_for_fdr = target_scores[i] + target_counts = (target_scores >= score_for_fdr).sum() + return score_for_fdr, target_counts + + def plot(self, ax=None): + if ax is None: + fig, ax = plt.subplots(1) + target_scores = self.models[0].target_scores + decoy_scores = self.models[0].decoy_scores + + dmin = 0 + dmax = float('inf') + tmin = 0 + tmax = float('inf') + if len(target_scores): + tmin = target_scores.min() + tmax = target_scores.max() + if len(decoy_scores): + dmin = decoy_scores.min() + dmax = decoy_scores.max() + points = np.linspace( + min(tmin, dmin), + max(tmax, dmax), + 10000) + + target_scores = np.sort(target_scores) + target_counts = [(target_scores >= i).sum() for i in points] + decoy_counts = [(decoy_scores >= i).sum() for i in points] + + fdr = np.sort(self.estimate_fdr())[::-1] + + at_5_percent = np.where(fdr < 0.05)[0][0] + at_1_percent = np.where(fdr < 0.01)[0][0] + + line1 = ax.plot(points, target_counts, + label='Target', color='steelblue') + line2 = ax.plot(points, decoy_counts, label='Decoy', color='coral') + line4 = ax.vlines(target_scores[at_5_percent], 0, np.max( + target_counts), linestyle='--', color='green', lw=0.75, label='5% FDR') + line5 = ax.vlines(target_scores[at_1_percent], 0, np.max( + target_counts), linestyle='--', color='skyblue', lw=0.75, label='1% FDR') + ax.set_ylabel(""# Matches Retained"") + ax.set_xlabel(""Score"") + ax2 = ax.twinx() + ax2.set_ylabel(""FDR"") + line3 = ax2.plot(target_scores, fdr, label='FDR', + color='grey', linestyle='--') + ax.legend( + [line1[0], line2[0], line3[0], line4, line5], + ['Target', 'Decoy', 'FDR', '5% FDR', '1% FDR'], frameon=False) + + lo, hi = ax.get_ylim() + lo = max(lo, 0) + ax.set_ylim(lo, hi) + lo, hi = ax2.get_ylim() + ax2.set_ylim(0, hi) + + lo, hi = ax.get_xlim() + ax.set_xlim(-1, hi) + lo, hi = ax2.get_xlim() + ax2.set_xlim(-1, hi) + return ax + + +class GlycanSizeCalculator(object): + glycan_size_cache: Dict[str, int] + + def __init__(self): + self.glycan_size_cache = dict() + + def get_internal_size(self, glycan_composition: GlycanComposition) -> int: + key = str(glycan_composition) + if key in self.glycan_size_cache: + return self.glycan_size_cache[key] + n = approximate_internal_size_of_glycan(glycan_composition) + self.glycan_size_cache[key] = n + return n + + def __call__(self, glycan_composition: GlycanComposition) -> int: + return self.get_internal_size(glycan_composition) + + +class GlycopeptideFDREstimator(TaskBase): + display_fields = False + minimum_glycan_size: int = 3 + minimum_score: float = 1 + + strategy: EnumValue + grouper: 'SolutionSetGrouper' + + glycan_fdr: FiniteMixtureModelFDREstimator + peptide_fdr: Union[PeptideScoreTargetDecoyAnalyzer, PeptideScoreSVMModel] + glycopeptide_fdr: FiniteMixtureModelFDREstimator + + _peptide_fdr_estimator_type: Type[PeptideScoreTargetDecoyAnalyzer] + + def __init__(self, groups: 'SolutionSetGrouper', + strategy: Optional[GlycopeptideFDREstimationStrategy] = None, + peptide_fdr_estimator: Optional[Type[PeptideScoreTargetDecoyAnalyzer]] = None): + if peptide_fdr_estimator is None: + peptide_fdr_estimator = PeptideScoreTargetDecoyAnalyzer + if strategy is None: + strategy = GlycopeptideFDREstimationStrategy.multipart_gamma_gaussian_mixture + else: + strategy = GlycopeptideFDREstimationStrategy[strategy] + self.strategy = strategy + self.grouper = groups + self.glycan_fdr = None + self.peptide_fdr = None + self.glycopeptide_fdr = None + self._peptide_fdr_estimator_type = peptide_fdr_estimator + + def fit_glycan_fdr(self): + tt_gpsms = self.grouper.exclusive_match_groups['target_peptide_target_glycan'] + td_gpsms = self.grouper.exclusive_match_groups['target_peptide_decoy_glycan'] + + target_glycan_scores = np.array( + [s.score_set.glycan_score for s in tt_gpsms]) + decoy_glycan_scores = np.array( + [s.score_set.glycan_score for s in td_gpsms]) + + sizer = GlycanSizeCalculator() + size_mask = np.array( + [sizer(s.target.glycan_composition) + for s in td_gpsms], dtype=int) + + glycan_fdr = FiniteMixtureModelFDREstimator( + decoy_glycan_scores[(size_mask > self.minimum_glycan_size) & ( + decoy_glycan_scores > self.minimum_score)], + target_scores=target_glycan_scores[target_glycan_scores > self.minimum_score]) + + glycan_fdr.fit() + glycan_fdr.summarize(""Glycan FDR"") + + self.glycan_fdr = glycan_fdr + return self.glycan_fdr + + def fit_peptide_fdr(self): + tt_gpsms = self.grouper.exclusive_match_groups['target_peptide_target_glycan'] + dt_gpsms = self.grouper.exclusive_match_groups['decoy_peptide_target_glycan'] + + target_peptides = tt_gpsms + decoy_peptides = dt_gpsms + + peptide_fdr = self._peptide_fdr_estimator_type(target_peptides, decoy_peptides) + peptide_fdr.summarize(""Peptide FDR"") + + self.peptide_fdr = peptide_fdr + return self.peptide_fdr + + def fit_glycopeptide_fdr(self): + tt_gpsms = self.grouper.exclusive_match_groups['target_peptide_target_glycan'] + dd_gpsms = self.grouper.exclusive_match_groups['decoy_peptide_decoy_glycan'] + + target_total_scores = np.array([t.score_set.glycopeptide_score for t in tt_gpsms]) + decoy_total_scores = np.array([t.score_set.glycopeptide_score for t in dd_gpsms]) + + glycopeptide_fdr = FiniteMixtureModelFDREstimator( + decoy_total_scores[decoy_total_scores > self.minimum_score], + target_total_scores[target_total_scores > self.minimum_score]) + + glycopeptide_fdr.fit() + glycopeptide_fdr.summarize(""Glycopeptide FDR"") + + self.glycopeptide_fdr = glycopeptide_fdr + return self.glycopeptide_fdr + + def _assign_joint_fdr(self, solution_sets: List[MultiScoreSpectrumSolutionSet]): + for ts in solution_sets: + for t in ts: + t.q_value_set.peptide_q_value = self.peptide_fdr.score(t, assign=False) + t.q_value_set.glycan_q_value = self.glycan_fdr.fdr_map[t.score_set.glycan_score] + t.q_value_set.glycopeptide_q_value = self.glycopeptide_fdr.fdr_map[t.score_set.glycopeptide_score] + total = (t.q_value_set.peptide_q_value + t.q_value_set.glycan_q_value - + t.q_value_set.glycopeptide_q_value) + total = max(t.q_value_set.peptide_q_value, t.q_value_set.glycan_q_value, total) + t.q_value = t.q_value_set.total_q_value = total + if isinstance(ts, SpectrumSolutionSet): + ts.q_value = ts.best_solution().q_value + return solution_sets + + def _assign_minimum_fdr(self, solution_sets: List[MultiScoreSpectrumSolutionSet]): + for ts in solution_sets: + for t in ts: + t.q_value_set.peptide_q_value = self.peptide_fdr.score(t, assign=False) + t.q_value_set.glycan_q_value = self.glycan_fdr.fdr_map[t.score_set.glycan_score] + t.q_value_set.glycopeptide_q_value = self.glycopeptide_fdr.fdr_map[ + t.score_set.glycopeptide_score] + total = min(t.q_value_set.peptide_q_value, t.q_value_set.glycan_q_value) + t.q_value = t.q_value_set.total_q_value = total + ts.q_value = ts.best_solution().q_value + return solution_sets + + def _assign_peptide_fdr(self, solution_sets: List[MultiScoreSpectrumSolutionSet]): + for ts in solution_sets: + for t in ts: + total = t.q_value_set.peptide_q_value = self.peptide_fdr.score(t, assign=False) + t.q_value_set.glycan_q_value = 0 + t.q_value_set.glycopeptide_q_value = 0 + t.q_value = t.q_value_set.total_q_value = total + ts.q_value = ts.best_solution().q_value + return solution_sets + + def _assign_glycan_fdr(self, solution_sets): + for ts in solution_sets: + for t in ts: + t.q_value_set.peptide_q_value = 0 + total = t.q_value_set.glycan_q_value = self.glycan_fdr.fdr_map[t.score_set.glycan_score] + t.q_value_set.glycopeptide_q_value = 0 + t.q_value = t.q_value_set.total_q_value = total + ts.q_value = ts.best_solution().q_value + return solution_sets + + def fit_total_fdr(self, solution_sets: Optional[List[MultiScoreSpectrumSolutionSet]] = None): + if solution_sets is None: + solution_sets = self.grouper.match_type_groups['target_peptide_target_glycan'] + if self.strategy == GlycopeptideFDREstimationStrategy.multipart_gamma_gaussian_mixture: + self._assign_joint_fdr(solution_sets) + elif self.strategy == GlycopeptideFDREstimationStrategy.peptide_fdr: + self._assign_peptide_fdr(solution_sets) + elif self.strategy == GlycopeptideFDREstimationStrategy.glycan_fdr: + self._assign_glycan_fdr(solution_sets) + elif self.strategy == GlycopeptideFDREstimationStrategy.peptide_or_glycan: + self._assign_minimum_fdr(solution_sets) + else: + raise NotImplementedError(self.strategy) + return self.grouper + + def score_all(self, solution_set: MultiScoreSpectrumSolutionSet): + self.fit_total_fdr([solution_set]) + return solution_set + + def score(self, gpsm: MultiScoreSpectrumMatch, assign: bool=False): + q_value = gpsm.q_value + q_value_set = gpsm.q_value_set + placeholder = FDRSet.default() + gpsm.q_value_set = placeholder + self.score_all(MultiScoreSpectrumSolutionSet(gpsm.scan, [gpsm])) + result_q_value_set = placeholder + if not assign: + gpsm.q_value = q_value + gpsm.q_value_set = q_value_set + return result_q_value_set + + def run(self): + if self.strategy in (GlycopeptideFDREstimationStrategy.multipart_gamma_gaussian_mixture, + GlycopeptideFDREstimationStrategy.glycan_fdr, + GlycopeptideFDREstimationStrategy.peptide_or_glycan): + self.fit_glycan_fdr() + if self.strategy in (GlycopeptideFDREstimationStrategy.multipart_gamma_gaussian_mixture, + GlycopeptideFDREstimationStrategy.peptide_fdr, + GlycopeptideFDREstimationStrategy.peptide_or_glycan): + self.fit_peptide_fdr() + if self.strategy in (GlycopeptideFDREstimationStrategy.multipart_gamma_gaussian_mixture, + GlycopeptideFDREstimationStrategy.peptide_or_glycan): + self.fit_glycopeptide_fdr() + self.fit_total_fdr() + return self.grouper + + def pack(self): + self.grouper = SolutionSetGrouper([]) + if self.peptide_fdr is not None: + self.peptide_fdr.pack() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycopeptide/dynamic_generation/mixture.py",".py","46","1","from glycresoft.structure.probability import *","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/chromatogram_mapping/aggregation.py",".py","11051","244","from typing import (Any, Callable, Collection, DefaultDict, Dict, Hashable, + List, Optional, Set, Tuple, NamedTuple, Type, Union, + TYPE_CHECKING) + +from glycresoft.chromatogram_tree import Chromatogram, ChromatogramFilter +from glycresoft.chromatogram_tree.mass_shift import Unmodified + +from glycresoft.task import TaskBase + +from .base import Predicate, SolutionEntry, TargetType, default_threshold, DEBUG_MODE +from .chromatogram import TandemAnnotatedChromatogram +from .revision import MS2RevisionValidator +from .graph import build_glycopeptide_key, MassShiftDeconvolutionGraph, RepresenterDeconvolution + + +class GraphAnnotatedChromatogramAggregator(TaskBase): + annotated_chromatograms: List[TandemAnnotatedChromatogram] + delta_rt: float + require_unmodified: bool + threshold_fn: Predicate + key_fn: Callable[[TargetType], Hashable] + + revision_validator: MS2RevisionValidator + + def __init__(self, annotated_chromatograms, delta_rt=0.25, require_unmodified=True, + threshold_fn=default_threshold, key_fn=build_glycopeptide_key, + revision_validator: Optional[MS2RevisionValidator] = None): + if revision_validator is None: + revision_validator = MS2RevisionValidator(threshold_fn) + self.annotated_chromatograms = sorted(annotated_chromatograms, + key=lambda x: ( + max(sset.best_solution( + ).score for sset in x.tandem_solutions) + if x.tandem_solutions else -float('inf'), x.total_signal), + reverse=True) + self.delta_rt = delta_rt + self.require_unmodified = require_unmodified + self.threshold_fn = threshold_fn + self.key_fn = key_fn + self.revision_validator = revision_validator + + def build_graph(self) -> MassShiftDeconvolutionGraph: + self.log(""Constructing chromatogram graph"") + assignable = [] + rest: List[Chromatogram] = [] + for chrom in self.annotated_chromatograms: + if chrom.composition is not None: + assignable.append(chrom) + else: + rest.append(chrom) + graph = MassShiftDeconvolutionGraph(assignable) + graph.build(self.delta_rt, self.threshold_fn) + return graph, rest + + def deconvolve(self, graph: MassShiftDeconvolutionGraph): + components = graph.connected_components() + assigned = [] + if DEBUG_MODE: + breakpoint() + + for group in components: + spectra_in = set() + for node in group: + for sset in node.tandem_solutions: + spectra_in.add(sset.scan.id) + + deconv = RepresenterDeconvolution( + group, + threshold_fn=self.threshold_fn, + key_fn=self.key_fn, + revision_validator=self.revision_validator, + ) + deconv.solve() + reps = deconv.assign_representers() + spectra_out = set() + for node in reps: + for sset in node.tandem_solutions: + spectra_out.add(sset.scan.id) + if spectra_out != spectra_in: + self.error( + f""{len(spectra_in - spectra_out)} spectra lost while solving this component"") + if DEBUG_MODE and spectra_out != spectra_in: + breakpoint() + assigned.extend(reps) + return assigned + + def run(self): + graph, rest = self.build_graph() + solutions = self.deconvolve(graph) + solutions.extend(rest) + return ChromatogramFilter(solutions) + + +class AnnotatedChromatogramAggregator(TaskBase): + """"""A basic chromatogram merger that groups chromatograms according to their best analyte. + + This algorithm looks for RT proximity. + """""" + + annotated_chromatograms: ChromatogramFilter + delta_rt: float + require_unmodified: bool + threshold_fn: Predicate + + def __init__(self, annotated_chromatograms, delta_rt=0.25, require_unmodified=True, + threshold_fn=default_threshold): + self.annotated_chromatograms = annotated_chromatograms + self.delta_rt = delta_rt + self.require_unmodified = require_unmodified + self.threshold_fn = threshold_fn + + def combine_chromatograms(self, aggregated): + merged = [] + for entity, group in aggregated.items(): + out = [] + group = sorted(group, key=lambda x: x.start_time) + chroma = group[0] + for obs in group[1:]: + if chroma.chromatogram.overlaps_in_time(obs) or abs( + chroma.end_time - obs.start_time) < self.delta_rt: + chroma = chroma.merge(obs) + else: + out.append(chroma) + chroma = obs + out.append(chroma) + merged.extend(out) + return merged + + def aggregate_by_annotation(self, annotated_chromatograms: ChromatogramFilter) -> Tuple[ + List[TandemAnnotatedChromatogram], + DefaultDict[ + str, + List[TandemAnnotatedChromatogram] + ] + ]: + """"""Group chromatograms by their assigned entity."""""" + finished = [] + aggregated = DefaultDict(list) + for chroma in annotated_chromatograms: + if chroma.composition is not None: + if chroma.entity is not None: + # Convert to string to avoid redundant sequences from getting + # binned differently due to random ordering of ids. + aggregated[str(chroma.entity)].append(chroma) + else: + aggregated[str(chroma.composition)].append(chroma) + else: + finished.append(chroma) + return finished, aggregated + + def aggregate(self, annotated_chromatograms: ChromatogramFilter) -> List[TandemAnnotatedChromatogram]: + """"""Drives the aggregation process."""""" + self.log(""Aggregating Common Entities: %d chromatograms"" % + (len(annotated_chromatograms,))) + finished, aggregated = self.aggregate_by_annotation( + annotated_chromatograms) + finished.extend(self.combine_chromatograms(aggregated)) + self.log(""After Merging: %d chromatograms"" % (len(finished),)) + return finished + + def replace_solution(self, chromatogram: TandemAnnotatedChromatogram, solutions: List[SolutionEntry]): + # select the best solution + solutions = sorted( + solutions, key=lambda x: x.score, reverse=True) + + # remove the invalidated mass shifts so that we're dealing with the raw masses again. + current_shifts = chromatogram.chromatogram.mass_shifts + if len(current_shifts) > 1: + self.log(""... Found a multiply shifted identification with no Unmodified state: %s"" % ( + chromatogram.entity, )) + partitions = [] + for shift in current_shifts: + # The _ collects the ""not modified with shift"" portion of the chromatogram + # we'll strip out in successive iterations. By virtue of reaching this point, + # we're never dealing with an Unmodified portion. + partition, _ = chromatogram.chromatogram.bisect_mass_shift(shift) + # If we're somehow dealing with a compound mass shift here, remove + # the bad shift from the composite, and reset the modified nodes to + # Unmodified. + partitions.append(partition.deduct_node_type(shift)) + + # Merge in + accumulated_chromatogram = partitions[0] + for partition in partitions[1:]: + accumulated_chromatogram = accumulated_chromatogram.merge( + partition) + chromatogram.chromatogram = accumulated_chromatogram + + # update the tandem annotations + for solution_set in chromatogram.tandem_solutions: + solution_set.mark_top_solutions(reject_shifted=self.require_unmodified) + chromatogram.assign_entity( + solutions[0], + entity_chromatogram_type=chromatogram.chromatogram.__class__) + chromatogram.representative_solutions = solutions + return chromatogram + + def reassign_modified_only_cases(self, annotated_chromatograms): + out = [] + for chromatogram in annotated_chromatograms: + # the structure's best match has not been identified in an unmodified state + if Unmodified not in chromatogram.mass_shifts: + original_entity = getattr(chromatogram, ""entity"") + solutions = chromatogram.most_representative_solutions( + self.threshold_fn, reject_shifted=True) + # if there is a reasonable solution in an unmodified state + if solutions: + chromatogram = self.replace_solution( + chromatogram, solutions) + self.debug(""... Replacing %s with %s"", + original_entity, chromatogram.entity) + out.append(chromatogram) + else: + self.log( + ""... Could not find an alternative option for %r"" % (chromatogram,)) + out.append(chromatogram) + else: + out.append(chromatogram) + return out + + def run(self): + merged_chromatograms = self.aggregate(self.annotated_chromatograms) + if self.require_unmodified: + spliced = self.reassign_modified_only_cases(merged_chromatograms) + merged_chromatograms = self.aggregate(spliced) + result = ChromatogramFilter(merged_chromatograms) + return result + + +def aggregate_by_assigned_entity(annotated_chromatograms: List[TandemAnnotatedChromatogram], + delta_rt: float = 0.25, + require_unmodified: bool = True, + threshold_fn: Predicate = default_threshold, + revision_validator: Optional[MS2RevisionValidator] = None): + job = GraphAnnotatedChromatogramAggregator( + annotated_chromatograms, + delta_rt=delta_rt, + require_unmodified=require_unmodified, + threshold_fn=threshold_fn, + revision_validator=revision_validator + ) + finished = job.run() + return finished +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/chromatogram_mapping/__init__.py",".py","1913","26","from .base import (DEBUG_MODE, Predicate, default_threshold, always, TargetType, logger, + SolutionEntry, build_glycopeptide_key, KeyTargetMassShift, KeyMassShift, parsimony_sort) +from .revision import (MS2RevisionValidator, SignalUtilizationMS2RevisionValidator, + SpectrumMatchBackFiller, SpectrumMatchUpdater, RevisionSummary) +from .graph import (RepresenterDeconvolution, MassShiftDeconvolutionGraph, + MassShiftDeconvolutionGraphNode, MassShiftDeconvolutionGraphEdge) +from .representer import (RepresenterSelectionStrategy, + TotalBestRepresenterStrategy, TotalAboveAverageBestRepresenterStrategy) +from .chromatogram import (TandemAnnotatedChromatogram, SpectrumMatchSolutionCollectionBase, + TandemSolutionsWithoutChromatogram, ScanTimeBundle) +from .aggregation import (aggregate_by_assigned_entity, + AnnotatedChromatogramAggregator, GraphAnnotatedChromatogramAggregator) +from .mapper import ChromatogramMSMSMapper + +__all__ = [ + 'DEBUG_MODE', 'Predicate', 'default_threshold', 'always', 'TargetType', 'logger', + 'SolutionEntry', 'build_glycopeptide_key', 'KeyTargetMassShift', 'KeyMassShift', 'parsimony_sort', + 'MS2RevisionValidator', 'SignalUtilizationMS2RevisionValidator', 'SpectrumMatchBackFiller', + 'SpectrumMatchUpdater', 'RepresenterDeconvolution', 'MassShiftDeconvolutionGraph', + 'MassShiftDeconvolutionGraphNode', 'MassShiftDeconvolutionGraphEdge', + 'RepresenterSelectionStrategy', 'TotalBestRepresenterStrategy', 'TotalAboveAverageBestRepresenterStrategy', + 'TandemAnnotatedChromatogram', 'SpectrumMatchSolutionCollectionBase', 'TandemSolutionsWithoutChromatogram', + 'ScanTimeBundle', 'aggregate_by_assigned_entity', 'AnnotatedChromatogramAggregator', + 'GraphAnnotatedChromatogramAggregator', 'ChromatogramMSMSMapper', ""RevisionSummary"" +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/chromatogram_mapping/chromatogram.py",".py","13534","335"," +from typing import (Any, Callable, Collection, DefaultDict, + List, Optional, + TYPE_CHECKING) + +from glycresoft.chromatogram_tree.chromatogram import GlycopeptideChromatogram +from glycresoft.chromatogram_tree.mass_shift import MassShiftBase +from glycresoft.chromatogram_tree import ( + ChromatogramWrapper, + Unmodified) + +from glycresoft.task import log_handle + +from ..spectrum_match import SpectrumMatch, SpectrumSolutionSet + +from .base import SolutionEntry, Predicate, always, TargetType +from .representer import RepresenterSelectionStrategy, TotalBestRepresenterStrategy + + +class SpectrumMatchSolutionCollectionBase(object): + tandem_solutions: List[SpectrumSolutionSet] + best_msms_score: float + representative_solutions: List[SolutionEntry] + + def compute_representative_weights(self, threshold_fn: Predicate = always, reject_shifted: bool = False, + targets_ignored: Collection = None, + strategy: Optional[RepresenterSelectionStrategy] = None, **kwargs) -> List[SolutionEntry]: + """"""Calculate a total score for all matched structures across all time points for this + solution collection, and rank them. + + This total score is the sum of the score over all spectrum matches for which that + structure was the best match. The percentile is the ratio of the total score for the + `i`th structure divided by the sum of total scores over all structures. + + Parameters + ---------- + threshold_fn: Callable + A function that filters out invalid solutions based on some criteria, e.g. + not passing the FDR threshold. + reject_shifted: bool + Whether or not to omit any solution that was not mass-shifted. Defaults to False + + Returns + ------- + list + A list of solutions, ranked by percentile. + """""" + if strategy is None: + strategy = TotalBestRepresenterStrategy() + weights = strategy(self, threshold_fn=threshold_fn, + reject_shifted=reject_shifted, targets_ignored=targets_ignored, **kwargs) + return weights + + def filter_entries(self, entries: List[SolutionEntry], percentile_threshold: float = 1e-5) -> List[SolutionEntry]: + # This difference is not using the absolute value to allow for scenarios where + # a worse percentile is located at position 0 e.g. when hoisting via parsimony. + representers = [x for x in entries if ( + entries[0].percentile - x.percentile) < percentile_threshold] + return representers + + def most_representative_solutions(self, threshold_fn: Predicate = always, reject_shifted: bool = False, + targets_ignored: Collection = None, + percentile_threshold: float = 1e-5) -> List[SolutionEntry]: + """"""Find the most representative solutions, the (very nearly the same, hopefully) structures with + the highest aggregated score across all MSn events assigned to this collection. + + Parameters + ---------- + threshold_fn: Callable + A function that filters out invalid solutions based on some criteria, e.g. + not passing the FDR threshold. + reject_shifted: bool + Whether or not to omit any solution that was not mass-shifted. Defaults to False + percentile_threshold : float, optional + The difference between the worst and best percentile to be reported. Defaults to 1e-5. + + Returns + ------- + list + A list of solutions with approximately the greatest weight + """""" + weights = self.compute_representative_weights( + threshold_fn, reject_shifted=reject_shifted, targets_ignored=targets_ignored) + if weights: + representers = self.filter_entries( + weights, percentile_threshold=percentile_threshold) + return representers + else: + return [] + + def solutions_for(self, structure: TargetType, threshold_fn: Predicate = always, + reject_shifted: bool = False) -> List[SpectrumMatch]: + '''Get all spectrum matches in this collection for a given + structure. + + Parameters + ---------- + structure : Hashable + The structure collect matches for. + threshold_fn: Callable + A function that filters out invalid solutions based on some criteria, e.g. + not passing the FDR threshold. + reject_shifted: bool + Whether or not to omit any solution that was not mass-shifted. Defaults to False + + Returns + ------- + list + ''' + solutions = [] + for sset in self.tandem_solutions: + try: + psm = sset.solution_for(structure) + if threshold_fn(psm): + if psm.mass_shift != Unmodified and reject_shifted: + continue + solutions.append(psm) + except KeyError: + continue + return solutions + + def best_match_for(self, structure: TargetType, threshold_fn: Predicate = always) -> SpectrumMatch: + solutions = self.solutions_for(structure, threshold_fn=threshold_fn) + if not solutions: + raise KeyError(structure) + best_score = -float('inf') + best_match = None + for sol in solutions: + if best_score < sol.score: + best_score = sol.score + best_match = sol + return best_match + + def has_scan(self, scan_id: str) -> bool: + return any([sset.scan_id == scan_id for sset in self.tandem_solutions]) + + def get_scan(self, scan_id: str) -> SpectrumMatch: + for sset in self.tandem_solutions: + if sset.scan_id == scan_id: + return sset + raise KeyError(scan_id) + + +class TandemAnnotatedChromatogram(ChromatogramWrapper, SpectrumMatchSolutionCollectionBase): + time_displaced_assignments: List[SpectrumSolutionSet] + + def __init__(self, chromatogram): + super(TandemAnnotatedChromatogram, self).__init__(chromatogram) + self.tandem_solutions = [] + self.time_displaced_assignments = [] + self.best_msms_score = None + self.representative_solutions = None + + def bisect_charge(self, charge): + new_charge, new_no_charge = map( + self.__class__, self.chromatogram.bisect_charge(charge)) + for hit in self.tandem_solutions: + if hit.precursor_information.charge == charge: + new_charge.add_solution(hit) + else: + new_no_charge.add_solution(hit) + return new_charge, new_no_charge + + def bisect_mass_shift(self, mass_shift): + new_mass_shift, new_no_mass_shift = map( + self.__class__, self.chromatogram.bisect_mass_shift(mass_shift)) + for hit in self.tandem_solutions: + if hit.best_solution().mass_shift == mass_shift: + new_mass_shift.add_solution(hit) + else: + new_no_mass_shift.add_solution(hit) + return new_mass_shift, new_no_mass_shift + + def split_sparse(self, delta_rt=1.0): + parts = list( + map(self.__class__, self.chromatogram.split_sparse(delta_rt))) + for hit in self.tandem_solutions: + nearest = None + nearest_time = None + time = hit.scan_time + for part in parts: + time_err = min(abs(part.start_time - time), + abs(part.end_time - time)) + if time_err < nearest_time: + nearest = part + nearest_time = time_err + if part.spans_time_point(time): + part.add_solution(hit) + break + else: + nearest.add_solution(hit) + return parts + + def add_solution(self, item: SpectrumSolutionSet): + case_mass = item.precursor_information.neutral_mass + if abs(case_mass - self.chromatogram.neutral_mass) > 100: + log_handle.log( + ""Warning, mis-assigned spectrum match to chromatogram %r, %r"" % (self, item)) + self.tandem_solutions.append(item) + + def add_displaced_solution(self, item: SpectrumSolutionSet): + self.add_solution(item) + + def clone(self) -> 'TandemAnnotatedChromatogram': + new = super(TandemAnnotatedChromatogram, self).clone() + new.tandem_solutions = list(self.tandem_solutions) + new.time_displaced_assignments = list(self.time_displaced_assignments) + new.best_msms_score = self.best_msms_score + return new + + def merge(self, other: 'TandemAnnotatedChromatogram', node_type: MassShiftBase = Unmodified) -> 'TandemAnnotatedChromatogram': + if isinstance(other, TandemAnnotatedChromatogram) or hasattr(other, 'tandem_solutions'): + new = self.__class__(self.chromatogram.merge( + other.chromatogram, node_type=node_type)) + new.tandem_solutions = self.tandem_solutions + other.tandem_solutions + new.time_displaced_assignments = self.time_displaced_assignments + \ + other.time_displaced_assignments + else: + new = self.chromatogram.merge(other, node_type=node_type) + return new + + def merge_in_place(self, other: 'TandemAnnotatedChromatogram', node_type: MassShiftBase = Unmodified): + if isinstance(other, TandemAnnotatedChromatogram) or hasattr(other, 'tandem_solutions'): + new = self.chromatogram.merge( + other.chromatogram, node_type=node_type) + self.tandem_solutions = self.tandem_solutions + other.tandem_solutions + self.time_displaced_assignments = self.time_displaced_assignments + \ + other.time_displaced_assignments + else: + new = self.chromatogram.merge(other, node_type=node_type) + self.chromatogram = new + + def assign_entity(self, solution_entry, entity_chromatogram_type=GlycopeptideChromatogram): + entity_chroma = entity_chromatogram_type( + None, + self.chromatogram.nodes, self.chromatogram.mass_shifts, + self.chromatogram.used_as_mass_shift) + entity_chroma.entity = solution_entry.solution + if solution_entry.match.mass_shift != Unmodified: + identified_shift = solution_entry.match.mass_shift + for node in entity_chroma.nodes.unspool(): + if node.node_type == Unmodified: + node.node_type = identified_shift + else: + node.node_type = (node.node_type + identified_shift) + entity_chroma.invalidate() + self.chromatogram = entity_chroma + self.best_msms_score = solution_entry.best_score + + +class TandemSolutionsWithoutChromatogram(SpectrumMatchSolutionCollectionBase): + # For mimicking EntityChromatograms + entity: Any + composition: Any + + mass_shift: MassShiftBase + + def __init__(self, entity, tandem_solutions): + self.entity = entity + self.composition = entity + self.tandem_solutions = tandem_solutions + self.mass_shift = None + self.best_msms_score = None + self.update_mass_shift_and_score() + + def update_mass_shift_and_score(self): + match = self.best_match_for(self.structure) + if match is not None: + self.mass_shift = match.mass_shift + self.best_msms_score = match.score + + def assign_entity(self, solution_entry: SolutionEntry): + entity = solution_entry.solution + mass_shift = solution_entry.match.mass_shift + self.structure = entity + self.mass_shift = mass_shift + self.best_msms_score = solution_entry.best_score + + @property + def mass_shifts(self): + return [self.mass_shift] + + @property + def structure(self): + return self.entity + + @structure.setter + def structure(self, value): + self.entity = value + self.composition = value + + def __repr__(self): + template = ""{self.__class__.__name__}({self.entity!r}, {self.tandem_solutions}, {self.mass_shift})"" + return template.format(self=self) + + @classmethod + def aggregate(cls, solutions: List[SpectrumSolutionSet]) -> List['TandemSolutionsWithoutChromatogram']: + collect = DefaultDict(list) + for solution in solutions: + best_match = solution.best_solution() + collect[best_match.target.id].append(solution) + out = [] + for group in collect.values(): + solution = group[0] + best_match = solution.best_solution() + structure = best_match.target + out.append(cls(structure, group)) + return out + + +class ScanTimeBundle(object): + solution: SpectrumSolutionSet + scan_time: float + + def __init__(self, solution, scan_time): + self.solution = solution + self.scan_time = scan_time + + @property + def score(self): + try: + return self.solution.score + except AttributeError: + return None + + def __hash__(self): + return hash((self.solution, self.scan_time)) + + def __eq__(self, other): + return self.solution == other.solution and self.scan_time == other.scan_time + + def __repr__(self): + return ""ScanTimeBundle(%s, %0.4f, %0.4f)"" % ( + self.solution.scan.id, self.score, self.scan_time) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/chromatogram_mapping/representer.py",".py","6477","152","import array + +from typing import (Callable, Collection, DefaultDict, + List, TYPE_CHECKING) + +import numpy as np + +from glycresoft.chromatogram_tree import ( + Unmodified) + +from ..spectrum_match import SpectrumMatch, SpectrumSolutionSet + +from .base import SolutionEntry, logger, Predicate, always, TargetType, parsimony_sort + +if TYPE_CHECKING: + from .chromatogram import SpectrumMatchSolutionCollectionBase + + + +class RepresenterSelectionStrategy(object): + __slots__ = () + + def __init__(self, *args, **kwargs): + pass + + def compute_weights(self, collection: 'SpectrumMatchSolutionCollectionBase', threshold_fn: Callable = always, + reject_shifted: bool = False, targets_ignored: Collection = None, require_valid: bool = True) -> List[SolutionEntry]: + raise NotImplementedError() + + def select(self, representers): + raise NotImplementedError() + + def sort_solutions(self, representers): + return parsimony_sort(representers) + + def get_solutions_for_spectrum(self, solution_set: SpectrumSolutionSet, threshold_fn: Callable = always, + reject_shifted: bool = False, targets_ignored: Collection = None, require_valid: bool = True): + return filter(lambda x: x.valid, solution_set.get_top_solutions( + d=5, + reject_shifted=reject_shifted, + targets_ignored=targets_ignored, + require_valid=require_valid)) + + def __call__(self, collection, threshold_fn: Callable = always, reject_shifted: bool = False, + targets_ignored: Collection = None, require_valid: bool = True) -> List[SolutionEntry]: + return self.compute_weights( + collection, + threshold_fn=threshold_fn, + reject_shifted=reject_shifted, + targets_ignored=targets_ignored, + require_valid=require_valid) + + +class TotalBestRepresenterStrategy(RepresenterSelectionStrategy): + def compute_weights(self, collection: 'SpectrumMatchSolutionCollectionBase', threshold_fn: Callable = always, + reject_shifted: bool = False, targets_ignored: Collection = None, require_valid: bool = True) -> List[SolutionEntry]: + scores = DefaultDict(float) + best_scores = DefaultDict(float) + best_spectrum_match = dict() + for psm in collection.tandem_solutions: + if threshold_fn(psm): + sols = list(self.get_solutions_for_spectrum( + psm, + reject_shifted=reject_shifted, + targets_ignored=targets_ignored, + require_valid=require_valid) + ) + for sol in sols: + if not threshold_fn(sol): + continue + if reject_shifted and sol.mass_shift != Unmodified: + continue + scores[sol.target] += (sol.score) + if best_scores[sol.target] < sol.score: + best_scores[sol.target] = sol.score + best_spectrum_match[sol.target] = sol + + if len(scores) == 0 and require_valid and collection.tandem_solutions: + weights = self.compute_weights( + collection, + threshold_fn=threshold_fn, + reject_shifted=reject_shifted, + targets_ignored=targets_ignored, + require_valid=False + ) + if weights: + logger.warning( + f""Failed to find a valid solution for {collection.tandem_solutions}, falling back to previously disqualified solutions"") + return weights + + total = sum(scores.values()) + weights = [ + SolutionEntry(k, v, v / total, best_scores[k], + best_spectrum_match[k]) for k, v in scores.items() + if k in best_spectrum_match + ] + weights = self.sort_solutions(weights) + return weights + + +class TotalAboveAverageBestRepresenterStrategy(RepresenterSelectionStrategy): + def compute_weights(self, collection: 'SpectrumMatchSolutionCollectionBase', threshold_fn: Callable = always, + reject_shifted: bool = False, targets_ignored: Collection = None, require_valid: bool = True) -> List[SolutionEntry]: + scores = DefaultDict(lambda: array.array('d')) + best_scores = DefaultDict(float) + best_spectrum_match = dict() + for psm in collection.tandem_solutions: + if threshold_fn(psm): + sols = self.get_solutions_for_spectrum( + psm, + reject_shifted=reject_shifted, + targets_ignored=targets_ignored, + require_valid=require_valid + ) + for sol in sols: + if not threshold_fn(sol): + continue + if reject_shifted and sol.mass_shift != Unmodified: + continue + scores[sol.target].append(sol.score) + if best_scores[sol.target] < sol.score: + best_scores[sol.target] = sol.score + best_spectrum_match[sol.target] = sol + + if len(scores) == 0 and require_valid and collection.tandem_solutions: + weights = self.compute_weights( + collection, + threshold_fn=threshold_fn, + reject_shifted=reject_shifted, + targets_ignored=targets_ignored, + require_valid=False + ) + if weights: + logger.warning( + f""Failed to find a valid solution for {collection.tandem_solutions}, falling back to previously disqualified solutions"") + return weights + + population = np.concatenate(list(scores.values())) + min_score = np.mean(population) - np.std(population) + scores = {k: np.array(v) for k, v in scores.items()} + thresholded_scores = {k: v[v >= min_score].sum() + for k, v in scores.items()} + + total = sum([v for v in thresholded_scores.values()]) + weights = [ + SolutionEntry(k, v, v / total, best_scores[k], + best_spectrum_match[k]) for k, v in thresholded_scores.items() + if k in best_spectrum_match + ] + weights = self.sort_solutions(weights) + return weights +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/chromatogram_mapping/revision.py",".py","30347","691","from typing import (Any, Callable, Dict, List, Optional, Set, Tuple, Type, Union, + TYPE_CHECKING, NamedTuple) + +import numpy as np + +from ms_deisotope.data_source.scan import ProcessedScan +from ms_deisotope.data_source import ProcessedRandomAccessScanSource + +from glycresoft.task import TaskBase + +from glycresoft.chromatogram_tree.mass_shift import MassShiftBase +from glycresoft.scoring import ChromatogramSolution + +from glycresoft.tandem.target_decoy.base import FDREstimatorBase + +from ..spectrum_match import ( + SpectrumMatch, + SpectrumSolutionSet, + MultiScoreSpectrumMatch, + SpectrumMatcherBase +) + +from .base import Predicate, TargetType, SolutionEntry + +if TYPE_CHECKING: + from .chromatogram import ( + TandemAnnotatedChromatogram, + SpectrumMatchSolutionCollectionBase, + TandemSolutionsWithoutChromatogram + ) + from glycresoft.scoring.elution_time_grouping.structure import ( + ChromatogramProxy, + GlycopeptideChromatogramProxy + ) + from glycresoft.scoring.elution_time_grouping.model import ModelEnsemble as RetentionTimeModelEnsemble + + +class MS2RevisionValidator(TaskBase): + threshold_fn: Predicate + q_value_ratio_threshold: float = 1e9 + + def __init__(self, threshold_fn: Predicate): + self.threshold_fn = threshold_fn + + def has_valid_matches(self, chromatogram: 'TandemAnnotatedChromatogram', member_targets: Set[TargetType]) -> bool: + has_matches = any([chromatogram.solutions_for(target, threshold_fn=self.threshold_fn) + for target in member_targets]) + return has_matches + + def validate_spectrum_match(self, spectrum_match: Union[SpectrumMatch, MultiScoreSpectrumMatch], + solution_set: SpectrumSolutionSet) -> bool: + ## It would be desirable to be able to detect when the difference + ## in explanations are of such radically different quality that + ## any consideration of revision is a waste, but this can't be + ## done reliably as a function of q-value. It might be feasible to do + ## with score, but such a modification would be difficult to tune for + ## different scoring algorithms simultaneously. Perhaps if we + ## had a multidimensional threshold instead of a cascading threshold, + ## but such a thresholding scheme would need to be estimated + ## on the fly. + # best_solution: MultiScoreSpectrumMatch = solution_set.best_solution() + # if not self.threshold_fn(best_solution): + # return True + # ratio = spectrum_match.q_value / best_solution.q_value + # pass_threshold = ratio <= self.q_value_ratio_threshold + # if not pass_threshold: + # self.log( + # f""... Rejecting revision of {spectrum_match.scan.id} from {best_solution.target} to {spectrum_match.target} due to ID confidence {spectrum_match.q_value}/{best_solution.q_value}"") + # return pass_threshold + return True + + def can_rewrite_best_matches(self, chromatogram: 'TandemAnnotatedChromatogram', target: TargetType) -> bool: + # The count of spectra we are able to actually interpret the best spectrum match of + ssets_to_convert = 0 + # The count of spectra where we can reasonably revise the best match + ssets_could_convert = 0 + for sset in chromatogram.tandem_solutions: + if self.threshold_fn(sset.best_solution()): + ssets_to_convert += 1 + try: + match = sset.solution_for(target) + if self.threshold_fn(match) and self.validate_spectrum_match(match, sset): + if not match.best_match: + ssets_could_convert += 1 + except KeyError: + continue + if ssets_to_convert == 0: + return True + return (ssets_could_convert / ssets_to_convert) >= 0.5 + + def do_rewrite_best_matches(self, chromatogram: 'TandemAnnotatedChromatogram', + target: TargetType, + invalidated_targets: Set[TargetType]): + for sset in chromatogram.tandem_solutions: + try: + match = sset.solution_for(target) + if self.threshold_fn(match) and self.validate_spectrum_match(match, sset): + if not match.best_match: + sset.promote_to_best_match(match) + else: + self.debug( + f""... Skipping invalidation of {sset.scan_id!r}, alternative {target} did not pass threshold."") + continue + except KeyError: + # TODO: Fill in missing match against the preferred target + self.debug( + f""... Skipping invalidation of {sset.scan_id!r}, alternative {target} was not matched."") + continue + + for invalid_target in invalidated_targets: + try: + match = sset.solution_for(invalid_target) + except KeyError: + continue + # TODO: Is this really the right way to handle cases with totally + # different peptide backbones? This should require a minimum of MS2 score/FDR + # threshold passing + if match.best_match: + self.debug( + f""... Revoking best match status of {match.target} for scan {match.scan_id!r}"") + match.best_match = False + + +class SignalUtilizationMS2RevisionValidator(MS2RevisionValidator): + utilization_ratio_threshold: float = 0.6 + + def __init__(self, threshold_fn: Predicate, utilization_ratio_threshold: float = 0.6): + super().__init__(threshold_fn) + self.utilization_ratio_threshold = utilization_ratio_threshold + + def validate_spectrum_match(self, spectrum_match: Union[SpectrumMatch, MultiScoreSpectrumMatch], solution_set: SpectrumSolutionSet) -> bool: + baseline = super().validate_spectrum_match(spectrum_match, solution_set) + if not baseline: + return baseline + best_solution: MultiScoreSpectrumMatch = solution_set.best_solution() + if not self.threshold_fn(best_solution): + return True + ratio = spectrum_match.score_set.total_signal_utilization / \ + best_solution.score_set.total_signal_utilization + pass_threshold = ratio >= self.utilization_ratio_threshold + if baseline and not pass_threshold: + self.log( + f""... Rejecting revision of {spectrum_match.scan.id} from {best_solution.target} to {spectrum_match.target} due to signal ratio failing to pass threshold {ratio:0.3f}"") + return pass_threshold + + def has_valid_matches(self, chromatogram: 'TandemAnnotatedChromatogram', targets: Set[TargetType]) -> bool: + has_passing_case = False + # Loop over all targets and check if any of them manage to pass the ratio threshold, + # preventing + for target in targets: + for sset in chromatogram.tandem_solutions: + try: + solution: MultiScoreSpectrumMatch = sset.solution_for( + target) + except KeyError: + continue + + # Don't bother checking solutions that don't pass FDR threshold predicate + if not self.threshold_fn(solution): + continue + + if self.validate_spectrum_match(solution, sset): + # If a match passes the threshold, then something in this solution set is valid + has_passing_case = True + break + else: + # Otherwise keep checking solution sets + continue + + # If we found a valid match, we're done. + if has_passing_case: + break + + return has_passing_case + + +class SpectrumMatchBackFiller(TaskBase): + scorer: Type[SpectrumMatcherBase] + match_args: Dict[str, Any] + + spectrum_match_cls: Type[SpectrumMatch] + fdr_estimator: Optional[FDREstimatorBase] + threshold_fn: Predicate + mass_shifts: Optional[List[MassShiftBase]] + + scan_loader: ProcessedRandomAccessScanSource + + def __init__(self, scan_loader: ProcessedRandomAccessScanSource, + scorer: Type[SpectrumMatcherBase], + spectrum_match_cls: Type[SpectrumMatch], + id_maker, + threshold_fn: Predicate = lambda x: x.q_value < 0.05, + match_args=None, + fdr_estimator: Optional[FDREstimatorBase] = None, + mass_shifts: Optional[List[MassShiftBase]] = None): + if match_args is None: + match_args = {} + self.scan_loader = scan_loader + self.scorer = scorer + self.match_args = match_args + self.spectrum_match_cls = spectrum_match_cls + self.id_maker = id_maker + self.fdr_estimator = fdr_estimator + self.threshold_fn = threshold_fn + self.mass_shifts = mass_shifts + + def select_best_mass_shift_for(self, scan: ProcessedScan, + structure: TargetType, + mass_shifts: List[MassShiftBase]) -> Tuple[Optional[MassShiftBase], float]: + observed_mass = scan.precursor_information.neutral_mass + theoretical_mass = structure.total_mass + delta = observed_mass - theoretical_mass + + best_shift = None + best_shift_error = float('inf') + + for shift in mass_shifts: + err = delta - shift.mass + abs_err = abs(err) + if abs_err < best_shift_error: + best_shift = shift + best_shift_error = abs_err + return best_shift, best_shift_error + + def id_for_structure(self, structure: TargetType, reference: TargetType): + structure.protein_relation = reference.protein_relation + structure.id = self.id_maker(structure, reference) + return structure + + def evaluate_spectrum(self, scan_id: str, structure: TargetType, mass_shifts: List[MassShiftBase]) -> SpectrumMatcherBase: + scan = self.scan_loader.get_scan_by_id(scan_id) + best_shift, best_shift_error = self.select_best_mass_shift_for( + scan, structure, mass_shifts) + match = self.scorer.evaluate( + scan, structure, mass_shift=best_shift, **self.match_args) + return match + + def add_matches_to_solution_set(self, sset: SpectrumSolutionSet, + targets: List[TargetType], + mass_shifts: Optional[List[MassShiftBase]] = None, + should_promote: bool=False) -> List[Tuple[SpectrumSolutionSet, SpectrumMatch, bool]]: + if mass_shifts is None: + mass_shifts = self.mass_shifts + + solution_set_match_pairs = [] + + scan_id = sset.scan_id + for inst in targets: + matched = self.evaluate_spectrum( + scan_id, inst, mass_shifts) + match = self.spectrum_match_cls.from_match_solution( + matched) + match.scan = sset.scan + sset.insert(0, match) + solution_set_match_pairs.append((sset, match, False)) + + sset.sort() + sset.mark_top_solutions() + if self.fdr_estimator is not None: + self.fdr_estimator.score_all(sset) + + for inst in targets: + match = sset.solution_for(inst) + if self.threshold_fn(match) and should_promote: + match.best_match = True + sset.promote_to_best_match(match) + return solution_set_match_pairs + + +class SpectrumMatchInvalidatinCallback: + target_to_find: TargetType + threshold_fn: Callable[[SpectrumMatch], bool] + + def __init__(self, target_to_find: TargetType, threshold_fn: Callable[[SpectrumMatch], bool]): + self.target_to_find = target_to_find + self.threshold_fn = threshold_fn + + def __call__(self, sset: SpectrumSolutionSet, sm: SpectrumMatch) -> bool: + try: + preferred_sm = sset.solution_for(self.target_to_find) + if not self.threshold_fn(preferred_sm): + return True + return False + except KeyError: + return True + + +class MatchMarkResult(NamedTuple): + targets: Set[TargetType] + match_count: int + + def __add__(self, other: 'MatchMarkResult'): + if other is None: + return self + return self.__class__( + self.targets | other.targets, + self.match_count + other.match_count + ) + + @classmethod + def empty(cls): + return cls(set(), 0) + + +InvalidationFilter = Callable[[SpectrumSolutionSet, SpectrumMatch], bool] + + +class RevisionSummary(NamedTuple): + accepted: bool + rejected_matches: Optional[MatchMarkResult] = None + invalidated_matches: Optional[MatchMarkResult] = None + + @property + def rejected_match_count(self): + if not self.rejected_matches: + return 0 + return self.rejected_matches.match_count + + @property + def invalidated_match_count(self): + if not self.invalidated_matches: + return 0 + return self.invalidated_matches.match_count + + +class SpectrumMatchUpdater(SpectrumMatchBackFiller): + """"""Generate updates to :class:`TandemAnnotatedChromatogram` from chromatogram reviser like an RT predictor. + + This type needs to: + 1. Generate new spectrum matches using the same scorer if a solution set lacks + a match to the suggested target. + 2. Re-calculate the FDR of the new matches if needed. + 3. Generate a new unique ID for each source peptide that a glycopeptide matching + the revised glycoform could come from, that is consistent with the previous + ID space that other glycopeptides used. + 4. Update the assigned entity of each assigned chromatogram so that the correct + structure is the ""best match"", discarding the :class:`SolutionEntry` for the + incorrect assignment *without* deleting the spectrum matches to that themselves. + """""" + + spectrum_match_cls: Type[SpectrumMatch] + threshold_fn: Callable[[SpectrumMatch], bool] + fdr_estimator: FDREstimatorBase + match_args: Dict[str, Any] + + retention_time_delta: float + retention_time_model: 'RetentionTimeModelEnsemble' + + def __init__(self, scan_loader, + scorer, + spectrum_match_cls, + id_maker, + threshold_fn=lambda x: x.q_value < 0.05, + match_args=None, + fdr_estimator=None, retention_time_model=None, + retention_time_delta=0.35): + if match_args is None: + match_args = {} + + super().__init__( + scan_loader, + scorer, + spectrum_match_cls, + id_maker, + threshold_fn, + match_args, + fdr_estimator) + + self.retention_time_model = retention_time_model + self.retention_time_delta = retention_time_delta + + def _find_identical_keys_and_matches(self, chromatogram: 'SpectrumMatchSolutionCollectionBase', + structure: TargetType) -> Tuple[Set[TargetType], List[Tuple[SpectrumSolutionSet, SpectrumMatch]]]: + structures: Set[TargetType] = set() + key = str(structure) + spectrum_matches: List[Tuple[SpectrumSolutionSet, SpectrumMatch]] = [] + for sset in chromatogram.tandem_solutions: + for sm in sset: + if str(sm.target) == key: + structures.add(sm.target) + spectrum_matches.append((sset, sm)) + return structures, spectrum_matches + + def find_identical_peptides(self, chromatogram: 'SpectrumMatchSolutionCollectionBase', + structure: TargetType) -> Set[TargetType]: + structures, _spectrum_matches = self._find_identical_keys_and_matches( + chromatogram, structure) + return structures + + def find_identical_peptides_and_mark(self, chromatogram: 'SpectrumMatchSolutionCollectionBase', + structure: TargetType, + best_match: bool = False, + valid: bool = False, + reason: Optional[str] = None, + filter_fn: Optional[InvalidationFilter] = None + ) -> MatchMarkResult: + + structures, spectrum_matches = self._find_identical_keys_and_matches( + chromatogram, structure) + k = 0 + for sset, sm in spectrum_matches: + if filter_fn and filter_fn(sset, sm): + self.debug( + f""... NOT Marking {sm.scan_id} -> {sm.target} Valid = {valid},"" + f"" Best Match = {best_match}; Reason: {reason}"") + continue + self.debug( + f""... Marking {sm.scan_id} -> {sm.target} Valid = {valid}, Best Match = {best_match}; Reason: {reason}"") + sm.valid = valid + sm.best_match = best_match + # Do not want to invalidate order as that would force re-sorting + # and that would break any ""promoted"" solution whose score isn't + # the top one. + sset._invalidate(invalidate_order=False) + k += 1 + return MatchMarkResult(structures, k) + + def make_target_filter(self, target_to_find: TargetType) -> InvalidationFilter: + filter_fn = SpectrumMatchInvalidatinCallback( + target_to_find, self.threshold_fn) + + return filter_fn + + def get_spectrum_solution_sets(self, revision: Union['TandemAnnotatedChromatogram', + 'TandemSolutionsWithoutChromatogram', + 'ChromatogramProxy'], + chromatogram: Optional['SpectrumMatchSolutionCollectionBase'] = None, + invalidate_reference: bool = True): + if chromatogram is None: + chromatogram = revision.source + + reference = chromatogram.structure + mass_shifts = revision.mass_shifts + revised_structure = revision.structure + + if invalidate_reference: + reference_peptides, _count = self.find_identical_peptides_and_mark( + chromatogram, + reference, + reason=f""superceded by {revision.structure}"") + else: + reference_peptides = self.find_identical_peptides( + chromatogram, reference) + + revised_solution_sets = self.collect_matches( + chromatogram, + revised_structure, + mass_shifts, + reference_peptides, + should_promote=invalidate_reference) + + if self.fdr_estimator is not None: + for sset in chromatogram.tandem_solutions: + self.fdr_estimator.score_all(sset) + return revised_solution_sets + + def collect_candidate_solutions_for_rt_validation(self, chromatogram: Union['TandemAnnotatedChromatogram', + 'TandemSolutionsWithoutChromatogram'], + structure: TargetType, + rt_score: float, + overridden: Optional[TargetType] = None) -> Tuple[ + List[SolutionEntry], + List[SolutionEntry], + List[SolutionEntry], + Set[TargetType] + ]: + from glycresoft.scoring.elution_time_grouping import GlycopeptideChromatogramProxy + from .chromatogram import TandemSolutionsWithoutChromatogram + + representers: List[SolutionEntry] = chromatogram.compute_representative_weights( + self.threshold_fn) + + keep: List[SolutionEntry] = [] + match: List[SolutionEntry] = [] + rejected: List[SolutionEntry] = [] + invalidated: Set[TargetType] = set() + alternative_rt_scores: Dict[TargetType, float] = {} + + for r in representers: + if str(r.solution) == overridden: + rejected.append(r) + elif str(r.solution) == structure: + match.append(r) + else: + if self.retention_time_model and not isinstance(chromatogram, TandemSolutionsWithoutChromatogram): + if r.solution not in alternative_rt_scores: + proxy = GlycopeptideChromatogramProxy.from_chromatogram( + chromatogram) + proxy.structure = r.solution + alt_rt_score = alternative_rt_scores[r.solution] = self.retention_time_model.score_interval( + proxy, 0.01) + else: + alt_rt_score = alternative_rt_scores[r.solution] + if np.isnan(alt_rt_score) and not np.isnan(rt_score): + self.log( + f""RT score for alternative {r.solution} is NaN, reference {structure}"" + f"" RT score is {rt_score:0.3f}"") + elif not np.isnan(alt_rt_score) and np.isnan(rt_score): + self.log( + f""RT score alternative {r.solution} is {alt_rt_score:0.3f}, reference"" + f"" {structure} RT score is NaN"") + # If either is NaN, this is always false, so we never invalidate a NaN-predicted case. + if (rt_score - alt_rt_score) > self.retention_time_delta: + invalidated.add(r.solution) + continue + keep.append(r) + + return match, keep, rejected, invalidated + + def process_revision(self, revision: 'GlycopeptideChromatogramProxy', + chromatogram: Union[ + 'TandemAnnotatedChromatogram', + 'TandemSolutionsWithoutChromatogram'] = None) -> 'TandemAnnotatedChromatogram': + + if chromatogram is None: + chromatogram = revision.source + + reference = chromatogram.structure + revised_structure = revision.structure + assert reference != revised_structure + + _revised_solution_sets = self.get_spectrum_solution_sets( + revision, + chromatogram, + invalidate_reference=True + ) + + representers: List[SolutionEntry] = chromatogram.compute_representative_weights( + self.threshold_fn) + + revised_rt_score = None + if self.retention_time_model: + revised_rt_score = self.retention_time_model.score_interval( + revision, 0.01) + + match, keep, rejected, invalidated = self.collect_candidate_solutions_for_rt_validation( + chromatogram, revised_structure, revised_rt_score, reference) + + if not match: + self.log(""... Failed to identify alternative %s for %s passing the threshold"" % ( + revised_structure, reference)) + return chromatogram, RevisionSummary(False, None, None) + + alternative_filter_fn = self.make_target_filter(revised_structure) + + rejected_track = MatchMarkResult(set(), 0) + for reject in rejected: + marks = self.find_identical_peptides_and_mark( + chromatogram, + reject.solution, + reason=f""Rejecting {reject} in favor of {revised_structure}"", + filter_fn=alternative_filter_fn) + rejected_track = rejected_track + marks + + invalidated_track = MatchMarkResult(set(), 0) + for invalid in invalidated: + marks = self.find_identical_peptides_and_mark( + chromatogram, + invalid, + reason=f""... Invalidating {invalid} in favor of {revised_structure}"", + filter_fn=alternative_filter_fn) + invalidated_track = invalidated_track + marks + + marks = self.find_identical_peptides_and_mark( + chromatogram, + reference, + reason=f""superceded by {revision.structure}"") + rejected_track = rejected_track + marks + + representers = chromatogram.filter_entries(match + keep) + # When the input is a ChromatogramSolution, we have to explicitly + # set the attribute on the wrapped chromatogram object, not the wrapper + # or else it will be lost during later unwrapping. + if isinstance(chromatogram, ChromatogramSolution): + chromatogram.chromatogram.representative_solutions = representers + else: + chromatogram.representative_solutions = representers + + # This mutation is safe to call directly since it passes through the + # universal __getattr__ wrapper + chromatogram.assign_entity(match[0]) + return chromatogram, RevisionSummary(True, rejected_track, invalidated_track) + + def collect_matches(self, + chromatogram: 'TandemAnnotatedChromatogram', + structure: TargetType, + mass_shifts: List[MassShiftBase], + reference_peptides: List[TargetType], + should_promote: bool=False) -> List[Tuple[SpectrumSolutionSet, SpectrumMatch, bool]]: + """"""Collect spectrum matches to the new `structure` target, and all identical solutions from different sources for all spectra in `chromatogram`. + + Parameters + ---------- + chromatogram : :class:`~.TandemAnnotatedChromatogram` + The solution collection being traversed. + structure : :class:`~.TargetType` + The new structure we are going to assign to `chromatogram` and wish to + ensure there are spectrum matches for. + mass_shifts : :class:`list` of :class:`~.MassShiftBase` + The mass shifts which are legal to consider for matching `structure` to spectra + with. + reference_peptides : :class:`set` of :class:`~.TargetType` + Other sources of the peptide for `structure` to ensure that all are reported together. + Relies on :attr:`id_maker` to re-create appropriately keyed glycoforms. + should_promote : :class:`bool` + When :const:`True`, matches to ``structure`` are promoted to best-match status if they + pass the :attr:`threshold_fn`. + """""" + solution_set_match_pairs = [] + if structure.id is None or reference_peptides: + instances = self.id_maker(structure, reference_peptides) + else: + instances = [] + for sset in chromatogram.tandem_solutions: + try: + match = sset.solution_for(structure) + if not match.best_match and self.threshold_fn(match) and should_promote: + sset.promote_to_best_match(match) + solution_set_match_pairs.append((sset, match, True)) + except KeyError: + solution_set_match_pairs.extend( + self.add_matches_to_solution_set( + sset, + instances, + mass_shifts, + should_promote=should_promote + ) + ) + return solution_set_match_pairs + + def __call__(self, revision, chromatogram=None): + return self.process_revision(revision, chromatogram=chromatogram) + + def ensure_q_values(self, chromatogram): + for sset in chromatogram.tandem_solutions: + for sm in sset: + if sm.q_value is None and self.fdr_estimator is not None: + self.debug(""... Computing q-value for %s+%s @ %r"" % + (sm.target, sm.mass_shift.name, sm.scan_id)) + self.fdr_estimator.score(sm) + + def affirm_solution(self, chromatogram: 'TandemAnnotatedChromatogram') -> 'TandemAnnotatedChromatogram': + reference_peptides = self.find_identical_peptides( + chromatogram, chromatogram.entity) + + _matches = self.collect_matches( + chromatogram, + chromatogram.entity, + chromatogram.mass_shifts, + reference_peptides, + should_promote=True + ) + revised_rt_score = None + if self.retention_time_model: + revised_rt_score = self.retention_time_model.score_interval( + chromatogram, 0.01) + + self.ensure_q_values(chromatogram) + match, _keep, rejected, invalidated = self.collect_candidate_solutions_for_rt_validation( + chromatogram, chromatogram.entity, revised_rt_score, None) + + filter_fn = self.make_target_filter(chromatogram.entity) + + rejected_track = MatchMarkResult.empty() + for reject in rejected: + marks = self.find_identical_peptides_and_mark( + chromatogram, + reject.solution, + reason=f""Rejecting {reject} in favor of {chromatogram.entity}"", + filter_fn=filter_fn + ) + rejected_track = rejected_track + marks + + invalidated_track = MatchMarkResult.empty() + for invalid in invalidated: + marks = self.find_identical_peptides_and_mark( + chromatogram, + invalid, + reason=f""Invalidating {invalid} in favor of {chromatogram.entity}"", + filter_fn=filter_fn + ) + invalidated_track = invalidated_track + marks + + if not match: + self.log(""... Failed to affirm %s @ %0.2f passing the threshold"" % ( + chromatogram.entity, getattr(chromatogram, ""apex_time"", -1))) + affirmed = False + else: + affirmed = True + return chromatogram, RevisionSummary(affirmed, rejected_track, invalidated_track) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/chromatogram_mapping/base.py",".py","2225","76","import os +import logging +from typing import (Any, Callable, Hashable, + List, Tuple, NamedTuple, Union) + +from glycresoft.chromatogram_tree.mass_shift import MassShiftBase + +from glycresoft.structure.structure_loader import FragmentCachingGlycopeptide + +from ..spectrum_match.spectrum_match import SpectrumMatch +from ..spectrum_match.solution_set import NOParsimonyMixin + + +DEBUG_MODE = bool(os.environ.get('GLYCRESOFTCHROMATOGRAMDEBUG', False)) + +logger = logging.getLogger(""glycresoft.chromatogram_mapping"") +logger.addHandler(logging.NullHandler()) + + +def always(x): + return True + + +def default_threshold(x): + return x.q_value < 0.05 + + +Predicate = Callable[[Any], bool] +TargetType = Union[Any, FragmentCachingGlycopeptide] + + +class SolutionEntry(NamedTuple): + solution: Any + score: float + percentile: float + best_score: float + match: SpectrumMatch + + +class NOParsimonyRepresentativeSelector(NOParsimonyMixin): + def get_score(self, solution: SolutionEntry) -> float: + return solution.percentile + + def get_target(self, solution: SolutionEntry) -> Any: + return solution.match.target + + def sort(self, solution_set: List[SolutionEntry]) -> List[SolutionEntry]: + solution_set = sorted( + solution_set, key=lambda x: x.percentile, reverse=True) + try: + if solution_set and self.get_target(solution_set[0]).is_o_glycosylated(): + solution_set = self.hoist_equivalent_n_linked_solution( + solution_set) + except AttributeError: + import warnings + warnings.warn(""Could not determine glycosylation state of target of type %r"" % type( + self.get_target(solution_set[0]))) + return solution_set + + def __call__(self, solution_set: List[SolutionEntry]) -> List[SolutionEntry]: + return self.sort(solution_set) + + +parsimony_sort = NOParsimonyRepresentativeSelector() + + +def build_glycopeptide_key(solution) -> Tuple: + structure = solution + key = (str(structure.clone().deglycosylate()), + str(structure.glycan_composition)) + return key + + +KeyTargetMassShift = Tuple[Hashable, TargetType, MassShiftBase] +KeyMassShift = Tuple[Hashable, MassShiftBase] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/chromatogram_mapping/mapper.py",".py","6657","153","from typing import (Callable, Collection, + List, Optional, Type, Union) + +from ms_deisotope.peak_dependency_network.intervals import IntervalTreeNode + +from glycresoft.chromatogram_tree import ( + ChromatogramFilter, Chromatogram, build_rt_interval_tree, GlycopeptideChromatogram) + +from glycresoft.task import TaskBase + +from ..spectrum_match import SpectrumSolutionSet + +from .base import default_threshold, Predicate, DEBUG_MODE +from .revision import MS2RevisionValidator +from .chromatogram import TandemAnnotatedChromatogram, TandemSolutionsWithoutChromatogram, ScanTimeBundle +from .aggregation import GraphAnnotatedChromatogramAggregator + + +class ChromatogramMSMSMapper(TaskBase): + chromatograms: List[TandemAnnotatedChromatogram] + orphans: Union[List[ScanTimeBundle], + List[TandemSolutionsWithoutChromatogram]] + error_tolerance: float + rt_tree: IntervalTreeNode + scan_id_to_rt: Callable[[str], float] + + def __init__(self, chromatograms: Collection[Chromatogram], error_tolerance: float=1e-5, scan_id_to_rt=lambda x: x): + self.chromatograms = ChromatogramFilter(map( + TandemAnnotatedChromatogram, chromatograms)) + self.rt_tree = build_rt_interval_tree(self.chromatograms) + self.scan_id_to_rt = scan_id_to_rt + self.orphans = [] + self.error_tolerance = error_tolerance + + def find_chromatogram_spanning(self, time: float): + return ChromatogramFilter([interv[0] for interv in self.rt_tree.contains_point(time)]) + + def find_chromatogram_for(self, solution: SpectrumSolutionSet): + try: + precursor_scan_time = self.scan_id_to_rt( + solution.precursor_information.precursor_scan_id) + except Exception: + precursor_scan_time = self.scan_id_to_rt(solution.scan_id) + overlapping_chroma = self.find_chromatogram_spanning( + precursor_scan_time) + chromas = overlapping_chroma.find_all_by_mass( + solution.precursor_information.neutral_mass, self.error_tolerance) + if len(chromas) == 0: + self.orphans.append(ScanTimeBundle(solution, precursor_scan_time)) + else: + if len(chromas) > 1: + chroma = max(chromas, key=lambda x: x.total_signal) + else: + chroma = chromas[0] + chroma.tandem_solutions.append(solution) + + def assign_solutions_to_chromatograms(self, solutions: Collection[SpectrumSolutionSet]): + n = len(solutions) + for i, solution in enumerate(solutions): + if i % 5000 == 0: + self.log(""... %d/%d Solutions Handled (%0.2f%%)"" % + (i, n, (i * 100.0 / n))) + self.find_chromatogram_for(solution) + if DEBUG_MODE: + breakpoint() + + def distribute_orphans(self, threshold_fn: Predicate=default_threshold): + lost = [] + n = len(self.orphans) + n_chromatograms = len(self.chromatograms) + for j, orphan in enumerate(self.orphans): + mass = orphan.solution.precursor_ion_mass + time = orphan.scan_time + + if j % 5000 == 0: + self.log(""... %r %d/%d Orphans Handled (%0.2f%%)"" % + (orphan, j, n, (j * 100.0 / n))) + + candidates = self.chromatograms.find_all_by_mass( + mass, self.error_tolerance) + if len(candidates) > 0: + best_index = 0 + best_distance = float('inf') + for i, candidate in enumerate(candidates): + dist = min(abs(candidate.start_time - time), + abs(candidate.end_time - time)) + if dist < best_distance: + best_index = i + best_distance = dist + new_owner = candidates[best_index] + + if best_distance > 5: + if threshold_fn(orphan.solution): + lost.append(orphan.solution) + continue + + if DEBUG_MODE: + self.log(""... Assigning %r to %r with %d existing solutions with distance %0.3f"" % + (orphan, new_owner, len(new_owner.tandem_solutions), best_distance)) + new_owner.add_displaced_solution(orphan.solution) + else: + if threshold_fn(orphan.solution): + if n_chromatograms > 0 and DEBUG_MODE: + self.log(""No chromatogram found for %r, q-value %0.4f (mass: %0.4f, time: %0.4f)"" % ( + orphan, orphan.solution.q_value, mass, time)) + lost.append(orphan.solution) + self.log(""Distributed %d orphan identifications, %d did not find a nearby chromatogram"" % ( + n, len(lost))) + self.orphans = TandemSolutionsWithoutChromatogram.aggregate(lost) + + def assign_entities(self, threshold_fn: Predicate=default_threshold, + entity_chromatogram_type: Type[Chromatogram]=None): + if entity_chromatogram_type is None: + entity_chromatogram_type = GlycopeptideChromatogram + for chromatogram in self: + solutions = chromatogram.most_representative_solutions( + threshold_fn) + if solutions: + solutions = sorted( + solutions, key=lambda x: x.score, reverse=True) + chromatogram.assign_entity( + solutions[0], entity_chromatogram_type=entity_chromatogram_type) + chromatogram.representative_solutions = solutions + if DEBUG_MODE: + breakpoint() + + def merge_common_entities(self, annotated_chromatograms: List[TandemAnnotatedChromatogram], + delta_rt: float = 0.25, + require_unmodified: bool = True, + threshold_fn: Predicate = default_threshold, + revision_validator: Optional[MS2RevisionValidator] = None): + job = GraphAnnotatedChromatogramAggregator( + annotated_chromatograms, + delta_rt=delta_rt, + require_unmodified=require_unmodified, + threshold_fn=threshold_fn, + revision_validator=revision_validator + ) + result = job.run() + return result + + def __len__(self): + return len(self.chromatograms) + + def __iter__(self): + return iter(self.chromatograms) + + def __getitem__(self, i): + if isinstance(i, (int, slice)): + return self.chromatograms[i] + else: + return [self.chromatograms[j] for j in i] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/chromatogram_mapping/graph.py",".py","32129","736","from typing import (Any, Callable, Collection, DefaultDict, Dict, Hashable, + List, Optional, Set, Tuple, NamedTuple, Type, Union, + TYPE_CHECKING) + +from glycresoft.chromatogram_tree.mass_shift import MassShiftBase, Unmodified +from glycresoft.chromatogram_tree.relation_graph import ( + ChromatogramGraph, ChromatogramGraphEdge, ChromatogramGraphNode, TimeQuery) + +from glycresoft.task import TaskBase + +from ..spectrum_match import SpectrumMatch + +from .base import Predicate, always, SolutionEntry, TargetType, parsimony_sort, KeyMassShift, KeyTargetMassShift, build_glycopeptide_key +from .revision import MS2RevisionValidator, SpectrumMatchBackFiller + + +if TYPE_CHECKING: + from .chromatogram import TandemAnnotatedChromatogram + + +class MassShiftDeconvolutionGraphNode(ChromatogramGraphNode): + chromatogram: 'TandemAnnotatedChromatogram' + + def __init__(self, chromatogram, index, edges=None): + super(MassShiftDeconvolutionGraphNode, self).__init__( + chromatogram, index, edges=edges) + + def most_representative_solutions(self, threshold_fn: Predicate = always, reject_shifted: bool = False, percentile_threshold: float = 1e-5) -> List['SolutionEntry']: + """"""Find the most representative solutions, the (very nearly the same, hopefully) structures with + the highest aggregated score across all MSn events assigned to this collection. + + Parameters + ---------- + threshold_fn: Callable + A function that filters out invalid solutions based on some criteria, e.g. + not passing the FDR threshold. + reject_shifted: bool + Whether or not to omit any solution that was not mass-shifted. Defaults to False + percentile_threshold : float, optional + The difference between the worst and best percentile to be reported. Defaults to 1e-5. + + Returns + ------- + list + A list of solutions with approximately the greatest weight + """""" + return self.chromatogram.most_representative_solutions( + threshold_fn=threshold_fn, reject_shifted=reject_shifted, + percentile_threshold=percentile_threshold + ) + + def solutions_for(self, structure, threshold_fn: Predicate = always, reject_shifted: bool = False) -> List[SpectrumMatch]: + return self.chromatogram.solutions_for( + structure, threshold_fn=threshold_fn, reject_shifted=reject_shifted) + + @property + def mass_shifts(self): + return self.chromatogram.mass_shifts + + @property + def tandem_solutions(self): + return self.chromatogram.tandem_solutions + + @property + def total_signal(self): + return self.chromatogram.total_signal + + @property + def entity(self): + return self.chromatogram.entity + + def best_match_for(self, structure, threshold_fn: Predicate = always) -> SpectrumMatch: + solutions = self.solutions_for(structure, threshold_fn=threshold_fn) + if not solutions: + raise KeyError(structure) + best_score = -float('inf') + best_match = None + for sol in solutions: + if best_score < sol.score: + best_score = sol.score + best_match = sol + return best_match + + +class MassShiftDeconvolutionGraphEdge(ChromatogramGraphEdge): + def __hash__(self): + return hash(frozenset((self.node_a.index, self.node_b.index))) + + def __eq__(self, other): + if frozenset((self.node_a.index, self.node_b.index)) == frozenset((other.node_a.index, other.node_b.index)): + return self.transition == other.transition + return False + + def __ne__(self, other): + return not self == other + + +class MassShiftDeconvolutionGraph(ChromatogramGraph[MassShiftDeconvolutionGraphNode, MassShiftDeconvolutionGraphEdge]): + node_cls = MassShiftDeconvolutionGraphNode + edge_cls = MassShiftDeconvolutionGraphEdge + + mass_shifts: Set[MassShiftBase] + + def __init__(self, chromatograms: List['TandemAnnotatedChromatogram']): + super(MassShiftDeconvolutionGraph, self).__init__(chromatograms) + mass_shifts = set() + for node in self: + mass_shifts.update(node.mass_shifts) + self.mass_shifts = mass_shifts + + @property + def tandem_solutions(self): + solution_sets = [] + for node in self.nodes: + solution_sets.extend(node.tandem_solutions) + return solution_sets + + def __iter__(self): + return iter(self.nodes) + + def _construct_graph_nodes(self, chromatograms: List['TandemAnnotatedChromatogram']): + nodes = [] + for i, chroma in enumerate(chromatograms): + node = (self.node_cls(chroma, i)) + nodes.append(node) + if node.chromatogram.composition: + self.enqueue_seed(node) + self.assignment_map[node.chromatogram.composition] = node + return nodes + + def find_edges(self, node: MassShiftDeconvolutionGraphNode, query_width: float = 0.01, threshold_fn: Predicate = always, **kwargs): + query = TimeQuery(node.chromatogram, query_width) + nodes: List[MassShiftDeconvolutionGraphNode] = self.rt_tree.overlaps( + query.start, query.end) + + structure = node.chromatogram.structure + + for other in nodes: + solutions = other.solutions_for( + structure, threshold_fn=threshold_fn) + if solutions: + shifts_in_solutions = frozenset( + {m.mass_shift for m in solutions}) + self.edges.add( + self.edge_cls(node, other, (frozenset(node.mass_shifts), shifts_in_solutions))) + + def build(self, query_width: float = 0.01, threshold_fn: Predicate = always, **kwargs): + for node in self.iterseeds(): + self.find_edges(node, query_width=query_width, + threshold_fn=threshold_fn, **kwargs) + + +class RepresenterDeconvolution(TaskBase): + max_depth = 10 + threshold_fn: Predicate + key_fn: Callable[[TargetType], Hashable] + + group: List[MassShiftDeconvolutionGraphNode] + + conflicted: DefaultDict[MassShiftDeconvolutionGraphNode, List[KeyTargetMassShift]] + solved: DefaultDict[KeyTargetMassShift, List[MassShiftDeconvolutionGraphNode]] + participants: DefaultDict[KeyTargetMassShift, List[MassShiftDeconvolutionGraphNode]] + best_scores: DefaultDict[KeyMassShift, float] + + key_to_solutions: DefaultDict[KeyTargetMassShift, Set[TargetType]] + + spectrum_match_backfiller: Optional[""SpectrumMatchBackFiller""] + revision_validator: MS2RevisionValidator + + def __init__(self, group, threshold_fn=always, key_fn=build_glycopeptide_key, + spectrum_match_backfiller: Optional[""SpectrumMatchBackFiller""]=None, + revision_validator: Optional[MS2RevisionValidator]=None): + if revision_validator is None: + revision_validator = MS2RevisionValidator(threshold_fn) + self.group = group + self.threshold_fn = threshold_fn + self.key_fn = key_fn + self.spectrum_match_backfiller = spectrum_match_backfiller + self.revision_validator = revision_validator + + self.participants = None + self.key_to_solutions = None + self.conflicted = None + self.solved = None + self.best_scores = None + + self.build() + + def _simplify(self): + # When there is an un-considered double shift, this could lead to + # choosing that double-shift being called a trivial solution and + # locking in a specific interpretation regardless of weight. So + # this method won't be used automatically. + + # Search all members' assignment lists and see if any + # can be easily assigned. + for member, conflicts in list(self.conflicted.items()): + # There is no conflict, trivially solved. + if len(conflicts) == 1: + self.solved[conflicts[0]].append(member) + self.conflicted.pop(member) + else: + keys = {k for k, e, m in conflicts} + # There are multiple structures, but they all share the same key, essentially + # a positional isomer. Trivially solved, but need to use care when merging to avoid + # combining the different isomers. + if len(keys) == 1: + self.solved[conflicts[0]].append(member) + self.conflicted.pop(member) + + def build(self): + '''Construct the initial graph, populating all the maps + and then correcting for unsupported mass shifts. + ''' + participants = DefaultDict(list) + conflicted = DefaultDict(list) + key_to_solutions = DefaultDict(set) + best_scores = DefaultDict(float) + + for member in self.group: + for part in member.most_representative_solutions( + threshold_fn=self.threshold_fn, reject_shifted=False, percentile_threshold=0.4): + key = self.key_fn(part.solution) + mass_shift = part.match.mass_shift + score = part.best_score + key_to_solutions[key].add(part.solution) + participants[key, part.solution, mass_shift].append(member) + best_scores[key, mass_shift] = max(score, best_scores[key, mass_shift]) + conflicted[member].append((key, part.solution, mass_shift)) + + for part in member.most_representative_solutions( + threshold_fn=self.threshold_fn, reject_shifted=True, percentile_threshold=0.4): + key = self.key_fn(part.solution) + mass_shift = part.match.mass_shift + score = part.best_score + key_to_solutions[key].add(part.solution) + best_scores[key, mass_shift] = max(score, best_scores[key, mass_shift]) + participants[key, part.solution, mass_shift].append(member) + conflicted[member].append((key, part.solution, mass_shift)) + + self.solved = DefaultDict(list) + self.participants = participants + self.conflicted = conflicted + self.best_scores = best_scores + self.key_to_solutions = key_to_solutions + self.prune_unsupported_participants() + + def find_supported_participants(self) -> Dict[Tuple, bool]: + has_unmodified = DefaultDict(bool) + for (key, solution, mass_shift) in self.participants: + if mass_shift == Unmodified: + has_unmodified[key] = True + return has_unmodified + + def prune_unsupported_participants(self, support_map: Dict[Tuple, bool] = None): + '''Remove solutions that are not supported by an Unmodified + condition except when there is *no alternative*. + + Uses :meth:`find_supported_participants` to label solutions. + + Returns + ------- + pruned_conflicts : dict[list] + A mapping from graph node to pruned solution + restored : list + A list of the solutions that would have been pruned + but had to be restored to give a node support. + ''' + + if support_map is None: + support_map = self.find_supported_participants() + + pruned_participants: Dict[KeyTargetMassShift, List[MassShiftDeconvolutionGraphNode]] = {} + pruned_scores: Dict[Tuple[Hashable, MassShiftBase], float] = {} + pruned_conflicts: DefaultDict[MassShiftDeconvolutionGraphNode, + List[Tuple[Hashable, TargetType, MassShiftBase]]] = DefaultDict(list) + pruned_solutions: List[TargetType] = [] + kept_solutions = [] + + key: Hashable + solution: TargetType + mass_shift: MassShiftBase + # Loop through the participants, removing links to unsupported solutions + # and their metadata. + for (key, solution, mass_shift), nodes in list(self.participants.items()): + if not support_map[key]: + q = (key, solution, mass_shift) + try: + pruned_scores[key, mass_shift] = self.best_scores.pop((key, mass_shift)) + except KeyError: + pass + pruned_participants[q] = self.participants.pop(q) + pruned_solutions.append(solution) + for node in nodes: + pruned_conflicts[node].append(q) + self.conflicted[node].remove(q) + else: + kept_solutions.append(solution) + + restored: List[MassShiftDeconvolutionGraphNode] = [] + # If all solutions for a given node have been removed, have to put them back. + for node, options in list(self.conflicted.items()): + if not options: + alternatives = self.find_alternatives( + node, pruned_solutions) + if alternatives: + for alt in alternatives: + solution = alt.target + mass_shift = alt.mass_shift + key = self.key_fn(solution) + q = key, solution, mass_shift + + self.participants[q].append(node) + self.conflicted[node].append(q) + self.key_to_solutions[key].add(solution) + if self.threshold_fn(alt): + self.best_scores[key, mass_shift] = max( + alt.score, self.best_scores[key, mass_shift]) + else: + self.best_scores[key, mass_shift] = 1e-3 + continue + + restored.append(node) + self.conflicted[node] = conflicts = pruned_conflicts.pop(node) + for q in conflicts: + (key, solution, mass_shift) = q + try: + self.best_scores[key, mass_shift] = pruned_scores.pop( + (key, mass_shift)) + except KeyError: + pass + self.participants[q].append(node) + return pruned_conflicts, restored + + def find_alternatives(self, node: MassShiftDeconvolutionGraphNode, pruned_solutions, ratio_threshold=0.9): + alternatives = {alt_solution for _, + alt_solution, _ in self.participants} + ratios = [] + + for solution in pruned_solutions: + for sset in node.tandem_solutions: + try: + sm = sset.solution_for(solution) + if not self.threshold_fn(sm): + continue + for alt in alternatives: + try: + sm2 = sset.solution_for(alt) + weight1 = sm.score + weight2 = sm2.score / weight1 + if weight2 > ratio_threshold: + ratios.append((weight1, weight2, sm, sm2)) + except KeyError: + continue + except KeyError: + continue + ratios.sort(key=lambda x: (x[0], x[1]), reverse=True) + if not ratios: + return [] + weight1, weight2, sm, sm2 = ratios[0] + kept = [] + for pair in ratios: + if weight1 - pair[0] > 1e-5: + break + if weight2 - pair[1] > 1e-5: + break + kept.append(sm2) + return kept + + def resolve(self): + '''For each conflicted node, try to assign it to a solution based upon + the set of all solved nodes. + + Returns + ------- + changes : int + The number of nodes assigned during this execution. + ''' + tree: DefaultDict[Hashable, Dict[MassShiftBase, List[MassShiftDeconvolutionGraphNode]]] = DefaultDict(dict) + # Build a tree of key->mass_shift->members + for (key, solution, mass_shift), members in self.solved.items(): + tree[key][mass_shift] = list(members) + + changes = 0 + + # For each conflicted member, search through all putative explanations of the + # chromatogram and see if another mass shift state has been identified + # for that explanation's key. If so, and that explanation spans this + # member, then add the putative explanation to the set of hits with weight + # equal to that best score (sum across all supporting mass shifts for same key) + # for that putative explanation. + # Sort for determinism. + for member, conflicts in sorted( + self.conflicted.items(), + key=lambda x: x[0].chromatogram.total_signal, reverse=True): + hits: DefaultDict[KeyTargetMassShift, float] = DefaultDict(float) + for key, solution, mass_shift in conflicts: + # Other solved groups' keys to solved mass shifts + shifts_to_solved = tree[key] + for solved_mass_shift, solved_members in shifts_to_solved.items(): + if any(m.overlaps(member) for m in solved_members): + hits[key, solution, mass_shift] += self.best_scores[key, solved_mass_shift] + if not hits: + continue + # Select the solution with the greatest total weight. + ordered_options = sorted(hits.items(), key=lambda x: x[1], reverse=True) + (best_key, best_solution, best_mass_shift), score = ordered_options[0] + + # Add a new solution to the tracker, and update the tree + self.solved[best_key, best_solution, best_mass_shift].append(member) + tree[best_key][best_mass_shift] = self.solved[best_key, best_solution, best_mass_shift] + + self.conflicted.pop(member) + changes += 1 + return changes + + def total_weight_for_keys(self, score_map=None): + if score_map is None: + score_map = self.best_scores + acc = DefaultDict(list) + for (key, mass_shift), score in score_map.items(): + acc[key].append(score) + return { + key: sum(val) for key, val in acc.items() + } + + def nominate_key_mass_shift(self, score_map=None): + '''Find the key with the greatest total score + over all mass shifts and nominate it and its + best mass shift. + + Returns + ------- + key : tuple + The key tuple for the best solution + mass_shift : :class:`~.MassShiftBase` + The best mass shift for the best solution + ''' + if score_map is None: + score_map = self.best_scores + totals = self.total_weight_for_keys(score_map) + if len(totals) == 0: + return None, None + best_key, _ = max(totals.items(), key=lambda x: x[1]) + + best_mass_shift = None + best_score = -float('inf') + for (key, mass_shift), score in score_map.items(): + if key == best_key: + if best_score < score: + best_score = score + best_mass_shift = mass_shift + return best_key, best_mass_shift + + def find_starting_point(self): + '''Find a starting point for deconvolution and mark it as solved. + + Returns + ------- + key : tuple + The key tuple for the best solution + best_match : object + The target that belongs to this key-mass shift pair. + mass_shift : :class:`~.MassShiftBase` + The best mass shift for the best solution + ''' + nominated_key, nominated_mass_shift = self.nominate_key_mass_shift() + if nominated_key is None: + return None, None, None + best_node = best_match = None + assignable = [] + + for member, conflicts in self.conflicted.items(): + for key, solution, mass_shift in conflicts: + if (key == nominated_key) and (mass_shift == nominated_mass_shift): + try: + match = member.best_match_for(solution, threshold_fn=self.threshold_fn) + if match is None: + continue + assignable.append((member, match)) + except KeyError: + continue + if not assignable: + self.log(""Could not find a solution matching %r %r. Trying to drop the mass shift."" % (nominated_key, nominated_mass_shift)) + for member, conflicts in self.conflicted.items(): + for key, solution, mass_shift in conflicts: + self.log(key) + if (key == nominated_key): + self.log(""Key Match %r for %r"" % (key, solution)) + try: + match = member.best_match_for(solution, threshold_fn=self.threshold_fn) + self.log(""Match: %r"" % match) + if match is None: + self.log(""Match is None, skipping"") + continue + assignable.append((member, match)) + except KeyError as err: + self.log(""KeyError, skipping: %r"" % err) + continue + + + if assignable: + best_node, best_match = max(assignable, key=lambda x: x[1].score) + + self.solved[nominated_key, best_match.target, nominated_mass_shift].append(best_node) + self.conflicted.pop(best_node) + return nominated_key, best_match, nominated_mass_shift + + def recurse(self, depth=0): + subgroup = list(self.conflicted) + subprob = self.__class__(subgroup, threshold_fn=self.threshold_fn, key_fn=self.key_fn) + subprob.solve(depth=depth + 1) + + for key, val in subprob.solved.items(): + self.solved[key].extend(val) + + n = len(self.conflicted) + k = len(subprob.conflicted) + changed = n - k + self.conflicted = subprob.conflicted + return changed + + def default(self): + '''Assign each chromatogram to its highest scoring identification + individually, the solution graph could not be deconvolved. + ''' + for member, conflicts in list(self.conflicted.items()): + entry = member.most_representative_solutions(threshold_fn=self.threshold_fn)[0] + key = self.key_fn(entry.solution) + self.solved[key, entry.solution, entry.match.mass_shift].append(member) + self.conflicted.pop(member) + + def solve(self, depth=0): + '''Deconvolve the graph, removing conflicts and adding nodes to the + solved set. + + If no nodes are solved initially, :meth:`find_starting_point` is used to select one. + + Solutions are found using :meth:`resolve` to build on starting points and + :meth:`recurse` + + ''' + if depth > self.max_depth: + self.default() + return self + if not self.solved: + nominated_key, _, _ = self.find_starting_point() + if nominated_key is None: + self.log(""No starting point found in %r, defaulting."", self.group) + self.default() + return self + + i = 0 + while self.conflicted: + changed = self.resolve() + if changed == 0 and self.conflicted: + changed = self.recurse(depth) + if changed == 0: + break + i += 1 + if i > 20: + break + return self + + def _representer_best_scores_percentiles(self, member: 'TandemAnnotatedChromatogram', solutions: Set[TargetType]) -> Tuple[Dict[TargetType, SpectrumMatch], Dict[TargetType, float], Dict[TargetType, float]]: + entries: Dict[TargetType, List[SpectrumMatch]] = dict() + for sol in solutions: + entries[sol] = member.solutions_for( + sol, threshold_fn=self.threshold_fn) + scores: Dict[TargetType, float] = {} + total = 1e-6 + best_matches: Dict[TargetType, SpectrumMatch] = {} + for k, v in entries.items(): + best_match: Optional[SpectrumMatch] = None + sk: float = 0 + for match in v: + if best_match is None or best_match.score < match.score: + best_match = match + sk += match.score + best_matches[k] = best_match + scores[k] = sk + total += sk + percentiles = {k: v / total for k, v in scores.items()} + return best_matches, scores, percentiles + + def _representer_solution_entries(self, member: 'TandemAnnotatedChromatogram', + best_matches: Dict[TargetType, SpectrumMatch], + scores: Dict[TargetType, float], + percentiles: Dict[TargetType, float]) -> List[SolutionEntry]: + sols = [] + for k, best_match in best_matches.items(): + score = scores[k] + if best_match is None: + try: + best_match = member.best_match_for(k) + except KeyError: + continue + score = best_match.score + sols.append( + SolutionEntry( + k, score, percentiles[k], best_match.score, best_match)) + + sols = parsimony_sort(sols) + return sols + + def assign_representers(self, percentile_threshold=1e-5): + '''Apply solutions to solved graph nodes, constructing new chromatograms with + corrected mass shifts, entities, and representative_solution attributes and then + merge within keys as appropriate. + + Returns + ------- + merged : list[ChromatogramWrapper] + The merged chromatograms + ''' + # Note suggested to switch to list, but reason unclear. + assigned: DefaultDict[Any, Set['TandemAnnotatedChromatogram']] = DefaultDict(set) + + invalidated_alternatives: DefaultDict[Any, Set[TargetType]] = DefaultDict(set) + + # For each (key, mass shift) pair and their members, compute the set of representers for + # that key from all structures that as subsumed into it (repeated peptide and alternative + # localization). + # NOTE: Alternative localizations fall under the same key, so we have to re-do ranking + # of solutions again here to make sure that the aggregate scores are available to separate + # different localizations. Alternatively, may need to port in localization-separating key + # logic. + _mass_shift: MassShiftBase + for (key, _solution, _mass_shift), members in self.solved.items(): + # We do not use _mass_shift here because it will be inferred from the best solution + # for `key` on the chromatogram anyway, we only needed it keep the hash distinct + # + # We look up solutions instead of using _solution from the loop here because + # shared peptides between proteins need to be tracked separately. + solutions = self.key_to_solutions[key] + for member in members: + # Summarize each explainer + best_matches, scores, percentiles = self._representer_best_scores_percentiles(member, solutions) + + # Pack each explainer into a SolutionEntry instance + sols = self._representer_solution_entries(member, best_matches, scores, percentiles) + if sols: + # This difference is not using the absolute value to allow for scenarios where + # a worse percentile is located at position 0 e.g. when hoisting via parsimony. + representers = [x for x in sols if ( + sols[0].percentile - x.percentile) < percentile_threshold] + else: + representers = [] + + # Mass shifts will be applied when we assign the representer + fresh = member.chromatogram.clone().drop_mass_shifts() + + fresh.assign_entity(representers[0]) + fresh.representative_solutions = representers + + assigned[key].add(fresh) + if key != self.key_fn(member.chromatogram.entity): + invalidated_alternatives[key].add(member.chromatogram.entity) + + merged = [] + for key, members in assigned.items(): + members: List['TandemAnnotatedChromatogram'] = sorted(members, key=lambda x: x.start_time) + invalidated_targets = invalidated_alternatives[key] + retained: List['TandemAnnotatedChromatogram'] = [] + + member_targets: Set[TargetType] = set() + for chrom in members: + member_targets.add(chrom.entity) + + member_targets -= invalidated_targets + + can_merge: List['TandemAnnotatedChromatogram'] = [] + + for member in members: + if self.revision_validator.has_valid_matches(member, member_targets): + can_merge.append(member) + else: + retained_solutions = member.most_representative_solutions(self.threshold_fn) + member.representative_solutions = retained_solutions + member.assign_entity(retained_solutions[0]) + retained.append(member) + + sink = None + if can_merge: + sink = can_merge[0] + did_update_sink_id = False + if sink.entity not in member_targets: + self.error(f""... While deconvolving mass shifts, sink node {sink}'s label not in valid list {member_targets}"") + options = sorted( + filter( + lambda x: x.solution in member_targets, + sink.compute_representative_weights( + self.threshold_fn) + ), + key=lambda x: x.score, + reverse=True + ) + if options: + self.error(f""... Failed to re-assign {sink} to a valid target"") + sink.assign_entity(options[0]) + # May not be exhaustive enough, search for ""best"" case in `can_merge` matching + # to a `member_targets` before assigning `sink` role to a chromatogram? + did_update_sink_id = True + + for member in can_merge[1:]: + # Might this obscure the ""best localization""? Perhaps, but localization is already getting + # mowed down at the aggregate level. + if self.revision_validator.can_rewrite_best_matches(member, sink.entity): + self.revision_validator.do_rewrite_best_matches(member, sink.entity, invalidated_targets) + sink.merge_in_place(member) + else: + retained_solutions = member.most_representative_solutions(self.threshold_fn) + member.representative_solutions = retained_solutions + member.assign_entity(retained_solutions[0]) + retained.append(member) + + if did_update_sink_id: + options = sorted( + filter( + lambda x: x.solution in member_targets, + sink.compute_representative_weights( + self.threshold_fn) + ), + key=lambda x: x.score, + reverse=True + ) + if options: + self.error(f""... Failed to re-assign {sink} to a valid target after merging!"") + sink.assign_entity(options[0]) + + if sink is not None: + merged.append(sink) + if retained: + merged.extend(retained) + return merged +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycan/composition_matching.py",".py","9099","221","from collections import defaultdict + +from multiprocessing import Manager as IPCManager + +from glycopeptidepy.structure.glycan import GlycanCompositionProxy + +from glycresoft.task import TaskBase +from .scoring.signature_ion_scoring import SignatureIonScorer +from ..chromatogram_mapping import ChromatogramMSMSMapper + +from ..process_dispatcher import ( + IdentificationProcessDispatcher, + SpectrumIdentificationWorkerBase) + + +class ChromatogramAssignmentRecord(GlycanCompositionProxy): + def __init__(self, glycan_composition, id_key, index): + self.glycan_composition = glycan_composition + self.id_key = id_key + self.index = index + GlycanCompositionProxy.__init__(self, glycan_composition) + + @property + def id(self): + return self.id_key + + def __repr__(self): + return ""{self.__class__.__name__}({self.glycan_composition}, {self.id_key}, {self.index})"".format( + self=self) + + @classmethod + def build(cls, chromatogram, default_glycan_composition=None, index=None): + key = (chromatogram.start_time, chromatogram.end_time, chromatogram.key) + if chromatogram.glycan_composition: + glycan_composition = chromatogram.glycan_composition + else: + glycan_composition = default_glycan_composition + return cls(glycan_composition, key, index) + + +class GlycanCompositionIdentificationWorker(SpectrumIdentificationWorkerBase): + def __init__(self, input_queue, output_queue, done_event, scorer_type, evaluation_args, + spectrum_map, mass_shift_map, log_handler, solution_packer): + SpectrumIdentificationWorkerBase.__init__( + self, input_queue, output_queue, done_event, scorer_type, evaluation_args, + spectrum_map, mass_shift_map, log_handler=log_handler, solution_packer=solution_packer) + + def evaluate(self, scan, structure, *args, **kwargs): + target = structure + matcher = self.scorer_type.evaluate(scan, target, *args, **kwargs) + return matcher + + +class SignatureIonMapper(TaskBase): + + # simple default value from experimentation + minimum_score = 0.05 + + def __init__(self, tandem_scans, chromatograms, scan_id_to_rt=lambda x: x, + mass_shifts=None, minimum_mass=500, batch_size=1000, + default_glycan_composition=None, scorer_type=None, + n_processes=4): + if scorer_type is None: + scorer_type = SignatureIonScorer + if mass_shifts is None: + mass_shifts = [] + self.chromatograms = chromatograms + self.tandem_scans = sorted( + tandem_scans, key=lambda x: x.precursor_information.extracted_neutral_mass, + reverse=True) + self.scan_id_to_rt = scan_id_to_rt + self.mass_shifts = mass_shifts + self.minimum_mass = minimum_mass + self.default_glycan_composition = default_glycan_composition + self.default_glycan_composition.id = -1 + self.scorer_type = scorer_type + self.n_processes = n_processes + self.ipc_manager = IPCManager() + + def prepare_scan_set(self, scan_set): + if hasattr(scan_set[0], 'convert'): + out = [] + # Account for cases where the scan may be mentioned in the index, but + # not actually present in the MS data + for o in scan_set: + try: + scan = (self.scorer_type.load_peaks(o)) + out.append(scan) + except KeyError: + self.log(""Missing Scan: %s"" % (o.id,)) + scan_set = out + out = [] + for scan in scan_set: + try: + out.append(scan) + except AttributeError as e: + self.log(""Missing Scan: %s %r"" % (scan.id, e)) + continue + return out + + def map_to_chromatograms(self, precursor_error_tolerance=1e-5): + mapper = ChromatogramMSMSMapper( + self.chromatograms, error_tolerance=precursor_error_tolerance, + scan_id_to_rt=self.scan_id_to_rt) + for scan in self.tandem_scans: + scan_time = mapper.scan_id_to_rt(scan.precursor_information.precursor_scan_id) + hits = mapper.find_chromatogram_spanning(scan_time) + if hits is None: + continue + match = hits.find_all_by_mass( + scan.precursor_information.neutral_mass, + precursor_error_tolerance) + if match: + for m in match: + m.add_solution(scan) + for mass_shift in self.mass_shifts: + match = hits.find_all_by_mass( + scan.precursor_information.neutral_mass - mass_shift.mass, + precursor_error_tolerance) + if match: + for m in match: + m.add_solution(scan) + return mapper + + def _build_scan_to_entity_map(self, annotated_chromatograms): + + scan_map = dict() + hit_map = dict() + hit_to_scan = dict() + default = self.default_glycan_composition + for i, chroma in enumerate(annotated_chromatograms, 1): + if not chroma.tandem_solutions: + continue + default = default.clone() + default.id = -i + record = ChromatogramAssignmentRecord.build(chroma, default, index=i - 1) + hit_map[record.id] = record + scans = [] + for scan in self.prepare_scan_set(chroma.tandem_solutions): + scan_map[scan.id] = scan + scans.append(scan.id) + hit_to_scan[record.id] = scans + return scan_map, hit_map, hit_to_scan + + def _chunk_chromatograms(self, chromatograms, batch_size=3500): + chunk = [] + k = 0 + for chroma in chromatograms: + chunk.append(chroma) + k += len(chroma.tandem_solutions) + if k >= batch_size: + yield chunk + chunk = [] + k = 0 + yield chunk + + def _score_mapped_tandem_parallel(self, annotated_chromatograms, *args, **kwargs): + for chunk in self._chunk_chromatograms(annotated_chromatograms): + scan_map, hit_map, hit_to_scan = self._build_scan_to_entity_map(chunk) + ipd = IdentificationProcessDispatcher( + worker_type=GlycanCompositionIdentificationWorker, + scorer_type=self.scorer_type, + init_args={}, evaluation_args=kwargs, + n_processes=self.n_processes, + ipc_manager=self.ipc_manager) + scan_solution_map = ipd.process(scan_map, hit_map, hit_to_scan, defaultdict(lambda: ""Unmodified"")) + + for scan_id, matches in scan_solution_map.items(): + for match in matches: + chroma = chunk[match.target.index] + updated_scans = [] + for scan in chroma.tandem_solutions: + if scan.scan_id == scan_id: + # match.scan = SpectrumReference(scan_id, scan.precursor_information) + match.target = match.target.glycan_composition + updated_scans.append(match) + else: + updated_scans.append(scan) + chroma.tandem_solutions = updated_scans + return annotated_chromatograms + + def _score_mapped_tandem_sequential(self, annotated_chromatograms, *args, **kwargs): + i = 0 + + ni = len(annotated_chromatograms) + for chroma in annotated_chromatograms: + i += 1 + if i % 500 == 0: + self.log(""... Handling chromatogram %d/%d (%0.3f%%)"" % (i, ni, (i * 100. / ni))) + tandem_scans = self.prepare_scan_set(chroma.tandem_solutions) + if chroma.glycan_composition is None: + if self.default_glycan_composition is None: + continue + else: + glycan_composition = self.default_glycan_composition + else: + glycan_composition = chroma.glycan_composition + solutions = [] + j = 0 + nj = len(tandem_scans) + for scan in tandem_scans: + j += 1 + if j % 500 == 0: + self.log(""...... Handling spectrum match %d/%d (%0.3f%%)"" % (j, nj, (j * 100. / nj))) + + solution = self.scorer_type.evaluate( + scan, glycan_composition, + *args, **kwargs) + solutions.append(solution) + chroma.tandem_solutions = solutions + return annotated_chromatograms + + def score_mapped_tandem(self, annotated_chromatograms, *args, **kwargs): + if self.n_processes > 1: + annotated_chromatograms = self._score_mapped_tandem_parallel( + annotated_chromatograms, **kwargs) + else: + annotated_chromatograms = self._score_mapped_tandem_sequential( + annotated_chromatograms, **kwargs) + return annotated_chromatograms +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycan/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycan/denovo.py",".py","1057","27","import itertools + +from glypy.composition import Composition +from glypy.composition.composition_transform import strip_derivatization +from glypy.structure.glycan_composition import FrozenMonosaccharideResidue, MonosaccharideResidue +from glypy.io.nomenclature.identity import is_a + +from glycresoft.structure.fragment_match_map import SpectrumGraph +from glycresoft.structure.denovo import MassWrapper, PathFinder + + +class DeNovoSolution(object): + def __init__(self, scan, supporting_paths=None, completion_gap=None): + self.scan = scan + self.supporting_paths = supporting_paths + self.completion_gap = completion_gap + + @property + def precursor_mass(self): + return self.scan.precursor_information.neutral_mass + + +class DeNovoGlycanSequencer(PathFinder): + def __init__(self, spectrum, components, precursor_error_tolerance=1e-5, product_error_tolerance=2e-5): + super(DeNovoGlycanSequencer, self).__init__(spectrum, components, product_error_tolerance) + self.precursor_error_tolerance = precursor_error_tolerance +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycan/scoring/signature_ion_scoring.py",".py","8136","218","import itertools + +from collections import Counter + +import numpy as np + +from glypy.structure.fragment import Fragment +from glypy.composition import Composition +from glypy.composition.composition_transform import strip_derivatization +from glypy.structure.glycan_composition import MonosaccharideResidue +from glypy.io.nomenclature.identity import is_a + +from glycresoft.structure import FragmentMatchMap +from glycresoft.structure.fragment_match_map import SpectrumGraph +from glycresoft.tandem.spectrum_match import SpectrumMatcherBase + +from glycopeptidepy.utils.memoize import memoize + + +dhex = MonosaccharideResidue.from_iupac_lite(""dHex"") + + +@memoize(100000000000) +def is_dhex(residue): + try: + return is_a( + strip_derivatization(residue.clone( + monosaccharide_type=MonosaccharideResidue)), dhex) + except TypeError: + if not isinstance(residue, MonosaccharideResidue): + return False + else: + raise + + +class SignatureIonScorer(SpectrumMatcherBase): + def __init__(self, scan, glycan_composition, mass_shift=None, use_oxonium=True): + super(SignatureIonScorer, self).__init__(scan, glycan_composition, mass_shift) + self.fragments_searched = 0 + self.fragments_matched = 0 + self.minimum_intensity_threshold = 0.01 + self.use_oxonium = use_oxonium + + def _get_matched_peaks(self): + peaks = set() + for peak in self.solution_map.by_peak: + peaks.add(peak) + for p1, p2, label in self.spectrum_graph: + peaks.add(p1) + peaks.add(p2) + return peaks + + def percent_matched_intensity(self): + matched = 0 + total = 0 + + for peak in self._get_matched_peaks(): + matched += peak.intensity + + for peak in self.spectrum: + total += peak.intensity + return matched / total + + def _find_peak_pairs(self, error_tolerance=2e-5, include_compound=False, *args, **kwargs): + peak_set = self.spectrum + pairs = SpectrumGraph() + + blocks = [(part, part.mass()) for part in self.target if not is_dhex(part)] + if include_compound: + compound_blocks = list(itertools.combinations(self.target, 2)) + compound_blocks = [(block, sum(part.mass() for part in block)) + for block in compound_blocks] + blocks.extend(compound_blocks) + try: + max_peak = max([p.intensity for p in peak_set]) + threshold = max_peak * self.minimum_intensity_threshold + except ValueError: + return [] + + for peak in peak_set: + if peak.intensity < threshold or peak.neutral_mass < 150: + continue + for block, mass in blocks: + for other in peak_set.all_peaks_for(peak.neutral_mass + mass, error_tolerance): + if other.intensity < threshold: + continue + pairs.add(peak, other, block) + return pairs + + def match(self, error_tolerance=2e-5, include_compound=False, combination_size=3, *args, **kwargs): + glycan_composition = self.target + peak_set = self.spectrum + matches = FragmentMatchMap() + water = Composition(""H2O"") + counter = 0 + try: + max_peak = max([p.intensity for p in peak_set]) + threshold = max_peak * self.minimum_intensity_threshold + except ValueError: + self.solution_map = matches + self.fragments_searched = counter + self.pairs = SpectrumGraph() + return matches + # Simple oxonium ions + for k in glycan_composition.keys(): + # dhex does not produce a reliable oxonium ion + if is_dhex(k): + continue + counter += 1 + f = Fragment('B', {}, [], k.mass(), name=str(k), + composition=k.total_composition()) + for hit in peak_set.all_peaks_for(f.mass, error_tolerance): + if hit.intensity < threshold: + continue + matches.add(hit, f) + f = Fragment('B', {}, [], k.mass() - water.mass, name=""%s-H2O"" % str(k), + composition=k.total_composition() - water) + for hit in peak_set.all_peaks_for(f.mass, error_tolerance): + if hit.intensity / max_peak < self.minimum_intensity_threshold: + continue + matches.add(hit, f) + + # Compound oxonium ions + if include_compound: + for i in range(2, combination_size + 1): + for kk in itertools.combinations_with_replacement(sorted(glycan_composition, key=str), i): + counter += 1 + invalid = False + for k, v in Counter(kk).items(): + if glycan_composition[k] < v: + invalid = True + break + if invalid: + continue + key = '-'.join(map(str, kk)) + mass = sum(k.mass() for k in kk) + composition = sum((k.total_composition() for k in kk), Composition()) + f = Fragment('B', {}, [], mass, name=key, + composition=composition) + for hit in peak_set.all_peaks_for(f.mass, error_tolerance): + if hit.intensity / max_peak < 0.01: + continue + matches.add(hit, f) + + f = Fragment('B', {}, [], mass - water.mass, name=""%s-H2O"" % key, + composition=composition - water) + for hit in peak_set.all_peaks_for(f.mass, error_tolerance): + if hit.intensity / max_peak < 0.01: + continue + matches.add(hit, f) + + self.spectrum_graph = self._find_peak_pairs(error_tolerance, include_compound) + self.solution_map = matches + self.fragments_searched = counter + return matches + + def penalize(self, ratio, count): + count = float(count) + scale = min(np.log(count) / np.log(4), 1) + return ratio * scale + + def oxonium_ratio(self): + imax = max(self.spectrum, key=lambda x: x.intensity).intensity + oxonium = 0 + n = 0 + for peak, fragment in self.solution_map: + oxonium += peak.intensity / imax + n += 1 + self.fragments_matched = n + if n == 0: + return 0, 0 + return (oxonium / n), n + + def _score_pairs(self): + try: + imax = max(self.spectrum, key=lambda x: x.intensity).intensity + except ValueError: + return 0 + edge_weight = 0 + n = 0 + for p1, p2, label in self.spectrum_graph: + edge_weight += (p1.intensity + p2.intensity) / imax + n += 1 + if n == 0: + return 0 + scale = max(min(np.log(n) / np.log(4), 1), 0.01) + return (edge_weight / n) * scale + + def calculate_score(self, error_tolerance=2e-5, include_compound=False, *args, **kwargs): + if len(self.spectrum) == 0: + self._score = 0 + return self._score + + use_oxonium = kwargs.get(""use_oxonium"") + if use_oxonium is not None: + self.use_oxonium = use_oxonium + + if self.use_oxonium: + try: + oxonium_ratio, n = self.oxonium_ratio() + except ValueError: + oxonium_ratio, n = 0, 0 + else: + oxonium_ratio = n = 0 + if n == 0: + self._score = 0 + else: + # simple glycan compositions like high mannose N-glycans don't produce + # many distinct oxonium ions + if len(self.target.items()) > 2: + self._score = self.penalize(oxonium_ratio, n) + else: + self._score = oxonium_ratio + edge_weight = self._score_pairs() + if edge_weight > self._score: + self._score = edge_weight + return self._score +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycan/scoring/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycan/scoring/base.py",".py","2083","49","import glypy + +from glycresoft.structure import FragmentMatchMap +from glycresoft.tandem.spectrum_match import SpectrumMatcherBase + +water = glypy.Composition(""H2O"") +water_mass = water.mass + + +class GlycanSpectrumMatcherBase(SpectrumMatcherBase): + + def _match_fragments(self, series, error_tolerance=2e-5, max_cleavages=2, include_neutral_losses=None): + for fragment in self.target.fragments(series, max_cleavages=max_cleavages): + peaks = self.spectrum.all_peaks_for(fragment.mass, error_tolerance) + for peak in peaks: + self.solution_map.add(peak, fragment) + if include_neutral_losses: + for loss, label in include_neutral_losses: + peaks = self.spectrum.all_peaks_for( + fragment.mass - loss.mass, error_tolerance) + if peaks: + fragment_loss = fragment.copy() + fragment_loss.mass -= loss.mass + fragment_loss.composition -= loss + fragment_loss.name += label + for peak in peaks: + self.solution_map.add(peak, fragment_loss) + + def match(self, error_tolerance=2e-5, *args, **kwargs): + self.solution_map = FragmentMatchMap() + include_neutral_losses = kwargs.get(""include_neutral_losses"", False) + max_cleavages = kwargs.get(""max_cleavages"", 2) + is_hcd = self.is_hcd() + is_exd = self.is_exd() + if include_neutral_losses and isinstance(include_neutral_losses, (int, bool)): + include_neutral_losses = [(glypy.Composition(""H2O""), ""-H2O"")] + + if is_hcd: + self._match_fragments( + ""BY"", error_tolerance, max_cleavages=max_cleavages, + include_neutral_losses=include_neutral_losses) + else: + self._match_fragments( + ""ABCXYZ"", error_tolerance, max_cleavages=max_cleavages, + include_neutral_losses=include_neutral_losses) + + def _theoretical_mass(self): + return self.target.mass() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycan/scoring/binomial_coverage/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycan/scoring/binomial_coverage/score_components.py",".py","5390","164","from scipy.misc import comb +import numpy as np + +import math +from collections import defaultdict + +from glypy.utils import make_struct + + +#: Store whether a fragment was observed for the reducing or non-reducing end of a particular glycosidic bond +GlycosidicBondMatch = make_struct(""GlycosidicBondMatch"", [""reducing"", ""non_reducing""]) + +#: Store how many times a fragment was observed for the reducing, non-reducing, or non-bisecting cross-ring +#: permutations of a particular monosaccharide +CrossringMatch = make_struct(""CrossringMatch"", [""reducing"", ""non_reducing"", ""non_bisecting""]) + + +def is_primary_fragment(f): + return f.break_count == 1 + + +class FragmentScorer(object): + """"""Score the data with respect to structure characterization. + + Attributes + ---------- + crossring_map : dict + Mapping of residue id to CrossringMatch + crossring_score : float + Score derived from cross-ring coverage + final_score : float + The final product score combining glycosidic and cross-ring scores + fragments : list + The list of matched fragments + glycosidic_map : dict + Mapping of link id to GlycosidicBondMatch + glycosidic_score : float + Score derived from glycosidic fragments + structure : StructureRecord + Source structure to be matched + """""" + def __init__(self, structure, matched_fragments): + self.structure = structure + self.fragments = list(filter(is_primary_fragment, matched_fragments)) + + self.glycosidic_map = defaultdict(lambda: GlycosidicBondMatch(0, 0)) + self.crossring_map = defaultdict(lambda: CrossringMatch(0, 0, 0)) + + self.glycosidic_score = 0. + self.crossring_score = 0. + + self._score_glycosidic() + self._score_crossring() + + self.final_score = 0. + self._score_final() + + def _score_final(self): + self.final_score = -100 * np.log10((1 - self.glycosidic_score) * (1 - self.crossring_score)) + + def _score_glycosidic(self): + for f in [f for f in self.fragments if not f.crossring_cleavages]: + link_ind = f.link_ids.keys()[0] + link_rec = self.glycosidic_map[link_ind] + if f.kind in ""BC"": + link_rec.non_reducing = 1 + else: + link_rec.reducing = 1 + + self.glycosidic_score = sum(map(sum, self.glycosidic_map.values())) / (2. * (len(self.structure) - 1)) + + def _score_crossring(self): + + def has_parent(fragment, residue): + parents = {n.id for p, n in residue.parents()} + return bool(parents & fragment.included_nodes) + + def has_child(fragment, residue): + children = {n.id for p, n in residue.children()} + return bool(children & fragment.included_nodes) + + for f in [f for f in self.fragments if not f.link_ids]: + residue = self.structure.get(f.crossring_cleavages.keys()[0]) + residue_record = self.crossring_map[residue.id] + + parent = has_parent(f, residue) + child = has_child(f, residue) + + if parent and child: + residue_record.non_bisecting += 1 + elif parent: + residue_record.reducing += 1 + elif child: + residue_record.non_reducing += 1 + + self.crossring_score = sum(map(sum, self.crossring_map.values())) / (3. * len(self.structure)) + + +def binomial_tail_probability(n, k, p): + total = 0.0 + for i in range(k, n): + total += comb(n, i, exact=True) * (p ** i) * ((1 - p) ** (n - i)) + return total + + +def drop_below_intensity(peaks, threshold): + return [p for p in peaks if p.intensity > threshold] + + +def median_intensity(peaks): + return np.median([p.intensity for p in peaks]) + + +SimplePeak = make_struct(""SimplePeak"", [""intensity""]) + + +epsilon = 1e-10 + + +class IntensityRankScorer(object): + """"""Scores an assigned peak list against a uniform intensity + random model. + + Attributes + ---------- + assigned_peaks : list + The collection of assigned and deconvoluted peaks + final_score : float + The final score for this data + medians : dict + A cache for already computed median intensities + peaklist : list + The set of all experimental peaks + scores : dict + Scores for each tier + transformed_peaks : list + The collection of assigned peaks' most abundant peaks + """""" + def __init__(self, peaklist, assigned_peaks): + self.peaklist = peaklist + self.assigned_peaks = assigned_peaks + self.transformed_peaks = [SimplePeak( + max([p.intensity for p in sol.fit.experimental])) for sol in assigned_peaks] + self.scores = {} + self.medians = {0: 0} + self.final_score = 0. + self.rank() + + def rank(self): + for a in range(1, 5): + med = median_intensity( + drop_below_intensity( + self.transformed_peaks, + self.medians[a - 1])) + self.medians[a] = med + i = len(drop_below_intensity(self.transformed_peaks, med)) + n = len(drop_below_intensity(self.peaklist, self.medians[a - 1])) + p = binomial_tail_probability(n, i, 0.5) + self.scores[a] = p + total = 0. + for p in self.scores.values(): + total += math.log(p + epsilon) + self.final_score = -np.log10(math.exp(total)) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/glycan/scoring/binomial_coverage/matcher.py",".py","4227","99","from ms_deisotope import CompositionListPeakDependenceGraphDeconvoluter, DistinctPatternFitter + +from glycresoft.database.composition_aggregation import Formula, CommonComposition, Composition +from glycresoft.tandem.spectrum_match import SpectrumMatcherBase + + +from .score_components import IntensityRankScorer, FragmentScorer + + +def get_fragments(assigned_peaks): + results = set() + for peak in assigned_peaks: + results.update(peak.solution.base_data) + return results + + +class BinomialCoverageSpectrumMatcher(SpectrumMatcherBase): + """"""Encapsulates the process of matching experimental peaks to theoretical peaks. + + Given a :class:`ms_peak_picker.PeakIndex` from a :class:`MSMSScan` and a :class:`StructureRecord` + instance, this type will determine the set of all compositions needed to search, handling ambiguous + compositions and managing the searching process. + + Attributes + ---------- + assigned_peaks : list + The list of deconvolved peaks that were assigned compositions + composition_list : list + The list of compositions to attempt to assign + matched_fragments : list + The list of theoretical fragments for which compositions were assigned + peak_set : ms_peak_picker.PeakIndex + The list of experimental peaks + structure_record : StructureRecord + The structure to search for fragments from + """""" + def __init__(self, scan, target): + super(BinomialCoverageSpectrumMatcher, self).__init__(scan, target) + self.peak_set = self.scan.peak_set + self.composition_list = None + self.assigned_peaks = None + self.matched_fragments = None + + self.make_composition_list() + + @property + def structure(self): + return self.target + + def make_composition_list(self): + """"""Aggregate all theoretical compositions by formula so that each composition + is present exactly once, containing all possible sources of that composition in + a single :class:`CommonComposition` instance. + + Sets the :attr:`composition_list` attribute. Called during initialization. + """""" + self.composition_list = CommonComposition.aggregate( + Formula(f.composition, f) for f in self.structure.fragment_map.values()) + + # Is there anything added by including the precursor? Maybe in the graph solving step + # f = Formula(self.structure_record.structure.total_composition(), self.structure_record) + # self.composition_list.append(CommonComposition(f, [f.data])) + + def match(self, mass_tolerance=5e-6, charge_carrier=Composition(""Na"").mass, fitter_parameters=None): + """"""Perform the actual matching of peaks, fitting isotopic patterns and retrieving the matched + structural features. + + Parameters + ---------- + mass_tolerance : float, optional + The parts-per-million mass error tolerance allowed. Defaults to 5ppm, entered as 5e-6 + charge_range : tuple, optional + The a tuple defining the minimum and maximum of the range of charge states to consider + for each composition. Defaults to positive (1, 3) + charge_carrier : float, optional + The mass of the charge carrying element. By default for the experimental set up described + here, this is the mass of a sodium (Na) + + Returns + ------- + SpectrumSolution + """""" + + if fitter_parameters is None: + fitter_parameters = {} + + charge_range = (1, self.scan.precursor_information.charge) + dec = CompositionListPeakDependenceGraphDeconvoluter( + self.peak_set, self.composition_list, + scorer=DistinctPatternFitter(**fitter_parameters)) + self.assigned_peaks = dec.deconvolute( + charge_range=charge_range, charge_carrier=charge_carrier, + error_tolerance=mass_tolerance) + self.matched_fragments = list(get_fragments(self.assigned_peaks)) + + self._structure_scorer = FragmentScorer(self.structure, self.matched_fragments) + self._spectrum_scorer = IntensityRankScorer(self.peak_set, self.assigned_peaks) + self.score = self._spectrum_scorer.final_score + self._structure_scorer.final_score +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/match_between_runs/match_between.py",".py","12681","284","import csv +import warnings +from collections import defaultdict, namedtuple + +from glycresoft.task import TaskBase +from glycresoft.chromatogram_tree.utils import ArithmeticMapping +from glycresoft.chromatogram_tree.chromatogram import GlycopeptideChromatogram +from glycresoft.scoring import ChromatogramSolution +from glycresoft.tandem.chromatogram_mapping import TandemAnnotatedChromatogram +from glycresoft.tandem.identified_structure import IdentifiedStructure + +from glycresoft.plotting import chromatogram_artist + + +MergeAction = namedtuple(""MergeAction"", (""label"", ""existing"", ""new"", ""shift"")) +CreateAction = namedtuple( + ""CreateAction"", (""label"", ""structure"", ""chromatogram"", ""shift"")) +LinkAction = namedtuple('LinkAction', ('label', 'from_', 'to', ""shift"", 'reason')) + + +class SharedIdentification(object): + def __init__(self, identification_key, identifications=None, links=None): + if identifications is None: + identifications = dict() + if links is None: + links = set() + self.identification_key = identification_key + self.identifications = dict(identifications) + self.links = links + + @property + def structure(self): + return self.identification_key + + def __getitem__(self, key): + return self.identifications[key] + + def __setitem__(self, key, value): + self.identifications[key] = value + + def __contains__(self, key): + return key in self.identifications + + def __iter__(self): + return iter(self.identifications) + + def __len__(self): + return len(self.identifications) + + def keys(self): + return self.identifications.keys() + + def values(self): + return self.identifications.values() + + def items(self): + return self.identifications.items() + + def __repr__(self): + template = ""{self.__class__.__name__}({self.identification_key}, {self.identifications})"" + return template.format(self=self) + + def weighted_neutral_masses(self): + result = ArithmeticMapping() + for key, value in self.identifications.items(): + result[key] = value.weighted_neutral_mass + return result + + def apex_times(self): + result = ArithmeticMapping() + for key, value in self.identifications.items(): + result[key] = value.apex_time + return result + + def total_signals(self): + result = ArithmeticMapping() + for key, value in self.identifications.items(): + result[key] = value.total_signal + return result + + def plot(self, ax=None, **kwargs): + label_map = {v.chromatogram: k for k, v in self.items()} + + def labeler(chromatogram, *args, **kwargs): + return label_map[chromatogram] + + art = chromatogram_artist.SmoothingChromatogramArtist( + self.values(), label_peaks=False, ax=ax, **kwargs) + return art.draw(label_function=labeler, legend_cols=1) + + +class MatchBetweenRunBuilder(TaskBase): + def __init__(self, datasets, mass_error_tolerance=1e-5, time_error_tolerance=2.0): + self.datasets = datasets + self.feature_table = dict() + self.build_feature_table() + self.labels = sorted([mbd.label for mbd in self.datasets]) + + self.mass_error_tolerance = mass_error_tolerance + self.time_error_tolerance = time_error_tolerance + + def build_feature_table(self, mass_error_tolerance=1e-5, time_error_tolerance=2.0): + for mbd in self.datasets: + for ids in mbd.identified_structures: + try: + shared = self.feature_table[ids.structure] + except KeyError: + shared = SharedIdentification(ids.structure) + self.feature_table[ids.structure] = shared + if mbd.label in shared: + current = shared[mbd.label] + self.log(""Multiple entries for %r in %r"" % + (ids, mbd.label)) + shared[mbd.label] = max( + [current, ids], key=lambda x: x.total_signal or 0) + self.log(""Chose %r"" % (shared[mbd.label], )) + else: + shared[mbd.label] = ids + + def get_by_label(self, label): + for mbd in self.datasets: + if mbd.label == label: + return mbd + return None + + def create(self, label, structure, chromatogram, shift): + self.log(""Creating %r as %r in %r"" % (chromatogram, structure, label)) + mbd = self.get_by_label(label) + ids = mbd.create(structure, chromatogram, shift) + if ids is not None: + shared_id = self.feature_table[structure] + shared_id[mbd.label] = ids + mbd.add(ids) + + def merge(self, label, structure, new, shift): + self.log(""Merging %r into %r in %r"" % (new, structure, label)) + mbd = self.get_by_label(label) + if isinstance(new, IdentifiedStructure): + if new == structure: + raise ValueError(""Cannot merge the same structure"") + elif new.structure.full_structure_equality(structure.structure): + raise ValueError(""Cannot merge equivalent structure"") + else: + raise ValueError(""Cannot merge ambiguous structure"") + new = new.chromatogram + mbd.merge(structure, new, shift) + + def link(self, label, structure_from, structure_to, shift, reason): + sf = self.feature_table[structure_from] + st = self.feature_table[structure_to] + link = LinkAction(label, structure_from, structure_to, shift, reason) + sf.links.add(link) + st.links.add(link) + + def search(self, shared_id, mass_error_tolerance=1e-5, time_error_tolerance=2.0): + create_actions = set() + merge_actions = set() + link_actions = set() + + for inst in shared_id.values(): + merges, creates, links = self.find( + inst, mass_error_tolerance, time_error_tolerance) + create_actions.update(creates) + merge_actions.update(merges) + link_actions.update(links) + return merge_actions, create_actions, link_actions + + def match_structure_between(self, shared_id, mass_error_tolerance=1e-5, time_error_tolerance=2.0): + merge_actions, create_actions, link_actions = self.search( + shared_id, mass_error_tolerance, time_error_tolerance) + + create_actions = sorted( + create_actions, key=lambda x: x.chromatogram.total_signal, reverse=True) + merge_actions = sorted( + merge_actions, key=lambda x: x.new.total_signal, reverse=True) + link_actions = sorted( + link_actions, key=lambda x: max(x.from_.total_signal, x.to.total_signal), reverse=True) + + for action in create_actions: + self.create(action.label, action.structure, + action.chromatogram, action.shift) + + for action in merge_actions: + self.merge(action.label, action.existing, action.new, action.shift) + + for action in link_actions: + self.link(action.label, action.from_.structure, + action.to.structure, action.shift, action.reason) + + return merge_actions, create_actions, link_actions + + def find(self, ids, mass_error_tolerance=1e-5, time_error_tolerance=2.0): + create_actions = set() + merge_actions = set() + link_actions = set() + + for mbd in self.datasets: + shared_id = self.feature_table[ids.structure] + out = mbd.find(ids, mass_error_tolerance, time_error_tolerance) + # We've identified this structure in this sample already + if mbd.label in shared_id: + existing_match = shared_id[mbd.label] + for entity, shift in out: + if isinstance(entity, IdentifiedStructure): + if entity == existing_match: + continue + if entity.structure != existing_match.structure: + if entity.structure.full_structure_equality(existing_match.structure): + # Then is the protein different? We'll probably deal with them + # soon. + self.log(""Skipping Shared Structure %r in %r\n"" % ( + existing_match.structure, mbd.label)) + else: + # Totally different structure, emit a warning? + warnings.warn(""Ambiguous 1 Link Between %r and %r with shift %r\n"" % ( + existing_match.structure, entity.structure, shift)) + link_actions.add( + LinkAction(mbd.label, existing_match, entity, shift, 1)) + else: + if existing_match.chromatogram and entity.chromatogram: + self.log(""Multiple chromatograms for %r at %0.2f and %0.2f\n"" % ( + existing_match.structure, existing_match.apex_time, entity.apex_time)) + else: + # It's a chromatogram, is it a different mass shift state? + existing_apex_time = existing_match.apex_time + if existing_apex_time is None: + existing_apex_time = existing_match.tandem_solutions[0].scan_time + if abs(entity.apex_time - existing_apex_time) < time_error_tolerance: + if existing_match.chromatogram is not None and existing_match.chromatogram.common_nodes(entity): + self.log(""Repeated attempt to merge %r and %r in %r\n"" % ( + existing_match.structure, entity, mbd.label)) + continue + merge_actions.add(MergeAction( + mbd.label, existing_match.structure, entity, shift)) + + else: + for entity, shift in out: + if isinstance(entity, IdentifiedStructure): + if entity.structure.full_structure_equality(ids.structure): + # Then is the protein different? Should already be handled above. + warnings.warn(""Ambiguous 2 Link Between %r and %r with shift %r in %r\n"" % ( + ids.structure, entity.structure, shift.name, mbd.label)) + else: + # Totally different structure, emit a warning? + self.log(""Ambiguous 3 Link Between %r and %r with shift %r in %r\n"" % ( + ids.structure, entity.structure, shift.name, mbd.label)) + link_actions.add( + LinkAction(mbd.label, ids, entity, shift, 3)) + else: + # It's a chromatogram. Wrap it in something and add it to the shared_id + create_actions.add(CreateAction( + mbd.label, ids.structure, entity, shift)) + + return merge_actions, create_actions, link_actions + + def run(self): + n = len(self.feature_table) + for i, shared_id in enumerate(self.feature_table.values()): + if i % 100 == 0 and i: + self.log(""Processed %d/%d shared identifications (%0.2f%%)"" % (i, n, i * 100.0 / n)) + self.match_structure_between(shared_id, self.mass_error_tolerance, self.time_error_tolerance) + + def to_csv(self, stream): + keys = ['glycopeptide', 'mass_shifts'] + [ + '%s_abundance' % a for a in self.labels] + [ + '%s_apex_time' % a for a in self.labels] + writer = csv.DictWriter(stream, keys) + writer.writeheader() + for gp, shared_id in self.feature_table.items(): + mass_shifts = set() + record = { + ""glycopeptide"": str(gp) + } + seen = set() + for label, inst in shared_id.items(): + record['%s_abundance' % label] = inst.total_signal or '0' + record['%s_apex_time' % label] = inst.apex_time + mass_shifts.update(inst.mass_shifts) + for label in set(self.labels) - set(shared_id.keys()): + record['%s_abundance' % label] = None + record['%s_apex_time' % label] = None + record['mass_shifts'] = ';'.join(m.name for m in mass_shifts) + writer.writerow(record) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/match_between_runs/dataset.py",".py","9407","221","import logging + +from typing import Any, Iterable, List, DefaultDict, Optional, Tuple, Union +from glycresoft.serialize.chromatogram import MassShift +from glycresoft.structure.structure_loader import FragmentCachingGlycopeptide + + +from ms_deisotope.data_source import RandomAccessScanSource, ProcessedScan + +from glycresoft import serialize + +from glycresoft.chromatogram_tree import ( + Chromatogram, GlycopeptideChromatogram, ChromatogramTreeList, + ChromatogramFilter) + +from glycresoft.trace import ChromatogramExtractor +from glycresoft.scoring import ChromatogramSolution +from glycresoft.tandem.chromatogram_mapping import TandemAnnotatedChromatogram + +from glycresoft.tandem.spectrum_match import ( + ScoreSet, FDRSet, MultiScoreSpectrumMatch, MultiScoreSpectrumSolutionSet) + +from glycresoft.tandem.glycopeptide.identified_structure import IdentifiedGlycopeptide + + +logger = logging.getLogger(__name__) +logger.addHandler(logging.NullHandler()) + + +class FakeSpectrumMatch(MultiScoreSpectrumMatch): + def __init__(self, target, mass_shift=None): + super(FakeSpectrumMatch, self).__init__( + scan=None, target=target, score_set=ScoreSet(1e-6, 1e-6, 1e-6, 0), + best_match=True, data_bundle=None, q_value_set=FDRSet(0.99, 0.99, 0.99, 0.99), + mass_shift=mass_shift, match_type=0) + + +class MatchBetweenDataset(object): + chromatograms: ChromatogramFilter + identified_structures: List[IdentifiedGlycopeptide] + label: str + + scan_loader: RandomAccessScanSource[Any, ProcessedScan] + analysis_loader: Optional[serialize.AnalysisDeserializer] + + _find_by_structure: DefaultDict[Union[str, FragmentCachingGlycopeptide], List[IdentifiedGlycopeptide]] + + def __init__(self, analysis_loader, scan_loader, label=None): + if label is None and analysis_loader is not None: + label = analysis_loader.analysis.name + + self.chromatograms = ChromatogramFilter([]) + self.identified_structures = [] + self._find_by_structure = DefaultDict(list) + + self.analysis_loader = analysis_loader + self.scan_loader = scan_loader + if self.scan_loader is not None: + self._load_chromatograms() + self._prepare_structure_map() + self.label = label + + @classmethod + def from_chromatograms_and_identifications(cls, chromatograms: Iterable[Chromatogram], + identifications: List[IdentifiedGlycopeptide], + analysis_loader: Optional[serialize.AnalysisDeserializer]=None, + scan_loader: Optional[RandomAccessScanSource]=None, + label: Optional[str]=None): + if label is None and analysis_loader is not None: + label = analysis_loader.analysis.name + self = cls(None, None, label=label) + self.analysis_loader = analysis_loader + self.scan_loader = scan_loader + self.label = None if analysis_loader is None else analysis_loader.analysis.name + + self.identified_structures = identifications + self.chromatograms = self._map_chromatograms(chromatograms, identifications) + + self._prepare_structure_map() + return self + + def _map_chromatograms(self, chromatograms: Iterable[Chromatogram], + identifications: Iterable[IdentifiedGlycopeptide]): + for chrom in chromatograms: + chrom.mark = False + for idgp in identifications: + if idgp.chromatogram is None: + continue + for mshift in idgp.mass_shifts: + chroma = chromatograms.find_all_by_mass( + idgp.weighted_neutral_mass + mshift.mass, 1e-5) + for chrom in chroma: + if idgp.chromatogram.overlaps_in_time(chrom): + chrom.mark = True + + chromatograms = ChromatogramFilter( + [chrom for chrom in chromatograms if not chrom.mark] + list(identifications)) + return chromatograms + + def _load_chromatograms(self): + logger.info(f""Loading chromatograms from {self.scan_loader.source_file_name}"") + extractor = ChromatogramExtractor( + self.scan_loader, minimum_mass=1000.0, grouping_tolerance=1.5e-5) + chromatograms = extractor.run() + for chrom in chromatograms: + chrom.mark = False + if self.analysis_loader is not None: + logger.info(f""Loading identified glycopeptides from {self.analysis_loader.analysis.name}"") + idgps = self.analysis_loader.load_identified_glycopeptides(0.1) + self.identified_structures = idgps + self.chromatograms = self._map_chromatograms(chromatograms, idgps) + + @property + def ms1_scoring_model(self): + return self.analysis_loader.analysis.parameters.get('scoring_model') + + def find(self, ids: IdentifiedGlycopeptide, + mass_error_tolerance: float=1e-5, + time_error_tolerance: float=2.0) -> List[Tuple[Union[Chromatogram, IdentifiedGlycopeptide], + Optional[MassShift]]]: + key = ids.structure + out = [] + id_out = [] + ids_mass = ids.weighted_neutral_mass + ids_apex_time = ids.apex_time + if ids_apex_time is None: + ids_apex_time = ids.tandem_solutions[0].scan_time + if key in self._find_by_structure: + results = self._find_by_structure[key] + for result in results: + if abs(result.weighted_neutral_mass - ids_mass) / ids_mass < mass_error_tolerance: + apex_time = result.apex_time + if apex_time is None: + apex_time = result.tandem_solutions[0].scan_time + if abs(apex_time - ids_apex_time) < time_error_tolerance: + id_out.append((result, None)) + for mshift in ids.mass_shifts: + qmass = mshift.mass + ids_mass + chroma = self.chromatograms.find_all_by_mass( + qmass, mass_error_tolerance) + for chrom in chroma: + if abs(chrom.apex_time - ids_apex_time) < time_error_tolerance: + if not isinstance(chrom, Chromatogram) and (chrom, None) in id_out: + continue + out.append((chrom, mshift)) + return id_out + out + + def get_identified_structure_for(self, structure): + key = structure + candidates = self._find_by_structure[key] + for candidate in candidates: + if candidate.structure == structure: + return candidate + raise KeyError(""Could not locate %r (%r)"" % + (structure, structure.protein_relation)) + + def create(self, structure, chromatogram, shift): + chrom = GlycopeptideChromatogram( + structure, ChromatogramTreeList()) + chrom = chrom.merge(chromatogram, shift) + + # If there is another identification that this wasn't merged with because of varying + # errors in apex time matching, things break down. Check just in case we really want + # to merge here. + try: + existing = self.get_identified_structure_for(structure) + if existing.chromatogram.common_nodes(chrom): + return None + else: + return self.merge(structure, chromatogram, shift) + except KeyError: + pass + ms1_model = self.ms1_scoring_model + chrom = ChromatogramSolution( + chrom, ms1_model.logitscore(chrom), scorer=ms1_model) + chrom = TandemAnnotatedChromatogram(chrom) + sset = MultiScoreSpectrumSolutionSet( + None, [FakeSpectrumMatch(structure)]) + sset.q_value = sset.best_solution().q_value + idgp = IdentifiedGlycopeptide(structure, [sset], chrom) + return idgp + + def merge(self, structure, chromatogram, shift): + candidate = self.get_identified_structure_for(structure) + chrom = GlycopeptideChromatogram( + structure, ChromatogramTreeList()) + chrom = chrom.merge(chromatogram, shift) + chrom = TandemAnnotatedChromatogram(chrom) + if candidate.chromatogram is None: + candidate.chromatogram = chrom + else: + candidate.chromatogram = candidate.chromatogram.merge(chrom) + + def add(self, ids): + key = ids.structure + self._find_by_structure[key].append(ids) + self.identified_structures.append(ids) + self.chromatograms.extend([ids]) + + def _protein_name_label_map(self): + proteins = self.analysis_loader.query(serialize.Protein).all() + name_map = dict() + for prot in proteins: + name_map[prot.id] = prot.name + return name_map + + def _prepare_structure_map(self): + self._find_by_structure = DefaultDict(list) + if self.analysis_loader is not None: + name_map = self._protein_name_label_map() + else: + name_map = None + for ids in self.identified_structures: + try: + if name_map is not None: + pr = ids.protein_relation + pr.protein_id = name_map.get(pr.protein_id, pr.protein_id) + except AttributeError: + pass + self._find_by_structure[(ids.structure)].append(ids) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/match_between_runs/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/target_decoy/__init__.py",".py","640","31","from .base import ( + ScoreCell, + ScoreThresholdCounter, + ArrayScoreThresholdCounter, + NearestValueLookUp, + TargetDecoyAnalyzer, + TargetDecoySet, + GroupwiseTargetDecoyAnalyzer, + PeptideScoreTargetDecoyAnalyzer, + FDREstimatorBase, +) + +from .svm import ( + SVMModelBase, + PeptideScoreSVMModel +) + +__all__ = [ + ""ScoreCell"", + ""ScoreThresholdCounter"", + ""ArrayScoreThresholdCounter"", + ""NearestValueLookUp"", + ""TargetDecoyAnalyzer"", + ""TargetDecoySet"", + ""GroupwiseTargetDecoyAnalyzer"", + ""PeptideScoreTargetDecoyAnalyzer"", + ""SVMModelBase"", + ""PeptideScoreSVMModel"", + ""FDREstimatorBase"", +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/target_decoy/base.py",".py","27970","837","# -*- coding: utf-8 -*- +import math +import logging + +from typing import Callable, List, NamedTuple, Optional, Sequence, Tuple, Union +from collections import defaultdict, namedtuple + +import numpy as np +try: + from matplotlib import pyplot as plt +except (ImportError, RuntimeError): + plt = None + +from glycresoft.task import LoggingMixin +from glycresoft.tandem.spectrum_match import SpectrumSolutionSet, SpectrumMatch + +ScoreCell = namedtuple('ScoreCell', ['score', 'value']) + +logger = logging.getLogger(__name__) +logger.addHandler(logging.NullHandler()) + + +class NearestValueLookUp(object): + """""" + A mapping-like object which simplifies + finding the value of a pair whose key is nearest + to a given query. + + .. note:: + Queries exceeding the maximum key will return + the maximum key's value. + """""" + + def __init__(self, items): + if isinstance(items, dict): + items = items.items() + self.items = sorted( + [ScoreCell(*x) for x in items if not np.isnan(x[0])], key=lambda x: x[0]) + + def max_key(self): + try: + return self.items[-1][0] + except IndexError: + return 0 + + def _find_closest_item(self, value, key_index=0): + array = self.items + lo = 0 + hi = len(array) + n = hi + + error_tolerance = 1e-3 + + if np.isnan(value): + return lo + + if lo == hi: + return lo + + while hi - lo: + i = (hi + lo) // 2 + x = array[i][key_index] + err = x - value + if abs(err) < error_tolerance: + mid = i + best_index = mid + best_error = abs(err) + i = mid - 1 + while i >= 0: + x = array[i][key_index] + err = abs(x - value) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i -= 1 + i = mid + 1 + while i < n: + x = array[i][key_index] + err = abs(x - value) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i += 1 + return best_index + elif (hi - lo) == 1: + mid = i + best_index = mid + best_error = abs(err) + i = mid - 1 + while i >= 0: + x = array[i][key_index] + err = abs(x - value) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i -= 1 + i = mid + 1 + while i < n: + x = array[i][key_index] + err = abs(x - value) + if err < best_error: + best_error = err + best_index = i + elif err > error_tolerance: + break + i += 1 + return best_index + elif x < value: + lo = i + elif x > value: + hi = i + + def get_pair(self, key, key_index=0): + k = self._find_closest_item(key, key_index) + 1 + return self.items[k] + + def __len__(self): + return len(self.items) + + def __repr__(self): + return ""{s.__class__.__name__}({size})"".format( + s=self, size=len(self)) + + def __getitem__(self, key): + return self._get_one(key) + + def _get_sequence(self, key): + value = [self._get_one(k) for k in key] + if isinstance(key, np.ndarray): + value = np.array(value, dtype=float) + return value + + def _get_one(self, key): + ix = self._find_closest_item(key) + if ix >= len(self): + ix = len(self) - 1 + if ix < 0: + ix = 0 + pair = self.items[ix] + return pair[1] + + +try: + _NearestValueLookUp = NearestValueLookUp + from glycresoft._c.tandem.target_decoy import NearestValueLookUp as NearestValueLookUp +except ImportError: + pass + + +class ScoreThresholdCounter(object): + def __init__(self, series, thresholds): + self.series = self._prepare_series(series) + self.thresholds = sorted(set(np.round((thresholds), 10))) + self.counter = defaultdict(int) + self.counts_above_threshold = None + self.n_thresholds = len(self.thresholds) + self.threshold_index = 0 + self.current_threshold = self.thresholds[self.threshold_index] + self.current_count = 0 + + self._i = 0 + self._is_done = False + + self.find_counts() + self.counts_above_threshold = self.compute_complement() + self.counter = NearestValueLookUp(self.counter) + + def _prepare_series(self, series): + return sorted(series, key=lambda x: x.score) + + def advance_threshold(self): + self.threshold_index += 1 + if self.threshold_index < self.n_thresholds: + self.current_threshold = self.thresholds[self.threshold_index] + self.counter[self.current_threshold] = self.current_count + return True + else: + self._is_done = True + return False + + def test(self, item): + if item.score < self.current_threshold: + self.current_count += 1 + self._i += 1 + else: + # Rather than using recursion, just invert the condition + # being tested and loop here. + while self.advance_threshold(): + if item.score > self.current_threshold: + continue + else: + self.current_count += 1 + self._i += 1 + break + + def find_counts(self): + for item in self.series: + self.test(item) + + def compute_complement(self): + complement = defaultdict(int) + n = len(self.series) + + for k, v in self.counter.items(): + complement[k] = n - v + return NearestValueLookUp(complement) + + +class ArrayScoreThresholdCounter(ScoreThresholdCounter): + + def _prepare_series(self, series): + return np.sort(np.array(series)) + + def test(self, item): + if item < self.current_threshold: + self.current_count += 1 + self._i += 1 + else: + # Rather than using recursion, just invert the condition + # being tested and loop here. + while self.advance_threshold(): + if item > self.current_threshold: + continue + else: + self.current_count += 1 + self._i += 1 + break + + +class TargetDecoySet(NamedTuple): + target_matches: List[SpectrumSolutionSet] + decoy_matches: List[SpectrumSolutionSet] + + def target_count(self): + return len(self.target_matches) + + def decoy_count(self): + return len(self.decoy_matches) + + +# implementation derived from pyteomics +_precalc_fact = np.log([math.factorial(n) for n in range(20)]) + + +def log_factorial(x): + x = np.array(x) + m = (x >= _precalc_fact.size) + out = np.empty(x.shape) + out[~m] = _precalc_fact[x[~m].astype(int)] + x = x[m] + out[m] = x * np.log(x) - x + 0.5 * np.log(2 * np.pi * x) + return out + + +def _log_pi_r(d, k, p=0.5): + return k * math.log(p) + log_factorial(k + d) - log_factorial(k) - log_factorial(d) + + +def _log_pi(d, k, p=0.5): + return _log_pi_r(d, k, p) + (d + 1) * math.log(1 - p) + + +def _expectation(d, t, p=0.5): + """"""The conditional tail probability for the negative binomial + random variable for the number of incorrect target matches + + Parameters + ---------- + d : int + The number of decoys retained + t : int + The number of targets retained + p : float, optional + The parameter :math:`p` of the negative binomial, + :math:`1 / 1 + (ratio of the target database to the decoy database)` + + Returns + ------- + float + The theoretical number of incorrect target matches + + References + ---------- + Levitsky, L. I., Ivanov, M. V., Lobas, A. A., & Gorshkov, M. V. (2017). + Unbiased False Discovery Rate Estimation for Shotgun Proteomics Based + on the Target-Decoy Approach. Journal of Proteome Research, 16(2), 393–397. + https://doi.org/10.1021/acs.jproteome.6b00144 + """""" + if t is None: + return d + 1 + t = int(t) + m = np.arange(t + 1, dtype=int) + pi = np.exp(_log_pi(d, m, p)) + return ((m * pi).cumsum() / pi.cumsum())[t] + + +def expectation_correction(targets, decoys, ratio): + """"""Estimate a correction for the number of decoys at a given + score threshold for small data size. + + Parameters + ---------- + targets : int + The number of targets retained + decoys : int + The number of decoys retained + ratio : float + The ratio of target database to decoy database + + Returns + ------- + float + The number of decoys to add for the correction + + References + ---------- + Levitsky, L. I., Ivanov, M. V., Lobas, A. A., & Gorshkov, M. V. (2017). + Unbiased False Discovery Rate Estimation for Shotgun Proteomics Based + on the Target-Decoy Approach. Journal of Proteome Research, 16(2), 393–397. + https://doi.org/10.1021/acs.jproteome.6b00144 + """""" + p = 1. / (1. + ratio) + tfalse = _expectation(decoys, targets, p) + return tfalse + + +class FDREstimatorBase(LoggingMixin): + + def summarize(self, name: Optional[str] = None): + if name is None: + name = ""FDR"" + + threshold_05, count_05 = self.get_count_for_fdr(0.05) + self.log(f""5% {name} = {threshold_05:0.3f} ({count_05})"") + threshold_01, count_01 = self.get_count_for_fdr(0.01) + self.log(f""1% {name} = {threshold_01:0.3f} ({count_01})"") + + def score(self, spectrum_match: SpectrumMatch, assign: bool=False) -> float: + raise NotImplementedError() + + def score_all(self, solution_set: SpectrumSolutionSet): + raise NotImplementedError() + + def plot(self, ax=None): + raise NotImplementedError() + + def get_count_for_fdr(self, threshold: float) -> Tuple[float, int]: + raise NotImplementedError() + + +class TargetDecoyAnalyzer(FDREstimatorBase): + """"""Estimate the False Discovery Rate using the Target-Decoy method. + + Attributes + ---------- + database_ratio : float + The ratio of the size of the target database to the decoy database + target_weight : float + A weight (less than 1.0) to put on target matches to make them weaker + than decoys in situations where there is little data. + decoy_correction : Number + A quantity to use to correct for decoys, and if non-zero, + will indicate that the negative binomial correction for decoys should be + used. + decoy_pseudocount : Number + The value to report when querying the decoy count for a score exceeding + the maximum score of a decoy match. This is distinct from `decoy_correction` + decoy_count : int + The total number of decoys + decoys : list + The decoy matches to consider + n_decoys_at : dict + The number of decoy matches above each threshold + n_targets_at : dict + The number of target matches above each threshold + target_count : int + The total number of targets + targets : list + The target matches to consider + thresholds : list + The distinct score thresholds + with_pit : bool + Whether or not to use the ""percent incorrect target"" adjustment + """""" + n_targets_at: NearestValueLookUp + n_decoys_at: NearestValueLookUp + + targets: Sequence[SpectrumMatch] + decoys: Sequence[SpectrumMatch] + + target_count: int + decoy_count: int + + database_ratio: float + decoy_correction: float + + target_weight: float + decoy_pseudocount: float + + def __init__(self, target_series, decoy_series, with_pit=False, decoy_correction=0, database_ratio=1.0, + target_weight=1.0, decoy_pseudocount=1.0): + self.targets = target_series + self.decoys = decoy_series + self.target_count = len(target_series) + self.decoy_count = len(decoy_series) + self.database_ratio = database_ratio + self.target_weight = target_weight + self.with_pit = with_pit + self.decoy_correction = decoy_correction + self.decoy_pseudocount = decoy_pseudocount + + self._calculate_thresholds() + self._q_value_map = self.calculate_q_values() + + def get_score(self, spectrum_match: SpectrumMatch) -> float: + return spectrum_match.score + + def has_score(self, spectrum_match: SpectrumMatch) -> bool: + return hasattr(spectrum_match, 'score') + + def pack(self): + self.targets = [] + self.decoys = [] + + def _calculate_thresholds(self): + self.n_targets_at = NearestValueLookUp([]) + self.n_decoys_at = NearestValueLookUp([]) + + target_series = self.targets + decoy_series = self.decoys + + if len(target_series) and self.has_score(target_series[0]): + target_series = np.array([self.get_score(t) + for t in target_series], dtype=float) + else: + target_series = np.array(target_series, dtype=float) + + if len(decoy_series) and self.has_score(decoy_series[0]): + decoy_series = np.array([self.get_score(t) + for t in decoy_series], dtype=float) + else: + decoy_series = np.array(decoy_series, dtype=float) + + thresholds = np.unique( + np.sort(np.concatenate([target_series, decoy_series])) + ) + + self.thresholds = thresholds + if len(thresholds) > 0: + self.n_targets_at = ArrayScoreThresholdCounter( + target_series, self.thresholds).counts_above_threshold + self.n_decoys_at = ArrayScoreThresholdCounter( + decoy_series, self.thresholds).counts_above_threshold + else: + self.n_targets_at = NearestValueLookUp([]) + self.n_decoys_at = NearestValueLookUp([]) + + def n_decoys_above_threshold(self, threshold: float) -> int: + try: + if threshold > self.n_decoys_at.max_key(): + return self.decoy_pseudocount + self.decoy_correction + return self.n_decoys_at[threshold] + self.decoy_correction + except (IndexError, KeyError): + if len(self.n_decoys_at) == 0: + return self.decoy_correction + else: + raise + + def n_targets_above_threshold(self, threshold: float) -> int: + try: + return self.n_targets_at[threshold] + except (IndexError, KeyError): + if len(self.n_targets_at) == 0: + return 0 + else: + raise + + def expectation_correction(self, t: int, d: int) -> float: + return expectation_correction(t, d, self.database_ratio) + + def target_decoy_ratio(self, cutoff: float) -> float: + + decoys_at = self.n_decoys_above_threshold(cutoff) + targets_at = self.n_targets_above_threshold(cutoff) + decoy_correction = 0 + if self.decoy_correction: + try: + decoy_correction = self.expectation_correction( + targets_at, decoys_at) + except Exception as ex: + print(ex) + try: + ratio = (decoys_at + decoy_correction) / float( + targets_at * self.database_ratio * self.target_weight) + except ZeroDivisionError: + ratio = (decoys_at + decoy_correction) + return ratio, targets_at, decoys_at + + def estimate_percent_incorrect_targets(self, cutoff: float) -> float: + target_cut = self.target_count - self.n_targets_above_threshold(cutoff) + decoy_cut = self.decoy_count - self.n_decoys_above_threshold(cutoff) + percent_incorrect_targets = target_cut / float(decoy_cut) + + return percent_incorrect_targets + + def estimate_fdr(self, cutoff: float) -> float: + if self.with_pit: + percent_incorrect_targets = self.estimate_percent_incorrect_targets( + cutoff) + else: + percent_incorrect_targets = 1.0 + return percent_incorrect_targets * self.target_decoy_ratio(cutoff)[0] + + def calculate_q_values(self): + # Thresholds in ascending order + thresholds = self.thresholds + mapping = {} + last_score = float('inf') + last_q_value = 0 + for threshold in thresholds: + try: + q_value = self.estimate_fdr(threshold) + # If a worse score has a lower q-value than a better score, use that q-value + # instead. + if last_q_value < q_value and last_score < threshold: + q_value = last_q_value + last_q_value = q_value + last_score = threshold + mapping[threshold] = q_value + except ZeroDivisionError: + mapping[threshold] = 1. + return NearestValueLookUp(mapping) + + def score_for_fdr(self, fdr_estimate: float) -> float: + i = -1 + n = len(self.q_value_map) + if n == 0: + return 0 + for _score, fdr in self.q_value_map.items: + i += 1 + if fdr_estimate >= fdr: + if i < n: + cella = self.q_value_map.items[i] + else: + cella = ScoreCell(fdr_estimate, 0) + + if i - 1 >= 0: + cellb = self.q_value_map.items[i - 1] + else: + cellb = ScoreCell(fdr_estimate, 0) + + if i + 1 < n: + cellc = self.q_value_map.items[i + 1] + else: + cellc = ScoreCell(fdr_estimate, 0) + distance_a = abs(fdr_estimate - cella.value) + distance_b = abs(fdr_estimate - cellb.value) + distance_c = abs(fdr_estimate - cellc.value) + min_distance = min(distance_a, distance_b, distance_c) + if min_distance == distance_a: + return cella.score + elif min_distance == distance_b: + return cellb.score + else: + return cellc.score + return float('inf') + + def get_count_for_fdr(self, fdr_estimate: float) -> Tuple[float, int]: + threshold = self.score_for_fdr(fdr_estimate) + count = self.n_targets_above_threshold(threshold) + return threshold, count + + def plot(self, ax=None): + if ax is None: + fig, ax = plt.subplots(1) + thresholds = sorted(self.thresholds, reverse=False) + target_counts = np.array( + [self.n_targets_above_threshold(i) for i in thresholds]) + decoy_counts = np.array([self.n_decoys_above_threshold(i) + for i in thresholds]) + fdr = np.array([self.q_value_map[i] for i in thresholds]) + try: + at_5_percent = np.where(fdr < 0.05)[0][0] + except IndexError: + at_5_percent = -1 + try: + at_1_percent = np.where(fdr < 0.01)[0][0] + except IndexError: + at_1_percent = -1 + line1 = ax.plot(thresholds, target_counts, + label='Target', color='steelblue') + line2 = ax.plot(thresholds, decoy_counts, label='Decoy', color='coral') + tline5 = ax.vlines( + thresholds[at_5_percent], 0, np.max(target_counts), linestyle='--', color='green', + lw=0.75, label='5% FDR') + tline1 = ax.vlines( + thresholds[at_1_percent], 0, np.max(target_counts), linestyle='--', color='skyblue', + lw=0.75, label='1% FDR') + ax.set_ylabel(""# Matches Retained"") + ax.set_xlabel(""Score"") + ax2 = ax.twinx() + line3 = ax2.plot(thresholds, fdr, label='FDR', + color='grey', linestyle='--') + ax2.set_ylabel(""FDR"") + ax.legend([line1[0], line2[0], line3[0], tline5, tline1], + ['Target', 'Decoy', 'FDR', ""5% FDR"", ""1% FDR""], frameon=False) + + lo, hi = ax.get_ylim() + lo = max(lo, 0) + ax.set_ylim(lo, hi) + lo, hi = ax2.get_ylim() + ax2.set_ylim(0, hi) + + lo, hi = ax.get_xlim() + ax.set_xlim(-1, hi) + lo, hi = ax2.get_xlim() + ax2.set_xlim(-1, hi) + return ax + + def q_values(self): + q_map = self._q_value_map + if len(q_map) == 0: + import warnings + warnings.warn(""No FDR estimate what possible."") + for target in self.targets: + target.q_value = 0.0 + for decoy in self.decoys: + decoy.q_value = 0.0 + return + for target in self.targets: + try: + target.q_value = q_map[self.get_score(target)] + except IndexError: + target.q_value = 0.0 + for decoy in self.decoys: + try: + decoy.q_value = q_map[self.get_score(decoy)] + except IndexError: + decoy.q_value = 0.0 + + def score(self, spectrum_match, assign=True): + try: + q_value = self._q_value_map[self.get_score(spectrum_match)] + except IndexError: + import warnings + warnings.warn(""Empty q-value mapping. q-value will be 0."") + q_value = 0.0 + if assign: + spectrum_match.q_value = q_value + return q_value + + def score_all(self, solution_set): + for spectrum_match in solution_set: + self.score(spectrum_match, assign=True) + solution_set.q_value = solution_set.best_solution().q_value + return solution_set + + @property + def q_value_map(self): + return self._q_value_map + + @property + def fdr_map(self): + return self._q_value_map + + +class GroupwiseTargetDecoyAnalyzer(FDREstimatorBase): + _grouping_labels = None + targets: Sequence[SpectrumMatch] + decoys: Sequence[SpectrumMatch] + + groups: List[List[Tuple[List[SpectrumMatch], List[SpectrumMatch]]]] + group_fits: List[TargetDecoyAnalyzer] + grouping_functions: List[Callable[[SpectrumMatch], bool]] + grouping_labels: List[str] + + def __init__(self, target_series, decoy_series, with_pit=False, grouping_functions=None, decoy_correction=0, + database_ratio=1.0, target_weight=1.0, decoy_pseudocount=1.0, grouping_labels=None): + if grouping_functions is None: + grouping_functions = [lambda x: True] + if grouping_labels is None: + grouping_labels = [""Group %d"" % + i for i in range(1, len(grouping_functions) + 1)] + self.targets = target_series + self.decoys = decoy_series + self.with_pit = with_pit + self.grouping_labels = grouping_labels + self.grouping_functions = [] + self.groups = [] + self.group_fits = [] + self.decoy_pseudocount = decoy_pseudocount + self.decoy_correction = decoy_correction + self.database_ratio = database_ratio + self.target_weight = target_weight + + for fn in grouping_functions: + self.add_group(fn) + + self.partition() + + @property + def grouping_labels(self): + if self._grouping_labels is None: + self._grouping_labels = [ + ""Group %d"" % i for i in range(1, len(self.grouping_functions) + 1)] + return self._grouping_labels + + @grouping_labels.setter + def grouping_labels(self, labels): + self._grouping_labels = labels + + def pack(self): + self.targets = [] + self.decoys = [] + self.groups = [[] for g in self.groups] + for fit in self.group_fits: + fit.pack() + + def partition(self): + for target in self.targets: + i = self.find_group(target) + self.groups[i][0].append(target) + for decoy in self.decoys: + i = self.find_group(decoy) + self.groups[i][1].append(decoy) + for group in self.groups: + fit = TargetDecoyAnalyzer( + *group, with_pit=self.with_pit, + decoy_correction=self.decoy_correction, + database_ratio=self.database_ratio, + target_weight=self.target_weight, + decoy_pseudocount=self.decoy_pseudocount) + self.group_fits.append(fit) + + def add_group(self, fn): + self.grouping_functions.append(fn) + self.groups.append(([], [])) + return len(self.groups) + + def find_group(self, spectrum_match): + for i, fn in enumerate(self.grouping_functions): + if fn(spectrum_match): + return i + return None + + def q_values(self): + for group in self.group_fits: + group.q_values() + + def score(self, spectrum_match, assign=True): + i = self.find_group(spectrum_match) + fit = self.group_fits[i] + return fit.score(spectrum_match, assign=assign) + + def score_all(self, solution_set): + for spectrum_match in solution_set: + self.score(spectrum_match, assign=True) + solution_set.q_value = solution_set.best_solution().q_value + return solution_set + + def plot(self, ax=None): + if ax is None: + fig, ax = plt.subplots(1) + ax2 = ax.twinx() + lines = [] + labels = [] + for _, (group_fit, label) in enumerate(zip(self.group_fits, self.grouping_labels)): + thresholds = sorted(group_fit.thresholds, reverse=False) + target_counts = np.array( + [group_fit.n_targets_above_threshold(i) for i in thresholds]) + decoy_counts = np.array( + [group_fit.n_decoys_above_threshold(i) for i in thresholds]) + + fdr = np.array([group_fit.q_value_map[i] for i in thresholds]) + line1 = ax.plot(thresholds, target_counts, + label='%s Target' % label, ) + lines.append(line1[0]) + labels.append(line1[0].get_label()) + + line2 = ax.plot(thresholds, decoy_counts, + label='%s Decoy' % label, ) + lines.append(line2[0]) + labels.append(line2[0].get_label()) + + line3 = ax2.plot(thresholds, fdr, label='%s FDR' % label, + linestyle='--') + lines.append(line3[0]) + labels.append(line3[0].get_label()) + + ax.set_ylabel(""# Matches Retained"") + ax.set_xlabel(""Score"") + + ax2.set_ylabel(""FDR"") + ax.legend(lines, labels, frameon=False) + + lo, hi = ax.get_ylim() + lo = max(lo, 0) + ax.set_ylim(lo, hi) + lo, hi = ax2.get_ylim() + ax2.set_ylim(0, hi) + + lo, hi = ax.get_xlim() + ax.set_xlim(-1, hi) + lo, hi = ax2.get_xlim() + ax2.set_xlim(-1, hi) + return ax + + def summarize(self, name: Optional[str]=None): + if name is None: + name = ""FDR"" + + for group_name, group_fit in zip(self.grouping_labels, self.group_fits): + group_fit.summarize(f""{group_name} {name}"") + + +class PeptideScoreTargetDecoyAnalyzer(TargetDecoyAnalyzer): + """""" + A :class:`TargetDecoyAnalyzer` subclass for directly + handling :class:`~.MultiScoreSpectrumMatch` instances. + """""" + + def get_score(self, spectrum_match): + return spectrum_match.score_set.peptide_score + + def has_score(self, spectrum_match): + try: + spectrum_match.score_set.peptide_score + return True + except AttributeError: + return False +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/target_decoy/svm.py",".py","10379","292","# Inspired heavily by mokapot +# https://github.com/wfondrie/mokapot +# https://pubs.acs.org/doi/10.1021/acs.jproteome.0c01010 + + +from typing import Any, Dict, List, Optional, Tuple + +from array import ArrayType as Array + +import numpy as np +from numpy.typing import NDArray + +from sklearn.svm import LinearSVC +from sklearn.preprocessing import StandardScaler + +from ..spectrum_match import SpectrumMatch, MultiScoreSpectrumMatch + +from .base import TargetDecoyAnalyzer, NearestValueLookUp, PeptideScoreTargetDecoyAnalyzer, FDREstimatorBase + + +def _transform_fast(self: StandardScaler, X: np.ndarray) -> np.ndarray: + Y = (X - self.mean_) + Y /= self.scale_ + return Y + + +def _fast_decision_function(self: LinearSVC, X: np.ndarray) -> np.ndarray: + Y = X.dot(self.coef_[0, :]) + Y += self.intercept_ + return Y + + +class SVMModelBase(FDREstimatorBase): + dataset: TargetDecoyAnalyzer + proxy_dataset: TargetDecoyAnalyzer + + scaler: StandardScaler + model: LinearSVC + model_args: Dict[str, Any] + + max_iter: int + train_fdr: float + worse_than_score: bool + trained: bool + + def __init__(self, target_matches: Optional[List[MultiScoreSpectrumMatch]]=None, + decoy_matches: Optional[List[MultiScoreSpectrumMatch]]=None, + train_fdr: float=0.01, max_iter: int=10, **model_args): + self.scaler = StandardScaler() + self.train_fdr = train_fdr + self.max_iter = max_iter + self.trained = False + self.model_args = model_args.copy() + self.model = LinearSVC(dual=False, **self.model_args) + self.worse_than_score = False + self.dataset = None + self.proxy_dataset = None + + if target_matches is not None and decoy_matches is not None: + tda = self._wrap_dataset(target_matches, decoy_matches) + _, count = tda.get_count_for_fdr(self.train_fdr) + if count < 100: + self.warn(f""Found {count} targets passing {self.train_fdr} FDR threshold, "" + ""too few observations to fit a reliable model"") + self.fit(tda) + + def feature_names(self) -> List[str]: + raise NotImplementedError() + + def _wrap_dataset(self, target_matches: List[MultiScoreSpectrumMatch], + decoy_matches: List[MultiScoreSpectrumMatch]): + tda = TargetDecoyAnalyzer(target_matches, decoy_matches, decoy_pseudocount=0.0) + return tda + + def pack(self): + self.dataset.pack() + self.proxy_dataset.pack() + + def __getstate__(self): + return { + ""scaler"": self.scaler, + ""model"": self.model, + ""model_args"": self.model_args, + ""trained"": self.trained, + ""worse_than_score"": self.worse_than_score, + ""max_iter"": self.max_iter, + ""train_fdr"": self.train_fdr, + ""dataset"": self.dataset, + ""proxy_dataset"": self.proxy_dataset + } + + def __setstate__(self, state): + self.scaler = state['scaler'] + self.model = state['model'] + self.model_args = state['model_args'] + self.trained = state['trained'] + self.worse_than_score = state['worse_than_score'] + self.max_iter = state['max_iter'] + self.train_fdr = state['train_fdr'] + self.dataset = state['dataset'] + self.proxy_dataset = state['proxy_dataset'] + + def init_model(self): + return LinearSVC(dual=False, **self.model_args) + + def prepare_model(self, model, features: np.ndarray, labels: List[bool]): + return model + + def predict(self, X: NDArray[np.floating]) -> NDArray[np.floating]: + X_ = _transform_fast(self.scaler, X) + return _fast_decision_function(self.model, X_) + + def _get_psms_labels( + self, tda: TargetDecoyAnalyzer, fdr_threshold: float = None + ) -> Tuple[List[MultiScoreSpectrumMatch], NDArray[np.bool_], NDArray[np.bool_]]: + if fdr_threshold is None: + fdr_threshold = self.train_fdr + labels = Array('b') + is_target = Array('b') + psms = [] + q_value_map = tda.q_value_map + + for t in tda.targets: + labels.append(int(q_value_map[tda.get_score(t)] <= fdr_threshold)) + psms.append(t) + is_target.append(True) + + n_targets = np.frombuffer(labels, dtype=bool).sum() + + for d in tda.decoys: + labels.append(-1) + psms.append(d) + is_target.append(False) + + n_decoys = len(tda.decoys) + + self.log( + f""Selected {n_targets} target spectra and {n_decoys} decoy spectra selected for training"" + ) + return psms, np.frombuffer(labels, dtype=np.int8), np.frombuffer(is_target, dtype=bool) + + def extract_features(self, psms: List[MultiScoreSpectrumMatch]) -> np.ndarray: + '''Override in subclass to construct feature matrix for SVM model''' + raise NotImplementedError() + + def _wrap_psms_with_score( + self, psms: List[SpectrumMatch], scores: List[float], is_target: List[bool] + ) -> List[SpectrumMatch]: + targets = [] + decoys = [] + for psm, score, is_t in zip(psms, scores, is_target): + wrapped = SpectrumMatch(psm.scan, psm.target, score) + if is_t: + targets.append(wrapped) + else: + decoys.append(wrapped) + return targets, decoys + + def scores_to_q_values( + self, psms: List[SpectrumMatch], scores: np.ndarray, is_target: List[bool] + ) -> Tuple[NearestValueLookUp, np.ndarray, ]: + + targets, decoys = self._wrap_psms_with_score(psms, scores, is_target) + tda = TargetDecoyAnalyzer(targets, decoys, decoy_pseudocount=0) + q_value_map = tda.q_value_map + q_values = np.array([q_value_map[s] for s in scores]) + + updated_labels = (q_values <= self.train_fdr).astype(int) + updated_labels[~np.asanyarray(is_target)] = -1 + return q_value_map, q_values, updated_labels, tda + + def fit(self, tda: TargetDecoyAnalyzer): + self.dataset = tda + psms, labels, is_target = self._get_psms_labels(tda, self.train_fdr) + + k = is_target.sum() + has_no_decoys = k == len(is_target) + has_no_targets = k == 0 + if has_no_decoys or has_no_targets: + self.worse_than_score = True + self.proxy_dataset = self.dataset + return + + features = self.extract_features(psms) + normalized_features = self.scaler.fit_transform(features) + starting_labels = labels + + model = self.prepare_model(self.model, normalized_features, labels) + for i in range(self.max_iter): + observations = normalized_features[labels.astype(bool), :] + target_labels_i = (labels[labels.astype(bool)] + 1) / 2 + if (target_labels_i == 1).sum() == 0 or (target_labels_i == 0).sum() == 0: + self.warn(""Found only one observation class, cannot proceed with model fitting"") + break + model.fit(observations, target_labels_i) + + scores = self.model.decision_function(normalized_features) + _q_value_map, _q_values, labels, self.proxy_dataset = self.scores_to_q_values( + psms, scores, is_target + ) + self.log(f""... Round {i}: {(labels == 1).sum()}"") + + if (labels == 1).sum() < (starting_labels == 1).sum(): + self.log( + f""Model performing worse than initial {(labels == 1).sum()} < {(starting_labels == 1).sum()}"" + ) + self.worse_than_score = True + assert self.dataset is not None + self.model = model + self.trained = True + self._normalized_features = normalized_features + + @property + def weights(self): + try: + return self.model.coef_ + except AttributeError: + self.log(""Model coefficients not yet fit"") + return [[]] + + def plot(self, ax=None): + if self.worse_than_score: + return self.dataset.plot(ax=ax) + ax = self.proxy_dataset.plot(ax=ax) + lo, hi = ax.get_xlim() + lo = self.proxy_dataset.thresholds[0] - 0.25 + ax.set_xlim(lo, hi) + ax.set_xlabel(""SVM Score"") + return ax + + def get_count_for_fdr(self, q_value: float): + return self.proxy_dataset.get_count_for_fdr(q_value) + + @property + def q_value_map(self): + return self.proxy_dataset.q_value_map + + @property + def fdr_map(self): + return self.q_value_map + + def score(self, spectrum_match: MultiScoreSpectrumMatch, assign=None): + if assign: + self.warn(""The assign argument is a no-op"") + if self.worse_than_score: + return self.dataset.score(spectrum_match, assign=False) + x = self.extract_features([spectrum_match]) + y = self.predict(x) + return self.q_value_map[y[0]] + + def summarize(self, name: Optional[str]=None): + if name is None: + name = ""FDR"" + if self.worse_than_score: + self.dataset.summarize(name) + return + + self.log(""Feature Weights:"") + feature_names = self.feature_names() + ['intercept'] + feature_values = list(self.weights[0]) + [self.model.intercept_] + for fname, fval in zip(feature_names, feature_values): + self.log(f""... {fname}: {fval}"") + + threshold_05, count_05 = self.get_count_for_fdr(0.05) + self.log(f""5% {name} = {threshold_05:0.3f} ({count_05})"") + threshold_01, count_01 = self.get_count_for_fdr(0.01) + self.log(f""1% {name} = {threshold_01:0.3f} ({count_01})"") + + +class PeptideScoreSVMModel(SVMModelBase): + + def _wrap_dataset(self, target_matches: List[MultiScoreSpectrumMatch], + decoy_matches: List[MultiScoreSpectrumMatch]): + tda = PeptideScoreTargetDecoyAnalyzer( + target_matches, decoy_matches, decoy_pseudocount=0.0) + return tda + + def feature_names(self) -> List[str]: + return [ + ""peptide_score"", + ""peptide_coverage"", + ] + + def extract_features(self, psms: List[MultiScoreSpectrumMatch]) -> np.ndarray: + features = np.zeros((len(psms), 2)) + for i, psm in enumerate(psms): + features[i, :] = ( + psm.score_set.peptide_score, + psm.score_set.peptide_coverage, + ) + return features +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/spectrum_match/solution_set.py",".py","33162","991","""""""Represent collections of :class:`~SpectrumMatch` instances covering the same spectrum. + +Also includes methods for selecting which are worth keeping for downstream consideration. +"""""" +import logging +from typing import Iterable, Iterator, List, Dict, Any, Optional, Type, Union, Sequence, TypeVar + +from ms_deisotope.data_source import ProcessedScan + +from glycresoft.chromatogram_tree import Unmodified +from glycresoft.task import log_handle + +from .spectrum_match import SpectrumMatch, SpectrumReference, ScanWrapperBase, MultiScoreSpectrumMatch + + +logger = logging.getLogger(__name__) + +MatchType = TypeVar('MatchType', bound=SpectrumMatch) + + +class SpectrumMatchRetentionStrategyBase(object): + """""" + A method for filtering :class:`SpectrumMatch` objects out of a list according to a specific criterion. + + Attributes + ---------- + threshold: object + Some abstract threshold + """""" + threshold: float + + def __init__(self, threshold): + self.threshold = threshold + + def filter_matches(self, solution_set: 'SpectrumSolutionSet'): + """""" + Filter :class:`SpectrumMatch` objects from a list. + + Parameters + ---------- + solution_set : list + The list of :class:`SpectrumMatch` objects to filter. + + Returns + ------- + list + """""" + raise NotImplementedError() + + def __call__(self, solution_set: 'SpectrumSolutionSet'): + return self.filter_matches(solution_set) + + def __repr__(self): + return ""{self.__class__.__name__}({self.threshold})"".format(self=self) + + +class MinimumScoreRetentionStrategy(SpectrumMatchRetentionStrategyBase): + """""" + Filtering :class:`~.SpectrumMatch` from a list if their :attr:`~.SpectrumMatch.score` < :attr:`threshold`. + + Parameters + ---------- + solution_set : list + The list of :class:`SpectrumMatch` objects to filter. + + Returns + ------- + list + """""" + + def filter_matches(self, solution_set): + retain = [] + for match in solution_set: + if match.score > self.threshold: + retain.append(match) + return retain + + +class MinimumMultiScoreRetentionStrategy(SpectrumMatchRetentionStrategyBase): + """""" + A minimum score filtering strategy for multi-score matches. + + A strategy for filtering :class:`~.SpectrumMatch` from a list if + their :attr:`~.SpectrumMatch.score_set` is less than :attr:`threshold`, + assuming they share the same dimensions. + + Parameters + ---------- + solution_set : list + The list of :class:`SpectrumMatch` objects to filter. + + Returns + ------- + list + """""" + + def filter_matches(self, solution_set): + retain = [] + for match in solution_set: + for score_i, ref_i in zip(match.score_set, self.threshold): + if score_i < ref_i: + break + else: + retain.append(match) + return retain + + +class MaximumSolutionCountRetentionStrategy(SpectrumMatchRetentionStrategyBase): + """""" + A strategy for filtering :class:`~.SpectrumMatch` from a list to retain the top :attr:`threshold` entries. + + This assumes that `solution_set` is sorted. + + Parameters + ---------- + solution_set : list + The list of :class:`SpectrumMatch` objects to filter. + + Returns + ------- + list + """""" + + def group_solutions(self, solutions, threshold=1e-2): + """""" + Group solutions which have scores that are very close to one-another so they are not arbitrarily truncated. + + Parameters + ---------- + solutions : list + A list of :class:`~.SpectrumMatchBase` + threshold : float, optional + The maxmimum distance between two scores to still be considered + part of a group (the default is 1e-2) + + Returns + ------- + list + """""" + groups = [] + if len(solutions) == 0: + return groups + current_group = [solutions[0]] + last_solution = solutions[0] + for solution in solutions[1:]: + delta = abs(solution.score - last_solution.score) + if delta > threshold: + groups.append(current_group) + current_group = [solution] + else: + current_group.append(solution) + last_solution = solution + groups.append(current_group) + return groups + + def filter_matches(self, solution_set): + groups = self.group_solutions(solution_set) + return [b for a in groups[:self.threshold] for b in a] + + +class TopScoringSolutionsRetentionStrategy(SpectrumMatchRetentionStrategyBase): + """""" + Retain only solutions with :attr:`threshold` of the top score. + + A strategy for filtering :class:`~.SpectrumMatch` from a list to retain + those with scores that are within :attr:`threshold` of the highest score in + the set. + + This assumes that `solution_set` is sorted and that the highest score is at + the 0th index.. + + Parameters + ---------- + solution_set : list + The list of :class:`SpectrumMatch` objects to filter. + + Returns + ------- + list + """""" + + def filter_matches(self, solution_set): + if len(solution_set) == 0: + return solution_set + best_score = solution_set[0].score + retain = [] + for solution in solution_set: + if (best_score - solution.score) < self.threshold: + retain.append(solution) + return retain + + +class QValueRetentionStrategy(SpectrumMatchRetentionStrategyBase): + """""" + Filtering :class:`~.SpectrumMatch` from a list if their :attr:`~.SpectrumMatch.q_value` < :attr:`threshold`. + + A strategy for filtering :class:`~.SpectrumMatch` from a list to retain + those with q-value that are less than :attr:`threshold`. + + Parameters + ---------- + solution_set : list + The list of :class:`SpectrumMatch` objects to filter. + + Returns + ------- + list + """""" + + def filter_matches(self, solution_set): + retain = [] + for match in solution_set: + if match.q_value < self.threshold: + retain.append(match) + return retain + + +class SpectrumMatchRetentionMethod(SpectrumMatchRetentionStrategyBase): + """""" + Combine several :class:`SpectrumMatchRetentionStrategyBase` together. + + A collection of several :class:`SpectrumMatchRetentionStrategyBase` + objects which are applied in order to iteratively filter out :class:`SpectrumMatch` + objects. + + This class implements the same :class:`SpectrumMatchRetentionStrategyBase` API + so it may be used interchangably with single strategies. + + Attributes + ---------- + strategies: list + The list of :class:`SpectrumMatchRetentionStrategyBase` + """""" + + def __init__(self, strategies=None): # pylint: disable=super-init-not-called + if strategies is None: + strategies = [] + self.strategies = strategies + + def filter_matches(self, solution_set): + retained = list(solution_set) + for strategy in self.strategies: + retained = strategy(retained) + return retained + + def __repr__(self): + return ""{self.__class__.__name__}({self.strategies!r})"".format(self=self) + + +default_selection_method = SpectrumMatchRetentionMethod([ + MinimumScoreRetentionStrategy(4.), + TopScoringSolutionsRetentionStrategy(3.), + MaximumSolutionCountRetentionStrategy(100) +]) + + +default_multiscore_selection_method = SpectrumMatchRetentionMethod([ + MinimumMultiScoreRetentionStrategy((1.0, 0., 0.)), + TopScoringSolutionsRetentionStrategy(100.), + MaximumSolutionCountRetentionStrategy(100), +]) + +class SpectrumMatchSortingStrategy(object): + """"""A base strategy for sorting spectrum matches to rank the best solution."""""" + + def key_function(self, spectrum_match: SpectrumMatch): + """""" + Create the sorting key for the spectrum match. + + For consistency, the target's ``id`` attribute is used to order + matches that have the same score so repeated searches with the same + database produce the same ordering. + + Returns + ------- + tuple + """""" + return (spectrum_match.valid, spectrum_match.score, spectrum_match.target.id) + + def sort(self, solution_set: 'SpectrumSolutionSet', maximize: bool = True) -> List[SpectrumMatch]: + """""" + Perform the sorting step. + + Parameters + ---------- + solution_set: :class:`Iterable` of :class:`~.SpectrumMatch` instances + The spectrum matches to sort + maximize: bool + Whether to sort ascending or descending + + Returns + ------- + :class:`list` of :class:`~.SpectrumMatch` instances + """""" + return sorted(solution_set, key=self.key_function, reverse=maximize) + + def __call__(self, solution_set: 'SpectrumSolutionSet', maximize: bool = True) -> List[SpectrumMatch]: + """""" + Perform the sorting step. + + Parameters + ---------- + solution_set: :class:`Iterable` of :class:`~.SpectrumMatch` instances + The spectrum matches to sort + maximize: bool + Whether to sort ascending or descending + + Returns + ------- + :class:`list` of :class:`~.SpectrumMatch` instances + """""" + return self.sort(solution_set, maximize=maximize) + + +class MultiScoreSpectrumMatchSortingStrategy(SpectrumMatchSortingStrategy): + def key_function(self, spectrum_match: MultiScoreSpectrumMatch): + return (spectrum_match.valid, spectrum_match.score_set, spectrum_match.target.id) + + +class NOParsimonyMixin(object): + """""" + Provides shared methods for a parsimony step re-ordering solutions when the top + solution may be N-linked or O-linked. + """""" + + threshold_percentile: float + + def __init__(self, threshold_percentile=0.5): + self.threshold_percentile = threshold_percentile + + def get_score(self, solution): + return solution.score_set.glycan_score + + def get_target(self, solution): + return solution.target + + def hoist_equivalent_n_linked_solution(self, solution_set: Iterable[SpectrumMatch], + maximize: bool=True) -> List[SpectrumMatch]: + """""" + Apply a parsimony step re-ordering solutions when the top solution may be N-linked or O-linked. + + The O-linked core motif is much simpler than the N-linked core, so it gets + preferential treatment. This re-orders the matches so that the N-linked solution + equivalent to the O-linked solution gets marked as the top solution if the + N-linked solution's glycan score is within :attr:`threshold_percent` of the + actual top scoring O-linked solution. + + Parameters + ---------- + solution_set: :class:`Iterable` of :class:`~.SpectrumMatch` instances + The spectrum matches to sort + maximize: bool + Whether to sort ascending or descending + + Returns + ------- + :class:`list` of :class:`~.SpectrumMatch` instances + """""" + best_solution = solution_set[0] + best_gp = self.get_target(best_solution) + best_gc = best_gp.glycan_composition + + hoisted = [] + rest = [best_solution] + if maximize: + threshold = self.get_score(best_solution) * self.threshold_percentile + else: + threshold = self.get_score(best_solution) * (1 + (1 - self.threshold_percentile)) + i = 0 + for i, sm in enumerate(solution_set): + if i == 0: + continue + + if maximize: + if self.get_score(sm) < threshold: + rest.append(sm) + break + else: + if self.get_score(sm) > threshold: + rest.append(sm) + break + sm_target = self.get_target(sm) + if (best_gp.base_sequence_equality(sm_target) and str(best_gc) == str(sm_target.glycan_composition) + and sm_target.is_n_glycosylated()): + hoisted.append(sm) + log_handle.log(f""Hoisting {sm.target} for scan {sm.scan.scan_id!r}"") + else: + rest.append(sm) + rest.extend(solution_set[i + 1:]) + hoisted.extend(rest) + return hoisted + + +class NOParsimonyMultiScoreSpectrumMatchSortingStrategy(NOParsimonyMixin, MultiScoreSpectrumMatchSortingStrategy): + """""" + A sorting strategy that applies prefers N-glycans to O-glycans on the same peptide. + + It applies parsimony to selecting the top solution when + an N-linked solution is more parsimonious than an O-linked solution. + """""" + + def sort(self, solution_set: Iterable[MultiScoreSpectrumMatch], maximize=True) -> List[MultiScoreSpectrumMatch]: + solution_set = super(NOParsimonyMultiScoreSpectrumMatchSortingStrategy, self).sort(solution_set, maximize) + if solution_set and solution_set[0].target.is_o_glycosylated(): + solution_set = self.hoist_equivalent_n_linked_solution(solution_set, maximize) + return solution_set + + +single_score_sorter = SpectrumMatchSortingStrategy() +multi_score_sorter = MultiScoreSpectrumMatchSortingStrategy() +# This sort function isn't useful at this moment. The actual +# ordering is set in chromatogram_mapping +# multi_score_parsimony_sorter = NOParsimonyMultiScoreSpectrumMatchSortingStrategy(0.75) + + + +class SpectrumSolutionSet(ScanWrapperBase, Sequence[MatchType]): + """""" + A collection of spectrum matches against a single scan with different structures. + + Implements the :class:`Sequence` interface. + + Attributes + ---------- + scan: :class:`~.Scan`-like + The matched scan + solutions: list + The distinct spectrum matches. + score: float + The best match's score + """""" + + spectrum_match_type: Type[MatchType] = SpectrumMatch + default_selection_method: SpectrumMatchRetentionMethod = default_selection_method + + scan: Union[ProcessedScan, SpectrumReference] + solutions: List[MatchType] + + _target_map: Dict[Any, MatchType] + _is_top_only: bool + _is_sorted: bool + _is_simplified: bool + _q_value: Optional[float] + + def __init__(self, scan, solutions=None): + if solutions is None: + solutions = [] + self.scan = scan + self.solutions = solutions + self._is_sorted = False + self._is_simplified = False + self._is_top_only = False + self._target_map = None + self._q_value = None + + def is_ambiguous(self) -> bool: + seen = set() + + for sm in self: + if sm.is_best_match: + seen.add(str(sm.target)) + return len(seen) > 1 + + def is_multiscore(self) -> bool: + """""" + Check whether this match has been produced by summarizing a multi-score match, rather + than a single score match. + + Returns + ------- + bool + """""" + return False + + def _invalidate(self, invalidate_order: bool): + if invalidate_order: + self._is_sorted = False + self._target_map = None + self._q_value = None + + @property + def score(self): + """"""The best match's score. + + Returns + ------- + float + """""" + return self.best_solution().score + + @property + def q_value(self): + """"""The best match's q-value. + + Returns + ------- + float + """""" + if self._q_value is None: + self._q_value = self.best_solution().q_value + return self._q_value + + @q_value.setter + def q_value(self, value): + self._q_value = value + + def _make_target_map(self): + self._target_map = { + sol.target: sol for sol in self + } + + def has_solution(self, target) -> bool: + if self._target_map is None: + self._make_target_map() + return target in self._target_map + + def solution_for(self, target) -> MatchType: + """""" + Find the spectrum match from this set which corresponds to the provided `target` structure. + + Parameters + ---------- + target : object + The target to search for + + Returns + ------- + :class:`~.SpectrumMatchBase` + """""" + if self._target_map is None: + self._make_target_map() + return self._target_map[target] + + def precursor_mass_accuracy(self): + """""" + The precursor mass accuracy of the best match. + + Returns + ------- + float + """""" + return self.best_solution().precursor_mass_accuracy() + + def best_solution(self, reject_shifted=False, targets_ignored=None, require_valid=True) -> MatchType: + """""" + The element in :attr:`solutions` which is the best match to :attr:`scan`, the match at position 0. + + If the collection is not sorted, :meth:`sort` will be called. + + Parameters + ---------- + reject_shifted : bool + Whether or not to reject any solution where the mass shift is not :obj:`Unmodified`. + Defaults to :const:`False`. + targets_ignored : Container + A collection of :attr:`~.SpectrumMatch.target` values to ignore + + Returns + ------- + :class:`~.SpectrumMatchBase` + """""" + if not self._is_sorted: + self.sort() + if targets_ignored is None: + targets_ignored = () + if not reject_shifted and not targets_ignored: + for solution in self.solutions: + if solution.valid: + return solution + for solution in self: + if (solution.mass_shift == Unmodified or not reject_shifted) and (solution.target in targets_ignored or + not targets_ignored) and (solution.valid or not require_valid): + return solution + + def mark_top_solutions(self, reject_shifted=False, targets_ignored=None) -> 'SpectrumSolutionSet': + solution = self.best_solution( + reject_shifted=reject_shifted, + targets_ignored=targets_ignored) + if solution is None and reject_shifted: + return self.mark_top_solutions(reject_shifted=False, targets_ignored=targets_ignored) + if solution is None and targets_ignored: + return self.mark_top_solutions( + reject_shifted=reject_shifted, targets_ignored=None) + if solution is None and not reject_shifted and not targets_ignored: + logger.warn(f""Could not mark a top solution for {self.scan_id} (not reject shifted and not targets ignore)"") + return self + if solution is None: + logger.warn(f""Could not mark a top solution for {self.scan_id}"") + return self + solution.best_match = True + best_solution_score = solution.score + for solution in self: + if (abs(best_solution_score - solution.score) < 1e-3 or + best_solution_score < solution.score) and solution.valid: + solution.best_match = True + else: + solution.best_match = False + return self + + def __repr__(self): + if len(self) == 0: + return ""{self.__class__.__name__}({self.scan}, [])"".format(self=self) + return ""{self.__class__.__name__}({self.scan}, {best.target}, {best.score})"".format( + self=self, best=self.best_solution()) + + def __getitem__(self, i): + return self.solutions[i] + + def __iter__(self) -> Iterator[MatchType]: + return iter(self.solutions) + + def __len__(self): + return len(self.solutions) + + def simplify(self): + """""" + Discard excess information in this collection to save space. + + Converts :attr:`scan` to a :class:`~.SpectrumReference`, and + converts all matches to :class:`~.SpectrumMatch`, discarding + matcher-specific information. + + """""" + if self._is_simplified: + return + self.scan = SpectrumReference( + self.scan.id, self.scan.precursor_information) + solutions = [] + if len(self) > 0: + best_score = self.best_solution().score + for sol in self.solutions: + sm = self.spectrum_match_type.from_match_solution(sol) + if abs(sm.score - best_score) < 1e-6: + sm.best_match = True + sm.scan = self.scan + solutions.append(sm) + self.solutions = solutions + self._is_simplified = True + self._invalidate(False) + + def get_top_solutions(self, d=3, reject_shifted=False, targets_ignored=None, + require_valid=True) -> List[MatchType]: + """""" + Get all matches within `d` of the best solution. + + Parameters + ---------- + d : float, optional + The delta between the best match and the worst to return + (the default is 3) + reject_shifted : bool + Whether or not to reject any solution where the mass shift is not :obj:`Unmodified`. + Defaults to :const:`False`. + targets_ignored : Container + A collection of :attr:`~.SpectrumMatch.target` values to ignore + + Returns + ------- + list + """""" + best = self.best_solution( + reject_shifted=reject_shifted, targets_ignored=targets_ignored, require_valid=require_valid) + if best is None and reject_shifted: + return self.get_top_solutions( + d, + reject_shifted=False, + targets_ignored=targets_ignored, + require_valid=require_valid + ) + if best is None and targets_ignored: + return self.get_top_solutions( + d, + reject_shifted=reject_shifted, + targets_ignored=None, + require_valid=require_valid + ) + if best is None: + return [] + best_score = best.score + if reject_shifted: + return [x for x in self.solutions if (best_score - x.score) < d and x.mass_shift == Unmodified] + return [x for x in self.solutions if (best_score - x.score) < d] + + def select_top(self, method=None) -> 'SpectrumSolutionSet': + """""" + Filter spectrum matches in this collection in-place. + + If all the solutions would be filtered out, only the best solution + will be kept. + + .. warning:: + This method is dangerous to use when spectrum matches in the same + list are part of different groups (e.g. different decoy sets). Use + it with caution. + + Parameters + ---------- + method : :class:`SpectrumRetentionStrategyBase`, optional + The filtering strategy to use, a callable object that returns a + shortened list of :class:`~.SpectrumMatchBase` instances. + If :const:`None`, :attr:`default_selection_method` will be used. + + """""" + if method is None: + method = self.default_selection_method + if self._is_top_only: + return self + if not self._is_sorted: + self.sort() + if len(self) > 0: + best_solution = self.best_solution() + after = method(self) + self.solutions = after + if len(self) == 0: + self.solutions = [best_solution] + self._is_top_only = True + self._invalidate(False) + return self + + def sort(self, maximize=True, method=None) -> 'SpectrumSolutionSet': + """""" + Sort the spectrum matches in this solution set according to their score attribute. + + In the event of a tie, in order to enforce determistic behavior, this will also + sort matches according to their target's id attribute. + + Sets :attr:`_is_sorted` to :const:`True`. + + Parameters + ---------- + maximize : bool, optional + If true, sort descending order instead of ascending. Defaults to :const:`True` + + See Also + -------- + sort_by + sort_q_value + """""" + if method is None: + method = single_score_sorter + self.solutions = method(self.solutions, maximize=maximize) + self._is_sorted = True + return self + + def sort_by(self, sort_fn=None, maximize=True) -> 'SpectrumSolutionSet': + """""" + Sort the spectrum matches in this solution set according to `sort_fn`. + + This method behaves the same way :meth:`sort` does, except instead of + sorting on an intrinsic attribute it uses a callable. It uses the same + determistic augmentation as :meth:`sort` + + Parameters + ---------- + sort_fn : Callable, optional + The sort key function to use. If not provided, falls back to :meth:`sort`. + maximize : bool, optional + If true, sort descending order instead of ascending. Defaults to :const:`True` + + See Also + -------- + sort + """""" + if sort_fn is None: + return self.sort(maximize=maximize) + self.solutions.sort(key=lambda x: (sort_fn(x), x.target.id), reverse=maximize) + self._is_sorted = True + return self + + def sort_q_value(self) -> 'SpectrumSolutionSet': + """""" + Sort the spectrum matches in this solution set according to their q_value attribute. + + In the event of a tie, in order to enforce determistic behavior, this will also + sort matches according to their target's id attribute. + + Sets :attr:`_is_sorted` to :const:`True`. + + See Also + -------- + sort + sort_by + """""" + self.solutions.sort(key=lambda x: (x.q_value, x.target.id), reverse=False) + self._is_sorted = True + return self + + def merge(self, other) -> 'SpectrumSolutionSet': + self._invalidate(True) + self.solutions.extend(other) + self.sort() + if self._is_top_only: + self._is_top_only = False + self.select_top() + return self + + def append(self, match: MatchType) -> 'SpectrumSolutionSet': + self._invalidate(True) + self.solutions.append(match) + self.sort() + if self._is_top_only: + self._is_top_only = False + self.select_top() + return self + + def insert(self, position: int, match: MatchType, is_sorted=True): + was_sorted = self._is_sorted + self._invalidate(True) + if is_sorted: + self._is_sorted = was_sorted + self.solutions.insert(position, match) + + def remove(self, match: MatchType): + self.solutions.remove(match) + + def promote_to_best_match(self, match: MatchType, reject_shifted: bool=False, + targets_ignored: Optional[List[Any]] = None) -> 'SpectrumSolutionSet': + try: + self.remove(match) + except ValueError: + pass + self.insert(0, match, is_sorted=True) + return self.mark_top_solutions( + reject_shifted=reject_shifted, + targets_ignored=targets_ignored + ) + + def clone(self): + dup = self.__class__(self.scan, [ + s.clone() for s in self.solutions + ]) + dup._is_simplified = self._is_simplified + dup._is_top_only = self._is_top_only + dup._is_sorted = self._is_sorted + return dup + + def __eq__(self, other): + if self.scan.id != other.scan.id: + return False + return self.solutions == other.solutions + + def __ne__(self, other): + return not (self == other) + + @property + def key(self) -> frozenset: + scan_id = self.scan.id + return frozenset([(scan_id, match.target.id) for match in self]) + + def rank(self) -> 'SpectrumSolutionSet': + """""" + Rank the spectrum matches in this solution set by their ordering and scores. + + The best match receiving the lowest rank and successive matches receiving + higher ranks, the best rank being 1. Spectrum matches with scores that are + very close together will receive the same rank. + + The score ranking process is only approximate because in some scenarios the + match ordering is overridden by external factors e.g. retention time, signature + ions, or adducts. + + Returns + ------- + SpectrumSolutionSet + """""" + if not self: + return self + current_rank = 0 + current_score = float('inf') + for sm in self: + if abs(sm.score - current_score) >= 1e-3: + current_rank += 1 + current_score = sm.score + sm.rank = current_rank + return self + + +def close_to_or_greater_than(value: float, reference: float, delta: float=1e-3): + return abs(value - reference) < delta or value > reference + + +class MultiScoreSpectrumSolutionSet(SpectrumSolutionSet[MultiScoreSpectrumMatch]): + spectrum_match_type = MultiScoreSpectrumMatch + default_selection_method = default_multiscore_selection_method + + def is_multiscore(self): + return True + + # NOTE: Sorting by total score is not guaranteed to sort by total + # FDR. Sorting by FDR after-the-fact is cheating though because we + # don't count next-best decoys. + + def sort(self, maximize=True, method=None): + """""" + Sort the spectrum matches in this solution set according to their score_set attribute. + + In the event of a tie, in order to enforce determistic behavior, this will also + sort matches according to their target's id attribute. + + Sets :attr:`_is_sorted` to :const:`True`. + + See Also + -------- + sort_by + sort_q_value + """""" + if method is None: + method = multi_score_sorter + self.solutions = method(self.solutions, maximize=maximize) + self._is_sorted = True + return self + + def mark_top_solutions(self, reject_shifted=False, targets_ignored=None): + solution = self.best_solution(reject_shifted=reject_shifted, targets_ignored=targets_ignored) + if solution is None and reject_shifted: + return self.mark_top_solutions(reject_shifted=False, targets_ignored=targets_ignored) + if solution is None and targets_ignored: + return self.mark_top_solutions(reject_shifted=reject_shifted, targets_ignored=None) + if solution is None and not reject_shifted and not targets_ignored: + logger.warn(f""Could not mark a top solution for {self.scan_id}"") + return self + solution.best_match = True + score_set = solution.score_set + for solution in self: + if not solution.valid: + solution.best_match = False + continue + if reject_shifted and solution.mass_shift != Unmodified: + solution.best_match = False + continue + if targets_ignored and solution.target in targets_ignored: + solution.best_match = False + continue + if ((score_set.glycopeptide_score - solution.score_set.glycopeptide_score)) < 1e-3: + # NOTE: This requires that both the peptide portion and the glycan portion be as + # good or better than the ""best"" match. When the ""best match"" is better in one + # dimension and worse in another dimension, this becomes more ambiguous. It's + # possible to query the FDR of the cases, but :meth:`mark_top_solutions` may + # be called before FDR estimation. Furthermore, a ""best match"" ranked by FDR + # potentially introduces all sorts of issues of re-ranking, and could introduce + # an undesirable number of ""alternative"" best matches. + if (score_set.peptide_score - solution.score_set.peptide_score) < 1e-3 and ( + score_set.glycan_score - solution.score_set.glycan_score) < 1e-3: + solution.best_match = True + else: + solution.best_match = False + else: + solution.best_match = False + return self + + def sort_q_value(self): + """""" + Sort the spectrum matches in this solution set according to their q_value_set attribute. + + In the event of a tie, in order to enforce determistic behavior, this will also + sort matches according to their target's id attribute. + + Sets :attr:`_is_sorted` to :const:`True`. + + See Also + -------- + sort + sort_by + """""" + self.solutions.sort(key=lambda x: ( + x.q_value_set, x.score_set, x.target.id), reverse=False) + self._is_sorted = True + return self + + @property + def score_set(self): + """""" + The best match's score set. + + Returns + ------- + ScoreSet + """""" + return self.best_solution().score_set + + @property + def q_value_set(self): + """""" + The best match's q-value set. + + Returns + ------- + FDRSet + """""" + return self.best_solution().q_value_set +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/spectrum_match/spectrum_match.py",".py","31445","1009","import warnings +import struct +import logging + +from typing import Any, ClassVar, List, Tuple, Type, Union, Optional, TYPE_CHECKING, Generic, TypeVar +from enum import IntFlag + +import glycopeptidepy + +from glypy.utils import make_struct + +from ms_deisotope import DeconvolutedPeakSet, isotopic_shift +from ms_deisotope.data_source import ProcessedScan +from ms_deisotope.data_source.metadata import activation +from glycresoft.chromatogram_tree.mass_shift import MassShiftBase + +from glycresoft.structure import ( + ScanWrapperBase, ScanInformation, FragmentCachingGlycopeptide) + +from glycresoft.structure.enums import SpectrumMatchClassification + +from glycresoft.chromatogram_tree import Unmodified + +from glycresoft.tandem.ref import TargetReference, SpectrumReference + +if TYPE_CHECKING: + from glycresoft.tandem.target_decoy.base import FDREstimatorBase + from glycresoft.plotting.spectral_annotation import TidySpectrumMatchAnnotator + from matplotlib.axes import Axes + +neutron_offset = isotopic_shift() + +LowCID = activation.dissociation_methods['low-energy collision-induced dissociation'] + +logger = logging.getLogger(""glycresoft.spectrum_match"") +logger.addHandler(logging.NullHandler()) + + +class ScanMatchManagingMixin(ScanWrapperBase): + __slots__ = () + + target: Union[FragmentCachingGlycopeptide, Any] + mass_shift: MassShiftBase + + def __init__(self, scan, target, mass_shift=None): + if mass_shift is None: + mass_shift = Unmodified + self.scan = scan + self.target = target + self.mass_shift = mass_shift + + def drop_peaks(self): + self.scan = ScanInformation.from_scan(self.scan) + return self + + @staticmethod + def load_peaks(scan) -> ProcessedScan: + try: + return scan.convert(fitted=False, deconvoluted=True) + except AttributeError: + return scan + + @staticmethod + def threshold_peaks(deconvoluted_peak_set, threshold_fn=lambda peak: True): + """""" + Filter a deconvoluted peak set by a predicate function. + + Parameters + ---------- + deconvoluted_peak_set : :class:`ms_deisotope.DeconvolutedPeakSet` + The deconvoluted peaks to filter + threshold_fn : Callable + The predicate function to use to decide whether or not to keep a peak. + + Returns + ------- + :class:`ms_deisotope.DeconvolutedPeakSet` + """""" + deconvoluted_peak_set = DeconvolutedPeakSet([ + p for p in deconvoluted_peak_set + if threshold_fn(p) + ]) + deconvoluted_peak_set._reindex() + return deconvoluted_peak_set + + def is_hcd(self) -> bool: + """""" + Check whether the MSn spectrum was fragmented using a collisional dissociation + mechanism or not. + + The result is cached on :attr:`scan`, so the interpretation does not need to be repeated. + + .. note:: If no activation information is present, the spectrum will be assumed to be HCD. + + Returns + ------- + bool + """""" + scan = self.scan + annotations = scan.annotations + try: + result = annotations['is_hcd'] + except KeyError: + activation_info = scan.activation + if activation_info is None: + if scan.ms_level == 1: + result = False + else: + warnings.warn( + ""Activation information is missing. Assuming HCD"") + result = True + else: + result = activation_info.has_dissociation_type(activation.HCD) or\ + activation_info.has_dissociation_type(activation.CID) or\ + activation_info.has_dissociation_type(LowCID) or\ + activation_info.has_dissociation_type( + activation.UnknownDissociation) + annotations['is_hcd'] = result + return result + + def is_exd(self) -> bool: + """""" + Check if the scan was dissociated using an E*x*D method. + + This checks for ECD and ETD terms. + + This method caches its result in the scan's annotations. + + Returns + ------- + bool + + See Also + -------- + is_hcd + """""" + scan = self.scan + annotations = scan.annotations + try: + result = annotations['is_exd'] + except KeyError: + + activation_info = scan.activation + if activation_info is None: + if scan.ms_level == 1: + result = False + else: + warnings.warn( + ""Activation information is missing. Assuming not ExD"") + result = False + else: + result = activation_info.has_dissociation_type(activation.ETD) or\ + activation_info.has_dissociation_type(activation.ECD) + annotations['is_exd'] = result + return result + + def mz_range(self) -> Tuple[float, float]: + scan = self.scan + annotations = scan.annotations + try: + result = annotations['mz_range'] + except KeyError: + acquisition_info = scan.acquisition_information + if acquisition_info is None: + mz_range = (0, 1e6) + else: + lo = float('inf') + hi = 0 + for event in acquisition_info: + for window in event: + lo = min(window.lower, lo) + hi = max(window.upper, hi) + # No events/windows or an error + if hi < lo: + mz_range = (0, 1e6) + else: + mz_range = (lo, hi) + annotations['mz_range'] = mz_range + result = mz_range + return result + + def get_auxiliary_data(self): + return {} + + +class _SpectrumMatchBase(object): + __slots__ = ['scan', 'target', ""mass_shift""] + + scan: ProcessedScan + target: Union[FragmentCachingGlycopeptide, Any] + mass_shift: MassShiftBase + + +class SpectrumMatchBase(_SpectrumMatchBase, ScanMatchManagingMixin): + """""" + A base class for spectrum matches, a scored pairing between a structure + and tandem mass spectrum. + + Attributes + ---------- + scan: :class:`ms_deisotope.ProcessedScan` + The processed MSn spectrum to match + target: :class:`object` + A structure that can be fragmented and scored against. + mass_shift: :class:`~.MassShift` + A mass shifting adduct that alters the precursor mass and optionally some + of the fragment masses. + + """""" + + __slots__ = [] + + scan: ProcessedScan + target: Any + mass_shift: MassShiftBase + + def _theoretical_mass(self) -> float: + return self.target.total_composition().mass + + def precursor_mass_accuracy(self, offset: int=0) -> float: + """""" + Calculate the precursor mass accuracy in PPM, accounting for neutron offset + and mass shift. + + Parameters + ---------- + offset : int, optional + The number of neutron errors to account for (the default is 0). + + Returns + ------- + float: + The precursor mass accuracy in PPM. + """""" + observed = self.precursor_ion_mass + theoretical = self._theoretical_mass() + ( + offset * neutron_offset) + self.mass_shift.mass + return (observed - theoretical) / theoretical + + def determine_precursor_offset(self, + probing_range: int=3, + include_error: bool=False) -> Union[int, Tuple[int, float]]: + """""" + Iteratively re-estimate what the actual offset to the precursor mass was. + + Parameters + ---------- + probing_range : int, optional + The range of neutron errors to account for. (the default is 3) + include_error : bool, optional + Whether or not to return both the offset and the estimated mass error in PPM. + Defaults to False. + + Returns + ------- + best_offset: int + The best precursor offset. + error: float + The precursor mass error (in PPM) if `include_error` is :const:`True` + """""" + best_offset = 0 + best_error = float('inf') + theoretical_mass_base = self._theoretical_mass() + self.mass_shift.mass + observed = self.precursor_ion_mass + for i in range(probing_range + 1): + theoretical = theoretical_mass_base + i * neutron_offset + error = abs((observed - theoretical) / theoretical) + if error < best_error: + best_error = error + best_offset = i + if include_error: + return best_offset, best_error + return best_offset + + def __reduce__(self): + return self.__class__, (self.scan, self.target), self.__getstate__() + + def __getstate__(self): + return { + ""mass_shift"": self.mass_shift + } + + def __setstate__(self, state): + self.mass_shift = state.get(""mass_shift"", Unmodified) + + def get_top_solutions(self): + return [self] + + def __eq__(self, other): + try: + target_id = self.target.id + except AttributeError: + target_id = None + try: + other_target_id = self.target.id + except AttributeError: + other_target_id = None + return (self.scan == other.scan) and (self.target == other.target) and ( + target_id == other_target_id) + + def __ne__(self, other): + return not (self == other) + + def __hash__(self): + try: + target_id = self.target.id + except AttributeError: + target_id = None + return hash((self.scan.id, self.target, target_id)) + + +class SpectrumMatcherBase(SpectrumMatchBase): + __slots__ = [""spectrum"", ""_score""] + + spectrum: DeconvolutedPeakSet + _score: float + + def __init__(self, scan: ProcessedScan, target: Union[FragmentCachingGlycopeptide, Any], + mass_shift: Optional[MassShiftBase]=None): + if mass_shift is None: + mass_shift = Unmodified + self.scan = scan + self.spectrum = scan.deconvoluted_peak_set + self.target = target + self._score = 0 + self.mass_shift = mass_shift + + def drop_peaks(self): + super(SpectrumMatcherBase, self).drop_peaks() + self.spectrum = DeconvolutedPeakSet([]) + return self + + @property + def score(self): + """"""The aggregate spectrum match score. + + Returns + ------- + float + """""" + return self._score + + @score.setter + def score(self, value): + self._score = value + + def match(self, *args, **kwargs): + """"""Match theoretical fragments against experimental peaks. + """""" + raise NotImplementedError() + + def calculate_score(self, *args, **kwargs) -> float: + """"""Calculate a score given the fragment-peak matching. + + This method should populate :attr:`_score`. + + Returns + ------- + float + """""" + raise NotImplementedError() + + def base_peak(self) -> float: + """"""Find the base peak intensity of the spectrum, the + most intense peak's intensity. + + Returns + ------- + float + + """""" + try: + return self.scan.annotations['_base_peak'] + except KeyError: + peak = self.scan.base_peak() + if peak is not None: + value = self.spectrum.annotations['_base_peak'] = peak.intensity + else: + value = self.spectrum.annotations['_base_peak'] = 0.0 + return value + + @classmethod + def evaluate(cls, scan, target, *args, **kwargs): + """""" + A high level method to construct a :class:`SpectrumMatcherBase` + instance over a scan and target, call :meth:`match`, and + :meth:`calculate_score`. + + Parameters + ---------- + scan : :class:`~.ProcessedScan` + The scan to match against. + target : :class:`object` + The structure to match. + + Returns + ------- + :class:`SpectrumMatcherBase` + """""" + mass_shift = kwargs.pop(""mass_shift"", Unmodified) + inst = cls(scan, target, mass_shift=mass_shift) + inst.match(*args, **kwargs) + inst.calculate_score(*args, **kwargs) + return inst + + def __getstate__(self): + state = super(SpectrumMatcherBase, self).__getstate__() + state['score'] = self.score + return state + + def __setstate__(self, state): + super(SpectrumMatcherBase, self).__setstate__(state) + self._score = state.get('score') + + def __reduce__(self): + return self.__class__, (self.scan, self.target,), self.__getstate__() + + def __repr__(self): + return f""{self.__class__.__name__}({self.scan_id}, {self.spectrum}, {self.target}, {self.score})"" + + def plot(self, ax: Optional['Axes']=None, **kwargs) -> 'TidySpectrumMatchAnnotator': + """""" + Plot the spectrum match, using the :class:`~.TidySpectrumMatchAnnotator` + algorithm. + + Parameters + ---------- + ax : :class:`matplotlib.Axis`, optional + The axis to draw on. If not provided, a new figure + and axis will be created. + + Returns + ------- + :class:`~.TidySpectrumMatchAnnotator` + """""" + from glycresoft.plotting import spectral_annotation + art = spectral_annotation.TidySpectrumMatchAnnotator(self, ax=ax) + art.draw(**kwargs) + return art + + @classmethod + def get_score_set_type(cls) -> Type['ScoreSet']: + return ScoreSet + + @classmethod + def get_fdr_model_for_dimension(cls, label: str) -> Optional[Type['FDREstimatorBase']]: + if label == 'peptide': + from glycresoft.tandem.target_decoy import PeptideScoreSVMModel + return PeptideScoreSVMModel + +try: + from glycresoft._c.tandem.tandem_scoring_helpers import base_peak + SpectrumMatcherBase.base_peak = base_peak +except ImportError: + pass + + +class MatchFlags(IntFlag): + Unknown = 0 + Valid = 1 + Ambiguous = 2 + BestMatch = 4 + + +F = TypeVar('F', bound=IntFlag) + + +class FlagProperty(Generic[F]): + __slots__ = ('flag', ) + + flag: F + + def __repr__(self): + return f""{self.__class__.__name__}({self.flag})"" + + def __init__(self, flag: F): + self.flag = flag + + def __get__(self, obj, cls) -> bool: + if obj is None: + return self + return bool(obj.flags & self.flag) + + def __set__(self, obj, value: bool): + if value: + obj.flags |= self.flag + else: + obj.flags &= ~self.flag + + +class SpectrumMatch(SpectrumMatchBase): + """""" + Represent a summarized spectrum match, which has been calculated already. + + Attributes + ---------- + score: float + The aggregate match score of the spectrum-structure pairing + best_match: bool + Whether or not this spectrum match is the best match for :attr:`scan` + q_value: float + The false discovery rate for the match + id: int + The unique identifier of the match + + """""" + + __slots__ = [ + 'score', '_best_match', 'data_bundle', + 'q_value', 'id', 'valid', 'localizations', + 'rank', 'cluster_id' + ] + + score: float + q_value: float + + valid: bool + best_match: bool + + id: Optional[int] + + localizations: Optional[List['LocalizationScore']] + data_bundle: Optional[Any] + + rank: Optional[int] + cluster_id: Optional[int] + + def __init__(self, scan, target, score, best_match=False, data_bundle=None, + q_value=None, id=None, mass_shift=None, valid=True, + localizations=None, rank=0, cluster_id=None): + super(SpectrumMatch, self).__init__(scan, target, mass_shift) + + self.score = score + self._best_match = best_match + self.data_bundle = data_bundle + self.q_value = q_value + self.id = id + self.valid = valid + self.localizations = localizations + self.rank = rank + self.cluster_id = cluster_id + + @property + def best_match(self) -> bool: + return self._best_match + + @best_match.setter + def best_match(self, value: bool): + if logger.isEnabledFor(logging.DEBUG): + logger.debug( + f""... Setting {self.target}@{self.scan.id} best match to {value}"", + stacklevel=2 + ) + self._best_match = value + + @property + def is_best_match(self) -> bool: + return self.best_match + + @is_best_match.setter + def is_best_match(self, value: bool): + self.best_match = value + + def is_multiscore(self) -> bool: + """"""Check whether this match has been produced by summarizing a multi-score + match, rather than a single score match. + + Returns + ------- + bool + """""" + return False + + def pack(self): + """"""Package up the information of the match into the minimal information to + describe the match. + + This method returns an opaque data carrier that can be reconstituted using + :meth:`unpack`. + + Returns + ------- + object + """""" + return (self.target.id, self.score, int(self.best_match), self.mass_shift.name) + + @classmethod + def unpack(cls, data, spectrum, resolver, offset=0): + """"""Reconstitute a :class:`SpectrumMatch` from packed + data and a lookup table. + + Parameters + ---------- + data : object + The result of :meth:`pack` + spectrum : :class:`~.ProcessedScan` or :class:`~.SpectrumReference` + The spectrum that was matched. + resolver : :class:`object` + An object which can be used to resolve mass shifts and targets. + offset : int, optional + The offset into `data` to start reading from. Defaults to `0`. + + Returns + ------- + match: :class:`SpectrumMatch` + The reconstructed match + offset: int + The next offset to read from in `data` + """""" + i = offset + target_id = int(data[i]) + score = float(data[i + 1]) + try: + best_match = bool(int(data[i + 2])) + except ValueError: + best_match = bool(data[i + 2]) + mass_shift_name = data[i + 3] + mass_shift = resolver.resolve_mass_shift(mass_shift_name) + match = SpectrumMatch( + spectrum, + resolver.resolve_target(target_id), + score, + best_match, + mass_shift=mass_shift) + i += 4 + return match, i + + def clear_caches(self): + """"""Clear caches on :attr:`target`. + """""" + try: + self.target.clear_caches() + except AttributeError: + pass + + def __reduce__(self): + return self.__class__, (self.scan, self.target, self.score, self.best_match, + self.data_bundle, self.q_value, self.id, + self.mass_shift, self.valid, self.localizations) + + def evaluate(self, scorer_type: Type[SpectrumMatcherBase], *args, **kwargs): + """"""Re-evaluate this spectrum-structure pair. + + Parameters + ---------- + scorer_type : :class:`SpectrumMatcherBase` + The matcher type to use. + + Returns + ------- + :class:`SpectrumMatcherBase` + """""" + if isinstance(self.scan, SpectrumReference): + raise TypeError(""Cannot evaluate a spectrum reference"") + elif isinstance(self.target, TargetReference): + raise TypeError(""Cannot evaluate a target reference"") + return scorer_type.evaluate(self.scan, self.target, *args, **kwargs) + + def __repr__(self): + return ""%s(%s, %s, %0.4f, %r)"" % ( + self.__class__.__name__, + self.scan, self.target, self.score, self.mass_shift) + + @classmethod + def from_match_solution(cls, match: SpectrumMatcherBase) -> 'SpectrumMatch': + """"""Create a :class:`SpectrumMatch` from another :class:`SpectrumMatcherBase` + + Parameters + ---------- + match : :class:`SpectrumMatcherBase` + The :class:`SpectrumMatcherBase` to convert + + Returns + ------- + :class:`SpectrumMatch` + """""" + self = cls(match.scan, match.target, match.score, mass_shift=match.mass_shift) + if hasattr(match, 'q_value'): + self.q_value = match.q_value + return self + + def clone(self): + """"""Create a shallow copy of this object + + Returns + ------- + :class:`SpectrumMatch` + """""" + return self.__class__( + self.scan, self.target, self.score, self.best_match, self.data_bundle, + self.q_value, self.id, self.mass_shift, self.localizations) + + def get_auxiliary_data(self): + return self.data_bundle + + +class ModelTreeNode(object): + def __init__(self, model, children=None): + if children is None: + children = {} + self.children = children + self.model = model + + def get_model_node_for(self, scan, target, *args, **kwargs): + for decider, model_node in self.children.items(): + if decider(scan, target, *args, **kwargs): + return model_node.get_model_node_for(scan, target, *args, **kwargs) + return self + + def evaluate(self, scan, target, *args, **kwargs): + node = self.get_model_node_for(scan, target, *args, **kwargs) + return node.model.evaluate(scan, target, *args, **kwargs) + + def __call__(self, scan, target, *args, **kwargs): + node = self.get_model_node_for(scan, target, *args, **kwargs) + return node.model(scan, target, *args, **kwargs) + + def load_peaks(self, scan): + return self.model.load_peaks(scan) + + +_ScoreSet = make_struct(""ScoreSet"", ['glycopeptide_score', 'peptide_score', 'glycan_score', 'glycan_coverage', + ""stub_glycopeptide_intensity_utilization"", + ""oxonium_ion_intensity_utilization"", + ""n_stub_glycopeptide_matches"", + ""peptide_coverage"", ""total_signal_utilization""]) + + +class ScoreSet(_ScoreSet): + __slots__ = () + packer = struct.Struct(""!ffffffffff"") + + glycopeptide_score: float + peptide_score: float + glycan_score: float + glycan_coverage: float + stub_glycopeptide_intensity_utilization: float + oxonium_ion_intensity_utilization: float + n_stub_glycopeptide_matches: float + peptide_coverag: float + total_signal_utilization: float + + def __len__(self): + return 4 + + def __lt__(self, other): + if self.glycopeptide_score < other.glycopeptide_score: + return True + elif abs(self.glycopeptide_score - other.glycopeptide_score) > 1e-3: + return False + + if self.peptide_score < other.peptide_score: + return True + elif abs(self.peptide_score - other.peptide_score) > 1e-3: + return False + + if self.glycan_score < other.glycan_score: + return True + elif abs(self.glycan_score - other.glycan_score) > 1e-3: + return False + + if self.glycan_coverage < other.glycan_coverage: + return True + return False + + def __gt__(self, other): + if self.glycopeptide_score > other.glycopeptide_score: + return True + elif abs(self.glycopeptide_score - other.glycopeptide_score) > 1e-3: + return False + + if self.peptide_score > other.peptide_score: + return True + elif abs(self.peptide_score - other.peptide_score) > 1e-3: + return False + + if self.glycan_score > other.glycan_score: + return True + elif abs(self.glycan_score - other.glycan_score) > 1e-3: + return False + + if self.glycan_coverage > other.glycan_coverage: + return True + return False + + @classmethod + def from_spectrum_matcher(cls, match): + # Outdated, see Cython implementation + return cls(match.score, match.peptide_score(), match.glycan_score(), match.glycan_coverage()) + + def pack(self): + return self.packer.pack(*self) + + @classmethod + def unpack(cls, binary): + return cls(*cls.packer.unpack(binary)) + + @classmethod + def field_names(cls): + return [ + ""total_score"", + ""peptide_score"", + ""glycan_score"", + ""glycan_coverage"", + ""stub_glycopeptide_intensity_utilization"", + ""oxonium_ion_intensity_utilization"", + ""n_stub_glycopeptide_matches"", + ""peptide_coverage"", + ""total_signal_utilization"", + ] + + def values(self): + return [ + self.glycopeptide_score, + self.peptide_score, + self.glycan_score, + self.glycan_coverage, + self.stub_glycopeptide_intensity_utilization, + self.oxonium_ion_intensity_utilization, + self.n_stub_glycopeptide_matches, + self.peptide_coverage, + self.total_signal_utilization + ] + + +class FDRSet(make_struct(""FDRSet"", ['total_q_value', 'peptide_q_value', 'glycan_q_value', 'glycopeptide_q_value'])): + __slots__ = () + packer = struct.Struct(""!ffff"") + + total_q_value: float + peptide_q_value: float + glycan_q_value: float + glycopeptide_q_value: float + + def pack(self): + return self.packer.pack(*self) + + @classmethod + def unpack(cls, binary): + return cls(*cls.packer.unpack(binary)) + + @classmethod + def default(cls): + return cls(1.0, 1.0, 1.0, 1.0) + + def __lt__(self, other): + if self.total_q_value < other.total_q_value: + return True + elif abs(self.total_q_value - other.total_q_value) > 1e-3: + return False + + if self.peptide_q_value < other.peptide_q_value: + return True + elif abs(self.peptide_q_value - other.peptide_q_value) > 1e-3: + return False + + if self.glycan_q_value < other.glycan_q_value: + return True + elif abs(self.glycan_q_value - other.glycan_q_value) > 1e-3: + return False + + if self.glycopeptide_q_value < other.glycopeptide_q_value: + return True + return False + + def __gt__(self, other): + if self.total_q_value > other.total_q_value: + return True + elif abs(self.total_q_value - other.total_q_value) > 1e-3: + return False + + if self.peptide_q_value > other.peptide_q_value: + return True + elif abs(self.peptide_q_value - other.peptide_q_value) > 1e-3: + return False + + if self.glycan_q_value > other.glycan_q_value: + return True + elif abs(self.glycan_q_value - other.glycan_q_value) > 1e-3: + return False + + if self.glycopeptide_q_value > other.glycopeptide_q_value: + return True + return False + + +try: + _PyScoreSet = ScoreSet + _PyFDRSet = FDRSet + from glycresoft._c.tandem.spectrum_match import ScoreSet, FDRSet + _has_c = True +except ImportError: + _has_c = False + + +class MultiScoreSpectrumMatch(SpectrumMatch): + __slots__ = ('score_set', 'match_type', '_q_value_set') + + score_set_type: ClassVar[Type] = ScoreSet + + def __init__(self, scan, target, score_set, best_match=False, data_bundle=None, + q_value_set=None, id=None, mass_shift=None, valid=True, match_type=None, + localizations=None, rank=0, cluster_id=None): + if q_value_set is None: + q_value_set = FDRSet.default() + else: + q_value_set = FDRSet(*q_value_set) + self._q_value_set = None + super(MultiScoreSpectrumMatch, self).__init__( + scan, target, score_set[0], best_match, data_bundle, q_value_set[0], + id, mass_shift, valid=valid, localizations=localizations, rank=rank, + cluster_id=cluster_id) + if isinstance(score_set, ScoreSet): + self.score_set = score_set + else: + self.score_set = self.score_set_type(*score_set) + self.q_value_set = q_value_set + self.match_type = SpectrumMatchClassification[match_type] + + def is_multiscore(self): + return True + + @property + def q_value_set(self): + return self._q_value_set + + @q_value_set.setter + def q_value_set(self, value): + self._q_value_set = value + self.q_value = self._q_value_set.total_q_value + + def clone(self): + """"""Create a shallow copy of this object + + Returns + ------- + :class:`SpectrumMatch` + """""" + return self.__class__( + self.scan, self.target, self.score_set, self.best_match, self.data_bundle, + self.q_value_set, self.id, self.mass_shift, self.valid, self.match_type, self.localizations, + self.rank, self.cluster_id) + + def __reduce__(self): + return self.__class__, (self.scan, self.target, self.score_set, self.best_match, + self.data_bundle, self.q_value_set, self.id, self.mass_shift, + self.valid, self.match_type.value, self.localizations, self.rank, + self.cluster_id) + + def pack(self): + return (self.target.id, self.score_set.pack(), int(self.best_match), + self.mass_shift.name, self.match_type.value) + + @classmethod + def from_match_solution(cls, match: SpectrumMatcherBase) -> 'MultiScoreSpectrumMatch': + try: + + self = cls( + match.scan, + match.target, + match.get_score_set_type().from_spectrum_matcher(match), + mass_shift=match.mass_shift + ) + if hasattr(match, 'q_value_set'): + self.q_value_set = match.q_value_set + return self + except AttributeError: + if isinstance(match, MultiScoreSpectrumMatch): + return match + else: + raise + + +class LocalizationScore(object): + __slots__ = (""position"", ""modification"", ""score"") + + position: int + modification: str + score: float + + def __init__(self, position: int, modification: str, score: float): + if isinstance(modification, (glycopeptidepy.Modification, glycopeptidepy.ModificationRule)): + modification = modification.name + elif not isinstance(modification, str): + modification = str(modification) + + self.position = position + self.modification = modification + self.score = score + + def __reduce__(self): + return self.__class__, (self.position, self.modification, self.score) + + def copy(self): + return self.__class__(self.position, self.modification, self.score) + + def __repr__(self): + return f""{self.__class__.__name__}({self.position}, {self.modification}, {self.score})"" + + def __str__(self): + return f""{self.modification}:{self.position}:{self.score}"" + + @classmethod + def parse(cls, text: str): + mod, pos, score = text.rsplit("":"", 2) + pos = int(pos) + score = float(score) + return cls(pos, mod, score) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/spectrum_match/__init__.py",".py","1235","40","from .spectrum_match import ( + SpectrumMatchBase, SpectrumMatcherBase, ScanWrapperBase, + SpectrumMatch, + ModelTreeNode, + Unmodified, TargetReference, SpectrumReference, + neutron_offset, MultiScoreSpectrumMatch, ScoreSet, + FDRSet, LocalizationScore, + SpectrumMatchClassification) + +from .solution_set import ( + SpectrumSolutionSet, SpectrumMatchRetentionStrategyBase, MinimumScoreRetentionStrategy, + MaximumSolutionCountRetentionStrategy, TopScoringSolutionsRetentionStrategy, + SpectrumMatchRetentionMethod, default_selection_method, MultiScoreSpectrumSolutionSet) + + +__all__ = [ + ""SpectrumMatchBase"", + ""SpectrumMatcherBase"", + ""ScanWrapperBase"", + ""SpectrumMatch"", + ""ModelTreeNode"", + ""Unmodified"", + ""TargetReference"", + ""SpectrumReference"", + ""neutron_offset"", + ""SpectrumSolutionSet"", + ""SpectrumMatchRetentionStrategyBase"", + ""MinimumScoreRetentionStrategy"", + ""MaximumSolutionCountRetentionStrategy"", + ""TopScoringSolutionsRetentionStrategy"", + ""SpectrumMatchRetentionMethod"", + ""default_selection_method"", + 'ScoreSet', + 'FDRSet', + 'LocalizationScore', + 'MultiScoreSpectrumMatch', + 'MultiScoreSpectrumSolutionSet', + 'SpectrumMatchClassification', +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/evaluation_dispatch/task.py",".py","10072","265","import os + +from typing import Any, Hashable, List, Mapping, Tuple, Optional, TypedDict, Union, Deque + +from glycresoft.task import TaskBase +from glycresoft.chromatogram_tree.mass_shift import MassShift + + +debug_mode = bool(os.environ.get(""GLYCRESOFTDEBUG"")) + +HitID = Hashable +GroupID = Hashable +DBHit = Any +WorkItem = Tuple[DBHit, List[Tuple[str, MassShift]]] + + +class WorkItemGroup(TypedDict): + work_orders: Mapping[HitID, WorkItem] + + +class StructureSpectrumSpecificationBuilder(object): + """"""Base class for building structure hit by spectrum specification + """""" + + def build_work_order(self, hit_id: HitID, hit_map: Mapping[HitID, DBHit], + scan_hit_type_map: Mapping[Tuple[str, HitID], MassShift], + hit_to_scan: Mapping[HitID, List[str]]) -> WorkItem: + """"""Packs several task-defining data structures into a simple to unpack payload for + sending over IPC to worker processes. + + Parameters + ---------- + hit_id : int + The id number of a hit structure + hit_map : dict + Maps hit_id to hit structure + hit_to_scan : dict + Maps hit id to list of scan ids + scan_hit_type_map : dict + Maps (scan id, hit id) to the type of mass shift + applied for this match + + Returns + ------- + tuple + Packaged message payload + """""" + return (hit_map[hit_id], + [(s, scan_hit_type_map[s, hit_id]) + for s in hit_to_scan[hit_id]]) + + +class TaskSourceBase(StructureSpectrumSpecificationBuilder, TaskBase): + """"""A base class for building a stream of work items through + :class:`StructureSpectrumSpecificationBuilder`. + """""" + + batch_size = 10000 + + def add(self, item: Union[WorkItem, WorkItemGroup]): + """"""Add ``item`` to the work stream + + Parameters + ---------- + item : object + The work item to deal + """""" + raise NotImplementedError() + + def join(self): + """"""Checkpoint that may halt the stream generation. + """""" + return + + def feed(self, hit_map: Mapping[HitID, str], + hit_to_scan: Mapping[HitID, List[str]], + scan_hit_type_map: Mapping[Tuple[str, HitID], MassShift]): + """"""Push tasks onto the input queue feeding the worker + processes. + + Parameters + ---------- + hit_map : dict + Maps hit id to structure + hit_to_scan : dict + Maps hit id to list of scan ids + scan_hit_type_map : dict + Maps (hit id, scan id) to the type of mass shift + applied for this match + """""" + i = 0 + n = len(hit_to_scan) + seen = dict() + log_interval = 10000 + for hit_id, scan_ids in hit_to_scan.items(): + i += 1 + hit = hit_map[hit_id] + # This sanity checking is likely unnecessary, and is a hold-over from + # debugging redundancy in the result queue. For the moment, it is retained + # to catch ""new"" bugs. + # If a hit structure's id doesn't match the id it was looked up with, something + # may be wrong with the upstream process. Log this event. + if hit.id != hit_id: + self.log(""Hit %r doesn't match its id %r"" % (hit, hit_id)) + if hit_to_scan[hit.id] != scan_ids: + self.log(""Mismatch leads to different scans! (%d, %d)"" % ( + len(scan_ids), len(hit_to_scan[hit.id]))) + # If a hit structure has been seen multiple times independent of whether or + # not the expected hit id matches, something may be wrong in the upstream process. + # Log this event. + if hit.id in seen: + self.log(""Hit %r already dealt under hit_id %r, now again at %r"" % ( + hit, seen[hit.id], hit_id)) + raise ValueError( + ""Hit %r already dealt under hit_id %r, now again at %r"" % ( + hit, seen[hit.id], hit_id)) + seen[hit.id] = hit_id + if i % self.batch_size == 0 and i: + self.join() + try: + work_order = self.build_work_order(hit_id, hit_map, scan_hit_type_map, hit_to_scan) + # if debug_mode: + # self.log(""...... Matching %s against %r"" % work_order) + self.add(work_order) + # Set a long progress update interval because the feeding step is less + # important than the processing step. Additionally, as the two threads + # run concurrently, the feeding thread can log a short interval before + # the entire process has formally logged that it has started. + if i % log_interval == 0: + self.log(""...... Dealt %d work items (%0.2f%% Complete)"" % (i, i * 100.0 / n)) + except Exception as e: + self.log(""An exception occurred while feeding %r and %d scan ids: %r"" % (hit_id, len(scan_ids), e)) + if i > log_interval: + self.log(""...... Finished dealing %d work items"" % (i,)) + self.join() + return + + def feed_groups(self, hit_map: Mapping[HitID, DBHit], + hit_to_scan: Mapping[HitID, List[str]], + scan_hit_type_map: Mapping[Tuple[HitID, str], MassShift], + hit_to_group: Mapping[HitID, GroupID]): + """"""Push task groups onto the input queue feeding the worker + processes. + + Parameters + ---------- + hit_map : dict + Maps hit id to structure + hit_to_scan : dict + Maps hit id to list of scan ids + scan_hit_type_map : dict + Maps (hit id, scan id) to the type of mass shift + applied for this match + hit_to_group: dict + Maps group id to the set of hit ids which are + """""" + i = 0 + j = 0 + seen = dict() + for group_key, hit_keys in hit_to_group.items(): + hit_group: WorkItemGroup = { + ""work_orders"": {} + } + i += 1 + for hit_id in hit_keys: + j += 1 + scan_ids = hit_to_scan[hit_id] + hit = hit_map[hit_id] + # This sanity checking is likely unnecessary, and is a hold-over from + # debugging redundancy in the result queue. For the moment, it is retained + # to catch ""new"" bugs. + # If a hit structure's id doesn't match the id it was looked up with, something + # may be wrong with the upstream process. Log this event. + if hit.id != hit_id: + self.log(""Hit %r doesn't match its id %r"" % (hit, hit_id)) + if hit_to_scan[hit.id] != scan_ids: + self.log(""Mismatch leads to different scans! (%d, %d)"" % ( + len(scan_ids), len(hit_to_scan[hit.id]))) + # If a hit structure has been seen multiple times independent of whether or + # not the expected hit id matches, something may be wrong in the upstream process. + # Log this event. + if hit.id in seen: + self.log(""Hit %r already dealt under hit_id %r, now again at %r in group %r"" % ( + hit, seen[hit.id], hit_id, group_key)) + raise ValueError( + ""Hit %r already dealt under hit_id %r, now again at %r"" % ( + hit, seen[hit.id], hit_id)) + seen[hit.id] = (hit_id, group_key) + work_order = self.build_work_order( + hit_id, hit_map, scan_hit_type_map, hit_to_scan) + hit_group['work_orders'][hit_id] = work_order + self.add(hit_group) + if i % self.batch_size == 0 and i: + self.join() + self.join() + return + + def __call__(self, hit_map: Mapping[HitID, Any], + hit_to_scan: Mapping[HitID, List[str]], + scan_hit_type_map: Mapping[Tuple[HitID, str], MassShift], + hit_to_group: Optional[Mapping[HitID, Any]]=None): + if not hit_to_group: + return self.feed(hit_map, hit_to_scan, scan_hit_type_map) + else: + return self.feed_groups(hit_map, hit_to_scan, scan_hit_type_map, hit_to_group) + + +class TaskDeque(TaskSourceBase): + """"""Generate an on-memory buffer of work items + + Attributes + ---------- + queue : :class:`~.deque` + The in-memory work queue + """""" + + queue: Deque[Union[WorkItem, WorkItemGroup]] + + def __init__(self): + self.queue = Deque() + + def add(self, item: Union[WorkItemGroup, WorkItem]): + self.queue.append(item) + + def pop(self): + return self.queue.popleft() + + def __iter__(self): + return iter(self.queue) + + +class TaskQueueFeeder(TaskSourceBase): + def __init__(self, input_queue, done_event): + self.input_queue = input_queue + self.done_event = done_event + + def add(self, item): + self.input_queue.put(item) + + def join(self): + return self.input_queue.join() + + def feed(self, hit_map, hit_to_scan, scan_hit_type_map): + """"""Push tasks onto the input queue feeding the worker + processes. + + Parameters + ---------- + hit_map : dict + Maps hit id to structure + hit_to_scan : dict + Maps hit id to list of scan ids + scan_hit_type_map : dict + Maps (hit id, scan id) to the type of mass shift + applied for this match + """""" + super(TaskQueueFeeder, self).feed(hit_map, hit_to_scan, scan_hit_type_map) + self.done_event.set() + return + + def feed_groups(self, hit_map, hit_to_scan, scan_hit_type_map, hit_to_group): + super(TaskQueueFeeder, self).feed_groups(hit_map, hit_to_scan, scan_hit_type_map, hit_to_group) + self.done_event.set() + return +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/evaluation_dispatch/__init__.py",".py","486","17","from .evaluation import ( + SpectrumEvaluatorBase, LocalSpectrumEvaluator, + SequentialIdentificationProcessor, SolutionHandler, + SolutionPacker, MultiScoreSolutionHandler, + MultiScoreSolutionPacker) + +from .task import ( + StructureSpectrumSpecificationBuilder, + TaskSourceBase, TaskDeque, TaskQueueFeeder) + +from .utils import ( + SentinelToken, ProcessDispatcherState) + +from .process import ( + IdentificationProcessDispatcher, + SpectrumIdentificationWorkerBase) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/evaluation_dispatch/utils.py",".py","804","36","from glypy.utils import Enum + + +class SentinelToken(object): + """"""An object to hold opaque identity information regarding a worker process, + to be used to signal that a worker process has received a signal + + Attributes + ---------- + token : object + The opaque identity + """""" + + def __init__(self, token): + self.token = token + + def __hash__(self): + return hash(self.token) + + def __eq__(self, other): + return self.token == other.token + + def __repr__(self): + return ""{self.__class__.__name__}({self.token})"".format(self=self) + + +class ProcessDispatcherState(Enum): + start = 1 + spawning = 2 + running = 3 + running_local_workers_live = 4 + running_local_workers_dead = 5 + terminating = 6 + terminating_workers_live = 7 + done = 8 +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/evaluation_dispatch/process.py",".py","29424","727","import os +import time +import traceback +from typing import Any, List, Mapping, Tuple, Type + + +try: + import cPickle as pickle +except ImportError: + import pickle + +from collections import deque +from threading import Thread + +import multiprocessing +from multiprocessing import Process, Event, Manager, JoinableQueue +from multiprocessing.managers import RemoteError + +try: + from Queue import Empty as QueueEmptyException +except ImportError: + from queue import Empty as QueueEmptyException + +from glypy.utils import uid + +from ms_deisotope.data_source import ProcessedScan + +from glycresoft.task import TaskBase +from glycresoft.chromatogram_tree import Unmodified, MassShift +from glycresoft.structure import LRUMapping + +from .evaluation import SolutionHandler, LocalSpectrumEvaluator, SpectrumEvaluatorBase +from .task import TaskQueueFeeder, DBHit, HitID, GroupID +from .utils import SentinelToken, ProcessDispatcherState + + +debug_mode = bool(os.environ.get(""GLYCRESOFTDEBUG"")) + + +class IdentificationProcessDispatcher(TaskBase): + """"""Orchestrates distributing the spectrum match evaluation + task across several processes. + + The distribution pushes individual structures (""targets"") and + the scan ids they mapped to in the MSn dimension to each worker. + + All scans in the batch being worked on are made available over + an IPC synchronized dictionary. + + Attributes + ---------- + done_event : multiprocessing.Event + An Event indicating that all work items + have been placed on `input_queue` + evaluation_args : dict + A dictionary containing arguments to be + passed through to `evaluate` on the worker + processes. + init_args : dict + A dictionary containing extra arguments + to use when initializing worker process + instances. + input_queue : multiprocessing.Queue + The queue from which worker processes + will read their targets and scan id mappings + ipc_manager : multiprocessing.SyncManager + Provider of IPC dictionary synchronization + log_controller : MessageSpooler + Logging facility to funnel messages from workers + through into the main process's log stream + n_processes : int + The number of worker processes to spawn + output_queue : multiprocessing.Queue + The queue which worker processes will + put ther results on, read in the main + process. + scan_load_map : multiprocessing.SyncManager.dict + An inter-process synchronized dictionary which + maps scan ids to scans. Used by worker processes + to request individual scans by name when they are + not found locally. + scan_solution_map : defaultdict(list) + A mapping from scan id to all candidate solutions. + scorer_type : SpectrumMatcherBase + The type used by workers to evaluate spectrum matches + worker_type : SpectrumIdentificationWorkerBase + The type instantiated to construct worker processes + workers : list + Container for created workers. + """""" + + solution_handler: SolutionHandler + state: ProcessDispatcherState + worker_type: Type['SpectrumIdentificationWorkerBase'] + + input_queue: JoinableQueue + output_queue: JoinableQueue + + producer_thread_done_event: Event + + + post_search_trailing_timeout = 1.5e2 + child_failure_timeout = 2.5e2 + + def __init__(self, worker_type, scorer_type, evaluation_args=None, init_args=None, + mass_shift_map=None, n_processes=3, ipc_manager=None, solution_handler_type=None): + if solution_handler_type is None: + solution_handler_type = SolutionHandler + if ipc_manager is None: + self.log(""Creating IPC Manager. Prefer to pass a reusable IPC Manager instead."") + ipc_manager = Manager() + if evaluation_args is None: + evaluation_args = dict() + if mass_shift_map is None: + mass_shift_map = { + Unmodified.name: Unmodified + } + + self.state = ProcessDispatcherState.start + self.ipc_manager = ipc_manager + self.worker_type = worker_type + self.scorer_type = scorer_type + self.n_processes = n_processes + + self.producer_thread_done_event = self.ipc_manager.Event() + self.consumer_done_event = self.ipc_manager.Event() + + self.input_queue = self._make_input_queue() + self.output_queue = self._make_output_queue() + + self.feeder = TaskQueueFeeder(self.input_queue, self.producer_thread_done_event) + + self.solution_handler = solution_handler_type({}, {}, mass_shift_map) + + self.evaluation_args = evaluation_args + self.init_args = init_args + self.workers = [] + self.log_controller = self.ipc_logger() + self.local_scan_map = dict() + self.scan_load_map = self.ipc_manager.dict() + self.local_mass_shift_map = mass_shift_map + self.mass_shift_load_map = self.ipc_manager.dict(mass_shift_map) + self.structure_map = dict() + self._token_to_worker = {} + self._has_received_token = set() + self._has_remote_error = False + self._result_buffer = deque() + + @property + def scan_solution_map(self): + return self.solution_handler.scan_solution_map + + def _make_input_queue(self): + try: + return JoinableQueue(int(1e5)) + except (OSError, ValueError): + return JoinableQueue() + + def _make_output_queue(self): + try: + return JoinableQueue(int(1e7)) + except (OSError, ValueError): + return JoinableQueue() + + def clear_pool(self): + """"""Tear down spawned worker processes and clear + the shared memory server + """""" + self.scan_load_map.clear() + self.local_scan_map.clear() + if self.state in (ProcessDispatcherState.running, ProcessDispatcherState.running_local_workers_dead): + self.state = ProcessDispatcherState.terminating + elif self.state == ProcessDispatcherState.running_local_workers_live: + self.state = ProcessDispatcherState.terminating_workers_live + else: + self.state = ProcessDispatcherState.terminating + for _i, worker in enumerate(self.workers): + exitcode = worker.exitcode + if exitcode != 0 and exitcode is not None: + self.log(""... Worker Process %r had exitcode %r"" % (worker, exitcode)) + try: + worker.join(1) + except AttributeError: + pass + if worker.is_alive() and worker.token not in self._has_received_token: + self.debug(""... Worker Process %r is still alive and incomplete"" % (worker, )) + worker.terminate() + + def create_pool(self, scan_map): + """"""Spawn a pool of workers and a supporting process + for sharing scans from ``scan_map`` by id with the workers + so they can load scans on demand. + + Parameters + ---------- + scan_map : dict + Map scan id to :class:`.ProcessedScan` object + """""" + self.state = ProcessDispatcherState.spawning + self.scan_load_map.clear() + # Do not copy the complete scan object into the IPC manager dict, as this will + # pickle the scan source, and then unpickle it several times on the recieving end. + self.scan_load_map.update({k: pickle.dumps(v.copy(deep=False).unbind(), -1) for k, v in scan_map.items()}) + self.local_scan_map.clear() + self.local_scan_map.update(scan_map) + + self.input_queue = self._make_input_queue() + self.output_queue = self._make_output_queue() + self.feeder = TaskQueueFeeder(self.input_queue, self.producer_thread_done_event) + + for _i in range(self.n_processes): + worker = self.worker_type( + input_queue=self.input_queue, + output_queue=self.output_queue, + producer_done_event=self.producer_thread_done_event, + consumer_done_event=self.consumer_done_event, + scorer_type=self.scorer_type, + evaluation_args=self.evaluation_args, + spectrum_map=self.scan_load_map, + mass_shift_map=self.mass_shift_load_map, + log_handler=self.log_controller.sender(), + solution_packer=self.solution_handler.packer, + **self.init_args) + worker._work_complete = self.ipc_manager.Event() + worker.start() + self._token_to_worker[worker.token] = worker + self.workers.append(worker) + + def all_workers_finished(self): + """"""Check if all worker processes have finished. + """""" + worker_still_busy = False + i = 0 + j = 0 + for worker in self.workers: + i += 1 + try: + is_done = worker.all_work_done() + j += is_done + if not is_done: + worker_still_busy = True + return worker_still_busy + except (RemoteError, KeyError): + worker_still_busy = True + self._has_remote_error = True + self.log(""... All Workers Done: %r (%d/%d), Error? %r"" % (not worker_still_busy, j, i, self._has_remote_error)) + return not worker_still_busy + + def build_work_order(self, hit_id: HitID, hit_map: Mapping[HitID, DBHit], + scan_hit_type_map: Mapping[Tuple[str, HitID], MassShift], + hit_to_scan: Mapping[HitID, List[str]]): + """"""Packs several task-defining data structures into a simple to unpack payload for + sending over IPC to worker processes. + + Parameters + ---------- + hit_id : int + The id number of a hit structure + hit_map : dict + Maps hit_id to hit structure + hit_to_scan : dict + Maps hit id to list of scan ids + scan_hit_type_map : dict + Maps (hit id, scan id) to the type of mass shift + applied for this match + + Returns + ------- + tuple + Packaged message payload + """""" + return self.feeder.build_work_order(hit_id, hit_map, scan_hit_type_map, hit_to_scan) + + def spawn_queue_feeder(self, hit_map, hit_to_scan, scan_hit_type_map, hit_to_group=None): + """"""Create a thread to run :meth:`feeder` with the provided arguments + so that work can be sent in tandem with waiting for results + + Parameters + ---------- + hit_map : dict + Maps hit id to structure + hit_to_scan : dict + Maps hit id to list of scan ids + scan_hit_type_map : dict + Maps (hit id, scan id) to the type of mass shift + applied for this match + hit_to_group: dict, optional + Maps group id to the set of hit ids which are + Returns + ------- + Thread + """""" + feeder_thread = Thread( + target=self.feeder, args=(hit_map, hit_to_scan, scan_hit_type_map, hit_to_group)) + feeder_thread.daemon = True + feeder_thread.start() + return feeder_thread + + def store_result(self, target, score_map): + """"""Save the spectrum match scores for ``target`` against the + set of matched scans + + Parameters + ---------- + target : object + The structure that was matched + score_map : dict + Maps (scan id, mass shift name) to score + scan_map : dict + Maps scan id to :class:`.ProcessedScan` + """""" + self.solution_handler(target, score_map) + + def _reconstruct_missing_work_items(self, seen, hit_map, hit_to_scan, scan_hit_type_map): + """"""Handle task items that are pending after it is believed that the workers + have crashed or the network communication has failed. + + Parameters + ---------- + seen : dict + Map of hit ids that have already been handled + hit_map : dict + Maps hit_id to hit structure + hit_to_scan : dict + Maps hit id to list of scan ids + scan_hit_type_map : dict + Maps (hit id, scan id) to the type of mass shift + applied for this match + """""" + missing = set(hit_to_scan) - set(seen) + i = 0 + n = len(missing) + evaluator = LocalSpectrumEvaluator( + self.workers[0], self.local_scan_map, self.local_mass_shift_map, + self.solution_handler.packer) + for missing_id in missing: + target, scan_spec = self.build_work_order(missing_id, hit_map, scan_hit_type_map, hit_to_scan) + try: + # Change this to be the target's ID and look it up in hit_map + target_id, score_map = evaluator.handle_item(target, scan_spec) + target = hit_map.get(target_id, target_id) + seen[target.id] = (-1, 0) + self.store_result(target, score_map) + i += 1 + if i % 1000 == 0: + self.log(""...... Processed %d local matches (%0.2f%%)"" % (i, i * 100. / n)) + except Exception as err: + self.error(""...... An error occurred while processing %r: %r"" % (target, err), exception=err) + raise + return i + + def get_result(self, seen, hit_map): + if self._result_buffer: + return self._result_buffer.popleft() + + payload = self.output_queue.get(True, 1) + self.output_queue.task_done() + + # Change this to be the target's ID and look it up in hit_map + if isinstance(payload, SentinelToken): + self.debug(""...... Received sentinel from %s"" % + (self._token_to_worker[payload.token].name)) + self._has_received_token.add(payload.token) + else: + self._result_buffer.extend(payload) + if self._result_buffer: + return self._result_buffer.popleft() + + def process(self, scan_map: Mapping[str, ProcessedScan], + hit_map: Mapping[HitID, DBHit], + hit_to_scan: Mapping[HitID, List[str]], + scan_hit_type_map: Mapping[Tuple[str, HitID], MassShift], + hit_group_map: Mapping[GroupID, List[HitID]]=None) -> Mapping[str, List]: + """"""Evaluate all spectrum matches, spreading work among the worker + process pool. + + Parameters + ---------- + scan_map : :class:`dict` + Mapping from :attr:`~.ScanBase.id` to :class:`~.ScanBase` instance + hit_map : :class:`dict` + Mapping from `structure.id` to the structure type to matche against + hit_to_scan : :class:`dict` + Mapping from `structure.id` to a list of :attr:`~.ScanBase.id` which + it has a precursor mass match. + scan_hit_type_map : :class:`dict` + Mapping from (:attr:`~.ScanBase.id`, `structure.id`) to :class:`MassShiftBase` + hit_group_map : :class:`dict`, optional + An additional :class:`dict` that maps abstract group ids to sets of hit ids + in `hit_map` which all share information that can be computed once and shared + between all members of the group. + """""" + self.structure_map = hit_map + self.solution_handler.scan_map = scan_map + self.create_pool(scan_map) + + # Won't feed hit groups until after more work is done here. + feeder_thread = self.spawn_queue_feeder( + hit_map, hit_to_scan, scan_hit_type_map, hit_group_map) + has_work = True + i = 0 + scan_count = len(scan_map) + n = len(hit_to_scan) + if n != len(hit_map): + self.log(""There is a mismatch between hit_map (%d) and hit_to_scan (%d)"" % ( + len(hit_map), n)) + n_spectrum_matches = sum(map(len, hit_to_scan.values())) + # Track the iteration number a particular structure (id) has been received + # on. This may be used to detect if a structure has been received multiple + # times, and to determine when all expected structures have been received. + seen = dict() + # Keep a running tally of the number of iterations when there are pending + # structure matches to process, but all workers claim to be done. + strikes = 0 + self.state = ProcessDispatcherState.running + self.log(""... Searching Matches (%d)"" % (n_spectrum_matches,)) + last_log_time = start_time = time.time() + should_log = False + log_cycle = 5000 + while has_work: + try: + payload = self.get_result(seen, hit_map) + if payload is None: + continue + else: + (target_id, score_map, token) = payload + target = hit_map.get(target_id, target_id) + if target.id in seen: + self.log( + ""...... Duplicate Results For %s. First seen at %r, now again at %r"" % ( + target, seen[target.id], (i, token))) + else: + seen[target.id] = (i, token) + if (i > n) and ((i - n) % 10 == 0): + self.log( + ""...... Warning: %d additional output received. %s and %d matches."" % ( + i - n, target, len(score_map))) + + i += 1 + strikes = 0 + if i % log_cycle == 0 or should_log: + last_log_time = time.time() + should_log = False + self.log( + ""...... Processed %d structures (%0.2f%%)"" % (i, i * 100. / n)) + self.store_result(target, score_map) + except QueueEmptyException: + if len(seen) == n: + has_work = False + # do worker life cycle management here + elif self.all_workers_finished(): + if len(seen) == n: + has_work = False + else: + strikes += 1 + if strikes % 50 == 0: + self.log( + ""...... %d cycles without output (%d/%d, %0.2f%% Done)"" % ( + strikes, len(seen), n, len(seen) * 100. / n)) + if strikes > self.post_search_trailing_timeout: + self.state = ProcessDispatcherState.running_local_workers_dead + self.log( + ""...... Too much time has elapsed with"" + "" missing items. Evaluating serially."") + i += self._reconstruct_missing_work_items( + seen, hit_map, hit_to_scan, scan_hit_type_map) + has_work = False + self.debug(""...... Processes"") + for worker in self.workers: + self.debug(""......... %r"" % (worker,)) + self.debug(""...... IPC Manager: %r"" % (self.ipc_manager,)) + else: + strikes += 1 + if strikes % 10 == 0: + check_time = time.time() + if check_time - last_log_time > 10: + should_log = True + if strikes % 50 == 0: + self.log( + ""...... %d cycles without output (%d/%d, %0.2f%% Done, %d children still alive)"" % ( + strikes, len(seen), n, len(seen) * 100. / n, + len(multiprocessing.active_children()) - 1)) + try: + input_queue_size = self.input_queue.qsize() + except Exception: + input_queue_size = -1 + is_feeder_done = self.producer_thread_done_event.is_set() + self.log(""...... Input Queue Status: %r. Is Feeder Done? %r"" % ( + input_queue_size, is_feeder_done)) + if strikes > (self.child_failure_timeout * (1 + (scan_count / 500.0) * ( + not self._has_remote_error))): + self.state = ProcessDispatcherState.running_local_workers_live + self.log( + (""...... Too much time has elapsed with"" + "" missing items (%d children still alive). Evaluating serially."") % ( + len(multiprocessing.active_children()) - 1,)) + i += self._reconstruct_missing_work_items( + seen, hit_map, hit_to_scan, scan_hit_type_map) + has_work = False + self.debug(""...... Processes"") + for worker in self.workers: + self.debug(""......... %r"" % (worker,)) + self.debug(""...... IPC Manager: %r"" % (self.ipc_manager,)) + continue + + consumer_end = time.time() + self.debug(""... Consumer Done (%0.3g sec.)"" % (consumer_end - start_time)) + self.consumer_done_event.set() + time.sleep(1) # Not a good solution but need to give workers a chance to sync + i_spectrum_matches = sum(map(len, self.scan_solution_map.values())) + self.log(""... Finished Processing Matches (%d)"" % (i_spectrum_matches,)) + self.clear_pool() + self.debug(""... Shutting Down Message Queue"") + self.log_controller.stop() + self.debug(""... Joining Feeder Thread (Done: %r)"" % (self.producer_thread_done_event.is_set(), )) + feeder_thread.join() + dispatcher_end = time.time() + self.log(""... Dispatcher Finished (%0.3g sec.)"" % (dispatcher_end - start_time)) + return self.scan_solution_map + + +class SpectrumIdentificationWorkerBase(Process, SpectrumEvaluatorBase): + verbose = False + + def __init__(self, input_queue, output_queue, producer_done_event, consumer_done_event, + scorer_type, evaluation_args, spectrum_map, mass_shift_map, log_handler, + solution_packer): + Process.__init__(self) + if evaluation_args is None: + evaluation_args = dict() + self.daemon = True + self.input_queue = input_queue + self.output_queue = output_queue + self.producer_done_event = producer_done_event + self.consumer_done_event = consumer_done_event + self.scorer_type = scorer_type + self.evaluation_args = evaluation_args + + self.solution_packer = solution_packer + + self.spectrum_map = spectrum_map + self.mass_shift_map = mass_shift_map + + self.local_scan_map = LRUMapping(1000) + self.local_mass_shift_map = dict({ + Unmodified.name: Unmodified + }) + self.solution_map = dict() + self._work_complete = Event() + self._work_complete.clear() + self.log_handler = log_handler + self.token = uid() + self.items_handled = 0 + self.result_buffer = [] + self.buffer_size = 1000 + self.last_sent_result = time.time() + + def log(self, message): + """"""Send a normal logging message via :attr:`log_handler` + + Parameters + ---------- + message : str + The message to log + """""" + if self.log_handler is not None: + self.log_handler(message) + + def debug(self, message): + """"""Send a debugging message via :attr:`log_handler` + + Parameters + ---------- + message : str + The message to log + """""" + if self.verbose: + self.log_handler(""DEBUG::%s"" % message) + + def fetch_scan(self, key): + try: + return self.local_scan_map[key] + except KeyError: + serialized_scan = self.spectrum_map[key] + scan = pickle.loads(serialized_scan) + self.local_scan_map[key] = scan + return scan + + def fetch_mass_shift(self, key): + try: + return self.local_mass_shift_map[key] + except KeyError: + mass_shift = self.mass_shift_map[key] + self.local_mass_shift_map[key] = mass_shift + return mass_shift + + def all_work_done(self): + """"""A helper method to encapsulate :attr:`_work_complete`'s ``is_set`` + method. + + Returns + ------- + bool + """""" + return self._work_complete.is_set() + + def _append_to_result_buffer(self, payload): + self.result_buffer.append(payload) + if len(self.result_buffer) > self.buffer_size: + self._flush_result_buffer() + + def _flush_result_buffer(self): + if self.result_buffer: + self.output_queue.put(self.result_buffer) + self.result_buffer = [] + self.last_sent_result = time.time() + + def pack_output(self, target): + """"""Transmit the completed identifications for a given target + structure. + + Rather than returning these values directly, this implementation uses + the output queue to send the target and its scores along an IPC queue. + + Parameters + ---------- + target : object + The structure being identified. + """""" + if self.solution_map: + target_id = getattr(target, 'id', target) + self._append_to_result_buffer((target_id, self.solution_map, self.token)) + self.solution_map = dict() + + def evaluate(self, scan, structure, evaluation_context=None, *args, **kwargs): + raise NotImplementedError() + + def cleanup(self): + """"""Send signals indicating the worker process is finished and do any + final shared resource cleanup needed on the worker's side. + + This will set the :attr:`_work_complete` event and join :attr:`output_queue` + """""" + self.debug(""... Process %s Setting Work Complete Flag. Processed %d structures"" % ( + self.name, self.items_handled)) + try: + self._work_complete.set() + except (RemoteError, KeyError): + self.log(""An error occurred while cleaning up worker %r"" % (self, )) + self._flush_result_buffer() + self.output_queue.put(SentinelToken(self.token)) + self.consumer_done_event.wait() + # joining the queue may not be necessary if we depend upon consumer_event_done + self.debug(""... Process %s Queue Joining"" % (self.name,)) + self.output_queue.join() + self.debug(""... Process %s Finished"" % (self.name,)) + + def before_task(self): + '''A method to be overriden by subclasses that want to do something before + starting the task loop. + ''' + pass + + def task(self): + """"""The worker process's main loop where it will poll for new work items, + process incoming work items and send them back to the master process. + """""" + has_work = True + self.items_handled = 0 + strikes = 0 + while has_work: + try: + payload = self.input_queue.get(True, 5) + self.input_queue.task_done() + strikes = 0 + except QueueEmptyException: + if self.producer_done_event.is_set(): + has_work = False + break + else: + strikes += 1 + self._flush_result_buffer() + if strikes % 1000 == 0: + self.log(""... %d iterations without work for %r"" % (strikes, self)) + continue + if self.items_handled % 100 == 0: + if time.time() - self.last_sent_result > 60: + self._flush_result_buffer() + # Handling a group of work items + if isinstance(payload, dict): + work_order = payload + self.items_handled += 1 + try: + self.handle_group(work_order) + except Exception: + message = ""An error occurred while processing %r on %r:\n%s"" % ( + work_order, self, traceback.format_exc()) + self.log(message) + break + else: # Handling a single work item + structure, scan_ids = payload + self.items_handled += 1 + try: + self.handle_item(structure, scan_ids) + except Exception: + message = ""An error occurred while processing %r on %r:\n%s"" % ( + structure, self, traceback.format_exc()) + self.log(message) + break + self.cleanup() + + def run(self): + new_name = getattr(self, 'process_name', None) + if new_name is not None: + TaskBase().try_set_process_name(new_name) + try: + self.before_task() + except Exception: + self.log(""An exception occurred during before_task for %r.\n%s"" % ( + self, traceback.format_exc())) + try: + self.task() + except Exception: + self.log(""An exception occurred while executing %r.\n%s"" % ( + self, traceback.format_exc())) + self.cleanup() +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/evaluation_dispatch/evaluation.py",".py","14146","380","'''Types for managing the evaluation of spectrum matches, to +describe matches in bulk for serialization. +''' +import time +from collections import defaultdict + +from typing import List, Mapping, Tuple, Any, Type + +from ms_deisotope.data_source import ProcessedScan + +from glycresoft.task import TaskBase + +from glycresoft.chromatogram_tree import MassShift + +from ..spectrum_match import SpectrumMatch, MultiScoreSpectrumMatch, ScoreSet +from .task import TaskDeque + + +class SpectrumEvaluatorBase(object): + """"""Abstract base class for abstracting away how spectrum matches are + set up. + + Attributes + ---------- + scan_map: Mapping + A mapping from scan id to :class:`~.ProcessedScan` + mass_shift_map: Mapping + A mapping from mass shift name to :class:`~.MassShift` + solution_map: Mapping + A mapping from (scan id, mass shift name) to the packaged match. + """""" + scan_map: Mapping[str, ProcessedScan] + mass_shift_map: Mapping[str, MassShift] + solution_map: Mapping[Tuple[str, str], Any] + + def fetch_scan(self, key): + return self.scan_map[key] + + def fetch_mass_shift(self, key): + return self.mass_shift_map[key] + + def create_evaluation_context(self, group): + return None + + def evaluate(self, scan: ProcessedScan, structure, + evaluation_context=None, *args, **kwargs): + """"""Evaluate the match between ``structure`` and ``scan`` + + Parameters + ---------- + scan : ms_deisotope.ProcessedScan + MSn scan to match against + structure : object + Structure to match against ``scan`` + evaluation_context: object, optional + The evaluation context used to carry external information into the evaluation. + *args + Propagated to scoring function + **kwargs + Propagated to scoring function + + Returns + ------- + SpectrumMatcherBase + """""" + raise NotImplementedError() + + def handle_instance(self, structure, scan, mass_shift, evaluation_context=None): + solution = self.evaluate(scan, structure, mass_shift=mass_shift, + evaluation_context=evaluation_context, + **self.evaluation_args) + self.solution_map[scan.id, mass_shift.name] = self.solution_packer(solution) + return solution + + def construct_cache_subgroups(self, work_order): + '''Build groups of structures which should be evaluated within the same context. + The default implementation assumes each structure should get its own context. + + Subclasses should override this to determine how to properly group things to + share context. + + Parameters + ---------- + work_order: :class:`dict` + A work order specification. Assumes the first entry in each order is the + structure to be grouped. + + Returns + ------- + subgroups: :class:`list` of :class:`list` + Each distinct subgroup to be evauluated together. + ''' + subgroups = [] + for key, order in work_order['work_orders'].items(): + record = order[0] + subgroups.append([record]) + return subgroups + + def evaluate_subgroup(self, work_order, subgroup): + """"""Evaluate a sub-group of structures with shared context against their respective + spectra. + + Parameters + ---------- + work_order : :class:`dict` + The work order specification which includes the mapping from structure ID to + spectrum hit type pairs. + subgroup : :class:`list` + The list of structures to evaluate together + + Returns + ------- + results: :class:`list` + A list of packed results for each member of the group + """""" + results = [] + evaluation_context = self.create_evaluation_context(subgroup) + for structure in subgroup: + scan_specification = work_order['work_orders'][structure.id][1] + scan_specification = [ + (self.fetch_scan(i), self.fetch_mass_shift(j)) for i, j in scan_specification] + solution_target = None + solution = None + for scan, mass_shift in scan_specification: + solution = self.handle_instance( + structure, scan, mass_shift, evaluation_context) + solution_target = solution.target + if solution is not None: + try: + solution.target.clear_caches() + except AttributeError: + pass + packed = self.pack_output(solution_target) + results.append(packed) + return results + + def handle_group(self, work_order): + results = [] + hit_cache_groups = self.construct_cache_subgroups(work_order) + for subgroup in hit_cache_groups: + results.extend(self.evaluate_subgroup(work_order, subgroup)) + return results + + def handle_item(self, structure, scan_specification): + scan_specification = [(self.fetch_scan(i), self.fetch_mass_shift(j)) for i, j in scan_specification] + solution_target = None + solution = None + for scan, mass_shift in scan_specification: + solution = self.handle_instance(structure, scan, mass_shift) + solution_target = solution.target + + if solution is not None: + try: + solution.target.clear_caches() + except AttributeError: + pass + return self.pack_output(solution_target) + + def pack_output(self, target): + raise NotImplementedError() + + +class LocalSpectrumEvaluator(SpectrumEvaluatorBase, TaskBase): + '''A :class:`SpectrumEvaluatorBase` implementation that counter-points + :class:`IdentificationProcessDispatcher` by doing all of its evaluation within + a single process. + + To avoid excessive subclassing, instances first try to steal the + :meth:`construct_cache_subgroups` and :meth:`create_evaluation_context` from + :attr:`evaluator`. + ''' + + log_process_cycle = 5000 + + evaluator: SpectrumEvaluatorBase + evaluation_args: dict + + + def __init__(self, evaluator, scan_map, mass_shift_map, solution_packer, evaluation_args=None): + if evaluation_args is None: + evaluation_args = dict() + self.evaluator = evaluator + self.scan_map = scan_map + self.mass_shift_map = mass_shift_map + self.solution_packer = solution_packer + self.solution_map = dict() + self.evaluation_args = evaluation_args + try: + self.construct_cache_subgroups = self.evaluator.construct_cache_subgroups + except AttributeError: + self.log(""Failed to acquire construct_cache_subgroups"") + try: + self.create_evaluation_context = self.evaluator.create_evaluation_context + except AttributeError: + self.log(""Failed to acquire create_evaluation_context"") + + def evaluate(self, scan, structure, *args, **kwargs): + return self.evaluator.evaluate(scan, structure, *args, **kwargs) + + def pack_output(self, target): + package = (target.id, self.solution_map) + self.solution_map = dict() + return package + + def process(self, hit_map: Mapping[Any, Any], + hit_to_scan_map: Mapping[Any, List[str]], + scan_hit_type_map: Mapping[Tuple[str, Any], MassShift], + hit_group_map: Mapping[int, List[Any]] = None) -> Mapping[str, List]: + deque_builder = TaskDeque() + deque_builder(hit_map, hit_to_scan_map, + scan_hit_type_map, hit_group_map) + i = 0 + has_groups = bool(hit_group_map) + if not has_groups: + n = len(hit_to_scan_map) + for target, scan_spec in deque_builder: + i += 1 + if i % self.log_process_cycle == 0: + self.log(""... %0.2f%% of Hits Searched (%d/%d)"" % + (i * 100. / n, i, n)) + target_id, result = self.handle_item(target, scan_spec) + target = hit_map[target_id] + yield (target, result) + else: + n = len(hit_group_map) + for work_order in deque_builder: + i += 1 + if i % self.log_process_cycle == 0: + self.log(""... %0.2f%% of Groups Searched (%d/%d)"" % + (i * 100. / n, i, n)) + for target_id, result in self.handle_group(work_order): + target = hit_map[target_id] + yield (target, result) + + +class SequentialIdentificationProcessor(TaskBase): + evaluation_method: SpectrumEvaluatorBase + evaluation_args: dict + + mass_shift_map: Mapping[str, MassShift] + structure_map: Mapping[Any, Any] + scan_map: Mapping[str, ProcessedScan] + + solution_handler: 'SolutionHandler' + solution_handler_type: Type['SolutionHandler'] + + + def __init__(self, evaluator, mass_shift_map, evaluation_args=None, solution_handler_type=None): + if evaluation_args is None: + evaluation_args = dict() + if solution_handler_type is None: + solution_handler_type = SolutionHandler + self.evaluation_method = evaluator + self.evaluation_args = evaluation_args + self.mass_shift_map = mass_shift_map + self.solution_handler_type = solution_handler_type + self.solution_handler = self.solution_handler_type({}, {}, self.mass_shift_map) + self.structure_map = None + self.scan_map = None + + def _make_evaluator(self, **kwargs): + evaluator = LocalSpectrumEvaluator( + self.evaluation_method, + self.scan_map, + self.mass_shift_map, + self.solution_handler.packer, + self.evaluation_args) + return evaluator + + def process(self, scan_map: Mapping[str, ProcessedScan], + hit_map: Mapping[Any, Any], + hit_to_scan_map: Mapping[Any, List[str]], + scan_hit_type_map: Mapping[Tuple[str, Any], MassShift], + hit_group_map: Mapping[int, List[Any]] = None) -> Mapping[str, List]: + self.structure_map = hit_map + start_time = time.time() + self.scan_map = self.solution_handler.scan_map = scan_map + evaluator = self._make_evaluator() + # self.log(""... Searching Hits (%d:%d)"" % ( + # len(hit_to_scan_map), + # sum(map(len, hit_to_scan_map.values())))) + for target, score_map in evaluator.process(hit_map, hit_to_scan_map, scan_hit_type_map, hit_group_map): + self.store_result(target, score_map) + end_time = time.time() + elapsed = end_time - start_time + self.log(""... Identification Completed (%0.2f sec.): %d Solutions"" % + (elapsed, self.solution_handler.counter, )) + return self.scan_solution_map + + @property + def scan_solution_map(self): + return self.solution_handler.scan_solution_map + + def store_result(self, target, score_map): + """"""Save the spectrum match scores for ``target`` against the + set of matched scans + + Parameters + ---------- + target : object + The structure that was matched + score_map : dict + Maps (scan id, mass shift name) to score + """""" + self.solution_handler(target, score_map) + + +class SolutionHandler(TaskBase): + def __init__(self, scan_solution_map, scan_map, mass_shift_map, packer=None): + if packer is None: + packer = SolutionPacker() + self.scan_solution_map = defaultdict(list, (scan_solution_map or {})) + self.scan_map = scan_map + self.mass_shift_map = mass_shift_map + self.packer = packer + self.counter = 0 + + def _make_spectrum_match(self, scan_id, target, score, shift_type): + return SpectrumMatch( + self.scan_map[scan_id], target, score, + mass_shift=self.mass_shift_map[shift_type]) + + def store_result(self, target, score_map): + """"""Save the spectrum match scores for ``target`` against the + set of matched scans + + Parameters + ---------- + target : object + The structure that was matched + score_map : dict + Maps (scan id, mass shift name) to score + """""" + self.counter += 1 + for hit_spec, result_pack in score_map.items(): + scan_id, shift_type = hit_spec + score = self.packer.unpack(result_pack) + psm = self._make_spectrum_match(scan_id, target, score, shift_type) + self.scan_solution_map[scan_id].append(psm) + + def __call__(self, target, score_map): + return self.store_result(target, score_map) + + +class SolutionPacker(object): + def __call__(self, spectrum_match): + return spectrum_match.score + + def unpack(self, package): + return package + + +class MultiScoreSolutionHandler(SolutionHandler): + def __init__(self, scan_solution_map, scan_map, mass_shift_map, packer=None, spectrum_match_type=None): + if spectrum_match_type is None: + spectrum_match_type = MultiScoreSpectrumMatch + if packer is None: + packer = MultiScoreSolutionPacker(score_set_tp=spectrum_match_type.score_set_type) + self.spectrum_match_type = spectrum_match_type + super(MultiScoreSolutionHandler, self).__init__( + scan_solution_map, scan_map, mass_shift_map, packer) + + def _make_spectrum_match(self, scan_id, target, score, shift_type): + return self.spectrum_match_type( + self.scan_map[scan_id], target, score, + mass_shift=self.mass_shift_map[shift_type]) + + +class MultiScoreSolutionPacker(object): + def __init__(self, score_set_tp=None): + if score_set_tp is None: + score_set_tp = ScoreSet + self.score_set_tp = score_set_tp + + def __call__(self, spectrum_match): + return self.score_set_tp.from_spectrum_matcher(spectrum_match).pack() + + def unpack(self, package): + return self.score_set_tp.unpack(package) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/peptide/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/peptide/scoring/simple_score.py",".py","2045","63","import numpy as np + +from glycresoft.structure import FragmentMatchMap + +from .base import ( + PeptideSpectrumMatcherBase, ChemicalShift, + HCDFragmentationStrategy, IonSeries) + + +class SimpleCountScorer(PeptideSpectrumMatcherBase): + def __init__(self, scan, sequence, mass_shift=None): + super(SimpleCountScorer, self).__init__(scan, sequence, mass_shift) + self._score = None + self.solution_map = FragmentMatchMap() + + def calculate_score(self, **kwargs): + self._score = len(self.solution_map) + return self._score + + +class SimpleCoverageScorer(PeptideSpectrumMatcherBase): + def __init__(self, scan, sequence, mass_shift=None): + super(SimpleCoverageScorer, self).__init__(scan, sequence, mass_shift) + self._score = None + self.solution_map = FragmentMatchMap() + + def _compute_coverage_vectors(self): + n_term_ions = np.zeros(len(self.target)) + c_term_ions = np.zeros(len(self.target)) + + for frag in self.solution_map.fragments(): + if frag.series in (IonSeries.b, IonSeries.c): + n_term_ions[frag.position] = 1 + elif frag.series in (IonSeries.y, IonSeries.z): + c_term_ions[frag.position] = 1 + n_term_ions[0] = 0 + return n_term_ions, c_term_ions + + def compute_coverage(self): + (n_term_ions, c_term_ions) = self._compute_coverage_vectors() + + mean_coverage = np.mean(np.log2(n_term_ions + c_term_ions[::-1] + 1) / np.log2(3)) + + return mean_coverage + + def calculate_score(self, **kwargs): + score = self._coverage_score() + self._score = score + return score + + def _coverage_score(self): + return self.compute_coverage() + + + +try: + _has_c = True + from glycresoft._c.tandem.tandem_scoring_helpers import _peptide_compute_coverage_vectors, compute_coverage + SimpleCoverageScorer._compute_coverage_vectors = _peptide_compute_coverage_vectors + SimpleCoverageScorer.compute_coverage = compute_coverage +except ImportError: + _has_c = False +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/peptide/scoring/__init__.py",".py","343","9","from glycresoft.tandem import target_decoy +from glycresoft.tandem.target_decoy import ( + TargetDecoyAnalyzer, GroupwiseTargetDecoyAnalyzer) + +from .base import SpectrumMatcherBase, PeptideSpectrumMatcherBase +from .intensity_score import LogIntensityScorer +from .simple_score import SimpleCoverageScorer +from .localize import AScoreEvaluator +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/peptide/scoring/intensity_score.py",".py","2451","70","import numpy as np +import math + +from glycresoft.structure import FragmentMatchMap +from glycopeptidepy.structure.fragment import IonSeries + +from .base import PeptideSpectrumMatcherBase +from .simple_score import SimpleCoverageScorer + + +class LogIntensityScorer(SimpleCoverageScorer): + def __init__(self, scan, sequence, mass_shift=None, *args, **kwargs): + super(LogIntensityScorer, self).__init__(scan, sequence, mass_shift, *args, **kwargs) + + def _intensity_score(self, error_tolerance=2e-5, *args, **kwargs): + total = 0 + target_ion_series = { + IonSeries.b, IonSeries.y, IonSeries.c, IonSeries.z} + for peak, fragment in self.solution_map: + if fragment.series not in target_ion_series: + continue + total += np.log10(peak.intensity) + return total + + def calculate_score(self, error_tolerance=2e-5, *args, **kwargs): + self._score = self._intensity_score(error_tolerance, *args, **kwargs) * self._coverage_score() + return self._score + + +class HyperscoreScorer(PeptideSpectrumMatcherBase): + def __init__(self, scan, sequence, mass_shift=None): + super(HyperscoreScorer, self).__init__(scan, sequence, mass_shift) + self._score = None + self.solution_map = FragmentMatchMap() + + def _calculate_hyperscore(self, *args, **kwargs): + n_term_intensity = 0 + c_term_intensity = 0 + n_term = 0 + c_term = 0 + for peak, fragment in self.solution_map: + if fragment.series in (IonSeries.b, IonSeries.c): + n_term += 1 + n_term_intensity += peak.intensity + elif fragment.series in (IonSeries.y, IonSeries.z): + c_term += 1 + c_term_intensity += peak.intensity + hyper = 0 + factors = [math.factorial(n_term), math.factorial(c_term), + n_term_intensity, c_term_intensity] + for f in factors: + if not f: + continue + hyper += math.log(f) + + return hyper + + def calculate_score(self, error_tolerance=2e-5, *args, **kwargs): + self._score = self._calculate_hyperscore( + error_tolerance, *args, **kwargs) + return self._score + + +try: + _has_c = True + from glycresoft._c.tandem.tandem_scoring_helpers import _calculate_hyperscore + HyperscoreScorer._calculate_hyperscore = _calculate_hyperscore +except ImportError: + _has_c = False +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/peptide/scoring/localize.py",".py","30304","787","# -*- coding: utf-8 -*- +import itertools +import math +import array + +from collections import defaultdict +from decimal import Decimal +from typing import Any, DefaultDict, Dict, List, Optional, Set, Tuple, Union, NamedTuple, Deque + +import numpy as np +from scipy.special import comb + +from glycopeptidepy import PeptideSequence, Modification, ModificationRule, IonSeries, PeptideFragment +from glycopeptidepy.utils.memoize import memoize +from glycopeptidepy.algorithm import PeptidoformGenerator, ModificationSiteAssignmentCombinator + +from ms_deisotope.data_source import ProcessedScan +from ms_deisotope.peak_set import window_peak_set, DeconvolutedPeak +from ms_deisotope.peak_dependency_network.intervals import SpanningMixin + +from glycresoft.structure import FragmentCachingGlycopeptide +from glycresoft.structure.probability import PredictorBase + +from glycresoft.tandem.spectrum_match.spectrum_match import LocalizationScore, ScanMatchManagingMixin + + +MAX_MISSING_A_SCORE = 1e3 + + +@memoize(100000000000) +def binomial_pmf(n, i, p): + try: + return comb(n, i, exact=True) * (p ** i) * ((1 - p) ** (n - i)) + except OverflowError: + dn = Decimal(n) + di = Decimal(i) + dp = Decimal(p) + x = math.factorial(dn) / (math.factorial(di) * math.factorial(dn - di)) + return float(x * dp ** di * ((1 - dp) ** (dn - di))) + + +class PeakWindow(SpanningMixin): + peaks: List[DeconvolutedPeak] + max_mass: float + + def __init__(self, peaks): + self.peaks = list(peaks) + self.max_mass = 0 + self.start = 0 + self.end = 0 + self._calculate() + + def __iter__(self): + return iter(self.peaks) + + def __getitem__(self, i): + return self.peaks[i] + + def __len__(self): + return len(self.peaks) + + def _calculate(self): + self.peaks.sort(key=lambda x: x.intensity, reverse=True) + max_mass = 0 + min_mass = float('inf') + for peak in self.peaks: + if peak.neutral_mass > max_mass: + max_mass = peak.neutral_mass + elif peak.neutral_mass < min_mass: + min_mass = peak.neutral_mass + self.end = self.max_mass = max_mass + self.start = min_mass + + def __repr__(self): + template = ""{self.__class__.__name__}({self.max_mass}, {size})"" + return template.format(self=self, size=len(self)) + + + +class BlindPeptidoformGenerator(PeptidoformGenerator): + """"""A sub-class of the :class:`~.PeptidoformGenerator` type that ignores + site-specificities. + """""" + def modification_sites_for(self, sequence, rules: List[ModificationRule], include_empty: bool=True): + variable_sites = { + mod: set(range(len(sequence))) for mod in rules} + modification_sites = ModificationSiteAssignmentCombinator( + variable_sites, include_empty=include_empty) + return modification_sites + + +class ModificationAssignment(NamedTuple): + site: int + modification: Modification + + @property + def is_ambiguous(self): + try: + return len(self.site) > 1 + except TypeError: + return False + + def itersites(self): + if self.is_ambiguous: + for i in self.site: + yield i + else: + yield self.site + + +class ProbableSitePair(NamedTuple): + top_solution1: PeptideSequence + top_solution2: PeptideSequence + modifications: List[Modification] + peak_depth: int + + +class AScoreSpec(NamedTuple): + site: ModificationAssignment + score: float + site_determining_ions: np.array + alternative_site_ions: np.array + + +class LocalizationCandidate(object): + peptide: PeptideSequence + modifications: List[Union[ModificationRule, Modification]] + fragments: List[PeptideFragment] + + def __init__(self, peptide, modifications, fragments=None): + self.peptide = peptide + self.modifications = modifications + self.fragments = fragments + + def __hash__(self): + return hash(self.peptide) + + def __eq__(self, other): + return self.peptide == other.peptide and self.modifications == other.modifications + + def make_solution(self, a_score: AScoreSpec, permutations: Optional[np.ndarray] = None) -> 'AScoreSolution': + return AScoreSolution(self.peptide, a_score, self.modifications, permutations, self.fragments) + + def __repr__(self): + template = ""{self.__class__.__name__}({d})"" + + def formatvalue(v): + if isinstance(v, float): + return ""%0.4f"" % v + else: + return str(v) + d = [ + ""%s=%s"" % (k, formatvalue(v)) if v is not self else ""(...)"" for k, v in sorted( + self.__dict__.items(), key=lambda x: x[0]) + if (not k.startswith(""_"") and not callable(v)) + and not (v is None) and k != ""fragments""] + + return template.format(self=self, d=', '.join(d)) + + +class AScoreSolution(LocalizationCandidate): + a_score: List[AScoreSpec] + permutations: np.ndarray + + def __init__(self, peptide: PeptideSequence, a_score, modifications: List[Modification], permutations, + fragments: Optional[List[PeptideFragment]]=None): + super().__init__(peptide, modifications, fragments) + self.a_score = a_score + self.permutations = permutations + + +class PeptidoformPermuter(object): + peptide: PeptideSequence + modification_rule: ModificationRule + modification_count: int + respect_specificity: bool + + def __init__(self, peptide: PeptideSequence, modification_rule: ModificationRule, + modification_count: int=1, respect_specificity: bool=True): + self.peptide = peptide + self.modification_rule = modification_rule + self.modification_count = modification_count + self.respect_specificity = respect_specificity + + def find_existing(self, modification_rule: ModificationRule): + '''Find existing modifications derived from this rule + + Parameters + ---------- + modification_rule: :class:`~.ModificationRule` + The modification rule to search for + + Returns + ------- + indices: list + The indices of :attr:`peptide` where modifications were found + ''' + indices = [] + for i, position in enumerate(self.peptide): + if position.modifications and modification_rule in position.modifications: + indices.append(i) + return indices + + def generate_base_peptides(self, modification_rule: ModificationRule) -> List[PeptideSequence]: + """"""Generate peptides from :attr:`peptide` which have had combinations of + modification sites removed. + + Parameters + ---------- + modification_rule : :class:`~.ModificationRule` + The modification rule to remove + + Returns + ------- + list + """""" + existing_indices = self.find_existing(modification_rule) + base_peptides: List[Union[PeptideSequence, FragmentCachingGlycopeptide]] = [] + for indices in itertools.combinations(existing_indices, self.modification_count): + base_peptide = self.peptide.clone() + for i in indices: + base_peptide.drop_modification(i, modification_rule) + base_peptides.append(base_peptide) + # The target modification was not present, so the unaltered peptide must be the base + if not base_peptides: + base_peptides = [self.peptide.clone()] + if isinstance(base_peptides[0], FragmentCachingGlycopeptide): + for bp in base_peptides: + bp.clear_caches() + return base_peptides + + def generate_peptidoforms(self, modification_rule: ModificationRule, base_peptides: Optional[PeptideSequence]=None): + if base_peptides is None: + base_peptides = self.generate_base_peptides(modification_rule) + if self.respect_specificity: + PeptidoformGeneratorType = PeptidoformGenerator + else: + PeptidoformGeneratorType = BlindPeptidoformGenerator + pepgen = PeptidoformGeneratorType( + [], [modification_rule], self.modification_count) + peptidoforms = defaultdict(set) + for base_peptide in base_peptides: + is_caching = isinstance(base_peptide, FragmentCachingGlycopeptide) + mod_combos = pepgen.modification_sites_for(base_peptide, pepgen.variable_modifications) + for mod_combo in mod_combos: + if len(mod_combo) != self.modification_count: + continue + mod_combo = [ModificationAssignment(*mc) for mc in mod_combo] + peptidoform, _n_mods = pepgen.apply_variable_modifications( + base_peptide, mod_combo, None, None) + if is_caching: + peptidoform.clear_caches() + peptidoforms[peptidoform].update(tuple(mod_combo)) + return [LocalizationCandidate(peptide, sorted(mods), self._generate_fragments(peptide)) + for peptide, mods in peptidoforms.items()] + + +class LocalizationScorerBase(PeptidoformPermuter, ScanMatchManagingMixin): + + scan: ProcessedScan + _fragment_cache: Dict[Union[PeptideSequence, Any], List[PeptideFragment]] + + def __init__(self, scan, peptide: PeptideSequence, modification_rule: ModificationRule, + modification_count: int = 1, respect_specificity: bool = True): + super().__init__(peptide, modification_rule, modification_count, respect_specificity) + self.scan = scan + self._fragment_cache = {} + + def _generate_fragments(self, peptidoform: PeptideSequence) -> List[PeptideFragment]: + key = str(peptidoform) + if key in self._fragment_cache: + return self._fragment_cache[key] + + ion_series = [] + + if self.is_hcd(): + ion_series.append(IonSeries.b) + ion_series.append(IonSeries.y) + if self.is_exd(): + ion_series.append(IonSeries.c) + ion_series.append(IonSeries.z) + + frags = itertools.chain.from_iterable( + itertools.chain.from_iterable( + map(peptidoform.get_fragments, ion_series) + ) + ) + frags = sorted(frags, key=lambda x: x.mass) + self._fragment_cache[key] = frags + return frags + + def clear_cache(self): + self._fragment_cache.clear() + + +class AScoreEvaluator(LocalizationScorerBase): + ''' + Calculate a localization statistic for given peptidoform and modification rule. + + The original probabilistic model is described in [1]. Implementation based heavily + on the OpenMS implementation [2]. + + References + ---------- + [1] Beausoleil, S. a, Villén, J., Gerber, S. a, Rush, J., & Gygi, S. P. (2006). + A probability-based approach for high-throughput protein phosphorylation analysis + and site localization. Nature Biotechnology, 24(10), 1285–1292. https://doi.org/10.1038/nbt1240 + [2] Rost, H. L., Sachsenberg, T., Aiche, S., Bielow, C., Weisser, H., Aicheler, F., … Kohlbacher, O. (2016). + OpenMS: a flexible open-source software platform for mass spectrometry data analysis. Nat Meth, 13(9), + 741–748. https://doi.org/10.1038/nmeth.3959 + ''' + peak_windows: List[PeakWindow] + + def __init__(self, scan, peptide, modification_rule, modification_count=1, respect_specificity=True): + self._scan = None + super().__init__( + scan, peptide, modification_rule, modification_count, respect_specificity) + self.peptidoforms = self.generate_peptidoforms(self.modification_rule) + + @property + def scan(self): + return self._scan + + @scan.setter + def scan(self, value): + self._scan = value + if value is None: + self.peak_windows = [] + else: + self.peak_windows = list(map(PeakWindow, window_peak_set(value.deconvoluted_peak_set))) + + + def match_ions(self, fragments: List[PeptideFragment], depth: int=10, error_tolerance: float=1e-5) -> Tuple[int, List[float]]: + '''Match fragments against the windowed peak set at a given + peak depth. + + Parameters + ---------- + fragments: list + A list of peptide fragments, sorted by mass + depth: int + The peak depth to search to, the `i`th most intense peak in + each window + error_tolerance: float + The PPM error tolerance to use when matching peaks. + + Returns + ------- + int: + The number of fragments matched + ''' + n = 0 + window_i = 0 + window_n = len(self.peak_windows) + current_window = self.peak_windows[window_i] + intensities: array.ArrayType[float] = array.array('f') + for frag in fragments: + while not current_window or (frag.mass >= (current_window.max_mass + 1)): + window_i += 1 + if window_i == window_n: + return n + current_window = self.peak_windows[window_i] + for peak in current_window[:depth]: + if abs(peak.neutral_mass - frag.mass) / frag.mass < error_tolerance: + intensities.append(peak.intensity) + n += 1 + return n, np.frombuffer(intensities, dtype=np.float32) + + def permutation_score(self, peptidoform: LocalizationCandidate, error_tolerance: float=1e-5) -> Tuple[np.ndarray, + List[List[float]]]: + '''Calculate the binomial statistic for this peptidoform + using the top 1 to 10 peaks. + + Parameters + ---------- + peptidoform: :class:`~.PeptideSequence` + The peptidoform to score + error_tolerance: float + The PPM error tolerance to use when matching peaks. + + Returns + ------- + :class:`numpy.ndarray`: + The binomial score at peak depth `i + 1` + + See Also + -------- + :meth:`_score_at_window_depth` + :meth:`match_ions` + ''' + fragments = peptidoform.fragments + N = len(fragments) + site_scores = np.zeros(10) + intensities = [None for i in range(10)] + for i in range(1, 11): + site_scores[i - 1], intensities[i - 1] = self._score_at_window_depth( + fragments, N, i, error_tolerance) + return site_scores, intensities + + def _score_at_window_depth(self, fragments: List[PeptideFragment], N: int, i: int, error_tolerance: float=1e-5) -> Tuple[float, List[float]]: + '''Score a fragment collection at a given peak depth, and + calculate the binomial score based upon the probability mass + function. + + Parameters + ---------- + fragments: list + A list of peptide fragments, sorted by mass + N: int + The maximum number of theoretical fragments + i: int + The peak depth to search through + error_tolerance: float + The PPM error tolerance to use when matching peaks. + + Returns + ------- + score: float + intensities: list[float] + ''' + n, intensities = self.match_ions(fragments, i, error_tolerance=error_tolerance) + p = i / 100.0 + # If a fragment matches twice, this count can exceed the theoretical maximum. + if n > N: + n = N + cumulative_score = binomial_pmf(N, n, p) + if cumulative_score == 0.0: + return MAX_MISSING_A_SCORE, intensities + return abs(-10.0 * math.log10(cumulative_score)), intensities + + def rank_permutations(self, permutation_scores): + """"""Rank generated peptidoforms by weighted sum of permutation scores + + Parameters + ---------- + permutation_scores : :class:`list` of :class:`list` of :class:`float` + The raw output of :meth:`permutation_score` for each peak depth for + each peptidoform. + + Returns + ------- + :class:`list` + A list of :class:`tuple` instances of (weighted score, peptidoform index) + """""" + ranking = [] + for i, perm_scores in enumerate(permutation_scores): + ranking.append((self._weighted_score(perm_scores), i)) + ranking.sort(reverse=True) + return ranking + + # Taken directly from reference [1] + _weight_vector = np.array([ + 0.5, 0.75, 1.0, 1.0, 1.0, 1.0, 0.75, 0.5, .25, .25 + ]) + + def _weighted_score(self, scores): + """"""Calculate the weighted sum score over the peak-depth permuted + binomial score vector. + + Parameters + ---------- + scores : :class:`list` + The binomial score at each peak depth + + Returns + ------- + float + """""" + return self._weight_vector.dot(scores) / 10.0 + + def score_solutions(self, error_tolerance: float=1e-5, peptidoforms: Optional[List[LocalizationCandidate]]=None) -> List[AScoreSolution]: + if peptidoforms is None: + peptidoforms = self.peptidoforms + scores, _intensities = zip(*[self.permutation_score(candidate, error_tolerance=error_tolerance) + for candidate in peptidoforms]) + ranked = self.rank_permutations(scores) + solutions = [peptidoforms[i].make_solution(score, scores[i]) + for score, i in ranked] + return solutions + + def score_localizations(self, solutions: List[AScoreSolution], error_tolerance=1e-5): + """"""Find pairs of sequence solutions which differ in the localization + of individual modifications w.r.t. to the best match to compute the final + per-modification A-score. + + The first solution in `solutions` is the highest ranked solution, and subsequent + solutions are searched for the next case where one of the modification of interest + is located at a different position, forming a pair for that modification site by + :meth:`find_highest_scoring_permutations`. For each pair, the sequences are re-scored + using only site-determining ions, and the difference between those scores is the A-score + for that pair's modification site, as calculated by :meth:`calculate_delta`. + + If there are no alternative sites for a given modification, that modification will be + given the A-score given by :const:`MAX_MISSING_A_SCORE`. If there is another + localization which scores equally well, the A-score will be 0 by definition of + the delta step. + + Parameters + ---------- + solutions : list + The list of :class:`AScoreSolution` objects, ranked by total score + error_tolerance : float, optional + The mass error tolerance to use when matching site-determining ions (the default is 1e-5) + + Returns + ------- + :class:`AScoreSolution` + """""" + delta_scores = [] + pairs = self.find_highest_scoring_permutations(solutions) + top_solution = solutions[0] + if not pairs: + for mod in top_solution.modifications: + delta_scores.append( + AScoreSpec( + mod, + MAX_MISSING_A_SCORE, + np.array([], dtype=np.float32), + np.array([], dtype=np.float32) + ) + ) + top_solution.a_score = delta_scores + return top_solution + for pair in pairs: + delta_score, intensities1, intensities2 = self.calculate_delta(pair, error_tolerance=error_tolerance) + pair.top_solution1.a_score = delta_score + delta_scores.append( + AScoreSpec( + pair.modifications, + delta_score, + intensities1, + intensities2 + ) + ) + top_solution.a_score = delta_scores + return top_solution + + def score(self, error_tolerance: float=1e-5) -> AScoreSolution: + solutions = self.score_solutions(error_tolerance) + top_solution = self.score_localizations(solutions, error_tolerance) + return top_solution + + def find_highest_scoring_permutations(self, solutions: List[AScoreSolution], + best_solution: Optional[AScoreSolution]=None, + offset: Optional[int] = None) -> List[ProbableSitePair]: + if best_solution is None: + best_solution = solutions[0] + offset = 1 + else: + if offset is None: + for i, sol in enumerate(solutions): + if sol == solutions: + offset = i + 1 + break + else: + raise ValueError(""Best solution %r not in solution set"") + permutation_pairs = [] + # for each modification under permutation, find the next best solution which + # does not have this modification in its set of permuted modifications, and + # package the pair into a :class:`ProbableSitePair`. + for site in best_solution.modifications: + for alt_solution in solutions[offset:]: + if site not in alt_solution.modifications: + peak_depth = np.argmax(best_solution.permutations - alt_solution.permutations) + 1 + permutation_pairs.append(ProbableSitePair(best_solution, alt_solution, site, peak_depth)) + break + return permutation_pairs + + def site_determining_ions(self, solutions: List[LocalizationCandidate]) -> List[List[PeptideFragment]]: + frag_sets = [set(sol.fragments) for sol in solutions] + counts = defaultdict(int) + for frag_set in frag_sets: + for frag in frag_set: + counts[frag] += 1 + site_determining = [] + for frag_set in frag_sets: + acc = [] + for frag in frag_set: + if counts[frag] == 1: + acc.append(frag) + site_determining.append(sorted(acc, key=lambda x: x.mass)) + return site_determining + + def calculate_delta(self, candidate_pair: ProbableSitePair, error_tolerance=1e-5): + if candidate_pair.top_solution1 == candidate_pair.top_solution2: + return 0.0 + site_frags = self.site_determining_ions( + [candidate_pair.top_solution1, candidate_pair.top_solution2]) + site_frags1, site_frags2 = site_frags[0], site_frags[1] + N1 = len(site_frags1) + N2 = len(site_frags2) + peak_depth = candidate_pair.peak_depth + score1, intensities1 = self._score_at_window_depth( + site_frags1, N1, peak_depth, error_tolerance=error_tolerance) + score2, intensities2 = self._score_at_window_depth( + site_frags2, N2, peak_depth, error_tolerance=error_tolerance) + return score1 - score2, intensities1, intensities2 + + +class _PeakSet: + peaks: Dict[int, float] + total: float + + def __init__(self, peaks=None, total=None): + if not peaks: + peaks = {} + total = 0 + self.peaks = peaks + self.total = total + + def add(self, peak: DeconvolutedPeak): + self.peaks[peak.index.neutral_mass] = peak.intensity + self.total += peak.intensity + + def shared_intensity(self, other: '_PeakSet'): + common = self.peaks.keys() & other.peaks.keys() + acc = 0 + for k in common: + acc += self.peaks[k] + return acc + + def count_partitions(self, other: '_PeakSet'): + common = self.peaks.keys() & other.peaks.keys() + m = len(common) + return len(self.peaks) - m, len(other.peaks) - m, m + + + +class _PTMProphetMatch(NamedTuple): + occupied: _PeakSet + unoccupied: _PeakSet + normalizer: float + + def o_score(self) -> float: + common = self.occupied.shared_intensity(self.unoccupied) + occupied_diff = (self.occupied.total - common) / self.normalizer + unoccupied_diff = (self.unoccupied.total - common) / self.normalizer + return occupied_diff / (occupied_diff + unoccupied_diff + 1e-6) + + def m_score(self) -> float: + m_occupied, m_unoccupied, _shared = self.occupied.count_partitions(self.unoccupied) + return m_occupied / (m_occupied + m_unoccupied + 1e-6) + + def to_solution(self, occupied_index: int, unoccupied_index: int) -> 'PTMProphetSolution': + return PTMProphetSolution(self.o_score(), self.m_score(), occupied_index, unoccupied_index) + + +class PTMProphetSolution(NamedTuple): + o_score: float + m_score: float + occupied_peptidoform_index: int + unoccupied_peptidoform_index: int + + +class ScoredIsoform(NamedTuple): + isoform: LocalizationCandidate + localizations: List[LocalizationScore] + score: float + + +class PTMProphetEvaluator(LocalizationScorerBase): + raw_matches: List[_PeakSet] + occupied_site_index: DefaultDict[int, Set[int]] + solution_for_site: Dict[int, PTMProphetSolution] + + def __init__(self, scan, peptide, modification_rule, modification_count=1, respect_specificity=True): + super().__init__( + scan, peptide, modification_rule, modification_count, respect_specificity) + self.peptidoforms = self.generate_peptidoforms(self.modification_rule) + self.raw_matches = [] + self.occupied_site_index = DefaultDict(set) + self.solution_for_site = {} + + def get_normalizer(self) -> float: + normalizer = float('inf') + for peak in self.scan.deconvoluted_peak_set: + if peak.intensity < normalizer: + normalizer = peak.intensity + return normalizer + + def score_arrangements(self, error_tolerance: float=1e-5): + raw_matches = [] + occupied_site_index = DefaultDict[int, Set[int]](set) + + normalizer = self.get_normalizer() + + for i, peptidoform in enumerate(self.peptidoforms): + acc = _PeakSet() + for fragment in peptidoform.fragments: + for peak in self.scan.deconvoluted_peak_set.all_peaks_for(fragment.mass, error_tolerance): + acc.add(peak) + raw_matches.append(acc) + for j, pos in enumerate(peptidoform.peptide): + if pos.has_modification(self.modification_rule): + occupied_site_index[j].add(i) + + self.raw_matches = raw_matches + self.occupied_site_index = occupied_site_index + + for site, occupied_in in self.occupied_site_index.items(): + best_occupied_match = _PeakSet() + best_occupied_index = None + best_unoccupied_match = _PeakSet() + best_unoccupied_index = None + for i in range(len(self.peptidoforms)): + if i in occupied_in: + if best_occupied_match.total < self.raw_matches[i].total: + best_occupied_match = self.raw_matches[i] + best_occupied_index = i + else: + if best_unoccupied_match.total < self.raw_matches[i].total: + best_unoccupied_match = self.raw_matches[i] + best_unoccupied_index = i + + if best_occupied_index is None: + continue + self.solution_for_site[site] = _PTMProphetMatch( + best_occupied_match, best_unoccupied_match, normalizer).to_solution( + best_occupied_index, best_unoccupied_index) + + def __repr__(self): + return f""{self.__class__.__name__}({self.scan}, {self.peptide}, {self.modification_rule}, {self.solution_for_site})"" + + def entropy(self, prophet: Optional[PredictorBase]) -> float: + m = self.modification_count + s = len(self.solution_for_site) + log_base = np.log(s / m) + acc = 0.0 + for sol in self.solution_for_site.values(): + prob = prophet.predict([sol.o_score, sol.m_score])[0] + acc += prob * np.log(prob) / log_base + return acc + + def site_probabilities(self, prophet: Optional[PredictorBase]) -> Dict[int, float]: + position_probs = {} + acc = 0.0 + for position, sol in self.solution_for_site.items(): + if prophet is not None: + prob = prophet.predict([sol.o_score, sol.m_score])[0] + else: + prob = sol.o_score + position_probs[position] = prob + acc += prob + acc /= self.modification_count + factor = 1 / acc if acc > 0 else 0 + return {k: min(v * factor, 1.0) for k, v in position_probs.items()} + + def score_isoforms(self, prophet: Optional[PredictorBase]) -> List[ScoredIsoform]: + weights: List[float] = [] + localizations: List[List[LocalizationScore]] = [] + sites = self.site_probabilities(prophet) + + for candidate in self.peptidoforms: + acc = 0.0 + parts: List[LocalizationScore] = [] + for mod_a in candidate.modifications: + try: + score = sites[mod_a.site] + except KeyError: + if not isinstance(mod_a.site, int): + # TODO: This needs to handle terminal modifications + # which requires a change to the core algorithm. + # Ignore them for now. + score = 0.0 + else: + # The position was never observed. Ignore it. + # May happen when sites are not restricted during + # peptidoform generation here but not during the original + # search. + score = 0.0 + acc += score + parts.append( + LocalizationScore( + mod_a.site, + mod_a.modification.name, + score + ) + ) + localizations.append(parts) + weights.append(acc) + + scored_isoforms = [] + for candidate, weight, loc_scores in zip(self.peptidoforms, weights, localizations): + scored_isoforms.append(ScoredIsoform( + candidate, loc_scores, weight)) + return scored_isoforms +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/tandem/peptide/scoring/base.py",".py","4661","102","from glycopeptidepy.structure.fragment import ChemicalShift, IonSeries, SimpleFragment, Composition +from glycopeptidepy.structure.fragmentation_strategy import EXDFragmentationStrategy, HCDFragmentationStrategy + +from ...spectrum_match import SpectrumMatcherBase + + +class PeptideSpectrumMatcherBase(SpectrumMatcherBase): + def get_fragments(self, series, strategy=None, include_neutral_losses=False): + fragments = self.target.get_fragments( + series, strategy=strategy, include_neutral_losses=include_neutral_losses) + return fragments + + def _match_backbone_series(self, series, error_tolerance=2e-5, masked_peaks=None, strategy=None, + include_neutral_losses=False): + if strategy is None: + strategy = HCDFragmentationStrategy + if masked_peaks is None: + masked_peaks = set() + for frags in self.get_fragments(series, strategy=strategy, include_neutral_losses=include_neutral_losses): + for frag in frags: + for peak in self.spectrum.all_peaks_for(frag.mass, error_tolerance): + if peak.index.neutral_mass in masked_peaks: + continue + self.solution_map.add(peak, frag) + + def _theoretical_mass(self): + return self.target.total_mass + + def _match_precursor(self, error_tolerance=2e-5, masked_peaks=None, include_neutral_losses=False): + if masked_peaks is None: + masked_peaks = set() + mass = self.target.total_mass + frag = SimpleFragment(""M"", mass, IonSeries.precursor, None) + for peak in self.spectrum.all_peaks_for(frag.mass, error_tolerance): + if peak.index.neutral_mass in masked_peaks: + continue + masked_peaks.add(peak) + self.solution_map.add(peak, frag) + if include_neutral_losses: + delta = -Composition(""NH3"") + for peak in self.spectrum.all_peaks_for(frag.mass + delta.mass, error_tolerance): + if peak.index.neutral_mass in masked_peaks: + continue + masked_peaks.add(peak) + shifted_frag = frag.clone() + shifted_frag.set_chemical_shift(ChemicalShift(""-NH3"", delta)) + self.solution_map.add(peak, shifted_frag) + delta = -Composition(""H2O"") + for peak in self.spectrum.all_peaks_for(frag.mass + delta.mass, error_tolerance): + if peak.index.neutral_mass in masked_peaks: + continue + masked_peaks.add(peak) + shifted_frag = frag.clone() + shifted_frag.set_chemical_shift(ChemicalShift(""-H2O"", delta)) + self.solution_map.add(peak, shifted_frag) + + def match(self, error_tolerance=2e-5, *args, **kwargs): + masked_peaks = set() + include_neutral_losses = kwargs.get(""include_neutral_losses"", False) + is_hcd = self.is_hcd() + is_exd = self.is_exd() + if not is_hcd and not is_exd: + is_hcd = True + + self._match_precursor(error_tolerance, masked_peaks, include_neutral_losses) + + # handle N-term + if is_hcd and not is_exd: + self._match_backbone_series( + IonSeries.b, error_tolerance, masked_peaks, HCDFragmentationStrategy, + include_neutral_losses) + elif is_exd: + self._match_backbone_series( + IonSeries.b, error_tolerance, masked_peaks, EXDFragmentationStrategy, + include_neutral_losses) + self._match_backbone_series( + IonSeries.c, error_tolerance, masked_peaks, EXDFragmentationStrategy, + include_neutral_losses) + + # handle C-term + if is_hcd and not is_exd: + self._match_backbone_series( + IonSeries.y, error_tolerance, masked_peaks, HCDFragmentationStrategy, + include_neutral_losses) + elif is_exd: + self._match_backbone_series( + IonSeries.y, error_tolerance, masked_peaks, EXDFragmentationStrategy, + include_neutral_losses) + self._match_backbone_series( + IonSeries.z, error_tolerance, masked_peaks, EXDFragmentationStrategy, + include_neutral_losses) + return self + + +try: + from glycresoft._c.tandem.tandem_scoring_helpers import ( + PeptideSpectrumMatcherBase_match_backbone_series, _match_precursor) + PeptideSpectrumMatcherBase._match_backbone_series = PeptideSpectrumMatcherBase_match_backbone_series + PeptideSpectrumMatcherBase._match_precursor = _match_precursor +except ImportError: + pass +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/config/__init__.py",".py","194","13"," +def get_configuration(): + from .config_file import get_configuration + return get_configuration() + + +from .config_file import DEBUG_MODE + + +__all__ = [ + ""get_configuration"", DEBUG_MODE +] +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/config/config_file.py",".py","3595","138","import hjson +import os +import platform +import shutil +import click + + +from .peptide_modification import (load_modification_rule, save_modification_rule) +from .substituent import (load_substituent_rule, save_substituent_rule) + +from psims.controlled_vocabulary import controlled_vocabulary as cv + + +CONFIG_DIR = click.get_app_dir(""glycresoft"") + +if platform.system().lower() != 'windows': + os.environ[""NOWAL""] = ""1"" + +_mpl_cache_dir = os.path.join(CONFIG_DIR, 'mpl') +cv_store = os.path.join(CONFIG_DIR, 'cv') + + +def populate_config_dir(): + os.makedirs(CONFIG_DIR) + + # Pre-populate OBO Cache to avoid needing to look these up + # by URL later + os.makedirs(cv_store) + with open(os.path.join(cv_store, 'psi-ms.obo'), 'wb') as fh: + fh.write(cv._use_vendored_psims_obo().read()) + with open(os.path.join(cv_store, 'unit.obo'), 'wb') as fh: + fh.write(cv._use_vendored_unit_obo().read()) + + os.makedirs(_mpl_cache_dir) + + +def delete_config_dir(): + shutil.rmtree(CONFIG_DIR, ignore_errors=True) + + +if not os.path.exists(CONFIG_DIR): + populate_config_dir() + +if not os.path.exists(_mpl_cache_dir): + os.makedirs(_mpl_cache_dir) + +os.environ[""MPLCONFIGDIR""] = _mpl_cache_dir + +CONFIG_FILE_NAME = ""glycresoft-cfg.hjson"" +USER_CONFIG_PATH = os.path.join(CONFIG_DIR, CONFIG_FILE_NAME) + +cv.configure_obo_store(os.path.join(CONFIG_DIR, ""cv"")) + +HAS_CONFIG = os.path.exists(USER_CONFIG_PATH) + +DEFAULT_CONFIG = { + ""version"": 0.4, + ""peptide_modifications"": {}, + ""glycan_modifications"": {}, + ""substituent_rules"": {}, + ""environment"": { + ""log_file_name"": ""glycresoft-log"", + ""log_file_mode"": ""a"" + }, + ""xml_huge_tree"": True +} + +_CURRENT_CONFIG = None + +if not HAS_CONFIG: + hjson.dump(DEFAULT_CONFIG, open(USER_CONFIG_PATH, 'w')) + + +def process(config): + for key, value in config['peptide_modifications'].items(): + load_modification_rule(value) + + for key, value in config[""substituent_rules""].items(): + load_substituent_rule(value) + + +def recursive_merge(a, b): + for k, v in b.items(): + if isinstance(b[k], dict) and isinstance(a.get(k), dict): + recursive_merge(a[k], v) + else: + a[k] = v + + +def get_configuration(): + global _CURRENT_CONFIG + _CURRENT_CONFIG = load_configuration_from_path(USER_CONFIG_PATH, apply=False) + local_config_path = os.path.join(os.getcwd(), CONFIG_FILE_NAME) + if os.path.exists(local_config_path): + local_config = load_configuration_from_path(local_config_path, apply=False) + recursive_merge(_CURRENT_CONFIG, local_config) + process(_CURRENT_CONFIG) + return _CURRENT_CONFIG + + +def load_configuration_from_path(path, apply=True): + cfg = hjson.load(open(path)) + if apply: + process(cfg) + return cfg + + +def set_configuration(obj): + global _CURRENT_CONFIG + _CURRENT_CONFIG = None + hjson.dump(obj, open(USER_CONFIG_PATH, 'w')) + return get_configuration() + + +def add_user_modification_rule(rule): + serialized = save_modification_rule(rule) + config = get_configuration() + config['peptide_modifications'][serialized['full_name']] = serialized + set_configuration(config) + return load_modification_rule(serialized) + + +def add_user_substituent_rule(rule): + serialized = save_substituent_rule(rule) + config = get_configuration() + config['substituent_rules'][serialized['name']] = serialized + set_configuration(config) + return load_substituent_rule(serialized) + + +try: + get_configuration() +except Exception: + set_configuration(DEFAULT_CONFIG) + + +DEBUG_MODE = bool(os.environ.get(""GLYCRESOFTDEBUG"")) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/config/colors.py",".py","320","16","import json + + +def read_colors_from_file(path): + with open(path, 'rt') as fh: + data = json.load(fh) + data = { + k: tuple(v) for k, v in data.items() + } + return data + + +def write_colors_to_file(colors, path): + with open(path, 'wt') as fh: + json.dump(colors, fh, sort_keys=True, indent=2) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/config/substituent.py",".py","1045","36","from glypy.structure.substituent import register as register_substituent_rule +from glypy.composition import formula, Composition + + +substituent_schema = { + ""name"": str, + ""composition"": str, + ""can_nh_derivatize"": bool, + ""is_nh_derivatizable"": bool, + ""attachment_composition"": str +} + + +def serialize_substituent_rule(substituent): + return { + ""name"": substituent.name, + ""composition"": formula(substituent.composition), + ""can_nh_derivatize"": substituent.can_nh_derivatize, + ""is_nh_derivatizable"": substituent.is_nh_derivatizable, + ""attachment_composition"": formula(substituent.attachment_composition) + } + + +def load_substituent_rule(rule_dict): + return register_substituent_rule( + rule_dict[""name""], + Composition(rule_dict[""composition""]), + rule_dict[""can_nh_derivatize""], + rule_dict[""is_nh_derivatizable""], + Composition(rule_dict[""attachment_composition""]), + ) + + +def save_substituent_rule(substituent): + return serialize_substituent_rule(substituent) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/config/mass_shift.py",".py","161","9","from glypy.composition import formula + +mass_shift_schema = { + ""name"": str, + ""composition"": str, + ""tandem_composition"": str, + ""charge_carrier"": int +} +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycresoft/config/peptide_modification.py",".py","1569","63","from glycopeptidepy.structure.modification import ( + ModificationTarget, ModificationRule, Modification, + ModificationCategory, SequenceLocation) + + +modification_rule_schema = { + ""composition"": dict, + ""mono_mass"": float, + ""full_name"": str, + ""title"": str, + ""specificity"": list, +} + + +modification_specificity_schema = { + ""position"": str, + ""site"": str +} + + +position_map = { + SequenceLocation.anywhere: ""Anywhere"", + SequenceLocation.n_term: ""Any N-term"", + SequenceLocation.c_term: ""Any C-term"", +} + + +def serialize_modification_target(target): + payloads = [] + if not target.amino_acid_targets: + payloads.append({ + ""site"": None, + ""position"": position_map[target.position_modifier] + }) + return payloads + else: + for aa in target.amino_acid_targets: + payloads.append({ + ""site"": str(aa), + ""position"": position_map[target.position_modifier] + }) + return payloads + + +def serialize_modification_rule(rule): + payload = dict() + payload['mono_mass'] = rule.mass + payload['full_name'] = rule.name + payload['title'] = rule.title + payload['composition'] = dict(rule.composition) + payload['specificity'] = [s for t in rule.targets for s in serialize_modification_target(t)] + return payload + + +def load_modification_rule(rule_dict): + rule = ModificationRule.from_unimod(rule_dict) + Modification.register_new_rule(rule) + return rule + + +def save_modification_rule(rule): + return serialize_modification_rule(rule) +","Python" +"Glycomics","mobiusklein/glycresoft","src/glycan_profiling/__init__.py",".py","974","24","import importlib +import sys +from types import ModuleType + +import glycresoft + +class LazyModule(ModuleType): + def __init__(self, name, mod_name): + super().__init__(name) + self.__mod_name = name + + def __getattr__(self, attr): + if ""_lazy_module"" not in self.__dict__: + self._lazy_module = importlib.import_module(self.__mod_name, package=""glycresoft"") + return getattr(self._lazy_module, attr) + +sys.modules['glycan_profiling'] = LazyModule(""glycresoft"", ""glycresoft"") +sys.modules[""glycan_profiling.serialize""] = LazyModule(""glycresoft.serialize"", ""glycresoft"") +sys.modules[""glycan_profiling.chromatogram_tree""] = LazyModule(""glycresoft.chromatogram_tree"", ""glycresoft"") +sys.modules[""glycan_profiling.config""] = LazyModule(""glycresoft.config"", ""glycresoft"") +sys.modules[""glycan_profiling.task""] = LazyModule(""glycresoft.task"", ""glycresoft"") +sys.modules[""glycan_profiling.structure""] = LazyModule(""glycresoft.structure"", ""glycresoft"") + +","Python" +"Glycomics","mobiusklein/glycresoft","docs/conf.py",".py","5162","179","# -*- coding: utf-8 -*- +# +# glycresoft documentation build configuration file, created by +# sphinx-quickstart on Tue Aug 08 17:36:35 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + +import sys +import os + +sys.path.append(os.path.abspath(""_ext"")) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.viewcode', + 'sphinx.ext.githubpages', + 'sphinx_clickx', + 'exec_directive' +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'glycresoft' +copyright = u'2024, Joshua Klein' +author = u'Joshua Klein' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = u'' +# The full version, including alpha/beta/rc tags. +release = u'' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set ""language"" from the command line for these cases. +language = ""en"" + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# + +html_theme_path = ['_theme'] +html_theme = 'custom_theme' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named ""default.css"" will overwrite the builtin ""default.css"". +html_static_path = ['_static'] +html_logo = '_static/img/logo.png' + +html_css_files = [ + ""css/custom.css"", +] + +html_sidebars = { + 'sidebar': ['sidebar.html', 'localtoc.html', 'relations.html', + 'sourcelink.html', 'searchbox.html'], +} + + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = 'glycresoftdoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'glycresoft.tex', u'glycresoft Documentation', + u'Joshua Klein', 'manual'), +] + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'glycresoft', u'glycresoft Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'glycresoft', u'glycresoft Documentation', + author, 'glycresoft', 'One line description of project.', + 'Miscellaneous'), +] + + + +","Python" +"Glycomics","mobiusklein/glycresoft","docs/_ext/sphinx_clickx.py",".py","10334","340","import re + +from docutils import nodes +from docutils.parsers.rst import directives +from docutils import statemachine + +import click +from docutils.parsers.rst import Directive + + +def clean_type_name(typename): + if not isinstance(typename, str): + try: + typename = typename.human_readable_name + except AttributeError: + typename = ' '.join(re.findall(r""[A-Z]+[^A-Z]+"", typename.__class__.__name__) + ).lower().strip() + cleaned = re.sub(r""(param$)|(param type)|(range)|(type)"", """", typename).strip() + return cleaned + + +def _indent(text, level=1): + prefix = ' ' * (4 * level) + + def prefixed_lines(): + for line in text.splitlines(True): + yield (prefix + line if line.strip() else line) + + return ''.join(prefixed_lines()) + + +def _get_usage(ctx): + """"""Alternative, non-prefixed version of 'get_usage'."""""" + formatter = ctx.make_formatter() + pieces = ctx.command.collect_usage_pieces(ctx) + formatter.write_usage(ctx.command_path, ' '.join(pieces), prefix='') + return formatter.getvalue().rstrip('\n') + + +def _get_help_record(ctx, opt): + """"""Re-implementation of click.Opt.get_help_record. + + The variant of 'get_help_record' found in Click makes uses of slashes to + separate multiple opts, and formats option arguments using upper case. This + is not compatible with Sphinx's 'option' directive, which expects + comma-separated opts and option arguments surrounded by angle brackets [1]. + + [1] http://www.sphinx-doc.org/en/stable/domains.html#directive-option + """""" + if opt.get_help_record(ctx) is None: + return None + + def _write_opts(opts): + rv, _ = click.formatting.join_options(opts) + if not opt.is_flag and not opt.count: + rv += ' <{}>'.format( + clean_type_name(opt.type)) + return rv + + rv = [_write_opts(opt.opts)] + if opt.secondary_opts: + rv.append(_write_opts(opt.secondary_opts)) + + help = opt.help or '' + extra = [] + if opt.default is not None and opt.show_default: + extra.append('default: %s' % ( + ', '.join('%s' % d for d in opt.default) + if isinstance(opt.default, (list, tuple)) + else opt.default, )) + if opt.required: + extra.append('required') + if extra: + help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra)) + + choices = [] + + if isinstance(opt.type, click.Choice): + def chunk(iterable, size=3): + i = 0 + iterable = tuple(iterable) + n = len(iterable) + while i < n: + yield iterable[i:i + size] + i += size + + choices.append(""| Choices: ["") + choices.append(""\n| "") + choices.append(';\n| '.join( + map(_indent, map(""; "".join, chunk(opt.type.choices))) + )) + choices.append(""]"") + + return ', '.join(rv), help, ''.join(choices) + + +def _format_option(ctx, opt): + """"""Format the output a `click.Option`."""""" + is_multiple = opt.multiple + opt = _get_help_record(ctx, opt) + if opt is None: + return + yield '.. option:: {}'.format(opt[0]) + if opt[1]: + yield '' + lines = list(statemachine.string2lines(opt[1], tab_width=4, convert_whitespace=True)) + if is_multiple: + lines[-1] += "" (May specify more than once)"" + for line in lines: + yield _indent(line) + if opt[2]: + yield '' + for line in statemachine.string2lines( + opt[2], tab_width=4, convert_whitespace=True): + yield _indent(line) + + +def _format_argument(arg): + """"""Format the output of a `click.Argument`."""""" + yield '.. option:: {}'.format(arg.human_readable_name) + yield '' + yield _indent('{} argument{}'.format( + 'Required' if arg.required else 'Optional', + '(s)' if arg.nargs != 1 else '')) + # yield _indent("""") + + description = ""<{}> "".format(arg.type.__class__.__name__.lower().replace( + ""paramtype"", """")) + + yield _indent(description + getattr(arg, ""doc_help"", """")) + + +def _format_envvar(param): + """"""Format the envvars of a `click.Option` or `click.Argument`."""""" + yield '.. envvar:: {}'.format(param.envvar) + yield '' + if isinstance(param, click.Argument): + param_ref = param.human_readable_name + else: + # if a user has defined an opt with multiple ""aliases"", always use the + # first. For example, if '--foo' or '-f' are possible, use '--foo'. + param_ref = param.opts[0] + + yield _indent('Provide a default for :option:`{}`'.format(param_ref)) + + +def _format_subcommand(command): + """"""Format a sub-command of a `click.Command` or `click.Group`."""""" + yield '.. object:: {}'.format(command[0]) + + if command[1].short_help: + yield '' + for line in statemachine.string2lines( + command[1].short_help, tab_width=4, convert_whitespace=True): + yield _indent(line) + + +def _format_command(ctx, show_nested): + """"""Format the output of `click.Command`."""""" + yield '.. program:: {}'.format(ctx.command_path) + + # usage + + yield '.. code-block:: shell' + yield '' + for line in _get_usage(ctx).splitlines(): + yield _indent(line) + yield '' + + # options + + # the hidden attribute is part of click 7.x only hence use of getattr + params = [x for x in ctx.command.params if isinstance(x, click.Option) + and not getattr(x, 'hidden', False)] + + if params: + # we use rubric to provide some separation without exploding the table + # of contents + yield '.. rubric:: Options' + yield '' + + for param in params: + for line in _format_option(ctx, param): + yield line + yield '' + + # arguments + + params = [x for x in ctx.command.params if isinstance(x, click.Argument)] + + if params: + yield '.. rubric:: Arguments' + yield '' + + for param in params: + for line in _format_argument(param): + yield line + yield '' + + # environment variables + + params = [x for x in ctx.command.params if getattr(x, 'envvar')] + + if params: + yield '.. rubric:: Environment variables' + yield '' + + for param in params: + for line in _format_envvar(param): + yield line + yield '' + + # if we're nesting commands, we need to do this slightly differently + if show_nested: + return + + commands = sorted(getattr(ctx.command, 'commands', {}).items()) + + if commands: + yield '.. rubric:: Commands' + yield '' + + for command in commands: + for line in _format_subcommand(command): + yield line + yield '' + + +class ClickDirective(Directive): + + has_content = False + required_arguments = 1 + option_spec = { + 'prog': directives.unchanged_required, + 'show-nested': directives.flag, + } + + def _load_module(self, module_path): + """"""Load the module."""""" + try: + module_name, attr_name = module_path.split(':', 1) + except ValueError: # noqa + raise self.error('""{}"" is not of format ""module.parser""'.format( + module_path)) + + try: + mod = __import__(module_name, globals(), locals(), [attr_name]) + except: # noqa + raise self.error('Failed to import ""{}"" from ""{}""'.format( + attr_name, module_name)) + + if not hasattr(mod, attr_name): + raise self.error('Module ""{}"" has no attribute ""{}""'.format( + module_name, attr_name)) + + return getattr(mod, attr_name) + + def _generate_nodes(self, name, command, parent=None, show_nested=False): + """"""Generate the relevant Sphinx nodes. + + Format a `click.Group` or `click.Command`. + + :param name: Name of command, as used on the command line + :param command: Instance of `click.Group` or `click.Command` + :param parent: Instance of `click.Context`, or None + :param show_nested: Whether subcommands should be included in output + :returns: A list of nested docutil nodes + """""" + ctx = click.Context(command, info_name=name, parent=parent) + + # Title + + # We build this with plain old docutils nodes + + section = nodes.section( + '', + nodes.title(text=name), + ids=[nodes.make_id(ctx.command_path)], + names=[nodes.fully_normalize_name(ctx.command_path)]) + section.attributes['classes'] = ['click-command-section'] + source_name = ctx.command_path + result = statemachine.ViewList() + + # Description + + # We parse this as reStructuredText, allowing users to embed rich + # information in their help messages if they so choose. + + if ctx.command.help: + for line in statemachine.string2lines( + ctx.command.help, tab_width=4, convert_whitespace=True): + result.append(line, source_name) + + result.append('', source_name) + + # Summary + + if isinstance(command, click.Command): + summary = _format_command(ctx, show_nested) + else: + # TODO(stephenfin): Do we care to differentiate? Perhaps we + # shouldn't show usage for groups? + summary = _format_command(ctx, show_nested) + + for line in summary: + result.append(line, source_name) + + self.state.nested_parse(result, 0, section) + + # Commands + + if show_nested: + commands = getattr(ctx.command, 'commands', {}) + for command_name, command_obj in sorted(commands.items()): + section.extend(self._generate_nodes( + command_name, + command_obj, + ctx, + show_nested)) + + return [section] + + def run(self): + self.env = self.state.document.settings.env + + command = self._load_module(self.arguments[0]) + + if 'prog' in self.options: + prog_name = self.options.get('prog') + else: + raise self.error(':prog: must be specified') + + show_nested = 'show-nested' in self.options + + return self._generate_nodes(prog_name, command, None, show_nested) + + +def setup(app): + app.add_directive('click', ClickDirective) +","Python" +"Glycomics","mobiusklein/glycresoft","docs/_ext/unimod_table.py",".py","751","24","from glycopeptidepy import Modification +from rst_table import as_rest_table + +rows = [[""UNIMOD"", ""Name"", ""Mass"", ""Other Names"", ""Targets""]] + +def unimod_name(rule): + names = list(filter(lambda x: x.startswith(""UNIMOD""), rule.names)) + if names: + return names[0] + +rules = Modification._table.rules() +unimod_rules = sorted(filter(unimod_name, rules), key=lambda x: int(unimod_name(x).split("":"")[1])) + +for rule in unimod_rules: + row = [ + unimod_name(rule), + rule.preferred_name, + rule.mass, + ', '.join(rule.names - {unimod_name(rule), rule.preferred_name}), + ', '.join(map(lambda x: x.replace(rule.name, '')[2:-1], rule.as_spec_strings())) + ] + rows.append(row) + +rendered_table = (as_rest_table(rows))","Python" +"Glycomics","mobiusklein/glycresoft","docs/_ext/exec_directive.py",".py","1454","45","# https://stackoverflow.com/questions/7250659/python-code-to-generate-part-of-sphinx-documentation-is-it-possible + +import sys +from os.path import basename +import traceback + +from io import StringIO + +from docutils.parsers.rst import Directive +from docutils import nodes, statemachine + + +class ExecDirective(Directive): + """"""Execute the specified python code and insert the output into the document"""""" + has_content = True + + def run(self): + oldStdout, sys.stdout = sys.stdout, StringIO() + + tab_width = self.options.get('tab-width', self.state.document.settings.tab_width) + source = self.state_machine.input_lines.source(self.lineno - self.state_machine.input_offset - 1) + + try: + exec('\n'.join(self.content)) + text = sys.stdout.getvalue() + lines = statemachine.string2lines(text, tab_width, convert_whitespace=True) + self.state_machine.insert_input(lines, source) + return [] + except Exception: + exc = traceback.format_exc() + return [nodes.error( + None, + nodes.paragraph(text=""Unable to execute python code at %s:%d:"" % ( + basename(source), self.lineno)), + nodes.paragraph(text=str(sys.exc_info()[1]))), + nodes.paragraph(text=exc) + ] + + finally: + sys.stdout = oldStdout + + +def setup(app): + app.add_directive('exec', ExecDirective) +","Python" +"Glycomics","mobiusklein/glycresoft","docs/_ext/rst_table.py",".py","3177","84","# http://code.activestate.com/recipes/579054-generate-sphinx-table/ + + +def as_rest_table(data, full=False): + """""" + >>> from report_table import as_rest_table + >>> data = [('what', 'how', 'who'), + ... ('lorem', 'that is a long value', 3.1415), + ... ('ipsum', 89798, 0.2)] + >>> print as_rest_table(data, full=True) + +-------+----------------------+--------+ + | what | how | who | + +=======+======================+========+ + | lorem | that is a long value | 3.1415 | + +-------+----------------------+--------+ + | ipsum | 89798 | 0.2 | + +-------+----------------------+--------+ + + >>> print as_rest_table(data) + ===== ==================== ====== + what how who + ===== ==================== ====== + lorem that is a long value 3.1415 + ipsum 89798 0.2 + ===== ==================== ====== + + """""" + data = data if data else [['No Data']] + table = [] + # max size of each column + sizes = list(map(max, zip(*[[len(str(elt)) for elt in member] + for member in data]))) + num_elts = len(sizes) + + if full: + start_of_line = '| ' + vertical_separator = ' | ' + end_of_line = ' |' + line_marker = '-' + else: + start_of_line = '' + vertical_separator = ' ' + end_of_line = '' + line_marker = '=' + + meta_template = vertical_separator.join(['{{{{{0}:{{{0}}}}}}}'.format(i) + for i in range(num_elts)]) + template = '{0}{1}{2}'.format(start_of_line, + meta_template.format(*sizes), + end_of_line) + # determine top/bottom borders + if full: + to_separator = str.maketrans('| ', '+-') + else: + to_separator = str.maketrans('|', '+') + start_of_line = start_of_line.translate(to_separator) + vertical_separator = vertical_separator.translate(to_separator) + end_of_line = end_of_line.translate(to_separator) + separator = '{0}{1}{2}'.format(start_of_line, + vertical_separator.join([x*line_marker for x in sizes]), + end_of_line) + # determine header separator + th_separator_tr = str.maketrans('-', '=') + start_of_line = start_of_line.translate(th_separator_tr) + line_marker = line_marker.translate(th_separator_tr) + vertical_separator = vertical_separator.translate(th_separator_tr) + end_of_line = end_of_line.translate(th_separator_tr) + th_separator = '{0}{1}{2}'.format(start_of_line, + vertical_separator.join([x*line_marker for x in sizes]), + end_of_line) + # prepare result + table.append(separator) + # set table header + titles = data[0] + table.append(template.format(*titles)) + table.append(th_separator) + + for d in data[1:-1]: + table.append(template.format(*d)) + if full: + table.append(separator) + table.append(template.format(*data[-1])) + table.append(separator) + return '\n'.join(table)","Python" +"Glycomics","mobiusklein/glycresoft","scripts/intracluster_similarity.py",".py","2878","79","import os +import csv + +from typing import Optional, DefaultDict, List, NamedTuple + +import click + +from glycresoft import serialize +from ms_deisotope.clustering.scan_clustering import SpectrumCluster +from ms_deisotope.output import ProcessedMSFileLoader +from ms_deisotope.data_source import ProcessedScan + + +class ClusterSpec(NamedTuple): + charge: int + adduct: str + + +class ClusterResult(NamedTuple): + glycopeptide: str + charge: int + adduct: str + average_similarity: float + cluster_size: int + + +@click.command() +@click.argument(""analysis_path"") +@click.option(""-m"", ""--mzml-path"", default=None, type=str) +@click.option(""-q"", ""--q-value-threshold"", default=0.01, type=float) +@click.option(""-o"", ""--output-path"", default=None, type=str) +def main(analysis_path: str, mzml_path: Optional[str] = None, q_value_threshold: Optional[float] = 0.01, output_path: Optional[str]=None): + ads = serialize.AnalysisDeserializer(analysis_path) + if mzml_path is None: + ms_reader = ads.open_ms_file() + else: + ms_reader = ProcessedMSFileLoader(mzml_path) + if output_path is None: + output_path = os.path.join( + os.path.dirname( + os.path.realpath(analysis_path) + ), + ""cluster_similarities.csv"" + ) + + idgps: List[serialize.IdentifiedGlycopeptide] = ads.query(serialize.IdentifiedGlycopeptide).filter(serialize.IdentifiedGlycopeptide.q_value <= q_value_threshold).all() + click.echo(f""Loaded {len(idgps)} glycopeptides"") + with open(output_path, 'wt', newline='') as fh: + writer = csv.DictWriter(fh, ClusterResult._fields) + writer.writeheader() + + with click.progressbar(idgps) as bar: + for idgp in bar: + tracks: DefaultDict[ClusterSpec, List[ProcessedScan]] = DefaultDict(list) + gp = idgp.structure + sset: serialize.GlycopeptideSpectrumSolutionSet + for sset in idgp.tandem_solutions: + scan_id = sset.scan.scan_id + try: + gpsm = sset.solution_for(gp) + if gpsm.q_value > q_value_threshold: + continue + adduct = gpsm.mass_shift.name + scan = ms_reader.get_scan_by_id(scan_id) + z = scan.precursor_information.charge + tracks[ClusterSpec(z, adduct)].append(scan) + except KeyError: + continue + gp_str = gp.glycopeptide_sequence + for key, track in tracks.items(): + cluster = SpectrumCluster(track) + sim = cluster.average_similarity() + rec = ClusterResult(gp_str, *key, sim, len(track)) + writer.writerow(rec._asdict()) + + + +if __name__ == ""__main__"": + main.main()","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_glycan_prebuilt.py",".py","1343","43","import unittest +import tempfile + + +from glycresoft import serialize + +from glycresoft.database.prebuilt import biosynthesis_human_n_linked + + +class GlycanCombinatoricsTests(unittest.TestCase): + def setup_tempfile(self): + file_name = tempfile.mktemp() + '.tmp' + open(file_name, 'w').write('') + return file_name + + def clear_file(self, path): + open(path, 'wb') + + def setup_compositions(self, database_path, **kwargs): + builder = biosynthesis_human_n_linked.BiosynthesisHumanNGlycansBuilder() + result = builder.build(database_path, **kwargs) + return result + + def test_prebuilt_native(self): + path = self.setup_tempfile() + hypothesis_builder = self.setup_compositions(path) + glycan_count = hypothesis_builder.query(serialize.GlycanComposition).count() + self.assertEqual(448, glycan_count) + hypothesis_builder.close() + self.clear_file(path) + + def test_prebuilt_permethylated(self): + path = self.setup_tempfile() + hypothesis_builder = self.setup_compositions(path, derivatization='methyl') + glycan_count = hypothesis_builder.query(serialize.GlycanComposition).count() + self.assertEqual(448, glycan_count) + hypothesis_builder.close() + self.clear_file(path) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_rt_model.py",".py","3997","92","import unittest + +import glycopeptidepy + +from glypy.structure.glycan_composition import HashableGlycanComposition + +from glycresoft.chromatogram_tree.mass_shift import Unmodified, Ammonium +from glycresoft.scoring.elution_time_grouping.structure import ChromatogramProxy, GlycopeptideChromatogramProxy +from glycresoft.scoring.elution_time_grouping.reviser import IsotopeRule + + +class TestChromatogramProxy(unittest.TestCase): + def _create_instance(self) -> ChromatogramProxy: + gc = HashableGlycanComposition(Hex=5, HexNAc=4, NeuAc=2, Fuc=1) + return ChromatogramProxy(gc.mass(), 25.0, 1e6, gc, None, [Unmodified, Ammonium]) + + def test_apex_time(self): + proxy = self._create_instance() + self.assertAlmostEqual(proxy.apex_time, 25.0, 3) + + def test_weight(self): + proxy = self._create_instance() + assert proxy.weight == 1.0 + + def test_copy(self): + proxy = self._create_instance() + assert proxy == proxy.copy() + + def test_shift_glycan(self): + proxy = self._create_instance() + new = proxy.shift_glycan_composition(HashableGlycanComposition(Fuc=2, NeuAc=-1)) + assert new.glycan_composition == HashableGlycanComposition( + Hex=5, HexNAc=4, NeuAc=1, Fuc=3) + + +class TestGlycopeptideChromatogramProxy(TestChromatogramProxy): + def _create_instance(self) -> GlycopeptideChromatogramProxy: + gc = HashableGlycanComposition(Hex=5, HexNAc=4, NeuAc=2, Fuc=1) + glycopeptide = glycopeptidepy.parse(""NEEYN(N-Glycosylation)K"" + str(gc)) + inst = GlycopeptideChromatogramProxy(glycopeptide.total_mass, 25.0, 1e6, gc, None, [Unmodified, Ammonium], structure=glycopeptide) + assert inst.structure == glycopeptide + return inst + + def test_shift_glycan(self): + proxy = self._create_instance() + new = proxy.shift_glycan_composition( + HashableGlycanComposition(Fuc=2, NeuAc=-1)) + assert new.glycan_composition == HashableGlycanComposition( + Hex=5, HexNAc=4, NeuAc=1, Fuc=3) + assert new.structure == glycopeptidepy.parse( + ""NEEYN(N-Glycosylation)K"" + str(new.glycan_composition)) + assert new.kwargs['original_structure'] == str(proxy.structure) + + +class TestRevisionRule(unittest.TestCase): + def _create_instance(self) -> GlycopeptideChromatogramProxy: + gc = HashableGlycanComposition(Hex=5, HexNAc=4, NeuAc=1, Fuc=3) + glycopeptide = glycopeptidepy.parse(""NEEYN(N-Glycosylation)K"" + str(gc)) + inst = GlycopeptideChromatogramProxy(glycopeptide.total_mass, 25.0, 1e6, gc, None, [Unmodified, Ammonium], structure=glycopeptide) + assert inst.structure == glycopeptide + return inst + + def test_apply(self): + proxy = self._create_instance() + rule = IsotopeRule.clone() + new = rule(proxy) + assert new.glycan_composition == HashableGlycanComposition( + Hex=5, HexNAc=4, NeuAc=2, Fuc=1) + assert new.structure == glycopeptidepy.parse( + ""NEEYN(N-Glycosylation)K"" + str(new.glycan_composition)) + assert new.kwargs['original_structure'] == str(proxy.structure) + + def test_apply_with_cache(self): + proxy = self._create_instance() + rule = IsotopeRule.with_cache() + new = rule(proxy) + assert new.glycan_composition == HashableGlycanComposition( + Hex=5, HexNAc=4, NeuAc=2, Fuc=1) + assert new.structure == glycopeptidepy.parse( + ""NEEYN(N-Glycosylation)K"" + str(new.glycan_composition)) + assert new.kwargs['original_structure'] == str(proxy.structure) + + new2 = rule(proxy) + assert new2.glycan_composition == HashableGlycanComposition( + Hex=5, HexNAc=4, NeuAc=2, Fuc=1) + assert new2.structure == glycopeptidepy.parse( + ""NEEYN(N-Glycosylation)K"" + str(new.glycan_composition)) + assert new2.kwargs['original_structure'] == str(proxy.structure) + + assert new2 is not new + assert new2.structure is not new.structure +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_constrained_combinatorics.py",".py","2830","112","import unittest +import tempfile + +from io import StringIO + +from glycresoft.database.builder.glycan import constrained_combinatorics + + +FILE_SOURCE = '''Hex 3 12 +HexNAc 2 10 +Fuc 0 5 +Neu5Ac 0 4 + +Fuc < HexNAc +HexNAc > NeuAc + 1 +''' # The mismatch between Neu5Ac <-> NeuAc tests the IUPAC normalization mechanism + + +FILE_SOURCE2 = '''Hex 3 12 +HexNAc 2 10 +Fuc 0 5 +Neu5Ac 0 4 + +Fuc < HexNAc +HexNAc - 1 > NeuAc +''' + +FILE_SOURCE3 = '''Hex 3 12 +HexNAc 2 10 +Fuc 0 5 +Neu5Ac 0 4 + +Fuc < HexNAc +NeuAc < HexNAc - 1 +''' + +FILE_SOURCE4 = '''Hex 3 12 +HexNAc 2 10 +Fuc 0 5 +Neu5Ac 0 4 + +Fuc < HexNAc +NeuAc < HexNAc +''' + + +class GlycanCombinatoricsTests(unittest.TestCase): + + def setup_tempfile(self): + file_name = tempfile.mktemp() + file_name += '.tmp' + open(file_name, 'w').write(FILE_SOURCE) + return file_name + + def clear_file(self, path): + open(path, 'wb').close() + + def test_run(self): + file_name = self.setup_tempfile() + builder = constrained_combinatorics.CombinatorialGlycanHypothesisSerializer( + file_name, file_name + '.db') + builder.run() + inst = builder.query(constrained_combinatorics.DBGlycanComposition).filter( + constrained_combinatorics.DBGlycanComposition.hypothesis_id == builder.hypothesis_id, + constrained_combinatorics.DBGlycanComposition.composition == ""{Hex:3; HexNAc:2}"").one() + self.assertAlmostEqual(inst.calculated_mass, 910.32777, 3) + + self.do_neuac_check(builder) + + builder.engine.dispose() + self.clear_file(file_name + '.db') + self.clear_file(file_name) + + def do_neuac_check(self, builder): + i = 0 + for composition in builder.query(constrained_combinatorics.DBGlycanComposition): + composition = composition.convert() + i += 1 + self.assertGreater(composition[""HexNAc""] - 1, composition['Neu5Ac']) + + +class GlycanCombinatoricsTestsWithReversedTermInConditional(GlycanCombinatoricsTests): + + def setup_tempfile(self): + file_name = tempfile.mktemp() + open(file_name, 'w').write(FILE_SOURCE2) + return file_name + + +class GlycanCombinatoricsTestsWithReversedConditional(GlycanCombinatoricsTests): + + def setup_tempfile(self): + file_name = tempfile.mktemp() + open(file_name, 'w').write(FILE_SOURCE3) + return file_name + + +class GlycanCombinatoricsTestsWithoutSubtractionInConditional(GlycanCombinatoricsTests): + + def setup_tempfile(self): + file_name = tempfile.mktemp() + open(file_name, 'w').write(FILE_SOURCE4) + return file_name + + def do_neuac_check(self, builder): + self.assertRaises(AssertionError, lambda: super( + GlycanCombinatoricsTestsWithoutSubtractionInConditional, self).do_neuac_check(builder)) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_glycopeptide_search.py",".py","7727","234","import unittest +import traceback + +from lxml import html +from click.testing import Result, CliRunner + +from glycresoft import serialize +from glycresoft.cli.analyze import ( + search_glycopeptide, + search_glycopeptide_multipart, +) + +from .fixtures import get_test_data + + +class _GlycopeptideSearchToolBase: + mzml_path: str + classic_result_db: str + indexed_result_db: str + + classic_search_db: str = get_test_data(""agp.db"") + + indexed_search_db: str = get_test_data(""agp_indexed.db"") + indexed_decoy_search_db: str = get_test_data(""agp_indexed_decoy.db"") + + indexed_gp_csv_headers = [ + ""glycopeptide"", + ""analysis"", + ""neutral_mass"", + ""mass_accuracy"", + ""ms1_score"", + ""ms2_score"", + ""q_value"", + ""total_signal"", + ""start_time"", + ""end_time"", + ""apex_time"", + ""charge_states"", + ""msms_count"", + ""peptide_start"", + ""peptide_end"", + ""protein_name"", + ""mass_shifts"", + ""predicted_apex_interval_start"", + ""predicted_apex_interval_end"", + ""retention_time_score"", + ""group_id"", + ""glycopeptide_score"", + ""peptide_score"", + ""glycan_score"", + ""glycan_coverage"", + ""total_q_value"", + ""peptide_q_value"", + ""glycan_q_value"", + ""glycopeptide_q_value"", + ""localizations"", + ""n_glycosylation_sites"", + ""missed_cleavages"", + ] + + indexed_gpsm_csv_header = [ + ""glycopeptide"", + ""analysis"", + ""neutral_mass"", + ""mass_accuracy"", + ""mass_shift_name"", + ""scan_id"", + ""scan_time"", + ""charge"", + ""ms2_score"", + ""q_value"", + ""precursor_abundance"", + ""peptide_start"", + ""peptide_end"", + ""protein_name"", + ""is_best_match"", + ""is_precursor_fit"", + ""rank"", + ""group_id"", + ""peptide_score"", + ""glycan_score"", + ""glycan_coverage"", + ""peptide_q_value"", + ""glycan_q_value"", + ""glycopeptide_q_value"", + ""localizations"", + ""n_glycosylation_sites"", + ""precursor_scan_id"", + ""precursor_activation"", + ""missed_cleavages"", + ] + + gp_csv_suffix = ""-glycopeptides.csv"" + gpsm_csv_suffix = ""-glycopeptide-spectrum-matches.csv"" + html_report_suffix = ""-report.html"" + + def parse_html_report(self, html_path: str): + tree = html.parse(html_path) + n_prots = len(tree.findall( + "".//section[@id='protein-table-container']/table/tbody/tr"")) + n_gps = len(tree.xpath( + "".//*[@class and contains(concat(' ', normalize-space(@class), ' '), ' glycopeptide-detail-table-row ')]"")) + return n_prots, n_gps + + def evaluate_classic_search(self, result: Result, output_file: str): + if result.exit_code != 0: + print(f""Exit Code {result.exit_code}"") + print(f""Exit Code {traceback.format_exception(*result.exc_info)}"") + print(result.output) + assert result.exit_code == 0 + db = serialize.DatabaseBoundOperation(output_file) + ref_db = serialize.DatabaseBoundOperation(self.classic_result_db) + + for model_tp in [ + serialize.Glycopeptide, + serialize.Peptide, + serialize.Protein, + serialize.GlycanComposition, + serialize.GlycopeptideSpectrumSolutionSet, + serialize.IdentifiedGlycopeptide, + ]: + assert db.query(model_tp).count() == ref_db.query(model_tp).count() + + prefix = output_file.rsplit(""."", 1)[0] + + html_path = prefix + self.html_report_suffix + n_prots, n_gps = self.parse_html_report(html_path) + + id_n_prots = db.query(serialize.Protein).join( + serialize.Glycopeptide).join( + serialize.IdentifiedGlycopeptide).group_by( + serialize.Protein.id).count() + assert n_prots == id_n_prots + + id_n_gps = db.query(serialize.IdentifiedGlycopeptide).count() + assert id_n_gps == n_gps + + def evaluate_indexed_search(self, result: Result, output_file: str): + if result.exit_code != 0: + print(f""Exit Code {result.exit_code}"") + print(f""Exit Code {traceback.format_exception(*result.exc_info)}"") + print(result.output) + assert result.exit_code == 0 + db = serialize.DatabaseBoundOperation(output_file) + ref_db = serialize.DatabaseBoundOperation(self.indexed_result_db) + + for model_tp in [ + serialize.Glycopeptide, + serialize.Peptide, + serialize.Protein, + serialize.GlycanComposition, + serialize.GlycopeptideSpectrumMatch, + serialize.GlycopeptideSpectrumSolutionSet, + serialize.IdentifiedGlycopeptide, + ]: + assert db.query(model_tp).count() == ref_db.query(model_tp).count() + + prefix = output_file.rsplit(""."", 1)[0] + + html_path = prefix + self.html_report_suffix + n_prots, n_gps = self.parse_html_report(html_path) + + id_n_prots = db.query(serialize.Protein).join( + serialize.Glycopeptide).join( + serialize.IdentifiedGlycopeptide).group_by( + serialize.Protein.id).count() + assert n_prots == id_n_prots + + id_n_gps = db.query(serialize.IdentifiedGlycopeptide).count() + assert id_n_gps == n_gps + + with open(prefix + self.gp_csv_suffix, 'rt') as fh: + headers = fh.readline().strip().split("","") + assert set(headers) <= set(self.indexed_gp_csv_headers) + + with open(prefix + self.gpsm_csv_suffix, 'rt') as fh: + headers = fh.readline().strip().split("","") + assert set(headers) <= set(self.indexed_gpsm_csv_header) + + def test_classic_search(self): + runner = CliRunner() + with runner.isolated_filesystem() as _dir_man: + result = runner.invoke( + search_glycopeptide, + [ + ""-o"", + ""./classic_agp_search.db"", + self.classic_search_db, + self.mzml_path, + ""1"", + ""--export"", + ""csv"", + ""--export"", + ""html"", + ""--export"", + ""psm-csv"", + ], + ) + self.evaluate_classic_search(result, ""./classic_agp_search.db"") + + def test_indexed_search(self): + runner = CliRunner() + with runner.isolated_filesystem() as _dir_man: + result = runner.invoke( + search_glycopeptide_multipart, + [ + ""-o"", + ""./indexed_agp_search.db"", + ""-M"", + ""--export"", + ""csv"", + ""--export"", + ""html"", + ""--export"", + ""psm-csv"", + self.indexed_search_db, + self.indexed_decoy_search_db, + self.mzml_path, + ], + ) + self.evaluate_indexed_search(result, ""./indexed_agp_search.db"") + + +class TestGlycopeptideSearchTool(_GlycopeptideSearchToolBase, unittest.TestCase): + mzml_path = get_test_data(""20150710_3um_AGP_001_29_30.preprocessed.mzML"") + classic_result_db = get_test_data(""classic_agp_search.db"") + indexed_result_db = get_test_data(""indexed_agp_search.db"") + + +class TestGlycopeptideSearchToolNoMS2(_GlycopeptideSearchToolBase, unittest.TestCase): + mzml_path = get_test_data(""AGP_Glycomics_20150930_06.deconvoluted.mzML"") + classic_result_db = get_test_data(""classic_agp_search_empty.db"") + indexed_result_db = get_test_data(""indexed_agp_search_empty.db"") +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_composition_network.py",".py","7160","201","import unittest + +import glypy +import pickle + +from textwrap import dedent +from io import BytesIO + +from glycresoft.database import composition_network +from glycresoft.database.builder.glycan import constrained_combinatorics + +compositions = [ + glypy.glycan_composition.FrozenGlycanComposition(HexNAc=2, Hex=i) for i in range(3, 10) +] + [ + glypy.glycan_composition.FrozenGlycanComposition(HexNAc=4, Hex=5, NeuAc=2), + glypy.glycan_composition.FrozenGlycanComposition(HexNAc=3, Hex=5), +] + + +_PERMETHYLATED_COMPOSITIONS = '''{Fuc^Me:1; Hex^Me:6; HexNAc^Me:5; Neu5NAc^Me:3}$C1H4 +{Fuc^Me:2; Hex^Me:6; HexNAc^Me:5}$C1H4 +{Fuc^Me:2; Hex^Me:6; HexNAc^Me:5; Neu5NAc^Me:2}$C1H4 +{Fuc^Me:2; Hex^Me:6; HexNAc^Me:5; Neu5NAc^Me:3}$C1H4 +{Fuc^Me:3; Hex^Me:6; HexNAc^Me:5; Neu5NAc^Me:2}$C1H4 +{Fuc^Me:1; Hex^Me:3; HexNAc^Me:5}$C1H4 +{Fuc^Me:2; Hex^Me:7; HexNAc^Me:8}$C1H4 +{Hex^Me:6; HexNAc^Me:8; Neu5NAc^Me:1}$C1H4 +{Fuc^Me:1; Hex^Me:3; HexNAc^Me:3}$C1H4 +{Hex^Me:8; HexNAc^Me:3; Neu5NAc^Me:1}$C1H4 +{Fuc^Me:1; Hex^Me:8; HexNAc^Me:3; Neu5NAc^Me:1}$C1H4 +{Fuc^Me:2; Hex^Me:7; HexNAc^Me:4}$C1H4 +{Fuc^Me:3; Hex^Me:7; HexNAc^Me:4}$C1H4 +{Hex^Me:7; HexNAc^Me:5; Neu5NAc^Me:3}$C1H4 +{Fuc^Me:1; Hex^Me:7; HexNAc^Me:5; Neu5NAc^Me:2}$C1H4 +{Fuc^Me:2; Hex^Me:7; HexNAc^Me:5; Neu5NAc^Me:2}$C1H4 +{Fuc^Me:1; Hex^Me:4; HexNAc^Me:4}$C1H4 +{Fuc^Me:3; Hex^Me:4; HexNAc^Me:4; Neu5NAc^Me:1}$C1H4 +{Fuc^Me:3; Hex^Me:4; HexNAc^Me:6; Neu5NAc^Me:1}$C1H4 +{Hex^Me:5; HexNAc^Me:4}$C1H4 +{Hex^Me:5; HexNAc^Me:4; Neu5NAc^Me:2}$C1H4 +{Fuc^Me:1; Hex^Me:5; HexNAc^Me:4; Neu5NAc^Me:1}$C1H4 +{Fuc^Me:1; Hex^Me:5; HexNAc^Me:4; Neu5NAc^Me:2}$C1H4 +{Hex^Me:5; HexNAc^Me:5; Neu5NAc^Me:1}$C1H4 +{Fuc^Me:1; Hex^Me:5; HexNAc^Me:5; Neu5NAc^Me:1}$C1H4 +{Fuc^Me:1; Hex^Me:5; HexNAc^Me:5; Neu5NAc^Me:3}$C1H4 +{Hex^Me:5; HexNAc^Me:7}$C1H4 +{Fuc^Me:1; Hex^Me:5; HexNAc^Me:7}$C1H4 +{Fuc^Me:1; Hex^Me:6; HexNAc^Me:4; Neu5NAc^Me:1}$C1H4 +{Fuc^Me:2; Hex^Me:6; HexNAc^Me:4; Neu5NAc^Me:1}$C1H4 +{Hex^Me:6; HexNAc^Me:5; Neu5NAc^Me:3}$C1H4 +'''.splitlines() + + +class NeighborhoodWalkerTest(unittest.TestCase): + + def make_human_definition_buffer(self): + text = b'''Hex 3 10 +HexNAc 2 9 +Fuc 0 5 +NeuAc 0 5 + +Fuc < HexNAc +HexNAc > NeuAc + 1''' + buff = BytesIO() + buff.write(text) + buff.seek(0) + return buff + + def make_mammalian_definition_buffer(self): + text = b'''Hex 3 10 +HexNAc 2 9 +Fuc 0 5 +NeuAc 0 5 +NeuGc 0 5 + +Fuc < HexNAc +HexNAc > (NeuAc + NeuGc) + 1''' + buff = BytesIO() + buff.write(text) + buff.seek(0) + return buff + + def generate_compositions(self, rule_buffer): + rules, constraints = constrained_combinatorics.parse_rules_from_file( + rule_buffer) + compositions = list(constrained_combinatorics.CombinatoricCompositionGenerator( + rules_table=rules, constraints=constraints)) + # strip out glycan classes + compositions = [c[0] for c in compositions] + return compositions + + def test_human_network(self): + rules_buffer = self.make_human_definition_buffer() + compositions = self.generate_compositions(rules_buffer) + g = composition_network.CompositionGraph(compositions) + self.assertEqual(len(g), 1424) + walker = composition_network.NeighborhoodWalker(g) + + neighborhood_sizes = { + ""tri-antennary"": 188, + ""bi-antennary"": 104, + ""asialo-bi-antennary"": 96, + ""tetra-antennary"": 276, + ""hybrid"": 80, + # ""over-extended"": 170, + ""asialo-tri-antennary"": 60, + ""penta-antennary"": 336, + ""asialo-penta-antennary"": 72, + ""high-mannose"": 16, + ""asialo-tetra-antennary"": 68} + for k, v in neighborhood_sizes.items(): + self.assertEqual(v, len(walker.neighborhood_maps[k]), ""%s had %d members, not %d"" % ( + k, len(walker.neighborhood_maps[k]), v)) + + def test_mammalian_network(self): + rules_buffer = self.make_mammalian_definition_buffer() + compositions = self.generate_compositions(rules_buffer) + g = composition_network.CompositionGraph(compositions) + self.assertEqual(len(g), 5096) + + walker = composition_network.NeighborhoodWalker(g) + + neighborhood_sizes = { + 'tri-antennary': 408, + 'bi-antennary': 180, + 'asialo-bi-antennary': 144, + 'tetra-antennary': 720, + 'hybrid': 140, + # 'over-extended': 363, + 'asialo-tri-antennary': 60, + 'penta-antennary': 1080, + 'asialo-penta-antennary': 72, + 'high-mannose': 16, + 'asialo-tetra-antennary': 68, + } + for k, v in neighborhood_sizes.items(): + self.assertEqual(v, len(walker.neighborhood_maps[k]), ""%s had %d members, not %d"" % ( + k, len(walker.neighborhood_maps[k]), v)) + + +class CompositionGraphTest(unittest.TestCase): + + def test_construction(self): + g = composition_network.CompositionGraph(compositions) + self.assertTrue(len(g) == 9) + self.assertTrue(len(g.edges) == 0) + g.create_edges(1) + self.assertTrue(len(g.edges) == 7) + + def test_index(self): + g = composition_network.CompositionGraph(compositions) + node = g[""{Hex:5; HexNAc:2}""] + self.assertTrue(node.glycan_composition[""Hex""] == 5) + self.assertTrue(node.glycan_composition[""HexNAc""] == 2) + i = node.index + self.assertEqual(g[i], node) + + def test_bridge(self): + g = composition_network.CompositionGraph(compositions) + g.create_edges(1) + for edge in g.edges: + self.assertTrue(edge.order < 2) + node_to_remove = g[""{Hex:5; HexNAc:2}""] + removed_edges = g.remove_node(node_to_remove) + neighbors = [e[node_to_remove] for e in removed_edges] + assert len(neighbors) == 3 + n_order_2_edges = 0 + for edge in g.edges: + if edge.order == 2: + self.assertTrue( + edge.node1 in neighbors and edge.node2 in neighbors) + n_order_2_edges += 1 + self.assertTrue(n_order_2_edges > 0) + node_to_remove = g[""{Hex:6; HexNAc:2}""] + removed_edges = g.remove_node(node_to_remove) + neighbors = [e[node_to_remove] for e in removed_edges] + assert len(neighbors) == 3 + for edge in g.edges: + if edge.order == 3: + self.assertTrue( + edge.node1 in neighbors and edge.node2 in neighbors) + + def test_pickle(self): + g = composition_network.CompositionGraph(compositions) + g.create_edges(1) + self.assertEqual(g, pickle.loads(pickle.dumps(g))) + + def test_clone(self): + g = composition_network.CompositionGraph(compositions) + g.create_edges(1) + self.assertEqual(g, g.clone()) + + def test_normalize(self): + g = composition_network.CompositionGraph(_PERMETHYLATED_COMPOSITIONS) + self.assertIsNotNone(g[""{Fuc:1; Hex:6; HexNAc:5; Neu5Ac:3}""]) + self.assertEqual(g[""{Fuc^Me:1; Hex^Me:6; HexNAc^Me:5; Neu5Ac^Me:3}$C1H4""], g[""{Fuc:1; Hex:6; HexNAc:5; Neu5Ac:3}""]) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_fasta_glycopeptide.py",".py","13370","287","import unittest +import tempfile +import warnings + +from glycresoft.serialize.hypothesis.peptide import Peptide, Protein, Glycopeptide +from glycresoft.database.builder.glycopeptide import naive_glycopeptide +from glycresoft.database.builder.glycan import ( + TextFileGlycanHypothesisSerializer, + CombinatorialGlycanHypothesisSerializer) +from glycresoft import serialize +from . import fixtures + +from .test_constrained_combinatorics import FILE_SOURCE as GLYCAN_RULE_FILE_SOURCE + +from glycopeptidepy.structure import modification + + +FASTA_FILE_SOURCE = """""" +>sp|P02763|A1AG1_HUMAN Alpha-1-acid glycoprotein 1 OS=Homo sapiens GN=ORM1 PE=1 SV=1 +MALSWVLTVLSLLPLLEAQIPLCANLVPVPITNATLDQITGKWFYIASAFRNEEYNKSVQ +EIQATFFYFTPNKTEDTIFLREYQTRQDQCIYNTTYLNVQRENGTISRYVGGQEHFAHLL +ILRDTKTYMLAFDVNDEKNWGLSVYADKPETTKEQLGEFYEALDCLRIPKSDVVYTDWKK +DKCEPLEKQHEKERKQEEGES + +>sp|P19652|A1AG2_HUMAN Alpha-1-acid glycoprotein 2 OS=Homo sapiens GN=ORM2 PE=1 SV=2 +MALSWVLTVLSLLPLLEAQIPLCANLVPVPITNATLDRITGKWFYIASAFRNEEYNKSVQ +EIQATFFYFTPNKTEDTIFLREYQTRQNQCFYNSSYLNVQRENGTVSRYEGGREHVAHLL +FLRDTKTLMFGSYLDDEKNWGLSFYADKPETTKEQLGEFYEALDCLCIPRSDVMYTDWKK +DKCEPLEKQHEKERKQEEGES +"""""" + +HEPARANASE = """""" +>sp|Q9Y251|HPSE_HUMAN Heparanase OS=Homo sapiens GN=HPSE PE=1 SV=2 +MLLRSKPALPPPLMLLLLGPLGPLSPGALPRPAQAQDVVDLDFFT +QEPLHLVSPSFLSVTIDANLATDPRFLILLGSPKLRTLARGLSPA +YLRFGGTKTDFLIFDPKKESTFEERSYWQSQVNQDICKYGSIPPD +VEEKLRLEWPYQEQLLLREHYQKKFKNSTYSRSSVDVLYTFANCS +GLDLIFGLNALLRTADLQWNSSNAQLLLDYCSSKGYNISWELGNE +PNSFLKKADIFINGSQLGEDFIQLHKLLRKSTFKNAKLYGPDVGQ +PRRKTAKMLKSFLKAGGEVIDSVTWHHYYLNGRTATKEDFLNPDV +LDIFISSVQKVFQVVESTRPGKKVWLGETSSAYGGGAPLLSDTFA +AGFMWLDKLGLSARMGIEVVMRQVFFGAGNYHLVDENFDPLPDYW +LSLLFKKLVGTKVLMASVQGSKRRKLRVYLHCTNTDNPRYKEGDL +TLYAINLHNVTKYLRLPYPFSNKQVDKYLLRPLGPHGLLSKSVQL +NGLTLKMVDDQTLPPLMEKPLRPGSSLGLPAFSYSFFVIRNAKVA +ACI +"""""" + +VERSICAN = """""" +>sp|P13611|CSPG2_HUMAN Versican core protein OS=Homo sapiens GN=VCAN PE=1 SV=3 +MFINIKSILWMCSTLIVTHALHKVKVGKSPPVRGSLSGKVSLPCHFSTMPTLPPSYNTSEFLRIKWSKIEVDKNGKDLKETTVLVAQNGN +IKIGQDYKGRVSVPTHPEAVGDASLTVVKLLASDAGLYRCDVMYGIEDTQDTVSLTVDGVVFHYRAATSRYTLNFEAAQKACLDVGAVIA +TPEQLFAAYEDGFEQCDAGWLADQTVRYPIRAPRVGCYGDKMGKAGVRTYGFRSPQETYDVYCYVDHLDGDVFHLTVPSKFTFEEAAKEC +ENQDARLATVGELQAAWRNGFDQCDYGWLSDASVRHPVTVARAQCGGGLLGVRTLYRFENQTGFPPPDSRFDAYCFKPKEATTIDLSILA +ETASPSLSKEPQMVSDRTTPIIPLVDELPVIPTEFPPVGNIVSFEQKATVQPQAITDSLATKLPTPTGSTKKPWDMDDYSPSASGPLGKL +DISEIKEEVLQSTTGVSHYATDSWDGVVEDKQTQESVTQIEQIEVGPLVTSMEILKHIPSKEFPVTETPLVTARMILESKTEKKMVSTVS +ELVTTGHYGFTLGEEDDEDRTLTVGSDESTLIFDQIPEVITVSKTSEDTIHTHLEDLESVSASTTVSPLIMPDNNGSSMDDWEERQTSGR +ITEEFLGKYLSTTPFPSQHRTEIELFPYSGDKILVEGISTVIYPSLQTEMTHRRERTETLIPEMRTDTYTDEIQEEITKSPFMGKTEEEV +FSGMKLSTSLSEPIHVTESSVEMTKSFDFPTLITKLSAEPTEVRDMEEDFTATPGTTKYDENITTVLLAHGTLSVEAATVSKWSWDEDNT +TSKPLESTEPSASSKLPPALLTTVGMNGKDKDIPSFTEDGADEFTLIPDSTQKQLEEVTDEDIAAHGKFTIRFQPTTSTGIAEKSTLRDS +TTEEKVPPITSTEGQVYATMEGSALGEVEDVDLSKPVSTVPQFAHTSEVEGLAFVSYSSTQEPTTYVDSSHTIPLSVIPKTDWGVLVPSV +PSEDEVLGEPSQDILVIDQTRLEATISPETMRTTKITEGTTQEEFPWKEQTAEKPVPALSSTAWTPKEAVTPLDEQEGDGSAYTVSEDEL +LTGSERVPVLETTPVGKIDHSVSYPPGAVTEHKVKTDEVVTLTPRIGPKVSLSPGPEQKYETEGSSTTGFTSSLSPFSTHITQLMEETTT +EKTSLEDIDLGSGLFEKPKATELIEFSTIKVTVPSDITTAFSSVDRLHTTSAFKPSSAITKKPPLIDREPGEETTSDMVIIGESTSHVPP +TTLEDIVAKETETDIDREYFTTSSPPATQPTRPPTVEDKEAFGPQALSTPQPPASTKFHPDINVYIIEVRENKTGRMSDLSVIGHPIDSE +SKEDEPCSEETDPVHDLMAEILPEFPDIIEIDLYHSEENEEEEEECANATDVTTTPSVQYINGKHLVTTVPKDPEAAEARRGQFESVAPS +QNFSDSSESDTHPFVIAKTELSTAVQPNESTETTESLEVTWKPETYPETSEHFSGGEPDVFPTVPFHEEFESGTAKKGAESVTERDTEVG +HQAHEHTEPVSLFPEESSGEIAIDQESQKIAFARATEVTFGEEVEKSTSVTYTPTIVPSSASAYVSEEEAVTLIGNPWPDDLLSTKESWV +EATPRQVVELSGSSSIPITEGSGEAEEDEDTMFTMVTDLSQRNTTDTLITLDTSRIITESFFEVPATTIYPVSEQPSAKVVPTKFVSETD +TSEWISSTTVEEKKRKEEEGTTGTASTFEVYSSTQRSDQLILPFELESPNVATSSDSGTRKSFMSLTTPTQSEREMTDSTPVFTETNTLE +NLGAQTTEHSSIHQPGVQEGLTTLPRSPASVFMEQGSGEAAADPETTTVSSFSLNVEYAIQAEKEVAGTLSPHVETTFSTEPTGLVLSTV +MDRVVAENITQTSREIVISERLGEPNYGAEIRGFSTGFPLEEDFSGDFREYSTVSHPIAKEETVMMEGSGDAAFRDTQTSPSTVPTSVHI +SHISDSEGPSSTMVSTSAFPWEEFTSSAEGSGEQLVTVSSSVVPVLPSAVQKFSGTASSIIDEGLGEVGTVNEIDRRSTILPTAEVEGTK +APVEKEEVKVSGTVSTNFPQTIEPAKLWSRQEVNPVRQEIESETTSEEQIQEEKSFESPQNSPATEQTIFDSQTFTETELKTTDYSVLTT +KKTYSDDKEMKEEDTSLVNMSTPDPDANGLESYTTLPEATEKSHFFLATALVTESIPAEHVVTDSPIKKEESTKHFPKGMRPTIQESDTE +LLFSGLGSGEEVLPTLPTESVNFTEVEQINNTLYPHTSQVESTSSDKIEDFNRMENVAKEVGPLVSQTDIFEGSGSVTSTTLIEILSDTG +AEGPTVAPLPFSTDIGHPQNQTVRWAEEIQTSRPQTITEQDSNKNSSTAEINETTTSSTDFLARAYGFEMAKEFVTSAPKPSDLYYEPSG +EGSGEVDIVDSFHTSATTQATRQESSTTFVSDGSLEKHPEVPSAKAVTADGFPTVSVMLPLHSEQNKSSPDPTSTLSNTVSYERSTDGSF +QDRFREFEDSTLKPNRKKPTENIIIDLDKEDKDLILTITESTILEILPELTSDKNTIIDIDHTKPVYEDILGMQTDIDTEVPSEPHDSND +ESNDDSTQVQEIYEAAVNLSLTEETFEGSADVLASYTQATHDESMTYEDRSQLDHMGFHFTTGIPAPSTETELDVLLPTATSLPIPRKSA +TVIPEIEGIKAEAKALDDMFESSTLSDGQAIADQSEIIPTLGQFERTQEEYEDKKHAGPSFQPEFSSGAEEALVDHTPYLSIATTHLMDQ +SVTEVPDVMEGSNPPYYTDTTLAVSTFAKLSSQTPSSPLTIYSGSEASGHTEIPQPSALPGIDVGSSVMSPQDSFKEIHVNIEATFKPSS +EEYLHITEPPSLSPDTKLEPSEDDGKPELLEEMEASPTELIAVEGTEILQDFQNKTDGQVSGEAIKMFPTIKTPEAGTVITTADEIELEG +ATQWPHSTSASATYGVEAGVVPWLSPQTSERPTLSSSPEINPETQAALIRGQDSTIAASEQQVAARILDSNDQATVNPVEFNTEVATPPF +SLLETSNETDFLIGINEESVEGTAIYLPGPDRCKMNPCLNGGTCYPTETSYVCTCVPGYSGDQCELDFDECHSNPCRNGATCVDGFNTFR +CLCLPSYVGALCEQDTETCDYGWHKFQGQCYKYFAHRRTWDAAERECRLQGAHLTSILSHEEQMFVNRVGHDYQWIGLNDKMFEHDFRWT +DGSTLQYENWRPNQPDSFFSAGEDCVVIIWHENGQWNDVPCNYHLTYTCKKGTVACGQPPVVENAKTFGKMKPRYEINSLIRYHCKDGFI +QRHLPTIRCLGNGRWAIPKITCMNPSAYQRTYSMKYFKNSSSAKDNSINTSKHDHRWSRRWQESRR +"""""" + +o_glycans = """""" +{Hex:1; HexNAc:1; Neu5Ac:2} O-Glycan +"""""" + +simple_n_glycans = """""" +{Hex:5; HexNAc:2} N-Glycan +"""""" + +decorin = """""" +>sp|P21793|PGS2_BOVIN Decorin +MKATIIFLLVAQVSWAGPFQQKGLFDFMLEDEASGIGPEEHFPEVPEIEPMGPVCPFRCQ +CHLRVVQCSDLGLEKVPKDLPPDTALLDLQNNKITEIKDGDFKNLKNLHTLILINNKISK +ISPGAFAPLVKLERLYLSKNQLKELPEKMPKTLQELRVHENEITKVRKSVFNGLNQMIVV +ELGTNPLKSSGIENGAFQGMKKLSYIRIADTNITTIPQGLPPSLTELHLDGNKITKVDAA +SLKGLNNLAKLGLSFNSISAVDNGSLANTPHLRELHLNNNKLVKVPGGLADHKYIQVVYL +HNNNISAIGSNDFCPPGYNTKKASYSGVSLFSNPVQYWEIQPSTFRCVYVRAAVQLGNYK +"""""" + +constant_modifications = [""Carbamidomethyl (C)""] +variable_modifications = [""Deamidation (N)"", ""Pyro-glu from Q (Q@N-term)""] + + +mt = modification.RestrictedModificationTable( + constant_modifications=constant_modifications, + variable_modifications=variable_modifications) + +variable_modifications = [mt[v] for v in variable_modifications] +constant_modifications = [mt[c] for c in constant_modifications] + + +class FastaGlycopeptideTests(unittest.TestCase): + + def setup_tempfile(self, source): + file_name = tempfile.mktemp() + '.tmp' + open(file_name, 'w').write(source) + return file_name + + def clear_file(self, path): + open(path, 'wb') + + def test_build_hypothesis(self): + glycan_file = self.setup_tempfile(GLYCAN_RULE_FILE_SOURCE) + fasta_file = self.setup_tempfile(FASTA_FILE_SOURCE) + db_file = fasta_file + '.db' + + glycan_builder = CombinatorialGlycanHypothesisSerializer(glycan_file, db_file) + glycan_builder.start() + + glycopeptide_builder = naive_glycopeptide.MultipleProcessFastaGlycopeptideHypothesisSerializer( + fasta_file, db_file, glycan_builder.hypothesis_id, + use_uniprot=True, + constant_modifications=constant_modifications, + variable_modifications=variable_modifications, + max_missed_cleavages=1) + glycopeptide_builder.start() + + without_uniprot = 201400 + with_uniprot_without_variable_signal_peptide = 231800 + with_uniprot = 353400 + + observed_count = glycopeptide_builder.query(Glycopeptide).count() + + assert observed_count in ( + with_uniprot, with_uniprot_without_variable_signal_peptide, without_uniprot) + + if observed_count == without_uniprot: + warnings.warn(""UniProt Annotations Not Used"") + if observed_count == with_uniprot_without_variable_signal_peptide: + warnings.warn(""Variable Signal Peptide Was Not Used"") + + redundancy = glycopeptide_builder.query( + Glycopeptide.glycopeptide_sequence, + Protein.name, + serialize.func.count(Glycopeptide.glycopeptide_sequence)).join( + Glycopeptide.protein).join(Glycopeptide.peptide).group_by( + Glycopeptide.glycopeptide_sequence, + Protein.name, + Peptide.start_position, + Peptide.end_position).yield_per(1000) + + for sequence, protein, count in redundancy: + self.assertEqual(count, 1, ""%s in %s has multiplicity %d"" % (sequence, protein, count)) + + for case in glycopeptide_builder.query(Glycopeptide).filter( + Glycopeptide.glycopeptide_sequence == + ""SVQEIQATFFYFTPN(N-Glycosylation)K{Hex:5; HexNAc:4; Neu5Ac:2}"").all(): + self.assertAlmostEqual(case.calculated_mass, 4123.718954557139, 5) + + self.clear_file(glycan_file) + self.clear_file(fasta_file) + self.clear_file(db_file) + + def test_missing_glycopeptide(self): + glycan_file = self.setup_tempfile(o_glycans) + fasta_file = self.setup_tempfile(HEPARANASE) + db_file = fasta_file + '.db' + + glycan_builder = TextFileGlycanHypothesisSerializer(glycan_file, db_file) + glycan_builder.start() + + glycopeptide_builder = naive_glycopeptide.FastaGlycopeptideHypothesisSerializer( + fasta_file, db_file, glycan_builder.hypothesis_id, protease='trypsin', + constant_modifications=constant_modifications, + max_missed_cleavages=2) + glycopeptide_builder.start() + + case = glycopeptide_builder.query( + Glycopeptide.glycopeptide_sequence == ""KFKNSTYS(O-Glycosylation)R{Hex:1; HexNAc:1; Neu5Ac:2}"").first() + self.assertIsNotNone(case) + + self.clear_file(glycan_file) + self.clear_file(fasta_file) + self.clear_file(db_file) + + def test_throughput(self): + fasta_file = fixtures.get_test_data(""phil-82-proteins.fasta"") + glycan_file = fixtures.get_test_data(""IAV_matched_glycans.txt"") + db_file = self.setup_tempfile("""") + print(db_file) + + glycan_builder = TextFileGlycanHypothesisSerializer(glycan_file, db_file) + glycan_builder.start() + + glycopeptide_builder = naive_glycopeptide.MultipleProcessFastaGlycopeptideHypothesisSerializer( + fasta_file, db_file, glycan_builder.hypothesis_id, constant_modifications=constant_modifications, + variable_modifications=variable_modifications, max_missed_cleavages=2) + glycopeptide_builder.start() + self.clear_file(db_file) + + def test_uniprot_info(self): + fasta_file = self.setup_tempfile(decorin) + glycan_file = self.setup_tempfile(o_glycans) + db_file = self.setup_tempfile("""") + glycan_builder = TextFileGlycanHypothesisSerializer(glycan_file, db_file) + glycan_builder.start() + + glycopeptide_builder = naive_glycopeptide.MultipleProcessFastaGlycopeptideHypothesisSerializer( + fasta_file, db_file, glycan_builder.hypothesis_id, + protease=['trypsin'], + constant_modifications=constant_modifications, + variable_modifications=[], max_missed_cleavages=2) + glycopeptide_builder.start() + + peptides_without_uniprot = 80 + peptides_with_uniprot = 88 + peptides_with_uniprot_and_ragged_signal_peptide = 140 + + peptides_count = glycopeptide_builder.query(serialize.Peptide).count() + + if peptides_count == peptides_with_uniprot or peptides_count == peptides_with_uniprot_and_ragged_signal_peptide: + post_cleavage = glycopeptide_builder.query(serialize.Peptide).filter( + serialize.Peptide.base_peptide_sequence == ""DEASGIGPEEHFPEVPEIEPMGPVCPFR"").first() + self.assertIsNotNone(post_cleavage) + self.assertEqual( + len(glycopeptide_builder.query(serialize.Protein).first().annotations), 2 + ) + elif peptides_count == peptides_without_uniprot: + warnings.warn(""Failed to communicate with UniProt, skip this test"") + else: + raise ValueError(""Incorrect peptide count: %r"" % (peptides_count, )) + + self.clear_file(db_file) + self.clear_file(fasta_file) + self.clear_file(glycan_file) + + def test_extract_forward_backward(self): + fasta_file = fixtures.get_test_data(""yeast_glycoproteins.fa"") + glycan_file = self.setup_tempfile(simple_n_glycans) + forward_db = self.setup_tempfile("""") + reverse_db = self.setup_tempfile("""") + + glycan_builder = TextFileGlycanHypothesisSerializer(glycan_file, forward_db) + glycan_builder.start() + + builder = naive_glycopeptide.MultipleProcessFastaGlycopeptideHypothesisSerializer( + fasta_file, forward_db, 1) + cnt = builder.extract_proteins() + assert cnt == 251 + + glycan_builder = TextFileGlycanHypothesisSerializer(glycan_file, reverse_db) + glycan_builder.start() + + rev_builder = naive_glycopeptide.ReversingMultipleProcessFastaGlycopeptideHypothesisSerializer( + fasta_file, reverse_db, 1) + cnt = rev_builder.extract_proteins() + assert cnt == 251 + fwd_prots = builder.query(serialize.Protein).all() + rev_prots = rev_builder.query(serialize.Protein).all() + + for fx, rx in zip(fwd_prots, rev_prots): + assert fx.name == rx.name + assert len(fx.glycosylation_sites) == len(rx.glycosylation_sites) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/fixtures.py",".py","354","16","import os +import platform + +from multiprocessing import set_start_method + +data_path = os.path.join(os.path.dirname(__file__), ""test_data"") + +if platform.system() == 'Windows' or platform.system() == ""Darwin"": + set_start_method(""spawn"") +else: + set_start_method(""forkserver"") + + +def get_test_data(filename): + return os.path.join(data_path, filename) +","Python" +"Glycomics","mobiusklein/glycresoft","tests/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_glycan_source.py",".py","4630","125","import unittest +import tempfile + +from glycresoft.database.builder.glycan import glycan_source + + +FILE_SOURCE = ''' +{Hex:3; HexNAc:2} N-Glycan O-Glycan +{Fuc:1; Hex:3; HexNAc:2} N-Glycan +''' + + +GLYCONNECT_SOURCE = ''' +HexNAc:2 Hex:3 N-Glycan O-Glycan +dHex:1 Hex:3 HexNAc:2 N-Glycan +''' + + +BYONIC_SOURCE = ''' +HexNAc(2)Hex(3) N-Glycan O-Glycan +dHex(1)Hex(3)HexNAc(2) N-Glycan +''' + +class GlycanSourceTests(unittest.TestCase): + + def setup_tempfile(self): + file_name = tempfile.mktemp() + "".txt"" + open(file_name, 'w').write(FILE_SOURCE) + return file_name + + def clear_file(self, path): + open(path, 'wb') + + def test_run(self): + file_name = self.setup_tempfile() + builder = glycan_source.TextFileGlycanHypothesisSerializer( + file_name, file_name + '.db') + builder.start() + inst = builder.query(glycan_source.DBGlycanComposition).filter( + glycan_source.DBGlycanComposition.hypothesis_id == builder.hypothesis_id, + glycan_source.DBGlycanComposition.composition == ""{Hex:3; HexNAc:2}"").one() + self.assertAlmostEqual(inst.calculated_mass, 910.32777, 3) + self.assertTrue(""N-Glycan"" in inst.structure_classes) + builder.engine.dispose() + self.clear_file(file_name + '.db') + self.clear_file(file_name) + + def test_run_reduced(self): + file_name = self.setup_tempfile() + builder = glycan_source.TextFileGlycanHypothesisSerializer( + file_name, file_name + '.db', reduction=""H2"") + builder.start() + inst = builder.query(glycan_source.DBGlycanComposition).filter( + glycan_source.DBGlycanComposition.hypothesis_id == builder.hypothesis_id, + glycan_source.DBGlycanComposition.composition == ""{Hex:3; HexNAc:2}$H2"").one() + self.assertAlmostEqual(inst.calculated_mass, 912.3434, 3) + builder.engine.dispose() + self.clear_file(file_name + '.db') + self.clear_file(file_name) + + def test_run_permethylated(self): + file_name = self.setup_tempfile() + builder = glycan_source.TextFileGlycanHypothesisSerializer( + file_name, file_name + '.db', reduction=""H2"", derivatization='methyl') + builder.start() + inst = builder.query(glycan_source.DBGlycanComposition).filter( + glycan_source.DBGlycanComposition.hypothesis_id == builder.hypothesis_id, + glycan_source.DBGlycanComposition.composition == ""{Hex^Me:3; HexNAc^Me:2}$C1H4"").one() + self.assertAlmostEqual(inst.calculated_mass, 1164.6251311968801, 3) + builder.engine.dispose() + self.clear_file(file_name + '.db') + self.clear_file(file_name) + + +class GlyconnectGlycanSourceTests(unittest.TestCase): + def setup_tempfile(self): + file_name = tempfile.mktemp() + "".txt"" + open(file_name, 'w').write(GLYCONNECT_SOURCE) + return file_name + + def clear_file(self, path): + open(path, 'wb') + + def test_run(self): + file_name = self.setup_tempfile() + builder = glycan_source.TextFileGlycanHypothesisSerializer( + file_name, file_name + '.db') + builder.start() + inst = builder.query(glycan_source.DBGlycanComposition).filter( + glycan_source.DBGlycanComposition.hypothesis_id == builder.hypothesis_id, + glycan_source.DBGlycanComposition.composition == ""{Hex:3; HexNAc:2}"").one() + self.assertAlmostEqual(inst.calculated_mass, 910.32777, 3) + self.assertTrue(""N-Glycan"" in inst.structure_classes) + builder.engine.dispose() + self.clear_file(file_name + '.db') + self.clear_file(file_name) + + +class ByonicGlycanSourceTests(unittest.TestCase): + def setup_tempfile(self): + file_name = tempfile.mktemp() + "".txt"" + open(file_name, 'w').write(BYONIC_SOURCE) + return file_name + + def clear_file(self, path): + open(path, 'wb') + + def test_run(self): + file_name = self.setup_tempfile() + builder = glycan_source.TextFileGlycanHypothesisSerializer( + file_name, file_name + '.db') + builder.start() + inst = builder.query(glycan_source.DBGlycanComposition).filter( + glycan_source.DBGlycanComposition.hypothesis_id == builder.hypothesis_id, + glycan_source.DBGlycanComposition.composition == ""{Hex:3; HexNAc:2}"").one() + self.assertAlmostEqual(inst.calculated_mass, 910.32777, 3) + self.assertTrue(""N-Glycan"" in inst.structure_classes) + builder.engine.dispose() + self.clear_file(file_name + '.db') + self.clear_file(file_name) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_glycan_combinator.py",".py","3718","99","import unittest +import tempfile + +from glycresoft.database.builder.glycan import glycan_combinator, glycan_source +from glycresoft.database.builder.glycopeptide.common import GlycopeptideHypothesisSerializerBase + + +class GlycanCombinatoricsTests(unittest.TestCase): + def setup_tempfile(self): + file_name = tempfile.mktemp() + '.tmp' + open(file_name, 'w').write(FILE_SOURCE) + return file_name + + def clear_file(self, path): + open(path, 'wb') + + def setup_compositions(self, source_file, database_path): + builder = glycan_source.TextFileGlycanHypothesisSerializer(source_file, database_path) + builder.run() + return builder + + def test_combinator(self): + source_file = self.setup_tempfile() + database_path = source_file + '.db' + builder = self.setup_compositions(source_file, database_path) + self.assertTrue(builder.query(glycan_combinator.GlycanComposition).count() > 0) + + # Create the glycopeptide hypothesis that GlycanCombination objects must be associated with + glycopeptide_builder_stub = GlycopeptideHypothesisSerializerBase(database_path, ""test"", builder.hypothesis_id) + + combinator = glycan_combinator.GlycanCombinationSerializer( + database_path, builder.hypothesis_id, glycopeptide_builder_stub.hypothesis.id, max_size=2) + combinator.run() + inst = builder.query(glycan_combinator.GlycanCombination).filter( + glycan_combinator.GlycanCombination.hypothesis_id == builder.hypothesis_id, + glycan_combinator.GlycanCombination.count == 1, + glycan_combinator.GlycanCombination.composition == ""{Hex:5; HexNAc:4; Neu5Ac:2}"").one() + self.assertAlmostEqual(inst.calculated_mass, 2222.7830048, 5) + + inst = builder.query(glycan_combinator.GlycanCombination).filter( + glycan_combinator.GlycanCombination.hypothesis_id == builder.hypothesis_id, + glycan_combinator.GlycanCombination.count == 2, + glycan_combinator.GlycanCombination.composition == ""{Hex:10; HexNAc:8; Neu5Ac:3}"").first() + + self.assertAlmostEqual(inst.calculated_mass, 4154.47059322789, 5) + + self.clear_file(source_file) + self.clear_file(source_file + '.db') + + +FILE_SOURCE = ''' +{Hex:5; HexNAc:4; Neu5Ac:1} +{Hex:5; HexNAc:4; Neu5Ac:2} +{Fuc:1; Hex:5; HexNAc:4; Neu5Ac:2} +{Hex:6; HexNAc:4; Neu5Ac:2} +{Fuc:3; Hex:8; HexNAc:4} +{Fuc:2; Hex:6; HexNAc:5; Neu5Ac:1} +{Fuc:1; Hex:6; HexNAc:5; Neu5Ac:2} +{Fuc:3; Hex:6; HexNAc:5; Neu5Ac:1} +{Hex:6; HexNAc:5; Neu5Ac:3} +{Fuc:2; Hex:6; HexNAc:5; Neu5Ac:2} +{Hex:7; HexNAc:6; Neu5Ac:2} +{Fuc:1; Hex:6; HexNAc:5; Neu5Ac:3} +{Fuc:1; Hex:7; HexNAc:6; Neu5Ac:2} +{Hex:10; HexNAc:6; Neu5Ac:1} +{Fuc:2; Hex:6; HexNAc:5; Neu5Ac:3} +{Hex:7; HexNAc:6; Neu5Ac:3} +{Fuc:2; Hex:7; HexNAc:6; Neu5Ac:2} +{Hex:8; HexNAc:7; Neu5Ac:2} +{Fuc:1; Hex:7; HexNAc:6; Neu5Ac:3} +{Hex:7; HexNAc:6; Neu5Ac:4} +{Fuc:2; Hex:7; HexNAc:6; Neu5Ac:3} +{Hex:8; HexNAc:7; Neu5Ac:3} +{Fuc:1; Hex:7; HexNAc:6; Neu5Ac:4} +{Fuc:1; Hex:8; HexNAc:7; Neu5Ac:3} +{Fuc:2; Hex:7; HexNAc:6; Neu5Ac:4} +{Hex:8; HexNAc:7; Neu5Ac:4} +{Fuc:2; Hex:8; HexNAc:7; Neu5Ac:3} +{Fuc:2; Hex:8; HexNAc:10; Neu5Ac:1} +{Fuc:3; Hex:7; HexNAc:6; Neu5Ac:4} +{Hex:9; HexNAc:8; Neu5Ac:3} +{Fuc:5; Hex:7; HexNAc:9; Neu5Ac:1} +{Fuc:1; Hex:8; HexNAc:7; Neu5Ac:4} +{Fuc:2; Hex:8; HexNAc:7; Neu5Ac:4} +{Hex:9; HexNAc:8; Neu5Ac:4} +{Fuc:2; Hex:9; HexNAc:8; Neu5Ac:3} +{Fuc:3; Hex:8; HexNAc:7; Neu5Ac:4} +{Fuc:1; Hex:9; HexNAc:8; Neu5Ac:4} +{Fuc:3; Hex:11; HexNAc:8; Neu5Ac:2} +{Hex:9; HexNAc:8; Neu5Ac:5} +{Fuc:2; Hex:9; HexNAc:8; Neu5Ac:4} +{Fuc:3; Hex:9; HexNAc:8; Neu5Ac:4} +{Fuc:2; Hex:9; HexNAc:8; Neu5Ac:5} +{Fuc:5; Hex:12; HexNAc:9; Neu5Ac:2} +''' + +if __name__ == '__main__': + unittest.main() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_symbolic_expression.py",".py","1598","42","import unittest + +from glypy.composition import composition_transform +from glypy.structure import glycan_composition + +from glycresoft import symbolic_expression + + +class SymbolicExpressionTest(unittest.TestCase): + def test_normalize_glycan_composition(self): + base = glycan_composition.GlycanComposition.parse(""{Hex:6; HexNAc:5; Neu5Ac:3}"") + deriv = composition_transform.derivatize( + glycan_composition.GlycanComposition.parse( + ""{Hex:6; HexNAc:5; Neu5Ac:3}""), ""methyl"") + + normd_symbol = symbolic_expression.GlycanSymbolContext(deriv) + normd_composition = glycan_composition.GlycanComposition.parse(normd_symbol.serialize()) + + self.assertEqual(base, normd_composition) + + def test_complex_expression(self): + ex = symbolic_expression.parse_expression(""X + 1 + abs(-2Z) * 5"") + ctx = symbolic_expression.SymbolContext({""X"": 5, ""Z"": 3}) + expected = 36 + self.assertEqual(ex.evaluate(ctx), expected) + + def test_nested_sub_expression(self): + expr = symbolic_expression.parse_expression(""(2(x + 5)) + 5"") + assert expr.evaluate({'x': 0}) == 15 + assert expr.evaluate({""x"": 5}) == 25 + + def test_nested_simplify(self): + expr = symbolic_expression.parse_expression(""(((x + 5)))"") + assert isinstance(expr.expr, symbolic_expression.ExpressionNode) + expr = symbolic_expression.parse_expression(""((((2(x + 5)))))"") + assert expr.coefficient == 2 + assert isinstance(expr.expr, symbolic_expression.ExpressionNode) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_structure_loader.py",".py","1038","32","import unittest + +from glycresoft.structure.structure_loader import ( + FragmentCachingGlycopeptide, hashable_glycan_glycopeptide_parser, + HashableGlycanComposition, GlycanCompositionWithOffsetProxy) + +from glycopeptidepy.test.sequence_test_suite import PeptideSequenceSuiteBase + +glycopeptide = ""YPVLN(N-Glycosylation)VTMPN(Deamidation)NGKFDK{Hex:9; HexNAc:2}"" + + +class TestFragmentCachingGlycopeptide(PeptideSequenceSuiteBase, unittest.TestCase): + def parse_sequence(self, seqstr): + return FragmentCachingGlycopeptide(seqstr) + + def test_mass(self): + gp = FragmentCachingGlycopeptide(glycopeptide) + self.assertAlmostEqual(gp.total_mass, 3701.5421769127897, 2) + + def test_parse(self): + parts = hashable_glycan_glycopeptide_parser(glycopeptide) + gc = parts[-3] + self.assertIsInstance( + gc, (HashableGlycanComposition, GlycanCompositionWithOffsetProxy)) + + test_cad_fragmentation = None + test_glycan_fragments_stubs = None + + +if __name__ == '__main__': + unittest.main() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_task_execution_sequence.py",".py","800","30","import time +import random +from glycresoft.task import TaskExecutionSequence, Pipeline + +class MyTask(TaskExecutionSequence): + def __init__(self, threshold): + self.threshold = threshold + + def run(self, *args, **kwargs): + while not self.error_occurred(): + self.log(""I am alive!"") + time.sleep(1) + if random.random() > self.threshold: + self.log(""Erroring out!"") + raise Exception(""Failure"") + self.log(""Done!"") + + +if __name__ == ""__main__"": + task = MyTask(0.2) + task.start(True, True) + task2 = MyTask(1.0) + task2.start(False, True) + pipe = Pipeline([task, task2]) + pipe.join() + pipe.log(""Stopping"") + pipe.stop() + pipe.join(10) + pipe.log(""Stopped"", task.is_alive(), pipe.error_occurred()) +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_sample_consumer.py",".py","6543","178","import unittest +import tempfile +import os +import glob + +import ms_peak_picker +import ms_deisotope +from ms_deisotope.output import ProcessedMSFileLoader + +import numpy as np + +from glycresoft.profiler import SampleConsumer + +from . import fixtures + +agp_glycomics_mzml = fixtures.get_test_data(""AGP_Glycomics_20150930_06.centroid.mzML"") +agp_glycproteomics_mzml = fixtures.get_test_data(""20150710_3um_AGP_001_29_30.mzML"") +agp_glycproteomics_mzml_reference = fixtures.get_test_data(""20150710_3um_AGP_001_29_30.preprocessed.mzML"") + + +class SampleConsumerBase(object): + def make_output_directory(self): + path = tempfile.mkdtemp() + return path + + def cleanup(self, directory): + files = glob.glob(os.path.join(directory, ""*"")) + for f in files: + try: + os.remove(f) + except OSError: + pass + try: + os.remove(directory) + except OSError: + pass + + +class MSMSSampleConsumerTest(unittest.TestCase, SampleConsumerBase): + def build_args(self): + ms1_peak_picking_args = { + ""transforms"": [ + ] + } + + msn_peak_picking_args = { + ""transforms"": [ + ] + } + + ms1_deconvolution_args = { + ""scorer"": ms_deisotope.scoring.PenalizedMSDeconVFitter(20.0, 2.0), + ""max_missed_peaks"": 3, + ""averagine"": ms_deisotope.glycopeptide, + ""truncate_after"": SampleConsumer.MS1_ISOTOPIC_PATTERN_WIDTH, + ""ignore_below"": SampleConsumer.MS1_IGNORE_BELOW + } + + msn_deconvolution_args = { + ""scorer"": ms_deisotope.scoring.MSDeconVFitter(10.0), + ""averagine"": ms_deisotope.peptide, + ""max_missed_peaks"": 1, + ""truncate_after"": SampleConsumer.MSN_ISOTOPIC_PATTERN_WIDTH, + ""ignore_below"": SampleConsumer.MSN_IGNORE_BELOW + } + return ( + ms1_peak_picking_args, msn_peak_picking_args, + ms1_deconvolution_args, msn_deconvolution_args) + + def test_consumer(self): + (ms1_peak_picking_args, msn_peak_picking_args, + ms1_deconvolution_args, msn_deconvolution_args) = self.build_args() + outdir = self.make_output_directory() + outpath = os.path.join(outdir, ""test-output.mzML"") + + consumer = SampleConsumer( + agp_glycproteomics_mzml, + ms1_peak_picking_args=ms1_peak_picking_args, + ms1_deconvolution_args=ms1_deconvolution_args, + msn_peak_picking_args=msn_peak_picking_args, + msn_deconvolution_args=msn_deconvolution_args, + storage_path=outpath, sample_name=None, + n_processes=5, + extract_only_tandem_envelopes=True, + ms1_averaging=1) + consumer.start() + + reader = ProcessedMSFileLoader(outpath) + reference = ProcessedMSFileLoader(agp_glycproteomics_mzml_reference) + + for a_bunch, b_bunch in zip(reader, reference): + assert a_bunch.precursor.id == b_bunch.precursor.id + assert len(a_bunch.products) == len(b_bunch.products) + for a_product, b_product in zip(a_bunch.products, b_bunch.products): + assert a_product.precursor_information.defaulted == b_product.precursor_information.defaulted + matched = np.isclose(a_product.precursor_information.neutral_mass, + b_product.precursor_information.neutral_mass) + message = [""%0.3f not close to %0.3f for %s of %s"" % ( + a_product.precursor_information.neutral_mass, + b_product.precursor_information.neutral_mass, + a_product.id, a_product.precursor_information.precursor_scan_id)] + message.append(""Found precursor score %r, expected %r"" % ( + a_product.precursor_information.precursor.deconvoluted_peak_set.has_peak( + a_product.precursor_information.neutral_mass).score, + b_product.precursor_information.precursor.deconvoluted_peak_set.has_peak( + b_product.precursor_information.neutral_mass).score + )) + assert matched, '\n'.join(message) + assert len(a_product.deconvoluted_peak_set) == len(b_product.deconvoluted_peak_set) + + reader.close() + reference.close() + + self.cleanup(outdir) + + +@unittest.skip(""This test is subsumed by MSMSSampleConsumerTest"") +class SampleConsumerTest(unittest.TestCase, SampleConsumerBase): + def build_args(self): + ms1_peak_picking_args = { + ""transforms"": [ + ] + } + + msn_peak_picking_args = { + ""transforms"": [ + ] + } + + ms1_deconvolution_args = { + ""scorer"": ms_deisotope.scoring.PenalizedMSDeconVFitter(35.0, 2.0), + ""max_missed_peaks"": 1, + ""averagine"": ms_deisotope.glycan, + ""truncate_after"": SampleConsumer.MS1_ISOTOPIC_PATTERN_WIDTH, + ""ignore_below"": SampleConsumer.MS1_IGNORE_BELOW + } + + msn_deconvolution_args = { + ""scorer"": ms_deisotope.scoring.MSDeconVFitter(10.0), + ""averagine"": ms_deisotope.glycan, + ""max_missed_peaks"": 1, + ""truncate_after"": SampleConsumer.MSN_ISOTOPIC_PATTERN_WIDTH, + ""ignore_below"": SampleConsumer.MSN_IGNORE_BELOW + } + return ( + ms1_peak_picking_args, msn_peak_picking_args, + ms1_deconvolution_args, msn_deconvolution_args) + + def test_consumer(self): + (ms1_peak_picking_args, msn_peak_picking_args, + ms1_deconvolution_args, msn_deconvolution_args) = self.build_args() + outdir = self.make_output_directory() + outpath = os.path.join(outdir, ""test-output.mzML"") + + consumer = SampleConsumer( + agp_glycomics_mzml, + ms1_peak_picking_args=ms1_peak_picking_args, + ms1_deconvolution_args=ms1_deconvolution_args, + msn_peak_picking_args=msn_peak_picking_args, + msn_deconvolution_args=msn_deconvolution_args, + storage_path=outpath, sample_name=None, + n_processes=5, + extract_only_tandem_envelopes=False) + consumer.start() + + reader = ProcessedMSFileLoader(outpath) + + scan = reader.get_scan_by_id(""scanId=1601016"") + self.assertIsNotNone(scan.deconvoluted_peak_set.has_peak(958.66, use_mz=1)) + + reader.close() + + self.cleanup(outdir) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_core_search.py",".py","1643","51","import unittest + +import glypy +from glycopeptidepy import PeptideSequence +from ms_deisotope.output import ProcessedMSFileLoader + +from glycresoft.tandem.glycopeptide import core_search +from glycresoft.tandem.glycopeptide.core_search import ( + GlycanCombinationRecord, GlycanTypes, GlycanFilteringPeptideMassEstimator) + +from .fixtures import get_test_data + + +peptide_mass = PeptideSequence(""YLGNATAIFFLPDEGK"").mass +gc1 = glypy.glycan_composition.HashableGlycanComposition.parse(""{Hex:5; HexNAc:4; Neu5Ac:1}"") +gc2 = glypy.glycan_composition.HashableGlycanComposition.parse(""{Hex:5; HexNAc:4; Neu5Ac:2}"") +gc3 = glypy.glycan_composition.HashableGlycanComposition.parse(""{Hex:6; HexNAc:5; Neu5Ac:2}"") +glycan_compositions = [gc1, gc2, gc3] + +glycan_database = [] +for i, gc in enumerate(glycan_compositions): + record = GlycanCombinationRecord( + i + 1, gc.mass() - gc.composition_offset.mass, gc, 1, [ + GlycanTypes.n_glycan, + GlycanTypes.o_glycan, + + ]) + glycan_database.append(record) + + + +class TestGlycanFilteringPeptideMassEstimator(unittest.TestCase): + def load_spectra(self): + return list(ProcessedMSFileLoader(get_test_data(""example_glycopeptide_spectra.mzML""))) + + def make_estimator(self): + return GlycanFilteringPeptideMassEstimator(glycan_database) + + def test_estimate(self): + estimator = self.make_estimator() + scans = self.load_spectra() + scan = scans[0] + ranked = estimator.match(scan) + match = ranked[0] + print(match) + self.assertAlmostEqual(match.score, 29.715553766294754, 3) + + +if __name__ == ""__main__"": + unittest.main() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_mzid_glycopeptide.py",".py","2589","71","import unittest +import tempfile + +from glycresoft.serialize.hypothesis.peptide import Peptide, Protein, Glycopeptide +from glycresoft.database.builder.glycopeptide import informed_glycopeptide +from glycresoft.database.builder.glycan import ( + CombinatorialGlycanHypothesisSerializer) +from glycresoft import serialize + +from . import fixtures +from .test_constrained_combinatorics import FILE_SOURCE as GLYCAN_RULE_FILE_SOURCE + + +MZID_PATH = fixtures.get_test_data(""AGP_Proteomics2.mzid"") + + +class MzIdGlycopeptideTests(unittest.TestCase): + + def setup_tempfile(self, source): + file_name = tempfile.mktemp() + '.tmp' + open(file_name, 'w').write(source) + return file_name + + def clear_file(self, path): + open(path, 'wb') + + def test_build_hypothesis(self): + glycan_file = self.setup_tempfile(GLYCAN_RULE_FILE_SOURCE) + mzid_path = MZID_PATH + db_file = glycan_file + '.db' + + glycan_builder = CombinatorialGlycanHypothesisSerializer(glycan_file, db_file) + glycan_builder.run() + + glycopeptide_builder = informed_glycopeptide.MultipleProcessMzIdentMLGlycopeptideHypothesisSerializer( + mzid_path, db_file, glycan_builder.hypothesis_id) + glycopeptide_builder.run() + + gp_count = glycopeptide_builder.query(Glycopeptide).count() + with_uniprot = 769500 + with_uniprot_without_variable_signal_peptide = 659300 + without_uniprot = 651700 + without_any_external = 646000 + self.assertIn( + gp_count, (with_uniprot, without_uniprot, without_any_external)) + + redundancy = glycopeptide_builder.query( + Glycopeptide.glycopeptide_sequence, + Protein.name, + serialize.func.count(Glycopeptide.glycopeptide_sequence)).join( + Glycopeptide.protein).join(Glycopeptide.peptide).group_by( + Glycopeptide.glycopeptide_sequence, + Protein.name, + Peptide.start_position, + Peptide.end_position).yield_per(1000) + + for sequence, protein, count in redundancy: + self.assertEqual(count, 1, ""%s in %s has multiplicity %d"" % (sequence, protein, count)) + + for case in glycopeptide_builder.query(Glycopeptide).filter( + Glycopeptide.glycopeptide_sequence == + ""SVQEIQATFFYFTPN(N-Glycosylation)K{Hex:5; HexNAc:4; Neu5Ac:2}"").all(): + self.assertAlmostEqual(case.calculated_mass, 4123.718954557139, 5) + + self.clear_file(glycan_file) + self.clear_file(db_file) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_glycan_chromatogram_analyzer.py",".py","5291","127","import unittest +import tempfile +import os + + +from . import fixtures +from .test_constrained_combinatorics import ( + FILE_SOURCE) +from glycresoft.profiler import MzMLGlycanChromatogramAnalyzer, GeneralScorer +from glycresoft.database.builder.glycan import CombinatorialGlycanHypothesisSerializer +from glycresoft.serialize import AnalysisDeserializer + + +agp_glycomics_mzml = fixtures.get_test_data( + ""AGP_Glycomics_20150930_06.deconvoluted.mzML"") + + +class GlycanProfilerConsumerTest(unittest.TestCase): + + def setup_tempfile(self, content): + file_name = tempfile.mktemp() + '.tmp' + open(file_name, 'w').write(content) + return file_name + + def clear_file(self, path): + open(path, 'wb').close() + + def _make_hypothesis(self): + file_name = self.setup_tempfile(FILE_SOURCE) + builder = CombinatorialGlycanHypothesisSerializer( + file_name, file_name + '.db') + builder.run() + self.clear_file(file_name) + return file_name + '.db' + + def confirm_score(self, chroma, key, score): + match = chroma.find_key(key) + self.assertIsNotNone(match) + self.assertAlmostEqual(score, match.score, 1) + + def confirm_absent(self, chroma, key): + match = chroma.find_key(key) + self.assertIsNone(match) + + def test_profiler(self): + db_file = self._make_hypothesis() + output_file = self.setup_tempfile("""") + task = MzMLGlycanChromatogramAnalyzer( + db_file, 1, agp_glycomics_mzml, output_file, + analysis_name=""test-analysis"", + scoring_model=GeneralScorer) + task.start() + self.assertTrue(os.path.exists(output_file)) + ads = AnalysisDeserializer(output_file) + gcs = ads.load_glycan_composition_chromatograms() + self.assertEqual(len(gcs), 23) + self.clear_file(db_file) + # 'spacing_fit': 0.96367957815527916, 'isotopic_fit': 0.99366937970680247, + # 'line_score': 0.99780414736388745, 'charge_count': 0.9365769766604084 + self.confirm_score(gcs, ""{Fuc:1; Hex:7; HexNAc:6; Neu5Ac:4}"", 17.1458) + # 'spacing_fit': 0.96123524755239487, 'isotopic_fit': 0.97935840584492162, + # 'line_score': 0.99562733579066764, 'charge_count': 0.7368321292716115 + self.confirm_score(gcs, ""{Hex:8; HexNAc:7; Neu5Ac:3}"", 13.5279) + # 'spacing_fit': 0.94565181061625481, 'isotopic_fit': 0.99074210231338733, + # 'line_score': 0.98925755528448378, 'charge_count': 0.999773289306269 + self.confirm_score(gcs, ""{Hex:7; HexNAc:6; Neu5Ac:4}"", 20.4438) + # 'spacing_fit': 0.95567017048597336, 'isotopic_fit': 0.98274665306540443, + # 'line_score': 0.99706887771172914, 'charge_count': 0.7604540961453831 + self.confirm_score(gcs, ""{Fuc:2; Hex:6; HexNAc:5; Neu5Ac:3}"", 14.0977) + + ads.close() + self.clear_file(output_file) + + def test_smoothing_profiler(self): + db_file = self._make_hypothesis() + output_file = self.setup_tempfile("""") + task = MzMLGlycanChromatogramAnalyzer( + db_file, 1, agp_glycomics_mzml, output_file, + regularize=""grid"", + analysis_name=""test-analysis"", + scoring_model=GeneralScorer) + task.start() + # import cProfile + # prof = cProfile.Profile() + # prof.runcall(task.start) + # prof.print_stats() + # prof.dump_stats('smooth_profile.pstats') + self.assertTrue(os.path.exists(output_file)) + ads = AnalysisDeserializer(output_file, analysis_id=1) + gcs = ads.load_glycan_composition_chromatograms() + self.assertEqual(len(gcs), 23) + self.confirm_score(gcs, ""{Fuc:1; Hex:7; HexNAc:6; Neu5Ac:4}"", 16.1425) + self.confirm_score(gcs, ""{Hex:8; HexNAc:7; Neu5Ac:3}"", 8.8510) + self.confirm_score(gcs, ""{Hex:7; HexNAc:6; Neu5Ac:4}"", 16.6722) + network_params = ads.analysis.parameters['network_parameters'] + tau = [0.0, 12.173488161057854, 16.042106463675424, 0.0, 22.061954223206591, + 0.0, 13.928596053020485, 0.0, 9.4348332520855713, 0.0, 0.0, 0.0, 0.0, 0.0] + for a, b in zip(tau, network_params.tau): + self.assertAlmostEqual(a, b, 3) + ads.close() + + self.clear_file(output_file) + task = MzMLGlycanChromatogramAnalyzer( + db_file, 1, agp_glycomics_mzml, output_file, + regularize=0.2, + regularization_model=network_params, + analysis_name=""test-analysis"", + scoring_model=GeneralScorer) + task.start() + ads = AnalysisDeserializer(output_file, analysis_id=1) + gcs = ads.load_glycan_composition_chromatograms() + self.assertEqual(len(gcs), 23) + self.confirm_score(gcs, ""{Fuc:1; Hex:7; HexNAc:6; Neu5Ac:4}"", 16.7795) + self.confirm_score(gcs, ""{Hex:8; HexNAc:7; Neu5Ac:3}"", 10.6734) + self.confirm_score(gcs, ""{Hex:7; HexNAc:6; Neu5Ac:4}"", 18.3360) + self.confirm_score(gcs, ""{Fuc:2; Hex:6; HexNAc:5; Neu5Ac:3}"", 15.9628) + network_params = ads.analysis.parameters['network_parameters'] + for a, b in zip(tau, network_params.tau): + self.assertAlmostEqual(a, b, 3) + ads.close() + self.clear_file(output_file) + self.clear_file(db_file) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_target_decoy.py",".py","1307","32","import unittest + + +import numpy as np + +from glycresoft.tandem import target_decoy +from . import fixtures + + +class TestNearestValueLookup(unittest.TestCase): + + def _get_instance(self): + pairs = np.loadtxt(fixtures.get_test_data('numpairs.txt')) + return target_decoy.NearestValueLookUp(map(list, pairs)) + + def test_query(self): + nvl = self._get_instance() + indices = np.linspace(0, 20) + values = [0.34342784, 0.26780415, 0.22610257, 0.19385776, 0.16619172, + 0.14381995, 0.12177308, 0.10591941, 0.09414169, 0.08243626, + 0.07534748, 0.06410644, 0.05670103, 0.05028203, 0.04507182, + 0.04016268, 0.03451865, 0.03071733, 0.02744457, 0.02566964, + 0.02328244, 0.02104853, 0.01972112, 0.0186802, 0.01601498, + 0.01471843, 0.01368375, 0.01263298, 0.01172756, 0.0101476, + 0.00941398, 0.0079023, 0.00655977, 0.00564417, 0.00503525, + 0.00482724, 0.00415692, 0.00415692, 0.00398406, 0.00398406, + 0.00330487, 0.00282247, 0.00254669, 0.00232626, 0.00178678, + 0.00178678, 0.00152486, 0.00124185, 0.00124185, 0.00096339] + for ind, val in zip(indices, values): + q = nvl[ind] + self.assertAlmostEqual(val, q) +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_glycopeptide_scorers.py",".py","6443","141","import unittest + +from glycopeptidepy import Modification +from glypy.structure.glycan_composition import HashableGlycanComposition + +from ms_deisotope.output import ProcessedMSFileLoader +from glycresoft.tandem import oxonium_ions + +from .fixtures import get_test_data + +from glycresoft.tandem.glycopeptide.core_search import GlycanCombinationRecord +from glycresoft.tandem.oxonium_ions import OxoniumIndex +from glycresoft.structure import FragmentCachingGlycopeptide + +from glycresoft.tandem.glycopeptide.scoring import ( + base, intensity_scorer, simple_score, binomial_score, coverage_weighted_binomial) + +from glycresoft.tandem.peptide.scoring.localize import PTMProphetEvaluator + + +class TestGlycopeptideScorers(unittest.TestCase): + def load_spectra(self): + scan, scan2 = list(ProcessedMSFileLoader(get_test_data(""example_glycopeptide_spectra.mzML""))) + + return scan, scan2 + + def build_structures(self): + gp = FragmentCachingGlycopeptide( + 'YLGN(N-Glycosylation)ATAIFFLPDEGK{Hex:5; HexNAc:4; Neu5Ac:1}') + gp2 = FragmentCachingGlycopeptide('YLGN(#:iupac,glycosylation_type=N-Linked:?-?-Hexp-(?-?)-?-?-' + 'Hexp2NAc-(?-?)-a-D-Manp-(1-6)-[a-D-Neup5Ac-(?-?)-?-?-Hexp-(?-?' + ')-?-?-Hexp2NAc-(?-?)-a-D-Manp-(1-3)]b-D-Manp-(1-4)-b-D-Glcp2NA' + 'c-(1-4)-b-D-Glcp2NAc)ATAIFFLPDEGK') + return gp, gp2 + + def add_oxonium_index(self, scan, gp): + gc_rec = GlycanCombinationRecord( + 0, 1913.6770236770099, HashableGlycanComposition.parse(gp.glycan_composition), 1, []) + ox_index = OxoniumIndex() + ox_index.build_index([gc_rec], all_series=False, allow_ambiguous=False, + include_large_glycan_fragments=False, + maximum_fragment_size=4) + index_match = ox_index.match(scan.deconvoluted_peak_set, 2e-5) + scan.annotations['oxonium_index_match'] = index_match + + def test_simple_coverage_scorer(self): + scan, scan2 = self.load_spectra() + gp, gp2 = self.build_structures() + + match = simple_score.SimpleCoverageScorer.evaluate(scan, gp) + self.assertAlmostEqual(match.score, 0.574639463036, 3) + match = simple_score.SimpleCoverageScorer.evaluate(scan, gp2) + self.assertAlmostEqual(match.score, 0.574639463036, 3) + + match = simple_score.SimpleCoverageScorer.evaluate(scan2, gp) + self.assertAlmostEqual(match.score, 0.57850568223215082, 3) + match = simple_score.SimpleCoverageScorer.evaluate(scan2, gp2) + self.assertAlmostEqual(match.score, 0.848213154345, 3) + + def test_binomial_scorer(self): + scan, scan2 = self.load_spectra() + gp, gp2 = self.build_structures() + + match = binomial_score.BinomialSpectrumMatcher.evaluate(scan, gp) + self.assertAlmostEqual(match.score, 179.12869707912699, 3) + match = binomial_score.BinomialSpectrumMatcher.evaluate(scan, gp2) + self.assertAlmostEqual(match.score, 179.12869707912699, 3) + + match = binomial_score.BinomialSpectrumMatcher.evaluate(scan2, gp) + self.assertAlmostEqual(match.score, 139.55732008249882, 3) + match = binomial_score.BinomialSpectrumMatcher.evaluate(scan2, gp2) + self.assertAlmostEqual(match.score, 191.05060390867396, 3) + + def test_coverage_weighted_binomial(self): + scan, scan2 = self.load_spectra() + gp, gp2 = self.build_structures() + + match = coverage_weighted_binomial.CoverageWeightedBinomialScorer.evaluate(scan, gp) + self.assertAlmostEqual(match.score, 103.24070700636717, 3) + match = coverage_weighted_binomial.CoverageWeightedBinomialScorer.evaluate(scan, gp2) + self.assertAlmostEqual(match.score, 103.24070700636717, 3) + + self.add_oxonium_index(scan, gp) + match = coverage_weighted_binomial.CoverageWeightedBinomialScorer.evaluate(scan, gp) + self.assertAlmostEqual(match.score, 103.24070700636717, 3) + match = coverage_weighted_binomial.CoverageWeightedBinomialScorer.evaluate(scan, gp2) + self.assertAlmostEqual(match.score, 103.24070700636717, 3) + + match = coverage_weighted_binomial.CoverageWeightedBinomialScorer.evaluate(scan2, gp) + self.assertAlmostEqual(match.score, 81.04099136734635, 3) + match = coverage_weighted_binomial.CoverageWeightedBinomialScorer.evaluate(scan2, gp2) + self.assertAlmostEqual(match.score, 162.35792408346902, 3) + + def test_log_intensity(self): + scan, scan2 = self.load_spectra() + gp, gp2 = self.build_structures() + + match = intensity_scorer.LogIntensityScorer.evaluate(scan, gp) + self.assertAlmostEqual(match.score, 55.396555993522334, 3) + match = intensity_scorer.LogIntensityScorer.evaluate(scan, gp2, rare_signatures=True) + self.assertAlmostEqual(match.score, 55.396555993522334, 3) + + match = intensity_scorer.LogIntensityScorer.evaluate(scan2, gp) + self.assertAlmostEqual(match.score, 72.71569538828025, 3) + match = intensity_scorer.LogIntensityScorer.evaluate(scan2, gp2) + self.assertAlmostEqual(match.score, 157.97265377375456, 3) + + def test_log_intensity_reweighted(self): + scan, scan2 = self.load_spectra() + gp, gp2 = self.build_structures() + + match = intensity_scorer.LogIntensityScorerReweighted.evaluate(scan, gp) + self.assertAlmostEqual(match.score, 61.839439337876456, 3) + match = intensity_scorer.LogIntensityScorerReweighted.evaluate(scan, gp2) + self.assertAlmostEqual(match.score, 61.839439337876456, 3) + + match = intensity_scorer.LogIntensityScorerReweighted.evaluate( + scan2, gp) + self.assertAlmostEqual(match.score, 90.76611593053316, 3) + match = intensity_scorer.LogIntensityScorerReweighted.evaluate( + scan2, gp2) + self.assertAlmostEqual(match.score, 149.86761396041246, 3) + + def test_ptm_prophet(self): + scan, _scan2 = self.load_spectra() + gp, _gp2 = self.build_structures() + + match = PTMProphetEvaluator( + scan, gp, modification_rule=Modification(""N-Glycosylation"").rule, + respect_specificity=False + ) + + match.score_arrangements() + + match = PTMProphetEvaluator( + scan, gp, modification_rule=Modification(""N-Glycosylation"").rule, + respect_specificity=True + ) + + match.score_arrangements() +","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_data/__init__.py",".py","0","0","","Python" +"Glycomics","mobiusklein/glycresoft","tests/test_data/build_refs.sh",".sh","1268","27","#!/usr/bin/env bash + +glycresoft build-hypothesis glycopeptide-fa -c ""Carbamidomethyl (C)"" \ + -v ""Pyro-glu from Q (Q@N-term)"" -v ""Oxidation (M)"" \ + -m 1 -e trypsin -g ""./agp_glycans.txt"" ""./agp.fa"" agp.db + + +glycresoft build-hypothesis glycopeptide-fa -c ""Carbamidomethyl (C)"" \ + -v ""Pyro-glu from Q (Q@N-term)"" -v ""Oxidation (M)"" \ + -m 1 -e trypsin -g ""./agp_glycans.txt"" -F ""./agp.fa"" agp_indexed.db + + +glycresoft build-hypothesis glycopeptide-fa -c ""Carbamidomethyl (C)"" \ + -v ""Pyro-glu from Q (Q@N-term)"" -v ""Oxidation (M)"" \ + -m 1 -e trypsin -g ""./agp_glycans.txt"" -F -R ""./agp.fa"" agp_indexed_decoy.db + +glycresoft analyze search-glycopeptide -o ""./classic_agp_search.db"" \ + ""./agp.db"" ""./20150710_3um_AGP_001_29_30.preprocessed.mzML"" 1 + +glycresoft analyze search-glycopeptide -o ""./classic_agp_search_empty.db"" \ + ""./agp.db"" ""./AGP_Glycomics_20150930_06.deconvoluted.mzML"" 1 + +glycresoft analyze search-glycopeptide-multipart -o ""./indexed_agp_search.db"" -M \ + ""./agp_indexed.db"" ""./agp_indexed_decoy.db"" ""./20150710_3um_AGP_001_29_30.preprocessed.mzML"" + +glycresoft analyze search-glycopeptide-multipart -o ""./indexed_agp_search_empty.db"" -M \ + ""./agp_indexed.db"" ""./agp_indexed_decoy.db"" ""./AGP_Glycomics_20150930_06.deconvoluted.mzML""","Shell"