diff --git "a/data/dataset_Metabolic.csv" "b/data/dataset_Metabolic.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Metabolic.csv" @@ -0,0 +1,51917 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Metabolic","SBRG/cobradb","setup.py",".py","1322","44","# -*- coding: utf-8 -*- + +from os.path import abspath, dirname +from sys import path +from setuptools import setup, find_packages + +# To temporarily modify sys.path +SETUP_DIR = abspath(dirname(__file__)) + +setup( + name='cobradb', + version='0.3.0', + description=""""""COBRAdb loads genome-scale metabolic models and genome + annotations into a relational database."""""", + url='https://github.com/SBRG/cobradb', + author='Zachary King', + author_email='zaking@ucsd.edu', + license='MIT', + classifiers=[ + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.7', + ], + keywords='systems biology, genome-scale model', + packages=find_packages(), + install_requires=[ + 'SQLAlchemy>=1.3.10,<2', + # Be careful upgrading cobra for use with BiGG; ancient models (e.g. + # iND750.xml) cause errors with cobra versions >=0.15 + 'cobra>=0.14.2,<0.15', + 'python-libsbml>=5.18.0,<6', + 'numpy>=1.17.2,<2', + 'psycopg2>=2.8.3,<3', + 'biopython>=1.74,<2', + 'scipy>=1.3.1,<2', + 'lxml>=4.4.1,<5', + 'pytest>=4.6.6,<5', + 'six>=1.12.0,<2', + 'tornado>=4.5.3,<5', + 'escher>=1.7.3,<2', + 'configparser>=4.0.2,<5', + ], +) +","Python" +"Metabolic","SBRG/cobradb","cobradb/models.py",".py","15438","476","# -*- coding: utf-8 -*- + +""""""Module to implement ORM to the ome database"""""" + +from cobradb.settings import db_connection_string + +from sqlalchemy import (ForeignKey, Column, Integer, String, Float, Table, + LargeBinary, Boolean, create_engine, MetaData, Enum, + DateTime, UniqueConstraint) +from sqlalchemy.orm import sessionmaker, Session as _SA_Session +from sqlalchemy.ext.declarative import declarative_base + + +# Connect to postgres +engine = create_engine(db_connection_string) +Base = declarative_base(bind=engine) +metadata = MetaData(bind=engine) +Session = sessionmaker(bind=engine, class_=_SA_Session) + + +# Make the enums +_enum_l = [ + Enum('component', 'reaction', 'gene', 'compartmentalized_component', + name='synonym_type'), + Enum('pmid', 'doi', + name='reference_type'), + Enum('model_reaction', 'model_compartmentalized_component', 'model_gene', + name='old_id_synonym_type'), + Enum('is_version', name='is_version'), + Enum('component', 'reaction', name='deprecated_id_types'), + Enum('model_compartmentalized_component', 'model_reaction', + name='escher_map_matrix_type') +] +custom_enums = { x.name: x for x in _enum_l } + +#------------ +# Exceptions +#------------ + +class NotFoundError(Exception): + pass + +class AlreadyLoadedError(Exception): + pass + +#-------- +# Tables +#-------- + +class DatabaseVersion(Base): + __tablename__ = 'database_version' + + is_version = Column(custom_enums['is_version'], primary_key=True) + date_time = Column(DateTime, nullable=False) + + __table_args__ = ( + UniqueConstraint('is_version'), + ) + + def __init__(self, date_time): + self.is_version = 'is_version' + self.date_time = date_time + + +class Genome(Base): + __tablename__ = 'genome' + + id = Column(Integer, primary_key=True) + accession_type = Column(String(200), nullable=False) + accession_value = Column(String(200), nullable=False) + organism = Column(String(200), nullable=True) + taxon_id = Column(String(200), nullable=True) + ncbi_assembly_id = Column(String(200), nullable=True) + + __table_args__ = ( + UniqueConstraint('accession_type', 'accession_value'), + ) + + def __repr__(self): + return (''.format(self=self)) + + +class Chromosome(Base): + __tablename__ = 'chromosome' + + id = Column(Integer, primary_key=True) + ncbi_accession = Column(String(200)) + genome_id = Column(Integer, ForeignKey('genome.id')) + + __table_args__ = ( + UniqueConstraint('ncbi_accession', 'genome_id'), + ) + + def __repr__(self): + return ('' + .format(self=self)) + + +class GenomeRegion(Base): + __tablename__ = 'genome_region' + id = Column(Integer, primary_key=True) + chromosome_id = Column(Integer, ForeignKey('chromosome.id')) + bigg_id = Column(String, nullable=False) + leftpos = Column(Integer, nullable=True) + rightpos = Column(Integer, nullable=True) + strand = Column(String(1), nullable=True) + type = Column(String(20)) + dna_sequence = Column(String, nullable=True) + protein_sequence = Column(String, nullable=True) + + __table_args__ = ( + UniqueConstraint('bigg_id', 'chromosome_id'), + ) + + __mapper_args__ = { + 'polymorphic_identity': 'genome_region', + 'polymorphic_on': type + } + + def __repr__(self): + return ('' + .format(self=self)) + + +class Component(Base): + __tablename__ = 'component' + + id = Column(Integer, primary_key=True) + bigg_id = Column(String) + name = Column(String, nullable=True) + type = Column(String(20)) + + __table_args__ = (UniqueConstraint('bigg_id'), {}) + + __mapper_args__ = { + 'polymorphic_identity': 'component', + 'polymorphic_on': type + } + + def __repr__(self): + return ""Component (#%d): %s"" % \ + (self.id, self.name) + + +class Reaction(Base): + __tablename__ = 'reaction' + + id = Column(Integer, primary_key=True) + type = Column(String(20)) + bigg_id = Column(String, nullable=False) + name = Column(String, nullable=True) + reaction_hash = Column(String, nullable=False) + pseudoreaction = Column(Boolean, default=False) + + __table_args__ = ( + UniqueConstraint('bigg_id'), + ) + + __mapper_args__ = { + 'polymorphic_identity': 'reaction', + 'polymorphic_on': type + } + + def __repr__(self): + return ('' % + (self.id, self.bigg_id, ', pseudoreaction' if self.pseudoreaction else '')) + + +class DataSource(Base): + __tablename__ = 'data_source' + + id = Column(Integer, primary_key=True) + bigg_id = Column(String, nullable=False) + name = Column(String(100)) + url_prefix = Column(String) + + __table_args__ = ( + UniqueConstraint('bigg_id'), + ) + + def __repr__(self): + return ( + '' + ).format(self=self) + + +class Synonym(Base): + __tablename__ = 'synonym' + id = Column(Integer, primary_key=True) + ome_id = Column(Integer) + synonym = Column(String) + type = Column(custom_enums['synonym_type']) + data_source_id = Column(Integer, ForeignKey('data_source.id', ondelete='CASCADE')) + + __table_args__ = ( + UniqueConstraint('ome_id', 'synonym', 'type', 'data_source_id'), + ) + + def __repr__(self): + return ('' % + (self.id, self.synonym, self.type, self.ome_id, self.data_source_id)) + + +class Publication(Base): + __tablename__ = ""publication"" + id = Column(Integer, primary_key=True) + reference_type = Column(custom_enums['reference_type']) + reference_id = Column(String) + + __table_args__=( + UniqueConstraint('reference_type', 'reference_id'), + ) + + +class PublicationModel(Base): + __tablename__ = ""publication_model"" + model_id = Column(Integer, + ForeignKey('model.id', ondelete='CASCADE'), + primary_key=True) + publication_id = Column(Integer, + ForeignKey('publication.id', ondelete='CASCADE'), + primary_key=True) + + __table_args__ = ( + UniqueConstraint('model_id', 'publication_id'), + ) + + +class OldIDSynonym(Base): + __tablename__ = ""old_id_model_synonym"" + id = Column(Integer, primary_key=True) + type = Column(custom_enums['old_id_synonym_type']) + synonym_id = Column(Integer, + ForeignKey('synonym.id', ondelete='CASCADE'), + nullable=False) + ome_id = Column(Integer, nullable=False) + + __table_args__ = ( + UniqueConstraint('synonym_id', 'ome_id'), + ) + + def __repr__(self): + return ('' % + (self.id, self.type, self.ome_id, self.synonym_id)) + + +class GenomeRegionMap(Base): + __tablename__ = 'genome_region_map' + + genome_region_id_1 = Column(Integer, ForeignKey('genome_region.id'), primary_key=True) + genome_region_id_2 = Column(Integer, ForeignKey('genome_region.id'), primary_key=True) + distance = Column(Integer) + + __table_args__ = ( + UniqueConstraint('genome_region_id_1','genome_region_id_2'), + ) + + def __repr__(self): + return ""GenomeRegionMap (%d <--> %d) distance:%d"" % (self.genome_region_id_1, self.genome_region_id_2, self.distance) + + +class DeprecatedID(Base): + __tablename__ = 'deprecated_id' + + id = Column(Integer, primary_key=True) + type = Column(custom_enums['deprecated_id_types']) + deprecated_id = Column(String) + ome_id = Column(Integer) + + __table_args__ = ( + UniqueConstraint('type', 'deprecated_id', 'ome_id'), + ) + + def __repr__(self): + return ('' % + (self.type, self.deprecated_id, self.ome_id)) + + +class Model(Base): + __tablename__='model' + + id = Column(Integer, primary_key=True) + bigg_id = Column(String, nullable=False) + genome_id = Column(Integer, ForeignKey('genome.id', onupdate='CASCADE', ondelete=""CASCADE"")) + organism = Column(String(200), nullable=True) + published_filename = Column(String, nullable=True) + + __table_args__ = ( + UniqueConstraint('bigg_id', 'genome_id'), + ) + + def __repr__(self): + return ''.format(self=self) + + +class ModelGene(Base): + __tablename__='model_gene' + + id = Column(Integer, primary_key=True) + model_id = Column(Integer, + ForeignKey('model.id', onupdate=""CASCADE"", ondelete=""CASCADE""), + nullable=False) + gene_id = Column(Integer, + ForeignKey('gene.id', onupdate=""CASCADE"", ondelete=""CASCADE""), + nullable=False) + + __table_args__ = ( + UniqueConstraint('model_id', 'gene_id'), + ) + + +class ModelReaction(Base): + __tablename__='model_reaction' + + id = Column(Integer, primary_key=True) + reaction_id = Column(Integer, + ForeignKey('reaction.id', onupdate=""CASCADE"", ondelete=""CASCADE""), + nullable=False) + model_id = Column(Integer, + ForeignKey('model.id', onupdate=""CASCADE"", ondelete=""CASCADE""), + nullable=False) + copy_number = Column(Integer, nullable=False) + + objective_coefficient = Column(Float, nullable=False) + lower_bound = Column(Float, nullable=False) + upper_bound = Column(Float, nullable=False) + gene_reaction_rule = Column(String, nullable=False) + original_gene_reaction_rule = Column(String, nullable=True) + subsystem = Column(String, nullable=True) + + __table_args__ = ( + UniqueConstraint('reaction_id', 'model_id', 'copy_number'), + ) + + def __repr__(self): + return ('' + .format(self=self)) + + +class GeneReactionMatrix(Base): + __tablename__ = 'gene_reaction_matrix' + + id = Column(Integer, primary_key=True) + model_gene_id = Column(Integer, + ForeignKey('model_gene.id', onupdate=""CASCADE"", ondelete=""CASCADE""), + nullable=False) + model_reaction_id = Column(Integer, + ForeignKey('model_reaction.id', onupdate=""CASCADE"", ondelete=""CASCADE""), + nullable=False) + + __table_args__ = ( + UniqueConstraint('model_gene_id', 'model_reaction_id'), + ) + + def __repr__(self): + return ('' + .format(self=self)) + + +class CompartmentalizedComponent(Base): + __tablename__='compartmentalized_component' + id = Column(Integer, primary_key=True) + component_id = Column(Integer, + ForeignKey('component.id', onupdate=""CASCADE"", ondelete=""CASCADE""), + nullable=False) + compartment_id = Column(Integer, + ForeignKey('compartment.id', onupdate=""CASCADE"", ondelete=""CASCADE""), + nullable=False) + + __table_args__ = ( + UniqueConstraint('compartment_id', 'component_id'), + ) + + +class ModelCompartmentalizedComponent(Base): + __tablename__='model_compartmentalized_component' + id = Column(Integer, primary_key=True) + model_id = Column(Integer, + ForeignKey('model.id', onupdate=""CASCADE"", ondelete=""CASCADE""), + nullable=False) + compartmentalized_component_id = Column(Integer, + ForeignKey('compartmentalized_component.id'), + nullable=False) + formula = Column(String, nullable=True) + charge = Column(Integer, nullable=True) + + __table_args__ = ( + UniqueConstraint('compartmentalized_component_id', 'model_id'), + ) + + +class Compartment(Base): + __tablename__ = 'compartment' + id = Column(Integer, primary_key=True) + bigg_id = Column(String, unique = True) + name = Column(String) + + def __repr__(self): + return ('' + .format(self=self)) + + +class ReactionMatrix(Base): + __tablename__ = 'reaction_matrix' + id = Column(Integer, primary_key=True) + reaction_id = Column(Integer, ForeignKey('reaction.id'), nullable=False) + compartmentalized_component_id = Column(Integer, + ForeignKey('compartmentalized_component.id', + onupdate=""CASCADE"", ondelete=""CASCADE""), + nullable=False) + stoichiometry = Column(Float) + + __table_args__ = ( + UniqueConstraint('reaction_id', 'compartmentalized_component_id'), + ) + + +class EscherMap(Base): + __tablename__ = 'escher_map' + id = Column(Integer, primary_key=True) + map_name = Column(String, nullable=False) + map_data = Column(LargeBinary, nullable=False) + model_id = Column(Integer, ForeignKey(Model.id), nullable=False) + priority = Column(Integer, nullable=False) + + __table_args__ = ( + UniqueConstraint('map_name'), + ) + + +class EscherMapMatrix(Base): + __tablename__ = 'escher_map_matrix' + id = Column(Integer, primary_key=True) + ome_id = Column(Integer, nullable=False) + type = Column(custom_enums['escher_map_matrix_type'], nullable=False) + escher_map_id = Column(Integer, ForeignKey(EscherMap.id), nullable=False) + # the reaction id or node id + escher_map_element_id = Column(String(50)) + + __table_args__ = ( + UniqueConstraint('ome_id', 'type', 'escher_map_id'), + ) + + +class ModelCount(Base): + __tablename__='model_count' + id = Column(Integer, primary_key=True) + model_id = Column(Integer, + ForeignKey('model.id', onupdate=""CASCADE"", ondelete=""CASCADE""), + nullable=False) + reaction_count = Column(Integer) + gene_count = Column(Integer) + metabolite_count = Column(Integer) + + +class Gene(GenomeRegion): + __tablename__ = 'gene' + + id = Column(Integer, + ForeignKey('genome_region.id', onupdate=""CASCADE"", ondelete=""CASCADE""), + primary_key=True) + name = Column(String, nullable=True) + locus_tag = Column(String, nullable=True) + mapped_to_genbank = Column(Boolean, nullable=False) + alternative_transcript_of = Column(Integer, + ForeignKey('gene.id'), + nullable=True) + + __mapper_args__ = {'polymorphic_identity': 'gene'} + + def __repr__(self): + return '' % (self.id, self.bigg_id, + self.name) +","Python" +"Metabolic","SBRG/cobradb","cobradb/settings.py",".py","2814","79","# -*- coding: utf-8 -*- + +""""""Retrive local user settings"""""" + +from configparser import ConfigParser, NoOptionError +import os +from os.path import join, split, abspath, isfile, expanduser, dirname +from sys import modules +import six + +self = modules[__name__] + +# define various filepaths + +config = ConfigParser() + +# overwrite defaults settings with settings from the file +filepath = abspath(join(dirname(__file__), '..', 'settings.ini')) +if isfile(filepath): + config.read(filepath) +else: + raise Exception('No settings files at path: %s' % filepath) + +# prefer environment variables for database settings +env_names = { + 'postgres_host': 'COBRADB_POSTGRES_HOST', + 'postgres_port': 'COBRADB_POSTGRES_PORT', + 'postgres_user': 'COBRADB_POSTGRES_USER', + 'postgres_password': 'COBRADB_POSTGRES_PASSWORD', + 'postgres_database': 'COBRADB_POSTGRES_DATABASE', + 'postgres_test_database': 'COBRADB_POSTGRES_TEST_DATABASE', +} +for setting_name, env_name in six.iteritems(env_names): + if env_name in os.environ: + print('Setting %s with environment variable %s' % (setting_name, + env_name)) + setattr(self, setting_name, os.environ[env_name]) + else: + setattr(self, setting_name, config.get('DATABASE', setting_name)) + +# set up the database connection string +self.db_connection_string = ('postgresql://%s:%s@%s:%s/%s' % + (self.postgres_user, self.postgres_password, + self.postgres_host, self.postgres_port, + self.postgres_database)) + +# get the java executable (optional, for running Model Polisher) +if config.has_option('EXECUTABLES', 'java'): + self.java = config.get('EXECUTABLES', 'java') +else: + print('No Java executable provided.') + +if not config.has_section('DATA'): + raise Exception('DATA section was not found in settings.ini') + +# these are required +try: + self.model_directory = expanduser(config.get('DATA', 'model_directory')) +except NoOptionError: + raise Exception('model_directory was not supplied in settings.ini') + +try: + self.refseq_directory = expanduser(config.get('DATA', 'refseq_directory')) +except NoOptionError: + raise Exception('refseq_directory was not supplied in settings.ini') +try: + self.model_genome = expanduser(config.get('DATA', 'model_genome')) +except NoOptionError: + raise Exception('model_genome path was not supplied in settings.ini') + +# these are optional +for data_pref in ['compartment_names', 'reaction_hash_prefs', + 'gene_reaction_rule_prefs', 'data_source_preferences', + 'metabolite_duplicates']: + try: + setattr(self, data_pref, expanduser(config.get('DATA', data_pref))) + except NoOptionError: + setattr(self, data_pref, None) +","Python" +"Metabolic","SBRG/cobradb","cobradb/parse.py",".py","19644","561","# -*- coding: utf-8 -*- + +from cobradb.models import NotFoundError +from cobradb.util import scrub_gene_id, load_tsv, increment_id +from cobradb import settings + +import re +import cobra +import cobra.io +from os.path import join +import hashlib +import logging +from collections import defaultdict +import six + + +def _hash_fn(s): + to_hash = s if isinstance(s, six.binary_type) else s.encode('utf8') + # python 2: md5(bytes).hexdigest() => Py2 bytes str + # python 3: md5(bytes).hexdigest() => Py3 unicode str + return hashlib.md5(to_hash).hexdigest() + + +def hash_metabolite_dictionary(met_dict, string_only): + """"""Generate a unique hash for the metabolites and coefficients of the + reaction. Returns the native str type for Python 2 or 3. + + met_dict: A dictionary where keys are metabolite IDs and values and + coefficients. + + string_only: If True, return the string that would be hashed. + + """""" + sorted_mets = sorted([(m, v) for m, v in six.iteritems(met_dict)], + key=lambda x: x[0]) + sorted_mets_str = ''.join(['%s%.3f' % t for t in sorted_mets]) + if string_only: + return sorted_mets_str + else: + return _hash_fn(sorted_mets_str) + + +def hash_reaction(reaction, metabolite_dict, string_only=False, reverse=False): + """"""Generate a unique hash for the metabolites and coefficients of the + reaction. + + reaction: A COBRA Reaction. + + metabolite_dict: Dictionary to look up new metabolite ids. + + string_only: If True, return the string that would be hashed. + + """""" + the_dict = {metabolite_dict[m.id]: (-v if reverse else v) + for m, v in six.iteritems(reaction.metabolites)} + return hash_metabolite_dictionary(the_dict, string_only) + + +def load_and_normalize(model_filepath): + """"""Load a model, and give it a particular id style"""""" + + # load the model + if model_filepath.endswith('.xml'): + model = cobra.io.read_sbml_model(model_filepath) + elif model_filepath.endswith('.mat'): + model = cobra.io.load_matlab_model(model_filepath) + elif model_filepath.endswith('.json'): + model = cobra.io.load_json_model(model_filepath) + else: + raise Exception('The %s file is not a valid filetype', model_filepath) + # convert the ids + model, old_ids = convert_ids(model) + + # extract metabolite formulas from names (e.g. for iAF1260) + model = get_formulas_from_names(model) + + return model, old_ids + + +def _get_rule_prefs(): + """"""Get gene_reaction_rule prefs."""""" + return load_tsv(settings.gene_reaction_rule_prefs, required_column_num=2) + + +def _check_rule_prefs(rule_prefs, rule): + """"""Check the gene_reaction_rule against the prefs file, and return an existing + rule or the fixed one."""""" + for row in rule_prefs: + old_rule, new_rule = row + if old_rule == rule: + return new_rule + return rule + + +def remove_boundary_metabolites(model): + """"""Remove boundary metabolites (end in _b and only present in exchanges). Be + sure to loop through a static list of ids so the list does not get shorter + as the metabolites are deleted. + + """""" + for metabolite_id in [str(x) for x in model.metabolites]: + metabolite = model.metabolites.get_by_id(metabolite_id) + if not metabolite.id.endswith(""_b""): + continue + for reaction in list(metabolite._reaction): + if reaction.id.startswith(""EX_""): + metabolite.remove_from_model() + break + model.metabolites._generate_index() + +#----------------- +# Pseudoreactions +#----------------- + +class ConflictingPseudoreaction(Exception): + pass + + +def _has_gene_reaction_rule(reaction): + """"""Check if the reaction has a gene reaction rule."""""" + rule = getattr(reaction, 'gene_reaction_rule', None) + return rule is not None and rule.strip() != '' + + +def _reaction_single_met_coeff(reaction): + if len(reaction.metabolites) == 1: + return next(six.iteritems(reaction.metabolites)) + return None + + +def _reverse_reaction(reaction): + """"""Reverse the metabolite coefficients and the upper & lower bounds."""""" + reaction.add_metabolites({k: -v for k, v in six.iteritems(reaction.metabolites)}, + combine=False) + reaction.upper_bound, reaction.lower_bound = -reaction.lower_bound, -reaction.upper_bound + + +def _fix_exchange(reaction): + """"""Returns new id if the reaction was treated as an exchange."""""" + # does it look like an exchange? + met_coeff = _reaction_single_met_coeff(reaction) + if met_coeff is None: + return None + met, coeff = met_coeff + if split_compartment(remove_duplicate_tag(met.id))[1] != 'e': + return None + # check id + if not re.search(r'^ex_', reaction.id, re.IGNORECASE): + logging.warning('Reaction {r.id} looks like an exchange but it does not start with EX_. Renaming' + .format(r=reaction)) + # check coefficient + if abs(coeff) != 1: + raise ConflictingPseudoreaction('Reaction {} looks like an exchange ' + 'but it has a reactant with coefficient {}' + .format(reaction.id, coeff)) + # reverse if necessary + if coeff == 1: + _reverse_reaction(reaction) + logging.debug('Reversing pseudoreaction %s' % reaction.id) + return 'EX_%s' % met.id, 'Extracellular exchange' + + +# for sink & demand functions +_sink_regex = re.compile(r'^(sink|sk)_', re.IGNORECASE) + + +def _fix_demand(reaction): + """"""Returns new ID if the reaction was treated as a demand."""""" + # does it look like a demand? + met_coeff = _reaction_single_met_coeff(reaction) + if met_coeff is None: + return None + met, coeff = met_coeff + if split_compartment(met.id)[1] == 'e': + return None + # source bound should be 0 + if ((coeff > 0 and reaction.upper_bound != 0) or + (coeff < 0 and reaction.lower_bound != 0)): + return None + # if it could be a demand, but it is named sink_ or SK_, then let it be a + # sink (by returning None) because sink is really a superset of demand + if _sink_regex.search(reaction.id): + return None + # check id + if not re.search(r'^dm_', reaction.id, re.IGNORECASE): + logging.warning('Reaction {r.id} looks like a demand but it does not start with DM_. Renaming.' + .format(r=reaction)) + # check coefficient + if abs(coeff) != 1: + raise ConflictingPseudoreaction('Reaction {} looks like a demand ' + 'but it has a reactant with coefficient {}' + .format(reaction.id, coeff)) + # reverse if necessary + if coeff == 1: + _reverse_reaction(reaction) + logging.debug('Reversing pseudoreaction %s' % reaction.id) + return 'DM_%s' % met.id, 'Intracellular demand' + + +def _fix_sink(reaction): + """"""Returns new ID if the reaction was treated as a sink."""""" + # does it look like a sink? + met_coeff = _reaction_single_met_coeff(reaction) + if met_coeff is None: + return None + met, coeff = met_coeff + if split_compartment(met.id)[1] == 'e': + return None + # check id + if not _sink_regex.search(reaction.id): + logging.warning('Reaction {r.id} looks like a sink but it does not start with sink_ or SK_. Renaming.' + .format(r=reaction)) + # check coefficient + if abs(coeff) != 1: + raise ConflictingPseudoreaction('Reaction {} looks like a sink ' + 'but it has a reactant with coefficient {}' + .format(reaction.id, coeff)) + # reverse if necessary + if coeff == 1: + _reverse_reaction(reaction) + logging.debug('Reversing pseudoreaction %s' % reaction.id) + return 'SK_%s' % met.id, 'Intracellular source/sink' + + +def _fix_biomass(reaction): + """"""Returns new ID if the reaction was treated as a biomass."""""" + # does it look like an exchange? + regex = re.compile(r'biomass', re.IGNORECASE) + if not regex.search(reaction.id): + return None + new_id = ('BIOMASS_%s' % regex.sub('', reaction.id)).replace('__', '_') + return new_id, 'Biomass and maintenance functions' + + +def _fix_atpm(reaction): + """"""Returns new ID if the reaction was treated as a biomass."""""" + # does it look like a atpm? + mets = {k.id: v for k, v in six.iteritems(reaction.metabolites)} + subsystem = 'Biomass and maintenance functions' + if mets == {'atp_c': -1, 'h2o_c': -1, 'pi_c': 1, 'h_c': 1, 'adp_c': 1}: + return 'ATPM', subsystem + elif mets == {'atp_c': 1, 'h2o_c': 1, 'pi_c': -1, 'h_c': -1, 'adp_c': -1}: + _reverse_reaction(reaction) + logging.debug('Reversing pseudoreaction %s' % reaction.id) + return 'ATPM', subsystem + return None + + +def _normalize_pseudoreaction(new_style_id, reaction): + """"""If the reaction is a pseudoreaction (exchange, demand, sink, biomass, or + ATPM), then apply standard rules to it."""""" + + pseudo_id = None; subsystem = None + + # check atpm separately because there is a good reason for an atpm-like + # reaction with a gene_reaction_rule + is_atpm = False + res = _fix_atpm(reaction) + if res is not None: + pseudo_id, subsystem = res + reaction.subsystem = subsystem + is_atpm = True + + # check for other pseudoreactions + fns = [_fix_exchange, _fix_demand, _fix_sink, _fix_biomass] + res = None + for fn in fns: + if res is not None: + break + res = fn(reaction) + if res is not None: + pseudo_id, subsystem = res + reaction.subsystem = subsystem + + if pseudo_id is not None: + # does it have a gene_reaction_rule? OK if atpm reaction has + # gene_reaction_rule. + if _has_gene_reaction_rule(reaction): + if is_atpm: + return + raise ConflictingPseudoreaction('Reaction {r.id} looks like a pseudoreaction ' + 'but it has a gene_reaction_rule: ' + '{r.gene_reaction_rule}'.format(r=reaction)) + + return pseudo_id + + +#---------- +# ID fixes +#---------- + +def remove_duplicate_tag(the_id): + return re.sub(r'\$\$DROP.*', '', the_id) + +def add_duplicate_tag(the_id): + return '%s$$DROP' % the_id + + +def convert_ids(model): + """"""Converts metabolite and reaction ids to the new style. + + Returns a tuple with the new model and a dictionary of old ids set up like this: + + {'reactions': {'new_id': 'old_id'}, + 'metabolites': {'new_id': 'old_id'}, + 'genes': {'new_id': 'old_id'}} + + """""" + # loop through the ids: + metabolite_id_dict = defaultdict(list) + reaction_id_dict = defaultdict(list) + gene_id_dict = defaultdict(list) + + # fix metabolites + for metabolite in model.metabolites: + new_id = id_for_new_id_style(fix_legacy_id(metabolite.id, use_hyphens=False), + is_metabolite=True) + metabolite_id_dict[new_id].append(metabolite.id) + if new_id != metabolite.id: + # new_id already exists, then merge + if new_id in model.metabolites: + new_id = add_duplicate_tag(new_id) + while new_id in model.metabolites: + new_id = increment_id(new_id) + metabolite.id = new_id + model.metabolites._generate_index() + + # take out the _b metabolites + remove_boundary_metabolites(model) + + # load fixes for gene_reaction_rule's + rule_prefs = _get_rule_prefs() + + # separate ids and compartments, and convert to the new_id_style + for reaction in model.reactions: + # apply new id style + new_style_id = id_for_new_id_style(fix_legacy_id(reaction.id, use_hyphens=False)) + + # normalize pseudoreaction IDs + try: + pseudo_id = _normalize_pseudoreaction(new_style_id, reaction) + except ConflictingPseudoreaction as e: + logging.warning(str(e)) + # keep going despite the warning + pass + + new_id = pseudo_id if pseudo_id is not None else new_style_id + + # don't merge reactions with conflicting new_id's + if new_id != reaction.id and new_id in model.reactions: + new_id = add_duplicate_tag(new_id) + while new_id in model.reactions: + new_id = increment_id(new_id) + + reaction_id_dict[new_id].append(reaction.id) + reaction.id = new_id + + # fix the gene reaction rules + reaction.gene_reaction_rule = _check_rule_prefs(rule_prefs, reaction.gene_reaction_rule) + + model.reactions._generate_index() + + # update the genes + for gene in list(model.genes): + new_id = scrub_gene_id(gene.id) + gene_id_dict[new_id].append(gene.id) + for reaction in gene.reactions: + reaction.gene_reaction_rule = re.sub(r'\b' + re.escape(gene.id) + r'\b', new_id, + reaction.gene_reaction_rule) + + # remove old genes + from cobra.manipulation import remove_genes + remove_genes(model, [gene for gene in model.genes + if len(gene.reactions) == 0]) + + # fix the model id + bigg_id = re.sub(r'[^a-zA-Z0-9_]', '_', model.id) + model.id = bigg_id + + old_ids = {'metabolites': metabolite_id_dict, + 'reactions': reaction_id_dict, + 'genes': gene_id_dict} + + return model, old_ids + + +# the regex to separate the base id, the chirality ('_L') and the compartment ('_c') +reg_compartment = re.compile(r'(.*?)[_\(\[]([a-z][a-z0-9]?)[_\)\]]?$') +reg_chirality = re.compile(r'(.*?)_?_([LDSRM])$') +def id_for_new_id_style(old_id, is_metabolite=False): + """""" Get the new style id"""""" + new_id = old_id + + def _join_parts(the_id, the_compartment): + if the_compartment: + the_id = the_id + '_' + the_compartment + return the_id + + def _remove_d_underscore(s): + """"""Removed repeated, leading, and trailing underscores."""""" + s = re.sub(r'_+', '_', s) + s = re.sub(r'^_+', '', s) + s = re.sub(r'_+$', '', s) + return s + + # remove parentheses and brackets, for SBML & BiGG spec compatibility + new_id = re.sub(r'[^a-zA-Z0-9_]', '_', new_id) + + compartment_match = reg_compartment.match(new_id) + if compartment_match is None: + # still remove double underscores + new_id = _remove_d_underscore(new_id) + else: + base, compartment = compartment_match.groups() + chirality_match = reg_chirality.match(base) + if chirality_match is None: + new_id = _join_parts(_remove_d_underscore(base), compartment) + else: + new_base = '%s__%s' % (_remove_d_underscore(chirality_match.group(1)), + chirality_match.group(2)) + new_id = _join_parts(new_base, compartment) + + return new_id + + +def get_formulas_from_names(model): + reg = re.compile(r'.*_([A-Z][A-Z0-9]*)$') + # support cobra 0.3 and 0.4 + for metabolite in model.metabolites: + if (metabolite.formula is not None and str(metabolite.formula) != '' and getattr(metabolite, 'formula', None) is not None): + continue + name = getattr(metabolite, 'name', None) + if name: + m = reg.match(name) + if m: + metabolite.formula = m.group(1) + return model + + +def invalid_formula(formula): + return formula is not None and re.search(r'[^A-Za-z0-9]', formula) + +#------------- +# Model setup +#------------- + +def setup_model(model, substrate_reactions, aerobic=True, sur=10, max_our=10, + id_style='cobrapy', fix_iJO1366=False): + """"""Set up the model with environmntal parameters. + + model: a cobra model + substrate_reactions: A single reaction id, list of reaction ids, or dictionary with reaction + ids as keys and max substrate uptakes as keys. If a list or single id is + given, then each substrate will be limited to /sur/ + aerobic: True or False + sur: substrate uptake rate. Ignored if substrate_reactions is a dictionary. + max_our: Max oxygen uptake rate. + id_style: 'cobrapy' or 'simpheny'. + + """""" + if id_style=='cobrapy': o2 = 'EX_o2_e' + elif id_style=='simpheny': o2 = 'EX_o2(e)' + else: raise Exception('Invalid id_style') + + if isinstance(substrate_reactions, dict): + for r, v in six.iteritems(substrate_reactions): + model.reactions.get_by_id(r).lower_bound = -abs(v) + elif isinstance(substrate_reactions, list): + for r in substrate_reactions: + model.reactions.get_by_id(r).lower_bound = -abs(sur) + elif isinstance(substrate_reactions, str): + model.reactions.get_by_id(substrate_reactions).lower_bound = -abs(sur) + else: raise Exception('bad substrate_reactions argument') + + if aerobic: + model.reactions.get_by_id(o2).lower_bound = -abs(max_our) + else: + model.reactions.get_by_id(o2).lower_bound = 0 + + # model specific setup + if str(model)=='iJO1366' and aerobic==False: + for r in ['CAT', 'SPODM', 'SPODMpp']: + model.reactions.get_by_id(r).lower_bound = 0 + model.reactions.get_by_id(r).upper_bound = 0 + if fix_iJO1366 and str(model)=='iJO1366': + for r in ['ACACT2r']: + model.reactions.get_by_id(r).upper_bound = 0 + print('made ACACT2r irreversible') + + # TODO hydrogen reaction for ijo + + if str(model)=='iMM904' and aerobic==False: + necessary_ex = ['EX_ergst(e)', 'EX_zymst(e)', 'EX_hdcea(e)', + 'EX_ocdca(e)', 'EX_ocdcea(e)', 'EX_ocdcya(e)'] + for r in necessary_ex: + rxn = model.reactions.get_by_id(r) + rxn.lower_bound = -1000 + rxn.upper_bound = 1000 + + return model + +def turn_on_subsystem(model, subsystem): + raise NotImplementedError() + for reaction in model.reactions: + if reaction.subsystem.strip('_') == subsystem.strip('_'): + reaction.lower_bound = -1000 if reaction.reversibility else 0 + reaction.upper_bound = 1000 + return model + +def carbons_for_exchange_reaction(reaction): + if len(reaction._metabolites) > 1: + raise Exception('%s not an exchange reaction' % str(reaction)) + + metabolite = next(reaction._metabolites.iterkeys()) + try: + return metabolite.formula.elements['C'] + except KeyError: + return 0 + # match = re.match(r'C([0-9]+)', str(metabolite.formula)) + # try: + # return int(match.group(1)) + # except AttributeError: + # return 0 + +def fix_legacy_id(id, use_hyphens=False): + id = id.replace('_DASH_', '__') + id = id.replace('_FSLASH_', '/') + id = id.replace('_BSLASH_', ""\\"") + id = id.replace('_LPAREN_', '(') + id = id.replace('_LSQBKT_', '[') + id = id.replace('_RSQBKT_', ']') + id = id.replace('_RPAREN_', ')') + id = id.replace('_COMMA_', ',') + id = id.replace('_PERIOD_', '.') + id = id.replace('_APOS_', ""'"") + id = id.replace('&', '&') + id = id.replace('<', '<') + id = id.replace('>', '>') + id = id.replace('"', '""') + if use_hyphens: + id = id.replace('__', '-') + else: + id = id.replace(""-"", ""__"") + return id + +def split_compartment(component_id): + """"""Split the metabolite bigg_id into a metabolite and a compartment id. + + Arguments + --------- + + component_id: the bigg_id of the metabolite. + + """""" + match = re.search(r'_[a-z][a-z0-9]?$', component_id) + if match is None: + raise NotFoundError(""No compartment found for %s"" % component_id) + met = component_id[0:match.start()] + compartment = component_id[match.start()+1:] + return met, compartment +","Python" +"Metabolic","SBRG/cobradb","cobradb/component_loading.py",".py","11307","317","# -*- coding: utf-8 -*- + +from cobradb.models import * +from cobradb import settings +from cobradb.util import (scrub_gene_id, get_or_create_data_source, + get_or_create, timing) + +import sys, os, math, re +from os.path import basename +from warnings import warn +from sqlalchemy import text, or_, and_, func +import logging +import six +import itertools as it + + +class BadGenomeError(Exception): + pass + + +def _load_gb_file(genbank_file_handle): + """"""Load the Genbank file. + + Arguments + --------- + + genbank_file_handle: The handle to the genbank file. + + """""" + # imports + from Bio import SeqIO + + # load the genbank file + logging.debug('Loading file: %s' % genbank_file_handle.name) + try: + gb_file = SeqIO.read(genbank_file_handle, 'gb') + except IOError: + raise BadGenomeError(""File '%s' not found"" % genbank_file_handle.name) + except Exception as e: + raise BadGenomeError('BioPython failed to parse %s with error ""%s""' % + (genbank_file_handle.name, e.message)) + return gb_file + + +def get_genbank_accessions(genbank_filepath, fast=False): + """"""Load the file and return the NCBI Accession and Assembly IDs (if available). + + Returns a dictionary of accessions with keys: 'ncbi_accession', + 'ncbi_assembly', 'ncbi_bioproject'. + + Arguments + --------- + + genbank_filepath: The path to the genbank file. + + fast: If True, then only look in the first 100 lines. Faster because we do + not load the whole file. + + """""" + out = {'ncbi_assembly': None, + 'ncbi_accession': None, + 'ncbi_bioproject': None} + + if fast: + # try to find the BioProject ID in the first 100 lines. Otherwise, use + # the full SeqIO.read + line_limit = 100 + regex_dict = { + k: re.compile(v) for k, v in six.iteritems({ + 'ncbi_accession': r'VERSION\s+([\w.-]+)[^\w.-]', + 'ncbi_assembly': r'Assembly:\s*([\w.-]+)[^\w.-]', + 'ncbi_bioproject': r'BioProject:\s*([\w.-]+)[^\w.-]' + }) + } + with open(genbank_filepath, 'r') as f: + for i, line in enumerate(f.readlines()): + for key, regex in six.iteritems(regex_dict): + match = regex.search(line) + if match is not None: + out[key] = match.group(1) + if i > line_limit: + break + else: + # load the genbank file + with open(genbank_filepath, 'r') as f: + gb_file = _load_gb_file(f) + out['ncbi_accession'] = gb_file.id + for value in it.chain.from_iterable(x.split() for x in gb_file.dbxrefs): + if 'Assembly' in value: + out['ncbi_assembly'] = value.split(':')[1] + if 'BioProject' in value: + out['ncbi_bioproject'] = value.split(':')[1] + + return out + + +def load_gene_synonym(session, gene_db, synonym, data_source_id): + """"""Load the synonym for this gene from the given genome."""""" + data_source_id = get_or_create_data_source(session, data_source_id) + synonym_db, _ = get_or_create(session, Synonym, + type='gene', + ome_id=gene_db.id, + synonym=synonym, + data_source_id=data_source_id) + return synonym_db.id + + +def _get_qual(feat, name, get_first=False): + """"""Get a non-null attribute from the feature."""""" + try: + qual = feat.qualifiers[name] + except KeyError: + if get_first: + return None + else: + return [] + + def nonempty_str(s): + s = s.strip() + return None if s == '' else s + + if get_first: + return nonempty_str(qual[0]) + else: + return [y for y in (nonempty_str(x) for x in qual) + if y is not None] + +def _get_geneid(feature): + """"""Get the value of GeneID from db_xref, or else return None."""""" + db_xref = _get_qual(feature, 'db_xref') + if not db_xref: + return None + for ref in db_xref: + splitrefs = [x.strip() for x in ref.split(':')] + if len(splitrefs) == 2 and splitrefs[0].lower() == 'geneid': + return splitrefs[1] + return None + +@timing +def load_genome(genome_ref, genome_file_paths, session): + """"""Load the genome and chromosomes."""""" + + if len(genome_file_paths) == 0: + raise Exception('No files found for genome {}'.format(genome_ref)) + + # check that the genome doesn't already exist + if (session.query(Genome) + .filter(Genome.accession_type == genome_ref[0]) + .filter(Genome.accession_value == genome_ref[1])).count() > 0: + raise AlreadyLoadedError('Genome with %s %s already loaded' % genome_ref) + + logging.debug('Adding new genome: {}'.format(genome_ref)) + genome_db = Genome(accession_type=genome_ref[0], + accession_value=genome_ref[1]) + session.add(genome_db) + session.commit() + + n = len(genome_file_paths) + for i, genbank_file_path in enumerate(genome_file_paths): + logging.info('Loading chromosome [{} of {}] {}' + .format(i + 1, n, basename(genbank_file_path))) + with open(genbank_file_path, 'r') as f: + gb_file = _load_gb_file(f) + load_chromosome(gb_file, genome_db, session) + + +def first_uppercase(val): + if val is None: + return val + return str(val[0]).upper() + + +def load_chromosome(gb_file, genome_db, session): + chromosome = (session + .query(Chromosome) + .filter(Chromosome.ncbi_accession == gb_file.id) + .filter(Chromosome.genome_id == genome_db.id) + .first()) + if not chromosome: + logging.debug('Loading new chromosome: {}'.format(gb_file.id)) + chromosome = Chromosome(ncbi_accession=gb_file.id, + genome_id=genome_db.id) + session.add(chromosome) + session.commit() + else: + logging.debug('Chromosome already loaded: %s' % gb_file.id) + + # update genome + if genome_db.organism is None: + genome_db.organism = gb_file.annotations['organism'] + + bigg_id_warnings = 0 + duplicate_genes_warnings = 0 + warning_num = 5 + for i, feature in enumerate(gb_file.features): + + # update genome with the source information + if genome_db.taxon_id is None and feature.type == 'source': + for ref in _get_qual(feature, 'db_xref'): + if 'taxon' == ref.split(':')[0]: + genome_db.taxon_id = ref.split(':')[1] + break + continue + + # only read in CDSs + if feature.type != 'CDS': + continue + + # bigg_id required + bigg_id = None + gene_name = None + refseq_name = None + locus_tag = None + + # get bigg_id if possible from locus_tag or and GeneID + found_tag = _get_qual(feature, 'locus_tag', True) + found_gene_id = _get_geneid(feature) + if found_tag is not None: + locus_tag = found_tag + bigg_id = scrub_gene_id(found_tag) + elif found_gene_id is not None: + bigg_id = scrub_gene_id(found_gene_id) + + # get name + found_name = _get_qual(feature, 'gene', True) + if found_name is not None: + gene_name = found_name + refseq_name = found_name + + # warn about no locus_tag / bigg_id + if gene_name is not None and bigg_id is None: + if bigg_id_warnings <= warning_num: + msg = 'No locus_tag for gene. Using Gene name as bigg_id: %s' % gene_name + if bigg_id_warnings == warning_num: + msg += ' (Warnings limited to %d)' % warning_num + logging.warning(msg) + bigg_id_warnings += 1 + bigg_id = scrub_gene_id(gene_name) + gene_name = bigg_id + elif bigg_id is None: + logging.warning(('No locus_tag or gene name for gene %d in chromosome ' + '%s' % (i, chromosome.ncbi_accession))) + continue + + gene_db = (session + .query(Gene) + .filter(Gene.bigg_id == bigg_id) + .filter(Gene.chromosome_id == chromosome.id) + .first()) + if gene_db is None: + # get the strand and positions + strand = None + if feature.strand == 1: + strand = '+' + elif feature.strand == -1: + strand = '-' + leftpos = int(feature.location.start) + 1 + rightpos = int(feature.location.end) + + dna_sequence = str(feature.extract(gb_file.seq)).upper() + protein_sequence = first_uppercase(feature.qualifiers.get('translation', None)) + + # finally, create the gene + gene_db = Gene(bigg_id=bigg_id, + locus_tag=locus_tag, + chromosome_id=chromosome.id, + name=gene_name, + leftpos=leftpos, + rightpos=rightpos, + strand=strand, + dna_sequence=dna_sequence, + protein_sequence=protein_sequence, + mapped_to_genbank=True) + session.add(gene_db) + session.commit() + else: + # warn about duplicate genes. + # + # TODO The only downside to loading CDS's this way is that the + # leftpos and rightpos correspond to a CDS, not the whole gene. So + # these need to be fixed eventually. + if duplicate_genes_warnings <= warning_num: + msg = 'Duplicate genes %s on chromosome %s' % (bigg_id, chromosome.id) + if duplicate_genes_warnings == warning_num: + msg += ' (Warnings limited to %d)' % warning_num + logging.warning(msg) + duplicate_genes_warnings += 1 + + # load the synonyms for the gene + if locus_tag is not None: + load_gene_synonym(session, gene_db, locus_tag, 'refseq_locus_tag') + + if refseq_name is not None: + load_gene_synonym(session, gene_db, refseq_name, 'refseq_name') + + for ref in _get_qual(feature, 'gene_synonym'): + synonyms = [x.strip() for x in ref.split(';')] + for syn in synonyms: + load_gene_synonym(session, gene_db, syn, 'refseq_synonym') + + for ref in _get_qual(feature, 'db_xref'): + splitrefs = [x.strip() for x in ref.split(':')] + if len(splitrefs) == 2: + load_gene_synonym(session, gene_db, splitrefs[1], splitrefs[0]) + + for ref in _get_qual(feature, 'old_locus_tag'): + for syn in [x.strip() for x in ref.split(';')]: + load_gene_synonym(session, gene_db, syn, 'refseq_old_locus_tag') + + for ref in _get_qual(feature, 'note'): + for value in [x.strip() for x in ref.split(';')]: + sp = value.split(':') + if len(sp) == 2 and sp[0] == 'ORF_ID': + load_gene_synonym(session, gene_db, sp[1], 'refseq_orf_id') + + session.commit() +","Python" +"Metabolic","SBRG/cobradb","cobradb/__init__.py",".py","0","0","","Python" +"Metabolic","SBRG/cobradb","cobradb/model_loading.py",".py","47847","1095","# -*- coding: utf-8 -*- + +from cobradb.models import * +from cobradb import settings +from cobradb.model_dumping import dump_model +from cobradb import parse +from cobradb.util import (increment_id, check_pseudoreaction, load_tsv, + get_or_create_data_source, format_formula, scrub_name, + check_none, get_or_create, timing) + +from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound +from sqlalchemy import func +import re +import logging +from collections import defaultdict +import os +from os.path import join, basename, abspath, dirname +from difflib import SequenceMatcher +try: + from itertools import ifilter as filter +except ImportError: + pass +import cobra.io +import six + + +class GenbankNotFound(Exception): + pass + + +def get_model_list(): + """"""Get the models that are available, as SBML, in ome_data/models"""""" + return [x.replace('.xml', '').replace('.mat', '') for x in + os.listdir(join(settings.data_directory, 'models')) + if '.xml' in x or '.mat' in x] + + +def check_for_model(name): + """"""Check for model, case insensitive, and ignore periods and underscores"""""" + def min_name(n): + return n.lower().replace('.','').replace(' ','').replace('_','') + for x in get_model_list(): + if min_name(name)==min_name(x): + return x + return None + + +def _sim(name1, name2): + """"""Return true if the names are similar"""""" + clean1, clean2 = [n.lower().replace(' ', '') for n in [name1, name2]] + return SequenceMatcher(None, clean1, clean2).ratio() > 0.7 + + +def improve_name(session, db, new_name): + """"""If the new_name is a better descriptive name for the reaction or metabolite, + then update. + + """""" + cur_name = db.name + cur_id = db.bigg_id + # New name is not None and not similar to bigg_id + if (new_name is not None and not _sim(new_name, cur_id) and + (cur_name is None or _sim(cur_name, cur_id))): + logging.debug('Replacing name %s with %s' % (cur_name, new_name)) + db.name = new_name + session.commit() + + +@timing +def load_model(model_filepath, pub_ref, genome_ref, session): + """"""Load a model into the database. Returns the bigg_id for the new model. + + Arguments + --------- + + model_filepath: the path to the file where model is stored. + + pub_ref: a publication PMID or doi for the model, as a tuple like this: + + ('doi', '10.1128/ecosalplus.10.2.1') + + ('pmid', '21988831') + + Can be None + + genome_ref: A tuple specifying the genome accession type and value. The + first element can be ncbi_accession, ncbi_assembly, or organism. + + session: An instance of Session. + + """""" + # apply id normalization + logging.debug('Parsing SBML') + model, old_parsed_ids = parse.load_and_normalize(model_filepath) + model_bigg_id = model.id + + # check that the model doesn't already exist + if session.query(Model).filter_by(bigg_id=model_bigg_id).count() > 0: + raise AlreadyLoadedError('Model %s already loaded' % model_bigg_id) + + # check for a genome annotation for this model + if genome_ref is not None and genome_ref[0] == 'organism': + genome_id = None + organism = genome_ref[1] + elif genome_ref is not None and genome_ref[0] in ['ncbi_accession', 'ncbi_assembly']: + genome_db = (session + .query(Genome) + .filter(Genome.accession_type==genome_ref[0]) + .filter(Genome.accession_value==genome_ref[1]) + .first()) + if genome_db is None: + raise GenbankNotFound('Genome for model {} not found with genome_ref {}' + .format(model_bigg_id, genome_ref)) + genome_id = genome_db.id + organism = genome_db.organism + else: + logging.info('No Genome reference or organism provided for model {}'.format(model_bigg_id)) + genome_id = None + organism = None + + # Load the model objects. Remember: ORDER MATTERS! So don't mess around. + logging.debug('Loading objects for model {}'.format(model.id)) + published_filename = os.path.basename(model_filepath) + model_database_id = load_new_model(session, model, genome_id, pub_ref, + published_filename, organism) + + # metabolites/components and linkouts + # get compartment names + if os.path.exists(settings.compartment_names): + with open(settings.compartment_names, 'r') as f: + compartment_names = {} + for line in f.readlines(): + sp = [x.strip() for x in line.split('\t')] + try: + compartment_names[sp[0]] = sp[1] + except IndexError: + continue + else: + logging.warning('No compartment names file') + compartment_names = {} + comp_comp_db_ids, final_metabolite_ids = load_metabolites(session, model_database_id, model, + compartment_names, + old_parsed_ids['metabolites']) + + # reactions + model_db_rxn_ids = load_reactions(session, model_database_id, model, + old_parsed_ids['reactions'], + comp_comp_db_ids, final_metabolite_ids) + + # genes + load_genes(session, model_database_id, model, model_db_rxn_ids, + old_parsed_ids['genes']) + + # count model objects for the model summary web page + load_model_count(session, model_database_id) + + session.commit() + + return model_bigg_id + + +def load_new_model(session, model, genome_db_id, pub_ref, published_filename, + organism): + """"""Load the model. + + Arguments: + --------- + + session: A SQLAlchemy session. + + model: A COBRApy model. + + genome_db_id: The database ID of the genome. Can be None. + + pub_ref: a publication PMID or doi for the model, as a string like this: + + doi:10.1128/ecosalplus.10.2.1 + + pmid:21988831 + + Can be None + + organism: The organism. Can be None. + + Returns: + ------- + + The database ID of the new model row. + + """""" + model_db = Model(bigg_id=model.id, genome_id=genome_db_id, + published_filename=published_filename, organism=organism) + session.add(model_db) + if pub_ref is not None: + ref_type, ref_id = pub_ref + publication_db = (session + .query(Publication) + .filter(Publication.reference_type==ref_type) + .filter(Publication.reference_id==ref_id) + .first()) + if publication_db is None: + publication_db = Publication(reference_type=ref_type, + reference_id=ref_id) + session.add(publication_db) + session.commit() + publication_model_db = (session + .query(PublicationModel) + .filter(PublicationModel.publication_id == publication_db.id) + .filter(PublicationModel.model_id == model_db.id) + .first()) + if publication_model_db is None: + publication_model_db = PublicationModel(model_id=model_db.id, + publication_id=publication_db.id) + session.add(publication_model_db) + session.commit() + return model_db.id + + +def load_metabolites(session, model_id, model, compartment_names, + old_metabolite_ids): + """"""Load the metabolites as components and model components. + + Arguments: + --------- + + session: An SQLAlchemy session. + + model_id: The database ID for the model. + + model: The COBRApy model. + + old_metabolite_ids: A dictionary where keys are new IDs and values are old + IDs for compartmentalized metabolites. + + Returns + ------- + + comp_comp_db_ids: A dictionary where keys are the original compartmentalized + metabolite ids and the values are the database IDs for the compartmentalized + components. + + final_metabolite_ids: A new dictionary where keys are original + compartmentalized metabolite IDs from the model and values are the new + compartmentalized metabolite IDs. + + """""" + comp_comp_db_ids = {} + final_metabolite_ids = {} + + # only grab this once + data_source_id = get_or_create_data_source(session, 'old_bigg_id') + + # get metabolite id duplicates + met_dups = load_tsv(settings.metabolite_duplicates) + def _check_metabolite_duplicates(bigg_id): + """"""Return a new ID if there is a preferred ID, otherwise None."""""" + for row in met_dups: + if bigg_id in row[1:]: + return row[0] + return None + + # for each metabolite in the model + for metabolite in model.metabolites: + metabolite_id = parse.remove_duplicate_tag(metabolite.id) + + try: + component_bigg_id, compartment_bigg_id = parse.split_compartment(metabolite_id) + except Exception: + logging.error(('Could not find compartment for metabolite %s in' + 'model %s' % (metabolite_id, model.id))) + continue + + preferred = _check_metabolite_duplicates(component_bigg_id) + new_bigg_id = preferred if preferred else component_bigg_id + + # look for the formula in these places + formula_fns = [lambda m: getattr(m, 'formula', None), # support cobra v0.3 and 0.4 + lambda m: m.notes.get('FORMULA', None), + lambda m: m.notes.get('FORMULA1', None)] + # Cast to string, but not for None + strip_str_or_none = lambda v: str(v).strip() if v is not None else None + # Ignore the empty string + ignore_empty_str = lambda s: s if s != '' else None + # Use a generator for lazy evaluation + values = (ignore_empty_str(strip_str_or_none(formula_fn(metabolite))) + for formula_fn in formula_fns) + # Get the first non-null result. Otherwise _formula = None. + _formula = format_formula(next(filter(None, values), None)) + # Check for non-valid formulas + if parse.invalid_formula(_formula): + logging.warning('Invalid formula %s for metabolite %s in model %s' % (_formula, metabolite_id, model.id)) + _formula = None + + # get charge + try: + charge = int(metabolite.charge) + # check for float charge + if charge != metabolite.charge: + logging.warning('Could not load charge {} for {} in model {}' + .format(metabolite.charge, metabolite_id, model.id)) + charge = None + except Exception: + if hasattr(metabolite, 'charge') and metabolite.charge is not None: + logging.debug('Could not convert charge to integer for metabolite {} in model {}: {}' + .format(metabolite_id, model.id, metabolite.charge)) + charge = None + + # If there is no metabolite, add a new one. + metabolite_db = (session + .query(Component) + .filter(Component.bigg_id == new_bigg_id) + .first()) + + # if necessary, add the new metabolite, and keep track of the ID + new_name = scrub_name(getattr(metabolite, 'name', None)) + if metabolite_db is None: + # make the new metabolite + metabolite_db = Component(bigg_id=new_bigg_id, name=new_name) + session.add(metabolite_db) + session.commit() + else: + # If the metabolite is not new, consider improving the descriptive name + improve_name(session, metabolite_db, new_name) + + # add the deprecated id if necessary + if metabolite_db.bigg_id != component_bigg_id: + get_or_create(session, DeprecatedID, deprecated_id=component_bigg_id, + type='component', ome_id=metabolite_db.id) + + # if there is no compartment, add a new one + compartment_db = (session + .query(Compartment) + .filter(Compartment.bigg_id == compartment_bigg_id) + .first()) + if compartment_db is None: + try: + name = compartment_names[compartment_bigg_id] + except KeyError: + logging.warning('No name found for compartment %s' % compartment_bigg_id) + name = '' + compartment_db = Compartment(bigg_id=compartment_bigg_id, name=name) + session.add(compartment_db) + session.commit() + + # if there is no compartmentalized compartment, add a new one + comp_component_db = (session + .query(CompartmentalizedComponent) + .filter(CompartmentalizedComponent.component_id == metabolite_db.id) + .filter(CompartmentalizedComponent.compartment_id == compartment_db.id) + .first()) + if comp_component_db is None: + comp_component_db = CompartmentalizedComponent(component_id=metabolite_db.id, + compartment_id=compartment_db.id) + session.add(comp_component_db) + session.commit() + + # remember for adding the reaction + comp_comp_db_ids[metabolite.id] = comp_component_db.id + final_metabolite_ids[metabolite.id] = '%s_%s' % (new_bigg_id, compartment_bigg_id) + + # if there is no model compartmentalized compartment, add a new one + model_comp_comp_db = (session + .query(ModelCompartmentalizedComponent) + .filter(ModelCompartmentalizedComponent.compartmentalized_component_id == comp_component_db.id) + .filter(ModelCompartmentalizedComponent.model_id == model_id) + .first()) + if model_comp_comp_db is None: + model_comp_comp_db = ModelCompartmentalizedComponent(model_id=model_id, + compartmentalized_component_id=comp_component_db.id, + formula=_formula, + charge=charge) + session.add(model_comp_comp_db) + session.commit() + else: + if model_comp_comp_db.formula is None: + model_comp_comp_db.formula = _formula + if model_comp_comp_db.charge is None: + model_comp_comp_db.charge = charge + session.commit() + + # add synonyms + for old_bigg_id_c in old_metabolite_ids[metabolite.id]: + # Add Synonym and OldIDSynonym + synonym_db = (session + .query(Synonym) + .filter(Synonym.type == 'compartmentalized_component') + .filter(Synonym.ome_id == comp_component_db.id) + .filter(Synonym.synonym == old_bigg_id_c) + .filter(Synonym.data_source_id == data_source_id) + .first()) + if synonym_db is None: + synonym_db = Synonym(type='compartmentalized_component', + ome_id=comp_component_db.id, + synonym=old_bigg_id_c, + data_source_id=data_source_id) + session.add(synonym_db) + session.commit() + old_id_db = (session + .query(OldIDSynonym) + .filter(OldIDSynonym.type == 'model_compartmentalized_component') + .filter(OldIDSynonym.ome_id == model_comp_comp_db.id) + .filter(OldIDSynonym.synonym_id == synonym_db.id) + .first()) + if old_id_db is None: + old_id_db = OldIDSynonym(type='model_compartmentalized_component', + ome_id=model_comp_comp_db.id, + synonym_id=synonym_db.id) + session.add(old_id_db) + session.commit() + + # Also add Synonym and OldIDSynonym for the universal metabolite + try: + new_style_id = parse.id_for_new_id_style( + parse.fix_legacy_id(old_bigg_id_c, use_hyphens=False), + is_metabolite=True + ) + old_bigg_id_c_without_compartment = parse.split_compartment(new_style_id)[0] + except Exception as e: + logging.warning(e.message) + else: + synonym_db_2 = (session + .query(Synonym) + .filter(Synonym.type == 'component') + .filter(Synonym.ome_id == metabolite_db.id) + .filter(Synonym.synonym == old_bigg_id_c_without_compartment) + .filter(Synonym.data_source_id == data_source_id) + .first()) + if synonym_db_2 is None: + synonym_db_2 = Synonym(type='component', + ome_id=metabolite_db.id, + synonym=old_bigg_id_c_without_compartment, + data_source_id=data_source_id) + session.add(synonym_db_2) + session.commit() + old_id_db = (session + .query(OldIDSynonym) + .filter(OldIDSynonym.type == 'model_compartmentalized_component') + .filter(OldIDSynonym.ome_id == model_comp_comp_db.id) + .filter(OldIDSynonym.synonym_id == synonym_db_2.id) + .first()) + if old_id_db is None: + old_id_db = OldIDSynonym(type='model_compartmentalized_component', + ome_id=model_comp_comp_db.id, + synonym_id=synonym_db_2.id) + session.add(old_id_db) + session.commit() + + return comp_comp_db_ids, final_metabolite_ids + + +def _new_reaction(session, reaction, bigg_id, reaction_hash, model_db_id, model, + is_pseudoreaction, comp_comp_db_ids): + """"""Add a new universal reaction with reaction matrix rows."""""" + + # name is optional in cobra 0.4b2. This will probably change back. + name = check_none(getattr(reaction, 'name', None)) + reaction_db = Reaction(bigg_id=bigg_id, name=scrub_name(name), + reaction_hash=reaction_hash, + pseudoreaction=is_pseudoreaction) + session.add(reaction_db) + session.commit + + # for each reactant, add to the reaction matrix + for metabolite, stoich in six.iteritems(reaction.metabolites): + # get the component in the model + try: + comp_comp_db_id = comp_comp_db_ids[metabolite.id] + except KeyError: + logging.error('Could not find metabolite {!s} for model {!s} in the database' + .format(metabolite.id, model.id)) + continue + + # check if the reaction matrix row already exists + found_reaction_matrix = (session + .query(ReactionMatrix) + .filter(ReactionMatrix.reaction_id == reaction_db.id) + .filter(ReactionMatrix.compartmentalized_component_id == comp_comp_db_id) + .count() > 0) + if not found_reaction_matrix: + new_object = ReactionMatrix(reaction_id=reaction_db.id, + compartmentalized_component_id=comp_comp_db_id, + stoichiometry=stoich) + session.add(new_object) + else: + logging.debug('ReactionMatrix row already present for model {!s} metabolite {!s} reaction {!s}' + .format(model.id, metabolite.id, reaction_db.bigg_id)) + + return reaction_db + + +def _is_deprecated_reaction_id(session, reaction_id): + return (session.query(DeprecatedID) + .filter(DeprecatedID.type == 'reaction') + .filter(DeprecatedID.deprecated_id == reaction_id) + .first() is not None) + + +def load_reactions(session, model_db_id, model, old_reaction_ids, + comp_comp_db_ids, final_metabolite_ids): + """"""Load the reactions and stoichiometries into the model. + + TODO if the reaction is already loaded, we need to check the stoichometry + has. If that doesn't match, then add a new reaction with an incremented ID + (e.g. ACALD_1) + + Arguments + --------- + + session: An SQLAlchemy session. + + model_db_id: The database ID for the model. + + model: The COBRApy model. + + old_reaction_ids: A dictionary where keys are new IDs and values are old IDs + for reactions. + + comp_comp_db_ids: A dictionary where keys are the original compartmentalized + metabolite ids and the values are the database IDs for the compartmentalized + components. + + final_metabolite_ids: A new dictionary where keys are original + compartmentalized metabolite IDs from the model and values are the new + compartmentalized metabolite IDs. + + Returns + ------- + + A dictionary with keys for reaction BiGG IDs in the model and values for the + associated ModelReaction.id in the database. + + """""" + + # only grab this once + data_source_id = get_or_create_data_source(session, 'old_bigg_id') + + # get reaction hash_prefs + hash_prefs = load_tsv(settings.reaction_hash_prefs) + def _check_hash_prefs(a_hash, is_pseudoreaction): + """"""Return the preferred BiGG ID for a_hash, or None."""""" + for row in hash_prefs: + marked_pseudo = len(row) > 2 and row[2] == 'pseudoreaction' + if row[0] == a_hash and marked_pseudo == is_pseudoreaction: + return row[1] + return None + + # Generate reaction hashes, and find reactions in the same model in opposite + # directions. + reaction_hashes = {r.id: parse.hash_reaction(r, final_metabolite_ids) + for r in model.reactions} + reverse_reaction_hashes = {r.id: parse.hash_reaction(r, final_metabolite_ids, reverse=True) + for r in model.reactions} + reverse_reaction_hashes_rev = {v: k for k, v in six.iteritems(reverse_reaction_hashes)} + reactions_not_to_reverse = set() + for r_id, h in six.iteritems(reaction_hashes): + if h in reverse_reaction_hashes_rev: + reactions_not_to_reverse.add(r_id) + reactions_not_to_reverse.add(reverse_reaction_hashes_rev[h]) + + model_db_rxn_ids = {} + for reaction in model.reactions: + # Drop duplicates label + reaction_id = parse.remove_duplicate_tag(reaction.id) + + # Get the reaction + reaction_db = (session + .query(Reaction) + .filter(Reaction.bigg_id == reaction_id) + .first()) + + # check for pseudoreaction + is_pseudoreaction = check_pseudoreaction(reaction_id) + + # calculate the hash + reaction_hash = reaction_hashes[reaction.id] + hash_db = (session + .query(Reaction) + .filter(Reaction.reaction_hash == reaction_hash) + .filter(Reaction.pseudoreaction == is_pseudoreaction) + .first()) + # If there wasn't a match for the forward hash, also check the reverse + # hash. Do not check reverse hash for reactions with both directions + # defined in the same model (e.g. SUCDi and FRD7). + if not hash_db and reaction.id not in reactions_not_to_reverse: + reverse_hash_db = (session + .query(Reaction) + .filter(Reaction.reaction_hash == reverse_reaction_hashes[reaction.id]) + .filter(Reaction.pseudoreaction == is_pseudoreaction) + .first()) + else: + reverse_hash_db = None + + # bigg_id match hash match b==h pseudoreaction example function + # n n n first GAPD _new_reaction (1) + # n n y first EX_glc_e _new_reaction (1) + # y n n incorrect GAPD _new_reaction & increment (2) + # y n y incorrect EX_glc_e _new_reaction & increment (2) + # n y n GAPDH after GAPD reaction = hash_reaction (3a) + # n y y EX_glc__e after EX_glc_e reaction = hash_reaction (3a) + # y y n n ? reaction = hash_reaction (3a) + # y y n y ? reaction = hash_reaction (3a) + # y y y n second GAPD reaction = bigg_reaction (3b) + # y y y y second EX_glc_e reaction = bigg_reaction (3b) + # NOTE: only check pseudoreaction hash against other pseudoreactions + # 4a and 4b are 3a and 3b with a reversed reaction + + def _find_new_incremented_id(session, original_id): + """"""Look for a reaction bigg_id that is not already taken."""""" + new_id = increment_id(original_id) + while True: + # Check for existing and deprecated reaction ids + if (session.query(Reaction).filter(Reaction.bigg_id == new_id).first() is None and + not _is_deprecated_reaction_id(session, new_id)): + return new_id + new_id = increment_id(new_id) + + # Check for a preferred ID in the preferences, based on the forward + # hash. Don't check the reverse hash in preferences. + preferred_id = _check_hash_prefs(reaction_hash, is_pseudoreaction) + + # no reversed by default + is_reversed = False + is_new = False + + # (0) If there is a preferred ID, make that the new ID, and increment any old IDs + if preferred_id is not None: + # if the reaction already matches, just continue + if hash_db is not None and hash_db.bigg_id == preferred_id: + reaction_db = hash_db + # otherwise, make the new reaction + else: + # if existing reactions match the preferred reaction find a new, + # incremented id for the existing match + preferred_id_db = session.query(Reaction).filter(Reaction.bigg_id == preferred_id).first() + if preferred_id_db is not None: + new_id = _find_new_incremented_id(session, preferred_id) + logging.warning('Incrementing database reaction {} to {} and prefering {} (from model {}) based on hash preferences' + .format(preferred_id, new_id, preferred_id, model.id)) + preferred_id_db.bigg_id = new_id + session.commit() + + # make a new reaction for the preferred_id + reaction_db = _new_reaction(session, reaction, preferred_id, + reaction_hash, model_db_id, model, + is_pseudoreaction, comp_comp_db_ids) + is_new = True + + # (1) no bigg_id matches, no stoichiometry match or pseudoreaction, then + # make a new reaction + elif reaction_db is None and hash_db is None and reverse_hash_db is None: + # check that the id is not deprecated + if _is_deprecated_reaction_id(session, reaction.id): + logging.error(('Keeping bigg_id {} (hash {} - from model {}) ' + 'even though it is on the deprecated ID list. ' + 'You should add it to reaction-hash-prefs.txt') + .format(reaction_id, reaction_hash, model.id)) + reaction_db = _new_reaction(session, reaction, reaction_id, + reaction_hash, model_db_id, model, + is_pseudoreaction, comp_comp_db_ids) + is_new = True + + # (2) bigg_id matches, but not the hash, then increment the BIGG_ID + elif reaction_db is not None and hash_db is None and reverse_hash_db is None: + # loop until we find a non-matching find non-matching ID + new_id = _find_new_incremented_id(session, reaction.id) + logging.warning('Incrementing bigg_id {} to {} (from model {}) based on conflicting reaction hash' + .format(reaction_id, new_id, model.id)) + reaction_db = _new_reaction(session, reaction, new_id, + reaction_hash, model_db_id, model, + is_pseudoreaction, comp_comp_db_ids) + is_new = True + + # (3) but found a stoichiometry match, then use the hash reaction match. + elif hash_db is not None: + # WARNING TODO this requires that loaded metabolites always match on + # bigg_id, which should be the case. + + # (3a) + if reaction_db is None or reaction_db.id != hash_db.id: + reaction_db = hash_db + # (3b) BIGG ID matches a reaction with the same hash, then just continue + else: + pass + + # (4) but found a stoichiometry match, then use the hash reaction match. + elif reverse_hash_db is not None: + # WARNING TODO this requires that loaded metabolites always match on + # bigg_id, which should be the case. + + # Remember to switch upper and lower bounds + is_reversed = True + logging.info('Matched {} to {} based on reverse hash' + .format(reaction_id, reverse_hash_db.bigg_id)) + + # (4a) + if reaction_db is None or reaction_db.id != reverse_hash_db.id: + reaction_db = reverse_hash_db + # (4b) BIGG ID matches a reaction with the same hash, then just continue + else: + pass + + else: + raise Exception('Should not get here') + + # If the reaction is not new, consider improving the descriptive name + if not is_new: + new_name = scrub_name(check_none(getattr(reaction, 'name', None))) + improve_name(session, reaction_db, new_name) + + # Add reaction to deprecated ID list if necessary + if reaction_db.bigg_id != reaction_id: + get_or_create(session, DeprecatedID, deprecated_id=reaction_id, + type='reaction', ome_id=reaction_db.id) + + # If the reaction is reversed, then switch upper and lower bound + lower_bound = -reaction.upper_bound if is_reversed else reaction.lower_bound + upper_bound = -reaction.lower_bound if is_reversed else reaction.upper_bound + + # subsystem + subsystem = check_none(reaction.subsystem.strip()) + + # get the model reaction + model_reaction_db = (session + .query(ModelReaction) + .filter(ModelReaction.reaction_id == reaction_db.id) + .filter(ModelReaction.model_id == model_db_id) + .filter(ModelReaction.lower_bound == lower_bound) + .filter(ModelReaction.upper_bound == upper_bound) + .filter(ModelReaction.gene_reaction_rule == reaction.gene_reaction_rule) + .filter(ModelReaction.objective_coefficient == reaction.objective_coefficient) + .filter(ModelReaction.subsystem == subsystem) + .first()) + if model_reaction_db is None: + # get the number of existing copies of this reaction in the model + copy_number = (session + .query(ModelReaction) + .filter(ModelReaction.reaction_id == reaction_db.id) + .filter(ModelReaction.model_id == model_db_id) + .count()) + 1 + # make a new reaction + model_reaction_db = ModelReaction(model_id=model_db_id, + reaction_id=reaction_db.id, + gene_reaction_rule=reaction.gene_reaction_rule, + original_gene_reaction_rule=reaction.gene_reaction_rule, + upper_bound=upper_bound, + lower_bound=lower_bound, + objective_coefficient=reaction.objective_coefficient, + copy_number=copy_number, + subsystem=subsystem) + session.add(model_reaction_db) + session.commit() + + # remember the changed ids + model_db_rxn_ids[reaction.id] = model_reaction_db.id + + # add synonyms + # + # get the id from the published model + for old_bigg_id in old_reaction_ids[reaction.id]: + # add a synonym + synonym_db = (session + .query(Synonym) + .filter(Synonym.type == 'reaction') + .filter(Synonym.ome_id == reaction_db.id) + .filter(Synonym.synonym == old_bigg_id) + .filter(Synonym.data_source_id == data_source_id) + .first()) + if synonym_db is None: + synonym_db = Synonym(type='reaction', + ome_id=reaction_db.id, + synonym=old_bigg_id, + data_source_id=data_source_id) + session.add(synonym_db) + session.commit() + + # add OldIDSynonym + old_id_db = (session + .query(OldIDSynonym) + .filter(OldIDSynonym.type == 'model_reaction') + .filter(OldIDSynonym.ome_id == model_reaction_db.id) + .filter(OldIDSynonym.synonym_id == synonym_db.id) + .first()) + if old_id_db is None: + old_id_db = OldIDSynonym(type='model_reaction', + ome_id=model_reaction_db.id, + synonym_id=synonym_db.id) + session.add(old_id_db) + session.commit() + + return model_db_rxn_ids + + +# find gene functions +def _match_gene_by_fns(fn_list, session, gene_id, chromosome_ids): + """"""Go through each funciton and look for a match. + + """""" + for fn in fn_list: + match, is_alternative_transcript = fn(session, gene_id, chromosome_ids) + if len(match) > 0: + if len(match) > 1: + logging.warning('Multiple matches for gene {} with function {}. Using the first match.' + .format(gene_id, fn.__name__)) + return match[0], is_alternative_transcript + return None, False + + +def _by_bigg_id(session, gene_id, chromosome_ids): + # look for a matching model gene + gene_db = (session + .query(Gene) + .filter(func.lower(Gene.bigg_id) == func.lower(gene_id)) + .filter(Gene.chromosome_id.in_(chromosome_ids)) + .all()) + return gene_db, False + + +def _by_name(session, gene_id, chromosome_ids): + gene_db = (session + .query(Gene) + .filter(func.lower(Gene.name) == func.lower(gene_id)) + .filter(Gene.chromosome_id.in_(chromosome_ids)) + .all()) + return gene_db, False + + +def _by_synonym(session, gene_id, chromosome_ids): + gene_db = (session + .query(Gene) + .join(Synonym, Synonym.ome_id == Gene.id) + .filter(Gene.chromosome_id.in_(chromosome_ids)) + .filter(func.lower(Synonym.synonym) == func.lower(gene_id)) + .all()) + return gene_db, False + + +def _by_alternative_transcript(session, gene_id, chromosome_ids): + """"""Function to check for the alternative transcript match."""""" + check = re.match(r'(.*)_AT[0-9]{1,2}$', gene_id) + if not check: + gene_db = [] + else: + # find the old gene + gene_db = (session + .query(Gene) + .filter(Gene.chromosome_id.in_(chromosome_ids)) + .filter(func.lower(Gene.bigg_id) == func.lower(check.group(1))) + .filter(Gene.alternative_transcript_of.is_(None)) + .all()) + return gene_db, True + + +def _by_alternative_transcript_name(session, gene_id, chromosome_ids): + """"""Function to check for the alternative transcript match."""""" + check = re.match(r'(.*)_AT[0-9]{1,2}$', gene_id) + if not check: + gene_db = [] + else: + # find the old gene + gene_db = (session + .query(Gene) + .filter(Gene.chromosome_id.in_(chromosome_ids)) + .filter(func.lower(Gene.name) == func.lower(check.group(1))) + .filter(Gene.alternative_transcript_of.is_(None)) + .all()) + return gene_db, True + + +def _by_alternative_transcript_synonym(session, gene_id, chromosome_ids): + """"""Function to check for the alternative transcript match."""""" + check = re.match(r'(.*)_AT[0-9]{1,2}$', gene_id) + if not check: + gene_db = [] + else: + # find the old gene + gene_db = (session + .query(Gene) + .join(Synonym, Synonym.ome_id == Gene.id) + .filter(Gene.chromosome_id.in_(chromosome_ids)) + .filter(func.lower(Synonym.synonym) == func.lower(check.group(1))) + .filter(Gene.alternative_transcript_of.is_(None)) + .all()) + return gene_db, True + + +def _by_bigg_id_no_underscore(session, gene_id, chromosome_ids): + """"""Matches for T maritima genes"""""" + # look for a matching model gene + gene_db = (session + .query(Gene) + .filter(func.lower(Gene.bigg_id) == func.lower(gene_id.replace('_', ''))) + .filter(Gene.chromosome_id.in_(chromosome_ids)) + .all()) + return gene_db, False + + +def _replace_gene_str(rule, old_gene, new_gene): + return re.sub(r'\b'+old_gene+r'\b', new_gene, rule) + + +def load_genes(session, model_db_id, model, model_db_rxn_ids, old_gene_ids): + """"""Load the genes for this model. + + Arguments: + --------- + + session: An SQLAlchemy session. + + model_db_id: The database ID for the model. + + model: The COBRApy model. + + model_db_rxn_ids: A dictionary with keys for reactions in the model and + values for the associated ModelReaction.id in the database. + + old_gene_ids: A dictionary where keys are new IDs and values are old IDs for + genes. + + """""" + # only grab this once + data_source_id = get_or_create_data_source(session, 'old_bigg_id') + + # find the model in the db + model_db = session.query(Model).get(model_db_id) + + # find the chromosomes in the db + chromosome_ids = (session + .query(Chromosome.id) + .filter(Chromosome.genome_id == model_db.genome_id) + .all()) + if len(chromosome_ids) == 0: + logging.warning('No chromosomes for model %s' % model_db.bigg_id) + + # keep track of the gene-reaction associations + gene_bigg_id_to_model_reaction_db_ids = defaultdict(set) + for reaction in model.reactions: + # find the ModelReaction that corresponds to this particular reaction in + # the model + model_reaction_db = (session + .query(ModelReaction) + .get(model_db_rxn_ids[reaction.id])) + if model_reaction_db is None: + logging.error('Could not find ModelReaction {} for {} in model {}. Cannot load GeneReactionMatrix entries' + .format(model_db_rxn_ids[reaction.id], reaction.id, model.id)) + continue + for gene in reaction.genes: + gene_bigg_id_to_model_reaction_db_ids[gene.id].add(model_reaction_db.id) + + # load the genes + for gene in model.genes: + if len(chromosome_ids) == 0: + gene_db = None; is_alternative_transcript = False + else: + # find a matching gene + fns = [_by_bigg_id, _by_name, _by_synonym, _by_alternative_transcript, + _by_alternative_transcript_name, _by_alternative_transcript_synonym, + _by_bigg_id_no_underscore] + gene_db, is_alternative_transcript = _match_gene_by_fns(fns, session, + gene.id, + chromosome_ids) + + if not gene_db: + # add + if len(chromosome_ids) > 0: + logging.warning('Gene not in genbank file: {} from model {}' + .format(gene.id, model.id)) + gene_db = Gene(bigg_id=gene.id, + # name is optional in cobra 0.4b2. This will probably change back. + name=scrub_name(getattr(gene, 'name', None)), + mapped_to_genbank=False) + session.add(gene_db) + session.commit() + + elif is_alternative_transcript: + # duplicate gene for the alternative transcript + old_gene_db = gene_db + ome_gene = {} + ome_gene['bigg_id'] = gene.id + ome_gene['name'] = old_gene_db.name + ome_gene['leftpos'] = old_gene_db.leftpos + ome_gene['rightpos'] = old_gene_db.rightpos + ome_gene['chromosome_id'] = old_gene_db.chromosome_id + ome_gene['strand'] = old_gene_db.strand + ome_gene['mapped_to_genbank'] = True + ome_gene['alternative_transcript_of'] = old_gene_db.id + gene_db = Gene(**ome_gene) + session.add(gene_db) + session.commit() + + # duplicate all the synonyms + synonyms_db = (session + .query(Synonym) + .filter(Synonym.ome_id == old_gene_db.id) + .all()) + for syn_db in synonyms_db: + # add a new synonym + ome_synonym = {} + ome_synonym['type'] = syn_db.type + ome_synonym['ome_id'] = gene_db.id + ome_synonym['synonym'] = syn_db.synonym + ome_synonym['data_source_id'] = syn_db.data_source_id + synonym_object = Synonym(**ome_synonym) + session.add(synonym_object) + + # add model gene + model_gene_db = (session + .query(ModelGene) + .filter(ModelGene.gene_id == gene_db.id) + .filter(ModelGene.model_id == model_db_id) + .first()) + if model_gene_db is None: + model_gene_db = ModelGene(gene_id=gene_db.id, + model_id=model_db_id) + session.add(model_gene_db) + session.commit() + + # add old gene synonym + for old_bigg_id in old_gene_ids[gene.id]: + synonym_db = (session + .query(Synonym) + .filter(Synonym.type == 'gene') + .filter(Synonym.ome_id == gene_db.id) + .filter(Synonym.synonym == old_bigg_id) + .filter(Synonym.data_source_id == data_source_id) + .first()) + if synonym_db is None: + synonym_db = Synonym(type='gene', + ome_id=gene_db.id, + synonym=old_bigg_id, + data_source_id=data_source_id) + session.add(synonym_db) + session.commit() + # add OldIDSynonym + old_id_db = (session + .query(OldIDSynonym) + .filter(OldIDSynonym.type == 'model_gene') + .filter(OldIDSynonym.ome_id == model_gene_db.id) + .filter(OldIDSynonym.synonym_id == synonym_db.id) + .first()) + if old_id_db is None: + old_id_db = OldIDSynonym(type='model_gene', + ome_id=model_gene_db.id, + synonym_id=synonym_db.id) + session.add(old_id_db) + session.commit() + + # find model reaction + try: + model_reaction_db_ids = gene_bigg_id_to_model_reaction_db_ids[gene.id] + except KeyError: + # error message above + continue + + for mr_db_id in model_reaction_db_ids: + # add to the GeneReactionMatrix, if not already present + found_gene_reaction_row = (session + .query(GeneReactionMatrix) + .filter(GeneReactionMatrix.model_gene_id == model_gene_db.id) + .filter(GeneReactionMatrix.model_reaction_id == mr_db_id) + .count() > 0) + if not found_gene_reaction_row: + new_object = GeneReactionMatrix(model_gene_id=model_gene_db.id, + model_reaction_id=mr_db_id) + session.add(new_object) + + # update the gene_reaction_rule if the gene id has changed + if gene.id != gene_db.bigg_id: + mr = session.query(ModelReaction).get(mr_db_id) + new_rule = _replace_gene_str(mr.gene_reaction_rule, gene.id, + gene_db.bigg_id) + (session + .query(ModelReaction) + .filter(ModelReaction.id == mr_db_id) + .update({ModelReaction.gene_reaction_rule: new_rule})) + + +def load_model_count(session, model_db_id): + metabolite_count = (session + .query(ModelCompartmentalizedComponent.id) + .filter(ModelCompartmentalizedComponent.model_id == model_db_id) + .count()) + reaction_count = (session + .query(ModelReaction.id) + .filter(ModelReaction.model_id == model_db_id) + .count()) + gene_count = (session + .query(ModelGene.id) + .filter(ModelGene.model_id == model_db_id) + .count()) + mc = ModelCount(model_id=model_db_id, + gene_count=gene_count, + metabolite_count=metabolite_count, + reaction_count=reaction_count) + session.add(mc) +","Python" +"Metabolic","SBRG/cobradb","cobradb/util.py",".py","6371","212","# -*- coding: utf-8 -*- + +from cobradb.models import * +from cobradb import settings + +import re +import os +import logging +from time import time +from sys import stdout + + +def check_none(v): + """"""Return None if v is the empty string or the string 'None'."""""" + return None if (v == 'None' or v == '') else v + + +def get_or_create(session, query_class, **kwargs): + """"""Query the query_class, filtering by the given keyword arguments. If no result + is found, then add a new row to the database. + + Returns a tuple: (result of the query, Boolean: the result already existed) + + Arguments + --------- + + session: The SQLAlchemy session. + + query_class: The class to query. + + """""" + res = session.query(query_class).filter_by(**kwargs).first() + if res is not None: + return res, True + res = query_class(**kwargs) + session.add(res) + session.commit() + return res, False + + +def load_tsv(filename, required_column_num=None): + """"""Try to load a tsv prefs file. Ignore empty lines and lines beginning with #. + + Arguments + --------- + + filename: A tsv path to load. + + required_column_num: The number of columns to check for. + + """""" + if not os.path.exists(filename): + return [] + with open(filename, 'r') as f: + # split non-empty rows by tab + rows = [[check_none(x.strip()) for x in line.split('\t')] + for line in f.readlines() + if line.strip() != '' and line[0] != '#'] + + # check rows + if required_column_num is not None: + def check_row(row): + if len(row) != required_column_num: + logging.warning('Line in {} should have {} columns, but found {}: {}' + .format(filename, required_column_num, len(row), row)) + return None + return row + rows = [x for x in (check_row(r) for r in rows) if x is not None] + + return rows + + +def _find_data_source_url(bigg_id, url_prefs): + """"""Return (bigg_id, name, url prefix) for data source name."""""" + name = None; url_prefix = None + for row in url_prefs: + if row[0] == bigg_id: + if len(row) == 1: + logging.error('Bad row in data-source-prefs: {}'.format(row)) + if len(row) > 1: + name = check_none(row[1]) + if len(row) > 2: + url_prefix = check_none(row[2]) + break + # check synonyms + elif len(row) == 4 and bigg_id in (x.strip() for x in row[3].split(',')): + bigg_id, name, url_prefix = row[0], check_none(row[1]), check_none(row[2]) + break + return bigg_id, name, url_prefix + + +def get_or_create_data_source(session, bigg_id): + """"""Get the data source by name. If it does not exist in the database, then + add a new row by reading the preference file. + + Arguments + --------- + + session: The SQLAlchemy session. + + bigg_id: The BiGG ID of the DataSource. + + """""" + data_source_db = (session + .query(DataSource) + .filter(DataSource.bigg_id == bigg_id) + .first()) + if not data_source_db: + # get gene url_prefs + url_prefs = load_tsv(settings.data_source_preferences) + bigg_id, name, url_prefix = _find_data_source_url(bigg_id, url_prefs) + # data source may already exist if this is a synonym + data_source_db, exists = get_or_create(session, DataSource, + bigg_id=bigg_id, + name=name, + url_prefix=url_prefix) + if not exists: + if name is None: + logging.warning('No name found for data source %s' % bigg_id) + if url_prefix is None: + logging.warning('No URL found for data source %s' % bigg_id) + return data_source_db.id + + +def increment_id(id, increment_name=''): + match = re.match(r'(.*)_%s([0-9]+)$' % increment_name, id) + if match: + return '%s_%s%d' % (match.group(1), increment_name, int(match.group(2)) + 1) + else: + return '%s_%s%d' % (id, increment_name, 1) + + +def make_reaction_copy_id(bigg_id, copy_number): + return '{}_copy{}'.format(bigg_id, copy_number) + + +def check_pseudoreaction(reaction_id): + patterns = [ + r'^ATPM$', + r'^EX_.*', + r'^DM_.*', + r'^SK_.*', + r'^BIOMASS_.*' # case insensitive + ] + for pattern in patterns: + if re.match(pattern, reaction_id): + return True + return False + + +def format_formula(formula): + """"""Remove unnecessary characters from formula."""""" + if formula is None: + return formula + formula = formula.strip(""'[]"").replace('FULLR', 'R') + if formula.strip() in ['Fe1SO', 'UK', 'HP']: + return 'R' + return formula + + +def scrub_gene_id(the_id): + """"""Get a new style gene ID."""""" + the_id = re.sub(r'(.*)\.([0-9]{1,2})$', r'\1_AT\2', the_id) + the_id = re.sub(r'\W', r'_', the_id) + return the_id + + +def scrub_name(the_name): + """"""Make a nice looking name."""""" + if the_name is None: + return None + the_name = (the_name + .replace('_SPACE_SPACE_', ' ') + .replace('_SPACE_', ' ') + .replace('_COLON_', ':') + .replace('_COMMA_', ',')) + the_name = re.sub(r'^[RMG]?_', '', the_name) + the_name = re.sub(r'_', ' ', the_name) + # uppercase + the_name = re.sub('^([a-z])', lambda x: x.group(1).upper(), the_name) + if the_name.strip() == '': + return None + return the_name + + +def ref_str_to_tuple(ref): + """"""String like ' a : b ' to tuple like ('a', 'b')."""""" + return tuple(x.strip() for x in ref.split(':')) + + +def ref_tuple_to_str(key, val): + """"""Tuple like ('a', 'b') to string like 'a:b'."""""" + return '%s:%s' % (key, val) + + +def timing(function): + def wrapper(*args, **kwargs): + arg_str = str(args) + if arg_str[-2] == ',': # trailing comma + arg_str = arg_str[:-2] + ')' + try: + name = function.__name__ + except AttributeError: + name = function.func_name + logging.debug('starting %s' % name) + stdout.flush() + start = time() + res = function(*args, **kwargs) + logging.debug('%s complete (%.2f sec)'% (name, time() - start)) + return res + return wrapper +","Python" +"Metabolic","SBRG/cobradb","cobradb/model_dumping.py",".py","12891","306","# -*- coding: utf-8 -*- + +from cobradb.models import * +from cobradb.util import increment_id, make_reaction_copy_id, timing + +from sqlalchemy import and_ +import cobra.core +import logging +from itertools import repeat +from collections import defaultdict +from copy import copy +import six + +try: + from ipy_progressbar import ProgressBar +except ImportError: + pass + + +def _none_to_str(val): + return '' if val is None else val + + +def _make_annotation_lookup(db_links): + """"""Make a lookup dictionary from a list of flat external DB links"""""" + lookup = defaultdict(lambda: defaultdict(set)) + for res in db_links: + # skip old_bigg_id because it will be in notes + if res[0] not in ['old_bigg_id', 'deprecated']: + lookup[res[2]][res[0]].add(res[1]) + # return lists instead of sets + return { + bigg_id: {source: list(vals) for source, vals in links.items()} + for bigg_id, links in lookup.items() + } + + +@timing +def dump_model(bigg_id): + session = Session() + + # find the model + model_db = (session + .query(Model) + .filter(Model.bigg_id == bigg_id) + .first()) + + if model_db is None: + session.commit() + session.close() + raise Exception('Could not find model %s' % bigg_id) + + model = cobra.core.Model(bigg_id) + + # genes + logging.debug('Dumping genes') + # get genes and original bigg ids (might be multiple) + genes_db = (session + .query(Gene.bigg_id, Gene.name, Synonym.synonym) + .join(ModelGene, ModelGene.gene_id == Gene.id) + .join(OldIDSynonym, OldIDSynonym.ome_id == ModelGene.id) + .filter(OldIDSynonym.type == 'model_gene') + .join(Synonym, Synonym.id == OldIDSynonym.synonym_id) + .filter(ModelGene.model_id == model_db.id)) + gene_names = [] + old_gene_ids_dict = defaultdict(list) + for gene_id, gene_name, old_id in genes_db: + if gene_id not in old_gene_ids_dict: + gene_names.append((gene_id, gene_name)) + old_gene_ids_dict[gene_id].append(old_id) + + # get gene annotations + gene_db_links = _make_annotation_lookup( + session + .query(DataSource.bigg_id, Synonym.synonym, Gene.bigg_id) + .join(Synonym) + .join(Gene, Gene.id == Synonym.ome_id) + .filter(Synonym.type == 'gene') + ) + + for gene_id, gene_name in gene_names: + gene = cobra.core.Gene(gene_id) + gene.name = _none_to_str(gene_name) + gene.notes = {'original_bigg_ids': old_gene_ids_dict[gene_id]} + gene.annotation = gene_db_links.get(gene_id, {}) + # add SBO terms + gene.annotation['sbo'] = 'SBO:0000243' + model.genes.append(gene) + + # reactions + logging.debug('Dumping reactions') + # get original bigg ids (might be multiple) + reactions_db = (session + .query(ModelReaction, Reaction, Synonym.synonym) + .join(Reaction) + .outerjoin(OldIDSynonym, + and_(OldIDSynonym.ome_id == ModelReaction.id, + OldIDSynonym.type == 'model_reaction')) + .outerjoin(Synonym, + and_(Synonym.id == OldIDSynonym.synonym_id, + Synonym.type == 'reaction')) + .filter(ModelReaction.model_id == model_db.id)) + reactions_model_reactions = [] + found_model_reactions = set() + old_reaction_ids_dict = defaultdict(list) + for model_reaction, reaction, old_id in reactions_db: + # there may be multiple model reactions for a given bigg_id + if model_reaction.id not in found_model_reactions: + reactions_model_reactions.append((model_reaction, reaction)) + found_model_reactions.add(model_reaction.id) + if old_id is not None: + old_reaction_ids_dict[reaction.bigg_id].append(old_id) + + # get reaction annotations + reaction_db_links = _make_annotation_lookup( + session + .query(DataSource.bigg_id, Synonym.synonym, Reaction.bigg_id) + .join(Synonym) + .join(Reaction, Reaction.id == Synonym.ome_id) + .filter(Synonym.type == 'reaction') + ) + + # make dictionaries and cast results + result_dicts = [] + for mr_db, r_db in reactions_model_reactions: + d = {} + d['bigg_id'] = r_db.bigg_id + d['name'] = r_db.name + d['gene_reaction_rule'] = mr_db.gene_reaction_rule + d['lower_bound'] = mr_db.lower_bound + d['upper_bound'] = mr_db.upper_bound + d['objective_coefficient'] = mr_db.objective_coefficient + d['original_bigg_ids'] = old_reaction_ids_dict[r_db.bigg_id] + d['subsystem'] = mr_db.subsystem + d['annotation'] = reaction_db_links.get(r_db.bigg_id, {}) + # add SBO terms + if r_db.bigg_id.startswith('BIOMASS_'): + d['annotation']['sbo'] = 'SBO:0000629' + elif r_db.bigg_id.startswith('EX_'): + d['annotation']['sbo'] = 'SBO:0000627' + elif r_db.bigg_id.startswith('DM_'): + d['annotation']['sbo'] = 'SBO:0000628' + elif r_db.bigg_id.startswith('SK_'): + d['annotation']['sbo'] = 'SBO:0000632' + else: + # assume non-transport. will update for transporters later + d['annotation']['sbo'] = 'SBO:0000176' + # specify bigg id + d['annotation']['bigg.reaction'] = [r_db.bigg_id] + d['copy_number'] = mr_db.copy_number + result_dicts.append(d) + + def filter_duplicates(result_dicts): + """"""Find the reactions with multiple ModelReactions and increment names."""""" + tups_by_bigg_id = defaultdict(list) + # for each ModelReaction + for d in result_dicts: + # add to duplicates + tups_by_bigg_id[d['bigg_id']].append(d) + # duplicates have multiple ModelReactions + duplicates = {k: v for k, v in six.iteritems(tups_by_bigg_id) if len(v) > 1} + for bigg_id, dup_dicts in six.iteritems(duplicates): + # add _copy1, copy2, etc. to the bigg ids for the duplicates + for d in dup_dicts: + d['bigg_id'] = make_reaction_copy_id(bigg_id, d['copy_number']) + + return result_dicts + + # fix duplicates + result_filtered = filter_duplicates(result_dicts) + + reactions = [] + objectives = {} + for result_dict in result_filtered: + r = cobra.core.Reaction(result_dict['bigg_id']) + r.name = _none_to_str(result_dict['name']) + r.gene_reaction_rule = result_dict['gene_reaction_rule'] + r.lower_bound = result_dict['lower_bound'] + r.upper_bound = result_dict['upper_bound'] + r.notes = {'original_bigg_ids': result_dict['original_bigg_ids']} + r.subsystem = result_dict['subsystem'] + r.annotation = result_dict['annotation'] + reactions.append(r) + + objectives[r.id] = result_dict['objective_coefficient'] + model.add_reactions(reactions) + + for k, v in six.iteritems(objectives): + model.reactions.get_by_id(k).objective_coefficient = v + + # metabolites + logging.debug('Dumping metabolites') + # get original bigg ids (might be multiple) + metabolites_db = (session + .query(Component.bigg_id, + Component.name, + ModelCompartmentalizedComponent.formula, + ModelCompartmentalizedComponent.charge, + Compartment.bigg_id, + Synonym.synonym) + .join(CompartmentalizedComponent, + CompartmentalizedComponent.component_id == Component.id) # noqa + .join(Compartment, + Compartment.id == CompartmentalizedComponent.compartment_id) # noqa + .join(ModelCompartmentalizedComponent, + ModelCompartmentalizedComponent.compartmentalized_component_id == CompartmentalizedComponent.id) # noqa + .join(OldIDSynonym, OldIDSynonym.ome_id == ModelCompartmentalizedComponent.id) # noqa + .filter(OldIDSynonym.type == 'model_compartmentalized_component') # noqa + .filter(Synonym.type == 'compartmentalized_component') + .join(Synonym) + .filter(ModelCompartmentalizedComponent.model_id == model_db.id)) # noqa + metabolite_names = [] + old_metabolite_ids_dict = defaultdict(list) + for metabolite_id, metabolite_name, formula, charge, compartment_id, old_id in metabolites_db: + if metabolite_id + '_' + compartment_id not in old_metabolite_ids_dict: + metabolite_names.append((metabolite_id, metabolite_name, formula, charge, compartment_id)) + old_metabolite_ids_dict[metabolite_id + '_' + compartment_id].append(old_id) + + # get metabolite annotations + metabolite_db_links = _make_annotation_lookup( + session + .query(DataSource.bigg_id, Synonym.synonym, Component.bigg_id) + .join(Synonym) + .join(Component, Component.id == Synonym.ome_id) + .filter(Synonym.type == 'component') + ) + + metabolites = [] + compartments = set() + for component_id, component_name, formula, charge, compartment_id in metabolite_names: + if component_id is not None and compartment_id is not None: + m = cobra.core.Metabolite(id=component_id + '_' + compartment_id, + compartment=compartment_id, + formula=formula) + m.charge = charge + m.name = _none_to_str(component_name) + m.notes = {'original_bigg_ids': old_metabolite_ids_dict[component_id + '_' + compartment_id]} + m.annotation = metabolite_db_links.get(component_id, {}) + # specify bigg id + m.annotation['bigg.metabolite'] = [component_id] + m.annotation['sbo'] = 'SBO:0000247' + compartments.add(compartment_id) + metabolites.append(m) + model.add_metabolites(metabolites) + + # compartments + compartment_db = (session.query(Compartment) + .filter(Compartment.bigg_id.in_(compartments))) + model.compartments = {i.bigg_id: i.name for i in compartment_db} + + # reaction matrix + logging.debug('Dumping reaction matrix') + matrix_db = (session + .query(ReactionMatrix.stoichiometry, Reaction.bigg_id, + Component.bigg_id, Compartment.bigg_id) + # component, compartment + .join(CompartmentalizedComponent, + CompartmentalizedComponent.id == ReactionMatrix.compartmentalized_component_id) # noqa + .join(Component, + Component.id == CompartmentalizedComponent.component_id) + .join(Compartment, + Compartment.id == CompartmentalizedComponent.compartment_id) # noqa + # reaction + .join(Reaction, Reaction.id == ReactionMatrix.reaction_id) + .join(ModelReaction, ModelReaction.reaction_id == Reaction.id) + .filter(ModelReaction.model_id == model_db.id) + .distinct()) # make sure we don't duplicate + + # load metabolites + compartments_for_reaction = defaultdict(set) + for stoich, reaction_id, component_id, compartment_id in matrix_db: + try: + m = model.metabolites.get_by_id(component_id + '_' + compartment_id) + except KeyError: + logging.warning('Metabolite not found %s in compartment %s for reaction %s' % + (component_id, compartment_id, reaction_id)) + continue + # add to reactions + if reaction_id in model.reactions: + # check again that we don't duplicate + r = model.reactions.get_by_id(reaction_id) + if m not in r.metabolites: + r.add_metabolites({m: float(stoich)}) + # check for transporters and update sbo term + compartments_for_reaction[reaction_id].add(m.compartment) + if len(compartments_for_reaction[reaction_id]) > 1 and r.annotation['sbo'] == 'SBO:0000176': # noqa + r.annotation['sbo'] = 'SBO:0000185' + else: + # try incremented ids + while True: + reaction_id = increment_id(reaction_id, 'copy') + try: + # check again that we don't duplicate + r = model.reactions.get_by_id(reaction_id) + if m not in r.metabolites: + r.add_metabolites({m: float(stoich)}) + except KeyError: + break + + session.commit() + session.close() + + cobra.manipulation.annotate.add_SBO(model) + + return model +","Python" +"Metabolic","SBRG/cobradb","cobradb/map_loading.py",".py","8685","188","# -*- coding: utf-8 -*- + +from cobradb.models import * +from cobradb import parse + +from tornado.escape import url_escape +import json +import escher +import logging +import sys +import re +import six + +def load_maps_from_server(session, drop_maps=False): + if drop_maps: + logging.info('Dropping Escher maps') + connection = engine.connect() + trans = connection.begin() + try: + connection.execute('TRUNCATE escher_map, escher_map_matrix CASCADE;') + trans.commit() + except: + logging.warning('Could not drop Escher tables') + trans.rollback() + + logging.info('Getting index') + index = escher.plots.server_index() + + loaded_models = (session + .query(Model.bigg_id, Model.id) + .all()) + matching_models = [x for x in loaded_models + if x[0] in [m['model_name'] for m in index['models']] + # TODO remove: trick for matching E coli core to e_coli_core + or x[0] == 'e_coli_core' and 'E coli core' in [m['model_name'] for m in index['models']]] + + for model_bigg_id, model_id in matching_models: + maps = [(m['map_name'], m['organism']) for m in index['maps'] if + m['map_name'].split('.')[0] == model_bigg_id or + # TODO remove: trick for matching E coli core to e_coli_core + m['map_name'].split('.')[0] == 'E coli core' and model_bigg_id == 'e_coli_core'] + for map_name, org in maps: + map_json = escher.plots.map_json_for_name(map_name) + load_the_map(session, model_id, map_name, map_json) + +def load_the_map(session, model_id, map_name, map_json): + size = sys.getsizeof(map_json) + if size > 1e6: + logging.info('Skipping Escher map {} because it is too large ({:.2e} bytes)' + .format(map_name, size)) + return 1 + + warning_num = 5 + + high_priority = ['central', 'glycolysis'] + priority = (5 if any([s in map_name.lower() for s in high_priority]) else 1) + + escher_map_db = (session + .query(EscherMap) + .filter(EscherMap.map_name == map_name) + .first()) + if escher_map_db is None: + logging.info('Creating map %s' % map_name) + map_data = (bytes(map_json) if isinstance(map_json, six.binary_type) + else map_json.encode('utf8')) + escher_map_db = EscherMap(map_name=map_name, model_id=model_id, + priority=priority, map_data=map_data) + session.add(escher_map_db) + session.commit() + else: + logging.info('Map %s already in the database' % map_name) + if escher_map_db.model_id != model_id: + model_bigg_id = (session + .query(Model.bigg_id) + .filter(Model.id == model_id) + .first())[0] + logging.warning('Map %s does not match model %s' % (map_name, + model_bigg_id)) + + map_object = json.loads(map_json) + + logging.info('Adding reactions') + reaction_warnings = 0 + for element_id, reaction in six.iteritems(map_object[1]['reactions']): + # deal with reaction copies + map_reaction_bigg_id = re.sub(r'_copy[0-9]+$', '', reaction['bigg_id']) + # check for an existing mat row + mat_db = (session + .query(EscherMapMatrix) + .join(ModelReaction, ModelReaction.id == EscherMapMatrix.ome_id) + .filter(EscherMapMatrix.type == 'model_reaction') + .join(Reaction) + .filter(EscherMapMatrix.escher_map_id == escher_map_db.id) + .filter(Reaction.bigg_id == map_reaction_bigg_id) + .first()) + if mat_db is None: + # find the model reaction + model_reaction_db = (session + .query(ModelReaction.id) + .join(Reaction) + .filter(Reaction.bigg_id == map_reaction_bigg_id) + .filter(ModelReaction.model_id == model_id) + .first()) + if model_reaction_db is None: + if reaction_warnings <= warning_num: + msg = ('Could not find reaction %s in model for map %s' % (map_reaction_bigg_id, + map_name)) + if reaction_warnings == warning_num: + msg += ' (Warnings limited to %d)' % warning_num + logging.warning(msg) + reaction_warnings += 1 + continue + model_reaction_id = model_reaction_db[0] + mat_db = EscherMapMatrix(escher_map_id=escher_map_db.id, + ome_id=model_reaction_id, + escher_map_element_id=element_id, + type='model_reaction') + session.add(mat_db) + + logging.info('Adding metabolites') + comp_comp_warnings = 0 + for element_id, node in six.iteritems(map_object[1]['nodes']): + if node['node_type'] != 'metabolite': + continue + metabolite = node + + # split the bigg_id + try: + met_id, comp_id = parse.split_compartment(metabolite['bigg_id']) + except Exception: + logging.warning('Could not split compartment for metabolite %s' % metabolite['bigg_id']) + # check for an existing mat row + mat_db = (session + .query(EscherMapMatrix) + .join(ModelCompartmentalizedComponent, + ModelCompartmentalizedComponent.id == EscherMapMatrix.ome_id) + .filter(EscherMapMatrix.type == 'model_compartmentalized_component') + .join(CompartmentalizedComponent, + CompartmentalizedComponent.id == ModelCompartmentalizedComponent.compartmentalized_component_id) + .join(Component, + Component.id == CompartmentalizedComponent.component_id) + .join(Compartment, + Compartment.id == CompartmentalizedComponent.compartment_id) + .filter(EscherMapMatrix.escher_map_id == escher_map_db.id) + .filter(Component.bigg_id == met_id) + .filter(Compartment.bigg_id == comp_id) + .first()) + if mat_db is None: + # find the compartmentalized compartment + model_comp_comp_db = (session + .query(ModelCompartmentalizedComponent.id) + .join(CompartmentalizedComponent, + CompartmentalizedComponent.id == ModelCompartmentalizedComponent.compartmentalized_component_id) + .join(Component, + Component.id == CompartmentalizedComponent.component_id) + .join(Compartment, + Compartment.id == CompartmentalizedComponent.compartment_id) + .join(Model) + .filter(Compartment.bigg_id == comp_id) + .filter(Component.bigg_id == met_id) + .filter(Model.id == model_id) + .first()) + if model_comp_comp_db is None: + if comp_comp_warnings <= warning_num: + msg = ('Could not find compartmentalized component %s in model for map %s' % + ('%s_%s' % (met_id, comp_id), map_name)) + if comp_comp_warnings == warning_num: + msg += ' (Warnings limited to %d)' % warning_num + logging.warning(msg) + comp_comp_warnings += 1 + continue + model_comp_comp_id = model_comp_comp_db[0] + mat_db = EscherMapMatrix(escher_map_id=escher_map_db.id, + ome_id=model_comp_comp_id, + escher_map_element_id=element_id, + type='model_compartmentalized_component') + session.add(mat_db) + session.commit() + + return 0 + +if __name__==""__main__"": + logging.basicConfig(level=logging.DEBUG, stream=sys.stdout) + + session = Session() + load_maps_from_server(session, drop_maps=True) + session.close() +","Python" +"Metabolic","SBRG/cobradb","cobradb/version_loading.py",".py","402","18","# -*- coding: utf-8 -*- + +from cobradb.models import DatabaseVersion + +from datetime import datetime + +def load_version_date(session): + vers_db = (session + .query(DatabaseVersion) + .first()) + time = datetime.now() + if vers_db is None: + vers_db = DatabaseVersion(time) + session.add(vers_db) + else: + vers_db.date_time = time + session.commit() +","Python" +"Metabolic","SBRG/cobradb","cobradb/conftest.py",".py","4128","129","# -*- coding: utf-8 -*- + +from cobradb.models import * +from cobradb import settings +from cobradb.component_loading import load_genome +from cobradb.model_loading import load_model + +import pytest +from sqlalchemy import create_engine +import sys +import os +from os.path import join, realpath, dirname +import cobra.io +import logging + + +test_data_dir = realpath(join(dirname(__file__), 'test_data')) + + +@pytest.fixture(scope='session') +def session(request): + """"""Make a session"""""" + def teardown(): + Session.close_all() + request.addfinalizer(teardown) + + return Session() + + +@pytest.fixture(scope='session') +def setup_logger(): + logging.basicConfig(level=logging.DEBUG, stream=sys.stdout) + + +@pytest.fixture(scope='session') +def test_genbank_files(): + return [(('ncbi_accession', 'core'), join(test_data_dir, 'core.gb')), + (('ncbi_accession', 'core_2'), join(test_data_dir, 'core_2.gb'))] + + +@pytest.fixture(scope='session') +def test_model_files(): + return [{'path': join(test_data_dir, 'ecoli_core_model.xml'), + 'genome_ref': ('ncbi_accession', 'core'), + 'pmid': ('pmid', '25575024')}, + {'path': join(test_data_dir, 'ecoli_core_model_2.xml'), + 'genome_ref': ('ncbi_accession', 'core_2'), + 'pmid': ('pmid', '25575024')}, + {'path': join(test_data_dir, 'ecoli_core_model_3.xml'), + 'genome_ref': ('ncbi_accession', 'core'), + 'pmid': ('pmid', '25575024')}] + + +@pytest.fixture(scope='session') +def test_db_create(setup_logger): + user = settings.postgres_user + test_db = settings.postgres_test_database + # make sure the test database is clean + os.system('dropdb %s' % test_db) + os.system('createdb %s -U %s' % (test_db, user)) + logging.info('Dropped and created database %s' % test_db) + + +@pytest.fixture(scope='session') +def test_db(request, test_db_create): + user = settings.postgres_user + test_db = settings.postgres_test_database + engine = create_engine(""postgresql://%s:%s@%s/%s"" % (user, + settings.postgres_password, + settings.postgres_host, + test_db)) + Base.metadata.create_all(engine) + Session.configure(bind=engine) + logging.info('Loaded database schema') + + def teardown(): + # close all sessions. Comment this line out to see if cobradb functions are + # closing their sessions properly. + Session.close_all() + # clear the db for the next test + Base.metadata.drop_all(engine) + logging.info('Dropped database schema') + request.addfinalizer(teardown) + + +@pytest.fixture(scope='session') +def load_genomes(test_db, test_genbank_files, session): + settings.reaction_hash_prefs = join(test_data_dir, 'reaction-hash-prefs.txt') + settings.data_source_preferences = join(test_data_dir, 'data-source-prefs.txt') + settings.gene_reaction_rule_prefs = join(test_data_dir, 'gene-reaction-rule-prefs.txt') + settings.metabolite_duplicates = join(test_data_dir, 'metabolite-duplicates.txt') + + # load the test genomes + for genome_ref, gb in test_genbank_files: + load_genome(genome_ref, [gb], session) + + +@pytest.fixture(scope='session') +def load_models(load_genomes, test_model_files, session): + # fixture load_genomes will have loaded 2 genomes + + out = [] + for model_details in test_model_files: + # load the models + out.append(load_model(model_details['path'], + model_details['pmid'], + model_details['genome_ref'], + session)) + assert out == ['Ecoli_core_model', 'Ecoli_core_model_2', 'Ecoli_core_model_3'] + + +# Session +# - test_db_create +# -> dropbd +# -> createdb +# +# - test_db +# = create_all +# -> test_function_1 +# = drop_all +# +# - test_db +# = create_all +# -> test_function_2 +# = drop_all + +# py.test --capture=no # gives you the logs +# py.test --capture=no -k load # only runs tests with 'load' in the name +","Python" +"Metabolic","SBRG/cobradb","cobradb/tests/test_map_loading.py",".py","324","14","# -*- coding: utf-8 -*- + +from cobradb.models import Session +from cobradb.map_loading import load_the_map + +import pytest + +def test_load_the_map(test_db): + session = Session() + + assert load_the_map(None, None, None, 'x'*1000000) == 1 + with pytest.raises(Exception): + load_the_map(None, None, None, 'x'*400000) +","Python" +"Metabolic","SBRG/cobradb","cobradb/tests/test_util.py",".py","3409","93","# -*- coding: utf-8 -*- + +from cobradb.models import * +from cobradb.util import * +from cobradb.util import _find_data_source_url + +import pytest + + +def test_increment_id(): + assert increment_id('ACALD_1') == 'ACALD_2' + assert increment_id('ACALD_1a') == 'ACALD_1a_1' + assert increment_id('ACALD') == 'ACALD_1' + assert increment_id('ACALD_9') == 'ACALD_10' + assert increment_id('ACALD_10') == 'ACALD_11' + + +def test_make_reaction_copy_id(): + assert make_reaction_copy_id('ACALD', 3) == 'ACALD_copy3' + + +def test_check_pseudoreaction(): + assert check_pseudoreaction('ATPM') is True + assert check_pseudoreaction('ATPM1') is False + assert check_pseudoreaction('EX_glc_e') is True + assert check_pseudoreaction('aEX_glc_e') is False + assert check_pseudoreaction('SK_glc_e') is True + assert check_pseudoreaction('BIOMASS_objective') is True + assert check_pseudoreaction('BiomassEcoli') is False + assert check_pseudoreaction('DM_8') is True + + +def test__find_data_source_url(): + url_prefs = [['kegg.compound', 'KEGG Compound', 'http://identifiers.org/kegg.compound/']] + assert _find_data_source_url('kegg.compound', url_prefs) == ('kegg.compound', 'KEGG Compound', 'http://identifiers.org/kegg.compound/') + +def test__find_data_source_url_no_url(): + url_prefs = [['kegg.compound', 'KEGG Compound']] + assert _find_data_source_url('kegg.compound', url_prefs) == ('kegg.compound', 'KEGG Compound', None) + +def test__find_data_source_url_synonym(): + url_prefs = [['kegg.compound', 'KEGG Compound', '', 'KEGGID,KEGG_ID']] + assert _find_data_source_url('KEGGID', url_prefs) == ('kegg.compound', 'KEGG Compound', None) + assert _find_data_source_url('KEGG_ID', url_prefs) == ('kegg.compound', 'KEGG Compound', None) + + +def test_get_or_create_data_source(test_db, session, tmpdir): + prefsfile = str(tmpdir.join('data_source_preferences.txt')) + with open(prefsfile, 'w') as f: + f.write('my_data_source\tname\tmy_url_prefix') + + settings.data_source_preferences = prefsfile + + get_or_create_data_source(session, 'my_data_source') + assert (session + .query(DataSource) + .filter(DataSource.bigg_id == 'my_data_source') + .filter(DataSource.name == 'name') + .filter(DataSource.url_prefix == 'my_url_prefix') + .count()) == 1 + + +def test_format_formula(): + assert format_formula(""['abc']"") == 'abc' + + +def test_scrub_gene_id(): + assert scrub_gene_id('1234.5') == '1234_AT5' + assert scrub_gene_id('1234.56') == '1234_AT56' + assert scrub_gene_id('1234.56a') == '1234_56a' + assert scrub_gene_id('asdkf@#%*(@#$sadf') == 'asdkf________sadf' + + +def test_scrub_name(): + assert scrub_name('retpalm_SPACE_deleted_SPACE_10_09_2005_SPACE_SPACE_06_COLON_18_COLON_49_SPACE_PM') == 'Retpalm deleted 10 09 2005 06:18:49 PM' + assert scrub_name('R_ammonia_reversible_transport') == 'Ammonia reversible transport' + assert scrub_name('_ammonia_reversible_transport') == 'Ammonia reversible transport' + assert scrub_name(None) == None + assert scrub_name('_ ') == None + + +def test_load_tsv(tmpdir): + # test file + a_file = tmpdir.join('temp.txt') + a_file.write('# ignore\tignore\na\ttest \n\n') + # run the test + rows = load_tsv(str(a_file)) + assert rows == [['a', 'test']] + + # with required_column_num + rows = load_tsv(str(a_file), required_column_num=3) + assert rows == [] +","Python" +"Metabolic","SBRG/cobradb","cobradb/tests/test_parse.py",".py","13485","365","from cobradb.parse import * +from cobradb.parse import (_has_gene_reaction_rule, _normalize_pseudoreaction, + _reverse_reaction) + +from cobra.core import Reaction, Metabolite, Model +from cobra.io import read_sbml_model +import pytest +import six + + +@pytest.fixture(scope='session') +def example_model(test_model_files): + return read_sbml_model(test_model_files[0]['path']) + + +@pytest.fixture(scope='session') +def convert_ids_model(example_model): + example_model.id = 'A bad id' + example_model.add_reaction(Reaction('DADA')) + example_model.reactions.get_by_id('DADA').add_metabolites({ + Metabolite('dad_DASH_2_c'): -1 + }) + return convert_ids(example_model.copy()) + + +# -------------------------------------------------------------------- +# pseudoreactions +# -------------------------------------------------------------------- + +def test__has_gene_reaction_rule(): + reaction = Reaction('rxn') + assert _has_gene_reaction_rule(reaction) is False + reaction.gene_reaction_rule = 'b1779' + assert _has_gene_reaction_rule(reaction) is True + reaction.gene_reaction_rule = ' ' + assert _has_gene_reaction_rule(reaction) is False + + +def test__normalize_pseudoreaction_exchange(): + reaction = Reaction('EX_gone') + reaction.add_metabolites({Metabolite('glu__L_e'): -1}) + reaction.lower_bound = -1000 + reaction.upper_bound = 0 + pseudo_id = _normalize_pseudoreaction(reaction.id, reaction) + assert pseudo_id == 'EX_glu__L_e' + assert reaction.subsystem == 'Extracellular exchange' + + +def test__normalize_pseudoreaction_exchange_reversed(): + reaction = Reaction('EX_gone') + reaction.add_metabolites({Metabolite('glu__L_e'): 1}) + reaction.lower_bound = 0 + reaction.upper_bound = 1000 + pseudo_id = _normalize_pseudoreaction(reaction.id, reaction) + assert pseudo_id == 'EX_glu__L_e' + assert reaction.lower_bound == -1000 + assert reaction.upper_bound == 0 + assert list(reaction.metabolites.values()) == [-1] + + +def test__normalize_pseudoreaction_exchange_error_bad_coeff(): + reaction = Reaction('EX_gone') + reaction.add_metabolites({Metabolite('glu__L_e'): -2}) + with pytest.raises(ConflictingPseudoreaction) as excinfo: + _ = _normalize_pseudoreaction(reaction.id, reaction) + assert 'with coefficient' in str(excinfo.value) + assert reaction.id == 'EX_gone' + + +def test__normalize_pseudoreaction_exchange_error_bad_name(): + reaction = Reaction('gone') + reaction.add_metabolites({Metabolite('glu__L_e'): -1}) + assert _normalize_pseudoreaction(reaction.id, reaction) == 'EX_glu__L_e' + + +def test__normalize_pseudoreaction_exchange_error_has_gpr(): + reaction = Reaction('EX_gone') + reaction.add_metabolites({Metabolite('glu__L_e'): -1}) + reaction.gene_reaction_rule = 'b1779' + with pytest.raises(ConflictingPseudoreaction) as excinfo: + _ = _normalize_pseudoreaction(reaction.id, reaction) + assert 'has a gene_reaction_rule' in str(excinfo.value) + assert reaction.id == 'EX_gone' + + +def test__normalize_pseudoreaction_demand(): + reaction = Reaction('DM_gone') + reaction.add_metabolites({Metabolite('glu__L_c'): -1}) + reaction.lower_bound = 0 + reaction.upper_bound = 1000 + pseudo_id = _normalize_pseudoreaction(reaction.id, reaction) + assert pseudo_id == 'DM_glu__L_c' + assert reaction.subsystem == 'Intracellular demand' + + +def test__normalize_pseudoreaction_demand_reversed(): + reaction = Reaction('DM_gone') + reaction.add_metabolites({Metabolite('glu__L_c'): 1}) + reaction.lower_bound = -1000 + reaction.upper_bound = 0 + pseudo_id = _normalize_pseudoreaction(reaction.id, reaction) + assert list(reaction.metabolites.values()) == [-1] + assert reaction.lower_bound == 0 + assert reaction.upper_bound == 1000 + assert pseudo_id == 'DM_glu__L_c' + + +def test__normalize_pseudoreaction_demand_reversed_prefer_sink_name(): + reaction = Reaction('sink_gone') + reaction.add_metabolites({Metabolite('glu__L_c'): 1}) + reaction.lower_bound = -1000 + reaction.upper_bound = 0 + pseudo_id = _normalize_pseudoreaction(reaction.id, reaction) + assert list(reaction.metabolites.values()) == [-1] + assert reaction.lower_bound == 0 + assert reaction.upper_bound == 1000 + assert pseudo_id == 'SK_glu__L_c' + + +def test__normalize_pseudoreaction_demand_error_has_gpr(): + reaction = Reaction('DM_gone') + reaction.add_metabolites({Metabolite('glu__L_c'): -1}) + reaction.gene_reaction_rule = 'b1779' + with pytest.raises(ConflictingPseudoreaction) as excinfo: + _ = _normalize_pseudoreaction(reaction.id, reaction) + assert 'has a gene_reaction_rule' in str(excinfo.value) + assert reaction.id == 'DM_gone' + + +def test__normalize_pseudoreaction_sink(): + reaction = Reaction('SInk_gone') + reaction.add_metabolites({Metabolite('glu__L_c'): -1}) + reaction.lower_bound = -1000 + reaction.upper_bound = 0 + pseudo_id = _normalize_pseudoreaction(reaction.id, reaction) + assert pseudo_id == 'SK_glu__L_c' + assert reaction.subsystem == 'Intracellular source/sink' + + +def test__normalize_pseudoreaction_sink_reversed(): + reaction = Reaction('Sink_gone') + reaction.add_metabolites({Metabolite('glu__L_c'): 1}) + reaction.lower_bound = 0 + reaction.upper_bound = 50 + pseudo_id = _normalize_pseudoreaction(reaction.id, reaction) + assert list(reaction.metabolites.values()) == [-1] + assert reaction.lower_bound == -50 + assert reaction.upper_bound == 0 + assert pseudo_id == 'SK_glu__L_c' + + +def test__normalize_pseudoreaction_biomass(): + reaction = Reaction('my_biomass_2') + pseudo_id = _normalize_pseudoreaction(reaction.id, reaction) + assert pseudo_id == 'BIOMASS_my_2' + assert reaction.subsystem == 'Biomass and maintenance functions' + + +def test__normalize_pseudoreaction_biomass_has_gpr(): + reaction = Reaction('my_biomass_2') + reaction.gene_reaction_rule = 'b1779' + with pytest.raises(ConflictingPseudoreaction) as excinfo: + _ = _normalize_pseudoreaction(reaction.id, reaction) + assert 'has a gene_reaction_rule' in str(excinfo.value) + assert reaction.id == 'my_biomass_2' + + +def test__normalize_pseudoreaction_atpm(): + reaction = Reaction('notATPM') + reaction.add_metabolites({Metabolite('atp_c'): -1, + Metabolite('h2o_c'): -1, + Metabolite('pi_c'): 1, + Metabolite('h_c'): 1, + Metabolite('adp_c'): 1}) + pseudo_id = _normalize_pseudoreaction(reaction.id, reaction) + assert pseudo_id == 'ATPM' + assert reaction.subsystem == 'Biomass and maintenance functions' + + +def test__normalize_pseudoreaction_atpm_reversed(): + reaction = Reaction('notATPM') + reaction.add_metabolites({Metabolite('atp_c'): 1, + Metabolite('h2o_c'): 1, + Metabolite('pi_c'): -1, + Metabolite('h_c'): -1, + Metabolite('adp_c'): -1}) + reaction.lower_bound = -50 + reaction.upper_bound = 100 + pseudo_id = _normalize_pseudoreaction(reaction.id, reaction) + assert pseudo_id == 'ATPM' + assert reaction.lower_bound == -100 + assert reaction.upper_bound == 50 + + +def test__normalize_pseudoreaction_atpm_has_gpr(): + reaction = Reaction('NPT1') + reaction.add_metabolites({Metabolite('atp_c'): -1, + Metabolite('h2o_c'): -1, + Metabolite('pi_c'): 1, + Metabolite('h_c'): 1, + Metabolite('adp_c'): 1}) + reaction.gene_reaction_rule = 'b1779' + pseudo_id = _normalize_pseudoreaction(reaction.id, reaction) + # should not change + assert pseudo_id is None + assert reaction.id == 'NPT1' + + +#---------- +# ID fixes +#---------- + +def test_convert_ids_dad_2(convert_ids_model): + returned, old_ids = convert_ids_model + assert returned.id == 'A_bad_id' + assert 'dad_2_c' in returned.metabolites + assert 'dad_2_c' in [x.id for x in returned.reactions.get_by_id('DM_dad_2_c').metabolites] + assert ('dad_2_c', ['dad_DASH_2_c']) in old_ids['metabolites'].items() + + +def test_convert_ids_repeats_reactions(convert_ids_model): + returned, old_ids = convert_ids_model + assert 'EX_glu__L_e' in returned.reactions + assert 'EX_glu__L_e$$DROP' in returned.reactions + assert 'EX_glu__L_e$$DROP_1' in returned.reactions + assert 'EX_gln__L_e' in returned.reactions + assert 'EX_gln__L_e$$DROP' in returned.reactions + + old_ids_list = old_ids['reactions'].items() + assert ( + ('EX_gln__L_e', ['EX_gln_L_e']) in old_ids_list and + ('EX_gln__L_e$$DROP', ['EX_gln__L_e']) in old_ids_list + ) or ( + ('EX_gln__L_e', ['EX_gln__L_e']) in old_ids_list and + ('EX_gln__L_e$$DROP', ['EX_gln_L_e']) in old_ids_list + ) + + +def test_convert_ids_repeats_metabolites(convert_ids_model): + # metabolites should get merged + returned, old_ids = convert_ids_model + assert set(old_ids['metabolites']['glc__D_e']) == {'glc_D_e', 'glc_DASH_D_e'} + + +def test_convert_ids_repeats_gene(convert_ids_model): + # gene should get merged + returned, old_ids = convert_ids_model + assert '904_AT1' in [x.id for x in returned.reactions.get_by_id('FORt2').genes] + assert '904_AT1' in [x.id for x in returned.reactions.get_by_id('FORti').genes] + assert set(old_ids['genes']['904_AT1']) == {'904.1', '904_AT1'} + + +def test_convert_ids_genes(convert_ids_model, example_model): + returned, old_ids = convert_ids_model + + # lost a gene to merging + assert len(returned.genes) == len(example_model.genes) - 1 + + assert 'gene_with_period_AT22' in [x.id for x in returned.genes] + assert ( + returned.reactions.get_by_id('FRD7').gene_reaction_rule == + returned.reactions.get_by_id('FRD7').gene_reaction_rule + .replace('.22', '_AT22').replace('.12', '_AT12') + ) + assert old_ids['genes']['gene_with_period_AT22'] == ['gene_with_period.22'] + + assert ['.22' not in x.id for x in returned.genes] + assert ['.22' not in x.gene_reaction_rule for x in returned.reactions] + + +def test_id_for_new_id_style(): + """"""Test edge cases for the ID conversion."""""" + cases = [x.strip() for x in """""" + +M_sertrna_sec__c +M_lipidA_core_e_p +M_lipa_cold_e +M_lipa_cold_p +M_lipa_cold_c +M_sertrna_sec__c +M_lipidA_core_e_p +M_lipidA_core_e_p + + """""".split('\n') if x.strip() != ''] + + for case in cases: + new = id_for_new_id_style(case, is_metabolite=True) + met, compartment = split_compartment(new) + + # strip leading underscores + assert id_for_new_id_style('_13dpg_c') == '13dpg_c' + assert id_for_new_id_style('__13dpg_c') == '13dpg_c' + + # 2 character compartment + assert id_for_new_id_style('abc(c1)') == 'abc_c1' + + # remove internal __ + assert id_for_new_id_style('26dap__Z_c') == '26dap_Z_c' + assert id_for_new_id_style('26dap_Z_c') == '26dap_Z_c' + # except with [LDSRM] + assert id_for_new_id_style('26dap__M_c') == '26dap__M_c' + assert id_for_new_id_style('26dap__M_c') == '26dap__M_c' + + # other characters + assert id_for_new_id_style('ATPM(NGAM)') == 'ATPM_NGAM' + assert id_for_new_id_style('a()[]c*&^%b') == 'a_c_b' + + +def test_hash_reaction(test_model_files): + # there are no conflicts in model 2 + model, _ = load_and_normalize(test_model_files[1]['path']) + + lookup_dict = {m.id: 'g3ptest_c' if m.id == 'g3p_c' else m.id + for m in model.metabolites} + + # just the string + string = hash_reaction(model.reactions.GAPD, lookup_dict, string_only=True) + assert string == '13dpg_c1.000g3ptest_c-1.000h_c1.000nad_c-1.000nadh_c1.000pi_c-1.000' + + # no conflicts + num = 20 + hashes = {r.id: hash_reaction(r, lookup_dict) for r in model.reactions[:20]} + assert len(set(hashes.values())) == 20 + + # repeatable + k1, h1 = next(six.iteritems(hashes)) + assert h1 == hash_reaction(model.reactions.get_by_id(k1), lookup_dict) + + +def test_hash_reaction_reverse(test_model_files): + model, _ = load_and_normalize(test_model_files[1]['path']) + lookup_dict = {m.id: m.id for m in model.metabolites} + string = hash_reaction(model.reactions.GAPD, lookup_dict, reverse=True, + string_only=True) + assert string == '13dpg_c-1.000g3p_c1.000h_c-1.000nad_c1.000nadh_c-1.000pi_c1.000' + + # Not the same as forward + assert hash_reaction(model.reactions.GAPD, lookup_dict, string_only=False) != \ + hash_reaction(model.reactions.GAPD, lookup_dict, reverse=True, + string_only=False) + + +def test_custom_hashes(): + # These hashes are generated from old IDs in models (in reaction strings), + # and they match to these corrected BiGG reaction IDs + cases = [ + ('39b5f90a1919aef07473e2f835ce63af', 'EX_frmd_e', 'foam_e <=>'), + ('92f1047c72db0a36413d822863be514e', 'EX_phllqne_e', 'phyQ_e <=>'), + ] + model = Model() + for reaction_hash, bigg_id, reaction_string in cases: + reaction = Reaction(bigg_id) + model.add_reaction(reaction) + reaction.build_reaction_from_string(reaction_string) + lookup_dict = {m.id: m.id for m in model.metabolites} + assert hash_reaction(reaction, lookup_dict) == reaction_hash + +def test_reverse_reaction(): + model = Model() + reaction = Reaction('AB') + model.add_reaction(reaction) + reaction.build_reaction_from_string('a --> b') + _reverse_reaction(reaction) + assert reaction.reaction == 'b <-- a' +","Python" +"Metabolic","SBRG/cobradb","cobradb/tests/test_model_dumping.py",".py","4633","136","# -*- coding: utf-8 -*- + +from cobradb.models import * +from cobradb.model_dumping import dump_model +from cobradb.model_loading import load_model +from cobradb.component_loading import load_genome + +import pytest +import logging +import cobra.io +from os.path import join, exists +import shutil + + +# Dumping +@pytest.fixture(scope='session') +def dumped_model(load_models, session): + bigg_id = 'Ecoli_core_model' + model = dump_model(bigg_id) + return model + + +# TIP: always use the fixtures to avoid trouble +def test_cannot_dump_unknown_model(dumped_model, session): + with pytest.raises(Exception): + dump_model('C3PO', session) + + +# Model content +def test_dumped_model(dumped_model): + assert len(dumped_model.reactions) == 99 + assert len(dumped_model.metabolites) == 73 + assert len(dumped_model.genes) == 141 + assert dumped_model.genes.get_by_id('b0114').name == 'aceE' + assert dumped_model.genes.get_by_id('b3528').name == 'dctA' + + # check reaction + assert 'GAPD' in dumped_model.reactions + assert dumped_model.reactions.get_by_id('GAPD').name == 'Glyceraldehyde-3-phosphate dehydrogenase' + + # check metabolite + assert 'g3p_c' in dumped_model.metabolites + assert dumped_model.metabolites.get_by_id('g3p_c').name == 'Glyceraldehyde-3-phosphate' + + +def test_compartment_names(dumped_model): + assert dumped_model.compartments['c'] == 'cytosol' + assert dumped_model.compartments['e'] == 'extracellular space' + + +def test_formula(dumped_model): + assert str(dumped_model.metabolites.get_by_id('glc__D_e').formula) == 'C6H12O6' + + +def test_charge(dumped_model): + assert dumped_model.metabolites.get_by_id('glc__D_e').charge == 0 + + +def test_subsystem(dumped_model): + assert str(dumped_model.reactions.get_by_id('GAPD').subsystem) == 'Glycolysis/Gluconeogenesis' + + +def test_solve_model(dumped_model): + # test solve + dumped_model.reactions.get_by_id('EX_glc__D_e').lower_bound = -10 + sol = dumped_model.optimize() + assert sol.f > 0.5 and sol.f < 1.0 + + +def test_sbml_dump(dumped_model, tmpdir): + # temp sbml dump + m_file = join(str(tmpdir), 'test_model.sbml') + cobra.io.write_sbml_model(dumped_model, m_file) + loaded_model = cobra.io.read_sbml_model(m_file) + # check dumped_model id + assert loaded_model.id == dumped_model.id + + # Check for buggy metabolite. This was being saved without an ID in the SBML + # dumped_model for some reason. + assert 'formmfr_b_c' in [x.id for x in dumped_model.metabolites] + assert 'formmfr_b_c' in [x.id for x in loaded_model.metabolites] + assert '' not in [x.id for x in loaded_model.metabolites] + + # delete test directory + shutil.rmtree(str(tmpdir)) + + +def test_dumped_pseudoreactions(dumped_model): + # make sure ATPM and NTP1 are represented + r1 = dumped_model.reactions.get_by_id('NTP1') + r2 = dumped_model.reactions.get_by_id('ATPM') + assert r1.lower_bound == 3.15 + assert r2.lower_bound == 8.39 + assert r1.notes['original_bigg_ids'] == ['NTP1'] + assert r2.notes['original_bigg_ids'] == ['ATPM(NGAM)'] + + +def test_dump_multiple_reaction_copies(dumped_model): + r1 = dumped_model.reactions.get_by_id('ADK1_copy1') + assert r1.gene_reaction_rule == 'b0474' + assert r1.lower_bound == -1000 + assert r1.notes['original_bigg_ids'] == ['ADK1', 'ADK1_copy'] + + r2 = dumped_model.reactions.get_by_id('ADK1_copy2') + assert r2.gene_reaction_rule == 'b0474_test_copy' + assert r2.lower_bound == 0 + assert r2.notes['original_bigg_ids'] == ['ADK1', 'ADK1_copy'] + + +def test_dump_multiple_reaction_copies_exchange(dumped_model): + r = dumped_model.reactions.get_by_id('EX_glu__L_e') + assert set(r.notes['original_bigg_ids']) == {'EX_glu_L_e', 'EX_glu__L_e', 'EX_glu_DASH_L_e'} + + +def test_dump_multiple_metabolite_copies(dumped_model): + m = dumped_model.metabolites.get_by_id('glc__D_e') + assert set(m.notes['original_bigg_ids']) == {'glc_D_e', 'glc_DASH_D_e'} + +#--------- +# Old IDs +#--------- + +def test_reaction_notes(dumped_model): + assert dumped_model.reactions.get_by_id('ATPM').notes['original_bigg_ids'] == ['ATPM(NGAM)'] + + +def test_metabolite_notes(dumped_model): + assert dumped_model.metabolites.get_by_id('13dpg_c').notes['original_bigg_ids'] == ['_13dpg_c'] + + +def test_gene_notes(dumped_model): + assert dumped_model.genes.get_by_id('b0114').notes['original_bigg_ids'] == ['b0114'] + assert dumped_model.genes.get_by_id('b3528').notes['original_bigg_ids'] == ['b3528', 'b_3528'] + assert dumped_model.genes.get_by_id('gene_with_period_AT22').notes['original_bigg_ids'] == ['gene_with_period.22'] + assert [x.notes != {} for x in dumped_model.genes] +","Python" +"Metabolic","SBRG/cobradb","cobradb/tests/test_version_loading.py",".py","383","13","# -*- coding: utf-8 -*- + +from cobradb.models import DatabaseVersion +from cobradb.version_loading import * + +def test_load_version_date(test_db, session): + load_version_date(session) + res_db_1 = session.query(DatabaseVersion).one() + t1 = res_db_1.date_time + load_version_date(session) + res_db_2 = session.query(DatabaseVersion).one() + assert t1 != res_db_2.date_time +","Python" +"Metabolic","SBRG/cobradb","cobradb/tests/test_model_loading.py",".py","22045","463","# -*- coding: utf-8 -*- + +from cobradb.models import * +from cobradb.model_loading import load_model, GenbankNotFound +from cobradb.component_loading import load_genome + +from sqlalchemy.orm import aliased +from sqlalchemy import func +import pytest +import os +from os.path import join + + +@pytest.mark.usefixtures('load_models') +class TestsWithModels: + def test_cannot_load_same_model_twice(self, session, test_model_files): + model_details = test_model_files[0] + with pytest.raises(AlreadyLoadedError): + load_model(model_details['path'], model_details['pmid'], + model_details['genome_ref'], session) + + def test_counts(self, session): + # test the model + assert session.query(Model).count() == 3 + assert session.query(Genome).count() == 2 + assert session.query(Chromosome).count() == 2 + assert session.query(Reaction).count() == 99 + assert session.query(ModelReaction).count() == 289 + assert session.query(CompartmentalizedComponent).count() == 73 + assert session.query(ModelCompartmentalizedComponent).count() == 72 * 3 + 1 + assert session.query(Component).count() == 55 + assert session.query(Gene).count() == 286 + assert session.query(ModelGene).count() == 415 + + def test_no_charge_in_linkouts(self, session): + assert (session + .query(Synonym) + .join(DataSource) + .filter(DataSource.bigg_id == 'CHARGE') + .count()) == 0 + + def test_s0001(self, session): + assert session.query(Gene).filter(Gene.bigg_id == 's0001').count() == 3 + + def test_name_scrubbing(self, session): + assert session.query(Reaction).filter(Reaction.bigg_id == 'ACALD').first().name == 'Acetaldehyde dehydrogenase (acetylating)' + + def test_name_filtering_met(self, session): + # Filter for higher quality descriptive names + assert session.query(Component).filter(Component.name == 'E4P c').first() is None + assert session.query(Component).filter(Component.name == 'D-Erythrose-4-phosphate').first() is not None + + def test_name_filtering_rxn(self, session): + # Filter for higher quality descriptive names + assert session.query(Reaction).filter(Reaction.name == 'Atps4 z').first() is None + assert session.query(Reaction).filter(Reaction.name == 'ATP synthase (four protons for one ATP)').first() is not None + + # alternative transcripts + def test_alternative_transcripts_counts(self, session): + assert session.query(Synonym).filter(Synonym.synonym == '904').count() == 3 # 3 in first model, 0 in second model + assert session.query(Gene).filter(Gene.name == 'focA').count() == 3 # 3 in first model, 0 in second model + assert session.query(Gene).filter(Gene.bigg_id == '904_AT1').count() == 1 + assert session.query(Gene).filter(Gene.bigg_id == '904_AT12').count() == 1 + assert session.query(Gene).filter(Gene.bigg_id == 'b0904').count() == 2 + assert session.query(Gene).filter(Gene.bigg_id == 'frdB').count() == 0 + assert session.query(Gene).filter(Gene.bigg_id == 'frdB_AT1').count() == 1 + assert session.query(ModelGene).join(Gene).filter(Gene.bigg_id == '904_AT1').count() == 1 + assert session.query(ModelGene).join(Gene).filter(Gene.bigg_id == '904_AT12').count() == 1 + assert session.query(ModelGene).join(Gene).filter(Gene.bigg_id == 'gene_with_period_AT22').count() == 1 + + def test_alternative_transcripts(self, session): + # these alt. transcripts in model 1: + GeneSource = aliased(Gene) + res_db = (session + .query(Gene) + .join(GeneSource, + GeneSource.id == Gene.alternative_transcript_of) + .filter(Gene.bigg_id == '904_AT1') + .filter(GeneSource.bigg_id == 'b0904')) + assert res_db.count() == 1 + assert res_db.first().name == 'focA' + + def test_gene_reaction_rule_handling(self, session): + # make sure the locus tag b4153 is back in this gene_reaction_rule (in + # place of frdB). + # NOTE: COBRApy now reformats these without extra parens. + res_db = (session + .query(ModelReaction.gene_reaction_rule) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Reaction.bigg_id == 'FRD7') + .all()) + assert '904_AT12 and gene_with_period_AT22 and b4153 and b4154' in [x[0] for x in res_db] + + def tests_reaction_collisions(self, session): + # (2 ny-n) Model 1 has a different ACALD from models 2 and 3. The + # reaction-hash-prefs file should force the second and third models to have + # ACALD, and increment the first model. + assert (session + .query(ModelReaction) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .join(Model) + .filter(Reaction.bigg_id == 'ACALD_1') + .filter(Reaction.pseudoreaction == False) + .filter(Model.bigg_id == 'Ecoli_core_model') + .count() == 1) + assert (session + .query(ModelReaction) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .join(Model) + .filter(Reaction.bigg_id == 'ACALD') + .filter(Model.bigg_id == 'Ecoli_core_model_2') + .count() == 1) + assert (session + .query(ModelReaction) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Reaction.bigg_id == 'ACALD_2') + .count() == 0) + # (3a ny-n) Matches existing reaction. PFL was renamed in model 2. + assert (session + .query(ModelReaction) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Reaction.bigg_id == 'PFL') + .count() == 3) + # (3a yynn) bigg id and hash both return matches. PDH in model 2 matches ENO from + # model 1. + assert (session + .query(ModelReaction) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Reaction.bigg_id == 'ENO') + .count() == 3) + assert (session + .query(ModelReaction) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Reaction.bigg_id == 'PDH') + .count() == 3) + + def test_repeated_reaction_different_bounds(self, session): + # exact copies should get merged + assert (session + .query(Reaction) + .join(ModelReaction) + .join(Model) + .filter(Model.bigg_id == 'Ecoli_core_model') + .filter(Reaction.bigg_id == 'EX_glu__L_e') + .count()) == 1 + # copies with different bounds should be separated + res_db = (session + .query(Reaction, ModelReaction) + .join(ModelReaction) + .join(Model) + .filter(Model.bigg_id == 'Ecoli_core_model') + .filter(Reaction.bigg_id == 'EX_gln__L_e')) + assert res_db.count() == 2 + assert {(x.lower_bound, x.upper_bound) for x in (y[1] for y in res_db)} == {(0, 50), (0, 1000)} + + def tests_pseudoreactions(self, session): + # pseudoreactions. ATPM should be prefered to ATPM_NGAM based on + # reaction-id-prefs file. Thus, ATPM should be present 3 times, once with + # the ATPM(NGAM) synonym, and never as ATPM_1. + assert (session + .query(ModelReaction) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Reaction.bigg_id == 'ATPM') + .filter(Reaction.pseudoreaction == True) + .count() == 3) + assert (session + .query(OldIDSynonym) + .filter(OldIDSynonym.type == 'model_reaction') + .join(Synonym, OldIDSynonym.synonym_id == Synonym.id) + .filter(Synonym.synonym == 'ATPM(NGAM)') + .join(ModelReaction, ModelReaction.id == OldIDSynonym.ome_id) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Reaction.bigg_id == 'ATPM') + .count() == 1) + assert (session + .query(ModelReaction) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Reaction.bigg_id == 'ATPM_1') + .filter(Reaction.pseudoreaction == True) + .count() == 0) + # NTP1 should not be a pseudoreaction, and should not get incremented + assert (session + .query(ModelReaction) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Reaction.bigg_id == 'NTP1') + .filter(Reaction.pseudoreaction == False) + .count() == 1) + assert (session + .query(ModelReaction) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Reaction.bigg_id == 'NTP1_1') + .filter(Reaction.pseudoreaction == False) + .count() == 0) + assert (session + .query(OldIDSynonym) + .filter(OldIDSynonym.type == 'model_reaction') + .join(Synonym, OldIDSynonym.synonym_id == Synonym.id) + .filter(Synonym.synonym == 'NTP1') + .join(ModelReaction, ModelReaction.id == OldIDSynonym.ome_id) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Reaction.bigg_id == 'NTP1') + .count() == 1) + + def test_gene_reaction_matrix(self, session): + len_mr_db = (session + .query(GeneReactionMatrix, ModelReaction) + .join(ModelReaction, ModelReaction.id == GeneReactionMatrix.model_reaction_id) + .join(Model, Model.id == ModelReaction.model_id) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Model.bigg_id == 'Ecoli_core_model') + .filter(Reaction.bigg_id == 'ATPM') + .filter(ModelReaction.gene_reaction_rule == '') + .count()) + assert len_mr_db == 0 + len_mr_db = (session + .query(GeneReactionMatrix, ModelReaction) + .join(ModelReaction, ModelReaction.id == GeneReactionMatrix.model_reaction_id) + .join(Model, Model.id == ModelReaction.model_id) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Model.bigg_id == 'Ecoli_core_model') + .filter(Reaction.bigg_id == 'NTP1') + .filter(ModelReaction.gene_reaction_rule == 'b0650 or b4161') + .count()) + assert len_mr_db == 2 + + def test_gene_reaction_matrix_multiple_reaction_copies(self, session): + res_db = (session + .query(GeneReactionMatrix, Gene, ModelReaction) + .join(ModelGene) + .join(Gene) + .join(ModelReaction) + .join(Reaction) + .join(Model, Model.id == ModelReaction.model_id) + .filter(Reaction.bigg_id == 'ADK1') + .filter(Model.bigg_id == 'Ecoli_core_model') + .all()) + # two genes + assert len(res_db) == 2 + assert {x[1].bigg_id for x in res_db} == {'b0474', 'b0474_test_copy'} + # should be separate entries for each ModelReaction + assert res_db[0][2].id != res_db[1][2].id + + def test_gene_reaction_rule_prefs(self, session): + # gene_reaction_rule_prefs to fix reaction rules + mr_db = (session + .query(ModelReaction) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Model.bigg_id == 'Ecoli_core_model') + .filter(Reaction.bigg_id == 'ACKr') + .first()) + assert mr_db.gene_reaction_rule == 'b1849 or b2296 or b3115' + + def test_multiple_reaction_copies(self, session): + # make sure both copies of ADK1 are here + res = (session + .query(ModelReaction) + .join(Reaction) + .join(Model) + .filter(Reaction.bigg_id == 'ADK1') + .filter(Model.bigg_id == 'Ecoli_core_model') + .order_by(ModelReaction.copy_number) + .all()) + assert len(res) == 2 + assert res[0].copy_number == 1 + assert res[0].lower_bound == -1000 + assert res[1].copy_number == 2 + assert res[1].lower_bound == 0 + + def test_multiple_metabolite_copies(self, session): + # e.g. ID collision. One of them will get dropped; cobrapy cannot + # support multiple metabolites with same id + res = (session + .query(Synonym.synonym, Component, Compartment) + .join(OldIDSynonym) + .filter(OldIDSynonym.type == 'model_compartmentalized_component') + .filter(Synonym.type == 'compartmentalized_component') + .join(ModelCompartmentalizedComponent, ModelCompartmentalizedComponent.id == OldIDSynonym.ome_id) + .join(CompartmentalizedComponent) + .join(Component) + .join(Compartment) + .join(Model) + .filter(Component.bigg_id == 'glc__D') + .filter(Compartment.bigg_id == 'e') + .filter(Model.bigg_id == 'Ecoli_core_model')) + assert res.count() == 2 + + def test_multiple_metabolite_copies_2(self, session): + # e.g. ID collision + res = (session + .query(Synonym.synonym, Component, Compartment) + .join(OldIDSynonym) + .filter(OldIDSynonym.type == 'model_compartmentalized_component') + .filter(Synonym.type == 'component') + .join(ModelCompartmentalizedComponent, ModelCompartmentalizedComponent.id == OldIDSynonym.ome_id) + .join(CompartmentalizedComponent) + .join(Component) + .join(Compartment) + .join(Model) + .filter(Component.bigg_id == 'glc__D') + .filter(Compartment.bigg_id == 'e') + .filter(Model.bigg_id == 'Ecoli_core_model')) + assert res.count() == 1 + + def test_multiple_gene_copies(self, session): + # for T. maritima, the genes TM0846 and TM_0846 were the same, so + # multiple OldIdSynonyms + res_db = (session + .query(Synonym.synonym) + .join(OldIDSynonym) + .filter(OldIDSynonym.type == 'model_gene') + .join(ModelGene, ModelGene.id == OldIDSynonym.ome_id) + .join(Gene) + .join(Model) + .filter(Gene.bigg_id == 'b3528') + .filter(Model.bigg_id == 'Ecoli_core_model')) + assert [x[0] for x in res_db] == ['b3528', 'b_3528'] + + def test_old_reaction_id(self, session): + assert (session + .query(OldIDSynonym) + .filter(OldIDSynonym.type == 'model_reaction') + .join(Synonym, OldIDSynonym.synonym_id == Synonym.id) + .filter(Synonym.synonym == 'ACALD') + .join(ModelReaction, ModelReaction.id == OldIDSynonym.ome_id) + .join(Reaction, Reaction.id == ModelReaction.reaction_id) + .filter(Reaction.bigg_id == 'ACALD_1') + .count()) == 1 + + def test_old_metabolite_id(self, session): + assert (session + .query(OldIDSynonym) + .filter(OldIDSynonym.type == 'model_compartmentalized_component') + .join(Synonym, OldIDSynonym.synonym_id == Synonym.id) + .filter(Synonym.synonym == 'gln_L_c') + .join(ModelCompartmentalizedComponent, + ModelCompartmentalizedComponent.id == OldIDSynonym.ome_id) + .join(CompartmentalizedComponent, + CompartmentalizedComponent.id == ModelCompartmentalizedComponent.compartmentalized_component_id) + .join(Component, + Component.id == CompartmentalizedComponent.component_id) + .filter(Component.bigg_id == 'gln__L') + .count()) == 3 + + def test_old_metabolite_id_2(self, session): + res = (session + .query(Synonym.synonym, Synonym.type) + .join(OldIDSynonym, OldIDSynonym.synonym_id == Synonym.id) + .filter(OldIDSynonym.type == 'model_compartmentalized_component') + .join(ModelCompartmentalizedComponent, + ModelCompartmentalizedComponent.id == OldIDSynonym.ome_id) + .join(CompartmentalizedComponent, + CompartmentalizedComponent.id == ModelCompartmentalizedComponent.compartmentalized_component_id) + .join(Component, + Component.id == CompartmentalizedComponent.component_id) + .filter(Component.bigg_id == 'glc__D') + .join(Compartment) + .filter(Compartment.bigg_id == 'e') + .join(Model) + .filter(Model.bigg_id == 'Ecoli_core_model') + .all()) + # is this the desired behavior? + assert set(res) == {('glc_DASH_D_e', 'compartmentalized_component'), ('glc_D_e', 'compartmentalized_component'), ('glc__D', 'component')} + + def test_old_gene_id(self, session): + assert (session + .query(OldIDSynonym) + .filter(OldIDSynonym.type == 'model_gene') + .join(Synonym, OldIDSynonym.synonym_id == Synonym.id) + .filter(Synonym.synonym == 'gene_with_period.22') + .join(ModelGene, ModelGene.id == OldIDSynonym.ome_id) + .join(Gene, Gene.id == ModelGene.gene_id) + .filter(Gene.bigg_id == 'gene_with_period_AT22') + .count()) == 1 + + def test_leading_underscores(self, session): + # remove leading underscores (_13dpg in Model 1) + assert (session + .query(Component) + .filter(Component.bigg_id == '_13dpg') + .first()) is None + + def test_linkout_old_bigg_id(self, session): + res_db = (session + .query(Component, Synonym, DataSource) + .filter(Component.bigg_id == '13dpg') + .join(CompartmentalizedComponent) + .join(Synonym, Synonym.ome_id == CompartmentalizedComponent.id) + .filter(Synonym.type == 'compartmentalized_component') + .join(DataSource) + .filter(DataSource.bigg_id == 'old_bigg_id') + .all()) + assert len(res_db) == 2 + assert set(x[1].synonym for x in res_db) == {'_13dpg_c', '13dpg_c'} + + def tests_reaction_attributes(self, session): + r_db = (session.query(ModelReaction) + .join(Reaction) + .filter(Reaction.bigg_id == 'GAPD') + .first()) + assert r_db.objective_coefficient == 0 + assert r_db.upper_bound == 1000 + assert r_db.lower_bound == -1000 + assert r_db.subsystem == 'Glycolysis/Gluconeogenesis' + + def test_metabolite_attributes(self, session): + res_db = (session + .query(ModelCompartmentalizedComponent) + .join(CompartmentalizedComponent) + .join(Component) + .join(Model) + .filter(Component.bigg_id == '13dpg') + .filter(Model.bigg_id == 'Ecoli_core_model') + .first()) + assert res_db.formula == 'C3H4O10P2' + assert res_db.charge == -4 + + def test_reaction_direction_hash_1(self, session): + # Use PGI direction from the first model. PGI in the second model also + # needs to respect settings.metabolite_duplicates. + rm_db = (session + .query(ReactionMatrix) + .join(Reaction) + .join(CompartmentalizedComponent) + .join(Component) + .filter(Reaction.bigg_id == 'PGI') + .filter(Component.bigg_id == 'g6p') + .first()) + assert rm_db.stoichiometry == 1 + + def test_reaction_direction_hash_2(self, session): + # No incremented PGI, even though PGI in the two models are in different directions + assert session.query(Reaction).filter(Reaction.bigg_id == 'PGI_1').count() == 0 + + def test_reaction_direction_hash_3(self, session): + # The PGI in model 2 should have its upper and lower bounds reversed + r_db = (session + .query(ModelReaction) + .join(Model) + .join(Reaction) + .filter(Model.bigg_id == 'Ecoli_core_model_2') + .filter(Reaction.bigg_id == 'PGI') + .first()) + assert r_db.lower_bound == -1000 + assert r_db.upper_bound == 0 + + def test_reaction_direction_hash_4(self, session): + # ignore reverse hash mapping when reactions are in the same model + assert session.query(Reaction).filter(Reaction.bigg_id == 'FRD7').count() == 1 + assert session.query(Reaction).filter(Reaction.bigg_id == 'SUCDi').count() == 1 + + def test_bad_formula(self, session): + res_db = (session + .query(ModelCompartmentalizedComponent.formula) + .join(Model) + .join(CompartmentalizedComponent) + .join(Component) + .join(Compartment) + .filter(Model.bigg_id == 'Ecoli_core_model') + .filter(Component.bigg_id == 'acald') + .filter(Compartment.bigg_id == 'c') + .one()) + assert res_db[0] is None +","Python" +"Metabolic","SBRG/cobradb","cobradb/tests/test_component_loading.py",".py","6172","126","# -*- coding: utf-8 -*- + +from cobradb.models import * +from cobradb.component_loading import get_genbank_accessions + +import pytest + + +def test_get_genbank_accessions(test_genbank_files): + acc = get_genbank_accessions(test_genbank_files[0][1], fast=True) + assert acc == {'ncbi_accession': 'NC_000913.2', 'ncbi_assembly': None, 'ncbi_bioproject': None} + acc = get_genbank_accessions(test_genbank_files[0][1], fast=False) + assert acc == {'ncbi_accession': 'NC_000913.2', 'ncbi_assembly': None, 'ncbi_bioproject': None} + acc = get_genbank_accessions(test_genbank_files[1][1], fast=True) + assert acc == {'ncbi_accession': 'NC_000913.2', + 'ncbi_assembly': 'test_assembly.1', + 'ncbi_bioproject': 'PRJNA57779-core-2'} + acc = get_genbank_accessions(test_genbank_files[1][1], fast=False) + assert acc == {'ncbi_accession': 'NC_000913.2', + 'ncbi_assembly': 'test_assembly.1', + 'ncbi_bioproject': 'PRJNA57779-core-2'} + + +@pytest.mark.usefixtures('load_genomes') +class TestWithGenomes(): + def test_genome_taxon(self, session): + assert session.query(Genome).first().taxon_id == '511145' + + def test_genome_genes(self, session): + assert (session.query(Gene) + .filter(Gene.bigg_id == 'b0114') + .count()) == 2 + + def test_genome_synonyms_locus_tag(self, session): + assert (session.query(Synonym) + .join(DataSource) + .join(Gene, Gene.id == Synonym.ome_id) + .filter(Synonym.type == 'gene') + .filter(DataSource.bigg_id == 'refseq_locus_tag') + .filter(Synonym.synonym == 'b0114') + .filter(Gene.bigg_id == 'b0114') + .count()) == 2 + + def test_genome_empty_name(self, session): + gene_db = (session.query(Gene) + .filter(Gene.bigg_id == 'b0720') + .first()) + assert gene_db.name is None + + def test_gene_name_no_locus_id(self, session): + """"""Keep the gene name when there is no locus ID, so that, if alternative + transcripts are used later to match agains a synonym, the gene name is still + around. + + """""" + assert session.query(Gene).filter(Gene.bigg_id == 'appB').first().name == 'appB' + + def test_gene_name_no_locus_id_gene_id(self, session): + """"""Use the Gene ID (ncbigene) if present."""""" + assert session.query(Gene).filter(Gene.bigg_id == '945585').first().name == 'appC' + + def test_genome_synonyms_name(self, session): + assert (session.query(Synonym) + .join(DataSource) + .filter(DataSource.bigg_id == 'refseq_name') + .filter(Synonym.synonym == 'aceE') + .count()) == 2 + + def test_genome_synonyms_synonyms(self, session): + assert (session.query(Synonym) + .join(DataSource) + .filter(DataSource.bigg_id == 'refseq_synonym') + .filter(Synonym.synonym == 'ECK0113') + .count()) == 2 + + + def test_genome_synonyms_db_xref(self, session): + assert (session.query(Synonym) + .join(DataSource) + .filter(DataSource.bigg_id == 'ncbigi') + .filter(Synonym.synonym == '16128107') + .count()) == 2 + + + def test_genome_synonyms_db_xref_duplicate(self, session): + # this causes an error when we are not dealing with duplicates correctly + assert (session.query(Synonym) + .join(DataSource) + .filter(DataSource.bigg_id == 'tests_dup_syn') + .filter(Synonym.synonym == 'b0114') + .count()) == 1 + + + # only in core.gb: + def test_genome_synonyms_old_locus_tag(self, session): + assert (session.query(Synonym) + .join(DataSource) + .filter(DataSource.bigg_id == 'refseq_old_locus_tag') + .filter(Synonym.synonym == 'test_b0114') + .count()) == 1 + + + # only in core.gb: + def test_genome_synonyms_orf_id(self, session): + assert (session.query(Synonym) + .join(DataSource) + .filter(DataSource.bigg_id == 'refseq_orf_id') + .filter(Synonym.synonym == 'test_orf') + .count()) == 1 + + def test_dna_sequence(self, session): + assert (session.query(Gene.dna_sequence) + .join(Chromosome) + .join(Genome) + .filter(Gene.bigg_id == 'b0008') + .filter(Genome.accession_value == 'core') + .one())[0] == 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGCTTCTGAACTGGTTACCTGCCGTGAGTAAATTAAAATTTTATTGACTTAGGTCACTAAATACTTTAACCAATATAGGCATAGCGCACAGACAGATAAAAATTACAGAGTACACAACATCCATGAAACGCATTAGCACCACCATTACCACCACCATCACCATTACCACAGGTAACGGTGCGGGCTGACGCGTACAGGAAACACAGAAAAAAGCCCGCACCTGACAGTGCGGGCTTTTTTTTTCGACCAAAGGTAACGAGGTAACAACCATGCGAGTGTTGAAGTTCGGCGGTACATCAGTGGCAAATGCAGAACGTTTTCTGCGTGTTGCCGATATTCTGGAAAGCAATGCCAGGCAGGGGCAGGTGGCCACCGTCCTCTCTGCCCCCGCCAAAATCACCAACCACCTGGTGGCGATGATTGAAAAAACCATTAGCGGCCAGGATGCTTTACCCAATATCAGCGATGCCGAACGTATTTTTGCCGAACTTTTGACGGGACTCGCCGCCGCCCAGCCGGGGTTCCCGCTGGCGCAATTGAAAACTTTCGTCGATCAGGAATTTGCCCAAATAAAACATGTCCTGCATGGCATTAGTTTGTTGGGGCAGTGCCCGGATAGCATCAACGCTGCGCTGATTTGCCGTGGCGAGAAAATGTCGATCGCCATTATGGCCGGCGTATTAGAAGCGCGCGGTCACAACGTTACTGTTATCGATCCGGTCGAAAAACTGCTGGCAGTGGGGCATTACCTCGAATCTACCGTCGATATTGCTGAGTCCACCCGCCGTATTGCGGCAAGCCGCATTCCGGCTGATCACATGGTGCTGATGGCAGGTTTCACCGCCGGTAATGAAAAAGGCGAACTGGTGGTGCTTGGACGCAACGGT' + + def test_protein_sequence(self, session): + assert (session.query(Gene.protein_sequence) + .join(Chromosome) + .join(Genome) + .filter(Gene.bigg_id == 'b0008') + .filter(Genome.accession_value == 'core') + .one())[0] == 'MTDKLTSLRQYTTVVADTGDIAAMKLYQPQDATTNPSLILNAAQIPEYRKLIDDAVAWAKQQSNDRAQQIVDATDKLAVNIGLEILKLVPGRISTEVDARLSYDTEASIAKAKRLIKLYNDAGISNDRILIKLASTWQGIRAAEQLEKEGINCNLTLLFSFAQARACAEAGVFLISPFVGRILDWYKANTDKKEYAPAEDPGVVSVSEIYQYYKEHGYETVVMGASFRNIGEILELAGCDRLTIAPALLKELAESEGAIERKLSYTGEVKARPARITESEFLWQHNQDPMAVDKLAEGIRKFAIDQEKLEKMIGDLL' +","Python" +"Metabolic","LewisLabUCSD/CellFie","initCellFie.m",".m","457","17","% % set the cellfie directory +% CELLFIEDIR = fileparts(mfilename('fullpath')); +% +% % initialize the COBRA Toolbox +% if exist('CBTDIR', 'var') +% cd(CBTDIR); +% initCobraToolbox +% else +% error('Please initialize the COBRA Toolbox or set the main directory of the COBRA Toolbox CBTDIR'); +% end +% +% % change to the cellfie main directory +% cd(CELLFIEDIR); +% +% % add the entire cellfie repository to the MATLAB path +% addpath(genpath(CELLFIEDIR)); +","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","matlab_compiled/execCellfie/for_redistribution_files_only/run_execCellfie.sh",".sh","851","33","#!/bin/sh +# script for execution of deployed applications +# +# Sets up the MATLAB Runtime environment for the current $ARCH and executes +# the specified command. +# +exe_name=$0 +exe_dir=`dirname ""$0""` +echo ""------------------------------------------"" +if [ ""x$1"" = ""x"" ]; then + echo Usage: + echo $0 \ args +else + echo Setting up environment variables + MCRROOT=""$1"" + echo --- + DYLD_LIBRARY_PATH=.:${MCRROOT}/runtime/maci64 ; + DYLD_LIBRARY_PATH=${DYLD_LIBRARY_PATH}:${MCRROOT}/bin/maci64 ; + DYLD_LIBRARY_PATH=${DYLD_LIBRARY_PATH}:${MCRROOT}/sys/os/maci64; + export DYLD_LIBRARY_PATH; + echo DYLD_LIBRARY_PATH is ${DYLD_LIBRARY_PATH}; + shift 1 + args= + while [ $# -gt 0 ]; do + token=$1 + args=""${args} \""${token}\"""" + shift + done + eval ""\""${exe_dir}/execCellfie.app/Contents/MacOS/execCellfie\"""" $args +fi +exit + +","Shell" +"Metabolic","LewisLabUCSD/CellFie","matlab_compiled/execCellfie/for_testing/run_execCellfie.sh",".sh","851","33","#!/bin/sh +# script for execution of deployed applications +# +# Sets up the MATLAB Runtime environment for the current $ARCH and executes +# the specified command. +# +exe_name=$0 +exe_dir=`dirname ""$0""` +echo ""------------------------------------------"" +if [ ""x$1"" = ""x"" ]; then + echo Usage: + echo $0 \ args +else + echo Setting up environment variables + MCRROOT=""$1"" + echo --- + DYLD_LIBRARY_PATH=.:${MCRROOT}/runtime/maci64 ; + DYLD_LIBRARY_PATH=${DYLD_LIBRARY_PATH}:${MCRROOT}/bin/maci64 ; + DYLD_LIBRARY_PATH=${DYLD_LIBRARY_PATH}:${MCRROOT}/sys/os/maci64; + export DYLD_LIBRARY_PATH; + echo DYLD_LIBRARY_PATH is ${DYLD_LIBRARY_PATH}; + shift 1 + args= + while [ $# -gt 0 ]; do + token=$1 + args=""${args} \""${token}\"""" + shift + done + eval ""\""${exe_dir}/execCellfie.app/Contents/MacOS/execCellfie\"""" $args +fi +exit + +","Shell" +"Metabolic","LewisLabUCSD/CellFie","src/CellFie_slow.m",".m","14627","335","function[score, score_binary ,taskInfos, detailScoring]=CellFie(data,SampleNumber,ref,param) +% Compute the score associated to each metabolic task listed in taskstructure based on transcriptomic data +% +% USAGE: +% [score, score_binary ,taskInfos, detailScoring]=CellFie(data,SampleNumber,ref,param) +% +% INPUTS: +% data +% .gene cell array containing GeneIDs in the same +% format as model.genes +% .value mRNA expression data structure (genes x samples)associated to each gene metioned in data.gene +% SampleNumber Number of samples +% ref Reference model used to compute the +% metabolic task scores (e.g.,'MT_recon_2_2_entrez.mat') +% OPTIONAL INPUTS: +% param.ThreshType Type of thresholding approach used +% (i.e.,'global' or 'local') (default - local) +% related to the use of a GLOBAL thresholding approach - the threshold value is the same for all the genes +% param.percentile_or_value the threshold can be defined using a value introduced by the user ('value') +% or based on a percentile of the distribution of expression value for all the +% genes and across all samples of your +% dataset ('percentile') +% param.percentile percentile from the distribution of +% expression values for all the genes and across all samples that will be +% used to define the threshold value +% param.value expression value for which a gene is +% considered as active or not (e.g., 5) +% +% related to the use of a LOCAL thresholding approach - the threshold value is different for all the genes +% param.percentile_or_value the threshold can be defined using a value introduced by the user ('value') +% or based on a percentile of the distribution of expression value of a +% specific gene across all samples of your +% dataset ('percentile'-default) +% param.LocalThresholdType option to define the type of local thresholding approach to use +% - 'minmaxmean' (default options )- the threshold for a gene is determined by the mean of expression +% values observed for that gene among all the samples, tissues, or conditions BUT +% the threshold :(i) must be higher or equal to a lower bound and (ii) must be lower +% or equal to an upper bound. +% - 'mean' -the threshold for a gene is defined as the mean expression value +% of this gene across all the samples, tissues, or conditions +% param.percentile_low lower percentile used to define which gene +% are always inactive in the case of use 'MinMaxMean' local thresholding +% approach (default = 25) +% param.percentile_high upper percentile used to define which gene +% are always active in the case of use 'MinMaxMean' local thresholding +% approach (default= 75) +% param.value_low lower expression value used to define which gene +% are always inactive in the case of use 'MinMaxMean' local thresholding +% approach (e.g., 5) +% param.value_high upper expression value used to define which gene +% are always active in the case of use 'MinMaxMean' local thresholding +% approach (e.g., 5) +% +% related to the gene mapping approach used +% param.minSum: instead of using min and max, use min for AND and Sum +% for OR (default: false, i.e. use min) +% OUTPUTS: +% score relative quantification of the activity of a metabolic task in a specific condition +% based on the availability of data for multiple conditions +% score_binary binary version of the metabolic task score +% to determine whether a task is active or inactive in specific +% conditions +% taskInfos Description of the metabolic task assessed +% detailScoring Matrix detailing the scoring +% 1st column = sample ID +% 2nd column = task ID +% 3th column = task score for this sample +% 4th column = task score in binary version for this sample +% 5th column = essential reaction associated to this task +% 6th column = expression score associated to the reaction listed in the 5th column +% 7th column = gene used to determine the expression of the reaction listed in the 5th column +% 8th column = original expression value of the gene listed in the 7th column +% +% .. Authors: +% - Anne Richelle, January 2019 +if size(data.value,2) ~= SampleNumber + error('The number of samples defined is not the same as the size of the dataset') +end +if size(data.value,1) ~= length(data.gene) + error('data.value does not have the same number of rows as data.gene') +end +if ~exist('ref','var') + error('The reference model has not been defined - please choose a reference model') +end +if ~exist('param','var') + param.ThreshType='local'; + param.percentile_or_value='percentile'; + param.LocalThresholdType='minmaxmean'; + param.percentile_low=25; + param.percentile_high=75; +end + +f = waitbar(0,'Please wait...'); +waitbar(.15,f,'Loading your data'); + +%load the info about the task structure +load('taskStructure') +taskInfos=struct2cell(taskStructure); +taskInfos=taskInfos'; +taskInfos(:,5:end)=[]; + + +%load the reference model in matlab +load(ref); + +%% Depending on the model, load the list of reactions associated with the task +% All these files have the following format +% essentialRxnsbyTask_name_of_model and are located in essentialRxns folder +load(strcat('essentialRxns/essentialRxnsbyTask_',ref)); + +% check that at least part of list of gene provided are in the model loaded +ID_model=[]; +gene_notInModel=[]; +for i=1:length(data.gene) + if isempty(find(strcmp(data.gene{i},model.genes))) + gene_notInModel(end+1)=i; + else + tmpid=find(strcmp(data.gene{i},model.genes)==1); + ID_model(end+1)=tmpid(1); + end +end + +% introduce a warning in the webtool about how many of the genes provided are +% actually mapped to the model +if isempty(gene_notInModel) + display('All genes provided in data are included in the reference model') +else + display([num2str(length(gene_notInModel)),' genes provided are not included in the reference model:']) + data.gene(gene_notInModel) +end + +% remove the gene and associated value provided by the user in data that are not in the model +data.gene(gene_notInModel)=[]; +if SampleNumber==1 + data.value(gene_notInModel)=[]; +else + data.value(gene_notInModel,:)=[]; +end + +% get the threshold value and the histogram for the complete dataset and +% print a figure +if SampleNumber>1 + linData = reshape(data.value,numel(data.value),1); +else + linData=data.value; +end +linData(linData==0)=[]; + +% definition of the thresholds +if strcmp(param.ThreshType,'global') && strcmp(param.percentile_or_value,'percentile') + display('RUN - global: percentile') + l_global = (prctile(log10(linData),param.percentile)); + data.ths=10^l_global; +elseif strcmp(param.ThreshType,'global') && strcmp(param.percentile_or_value,'value') + display('RUN - global: value') + data.ths=param.value; +elseif strcmp(param.ThreshType,'local') && strcmp(param.LocalThresholdType,'mean') + display('RUN - local: mean') +elseif strcmp(param.ThreshType,'local') && strcmp(param.LocalThresholdType,'minmaxmean')&& strcmp(param.percentile_or_value,'percentile') + display('RUN - local: minmaxmean: percentile') + l_high = (prctile(log10(linData),param.percentile_high)); + data.ths_high=10^l_high; + l_low = (prctile(log10(linData),param.percentile_low)); + data.ths_low=10^l_low; +elseif strcmp(param.ThreshType,'local') && strcmp(param.LocalThresholdType,'minmaxmean')&& strcmp(param.percentile_or_value,'value') + display('RUN - local: minmaxmean: value') + data.ths_high=param.value_high; + data.ths_low=param.value_low; +else + error('No analysis triggered') +end + +%% Compute the threshold(s) depending on the approach used +Gene_score=[]; +switch param.ThreshType + case 'local' + if strcmp(param.LocalThresholdType,'mean') + %the threshold for each gene is equal to its mean value over + %all the samples + threshold=mean(data.value,2)'; + else + threshold=[]; + for i=1:length(data.gene) + expressionValue=data.value(i,:); + if mean(expressionValue)>=data.ths_high + threshold(i)=data.ths_high; + else + threshold(i)=max(mean(expressionValue),data.ths_low); + end + end + end + % every single gene is associated to an expression score + for i=1:SampleNumber + Gene_score(:,i)=5.*log(1+(data.value(:,i)./threshold')); + end + case 'global' + Gene_score=5.*log(1+(data.value./data.ths)); +end + +% Mapping of the expression data to the model +expression.gene=data.gene; +expression.Rxns=[]; +expression.gene_used=[]; +expression.count=[]; +minSum = false; + +waitbar(.25,f,'Load GPR parse'); +%% load parsedGPR for each model +load(strcat('parsedGPR/parsedGPR_',ref)); +%%parsedGPR = GPRparser(model,minSum);%code to compute the parsed GPR using +%%cobratoolbox + +waitbar(.45,f,'Mapping of the expression data to the model'); +for i=1:SampleNumber + if SampleNumber==1 + expression.value=Gene_score; + else + expression.value=Gene_score(:,i); + end + % Find wich genes in expression data are used in the model + [gene_id, gene_expr] = findUsedGenesLevels(model,expression); + % Link the gene to the model reactions + [expressionRxns, gene_used] = selectGeneFromGPR(model, gene_id, gene_expr, parsedGPR, minSum); + + gene_all=[]; + for j=1:length(gene_used) + if ~isempty(gene_used{j}) + gene_all(end+1)=str2num(gene_used{j}{1}); + end + end + countGene = tabulate(gene_all); + count=[]; + for k=1:length(gene_used) + if ~isempty(gene_used{k}) + tmp=countGene(str2num(gene_used{k}{1}),2); + count(k)=tmp; + else + count(k)=0; + end + end + expression.Rxns=[expression.Rxns expressionRxns]; + expression.gene_used=[expression.gene_used gene_used']; + expression.count=[expression.count count']; +end + +%% Compute the score +expressionRxns=expression.Rxns; +significance=1./expression.count; +significance(isinf(significance))=0; +ScorebyTask=[]; +ScorebyTask_binary=[]; +waitbar(.75,f,'Compute the task activity score'); +for i=1:size(taskInfos,1) + if ~isempty(essentialRxns{i}) + rxns=essentialRxns{i}; + rxnID=findRxnIDs(model,rxns); + rxnID(rxnID==0)=[]; + if ~isempty(rxnID) + expValue=expressionRxns(rxnID,:); + signValue=significance(rxnID,:); + % if no gene is associated with one of the reaction - + % remove the reactions from the count + if ~isempty(find(sum(expValue,2)==-SampleNumber)) + signValue(find(sum(expValue,2)==-SampleNumber),:)=[]; + expValue(find(sum(expValue,2)==-SampleNumber),:)=[]; + end + if ~isempty(expValue) + if size(expValue,1)>1 + ScorebyTask(i,:)=sum(expValue.*signValue)./size(expValue,1); + Val=sum(expValue)./size(expValue,1); + ID_up=find(Val>=5*log(2)); + ScorebyTask_binary(i,:)=zeros(1,SampleNumber); + ScorebyTask_binary(i,ID_up)=1; + else + ScorebyTask(i,:)=expValue.*signValue; + ID_up=find(expValue>=5*log(2)); + ScorebyTask_binary(i,:)=zeros(1,SampleNumber); + ScorebyTask_binary(i,ID_up)=1; + end + else + ScorebyTask(i,:)=-1.*ones(1,SampleNumber); + ScorebyTask_binary(i,:)=-1.*ones(1,SampleNumber); + end + else + ScorebyTask(i,:)=-1.*ones(1,SampleNumber); + ScorebyTask_binary(i,:)=-1.*ones(1,SampleNumber); + end + else + ScorebyTask(i,:)=-1.*ones(1,SampleNumber); + ScorebyTask_binary(i,:)=-1.*ones(1,SampleNumber); + end +end + +detailScoring={}; +waitbar(1,f,'Format the score'); +for j=1:SampleNumber + incR=1; + for i=1:size(taskInfos,1) + if ~isempty(essentialRxns{i}) + rxns=essentialRxns{i}; + rxnID=findRxnIDs(model,rxns); + rxnID(rxnID==0)=[]; + if ~isempty(rxnID) + for k=1:length(rxnID) + %1st column = sample ID + detailScoring{incR,((j-1)*8)+1}=j; + %2nd column = task ID + detailScoring{incR,((j-1)*8)+2}=i; + %3th column = task score for this sample + detailScoring{incR,((j-1)*8)+3}=ScorebyTask(i,j); + %4th column = task score in binary version for this sample + detailScoring{incR,((j-1)*8)+4}=ScorebyTask_binary(i,j); + %5th column = essential reaction associated to this + %task + detailScoring{incR,((j-1)*8)+5}=rxns(k); + %6th column = expression score associated to the + %reaction listed in the 5th column + detailScoring{incR,((j-1)*8)+6}=expression.Rxns(rxnID(k),j); + %7th column = gene used to determine the expression of the + %reaction listed in the 5th column + geneName=expression.gene_used(rxnID(k),j); + detailScoring{incR,((j-1)*8)+7}=geneName; + %8th column = original expression value of the gene + %listed in the 7th column + detailScoring{incR,((j-1)*8)+8}=data.value(find(strcmp(data.gene,geneName{1})),j); + incR=incR+1; + end + end + end + end + score=ScorebyTask; + score_binary=ScorebyTask_binary; +end +close(f) +","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","src/findUsedGenesLevels_all.m",".m","1596","55","function [gene_id, gene_expr] = findUsedGenesLevels_all(model, exprData, printLevel) +% Returns vectors of gene identifiers and corresponding gene expression +% levels for each gene present in the model ('model.genes'). +% +% USAGE: +% [gene_id, gene_expr] = findUsedGenesLevels(model, exprData) +% +% INPUTS: +% +% model: input model (COBRA model structure) +% +% exprData: mRNA expression data structure +% .gene cell array containing GeneIDs in the same +% format as model.genes +% .value Vector containing corresponding expression value (FPKM) +% +% OPTIONAL INPUTS: +% printLevel: Printlevel for output (default 0); +% +% OUTPUTS: +% +% gene_id: vector of gene identifiers present in the model +% that are associated with expression data +% +% gene_expr: vector of expression values associated to each +% 'gened_id' +% +% +% Authors: - S. Opdam & A. Richelle May 2017 + +if ~exist('printLevel','var') + printLevel = 0; +end + +gene_expr=[]; +gene_id = model.genes; +tmpb = length(exprData.value(1,:)); +for i = 1:numel(gene_id) + + cur_ID = gene_id{i}; + dataID=find(ismember(exprData.gene,cur_ID)==1); + if isempty (dataID) + gene_expr(i,:)=-ones(1,tmpb); + elseif length(dataID)==1 + gene_expr(i,:)=exprData.value(dataID,:); + elseif length(dataID)>1 + if printLevel > 0 + disp(['Double for ',num2str(cur_ID)]) + end + gene_expr(i)=mean(exprData.value(dataID)); + end +end + +end +","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","src/wide2long.m",".m","515","21","function longm = wide2long(ds,rownames,colnames) + % dstmp=mat2dataset(ds) + % dstmp.row = rownames(:,2) + % dsNew = stack(dstmp,dstmp.Properties.VarNames(1:end-1),... + % 'newDataVarName','Scores') + %ds.Properties.VarNames = colnames + longm = {}; + longm.sample = []; + longm.task = {}; + longm.value = []; + count=1; + for i=1:size(ds,2) + for j=1:size(ds,1) + longm.sample(count) = colnames(i); + longm.task{count} = rownames{j}; + longm.value(count)= ds(j,i); + count=count+1; + end + end +end + ","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","src/prctile.m",".m","5612","179","function y = prctile(x,p,dim) +%PRCTILE Percentiles of a sample. +% Y = PRCTILE(X,P) returns percentiles of the values in X. P is a scalar +% or a vector of percent values. When X is a vector, Y is the same size +% as P, and Y(i) contains the P(i)-th percentile. When X is a matrix, +% the i-th row of Y contains the P(i)-th percentiles of each column of X. +% For N-D arrays, PRCTILE operates along the first non-singleton +% dimension. +% +% Y = PRCTILE(X,P,DIM) calculates percentiles along dimension DIM. The +% DIM'th dimension of Y has length LENGTH(P). +% +% Percentiles are specified using percentages, from 0 to 100. For an N +% element vector X, PRCTILE computes percentiles as follows: +% 1) The sorted values in X are taken as the 100*(0.5/N), 100*(1.5/N), +% ..., 100*((N-0.5)/N) percentiles. +% 2) Linear interpolation is used to compute percentiles for percent +% values between 100*(0.5/N) and 100*((N-0.5)/N) +% 3) The minimum or maximum values in X are assigned to percentiles +% for percent values outside that range. +% +% PRCTILE treats NaNs as missing values, and removes them. +% +% Examples: +% y = prctile(x,50); % the median of x +% y = prctile(x,[2.5 25 50 75 97.5]); % a useful summary of x +% +% See also IQR, MEDIAN, NANMEDIAN, QUANTILE. + +% Copyright 1993-2015 The MathWorks, Inc. + + +if ~isvector(p) || numel(p) == 0 || any(p < 0 | p > 100) || ~isreal(p) + error(message('stats:prctile:BadPercents')); +end + +% Figure out which dimension prctile will work along. +sz = size(x); +if nargin < 3 + dim = find(sz ~= 1,1); + if isempty(dim) + dim = 1; + end + dimArgGiven = false; +else + % Permute the array so that the requested dimension is the first dim. + nDimsX = ndims(x); + perm = [dim:max(nDimsX,dim) 1:dim-1]; + x = permute(x,perm); + % Pad with ones if dim > ndims. + if dim > nDimsX + sz = [sz ones(1,dim-nDimsX)]; + end + sz = sz(perm); + dim = 1; + dimArgGiven = true; +end + +% If X is empty, return all NaNs. +if isempty(x) + if isequal(x,[]) && ~dimArgGiven + y = nan(size(p),'like',x); + else + szout = sz; szout(dim) = numel(p); + y = nan(szout,'like',x); + end + +else + % Drop X's leading singleton dims, and combine its trailing dims. This + % leaves a matrix, and we can work along columns. + nrows = sz(dim); + ncols = numel(x) ./ nrows; + x = reshape(x, nrows, ncols); + + x = sort(x,1); + n = sum(~isnan(x), 1); % Number of non-NaN values in each column + + % For columns with no valid data, set n=1 to get nan in the result + n(n==0) = 1; + + % If the number of non-nans in each column is the same, do all cols at once. + if all(n == n(1)) + n = n(1); + if isequal(p,50) % make the median fast + if rem(n,2) % n is odd + y = x((n+1)/2,:); + else % n is even + y = (x(n/2,:) + x(n/2+1,:))/2; + end + else + y = interpColsSame(x,p,n); + end + + else + % Get percentiles of the non-NaN values in each column. + y = interpColsDiffer(x,p,n); + end + + % Reshape Y to conform to X's original shape and size. + szout = sz; szout(dim) = numel(p); + y = reshape(y,szout); +end +% undo the DIM permutation +if dimArgGiven + y = ipermute(y,perm); +end + +% If X is a vector, the shape of Y should follow that of P, unless an +% explicit DIM arg was given. +if ~dimArgGiven && isvector(x) + y = reshape(y,size(p)); +end + + +function y = interpColsSame(x, p, n) +%INTERPCOLSSAME An aternative approach of 1-D linear interpolation which is +% faster than using INTERP1Q and can deal with invalid data so long as +% all columns have the same number of valid entries (scalar n). + +% Make p a column vector. Note that n is assumed to be scalar. +if isrow(p) + p = p'; +end + +% Form the vector of index values (numel(p) x 1) +r = (p/100)*n; +k = floor(r+0.5); % K gives the index for the row just before r +kp1 = k + 1; % K+1 gives the index for the row just after r +r = r - k; % R is the ratio between the K and K+1 rows + +% Find indices that are out of the range 1 to n and cap them +k(k<1 | isnan(k)) = 1; +kp1 = bsxfun( @min, kp1, n ); + +% Use simple linear interpolation for the valid precentages +y = bsxfun(@times, 0.5-r, x(k,:)) + bsxfun(@times, 0.5+r, x(kp1,:)); + +% Make sure that values we hit exactly are copied rather than interpolated +exact = (r==-0.5); +if any(exact) + y(exact,:) = x(k(exact),:); +end + +function y = interpColsDiffer(x, p, n) +%INTERPCOLSDIFFER A simple 1-D linear interpolation of columns that can +%deal with columns with differing numbers of valid entries (vector n). + +[nrows, ncols] = size(x); + +% Make p a column vector. n is already a row vector with ncols columns. +if isrow(p) + p = p'; +end + +% Form the grid of index values (numel(p) x numel(n)) +r = (p/100)*n; +k = floor(r+0.5); % K gives the index for the row just before r +kp1 = k + 1; % K+1 gives the index for the row just after r +r = r - k; % R is the ratio between the K and K+1 rows + +% Find indices that are out of the range 1 to n and cap them +k(k<1 | isnan(k)) = 1; +kp1 = bsxfun( @min, kp1, n ); + +% Convert K and Kp1 into linear indices +offset = nrows*(0:ncols-1); +k = bsxfun( @plus, k, offset ); +kp1 = bsxfun( @plus, kp1, offset ); + +% Use simple linear interpolation for the valid precentages. +% Note that NaNs in r produce NaN rows. +y = (0.5-r).*x(k) + (0.5+r).*x(kp1); + +% Make sure that values we hit exactly are copied rather than interpolated +exact = (r==-0.5); +if any(exact(:)) + y(exact) = x(k(exact)); +end +","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","src/findUsedGenesLevels.m",".m","1540","55","function [gene_id, gene_expr] = findUsedGenesLevels(model, exprData, printLevel) +% Returns vectors of gene identifiers and corresponding gene expression +% levels for each gene present in the model ('model.genes'). +% +% USAGE: +% [gene_id, gene_expr] = findUsedGenesLevels(model, exprData) +% +% INPUTS: +% +% model: input model (COBRA model structure) +% +% exprData: mRNA expression data structure +% .gene cell array containing GeneIDs in the same +% format as model.genes +% .value Vector containing corresponding expression value (FPKM) +% +% OPTIONAL INPUTS: +% printLevel: Printlevel for output (default 0); +% +% OUTPUTS: +% +% gene_id: vector of gene identifiers present in the model +% that are associated with expression data +% +% gene_expr: vector of expression values associated to each +% 'gened_id' +% +% +% Authors: - S. Opdam & A. Richelle May 2017 + +if ~exist('printLevel','var') + printLevel = 0; +end + +gene_expr=[]; +gene_id = model.genes; + +for i = 1:numel(gene_id) + + cur_ID = gene_id{i}; + dataID=find(ismember(exprData.gene,cur_ID)==1); + if isempty (dataID) + gene_expr(i)=-1; + elseif length(dataID)==1 + gene_expr(i)=exprData.value(dataID); + elseif length(dataID)>1 + if printLevel > 0 + disp(['Double for ',num2str(cur_ID)]) + end + gene_expr(i)=mean(exprData.value(dataID)); + end +end + +end +","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","src/tabulate.m",".m","2186","81","function table = tabulate(x) +%TABULATE Frequency table. +% TABLE = TABULATE(X) takes a vector X and returns a matrix, TABLE. +% The first column of TABLE contains the unique values of X. The +% second is the number of instances of each value. The last column +% contains the percentage of each value. If the elements of X are +% non-negative integers, then the output includes 0 counts for any +% integers that are between 1 and max(X) but do not appear in X. +% +% TABLE = TABULATE(X), where X is a categorical variable, character +% array, or a cell array of strings, returns TABLE as a cell array. The +% first column contains the unique string values in X, and the other two +% columns are as above. +% +% TABULATE with no output arguments returns a formatted table +% in the command window. +% +% See also PARETO. + +% Copyright 1993-2011 The MathWorks, Inc. + + +isnum = isnumeric(x); +if isnum && ~isfloat(x) + % use of hist() below requires float + x = double(x); +end +if isnum + if min(size(x)) > 1, + error(message('stats:tabulate:InvalidData')); + end + + y = x(~isnan(x)); +else + y = x; +end + +if ~isnum || any(y ~= round(y)) || any(y < 1); + docell = true; + [y,yn,yl] = grp2idx(y); + maxlevels = length(yn); +else + docell = false; + maxlevels = max(y); + %yn = cellstr(num2str((1:maxlevels)')); +end + +[counts values] = hist(y,(1:maxlevels)); + +total = sum(counts); +percents = 100*counts./total; + +if nargout == 0 + if docell + width = max(cellfun('length',yn)); + width = max(5, min(50, width)); + else + width = 5; + end + + % Create format strings similar to: ' %5s %5d %6.2f%%\n' + fmt1 = sprintf(' %%%ds %%5d %%6.2f%%%%\n',width); + fmt2 = sprintf(' %%%ds %%5s %%6s\n',width); + fprintf(1,fmt2,'Value','Count','Percent'); + if docell + for j=1:maxlevels + fprintf(1,fmt1,yn{j},counts(j),percents(j)); + end + else + fprintf(1,' %5d %5d %6.2f%%\n',[values' counts' percents']'); + end +else + if ~docell + table = [values' counts' percents']; + elseif isnum + table = [yl(:) counts' percents']; + else + table = [yn num2cell([counts' percents'])]; + end +end +","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","src/findRxnIDs.m",".m","596","28","function rxnID = findRxnIDs(model, rxnList) +% Finds reaction numbers in a model +% +% USAGE: +% +% rxnID = findRxnIDs(model, rxnList) +% +% INPUTS: +% model: COBRA model strcture +% rxnList: List of reactions +% +% OUTPUT: +% rxnID: IDs for reactions corresponding to rxnList +% +% .. Author: - Markus Herrgard 4/21/06 + +if (iscell(rxnList)) + [tmp,rxnID] = ismember(rxnList,model.rxns); +else + rxnID = find(strcmp(model.rxns,rxnList)); + if (isempty(rxnID)) + rxnID = 0; + end + if (length(rxnID) > 1) + rxnID = rxnID(1); + end +end +","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","src/selectGeneFromGPR_all.m",".m","3651","92","function [expressionCol, gene_used] = selectGeneFromGPR_all(model, gene_names, gene_exp, parsedGPR, minSum) +% Map gene expression to reaction expression using the GPR rules. An AND +% will be replaced by MIN and an OR will be replaced by MAX. +% +% USAGE: +% expressionCol = selectGeneFromGPR(model, gene_names, gene_exp, parsedGPR, minMax) +% +% INPUTS: +% model: COBRA model struct +% gene_names: gene identifiers corresponding to gene_exp. Names must +% be in the same format as model.genes (column vector) +% (as returned by ""findUsedGeneLevels.m"") +% gene_exp: gene FPKM/expression values, corresponding to names (column vector) +% (as returned by ""findUsedGeneLevels.m"") +% parsedGPR: GPR matrix as returned by ""GPRparser.m"" +% +% OPTIONAL INPUTS: +% minSum: instead of using min and max, use min for AND and Sum +% for OR +% +% OUTPUTS: +% expressionCol: reaction expression, corresponding to model.rxns. +% No gene-expression data and orphan reactions will +% be given a value of -1. +% +% AUTHOR: Anne Richelle, May 2017 + + +if ~exist('minSum','var') + minSum = false; +end +numSamp = length(gene_exp(1,:)); +gene_used={}; +for i=length(model.rxns):-1:1 + for zz = 1:numSamp + gene_used{i,zz}=''; + end +end + +SampStr = {}; +for zz = 1:numSamp +SampStr{zz} = int2str(zz); +end + +% -1 means unknown/no data +expressionCol = -1*ones(length(model.rxns),length(gene_exp(1,:))); +for i = 1:length(model.rxns) + curExprArr=parsedGPR{i}; + for zz = 1:numSamp +% tmpzz = int2str(zz); + tmpStuc.(['curExpr',SampStr{zz}])= []; + tmpStuc.(['gene_potential',SampStr{zz}])=[]; + end + for j=1:length(curExprArr) + if length(curExprArr{j})>=1 + geneID = find(ismember(gene_names,curExprArr{j})); + %geneID = find(ismember(gene_names,str2num(curExprArr{j}{1}))); + % if the gene is measured + if ~isempty(geneID) + for zz = 1:numSamp + % tmpzz = int2str(zz); + if minSum + % This is an or rule, so we sum up all options. + tmpStuc.(['curExpr',SampStr{zz}])= [tmpStuc.(['curExpr',SampStr{zz}]), sum(gene_exp(geneID,zz))]; + tmpStuc.(['gene_potential',SampStr{zz}])=[tmpStuc.(['gene_potential',SampStr{zz}]), gene_names(geneID,zz)']; + else + % If there is data for any gene in 'AND' rule, take the minimum value + [minGenevalue, minID]=min(gene_exp(geneID,zz)); + tmpStuc.(['curExpr',SampStr{zz}])= [tmpStuc.(['curExpr',SampStr{zz}]), minGenevalue]; %If there is data for any gene in 'AND' rule, take the minimum value + tmpStuc.(['gene_potential',SampStr{zz}])=[tmpStuc.(['gene_potential',SampStr{zz}]), gene_names(geneID(minID))]; + end + end + end + end + end + for zz = 1:numSamp +% tmpzz = int2str(zz); + if ~isempty(tmpStuc.(['curExpr',SampStr{zz}])) + if minSum + % in case of min sum these are and clauses that are combined, so its the minimum. + [expressionCol(i,zz), ID_min]=min(tmpStuc.(['curExpr',SampStr{zz}])); + gene_used{i,zz}=tmpStuc.(['gene_potential',SampStr{zz}])(ID_min); + else + % if there is data for any gene in the 'OR' rule, take the maximum value + [expressionCol(i,zz), ID_max]=max(tmpStuc.(['curExpr',SampStr{zz}])); + gene_used{i,zz}=tmpStuc.(['gene_potential',SampStr{zz}])(ID_max); + end + end + end +end + +end","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","src/CellFie.m",".m","14934","343","function[score, score_binary ,taskInfos, detailScoring]=CellFie(data,SampleNumber,ref,param) +% Compute the score associated to each metabolic task listed in taskstructure based on transcriptomic data +% +% USAGE: +% [score, score_binary ,taskInfos, detailScoring]=CellFie(data,SampleNumber,ref,param) +% +% INPUTS: +% data +% .gene cell array containing GeneIDs in the same +% format as model.genes +% .value mRNA expression data structure (genes x samples)associated to each gene metioned in data.gene +% SampleNumber Number of samples +% ref Reference model used to compute the +% metabolic task scores (e.g.,'MT_recon_2_2_entrez.mat') +% OPTIONAL INPUTS: +% param.ThreshType Type of thresholding approach used +% (i.e.,'global' or 'local') (default - local) +% related to the use of a GLOBAL thresholding approach - the threshold value is the same for all the genes +% param.percentile_or_value the threshold can be defined using a value introduced by the user ('value') +% or based on a percentile of the distribution of expression value for all the +% genes and across all samples of your +% dataset ('percentile') +% param.percentile percentile from the distribution of +% expression values for all the genes and across all samples that will be +% used to define the threshold value +% param.value expression value for which a gene is +% considered as active or not (e.g., 5) +% +% related to the use of a LOCAL thresholding approach - the threshold value is different for all the genes +% param.percentile_or_value the threshold can be defined using a value introduced by the user ('value') +% or based on a percentile of the distribution of expression value of a +% specific gene across all samples of your +% dataset ('percentile'-default) +% param.LocalThresholdType option to define the type of local thresholding approach to use +% - 'minmaxmean' (default options )- the threshold for a gene is determined by the mean of expression +% values observed for that gene among all the samples, tissues, or conditions BUT +% the threshold :(i) must be higher or equal to a lower bound and (ii) must be lower +% or equal to an upper bound. +% - 'mean' -the threshold for a gene is defined as the mean expression value +% of this gene across all the samples, tissues, or conditions +% param.percentile_low lower percentile used to define which gene +% are always inactive in the case of use 'MinMaxMean' local thresholding +% approach (default = 25) +% param.percentile_high upper percentile used to define which gene +% are always active in the case of use 'MinMaxMean' local thresholding +% approach (default= 75) +% param.value_low lower expression value used to define which gene +% are always inactive in the case of use 'MinMaxMean' local thresholding +% approach (e.g., 5) +% param.value_high upper expression value used to define which gene +% are always active in the case of use 'MinMaxMean' local thresholding +% approach (e.g., 5) +% +% related to the gene mapping approach used +% param.minSum: instead of using min and max, use min for AND and Sum +% for OR (default: false, i.e. use min) +% OUTPUTS: +% score relative quantification of the activity of a metabolic task in a specific condition +% based on the availability of data for multiple conditions +% score_binary binary version of the metabolic task score +% to determine whether a task is active or inactive in specific +% conditions +% taskInfos Description of the metabolic task assessed +% detailScoring Matrix detailing the scoring +% 1st column = sample ID +% 2nd column = task ID +% 3th column = task score for this sample +% 4th column = task score in binary version for this sample +% 5th column = essential reaction associated to this task +% 6th column = expression score associated to the reaction listed in the 5th column +% 7th column = gene used to determine the expression of the reaction listed in the 5th column +% 8th column = original expression value of the gene listed in the 7th column +% +% .. Authors: +% - Anne Richelle, January 2019 +if size(data.value,2) ~= SampleNumber + error('The number of samples defined is not the same as the size of the dataset') +end +if size(data.value,1) ~= length(data.gene) + error('data.value does not have the same number of rows as data.gene') +end +if ~exist('ref','var') + error('The reference model has not been defined - please choose a reference model') +end +if ~exist('param','var') + param.ThreshType='local'; + param.percentile_or_value='percentile'; + param.LocalThresholdType='minmaxmean'; + param.percentile_low=25; + param.percentile_high=75; +end + +% f = waitbar(0,'Please wait...'); +% waitbar(.15,f,'Loading your data'); + +%load the info about the task structure +load('taskStructure') +taskInfos=struct2cell(taskStructure); +taskInfos=taskInfos'; +taskInfos(:,5:end)=[]; + + +%load the reference model in matlab +load(ref); + +%% Depending on the model, load the list of reactions associated with the task +% All these files have the following format +% essentialRxnsbyTask_name_of_model and are located in essentialRxns folder +load(strcat('essentialRxns/essentialRxnsbyTask_',ref)); + +% check that at least part of list of gene provided are in the model loaded +ID_model=[]; +gene_notInModel=[]; +for i=1:length(data.gene) + if isempty(find(strcmp(data.gene{i},model.genes))) + gene_notInModel(end+1)=i; + else + tmpid=find(strcmp(data.gene{i},model.genes)==1); + ID_model(end+1)=tmpid(1); + end +end + +% introduce a warning in the webtool about how many of the genes provided are +% actually mapped to the model +if isempty(gene_notInModel) + display('All genes provided in data are included in the reference model') +else + display([num2str(length(gene_notInModel)),' genes provided are not included in the reference model:']) + data.gene(gene_notInModel) +end + +% remove the gene and associated value provided by the user in data that are not in the model +data.gene(gene_notInModel)=[]; +if SampleNumber==1 + data.value(gene_notInModel)=[]; +else + data.value(gene_notInModel,:)=[]; +end + +% get the threshold value and the histogram for the complete dataset and +% print a figure +if SampleNumber>1 + linData = reshape(data.value,numel(data.value),1); +else + linData=data.value; +end +linData(linData==0)=[]; + +% definition of the thresholds +if strcmp(param.ThreshType,'global') && strcmp(param.percentile_or_value,'percentile') + display('RUN - global: percentile') + l_global = (prctile(log10(linData),param.percentile)); + data.ths=10^l_global; +elseif strcmp(param.ThreshType,'global') && strcmp(param.percentile_or_value,'value') + display('RUN - global: value') + data.ths=param.value; +elseif strcmp(param.ThreshType,'local') && strcmp(param.LocalThresholdType,'mean') + display('RUN - local: mean') +elseif strcmp(param.ThreshType,'local') && strcmp(param.LocalThresholdType,'minmaxmean')&& strcmp(param.percentile_or_value,'percentile') + display('RUN - local: minmaxmean: percentile') + l_high = (prctile(log10(linData),param.percentile_high)); + data.ths_high=10^l_high; + l_low = (prctile(log10(linData),param.percentile_low)); + data.ths_low=10^l_low; +elseif strcmp(param.ThreshType,'local') && strcmp(param.LocalThresholdType,'minmaxmean')&& strcmp(param.percentile_or_value,'value') + display('RUN - local: minmaxmean: value') + data.ths_high=param.value_high; + data.ths_low=param.value_low; +else + error('No analysis triggered') +end + +%% Compute the threshold(s) depending on the approach used +Gene_score=[]; +switch param.ThreshType + case 'local' + if strcmp(param.LocalThresholdType,'mean') + %the threshold for each gene is equal to its mean value over + %all the samples + threshold=mean(data.value,2)'; + else + threshold=[]; + for i=1:length(data.gene) + expressionValue=data.value(i,:); + if mean(expressionValue)>=data.ths_high + threshold(i)=data.ths_high; + else + threshold(i)=max(mean(expressionValue),data.ths_low); + end + end + end + % every single gene is associated to an expression score + for i=1:SampleNumber + Gene_score(:,i)=5.*log(1+(data.value(:,i)./threshold')); + end + case 'global' + Gene_score=5.*log(1+(data.value./data.ths)); +end + +% Mapping of the expression data to the model +expression.gene=data.gene; +expression.Rxns=[]; +expression.gene_used=[]; +expression.count=[]; +minSum = false; + +%waitbar(.25,f,'Load GPR parse'); +%% load parsedGPR for each model +load(strcat('parsedGPR/parsedGPR_',ref)); +%%parsedGPR = GPRparser(model,minSum);%code to compute the parsed GPR using +%%cobratoolbox + +%waitbar(.45,f,'Mapping of the expression data to the model'); + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% run all samples at the same time +expression.value=Gene_score; +% Find wich genes in expression data are used in the model +[gene_id, gene_expr] = findUsedGenesLevels_all(model,expression); +% Link the gene to the model reactions +[expressionRxns, gene_used] = selectGeneFromGPR_all(model, gene_id, gene_expr, parsedGPR, minSum); + +for zz = 1:SampleNumber + gene_all=[]; + for j=1:length(gene_used(:,zz)) + if ~isempty(gene_used{j,zz}) + gene_all(end+1)=str2num(gene_used{j,zz}{1}); + end + end + countGene = tabulate(gene_all); + count=[]; + for k=1:length(gene_used(:,zz)) + if ~isempty(gene_used{k,zz}) + tmp=countGene(str2num(gene_used{k,zz}{1}),2); + count(k)=tmp; + else + count(k)=0; + end + end + expression.count=[expression.count count']; +end +expression.Rxns = expressionRxns; +expression.gene_used = gene_used; + + + +%% Compute the score +expressionRxns=expression.Rxns; +significance=1./expression.count; +significance(isinf(significance))=0; +ScorebyTask=[]; +ScorebyTask_binary=[]; +%waitbar(.75,f,'Compute the task activity score'); +for i=1:size(taskInfos,1) + if ~isempty(essentialRxns{i}) + rxns=essentialRxns{i}; + rxnID=findRxnIDs(model,rxns); + rxnID(rxnID==0)=[]; + if ~isempty(rxnID) + expValue=expressionRxns(rxnID,:); + signValue=significance(rxnID,:); + % if no gene is associated with one of the reaction - + % remove the reactions from the count + if ~isempty(find(sum(expValue,2)==-SampleNumber)) + signValue(find(sum(expValue,2)==-SampleNumber),:)=[]; + expValue(find(sum(expValue,2)==-SampleNumber),:)=[]; + end + if ~isempty(expValue) + if size(expValue,1)>1 + ScorebyTask(i,:)=sum(expValue.*signValue)./size(expValue,1); + Val=sum(expValue)./size(expValue,1); + ID_up=find(Val>=5*log(2)); + ScorebyTask_binary(i,:)=zeros(1,SampleNumber); + ScorebyTask_binary(i,ID_up)=1; + else + ScorebyTask(i,:)=expValue.*signValue; + ID_up=find(expValue>=5*log(2)); + ScorebyTask_binary(i,:)=zeros(1,SampleNumber); + ScorebyTask_binary(i,ID_up)=1; + end + else + ScorebyTask(i,:)=-1.*ones(1,SampleNumber); + ScorebyTask_binary(i,:)=-1.*ones(1,SampleNumber); + end + else + ScorebyTask(i,:)=-1.*ones(1,SampleNumber); + ScorebyTask_binary(i,:)=-1.*ones(1,SampleNumber); + end + else + ScorebyTask(i,:)=-1.*ones(1,SampleNumber); + ScorebyTask_binary(i,:)=-1.*ones(1,SampleNumber); + end +end + +detailScoring={}; + +tmpSampNum = {}; +for j=1:SampleNumber + tmpSampNum{j} = int2str(j); + incR.(['incR',tmpSampNum{j}])=1; +end + +for i=1:size(taskInfos,1) + if ~isempty(essentialRxns{i}) + rxns=essentialRxns{i}; + rxnID=findRxnIDs(model,rxns); + rxnID(rxnID==0)=[]; + for j=1:SampleNumber + if ~isempty(rxnID) + for k=1:length(rxnID) + %1st column = sample ID + detailScoring{incR.(['incR',tmpSampNum{j}]),((j-1)*8)+1}=j; + %2nd column = task ID + detailScoring{incR.(['incR',tmpSampNum{j}]),((j-1)*8)+2}=i; + %3th column = task score for this sample + detailScoring{incR.(['incR',tmpSampNum{j}]),((j-1)*8)+3}=ScorebyTask(i,j); + %4th column = task score in binary version for this sample + detailScoring{incR.(['incR',tmpSampNum{j}]),((j-1)*8)+4}=ScorebyTask_binary(i,j); + %5th column = essential reaction associated to this + %task + detailScoring{incR.(['incR',tmpSampNum{j}]),((j-1)*8)+5}=rxns(k); + %6th column = expression score associated to the + %reaction listed in the 5th column + detailScoring{incR.(['incR',tmpSampNum{j}]),((j-1)*8)+6}=expression.Rxns(rxnID(k),j); + %7th column = gene used to determine the expression of the + %reaction listed in the 5th column + geneName=expression.gene_used(rxnID(k),j); + detailScoring{incR.(['incR',tmpSampNum{j}]),((j-1)*8)+7}=geneName; + %8th column = original expression value of the gene + %listed in the 7th column + detailScoring{incR.(['incR',tmpSampNum{j}]),((j-1)*8)+8}=data.value((strcmp(data.gene,geneName{1})),j); % 8.64 + incR.(['incR',tmpSampNum{j}])=incR.(['incR',tmpSampNum{j}])+1; + end + end + end + end + score=ScorebyTask; + score_binary=ScorebyTask_binary; +end +end + + +%close(f)","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","src/runCellFie.m",".m","2834","106","addpath(genpath('/var/www/pinapl-py-site/')) +addpath(genpath('/var/www/MATLAB/lib/')) +addpath(genpath('/var/www/MATLAB/lib/MetTasks/')) +addpath(genpath('/var/www/MATLAB/lib/MetTasks/matlab')) +addpath(genpath('/var/www/MATLAB/lib//MetTasks/matlab/yaml')) +addpath(genpath('/var/www/MATLAB/lib/cobratoolbox/')) + + +yml = YAML.read(config_file); + +dataAll = readtable(data_file); +'input data head:' +dataAll(1:10,:) + +ThreshType = yml.ThreshType +SampleNumber = yml.SampleNumber +ref = yml.ref + +percentile_or_value = yml.percentile_or_value +percentile = yml.percentile +value = yml.value + +EnoughSamples = yml.EnoughSamples +LocalThresholdType = yml.LocalThresholdType +percentile_low = yml.percentileLow +percentile_high = yml.percentileHigh +value_low = yml.valueLow +value_high = yml.valueHigh + +data = {}; +data.gene = string( table2array( dataAll(:,1) ) ); +data.value = table2array( dataAll(:,2:end) ); +[score, score_binary ,taskInfos, detailScoring]=CellFie(data,ThreshType,SampleNumber,ref,percentile_or_value,percentile,value,LocalThresholdType,percentile_low,percentile_high,value_low,value_high) + +rownames=taskInfos(:,2) +colnames=1:SampleNumber +score_long=wide2long(score,rownames,colnames) + +fname='Analysis/Output/' +save 'Analysis/Output/score.mat' score +tab=table(taskInfos,score) +writetable(tab,fullfile(fname, 'score.csv')) + +% write names if present +tableNames = dataAll.Properties.VariableNames +writetable(tab,fullfile(fname, 'annotation.csv')) + +D2 = pdist(score); +Z2 = linkage(D2,'average'); +order2 = optimalleaforder(Z2, D2); +D3 = pdist(score'); +Z3 = linkage(D3,'average'); +order3 = optimalleaforder(Z3, D3); + +score_cluster = score(order2,order3); + +figure(2) +imagesc(score_cluster) +ax=gca; +ax.YTick=1:length(taskInfos(:,2)); +ax.YTickLabel=taskInfos(order2,2); + +ax.XTick=1:length(colnames); +ax.XTickLabel=colnames(order3); +colorbar +saveas(figure(2),'Analysis/Figures/score_heatmap.png') + +figure(3) +dendrogram(Z3) +saveas(figure(3),'Analysis/Figures/score_dendro.png') + +fname='Analysis/Output/' +save 'Analysis/Output/score_binary.mat' score_binary +tab=table(taskInfos,score_binary) +writetable(tab,fullfile(fname, 'score_binary.csv')) + +D2 = pdist(score_binary); +Z2 = linkage(D2,'average'); +order2 = optimalleaforder(Z2, D2); +D3 = pdist(score_binary'); +Z3 = linkage(D3,'average'); +order3 = optimalleaforder(Z3, D3); + +score_bin_cluster = score_binary(order2,order3); + +figure('units','normalized','outerposition',[0 0 1 1]) +imagesc(score_bin_cluster) +ax=gca; + +ax.XTick=1:length(colnames); +ax.XTickLabel=colnames(order3); +colorbar +fig=gcf; +saveas(figure(fig.Number),'Analysis/Figures/score_bin_heatmap.png') + +figure(3) +dendrogram(Z3) +saveas(figure(3),'Analysis/Figures/score_bin_dendro.png') + +save 'Analysis/Output/taskInfos.mat' taskInfos +fname='Analysis/Output/' +tab=table(taskInfos) +writetable(tab,fullfile(fname, 'taskInfos.csv')) + +exit +exit","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","src/selectGeneFromGPR.m",".m","2861","75","function [expressionCol, gene_used] = selectGeneFromGPR(model, gene_names, gene_exp, parsedGPR, minSum) +% Map gene expression to reaction expression using the GPR rules. An AND +% will be replaced by MIN and an OR will be replaced by MAX. +% +% USAGE: +% expressionCol = selectGeneFromGPR(model, gene_names, gene_exp, parsedGPR, minMax) +% +% INPUTS: +% model: COBRA model struct +% gene_names: gene identifiers corresponding to gene_exp. Names must +% be in the same format as model.genes (column vector) +% (as returned by ""findUsedGeneLevels.m"") +% gene_exp: gene FPKM/expression values, corresponding to names (column vector) +% (as returned by ""findUsedGeneLevels.m"") +% parsedGPR: GPR matrix as returned by ""GPRparser.m"" +% +% OPTIONAL INPUTS: +% minSum: instead of using min and max, use min for AND and Sum +% for OR +% +% OUTPUTS: +% expressionCol: reaction expression, corresponding to model.rxns. +% No gene-expression data and orphan reactions will +% be given a value of -1. +% +% AUTHOR: Anne Richelle, May 2017 + + +if ~exist('minSum','var') + minSum = false; +end +gene_used={}; +for i=1:length(model.rxns) + gene_used{i}=''; +end + +% -1 means unknown/no data +expressionCol = -1*ones(length(model.rxns),1); +for i = 1:length(model.rxns) + curExprArr=parsedGPR{i}; + curExpr= []; + gene_potential=[]; + for j=1:length(curExprArr) + if length(curExprArr{j})>=1 + geneID = find(ismember(gene_names,curExprArr{j})); + %geneID = find(ismember(gene_names,str2num(curExprArr{j}{1}))); + % if the gene is measured + if ~isempty(geneID) + if minSum + % This is an or rule, so we sum up all options. + curExpr= [curExpr, sum(gene_exp(geneID))]; + gene_potential=[gene_potential, gene_names(geneID)']; + else + % If there is data for any gene in 'AND' rule, take the minimum value + [minGenevalue, minID]=min(gene_exp(geneID)); + curExpr= [curExpr, minGenevalue]; %If there is data for any gene in 'AND' rule, take the minimum value + gene_potential=[gene_potential, gene_names(geneID(minID))]; + end + end + end + end + if ~isempty(curExpr) + if minSum + % in case of min sum these are and clauses that are combined, so its the minimum. + [expressionCol(i), ID_min]=min(curExpr); + gene_used{i}=gene_potential(ID_min); + else + % if there is data for any gene in the 'OR' rule, take the maximum value + [expressionCol(i), ID_max]=max(curExpr); + gene_used{i}=gene_potential(ID_max); + end + end +end + +end","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","test/suite/testCellFie.m",".m","5712","133","% Generation of all the potential results + +%% dataRecon22_local_minmaxmean_value +load('dataTest.mat') +SampleNumber=3; +ref='MT_recon_2_2_entrez.mat'; +param.ThreshType='local'; +param.percentile_or_value='value'; +param.LocalThresholdType='minmaxmean'; +param.value_low=25; +param.value_high=75; + +[score, score_binary ,taskInfos, detailScoring]=CellFie(data,SampleNumber,ref,param); +save dataRecon22_local_minmaxmean_value score score_binary taskInfos detailScoring +csvwrite('dataRecon22_local_minmaxmean_value.score.csv',score); +csvwrite('dataRecon22_local_minmaxmean_value.score_binary.csv',score_binary); +T = cell2table(taskInfos); +writetable(T,'dataRecon22_local_minmaxmean_value.taskInfo.csv'); + Var={}; + for i=1:SampleNumber + Var=[Var strcat('SampleID_S',num2str(i)) strcat('TaskID_S',num2str(i)) strcat('TaskScore_S',num2str(i))... + strcat('BinaryTaskScore_S',num2str(i)) strcat('EssentialRxnsTask_S',num2str(i))... + strcat('ExpressionScoreEssentialRxnsTask_S',num2str(i))... + strcat('GeneAssociatedToEssentialRxnsTask_S',num2str(i))... + strcat('GeneExpressionValue_S',num2str(i))]; + end + D = cell2table(detailScoring,'VariableNames',Var); + writetable(D,'dataRecon22_local_minmaxmean_value.detailScoring.csv') + +%% dataRecon22_local_minmaxmean_percentile +load('dataTest.mat') +SampleNumber=3; +ref='MT_recon_2_2_entrez.mat'; +param.ThreshType='local'; +param.percentile_or_value='percentile'; +param.LocalThresholdType='minmaxmean'; +param.percentile_low=25; +param.percentile_high=75; + +[score, score_binary ,taskInfos, detailScoring]=CellFie(data,SampleNumber,ref,param); +save dataRecon22_local_minmaxmean_percentile score score_binary taskInfos detailScoring +csvwrite('dataRecon22_local_minmaxmean_percentile.score.csv',score); +csvwrite('dataRecon22_local_minmaxmean_percentile.score_binary.csv',score_binary); +T = cell2table(taskInfos); +writetable(T,'dataRecon22_local_minmaxmean_percentile.taskInfo.csv'); + Var={}; + for i=1:SampleNumber + Var=[Var strcat('SampleID_S',num2str(i)) strcat('TaskID_S',num2str(i)) strcat('TaskScore_S',num2str(i))... + strcat('BinaryTaskScore_S',num2str(i)) strcat('EssentialRxnsTask_S',num2str(i))... + strcat('ExpressionScoreEssentialRxnsTask_S',num2str(i))... + strcat('GeneAssociatedToEssentialRxnsTask_S',num2str(i))... + strcat('GeneExpressionValue_S',num2str(i))]; + end + D = cell2table(detailScoring,'VariableNames',Var); + writetable(D,'dataRecon22_local_minmaxmean_percentile.detailScoring.csv'); + +%% dataRecon22_local_mean +load('dataTest.mat') +SampleNumber=3; +ref='MT_recon_2_2_entrez.mat'; +param.ThreshType='local'; +param.LocalThresholdType='mean'; + +[score, score_binary ,taskInfos, detailScoring]=CellFie(data,SampleNumber,ref,param); +save dataRecon22_local_mean score score_binary taskInfos detailScoring +csvwrite('dataRecon22_local_mean.score.csv',score); +csvwrite('dataRecon22_local_mean.score_binary.csv',score_binary); +T = cell2table(taskInfos); +writetable(T,'dataRecon22_local_mean.taskInfo.csv'); + Var={}; + for i=1:SampleNumber + Var=[Var strcat('SampleID_S',num2str(i)) strcat('TaskID_S',num2str(i)) strcat('TaskScore_S',num2str(i))... + strcat('BinaryTaskScore_S',num2str(i)) strcat('EssentialRxnsTask_S',num2str(i))... + strcat('ExpressionScoreEssentialRxnsTask_S',num2str(i))... + strcat('GeneAssociatedToEssentialRxnsTask_S',num2str(i))... + strcat('GeneExpressionValue_S',num2str(i))]; + end + D = cell2table(detailScoring,'VariableNames',Var); + writetable(D,'dataRecon22_local_mean.detailScoring.csv'); + +%% dataRecon22_global_value +load('dataTest.mat') +SampleNumber=3; +ref='MT_recon_2_2_entrez.mat'; +param.ThreshType='global'; +param.percentile_or_value='value'; +param.value=50; + +[score, score_binary ,taskInfos, detailScoring]=CellFie(data,SampleNumber,ref,param); +save dataRecon22_global_value score score_binary taskInfos detailScoring +csvwrite('dataRecon22_global_value.score.csv',score); +csvwrite('dataRecon22_global_value.score_binary.csv',score_binary); +T = cell2table(taskInfos); +writetable(T,'dataRecon22_global_value.taskInfo.csv'); + Var={}; + for i=1:SampleNumber + Var=[Var strcat('SampleID_S',num2str(i)) strcat('TaskID_S',num2str(i)) strcat('TaskScore_S',num2str(i))... + strcat('BinaryTaskScore_S',num2str(i)) strcat('EssentialRxnsTask_S',num2str(i))... + strcat('ExpressionScoreEssentialRxnsTask_S',num2str(i))... + strcat('GeneAssociatedToEssentialRxnsTask_S',num2str(i))... + strcat('GeneExpressionValue_S',num2str(i))]; + end + D = cell2table(detailScoring,'VariableNames',Var); + writetable(D,'dataRecon22_global_value.detailScoring.csv'); + +%% dataRecon22_global_percentile +load('dataTest.mat') +SampleNumber=3; +ref='MT_recon_2_2_entrez.mat'; +param.ThreshType='global'; +param.percentile_or_value='percentile'; +param.percentile=50; + +[score, score_binary ,taskInfos, detailScoring]=CellFie(data,SampleNumber,ref,param); +save dataRecon22_global_percentile score score_binary taskInfos detailScoring +csvwrite('dataRecon22_global_percentile.score.csv',score); +csvwrite('dataRecon22_global_percentile.score_binary.csv',score_binary); +T = cell2table(taskInfos); +writetable(T,'dataRecon22_global_percentile.taskInfo.csv'); + + Var={}; + for i=1:SampleNumber + Var=[Var strcat('SampleID_S',num2str(i)) strcat('TaskID_S',num2str(i)) strcat('TaskScore_S',num2str(i))... + strcat('BinaryTaskScore_S',num2str(i)) strcat('EssentialRxnsTask_S',num2str(i))... + strcat('ExpressionScoreEssentialRxnsTask_S',num2str(i))... + strcat('GeneAssociatedToEssentialRxnsTask_S',num2str(i))... + strcat('GeneExpressionValue_S',num2str(i))]; + end + D = cell2table(detailScoring,'VariableNames',Var); + writetable(D,'dataRecon22_global_percentile.detailScoring.csv'); + + +","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","genepattern/run_cellfie_in_docker.sh",".sh","166","2"," docker run --rm -v $PWD:/IO atwenzel/cellfie:1.3 /usr/local/MATLAB/MATLAB_Runtime/v94 test/suite/dataTest.mat 3 MT_recon_2_2_entrez.mat local value minmaxmean 25 75 +","Shell" +"Metabolic","LewisLabUCSD/CellFie","genepattern/execCellfie.m",".m","3197","74","function []=execCellfie(DATA,SAMP,REF,pTHRESH,pPERCVAL,pGLOBAL,pTYPE,pLOW,pHIGH,outputdir) + if contains(DATA,'mat') + load(DATA); + elseif( contains(DATA,'csv')||contains(DATA,'tsv')||contains(DATA,'xlsx')||contains(DATA,'xls')) + datatmp=readtable(DATA); + genetmp=table2array(datatmp(:,1)); + tmp = struct('gene',table2array(datatmp(:,1)),'value',table2array(datatmp(:,2:end))); + tmp.gene = num2cell(tmp.gene); + for i=1:length(genetmp) + tmp.gene{i}=int2str(genetmp(i)); + end + data=tmp; + else + error('Your data file must be formatted as: .mat, .csv, .tsv, .xlsx, or .xls with the correct suffix') + end + SampleNumber=str2num(SAMP); + ref=REF; + param.ThreshType=pTHRESH; + param.percentile_or_value=pPERCVAL; + param.LocalThresholdType=pTYPE; + if strcmp(pTHRESH,'local') + if strcmp(pTYPE,'minmaxmean') + if strcmp(pPERCVAL,'percentile') + param.percentile_low=str2num(pLOW); + param.percentile_high=str2num(pHIGH); + elseif strcmp(pPERCVAL,'value') + param.value_low=str2num(pLOW); + param.value_high=str2num(pHIGH); + else + error(""cutoff type must be 'percentile' or 'value'"") + end + end + elseif strcmp(pTHRESH,'global') + if strcmp(pPERCVAL,'percentile') + param.percentile=str2num(pGLOBAL); + elseif strcmp(pPERCVAL,'value') + param.value=str2num(pGLOBAL); + else + error(""cutoff type must be 'percentile' or 'value'"") + end + else + error(""threshold type must be 'local' or 'global'"") + end + + + [score, score_binary ,taskInfos, detailScoring]=CellFie(data,SampleNumber,ref,param); + + save cellfieout score score_binary taskInfos detailScoring + %saveas(figure(1),'histogram.png') + %close(figure(1)) + + csvwrite(strcat(outputdir,'/score.csv'),score); + csvwrite(strcat(outputdir,'/score_binary.csv'),score_binary); + T = cell2table(taskInfos); + writetable(T,strcat(outputdir,'/taskInfo.csv')); + Var={}; + for i=1:SampleNumber + Var=[Var strcat('SampleID_S',num2str(i)) strcat('TaskID_S',num2str(i)) strcat('TaskScore_S',num2str(i))... + strcat('BinaryTaskScore_S',num2str(i)) strcat('EssentialRxnsTask_S',num2str(i))... + strcat('ExpressionScoreEssentialRxnsTask_S',num2str(i))... + strcat('GeneAssociatedToEssentialRxnsTask_S',num2str(i))... + strcat('GeneExpressionValue_S',num2str(i))]; + end + D = cell2table(detailScoring,'VariableNames',Var); + writetable(D,strcat(outputdir,'/detailScoring.csv')); + +% ./matlab_compiled/execCellfie/for_redistribution_files_only/run_execCellfie.sh \ +% /usr/local/MATLAB/MATLAB_Runtime/v94 test/suite/dataTest.mat 3 \ +% MT_recon_2_2_entrez.mat local value NA minmaxmean 25 75 outtmp +% execCellfie('test/suite/dataTest.xlsx','3','MT_recon_2_2_entrez.mat','local','value','25','minmaxmean','25','75','outtmp') +% execCellfie('test/suite/dataTest.csv','3','MT_recon_2_2_entrez.mat','local','percentile','40','minmaxmean','15','85','outtmp') +% execCellfie('test/suite/dataTest.csv','3','MT_recon_2_2_entrez.mat','local','value','40','mean','15','85','outtmp') +% execCellfie('test/suite/dataTest.csv','3','MT_recon_2_2_entrez.mat','global','percentile','30','minmaxmean','15','85','outtmp') +","MATLAB" +"Metabolic","LewisLabUCSD/CellFie","genepattern/build_docker_container.sh",".sh","52","2","docker build -f genepattern/Dockerfile -t cellfie . +","Shell" +"Metabolic","LewisLabUCSD/CellFie","genepattern/bashwrapper.sh",".sh","642","28","# RUN: +# cd genepattern/ +# ./bashwrapper.sh 'test/suite/dataTest.mat' 3 'test/suite/MT_recon_2_2_entrez.mat' 'local' 'value' 'minmaxmean' 25 75 +## read parameters +#load('test/suite/dataTest.mat') +DATA=$1 +#SampleNumber=3; +SAMP=$2 +#ref='test/suite/MT_recon_2_2_entrez.mat'; +REF=$3 +#param.ThreshType='local'; +pTHRESH=$4 +#param.percentile_or_value='value'; +pPERCVAL=$5 +#param.LocalThresholdType='minmaxmean'; +pTYPE=$6 +#param.value_low=25; +pLOW=$7 +#param.value_high=75; +pHIGH=$8 + +#Run +CMD=""addpath(genpath('..'));execCellfie('$DATA',$SAMP,'$REF','$pTHRESH','$pPERCVAL','$pTYPE',$pLOW,$pHIGH);exit"" +echo $CMD +matlab -nosplash -nodesktop -r $CMD + + +","Shell" +"Metabolic","LewisLabUCSD/CellFie","genepattern/testexec.m",".m","1338","11"," +% ./matlab_compiled/execCellfie/for_redistribution_files_only/run_execCellfie.sh /usr/local/MATLAB/MATLAB_Runtime/v94 test/suite/dataTest.mat 3 MT_recon_2_2_entrez.mat local value NA minmaxmean 25 75 outtmp +% ./matlab_compiled/execCellfie/for_redistribution_files_only/run_execCellfie.sh /usr/local/MATLAB/MATLAB_Runtime/v94 test/suite/dataTest.csv 3 MT_recon_2_2_entrez.mat local value NA minmaxmean 25 75 outtmp +% ./matlab_compiled/execCellfie/for_redistribution_files_only/run_execCellfie.sh /usr/local/MATLAB/MATLAB_Runtime/v94 test/suite/dataTest.xlsx 3 MT_recon_2_2_entrez.mat local value NA minmaxmean 25 75 outtmp +% ./matlab_compiled/execCellfie/for_redistribution_files_only/run_execCellfie.sh /usr/local/MATLAB/MATLAB_Runtime/v94 test/suite/dataTest.mat 3 MT_recon_2_2_entrez.mat local value NA minmaxmean 25 75 outtmp + +execCellfie('../test/suite/dataTest.xlsx','3','MT_recon_2_2_entrez.mat','local','value','25','minmaxmean','25','75','outtmp') +execCellfie('../test/suite/dataTest.csv','3','MT_recon_2_2_entrez.mat','local','percentile','40','minmaxmean','15','85','outtmp') +execCellfie('../test/suite/dataTest.csv','3','MT_recon_2_2_entrez.mat','local','value','40','mean','15','85','outtmp') +execCellfie('../test/suite/dataTest.csv','3','MT_recon_2_2_entrez.mat','global','percentile','30','minmaxmean','15','85','outtmp') +","MATLAB" +"Metabolic","LCSB-BioCore/SBML.jl","src/version.jl",".jl","218","10"," +"""""" +$(TYPEDSIGNATURES) + +Get the version of the used SBML library in Julia version format. +"""""" +function Version()::VersionNumber + VersionNumber(unsafe_string(ccall(sbml(:getLibSBMLDottedVersion), Cstring, ()))) +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","src/math.jl",".jl","9031","252"," +"""""" +$(TYPEDSIGNATURES) + +Helper for quickly recognizing kinds of ASTs +"""""" +ast_is(ast::VPtr, what::Symbol)::Bool = ccall(sbml(what), Cint, (VPtr,), ast) != 0 + +"""""" +$(TYPEDSIGNATURES) + +Recursively parse all children of an AST node. +"""""" +parse_math_children(ast::VPtr)::Vector{Math} = [ + parse_math(ccall(sbml(:ASTNode_getChild), VPtr, (VPtr, Cuint), ast, i - 1)) for + i = 1:ccall(sbml(:ASTNode_getNumChildren), Cuint, (VPtr,), ast) +] + + + +# Mapping of AST node type value subset to relational operations. Depends on +# `ASTNodeType.h` (also see below the case with AST_NAME_TIME) +const relational_opers = Dict{Int32,String}( + 308 => ""eq"", + 309 => ""geq"", + 310 => ""gt"", + 311 => ""leq"", + 312 => ""lt"", + 313 => ""neq"", +) +# Inverse mapping, needed for creating `ASTNode_t` pointers from `MathApply` objects. +const inv_relational_opers = Dict(val => key for (key, val) in relational_opers) + +function relational_oper(t::Int) + haskey(relational_opers, t) || + throw(DomainError(t, ""Unknown ASTNodeType value for relational operator"")) + relational_opers[t] +end + +# Mapping of AST node type value subset to mathematical operations. Depends on +# `ASTNodeType.h` (also see below the case with AST_NAME_TIME) +const math_opers = Dict{Int32,String}(43 => ""+"", 45 => ""-"", 42 => ""*"", 47 => ""/"", 94 => ""^"") +# Inverse mapping, needed for creating `ASTNode_t` pointers from `MathApply` objects. +const inv_math_opers = Dict(val => key for (key, val) in math_opers) + +# Mapping of AST node type value subset to logical operations. Depends on +# `ASTNodeType.h` (also see below the case with AST_NAME_TIME) +const logical_opers = + Dict{Int32,String}(304 => ""and"", 305 => ""not"", 306 => ""or"", 307 => ""xor"") +# Inverse mapping, needed for creating `ASTNode_t` pointers from `MathApply` objects. +const inv_logical_opers = Dict(val => key for (key, val) in logical_opers) + +# Mapping of AST node type value subset to mathematical functions. Depends on +# `ASTNodeType.h` (also see below the case with AST_NAME_TIME) +const math_funcs = Dict{Int32,String}( + 269 => ""abs"", + 270 => ""arccos"", + 271 => ""arccosh"", + 272 => ""arccot"", + 273 => ""arccoth"", + 274 => ""arccsc"", + 275 => ""arccsch"", + 276 => ""arcsec"", + 277 => ""arcsech"", + 278 => ""arcsin"", + 279 => ""arcsinh"", + 280 => ""arctan"", + 281 => ""arctanh"", + 282 => ""ceiling"", + 283 => ""cos"", + 284 => ""cosh"", + 285 => ""cot"", + 286 => ""coth"", + 287 => ""csc"", + 288 => ""csch"", + 289 => ""delay"", + 290 => ""exp"", + 291 => ""factorial"", + 292 => ""floor"", + 293 => ""ln"", + 294 => ""log"", + 295 => ""piecewise"", + 296 => ""power"", + 297 => ""root"", + 298 => ""sec"", + 299 => ""sech"", + 300 => ""sin"", + 301 => ""sinh"", + 302 => ""tan"", + 303 => ""tanh"", +) +# Inverse mapping, needed for creating `ASTNode_t` pointers from `MathApply` objects. +const inv_math_funcs = Dict(val => key for (key, val) in math_funcs) +# Everybody wants to be a map! +const all_inv_function_mappings = + merge(inv_relational_opers, inv_math_opers, inv_logical_opers, inv_math_funcs) + +# This is for checking the ""special case"" named values as defined by SBML. +# The constants are the values of the enums AST_NAME_* in +# `libsbml/src/sbml/math/ASTNodeType.h`. These need to be kept up to date with +# the library (otherwise this breaks). +get_ast_type_id(::Type{MathAvogadro}) = 261 +get_ast_type_id(::Type{MathTime}) = 262 + +"""""" +$(TYPEDSIGNATURES) + +This attempts to parse out a decent Julia-esque [`Math`](@ref) AST from a +pointer to `ASTNode_t`. +"""""" +function parse_math(ast::VPtr)::Math + if ast_is(ast, :ASTNode_isName) + type = ccall(sbml(:ASTNode_getType), Cint, (VPtr,), ast) + if type == get_ast_type_id(MathAvogadro) + # this should be synonymous with calling ASTNode_isAvogadro() + return MathAvogadro(get_string(ast, :ASTNode_getName)) + elseif type == get_ast_type_id(MathTime) + # unfortunately there's no ASTNode_isTime() at the moment. + return MathTime(get_string(ast, :ASTNode_getName)) + else + return MathIdent(get_string(ast, :ASTNode_getName)) + end + elseif ast_is(ast, :ASTNode_isConstant) + return MathConst(get_string(ast, :ASTNode_getName)) + elseif ast_is(ast, :ASTNode_isInteger) + return MathVal(ccall(sbml(:ASTNode_getInteger), Cint, (VPtr,), ast)) + elseif ast_is(ast, :ASTNode_isRational) + return MathVal( + ccall(sbml(:ASTNode_getNumerator), Cint, (VPtr,), ast) // + ccall(sbml(:ASTNode_getDenominator), Cint, (VPtr,), ast), + ) + elseif ast_is(ast, :ASTNode_isReal) + return MathVal(ccall(sbml(:ASTNode_getReal), Cdouble, (VPtr,), ast)) + elseif ast_is(ast, :ASTNode_isFunction) + return MathApply(get_string(ast, :ASTNode_getName), parse_math_children(ast)) + elseif ast_is(ast, :ASTNode_isOperator) + return MathApply( + string(Char(ccall(sbml(:ASTNode_getCharacter), Cchar, (VPtr,), ast))), + parse_math_children(ast), + ) + elseif ast_is(ast, :ASTNode_isRelational) + return MathApply( + relational_oper(Int(ccall(sbml(:ASTNode_getType), Cint, (VPtr,), ast))), + parse_math_children(ast), + ) + elseif ast_is(ast, :ASTNode_isLogical) + return MathApply(get_string(ast, :ASTNode_getName), parse_math_children(ast)) + elseif ast_is(ast, :ASTNode_isLambda) + children = parse_math_children(ast) + if !isempty(children) + body = pop!(children) + return MathLambda(broadcast((x::MathIdent) -> x.id, children), body) + else + @warn ""invalid function definition found"" + return MathIdent(""?invalid?"") + end + else + @warn ""unsupported math element found"" + return MathIdent(""?unsupported?"") + end +end + +## Inverse of `parse_math`: create `ASTNode_t` pointers from `Math` objects. + +function get_astnode_ptr(m::Union{MathTime,MathAvogadro})::VPtr + astnode = ccall(sbml(:ASTNode_create), VPtr, ()) + ccall(sbml(:ASTNode_setName), Cint, (VPtr, Cstring), astnode, m.id) + ccall(sbml(:ASTNode_setType), Cint, (VPtr, Cuint), astnode, get_ast_type_id(typeof(m))) + ccall(sbml(:ASTNode_canonicalize), Cint, (VPtr,), astnode) + return astnode +end + +function get_astnode_ptr(m::Union{MathIdent,MathConst})::VPtr + m.id in (""?invalid?"", ""?unsupported?"") && + error(""Cannot get a pointer for `MathIdent` with ID \""$(m.id)\"""") + astnode = ccall(sbml(:ASTNode_create), VPtr, ()) + ccall(sbml(:ASTNode_setName), Cint, (VPtr, Cstring), astnode, m.id) + ccall(sbml(:ASTNode_canonicalize), Cint, (VPtr,), astnode) + return astnode +end + +function get_astnode_ptr(m::MathVal{<:Integer})::VPtr + astnode = ccall(sbml(:ASTNode_create), VPtr, ()) + ccall(sbml(:ASTNode_setInteger), Cint, (VPtr, Clong), astnode, m.val) + ccall(sbml(:ASTNode_canonicalize), Cint, (VPtr,), astnode) + return astnode +end + +function get_astnode_ptr(m::MathVal{<:Rational})::VPtr + astnode = ccall(sbml(:ASTNode_create), VPtr, ()) + # Note: this can be in principle a lossy reconstruction as `Rational`s in + # Julia are automatically simplified (e.g., 5//10 -> 1//2). + ccall( + sbml(:ASTNode_setRational), + Cint, + (VPtr, Clong, Clong), + astnode, + numerator(m.val), + denominator(m.val), + ) + ccall(sbml(:ASTNode_canonicalize), Cint, (VPtr,), astnode) + return astnode +end + +function get_astnode_ptr(m::MathVal{<:Real})::VPtr + astnode = ccall(sbml(:ASTNode_create), VPtr, ()) + ccall(sbml(:ASTNode_setReal), Cint, (VPtr, Cdouble), astnode, m.val) + ccall(sbml(:ASTNode_canonicalize), Cint, (VPtr,), astnode) + return astnode +end + +function get_astnode_ptr(m::MathApply)::VPtr + astnode = ccall(sbml(:ASTNode_create), VPtr, ()) + # Set the name + ccall(sbml(:ASTNode_setName), Cint, (VPtr, Cstring), astnode, m.fn) + # Set the type + if m.fn in keys(all_inv_function_mappings) + ccall( + sbml(:ASTNode_setType), + Cint, + (VPtr, Cuint), + astnode, + all_inv_function_mappings[m.fn], + ) + else + ccall(sbml(:ASTNode_setType), Cint, (VPtr, Cuint), astnode, 268) # 268 == AST_FUNCTION + end + # Add children + for child in m.args + child_ptr = get_astnode_ptr(child) + ccall(sbml(:ASTNode_addChild), Cint, (VPtr, VPtr), astnode, child_ptr) + end + ccall(sbml(:ASTNode_canonicalize), Cint, (VPtr,), astnode) + return astnode +end + +function get_astnode_ptr(m::MathLambda)::VPtr + astnode = ccall(sbml(:ASTNode_create), VPtr, ()) + # All arguments + for child in MathIdent.(m.args) + child_ptr = get_astnode_ptr(child) + ccall(sbml(:ASTNode_addChild), Cint, (VPtr, VPtr), astnode, child_ptr) + end + # Add the body + body = get_astnode_ptr(m.body) + ccall(sbml(:ASTNode_addChild), Cint, (VPtr, VPtr), astnode, body) + # Set the type + ccall(sbml(:ASTNode_setType), Cint, (VPtr, Cuint), astnode, 267) # 267 == AST_LAMBDA + # Done + return astnode +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","src/SBML.jl",".jl","905","41",""""""" +$(DocStringExtensions.README) +"""""" +module SBML + +using SBML_jll, Libdl + +using DocStringExtensions +using IfElse +using SparseArrays +using Unitful + +include(""types.jl"") +include(""structs.jl"") +include(""version.jl"") + +include(""converters.jl"") +include(""interpret.jl"") +include(""math.jl"") +include(""readsbml.jl"") +include(""writesbml.jl"") +include(""unitful.jl"") +include(""utils.jl"") + +"""""" +$(TYPEDSIGNATURES) + +A shortcut that loads a function symbol from `SBML_jll`. +"""""" +sbml(sym::Symbol)::VPtr = dlsym(SBML_jll.libsbml_handle, sym) + +export readSBML, readSBMLFromString, stoichiometry_matrix, flux_bounds, flux_objective +export writeSBML +export set_level_and_version, + libsbml_convert, convert_simplify_math, convert_promotelocals_expandfuns + +# Read a file at precompile time, to improve time-to-first `readSBML`. +writeSBML(readSBML(joinpath(@__DIR__, "".."", ""test"", ""data"", ""Dasgupta2020-written.xml""))) + +end # module +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","src/structs.jl",".jl","11358","544"," +"""""" +$(TYPEDEF) + +Common supertype for all SBML.jl objects. +"""""" +abstract type SBMLObject end + +"""""" +$(TYPEDEF) + +Part of a measurement unit definition that corresponds to the SBML definition +of `Unit`. For example, the unit ""per square megahour"", Mh^(-2), is written as: + + SBML.UnitPart(""second"", # base SI unit, this says we are measuring time + -2, # exponent, says ""per square"" + 6, # log-10 scale of the unit, says ""mega"" + 1/3600) # second-to-hour multiplier + +Compound units (such as ""volt-amperes"" and ""dozens of yards per ounce"") are +built from multiple `UnitPart`s. See also [`SBML.UnitDefinition`](@ref). + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct UnitPart <: SBMLObject + kind::String + exponent::Int + scale::Int + multiplier::Float64 +end + +"""""" +$(TYPEDEF) + +Representation of SBML unit definition, holding the name of the unit and a +vector of [`SBML.UnitPart`](@ref)s. See the definition of field `units` in +[`SBML.Model`](@ref). + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct UnitDefinition <: SBMLObject + name::Maybe{String} = nothing + unit_parts::Vector{UnitPart} +end + +"""""" +$(TYPEDEF) + +Abstract type for all kinds of gene product associations +"""""" +abstract type GeneProductAssociation <: SBMLObject end + +"""""" +$(TYPEDEF) + +Gene product reference in the association expression + +# Fields +$(TYPEDFIELDS) +"""""" +struct GPARef <: GeneProductAssociation + gene_product::String +end + +"""""" +$(TYPEDEF) + +Boolean binary ""and"" in the association expression + +# Fields +$(TYPEDFIELDS) +"""""" +struct GPAAnd <: GeneProductAssociation + terms::Vector{GeneProductAssociation} +end + +"""""" +$(TYPEDEF) + +Boolean binary ""or"" in the association expression + +# Fields +$(TYPEDFIELDS) +"""""" +struct GPAOr <: GeneProductAssociation + terms::Vector{GeneProductAssociation} +end + +"""""" +$(TYPEDEF) + +A simplified representation of MathML-specified math AST +"""""" +abstract type Math <: SBMLObject end + +"""""" +$(TYPEDEF) + +A literal value (usually a numeric constant) in mathematical expression + +# Fields +$(TYPEDFIELDS) +"""""" +struct MathVal{T} <: Math where {T} + val::T +end + +"""""" +$(TYPEDEF) + +An identifier (usually a variable name) in mathematical expression + +# Fields +$(TYPEDFIELDS) +"""""" +struct MathIdent <: Math + id::String +end + +"""""" +$(TYPEDEF) + +A constant identified by name (usually something like `pi`, `e` or `true`) in +mathematical expression + +# Fields +$(TYPEDFIELDS) +"""""" +struct MathConst <: Math + id::String +end + +"""""" +$(TYPEDEF) + +A special value representing the current time of the simulation, with a special +name. + +# Fields +$(TYPEDFIELDS) +"""""" +struct MathTime <: Math + id::String +end + +"""""" +$(TYPEDEF) + +A special value representing the Avogadro constant (which is a special named +value in SBML). + +# Fields +$(TYPEDFIELDS) +"""""" +struct MathAvogadro <: Math + id::String +end + +"""""" +$(TYPEDEF) + +Function application (""call by name"", no tricks allowed) in mathematical expression + +# Fields +$(TYPEDFIELDS) +"""""" +struct MathApply <: Math + fn::String + args::Vector{Math} +end + +"""""" +$(TYPEDEF) + +Function definition (aka ""lambda"") in mathematical expression + +# Fields +$(TYPEDFIELDS) +"""""" +struct MathLambda <: Math + args::Vector{String} + body::Math +end + + + +"""""" +$(TYPEDEF) + +Representation of a SBML CVTerm, usually carrying Model or Biological +qualifier, a list of resources, and possibly nested CV terms. + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct CVTerm <: SBMLObject + biological_qualifier::Maybe{Symbol} = nothing + model_qualifier::Maybe{Symbol} = nothing + resource_uris::Vector{String} = [] + nested_cvterms::Vector{CVTerm} = [] +end + +"""""" +$(TYPEDEF) + +Representation of SBML Parameter structure, holding a value annotated with +units and constantness information. + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct Parameter <: SBMLObject + name::Maybe{String} = nothing + value::Maybe{Float64} = nothing + units::Maybe{String} = nothing + constant::Maybe{Bool} = nothing + metaid::Maybe{String} = nothing + notes::Maybe{String} = nothing + annotation::Maybe{String} = nothing + sbo::Maybe{String} = nothing + cv_terms::Vector{CVTerm} = [] +end + +"""""" +$(TYPEDEF) + +SBML Compartment with sizing information. + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct Compartment <: SBMLObject + name::Maybe{String} = nothing + constant::Maybe{Bool} = nothing + spatial_dimensions::Maybe{Int} = nothing + size::Maybe{Float64} = nothing + units::Maybe{String} = nothing + metaid::Maybe{String} = nothing + notes::Maybe{String} = nothing + annotation::Maybe{String} = nothing + sbo::Maybe{String} = nothing + cv_terms::Vector{CVTerm} = [] +end + +"""""" +$(TYPEDEF) + +SBML SpeciesReference. + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct SpeciesReference <: SBMLObject + id::Maybe{String} = nothing + species::String + stoichiometry::Maybe{Float64} = nothing + constant::Maybe{Bool} = nothing +end + +"""""" +$(TYPEDEF) + +Reaction with stoichiometry that assigns reactants and products their relative +consumption/production rates, lower/upper bounds (in tuples `lb` and `ub`, with +unit names), and objective coefficient (`oc`). Also may contains `notes` and +`annotation`. + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct Reaction <: SBMLObject + name::Maybe{String} = nothing + reactants::Vector{SpeciesReference} = [] + products::Vector{SpeciesReference} = [] + kinetic_parameters::Dict{String,Parameter} = Dict() + lower_bound::Maybe{String} = nothing + upper_bound::Maybe{String} = nothing + gene_product_association::Maybe{GeneProductAssociation} = nothing + kinetic_math::Maybe{Math} = nothing + reversible::Bool + metaid::Maybe{String} = nothing + notes::Maybe{String} = nothing + annotation::Maybe{String} = nothing + sbo::Maybe{String} = nothing + cv_terms::Vector{CVTerm} = [] +end + +"""""" +$(TYPEDEF) + +Abstract type representing SBML rules. +"""""" +abstract type Rule <: SBMLObject end + +"""""" +$(TYPEDEF) + +SBML algebraic rule. + +# Fields +$(TYPEDFIELDS) +"""""" +struct AlgebraicRule <: Rule + math::Math +end + +"""""" +$(TYPEDEF) + +SBML assignment rule. + +# Fields +$(TYPEDFIELDS) +"""""" +struct AssignmentRule <: Rule + variable::String + math::Math +end + +"""""" +$(TYPEDEF) + +SBML rate rule. + +# Fields +$(TYPEDFIELDS) +"""""" +struct RateRule <: Rule + variable::String + math::Math +end + +"""""" +$(TYPEDEF) + +SBML constraint. + +# Fields +$(TYPEDFIELDS) +"""""" +struct Constraint <: SBMLObject + math::Math + message::String +end + +"""""" +$(TYPEDEF) + +Species metadata -- contains a human-readable `name`, a `compartment` +identifier, `formula`, `charge`, and additional `notes` and `annotation`. + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct Species <: SBMLObject + name::Maybe{String} = nothing + compartment::String + boundary_condition::Maybe{Bool} = nothing + formula::Maybe{String} = nothing + charge::Maybe{Int} = nothing + initial_amount::Maybe{Float64} = nothing + initial_concentration::Maybe{Float64} = nothing + substance_units::Maybe{String} = nothing + conversion_factor::Maybe{String} = nothing + only_substance_units::Maybe{Bool} = nothing + constant::Maybe{Bool} = nothing + metaid::Maybe{String} = nothing + notes::Maybe{String} = nothing + annotation::Maybe{String} = nothing + sbo::Maybe{String} = nothing + cv_terms::Vector{CVTerm} = [] +end + +"""""" +$(TYPEDEF) + +Gene product metadata. + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct GeneProduct <: SBMLObject + label::String + name::Maybe{String} = nothing + metaid::Maybe{String} = nothing + notes::Maybe{String} = nothing + annotation::Maybe{String} = nothing + sbo::Maybe{String} = nothing + cv_terms::Vector{CVTerm} = [] +end + +"""""" +$(TYPEDEF) + +Custom function definition. + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct FunctionDefinition <: SBMLObject + name::Maybe{String} = nothing + metaid::Maybe{String} = nothing + body::Maybe{Math} = nothing + notes::Maybe{String} = nothing + annotation::Maybe{String} = nothing + sbo::Maybe{String} = nothing + cv_terms::Vector{CVTerm} = [] +end + +"""""" +$(TYPEDEF) + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct EventAssignment <: SBMLObject + variable::String + math::Maybe{Math} = nothing +end + +"""""" +$(TYPEDEF) + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct Trigger <: SBMLObject + persistent::Bool + initial_value::Bool + math::Maybe{Math} = nothing +end + +"""""" +$(TYPEDEF) + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct Objective <: SBMLObject + type::String + flux_objectives::Dict{String,Float64} = Dict() +end + +"""""" +$(TYPEDEF) + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct Event <: SBMLObject + use_values_from_trigger_time::Bool + name::Maybe{String} = nothing + trigger::Maybe{Trigger} = nothing + event_assignments::Maybe{Vector{EventAssignment}} = nothing +end + +"""""" +$(TYPEDEF) + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct Member <: SBMLObject + id::Maybe{String} = nothing + metaid::Maybe{String} = nothing + name::Maybe{String} = nothing + id_ref::Maybe{String} = nothing + metaid_ref::Maybe{String} = nothing + notes::Maybe{String} = nothing + annotation::Maybe{String} = nothing + sbo::Maybe{String} = nothing + cv_terms::Vector{CVTerm} = [] +end + +"""""" +$(TYPEDEF) + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct Group <: SBMLObject + metaid::Maybe{String} = nothing + kind::Maybe{String} = nothing + name::Maybe{String} = nothing + members::Vector{Member} = [] + notes::Maybe{String} = nothing + annotation::Maybe{String} = nothing + sbo::Maybe{String} = nothing + cv_terms::Vector{CVTerm} = [] +end + +"""""" +$(TYPEDEF) + +Julia representation of SBML Model structure, with the reactions, species, +units, compartments, and many other things. + +Where available, all objects are contained in dictionaries indexed by SBML +identifiers. + +# Fields +$(TYPEDFIELDS) +"""""" +Base.@kwdef struct Model <: SBMLObject + parameters::Dict{String,Parameter} = Dict() + units::Dict{String,UnitDefinition} = Dict() + compartments::Dict{String,Compartment} = Dict() + species::Dict{String,Species} = Dict() + initial_assignments::Dict{String,Math} = Dict() + rules::Vector{Rule} = Rule[] + constraints::Vector{Constraint} = Constraint[] + reactions::Dict{String,Reaction} = Dict() + objectives::Dict{String,Objective} = Dict() + active_objective::Maybe{String} = nothing + gene_products::Dict{String,GeneProduct} = Dict() + function_definitions::Dict{String,FunctionDefinition} = Dict() + events::Vector{Pair{Maybe{String},Event}} = Pair{Maybe{String},Event}[] + groups::Dict{String,Group} = Dict() + name::Maybe{String} = nothing + id::Maybe{String} = nothing + metaid::Maybe{String} = nothing + conversion_factor::Maybe{String} = nothing + area_units::Maybe{String} = nothing + extent_units::Maybe{String} = nothing + length_units::Maybe{String} = nothing + substance_units::Maybe{String} = nothing + time_units::Maybe{String} = nothing + volume_units::Maybe{String} = nothing + notes::Maybe{String} = nothing + annotation::Maybe{String} = nothing + sbo::Maybe{String} = nothing + cv_terms::Vector{CVTerm} = [] +end + +# Explicitly make all SBML structs ""broadcastable"" as scalars. +# (This must be updated if any of the structs are added or removed.) +# +# Use this to regenerate the Union contents moreless automatically: +# +# sed -ne 's/.*\.*/\1,/p' src/structs.jl +Base.Broadcast.broadcastable(x::SBMLObject) = Ref(x) +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","src/utils.jl",".jl","14621","453","# Enum OperationReturnValues_t defined in +# `src/sbml/common/operationReturnValues.h` +const OPERATION_RETURN_VALUES = Dict( + 0 => ""LIBSBML_OPERATION_SUCCESS"", + -1 => ""LIBSBML_INDEX_EXCEEDS_SIZE"", + -2 => ""LIBSBML_UNEXPECTED_ATTRIBUTE"", + -3 => ""LIBSBML_OPERATION_FAILED"", + -4 => ""LIBSBML_INVALID_ATTRIBUTE_VALUE"", + -5 => ""LIBSBML_INVALID_OBJECT"", + -6 => ""LIBSBML_DUPLICATE_OBJECT_ID"", + -7 => ""LIBSBML_LEVEL_MISMATCH"", + -8 => ""LIBSBML_VERSION_MISMATCH"", + -9 => ""LIBSBML_INVALID_XML_OPERATION"", + -10 => ""LIBSBML_NAMESPACES_MISMATCH"", + -11 => ""LIBSBML_DUPLICATE_ANNOTATION_NS"", + -12 => ""LIBSBML_ANNOTATION_NAME_NOT_FOUND"", + -13 => ""LIBSBML_ANNOTATION_NS_NOT_FOUND"", + -14 => ""LIBSBML_MISSING_METAID"", + -15 => ""LIBSBML_DEPRECATED_ATTRIBUTE"", + -16 => ""LIBSBML_USE_ID_ATTRIBUTE_FUNCTION"", + -20 => ""LIBSBML_PKG_VERSION_MISMATCH"", + -21 => ""LIBSBML_PKG_UNKNOWN"", + -22 => ""LIBSBML_PKG_UNKNOWN_VERSION"", + -23 => ""LIBSBML_PKG_DISABLED"", + -24 => ""LIBSBML_PKG_CONFLICTED_VERSION"", + -25 => ""LIBSBML_PKG_CONFLICT"", + -30 => ""LIBSBML_CONV_INVALID_TARGET_NAMESPACE"", + -31 => ""LIBSBML_CONV_PKG_CONVERSION_NOT_AVAILABLE"", + -32 => ""LIBSBML_CONV_INVALID_SRC_DOCUMENT"", + -33 => ""LIBSBML_CONV_CONVERSION_NOT_AVAILABLE"", + -34 => ""LIBSBML_CONV_PKG_CONSIDERED_UNKNOWN"", +) + +"""""" +$(TYPEDSIGNATURES) + +Extract the vector of species (aka metabolite) identifiers, vector of reaction +identifiers, and a sparse stoichiometry matrix (of type `SparseMatrixCSC` from +`SparseArrays` package) from an existing `SBML.Model`. Returns a 3-tuple with +these values. +"""""" +function stoichiometry_matrix(m::SBML.Model) + rows = collect(keys(m.species)) + cols = collect(keys(m.reactions)) + row_idx = Dict(k => i for (i, k) in enumerate(rows)) + col_idx = Dict(k => i for (i, k) in enumerate(cols)) + + nnz = 0 + for (_, r) in m.reactions + for _ in r.reactants + nnz += 1 + end + for _ in r.products + nnz += 1 + end + end + + SI = Int[] + RI = Int[] + SV = Float64[] + sizehint!(SI, nnz) + sizehint!(RI, nnz) + sizehint!(SV, nnz) + + for (rid, r) in m.reactions + ridx = col_idx[rid] + for sr in r.reactants + push!(SI, row_idx[sr.species]) + push!(RI, ridx) + push!(SV, isnothing(sr.stoichiometry) ? -1.0 : -sr.stoichiometry) + end + for sr in r.products + push!(SI, row_idx[sr.species]) + push!(RI, ridx) + push!(SV, isnothing(sr.stoichiometry) ? 1.0 : sr.stoichiometry) + end + end + return rows, cols, SparseArrays.sparse(SI, RI, SV, length(rows), length(cols)) +end + +"""""" +$(TYPEDSIGNATURES) + +Extract the vectors of lower and upper bounds of reaction rates from the model, +in the same order as `keys(m.reactions)`. All bounds are accompanied with the +unit of the corresponding value (the behavior is based on SBML specification). +Missing bounds are represented by negative/positive infinite values with +empty-string unit. +"""""" +function flux_bounds(m::SBML.Model)::NTuple{2,Vector{Tuple{Float64,String}}} + # Now this is tricky. There are multiple ways in SBML to specify a + # lower/upper bound. There are the ""global"" model bounds that we completely + # ignore now because no one uses them. In reaction, you can specify the + # bounds using ""LOWER_BOUND"" and ""UPPER_BOUND"" parameters, but also there + # may be a FBC plugged-in objective name that refers to the parameters. + # We extract these, using the units from the parameters. For unbounded + # reactions this gives -Inf or Inf as a default. + + function get_bound(rxn, fld, param, default) + param_name = mayfirst(getfield(rxn, fld), param) + param = + get(rxn.kinetic_parameters, param_name, get(m.parameters, param_name, default)) + return (param.value, mayfirst(param.units, """")) + end + + ( + get_bound.( + values(m.reactions), + :lower_bound, + ""LOWER_BOUND"", + Parameter(value = -Inf), + ), + get_bound.( + values(m.reactions), + :upper_bound, + ""UPPER_BOUND"", + Parameter(value = Inf), + ), + ) +end + +"""""" +$(TYPEDSIGNATURES) + +Get the specified FBC maximization objective from a model, as a vector in the +same order as `keys(m.reactions)`. +"""""" +function fbc_flux_objective(m::Model, oid::String) + + obj = m.objectives[oid] + coef = obj.type == ""maximize"" ? 1.0 : -1.0 + + [ + maylift(o -> o * coef, get(obj.flux_objectives, rid, 0.0)) for + rid in keys(m.reactions) + ] +end + +"""""" +$(TYPEDSIGNATURES) + +Get a kinetic-parameter-specified flux objective from the model, as a vector in +the same order as `keys(m.reactions)`. +"""""" +function kinetic_flux_objective(m::Model) + mayfirst.( + ( + maylift( + p -> p.value, + get(m.reactions[rid].kinetic_parameters, ""OBJECTIVE_COEFFICIENT"", nothing), + ) for rid in keys(m.reactions) + ), + 0.0, + ) +end + +"""""" +$(TYPEDSIGNATURES) + +Collect a single maximization objective from FBC, and from kinetic parameters +if FBC is not available. Fails if there is more than 1 FBC objective. + +Provided for simplicity and compatibility with earlier versions of SBML.jl. +"""""" +function flux_objective(m::Model)::Vector{Float64} + oids = keys(m.objectives) + if length(oids) == 1 + fbc_flux_objective(m, first(oids)) + elseif length(oids) == 0 + kinetic_flux_objective(m) + else + throw( + DomainError( + oids, + ""Ambiguous objective choice in flux_objective. Use fbc_flux_objective to select a single objective."", + ), + ) + end +end + +"""""" +$(TYPEDSIGNATURES) + +Helper to get the first non-`nothing` value from the arguments. +"""""" +function mayfirst(args...) + for i in args + if !isnothing(i) + return i + end + end + nothing +end + +"""""" +$(TYPEDSIGNATURES) + +Helper to lift a function to work on [`Maybe`](@ref), returning `nothing` +whenever there's a `nothing` in args. +"""""" +maylift(f, args::Maybe...) = any(isnothing, args) ? nothing : f(args...) + +"""""" +$(TYPEDSIGNATURES) + +A helper for easily getting out a defaulted compartment size. +"""""" +get_compartment_size(m::SBML.Model, compartment; default = nothing) = + let c = get(m.compartments, compartment, nothing) + mayfirst( + maylift(x -> x.size, c), + maylift(x -> x.spatial_dimensions == 0 ? 1.0 : nothing, c), + default, + ) + end + +"""""" +$(TYPEDSIGNATURES) + +Return initial amounts for each species as a generator of pairs +`species_name => initial_amount`; the amount is set to `nothing` if not +available. If `convert_concentrations` is true and there is information about +initial concentration available together with compartment size, the result is +computed from the species' initial concentration. + +The units of measurement are ignored in this computation, but one may +reconstruct them from `substance_units` field of [`Species`](@ref) structure. + +# Example +``` +# get the initial amounts as dictionary +Dict(SBML.initial_amounts(model, convert_concentrations = true)) + +# suppose the compartment size is 10.0 if unspecified +collect(SBML.initial_amounts( + model, + convert_concentrations = true, + compartment_size = comp -> SBML.get_compartment_size(model, comp, 10.0), +)) + +# remove the empty entries +Dict(k => v for (k,v) in SBML.initial_amounts(model) if !isnothing(v)) +``` +"""""" +initial_amounts( + m::SBML.Model; + convert_concentrations = false, + compartment_size = comp -> get_compartment_size(m, comp), +) = ( + k => mayfirst( + maylift(first, s.initial_amount), + if convert_concentrations + maylift( + (ic, s) -> ic * s, + s.initial_concentration, + compartment_size(s.compartment), + ) + end, + ) for (k, s) in m.species +) + +"""""" +$(TYPEDSIGNATURES) + +Return initial concentrations of the species in the model. Refer to work-alike +[`initial_amounts`](@ref) for details. +"""""" +initial_concentrations( + m::SBML.Model; + convert_amounts = false, + compartment_size = comp -> get_compartment_size(m, comp), +) = ( + k => mayfirst( + maylift(first, s.initial_concentration), + if convert_amounts + maylift((ia, s) -> ia / s, s.initial_amount, compartment_size(s.compartment)) + end, + ) for (k, s) in m.species +) + +"""""" + isfreein(id::String, expr::SBML.Math) + +Determine if `id` is used and not bound (aka. free) in `expr`. +"""""" +isfreein(id::String, expr::SBML.Math) = interpret_math( + expr, + map_apply = (x, rec) -> any(rec.(x.args)), + map_const = _ -> false, + map_ident = x -> x.id == id, + map_lambda = (x, rec) -> id in x.args ? false : rec(x.body), + map_time = _ -> false, + map_avogadro = _ -> false, + map_value = _ -> false, +) + +"""""" + isboundbyrules( + id::String, + m::SBML.Model + ) + +Determine if an identifier seems defined or used by any Rules in the model. +"""""" +seemsdefined(id::String, m::SBML.Model) = + any(r.variable == id for r in m.rules if r isa AssignmentRule) || + any(r.variable == id for r in m.rules if r isa RateRule) || + any(isfreein(id, r.math) for r in m.rules if r isa AlgebraicRule) + +"""""" +$(TYPEDSIGNATURES) + +Convert a SBML math `formula` to ""extensive"" kinetic laws, where the references +to species that are marked as not having only substance units are converted +from amounts to concentrations. Compartment sizes are referenced by compartment +identifiers. A compartment with no obvious definition available in the model +(as detected by [`seemsdefined`](@ref)) is either defaulted as size-less (i.e., +size is 1.0) in case it does not have spatial dimensions, or reported as +erroneous. +"""""" +extensive_kinetic_math(m::SBML.Model, formula::SBML.Math) = interpret_math( + formula, + map_apply = (x, rec) -> SBML.MathApply(x.fn, rec.(x.args)), + map_const = identity, + map_ident = (x::SBML.MathIdent) -> begin + haskey(m.species, x.id) || return x + sp = m.species[x.id] + sp.only_substance_units && return x + if isnothing(m.compartments[sp.compartment].size) && + !seemsdefined(sp.compartment, m) + if m.compartments[sp.compartment].spatial_dimensions == 0 + # If the comparment ID doesn't seem directly defined anywhere + # and it is a zero-dimensional unsized compartment, just avoid + # any sizing questions. + return x + else + # In case the compartment is expected to be defined, complain. + throw( + DomainError( + sp.compartment, + ""compartment size is insufficiently defined"", + ), + ) + end + else + # Now we are sure that the model either has the compartment with + # constant size, or the definition is easily reachable. So just use + # the compartment ID as a variable to compute the concentration (or + # area-centration etc, with different dimensionalities) by dividing + # it. + return SBML.MathApply(""/"", [x, SBML.MathIdent(sp.compartment)]) + end + end, + map_lambda = (x, _) -> error( + ErrorException(""converting lambdas to extensive kinetic math is not supported""), + ), + map_time = identity, + map_avogadro = identity, + map_value = identity, +) + +"""""" +$(TYPEDSIGNATURES) + +Show the error messages reported by SBML in the `doc` document and throw the +`error` if they are more than 1. + +`report_severities` switches the reporting of certain error types defined by +libsbml; you can choose from `[""Fatal"", ""Error"", ""Warning"", ""Informational""]`. + +`throw_severities` selects errors on which the functions throws the `error`. +"""""" +function get_error_messages( + doc::VPtr, + error::Exception, + report_severities, + throw_severities, +) + n_errs = ccall(sbml(:SBMLDocument_getNumErrors), Cuint, (VPtr,), doc) + do_throw = false + for i = 1:n_errs + err = ccall(sbml(:SBMLDocument_getError), VPtr, (VPtr, Cuint), doc, i - 1) + msg = string(strip(get_string(err, :XMLError_getMessage))) + sev = string(strip(get_string(err, :XMLError_getSeverityAsString))) + + # keywords from `libsbml/src/sbml/xml/XMLError.cpp` xmlSeverityStringTable: + if sev == ""Fatal"" + sev in report_severities && @error ""SBML reported fatal error: $(msg)"" + elseif sev == ""Error"" + sev in report_severities && @error ""SBML reported error: $(msg)"" + elseif sev == ""Warning"" + sev in report_severities && @warn ""SBML reported warning: $(msg)"" + elseif sev == ""Informational"" + sev in report_severities && @info ""SBML reported: $(msg)"" + end + + sev in throw_severities && (do_throw = true) + end + do_throw && throw(error) + nothing +end + +"""""" +$(TYPEDSIGNATURES) + +If success is a 0-valued `Integer` (a logical `false`), then call +[`get_error_messages`](@ref) to show the error messages reported by SBML in the +`doc` document and throw the `error` if they are more than 1. `success` is +typically the value returned by an SBML C function operating on `doc` which +returns a boolean flag to signal a successful operation. +"""""" +check_errors( + success::Integer, + doc::VPtr, + error::Exception, + report_severities = [""Fatal"", ""Error""], + throw_severities = [""Fatal"", ""Error""], +) = Bool(success) || get_error_messages(doc, error, report_severities, throw_severities) + +"""""" +$(TYPEDSIGNATURES) + +Pretty-printer for a SBML model. +Avoids flushing too much stuff to terminal by accident. +"""""" +function Base.show(io::IO, ::MIME""text/plain"", m::SBML.Model) + print( + io, + repr(typeof(m)), + "" with "", + length(m.reactions), + "" reactions, "", + length(m.species), + "" species, and "", + length(m.parameters), + "" parameters."", + ) +end + +"""""" +$(TYPEDSIGNATURES) + +Get the URL of a SBML test case file in the `sbmlteam/sbml-test-suite` GitHub +repository. The URL can be downloaded using `Downloads.download` or any other +function. Preferably, users should implement a download cache and verify the +consistency of the downloaded files before using them. +"""""" +test_suite_url(case::Int; ref = ""release"", level = 3, version = 2) = + let + case_str = lpad(string(case), 5, '0') + ""https://raw.githubusercontent.com/sbmlteam/sbml-test-suite/$ref/cases/semantic/$case_str/$case_str-sbml-l$(level)v$(version).xml"" + end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","src/writesbml.jl",".jl","26287","712","# Level/Version for the document +const WRITESBML_DEFAULT_LEVEL = 3 +const WRITESBML_DEFAULT_VERSION = 2 +# Level/Version/Package version for the packages +const WRITESBML_FBC_DEFAULT_LEVEL = 3 +const WRITESBML_FBC_DEFAULT_VERSION = 1 +const WRITESBML_FBC_DEFAULT_PKGVERSION = 2 +const WRITESBML_GROUPS_DEFAULT_LEVEL = 3 +const WRITESBML_GROUPS_DEFAULT_VERSION = 1 +const WRITESBML_GROUPS_DEFAULT_PKGVERSION = 1 + + +function create_gene_product_association( + gpr::GPARef, + ptr::VPtr, + ::Symbol, + ::Symbol, + add_ref::Symbol, +) + ref_ptr = ccall(sbml(add_ref), VPtr, (VPtr,), ptr) + set_string!(ref_ptr, :GeneProductRef_setGeneProduct, gpr.gene_product) + return ref_ptr +end + +function create_gene_product_association( + gpr::GPAOr, + ptr::VPtr, + add_or::Symbol, + ::Symbol, + ::Symbol, +) + or_ptr = ccall(sbml(add_or), VPtr, (VPtr,), ptr) + for term in gpr.terms + create_gene_product_association( + term, + or_ptr, + :FbcOr_createOr, + :FbcOr_createAnd, + :FbcOr_createGeneProductRef, + ) + end + return or_ptr +end + +function create_gene_product_association( + gpr::GPAAnd, + ptr::VPtr, + ::Symbol, + add_and::Symbol, + ::Symbol, +) + and_ptr = ccall(sbml(add_and), VPtr, (VPtr,), ptr) + for term in gpr.terms + create_gene_product_association( + term, + and_ptr, + :FbcAnd_createOr, + :FbcAnd_createAnd, + :FbcAnd_createGeneProductRef, + ) + end + return and_ptr +end + +function add_rule(model::VPtr, r::AlgebraicRule) + algebraicrule_ptr = ccall(sbml(:Model_createAlgebraicRule), VPtr, (VPtr,), model) + ccall( + sbml(:AlgebraicRule_setMath), + Cint, + (VPtr, VPtr), + algebraicrule_ptr, + get_astnode_ptr(r.math), + ) +end + +function add_rule(model::VPtr, r::Union{AssignmentRule,RateRule}) + rule_ptr = if r isa AssignmentRule + ccall(sbml(:Model_createAssignmentRule), VPtr, (VPtr,), model) + else + ccall(sbml(:Model_createRateRule), VPtr, (VPtr,), model) + end + set_string!(rule_ptr, :Rule_setVariable, r.variable) + ccall(sbml(:Rule_setMath), Cint, (VPtr, VPtr), rule_ptr, get_astnode_ptr(r.math)) +end + +function add_unit_definition(model::VPtr, id::String, units::UnitDefinition) + unit_definition = ccall(sbml(:Model_createUnitDefinition), VPtr, (VPtr,), model) + set_string!(unit_definition, :UnitDefinition_setId, id) + set_string!(unit_definition, :UnitDefinition_setName, units.name) + for unit in units.unit_parts + unit_ptr = ccall(sbml(:UnitDefinition_createUnit), VPtr, (VPtr,), unit_definition) + unit_kind = ccall(sbml(:UnitKind_forName), Cint, (Cstring,), unit.kind) + set_int!(unit_ptr, :Unit_setKind, unit_kind) + set_int!(unit_ptr, :Unit_setScale, unit.scale) + set_int!(unit_ptr, :Unit_setExponent, unit.exponent) + set_double!(unit_ptr, :Unit_setMultiplier, unit.multiplier) + end +end + +function set_parameter_ptr!(parameter_ptr::VPtr, id::String, parameter::Parameter)::VPtr + set_string!(parameter_ptr, :Parameter_setId, id) + set_string!(parameter_ptr, :Parameter_setName, parameter.name) + set_metaid!(parameter_ptr, parameter.metaid) + set_double!(parameter_ptr, :Parameter_setValue, parameter.value) + set_string!(parameter_ptr, :Parameter_setUnits, parameter.units) + add_cvterms!(parameter_ptr, parameter.cv_terms) + set_bool!(parameter_ptr, :Parameter_setConstant, parameter.constant) + set_annotation_string!(parameter_ptr, parameter.annotation) + set_notes_string!(parameter_ptr, parameter.notes) + set_sbo_term!(parameter_ptr, parameter.sbo) + return parameter_ptr +end + +function set_string!(ptr::VPtr, fn_sym::Symbol, x::Maybe{String}) + isnothing(x) || + ccall(sbml(fn_sym), Cint, (VPtr, Cstring), ptr, x) == 0 || + error(""$fn_sym failed for value `$x' !"") +end + +function set_int!(ptr::VPtr, fn_sym::Symbol, x::Maybe{<:Integer}) + isnothing(x) || + ccall(sbml(fn_sym), Cint, (VPtr, Cint), ptr, x) == 0 || + error(""$fn_sym failed for value $x !"") +end + +function set_uint!(ptr::VPtr, fn_sym::Symbol, x::Maybe{<:Integer}) + isnothing(x) || + ccall(sbml(fn_sym), Cint, (VPtr, Cuint), ptr, x) == 0 || + error(""$fn_sym failed for value $x !"") +end + +function set_bool!(ptr::VPtr, fn_sym::Symbol, x::Maybe{Bool}) + isnothing(x) || + ccall(sbml(fn_sym), Cint, (VPtr, Cint), ptr, x) == 0 || + error(""$fn_sym failed for value $x !"") +end + +function set_double!(ptr::VPtr, fn_sym::Symbol, x::Maybe{Float64}) + isnothing(x) || + ccall(sbml(fn_sym), Cint, (VPtr, Cdouble), ptr, x) == 0 || + error(""$fn_sym failed for value $x !"") +end + +set_annotation_string!(ptr, x) = set_string!(ptr, :SBase_setAnnotationString, x) +set_notes_string!(ptr, x) = set_string!(ptr, :SBase_setNotesString, x) +set_metaid!(ptr, x) = set_string!(ptr, :SBase_setMetaId, x) +set_sbo_term!(ptr, x) = set_string!(ptr, :SBase_setSBOTermID, x) + +add_cvterms!(ptr, x) = add_cvterm!.(Ref(ptr), x) + +function add_cvterm!(ptr::VPtr, x::CVTerm, add = :SBase_addCVTerm) + qt = !isnothing(x.biological_qualifier) ? 1 : !isnothing(x.model_qualifier) ? 0 : 2 + # unfortunately the API is missing `createCVTerm` or a similar method. + cvt = ccall(sbml(:CVTerm_createWithQualifierType), VPtr, (Cint,), qt) + + isnothing(x.biological_qualifier) || + ccall( + sbml(:CVTerm_setBiologicalQualifierType), + Cint, + (VPtr, Cint), + cvt, + ccall( + sbml(:BiolQualifierType_fromString), + Cint, + (Cstring,), + x.biological_qualifier, + ), + ) == 0 || + error(""setting biological qualifier failed!"") + isnothing(x.model_qualifier) || + ccall( + sbml(:CVTerm_setModelQualifierType), + Cint, + (VPtr, Cint), + cvt, + ccall( + sbml(:ModelQualifierType_fromString), + Cint, + (Cstring,), + x.model_qualifier, + ), + ) == 0 || + error(""setting model qualifier failed!"") + + for res in x.resource_uris + set_string!(cvt, :CVTerm_addResource, res) + end + + for nested in x.nested_cvterms + add_cvterm!(cvt, nested, :CVTerm_addNestedCVTerm) + end + + ccall(sbml(add), Cint, (VPtr, VPtr), ptr, cvt) == 0 || error(""Adding a CVTerm failed!"") + ccall(sbml(:CVTerm_free), Cvoid, (VPtr,), cvt) +end + +## Write the model + +function model_to_sbml!(doc::VPtr, mdl::Model)::VPtr + # Create the model pointer + model = ccall(sbml(:SBMLDocument_createModel), VPtr, (VPtr,), doc) + + # Init the pluings + fbc_plugin = ccall(sbml(:SBase_getPlugin), VPtr, (VPtr, Cstring), model, ""fbc"") + groups_plugin = ccall(sbml(:SBase_getPlugin), VPtr, (VPtr, Cstring), model, ""groups"") + + # Set ids and name + set_string!(model, :Model_setId, mdl.id) + set_metaid!(model, mdl.metaid) + set_string!(model, :Model_setName, mdl.name) + + # Add parameters + for (id, parameter) in mdl.parameters + parameter_ptr = ccall(sbml(:Model_createParameter), VPtr, (VPtr,), model) + set_parameter_ptr!(parameter_ptr, id, parameter) + end + + # Add units + for (name, units) in mdl.units + add_unit_definition(model, name, units) + end + + # Add compartments + for (id, compartment) in mdl.compartments + compartment_ptr = ccall(sbml(:Model_createCompartment), VPtr, (VPtr,), model) + set_string!(compartment_ptr, :Compartment_setId, id) + set_string!(compartment_ptr, :Compartment_setName, compartment.name) + set_metaid!(compartment_ptr, compartment.metaid) + set_bool!(compartment_ptr, :Compartment_setConstant, compartment.constant) + set_uint!( + compartment_ptr, + :Compartment_setSpatialDimensions, + compartment.spatial_dimensions, + ) + set_double!(compartment_ptr, :Compartment_setSize, compartment.size) + set_string!(compartment_ptr, :Compartment_setUnits, compartment.units) + add_cvterms!(compartment_ptr, compartment.cv_terms) + set_notes_string!(compartment_ptr, compartment.notes) + set_annotation_string!(compartment_ptr, compartment.annotation) + set_sbo_term!(compartment_ptr, compartment.sbo) + end + + # Add gene products + fbc_plugin == C_NULL || + isempty(mdl.gene_products) || + set_bool!(fbc_plugin, :FbcModelPlugin_setStrict, true) + for (id, gene_product) in mdl.gene_products + geneproduct_ptr = + ccall(sbml(:FbcModelPlugin_createGeneProduct), VPtr, (VPtr,), fbc_plugin) + set_string!(geneproduct_ptr, :GeneProduct_setId, id) + set_string!(geneproduct_ptr, :GeneProduct_setLabel, gene_product.label) + set_string!(geneproduct_ptr, :GeneProduct_setName, gene_product.name) + set_metaid!(geneproduct_ptr, gene_product.metaid) + add_cvterms!(geneproduct_ptr, gene_product.cv_terms) + set_notes_string!(geneproduct_ptr, gene_product.notes) + set_annotation_string!(geneproduct_ptr, gene_product.annotation) + set_sbo_term!(geneproduct_ptr, gene_product.sbo) + end + + # Add initial assignments + for (symbol, math) in mdl.initial_assignments + initialassignment_ptr = + ccall(sbml(:Model_createInitialAssignment), VPtr, (VPtr,), model) + set_string!(initialassignment_ptr, :InitialAssignment_setSymbol, symbol) + ccall( + sbml(:InitialAssignment_setMath), + Cint, + (VPtr, VPtr), + initialassignment_ptr, + get_astnode_ptr(math), + ) == 0 || error(""setting initial assignment math failed!"") + end + + # Add constraints + for constraint in mdl.constraints + constraint_ptr = ccall(sbml(:Model_createConstraint), VPtr, (VPtr,), model) + # Note: this probably incorrect because our `Constraint` lost the XML namespace of the + # message, also we don't have an easy way to test this because no test file uses constraints. + message = ccall(sbml(:XMLNode_createTextNode), VPtr, (Cstring,), constraint.message) + set_string!(constraint_ptr, :Constraint_setMessage, message) + ccall( + sbml(:Constraint_setMath), + Cint, + (VPtr, VPtr), + constraint_ptr, + get_astnode_ptr(constraint.math), + ) == 0 || error(""setting constraint math failed!"") + end + + # Add reactions + for (id, reaction) in mdl.reactions + reaction_ptr = ccall(sbml(:Model_createReaction), VPtr, (VPtr,), model) + reaction_fbc_ptr = + ccall(sbml(:SBase_getPlugin), VPtr, (VPtr, Cstring), reaction_ptr, ""fbc"") + set_string!(reaction_ptr, :Reaction_setId, id) + set_bool!(reaction_ptr, :Reaction_setReversible, reaction.reversible) + set_string!(reaction_ptr, :Reaction_setName, reaction.name) + for (sr_create, srs) in [ + :Reaction_createReactant => reaction.reactants, + :Reaction_createProduct => reaction.products, + ] + for sr in srs + reactant_ptr = ccall(sbml(sr_create), VPtr, (VPtr,), reaction_ptr) + set_string!(reactant_ptr, :SpeciesReference_setSpecies, sr.species) + set_string!(reactant_ptr, :SpeciesReference_setId, sr.id) + set_double!( + reactant_ptr, + :SpeciesReference_setStoichiometry, + sr.stoichiometry, + ) + set_bool!(reactant_ptr, :SpeciesReference_setConstant, sr.constant) + end + end + if !isempty(reaction.kinetic_parameters) || !isnothing(reaction.kinetic_math) + kinetic_law_ptr = + ccall(sbml(:Reaction_createKineticLaw), VPtr, (VPtr,), reaction_ptr) + for (id, parameter) in reaction.kinetic_parameters + parameter_ptr = + ccall(sbml(:KineticLaw_createParameter), VPtr, (VPtr,), kinetic_law_ptr) + set_parameter_ptr!(parameter_ptr, id, parameter) + end + isnothing(reaction.kinetic_math) || + ccall( + sbml(:KineticLaw_setMath), + Cint, + (VPtr, VPtr), + kinetic_law_ptr, + get_astnode_ptr(reaction.kinetic_math), + ) == 0 || + error(""setting kinetic law math failed!"") + end + if !isnothing(reaction.lower_bound) || !isnothing(reaction.upper_bound) + set_string!( + reaction_fbc_ptr, + :FbcReactionPlugin_setLowerFluxBound, + reaction.lower_bound, + ) + set_string!( + reaction_fbc_ptr, + :FbcReactionPlugin_setUpperFluxBound, + reaction.upper_bound, + ) + end + if !isnothing(reaction.gene_product_association) + reaction_gpa_ptr = ccall( + sbml(:FbcReactionPlugin_createGeneProductAssociation), + VPtr, + (VPtr,), + reaction_fbc_ptr, + ) + + # the dispatch is a bit complicated in this case, we need to + # remember the type of the structure that we're working on (that + # sets the part of the symbol before `_`), and the type of the + # association we're creating sets the part behind `_`. So let's + # just tabulate and lag it through the recursion. + + create_gene_product_association( + reaction.gene_product_association, + reaction_gpa_ptr, + :GeneProductAssociation_createOr, + :GeneProductAssociation_createAnd, + :GeneProductAssociation_createGeneProductRef, + ) + end + set_metaid!(reaction_ptr, reaction.metaid) + add_cvterms!(reaction_ptr, reaction.cv_terms) + set_notes_string!(reaction_ptr, reaction.notes) + set_annotation_string!(reaction_ptr, reaction.annotation) + set_sbo_term!(reaction_ptr, reaction.sbo) + end + + # Add objectives + fbc_plugin == C_NULL || + isempty(mdl.objectives) || + set_bool!(fbc_plugin, :FbcModelPlugin_setStrict, true) + for (id, objective) in mdl.objectives + objective_ptr = + ccall(sbml(:FbcModelPlugin_createObjective), VPtr, (VPtr,), fbc_plugin) + set_string!(objective_ptr, :Objective_setId, id) + set_string!(objective_ptr, :Objective_setType, objective.type) + for (reaction, coefficient) in objective.flux_objectives + fluxobjective_ptr = + ccall(sbml(:Objective_createFluxObjective), VPtr, (VPtr,), objective_ptr) + set_string!(fluxobjective_ptr, :FluxObjective_setReaction, reaction) + set_double!(fluxobjective_ptr, :FluxObjective_setCoefficient, coefficient) + end + end + + fbc_plugin == C_NULL || + set_string!(fbc_plugin, :FbcModelPlugin_setActiveObjectiveId, mdl.active_objective) + + # Add species + fbc_plugin == C_NULL || + isempty(mdl.species) || + set_bool!(fbc_plugin, :FbcModelPlugin_setStrict, true) + for (id, species) in mdl.species + species_ptr = ccall(sbml(:Model_createSpecies), VPtr, (VPtr,), model) + set_string!(species_ptr, :Species_setId, id) + set_metaid!(species_ptr, species.metaid) + add_cvterms!(species_ptr, species.cv_terms) + set_string!(species_ptr, :Species_setName, species.name) + set_string!(species_ptr, :Species_setCompartment, species.compartment) + set_bool!(species_ptr, :Species_setBoundaryCondition, species.boundary_condition) + species_fbc_ptr = + ccall(sbml(:SBase_getPlugin), VPtr, (VPtr, Cstring), species_ptr, ""fbc"") + if species_fbc_ptr != C_NULL + set_string!( + species_fbc_ptr, + :FbcSpeciesPlugin_setChemicalFormula, + species.formula, + ) + set_int!(species_fbc_ptr, :FbcSpeciesPlugin_setCharge, species.charge) + end + set_double!(species_ptr, :Species_setInitialAmount, species.initial_amount) + set_double!( + species_ptr, + :Species_setInitialConcentration, + species.initial_concentration, + ) + set_string!(species_ptr, :Species_setSubstanceUnits, species.substance_units) + set_string!(species_ptr, :Species_setConversionFactor, species.conversion_factor) + set_bool!( + species_ptr, + :Species_setHasOnlySubstanceUnits, + species.only_substance_units, + ) + set_bool!(species_ptr, :Species_setConstant, species.constant) + set_notes_string!(species_ptr, species.notes) + set_annotation_string!(species_ptr, species.annotation) + set_sbo_term!(species_ptr, species.sbo) + end + + # Add function definitions + for (id, func_def) in mdl.function_definitions + functiondefinition_ptr = + ccall(sbml(:Model_createFunctionDefinition), VPtr, (VPtr,), model) + set_string!(functiondefinition_ptr, :FunctionDefinition_setId, id) + set_metaid!(functiondefinition_ptr, func_def.metaid) + add_cvterms!(functiondefinition_ptr, func_def.cv_terms) + set_string!(functiondefinition_ptr, :FunctionDefinition_setName, func_def.name) + isnothing(func_def.body) || + ccall( + sbml(:FunctionDefinition_setMath), + Cint, + (VPtr, VPtr), + functiondefinition_ptr, + get_astnode_ptr(func_def.body), + ) == 0 || + error(""setting function definition math failed!"") + set_notes_string!(functiondefinition_ptr, func_def.notes) + set_annotation_string!(functiondefinition_ptr, func_def.annotation) + set_sbo_term!(functiondefinition_ptr, func_def.sbo) + end + + # Add rules + for rule in mdl.rules + add_rule(model, rule) + end + + # Add events + for (id, event) in mdl.events + event_ptr = ccall(sbml(:Model_createEvent), VPtr, (VPtr,), model) + isnothing(id) || set_string!(event_ptr, :Event_setId, id) + set_bool!( + event_ptr, + :Event_setUseValuesFromTriggerTime, + event.use_values_from_trigger_time, + ) + set_string!(event_ptr, :Event_setName, event.name) + if !isnothing(event.trigger) + trigger_ptr = ccall(sbml(:Event_createTrigger), VPtr, (VPtr,), event_ptr) + set_bool!(trigger_ptr, :Trigger_setPersistent, event.trigger.persistent) + set_bool!(trigger_ptr, :Trigger_setInitialValue, event.trigger.initial_value) + isnothing(event.trigger.math) || + ccall( + sbml(:Trigger_setMath), + Cint, + (VPtr, VPtr), + trigger_ptr, + get_astnode_ptr(event.trigger.math), + ) == 0 || + error(""setting trigger math failed!"") + end + if !isnothing(event.event_assignments) + for event_assignment in event.event_assignments + event_assignment_ptr = + ccall(sbml(:Event_createEventAssignment), VPtr, (VPtr,), event_ptr) + set_string!( + event_assignment_ptr, + :EventAssignment_setVariable, + event_assignment.variable, + ) + isnothing(event_assignment.math) || + ccall( + sbml(:EventAssignment_setMath), + Cint, + (VPtr, VPtr), + event_assignment_ptr, + get_astnode_ptr(event_assignment.math), + ) == 0 || + error(""setting event assignment math failed!"") + end + end + end + + # Add groups + for (id, group) in mdl.groups + group_ptr = + ccall(sbml(:GroupsModelPlugin_createGroup), VPtr, (VPtr,), groups_plugin) + set_string!(group_ptr, :Group_setId, id) + set_metaid!(group_ptr, group.metaid) + set_string!(group_ptr, :Group_setKindAsString, group.kind) + set_string!(group_ptr, :Group_setName, group.name) + for mem in group.members + mem_ptr = ccall(sbml(:Group_createMember), VPtr, (VPtr,), group_ptr) + set_string!(mem_ptr, :Member_setId, mem.id) + set_metaid!(mem_ptr, mem.metaid) + set_string!(mem_ptr, :Member_setName, mem.name) + set_string!(mem_ptr, :Member_setIdRef, mem.id_ref) + set_string!(mem_ptr, :Member_setMetaIdRef, mem.metaid_ref) + set_notes_string!(mem_ptr, mem.notes) + set_annotation_string!(mem_ptr, mem.annotation) + set_sbo_term!(mem_ptr, mem.sbo) + add_cvterms!(mem_ptr, mem.cv_terms) + end + set_notes_string!(group_ptr, group.notes) + set_annotation_string!(group_ptr, group.annotation) + set_sbo_term!(group_ptr, group.sbo) + add_cvterms!(group_ptr, group.cv_terms) + end + + # Add conversion factor + set_string!(model, :Model_setConversionFactor, mdl.conversion_factor) + + # Add other units attributes + set_string!(model, :Model_setAreaUnits, mdl.area_units) + set_string!(model, :Model_setExtentUnits, mdl.extent_units) + set_string!(model, :Model_setLengthUnits, mdl.length_units) + set_string!(model, :Model_setSubstanceUnits, mdl.substance_units) + set_string!(model, :Model_setTimeUnits, mdl.time_units) + set_string!(model, :Model_setVolumeUnits, mdl.volume_units) + + # Notes and annotations + add_cvterms!(model, mdl.cv_terms) + set_notes_string!(model, mdl.notes) + set_annotation_string!(model, mdl.annotation) + set_sbo_term!(model, mdl.sbo) + + # We can finally return the model + return model +end + +function _create_doc(mdl::Model)::VPtr + # Create a namespaces object + sbmlns = ccall( + sbml(:SBMLNamespaces_create), + VPtr, + (Cuint, Cuint), + WRITESBML_DEFAULT_LEVEL, + WRITESBML_DEFAULT_VERSION, + ) + + fbc_required = + !isempty(mdl.objectives) || + !isempty(mdl.gene_products) || + any(!isnothing(sp.formula) for (_, sp) in mdl.species) || + any(!isnothing(sp.charge) for (_, sp) in mdl.species) + + groups_required = !isempty(mdl.groups) + + # Test if we have FBC and add it if required + if fbc_required + # we have FBC features, let's add FBC. + fbc_ext = ccall(sbml(:SBMLExtensionRegistry_getExtension), VPtr, (Cstring,), ""fbc"") + fbc_ns = ccall(sbml(:XMLNamespaces_create), VPtr, ()) + # create the sbml namespaces object with fbc + fbc_uri = ccall( + sbml(:SBMLExtension_getURI), + Cstring, + (VPtr, Cuint, Cuint, Cuint), + fbc_ext, + WRITESBML_FBC_DEFAULT_LEVEL, + WRITESBML_FBC_DEFAULT_VERSION, + WRITESBML_FBC_DEFAULT_PKGVERSION, + ) + ccall( + sbml(:XMLNamespaces_add), + Cint, + (VPtr, Cstring, Cstring), + fbc_ns, + fbc_uri, + ""fbc"", + ) + ccall( + sbml(:SBMLNamespaces_addPackageNamespaces), + Cint, + (VPtr, VPtr), + sbmlns, + fbc_ns, + ) + end + + # Again, test if we have groups and add it (this might deserve its own function now) + if groups_required + groups_ext = + ccall(sbml(:SBMLExtensionRegistry_getExtension), VPtr, (Cstring,), ""groups"") + groups_ns = ccall(sbml(:XMLNamespaces_create), VPtr, ()) + # create the sbml namespaces object with groups + groups_uri = ccall( + sbml(:SBMLExtension_getURI), + Cstring, + (VPtr, Cuint, Cuint, Cuint), + groups_ext, + WRITESBML_GROUPS_DEFAULT_LEVEL, + WRITESBML_GROUPS_DEFAULT_VERSION, + WRITESBML_GROUPS_DEFAULT_PKGVERSION, + ) + ccall( + sbml(:XMLNamespaces_add), + Cint, + (VPtr, Cstring, Cstring), + groups_ns, + groups_uri, + ""groups"", + ) + ccall( + sbml(:SBMLNamespaces_addPackageNamespaces), + Cint, + (VPtr, VPtr), + sbmlns, + groups_ns, + ) + end + + # Now, create document with the required SBML namespaces + doc = ccall(sbml(:SBMLDocument_createWithSBMLNamespaces), VPtr, (VPtr,), sbmlns) + + # Add notes about required packages + fbc_required && ccall( + sbml(:SBMLDocument_setPackageRequired), + Cint, + (VPtr, Cstring, Cint), + doc, + ""fbc"", + false, + ) + groups_required && ccall( + sbml(:SBMLDocument_setPackageRequired), + Cint, + (VPtr, Cstring, Cint), + doc, + ""groups"", + false, + ) + return doc +end + +"""""" +$(TYPEDSIGNATURES) + +Write the SBML structure in `mdl` to a file `filename`. + +To write the XML to a string, use `writeSBML(mdl::Model)`. +"""""" +function writeSBML(mdl::Model, filename::String) + doc = _create_doc(mdl) + model = try + model_to_sbml!(doc, mdl) + res = ccall(sbml(:writeSBML), Cint, (VPtr, Cstring), doc, filename) + res == 1 || error(""Writing the SBML file \""$(filename)\"" failed"") + finally + ccall(sbml(:SBMLDocument_free), Cvoid, (VPtr,), doc) + end + return nothing +end + +"""""" +$(TYPEDSIGNATURES) + +Convert the SBML structure in `mdl` into XML and return it in a string. + +To write directly to a file, use `writeSBML(mdl::Model, filename::String)`. +"""""" +function writeSBML(mdl::Model)::String + doc = _create_doc(mdl) + str = try + model_to_sbml!(doc, mdl) + unsafe_string(ccall(sbml(:writeSBMLToString), Cstring, (VPtr,), doc)) + finally + ccall(sbml(:SBMLDocument_free), Cvoid, (VPtr,), doc) + end + return str +end + +"""""" +$(TYPEDSIGNATURES) + +Shortcut for writing a SBML [`Model`](@ref) created by function `f`, suitable +for the `do` block syntax. + +# Example +``` +writeSBML(""my_model.xml"") do + compartments = ... + species = ... + Model(; name = ""my model"", compartments, species) +end +``` +"""""" +writeSBML(f::Function, args...; kwargs...) = writeSBML(f(), args...; kwargs...) +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","src/types.jl",".jl","264","16"," +"""""" + Maybe{X} + +Type shortcut for ""`X` or nothing"" or ""nullable `X`"" in javaspeak. Name +got inspired by our functional friends. +"""""" +const Maybe{X} = Union{Nothing,X} + +"""""" + VPtr + +A convenience wrapper for ""any"" (C `void`) pointer. +"""""" +const VPtr = Ptr{Cvoid} +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","src/interpret.jl",".jl","4349","148"," +# some helper functions for interpreting SBML math + +function sbmlPiecewise(args...) + if length(args) == 1 + args[1] + elseif length(args) >= 3 + IfElse.ifelse(args[2], args[1], sbmlPiecewise(args[3:end]...)) + else + throw(DomainError(args, ""malformed piecewise SBML function"")) + end +end + +sbmlNeq(a, b) = !isequal(a, b) +function sbmlRelational(op) + _iter(x, y) = op(x, y) + _iter(x, y, args...) = IfElse.ifelse(op(x, y), _iter(y, args...), op(x, y)) + _iter +end + +sbmlLog(x) = sbmlLog(10, x) +sbmlLog(base, x) = log(base, x) + +sbmlPower(x::Integer, y::Integer) = x^float(y) +sbmlPower(x, y) = x^y +sbmlRoot(x) = sqrt(x) +sbmlRoot(power, x) = x^(1 / power) + +sbmlRateOf(x) = throw(ErrorException(""`rateOf' function mapping not defined"")) + +"""""" +$(TYPEDSIGNATURES) + +Default mapping of SBML function names to Julia functions, represented as a +dictionary from Strings (SBML names) to functions. + +The default mapping only contains the basic SBML functions that are +unambiguously represented in Julia; it is supposed to be extended by the user +if more functions need to be supported. +"""""" +const default_function_mapping = Dict{String,Any}( + ""*"" => *, + ""+"" => +, + ""-"" => -, + ""/"" => /, + ""abs"" => abs, + ""and"" => &, + ""arccos"" => acos, + ""arccosh"" => acosh, + ""arccot"" => acot, + ""arccoth"" => acoth, + ""arccsc"" => acsc, + ""arccsch"" => acsch, + ""arcsec"" => asec, + ""arcsech"" => asech, + ""arcsin"" => asin, + ""arcsinh"" => asinh, + ""arctan"" => atan, + ""arctanh"" => atanh, + ""ceiling"" => ceil, + ""cos"" => cos, + ""cosh"" => cosh, + ""cot"" => cot, + ""coth"" => coth, + ""csc"" => csc, + ""csch"" => csch, + ""eq"" => sbmlRelational(isequal), + ""exp"" => exp, + ""factorial"" => factorial, + ""floor"" => floor, + ""geq"" => sbmlRelational(>=), + ""gt"" => sbmlRelational(>), + ""leq"" => sbmlRelational(<=), + ""ln"" => log, + ""log"" => sbmlLog, + ""lt"" => sbmlRelational(<), + ""neq"" => sbmlRelational(sbmlNeq), + ""not"" => !, + ""or"" => |, + ""piecewise"" => sbmlPiecewise, + ""power"" => sbmlPower, + ""rateOf"" => sbmlRateOf, + ""root"" => sbmlRoot, + ""sech"" => sech, + ""sec"" => sec, + ""sinh"" => sinh, + ""sin"" => sin, + ""tanh"" => tanh, + ""tan"" => tan, + ""xor"" => xor, +) + +allowed_sym(x, allowed_funs) = + haskey(allowed_funs, x) ? allowed_funs[x] : + throw(DomainError(x, ""Unknown SBML function"")) + +"""""" +$(TYPEDSIGNATURES) + +A dictionary of default constants filled in place of SBML Math constants in the +function conversion. +"""""" +const default_constants = Dict{String,Any}( + ""true"" => true, + ""false"" => false, + ""pi"" => pi, + ""e"" => exp(1), + ""exponentiale"" => exp(1), + ""avogadro"" => 6.02214076e23, +) + +"""""" +$(TYPEDSIGNATURES) + +Recursively interpret SBML.[`Math`](@ref) type. This can be used to relatively +easily traverse and evaluate the SBML math, or translate it into any custom +representation, such as `Expr` or the `Num` of Symbolics.jl (see the SBML test +suite for examples). + +By default, the function can convert SBML constants, values and function +applications, but identifiers, time values and lambdas are not mapped and throw +an error. Similarly SBML function `rateOf` is undefined, users must to supply +their own definition of `rateOf` that uses the correct derivative. +"""""" +function interpret_math( + x::SBML.Math; + map_apply = (x::SBML.MathApply, interpret::Function) -> + SBML.default_function_mapping[x.fn](interpret.(x.args)...), + map_const = (x::SBML.MathConst) -> default_constants[x.id], + map_ident = (x::SBML.MathIdent) -> + throw(ErrorException(""identifier mapping not defined"")), + map_lambda = (x::SBML.MathLambda, interpret::Function) -> + throw(ErrorException(""lambda function mapping not defined"")), + map_time = (x::SBML.MathTime) -> throw(ErrorException(""time mapping not defined"")), + map_avogadro = (x::SBML.MathAvogadro) -> map_ident(SBML.MathIdent(x.id)), + map_value = (x::SBML.MathVal) -> x.val, +) + interpret(x::SBML.MathApply) = map_apply(x, interpret) + interpret(x::SBML.MathConst) = map_const(x) + interpret(x::SBML.MathIdent) = map_ident(x) + interpret(x::SBML.MathLambda) = map_lambda(x, interpret) + interpret(x::SBML.MathTime) = map_time(x) + interpret(x::SBML.MathAvogadro) = map_avogadro(x) + interpret(x::SBML.MathVal) = map_value(x) + + interpret(x) +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","src/readsbml.jl",".jl","29481","816",""""""" +$(TYPEDSIGNATURES) + +C-call the SBML function `fn_sym` with a single parameter `x`, interpret the +result as a string and return it, or throw exception in case the pointer is +NULL. +"""""" +function get_string(x::VPtr, fn_sym::Symbol)::String + str = ccall(sbml(fn_sym), Cstring, (VPtr,), x) + if str != C_NULL + return unsafe_string(str) + else + throw(DomainError(x, ""Calling $fn_sym returned NULL, valid string expected."")) + end +end + +"""""" +$(TYPEDSIGNATURES) + +Like [`get_string`](@ref), but returns `nothing` instead of throwing an +exception. + +This is used to get notes and annotations and several other things (see +`get_notes`, `get_annotations`) +"""""" +function get_optional_string(x::VPtr, fn_sym::Symbol)::Maybe{String} + str = ccall(sbml(fn_sym), Cstring, (VPtr,), x) + if str != C_NULL + return unsafe_string(str) + else + return nothing + end +end + +"""""" +$(TYPEDSIGNATURES) + +Like [`get_string`](@ref), but returns `nothing` instead of throwing an +exception. Also returns values only if `fn_test` returns true. +"""""" +function get_optional_string(x::VPtr, fn_test::Symbol, fn_sym::Symbol)::Maybe{String} + if ccall(sbml(fn_test), Cint, (VPtr,), x) == 0 + return nothing + else + get_optional_string(x, fn_sym) + end +end + +"""""" +$(TYPEDSIGNATURES) + +Helper for getting out boolean flags. +"""""" +function get_optional_bool(x::VPtr, is_sym::Symbol, get_sym::Symbol)::Maybe{Bool} + if ccall(sbml(is_sym), Cint, (VPtr,), x) != 0 + return ccall(sbml(get_sym), Cint, (VPtr,), x) != 0 + else + return nothing + end +end + +"""""" +$(TYPEDSIGNATURES) + +Helper for getting out unsigned integers. +"""""" +function get_optional_int(x::VPtr, is_sym::Symbol, get_sym::Symbol)::Maybe{Int} + if ccall(sbml(is_sym), Cint, (VPtr,), x) != 0 + return ccall(sbml(get_sym), Cint, (VPtr,), x) + else + return nothing + end +end + +"""""" +$(TYPEDSIGNATURES) + +Helper for getting out C doubles aka Float64s. +"""""" +function get_optional_double(x::VPtr, is_sym::Symbol, get_sym::Symbol)::Maybe{Float64} + if ccall(sbml(is_sym), Cint, (VPtr,), x) != 0 + return ccall(sbml(get_sym), Cdouble, (VPtr,), x) + else + return nothing + end +end + +"""""" +$(TYPEDSIGNATURES) + +Shortcut for retrieving SBO term IDs (as strings). +"""""" +get_sbo_term(x::VPtr) = get_optional_string(x, :SBase_getSBOTermID) + +"""""" +$(TYPEDSIGNATURES) + +Shortcut for retrieving SBO term IDs (as strings). +"""""" +get_cv_terms(x::VPtr) = CVTerm[ + get_cv_term(ccall(sbml(:SBase_getCVTerm), VPtr, (VPtr, Cuint), x, i - 1)) for + i = 1:ccall(sbml(:SBase_getNumCVTerms), Cuint, (VPtr,), x) +] + +function get_cv_term(cvt::VPtr) + qual_type = ccall(sbml(:CVTerm_getQualifierType), Cint, (VPtr,), cvt) + + return CVTerm( + biological_qualifier = qual_type != 1 ? nothing : + let cstr = ccall( + sbml(:BiolQualifierType_toString), + Cstring, + (Cint,), + ccall(sbml(:CVTerm_getBiologicalQualifierType), Cint, (VPtr,), cvt), + ) + cstr == C_NULL ? nothing : Symbol(unsafe_string(cstr)) + end, + model_qualifier = qual_type != 0 ? nothing : + let cstr = ccall( + sbml(:ModelQualifierType_toString), + Cstring, + (Cint,), + ccall(sbml(:CVTerm_getModelQualifierType), Cint, (VPtr,), cvt), + ) + cstr == C_NULL ? nothing : Symbol(unsafe_string(cstr)) + end, + resource_uris = String[ + unsafe_string( + ccall(sbml(:CVTerm_getResourceURI), Cstring, (VPtr, Cuint), cvt, j - 1), + ) for j = 1:ccall(sbml(:CVTerm_getNumResources), Cuint, (VPtr,), cvt) + ], + nested_cvterms = CVTerm[ + get_cv_term( + ccall(sbml(:CVTerm_getNestedCVTerm), VPtr, (VPtr, Cuint), x, j - 1), + ) for j = 1:ccall(sbml(:CVTerm_getNumNestedCVTerms), Cuint, (VPtr,), cvt) + ], + ) +end + +"""""" +$(TYPEDSIGNATURES) + +Helper for converting XML that is not represented by SBML structures to String. +"""""" +function get_string_from_xmlnode(xmlnode::VPtr)::String + if ccall(sbml(:XMLNode_isText), Bool, (VPtr,), xmlnode) + str_ptr = ccall(sbml(:XMLNode_getCharacters), Cstring, (VPtr,), xmlnode) + str_ptr == C_NULL ? """" : unsafe_string(str_ptr) + else + children_num = ccall(sbml(:XMLNode_getNumChildren), Cuint, (VPtr,), xmlnode) + join( + ( + get_string_from_xmlnode( + ccall(sbml(:XMLNode_getChild), VPtr, (VPtr, Cint), xmlnode, n), + ) for n = 0:(children_num-1) + ), + ""\n"", + ) + end +end + +"""""" +$(TYPEDSIGNATURES) + +Internal helper for [`readSBML`](@ref). +"""""" +function _readSBML( + symbol::Symbol, + fn::String, + sbml_conversion, + report_severities, + throw_severities, +)::SBML.Model + doc = ccall(sbml(symbol), VPtr, (Cstring,), fn) + try + get_error_messages( + doc, + AssertionError(""Opening SBML document has reported errors""), + report_severities, + throw_severities, + ) + + sbml_conversion(doc) + + if 0 == ccall(sbml(:SBMLDocument_isSetModel), Cint, (VPtr,), doc) + throw(AssertionError(""SBML document contains no model"")) + end + + model = ccall(sbml(:SBMLDocument_getModel), VPtr, (VPtr,), doc) + + return get_model(model) + finally + ccall(sbml(:SBMLDocument_free), Nothing, (VPtr,), doc) + end +end + +"""""" +$(TYPEDSIGNATURES) + +Read the SBML from a XML file in `fn` and return the contained `SBML.Model`. + +The `sbml_conversion` is a function that does an in-place modification of the +single parameter, which is the C pointer to the loaded SBML document (C type +`SBMLDocument*`). Several functions for doing that are prepared, including +[`set_level_and_version`](@ref), [`libsbml_convert`](@ref), +[`convert_simplify_math`](@ref) and [`convert_promotelocals_expandfuns`](@ref). + +`report_severities` and `throw_severities` switch on and off reporting of +certain errors; see the documentation of [`get_error_messages`](@ref) for +details. + +To read from a string instead of a file, use [`readSBMLFromString`](@ref). + +# Example +``` +m = readSBML(""my_model.xml"", doc -> begin + set_level_and_version(3, 1)(doc) + convert_simplify_math(doc) +end) +``` +"""""" +function readSBML( + fn::String, + sbml_conversion = document -> nothing; + report_severities = [""Error""], + throw_severities = [""Fatal""], +)::SBML.Model + isfile(fn) || throw(AssertionError(""$(fn) is not a file"")) + _readSBML(:readSBML, fn, sbml_conversion, report_severities, throw_severities) +end + +"""""" +$(TYPEDSIGNATURES) + +Shortcut for running a function `f` on the contents of the SBML file, suitable +for the `do` block syntax. Returns whatever `f` returns. + +# Example +``` +readSBML(""my_model.xml"") do m + @info ""model stats"" length(m.species) length(m.reactions) +end +``` +"""""" +readSBML(f::Function, args...; kwargs...) = return f(readSBML(args...; kwargs...)) + +"""""" +$(TYPEDSIGNATURES) + +Read the SBML from the string `str` and return the contained `SBML.Model`. + +For the other arguments see the docstring of [`readSBML`](@ref), which can be +used to read from a file instead of a string. +"""""" +readSBMLFromString( + str::AbstractString, + sbml_conversion = document -> nothing; + report_severities = [""Error""], + throw_severities = [""Fatal""], +)::SBML.Model = _readSBML( + :readSBMLFromString, + String(str), + sbml_conversion, + report_severities, + throw_severities, +) + +get_notes(x::VPtr)::Maybe{String} = get_optional_string(x, :SBase_getNotesString) +get_annotation(x::VPtr)::Maybe{String} = get_optional_string(x, :SBase_getAnnotationString) +get_metaid(x::VPtr)::Maybe{String} = get_optional_string(x, :SBase_getMetaId) + +"""""" +$(TYPEDSIGNATURES) + +Convert a pointer to SBML `FbcAssociation_t` to the `GeneProductAssociation` +tree structure. +"""""" +function get_association(x::VPtr)::GeneProductAssociation + # libsbml C API is currently missing functions to check this in a normal + # way, so we use a bit of a hack. + typecode = ccall(sbml(:SBase_getTypeCode), Cint, (VPtr,), x) + if typecode == 808 # SBML_FBC_GENEPRODUCTREF + return GPARef(get_string(x, :GeneProductRef_getGeneProduct)) + elseif typecode == 809 # SBML_FBC_AND + return GPAAnd([ + get_association( + ccall(sbml(:FbcAnd_getAssociation), VPtr, (VPtr, Cuint), x, i - 1), + ) for i = 1:ccall(sbml(:FbcAnd_getNumAssociations), Cuint, (VPtr,), x) + ]) + elseif typecode == 810 # SBML_FBC_OR + return GPAOr([ + get_association( + ccall(sbml(:FbcOr_getAssociation), VPtr, (VPtr, Cuint), x, i - 1), + ) for i = 1:ccall(sbml(:FbcOr_getNumAssociations), Cuint, (VPtr,), x) + ]) + else + throw(ErrorException(""Unsupported FbcAssociation type"")) + end +end + +"""""" +$(TYPEDSIGNATURES) + +Extract the value of SBML `Parameter_t`. +"""""" +get_parameter(p::VPtr)::Pair{String,Parameter} = + get_string(p, :Parameter_getId) => Parameter( + name = get_optional_string(p, :Parameter_getName), + value = get_optional_double(p, :Parameter_isSetValue, :Parameter_getValue), + units = get_optional_string(p, :Parameter_getUnits), + constant = get_optional_bool(p, :Parameter_isSetConstant, :Parameter_getConstant), + metaid = get_metaid(p), + notes = get_notes(p), + annotation = get_annotation(p), + sbo = get_sbo_term(p), + cv_terms = get_cv_terms(p), + ) + +"""""" +$(TYPEDSIGNATURES) + +Take the `SBMLModel_t` pointer and extract all information required to make a +valid [`SBML.Model`](@ref) structure. +"""""" +function get_model(mdl::VPtr)::SBML.Model + # get the FBC plugin pointer (FbcModelPlugin_t) + mdl_fbc = ccall(sbml(:SBase_getPlugin), VPtr, (VPtr, Cstring), mdl, ""fbc"") + # and the Groups plugin pointer (GroupModelPlugin_t) + mdl_groups = ccall(sbml(:SBase_getPlugin), VPtr, (VPtr, Cstring), mdl, ""groups"") + + # get the parameters + parameters = Dict{String,Parameter}() + for i = 1:ccall(sbml(:Model_getNumParameters), Cuint, (VPtr,), mdl) + p = ccall(sbml(:Model_getParameter), VPtr, (VPtr, Cuint), mdl, i - 1) + id, v = get_parameter(p) + parameters[id] = v + end + + # parse out the unit definitions + units = Dict{String,UnitDefinition}() + for i = 1:ccall(sbml(:Model_getNumUnitDefinitions), Cuint, (VPtr,), mdl) + ud = ccall(sbml(:Model_getUnitDefinition), VPtr, (VPtr, Cuint), mdl, i - 1) + id = get_string(ud, :UnitDefinition_getId) + name = get_optional_string(ud, :UnitDefinition_getName) + unit_parts = [ + begin + u = ccall(sbml(:UnitDefinition_getUnit), VPtr, (VPtr, Cuint), ud, j - 1) + SBML.UnitPart( + unsafe_string( + ccall( + sbml(:UnitKind_toString), + Cstring, + (Cint,), + ccall(sbml(:Unit_getKind), Cint, (VPtr,), u), + ), + ), + ccall(sbml(:Unit_getExponent), Cint, (VPtr,), u), + ccall(sbml(:Unit_getScale), Cint, (VPtr,), u), + ccall(sbml(:Unit_getMultiplier), Cdouble, (VPtr,), u), + ) + end for j = 1:ccall(sbml(:UnitDefinition_getNumUnits), Cuint, (VPtr,), ud) + ] + units[id] = UnitDefinition(; name, unit_parts) + end + + # parse out compartment names + compartments = Dict{String,Compartment}() + for i = 1:ccall(sbml(:Model_getNumCompartments), Cuint, (VPtr,), mdl) + co = ccall(sbml(:Model_getCompartment), VPtr, (VPtr, Cuint), mdl, i - 1) + + compartments[get_string(co, :Compartment_getId)] = Compartment( + name = get_optional_string(co, :Compartment_getName), + constant = get_optional_bool( + co, + :Compartment_isSetConstant, + :Compartment_getConstant, + ), + spatial_dimensions = get_optional_int( + co, + :Compartment_isSetSpatialDimensions, + :Compartment_getSpatialDimensions, + ), + size = get_optional_double(co, :Compartment_isSetSize, :Compartment_getSize), + units = get_optional_string(co, :Compartment_getUnits), + metaid = get_metaid(co), + notes = get_notes(co), + annotation = get_annotation(co), + sbo = get_sbo_term(co), + cv_terms = get_cv_terms(co), + ) + end + + # parse out species + species = Dict{String,Species}() + for i = 1:ccall(sbml(:Model_getNumSpecies), Cuint, (VPtr,), mdl) + sp = ccall(sbml(:Model_getSpecies), VPtr, (VPtr, Cuint), mdl, i - 1) + sp_fbc = ccall(sbml(:SBase_getPlugin), VPtr, (VPtr, Cstring), sp, ""fbc"") # FbcSpeciesPlugin_t + + formula = nothing + charge = nothing + if sp_fbc != C_NULL + # if the FBC plugin is present, try to get the chemical formula and charge + if 0 != + ccall(sbml(:FbcSpeciesPlugin_isSetChemicalFormula), Cint, (VPtr,), sp_fbc) + formula = get_string(sp_fbc, :FbcSpeciesPlugin_getChemicalFormula) + end + if 0 != ccall(sbml(:FbcSpeciesPlugin_isSetCharge), Cint, (VPtr,), sp_fbc) + charge = ccall(sbml(:FbcSpeciesPlugin_getCharge), Cint, (VPtr,), sp_fbc) + end + end + + species[get_string(sp, :Species_getId)] = Species(; + name = get_optional_string(sp, :Species_getName), + compartment = get_string(sp, :Species_getCompartment), + boundary_condition = get_optional_bool( + sp, + :Species_isSetBoundaryCondition, + :Species_getBoundaryCondition, + ), + formula, + charge, + initial_amount = if ( + ccall(sbml(:Species_isSetInitialAmount), Cint, (VPtr,), sp) != 0 + ) + ccall(sbml(:Species_getInitialAmount), Cdouble, (VPtr,), sp) + end, + initial_concentration = if ( + ccall(sbml(:Species_isSetInitialConcentration), Cint, (VPtr,), sp) != 0 + ) + ccall(sbml(:Species_getInitialConcentration), Cdouble, (VPtr,), sp) + end, + substance_units = get_optional_string(sp, :Species_getSubstanceUnits), + conversion_factor = if ( + ccall(sbml(:Species_getConversionFactor), Cstring, (VPtr,), sp) != C_NULL + ) + get_string(sp, :Species_getConversionFactor) + end, + only_substance_units = get_optional_bool( + sp, + :Species_isSetHasOnlySubstanceUnits, + :Species_getHasOnlySubstanceUnits, + ), + constant = get_optional_bool(sp, :Species_isSetConstant, :Species_getConstant), + metaid = get_metaid(sp), + notes = get_notes(sp), + annotation = get_annotation(sp), + sbo = get_sbo_term(sp), + cv_terms = get_cv_terms(sp), + ) + end + + # parse out the flux objectives (these are complementary to the objectives + # that appear in the reactions, see comments lower) + objectives = Dict{String,Objective}() + active_objective = nothing + if mdl_fbc != C_NULL + for i = 1:ccall(sbml(:FbcModelPlugin_getNumObjectives), Cuint, (VPtr,), mdl_fbc) + flux_objectives = Dict{String,Float64}() + o = ccall( + sbml(:FbcModelPlugin_getObjective), + VPtr, + (VPtr, Cuint), + mdl_fbc, + i - 1, + ) + type = get_string(o, :Objective_getType) + for j = 1:ccall(sbml(:Objective_getNumFluxObjectives), Cuint, (VPtr,), o) + fo = ccall(sbml(:Objective_getFluxObjective), VPtr, (VPtr, Cuint), o, j - 1) + flux_objectives[get_string(fo, :FluxObjective_getReaction)] = + ccall(sbml(:FluxObjective_getCoefficient), Cdouble, (VPtr,), fo) + end + objectives[get_string(o, :Objective_getId)] = Objective(type, flux_objectives) + end + ao = get_string(mdl_fbc, :FbcModelPlugin_getActiveObjectiveId) + if ao != """" + # libsbml does not expose isSet* and unset* methods for the active objective + active_objective = ao + end + end + + # reactions! + reactions = Dict{String,Reaction}() + for i = 1:ccall(sbml(:Model_getNumReactions), Cuint, (VPtr,), mdl) + re = ccall(sbml(:Model_getReaction), VPtr, (VPtr, Cuint), mdl, i - 1) + kinetic_parameters = Dict{String,Parameter}() + lower_bound = nothing + upper_bound = nothing + math = nothing + + # kinetic laws store a second version of the bounds and objectives + kl = ccall(sbml(:Reaction_getKineticLaw), VPtr, (VPtr,), re) + if kl != C_NULL + for j = 1:ccall(sbml(:KineticLaw_getNumParameters), Cuint, (VPtr,), kl) + p = ccall(sbml(:KineticLaw_getParameter), VPtr, (VPtr, Cuint), kl, j - 1) + id, v = get_parameter(p) + kinetic_parameters[id] = v + end + + if ccall(sbml(:KineticLaw_isSetMath), Cint, (VPtr,), kl) != 0 + math = parse_math(ccall(sbml(:KineticLaw_getMath), VPtr, (VPtr,), kl)) + end + end + + re_fbc = ccall(sbml(:SBase_getPlugin), VPtr, (VPtr, Cstring), re, ""fbc"") + if re_fbc != C_NULL + lower_bound = get_optional_string( + re_fbc, + :FbcReactionPlugin_isSetLowerFluxBound, + :FbcReactionPlugin_getLowerFluxBound, + ) + upper_bound = get_optional_string( + re_fbc, + :FbcReactionPlugin_isSetUpperFluxBound, + :FbcReactionPlugin_getUpperFluxBound, + ) + end + + # extract species references + reactants = SpeciesReference[] + products = SpeciesReference[] + + add_stoi(sr, coll) = begin + stoichiometry = + if ccall(sbml(:SpeciesReference_isSetStoichiometry), Cint, (VPtr,), sr) != 0 + ccall(sbml(:SpeciesReference_getStoichiometry), Cdouble, (VPtr,), sr) + end + + constant = + if ccall(sbml(:SpeciesReference_isSetConstant), Cint, (VPtr,), sr) != 0 + ccall(sbml(:SpeciesReference_getConstant), Cint, (VPtr,), sr) != 0 + end + + push!( + coll, + SpeciesReference( + id = get_optional_string( + sr, + :SpeciesReference_isSetId, + :SpeciesReference_getId, + ), + species = get_string(sr, :SpeciesReference_getSpecies); + stoichiometry, + constant, + ), + ) + end + + for j = 1:ccall(sbml(:Reaction_getNumReactants), Cuint, (VPtr,), re) + sr = ccall(sbml(:Reaction_getReactant), VPtr, (VPtr, Cuint), re, j - 1) + add_stoi(sr, reactants) + end + + for j = 1:ccall(sbml(:Reaction_getNumProducts), Cuint, (VPtr,), re) + sr = ccall(sbml(:Reaction_getProduct), VPtr, (VPtr, Cuint), re, j - 1) + add_stoi(sr, products) + end + + # gene product associations + association = nothing + if re_fbc != C_NULL + gpa = ccall( + sbml(:FbcReactionPlugin_getGeneProductAssociation), + VPtr, + (VPtr,), + re_fbc, + ) + if gpa != C_NULL + a = ccall(sbml(:GeneProductAssociation_getAssociation), VPtr, (VPtr,), gpa) + a != C_NULL + association = get_association(a) + end + end + + # explicit reversible flag (defaults to true in SBML) + reversible = Bool(ccall(sbml(:Reaction_getReversible), Cint, (VPtr,), re)) + + reid = get_string(re, :Reaction_getId) + reactions[reid] = Reaction(; + name = get_optional_string(re, :Reaction_getName), + reactants, + products, + kinetic_parameters, + lower_bound, + upper_bound, + gene_product_association = association, + kinetic_math = math, + reversible, + metaid = get_metaid(re), + notes = get_notes(re), + annotation = get_annotation(re), + sbo = get_sbo_term(re), + cv_terms = get_cv_terms(re), + ) + end + + # extract gene products + gene_products = Dict{String,GeneProduct}() + if mdl_fbc != C_NULL + for i = 1:ccall(sbml(:FbcModelPlugin_getNumGeneProducts), Cuint, (VPtr,), mdl_fbc) + gp = ccall( + sbml(:FbcModelPlugin_getGeneProduct), + VPtr, + (VPtr, Cuint), + mdl_fbc, + i - 1, + ) + + id = get_optional_string(gp, :GeneProduct_getId) # IDs don't need to be set + + if id != nothing + gene_products[id] = GeneProduct( + label = get_string(gp, :GeneProduct_getLabel), + name = get_optional_string(gp, :GeneProduct_getName), + metaid = get_metaid(gp), + notes = get_notes(gp), + annotation = get_annotation(gp), + sbo = get_sbo_term(gp), + cv_terms = get_cv_terms(gp), + ) + end + end + end + + function_definitions = Dict{String,FunctionDefinition}() + for i = 1:ccall(sbml(:Model_getNumFunctionDefinitions), Cuint, (VPtr,), mdl) + fd = ccall(sbml(:Model_getFunctionDefinition), VPtr, (VPtr, Cuint), mdl, i - 1) + def = nothing + if ccall(sbml(:FunctionDefinition_isSetMath), Cint, (VPtr,), fd) != 0 + def = parse_math(ccall(sbml(:FunctionDefinition_getMath), VPtr, (VPtr,), fd)) + end + + function_definitions[get_string(fd, :FunctionDefinition_getId)] = + FunctionDefinition( + name = get_optional_string(fd, :FunctionDefinition_getName), + metaid = get_metaid(fd), + body = def, + notes = get_notes(fd), + annotation = get_annotation(fd), + sbo = get_sbo_term(fd), + cv_terms = get_cv_terms(fd), + ) + end + + initial_assignments = Dict{String,Math}() + num_ias = ccall(sbml(:Model_getNumInitialAssignments), Cuint, (VPtr,), mdl) + for i = 0:(num_ias-1) + ia = ccall(sbml(:Model_getInitialAssignment), VPtr, (VPtr, Cuint), mdl, i) + sym = ccall(sbml(:InitialAssignment_getSymbol), Cstring, (VPtr,), ia) + math_ptr = ccall(sbml(:InitialAssignment_getMath), VPtr, (VPtr,), ia) + if math_ptr != C_NULL + initial_assignments[unsafe_string(sym)] = parse_math(math_ptr) + end + end + + # events + events = Pair{Maybe{String},Event}[] + num_events = ccall(sbml(:Model_getNumEvents), Cuint, (VPtr,), mdl) + for i = 0:(num_events-1) + ev = ccall(sbml(:Model_getEvent), VPtr, (VPtr, Cuint), mdl, i) + + event_assignments = EventAssignment[] + for j = 0:(ccall(sbml(:Event_getNumEventAssignments), Cuint, (VPtr,), ev)-1) + eva = ccall(sbml(:Event_getEventAssignment), VPtr, (VPtr, Cuint), ev, j) + eva_math_ptr = ccall(sbml(:EventAssignment_getMath), VPtr, (VPtr,), eva) + push!( + event_assignments, + EventAssignment( + variable = unsafe_string( + ccall(sbml(:EventAssignment_getVariable), Cstring, (VPtr,), eva), + ), + math = eva_math_ptr == C_NULL ? nothing : parse_math(eva_math_ptr), + ), + ) + end + + trigger_ptr = ccall(sbml(:Event_getTrigger), VPtr, (VPtr,), ev) + trig_math_ptr = ccall(sbml(:Trigger_getMath), VPtr, (VPtr,), trigger_ptr) + trigger = Trigger(; + persistent = ccall(sbml(:Trigger_getPersistent), Bool, (VPtr,), trigger_ptr), + initial_value = ccall( + sbml(:Trigger_getInitialValue), + Bool, + (VPtr,), + trigger_ptr, + ), + math = trig_math_ptr == C_NULL ? nothing : parse_math(trig_math_ptr), + ) + + push!( + events, + get_optional_string(ev, :Event_getId) => SBML.Event(; + use_values_from_trigger_time = ccall( + sbml(:Event_getUseValuesFromTriggerTime), + Cint, + (VPtr,), + ev, + ) != 0, + name = get_optional_string(ev, :Event_getName), + trigger, + event_assignments, + ), + ) + end + + # rules + rules = Rule[] + num_rules = ccall(sbml(:Model_getNumRules), Cuint, (VPtr,), mdl) + for i = 0:(num_rules-1) + rule_ptr = ccall(sbml(:Model_getRule), VPtr, (VPtr, Cuint), mdl, i) + type = if ccall(sbml(:Rule_isAlgebraic), Bool, (VPtr,), rule_ptr) + AlgebraicRule + elseif ccall(sbml(:Rule_isAssignment), Bool, (VPtr,), rule_ptr) + AssignmentRule + elseif ccall(sbml(:Rule_isRate), Bool, (VPtr,), rule_ptr) + RateRule + end + if type in (AssignmentRule, RateRule) + var = ccall(sbml(:Rule_getVariable), Cstring, (VPtr,), rule_ptr) + end + math_ptr = ccall(sbml(:Rule_getMath), VPtr, (VPtr,), rule_ptr) + if math_ptr != C_NULL + math = parse_math(math_ptr) + rule = if type in (AssignmentRule, RateRule) + type(unsafe_string(var), math) + else + type(math) + end + push!(rules, rule) + end + end + + # constraints + constraints = Constraint[] + num_constraints = ccall(sbml(:Model_getNumConstraints), Cuint, (VPtr,), mdl) + for i = 0:(num_constraints-1) + constraint_ptr = ccall(sbml(:Model_getConstraint), VPtr, (VPtr, Cuint), mdl, i) + xml_ptr = ccall(sbml(:Constraint_getMessage), VPtr, (VPtr,), constraint_ptr) + message = get_string_from_xmlnode(xml_ptr) + math_ptr = ccall(sbml(:Constraint_getMath), VPtr, (VPtr,), constraint_ptr) + if math_ptr != C_NULL + math = parse_math(math_ptr) + constraint = Constraint(math, message) + push!(constraints, constraint) + end + end + + # groups (these require the groups extension) + groups = Dict{String,Group}() + if mdl_groups != C_NULL + num_groups = + ccall(sbml(:GroupsModelPlugin_getNumGroups), Cuint, (VPtr,), mdl_groups) + for i = 0:(num_groups-1) + grp = + ccall(sbml(:GroupsModelPlugin_getGroup), VPtr, (VPtr, Cuint), mdl_groups, i) + members = Member[ + let mem = ccall(sbml(:Group_getMember), VPtr, (VPtr, Cuint), grp, mi) + Member(; + id = get_optional_string(mem, :Member_getId), + metaid = get_metaid(mem), + name = get_optional_string(mem, :Member_getName), + id_ref = get_optional_string(mem, :Member_getIdRef), + metaid_ref = get_optional_string(mem, :Member_getMetaIdRef), + notes = get_notes(mem), + annotation = get_annotation(mem), + sbo = get_sbo_term(mem), + cv_terms = get_cv_terms(mem), + ) + end for + mi = 0:(ccall(sbml(:Group_getNumMembers), Cuint, (VPtr,), grp)-1) + ] + + groups[get_string(grp, :Group_getId)] = Group(; + metaid = get_metaid(grp), + kind = get_optional_string(grp, :Group_getKindAsString), + name = get_optional_string(grp, :Group_getName), + members, + notes = get_notes(grp), + annotation = get_annotation(grp), + sbo = get_sbo_term(grp), + cv_terms = get_cv_terms(grp), + ) + end + end + + return Model(; + parameters, + units, + compartments, + species, + initial_assignments, + rules, + constraints, + reactions, + objectives, + active_objective, + gene_products, + function_definitions, + events, + groups, + name = get_optional_string(mdl, :Model_getName), + id = get_optional_string(mdl, :Model_getId), + metaid = get_metaid(mdl), + conversion_factor = get_optional_string(mdl, :Model_getConversionFactor), + area_units = get_optional_string(mdl, :Model_getAreaUnits), + extent_units = get_optional_string(mdl, :Model_getExtentUnits), + length_units = get_optional_string(mdl, :Model_getLengthUnits), + substance_units = get_optional_string(mdl, :Model_getSubstanceUnits), + time_units = get_optional_string(mdl, :Model_getTimeUnits), + volume_units = get_optional_string(mdl, :Model_getVolumeUnits), + notes = get_notes(mdl), + annotation = get_annotation(mdl), + sbo = get_sbo_term(mdl), + cv_terms = get_cv_terms(mdl), + ) +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","src/unitful.jl",".jl","3614","104"," +# NOTE: this mapping is valid for Level 3/Version 2, it *may* not be valid for +# other versions. See +# https://github.com/sbmlteam/libsbml/blob/d4bc12abc4e72e451a0a0f2be4b0b6101ac94160/src/sbml/UnitKind.c#L46-L85 +const UNITFUL_KIND_STRING = Dict( + ""ampere"" => 1.0 * u""A"", # UNIT_KIND_AMPERE + ""avogadro"" => ustrip(u""mol^-1"", Unitful.Na), # UNIT_KIND_AVOGADRO + ""becquerel"" => 1.0 * u""Bq"", # UNIT_KIND_BECQUEREL + ""candela"" => 1.0 * u""cd"", # UNIT_KIND_CANDELA + ""Celsius"" => 1.0 * u""°C"", # UNIT_KIND_CELSIUS + ""coulomb"" => 1.0 * u""C"", # UNIT_KIND_COULOMB + ""dimensionless"" => 1, # UNIT_KIND_DIMENSIONLESS + ""farad"" => 1.0 * u""F"", # UNIT_KIND_FARAD + ""gram"" => 1.0 * u""g"", # UNIT_KIND_GRAM + ""gray"" => 1.0 * u""Gy"", # UNIT_KIND_GRAY + ""henry"" => 1.0 * u""H"", # UNIT_KIND_HENRY + ""hertz"" => 1.0 * u""Hz"", # UNIT_KIND_HERTZ + ""item"" => 1, # UNIT_KIND_ITEM + ""joule"" => 1.0 * u""J"", # UNIT_KIND_JOULE + ""katal"" => 1.0 * u""kat"", # UNIT_KIND_KATAL + ""kelvin"" => 1.0 * u""K"", # UNIT_KIND_KELVIN + ""kilogram"" => 1.0 * u""kg"", # UNIT_KIND_KILOGRAM + ""liter"" => 1.0 * u""L"", # UNIT_KIND_LITER + ""litre"" => 1.0 * u""L"", # UNIT_KIND_LITRE + ""lumen"" => 1.0 * u""lm"", # UNIT_KIND_LUMEN + ""lux"" => 1.0 * u""lx"", # UNIT_KIND_LUX + ""meter"" => 1.0 * u""m"", # UNIT_KIND_METER + ""metre"" => 1.0 * u""m"", # UNIT_KIND_METRE + ""mole"" => 1.0 * u""mol"", # UNIT_KIND_MOLE + ""newton"" => 1.0 * u""N"", # UNIT_KIND_NEWTON + ""ohm"" => 1.0 * u""Ω"", # UNIT_KIND_OHM + ""pascal"" => 1.0 * u""Pa"", # UNIT_KIND_PASCAL + ""radian"" => 1.0 * u""rad"", # UNIT_KIND_RADIAN + ""second"" => 1.0 * u""s"", # UNIT_KIND_SECOND + ""siemens"" => 1.0 * u""S"", # UNIT_KIND_SIEMENS + ""sievert"" => 1.0 * u""Sv"", # UNIT_KIND_SIEVERT + ""steradian"" => 1.0 * u""sr"", # UNIT_KIND_STERADIAN + ""tesla"" => 1.0 * u""T"", # UNIT_KIND_TESLA + ""volt"" => 1.0 * u""V"", # UNIT_KIND_VOLT + ""watt"" => 1.0 * u""W"", # UNIT_KIND_WATT + ""weber"" => 1.0 * u""W"", # UNIT_KIND_WEBER + ""(Invalid UnitKind)"" => 1, # UNIT_KIND_INVALID (let's treat is as a dimensionless quantity) +) + + +"""""" +$(TYPEDSIGNATURES) + +Converts an SBML unit definition (i.e., its vector of [`UnitPart`](@ref)s) to a +corresponding Unitful unit. +"""""" +unitful(u::UnitDefinition) = unitful(u.unit_parts) + +"""""" +$(TYPEDSIGNATURES) + +Converts a [`UnitPart`](@ref) to a corresponding Unitful unit. + +The conversion is done according to the formula from +[SBML L3v2 core manual release 2](https://sbml.org/specifications/sbml-level-3/version-2/core/release-2/sbml-level-3-version-2-release-2-core.pdf)(section 4.4.2). +"""""" +unitful(u::UnitPart) = + (u.multiplier * UNITFUL_KIND_STRING[u.kind] * exp10(u.scale))^u.exponent + +"""""" +$(TYPEDSIGNATURES) + +Converts an SBML unit (i.e., a vector of [`UnitPart`](@ref)s) to a corresponding +Unitful unit. +"""""" +unitful(u::Vector{UnitPart}) = prod(unitful.(u)) + +"""""" +$(TYPEDSIGNATURES) + +Computes a properly unitful value from a value-unit pair stored in the model +`m`. +"""""" +unitful(m::Model, val::Tuple{Float64,String}) = unitful(m.units[val[2]]) * val[1] + +"""""" +$(TYPEDSIGNATURES) + +Overload of [`unitful`](@ref) that uses the `default_unit` if the unit is not +found in the model. + +# Example +``` +julia> SBML.unitful(mdl, (10.0,""firkin""), 90 * u""lb"") +990.0 lb +``` +"""""" +unitful(m::Model, val::Tuple{Float64,String}, default_unit::Number) = + mayfirst(maylift(unitful, get(m.units, val[2], nothing)), default_unit) * val[1] + +"""""" +$(TYPEDSIGNATURES) + +Overload of [`unitful`](@ref) that allows specification of the `default_unit` by +string ID. +"""""" +unitful(m::Model, val::Tuple{Float64,String}, default_unit::String) = + unitful(m, val, unitful(m.units[default_unit])) +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","src/converters.jl",".jl","3752","114"," +"""""" +$(TYPEDSIGNATURES) + +A converter to pass into [`readSBML`](@ref) that enforces certain SBML level +and version. `report_severities` switches on and off reporting of certain +errors; see the documentation of [`get_error_messages`](@ref) for details. +"""""" +set_level_and_version( + level, + version, + report_severities = [""Fatal"", ""Error""], + throw_severities = [""Fatal"", ""Error""], +) = + doc -> check_errors( + ccall( + sbml(:SBMLDocument_setLevelAndVersion), + Cint, + (VPtr, Cint, Cint), + doc, + level, + version, + ), + doc, + ErrorException(""Setting of level and version did not succeed""), + report_severities, + throw_severities, + ) + +"""""" +$(TYPEDSIGNATURES) + +A converter that runs the SBML conversion routine, with specified conversion +options. The argument is a vector of pairs to allow specifying the order of +conversions. `report_severities` switches on and off reporting of certain +errors; see the documentation of [`get_error_messages`](@ref) for details. +"""""" +libsbml_convert( + conversion_options::AbstractVector{<:Pair{String,<:AbstractDict{String,String}}}, + report_severities = [""Fatal"", ""Error""], + throw_severities = [""Fatal"", ""Error""], +) = + doc -> begin + for (converter, options) in conversion_options + props = ccall(sbml(:ConversionProperties_create), VPtr, ()) + opt = ccall(sbml(:ConversionOption_create), VPtr, (Cstring,), converter) + ccall(sbml(:ConversionProperties_addOption), Cvoid, (VPtr, VPtr), props, opt) + for (k, v) in options + opt = ccall(sbml(:ConversionOption_create), VPtr, (Cstring,), k) + ccall(sbml(:ConversionOption_setValue), Cvoid, (VPtr, Cstring), opt, v) + ccall( + sbml(:ConversionProperties_addOption), + Cvoid, + (VPtr, VPtr), + props, + opt, + ) + end + check_errors( + # `SBMLDocument_convert` returns `LIBSBML_OPERATION_SUCCESS` (== 0) for a + # successful operation, something else when there is a failure. + iszero(ccall(sbml(:SBMLDocument_convert), Cint, (VPtr, VPtr), doc, props)), + doc, + ErrorException(""Conversion returned errors""), + report_severities, + throw_severities, + ) + end + end + +"""""" +$(TYPEDSIGNATURES) + +Quickly construct a single run of a `libsbml` converter from keyword arguments. +`report_severities` switches on and off reporting of certain errors; see the +documentation of [`get_error_messages`](@ref) for details. + +# Example +``` +readSBML(""example.xml"", libsbml_convert(""stripPackage"", package=""layout"")) +``` +"""""" +libsbml_convert( + converter::String; + report_severities = [""Fatal"", ""Error""], + throw_severities = [""Fatal"", ""Error""], + kwargs..., +) = libsbml_convert( + [converter => Dict{String,String}(string(k) => string(v) for (k, v) in kwargs)], + report_severities, + throw_severities, +) + +"""""" +$(TYPEDSIGNATURES) + +Shortcut for [`libsbml_convert`](@ref) that expands functions, local +parameters, and initial assignments in the SBML document. +"""""" +const convert_simplify_math = libsbml_convert( + [""promoteLocalParameters"", ""expandFunctionDefinitions"", ""expandInitialAssignments""] .=> Ref(Dict{String,String}()), +) + +"""""" +$(TYPEDSIGNATURES) + +Shortcut for [`libsbml_convert`](@ref) that expands functions and local +parameters in the SBML document. +"""""" +const convert_promotelocals_expandfuns = libsbml_convert( + [""promoteLocalParameters"", ""expandFunctionDefinitions""] .=> + Ref(Dict{String,String}()), +) +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","test/version.jl",".jl","112","5"," +@testset ""CCall to SBML works and SBML returns a version"" begin + @test SBML.Version() isa VersionNumber +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","test/loaddynamicmodels.jl",".jl","4138","119","compartment = SBML.MathIdent(""compartment"") +k1 = SBML.MathIdent(""k1"") +k2 = SBML.MathIdent(""k2"") +reaction1_k = SBML.MathIdent(""reaction1_k"") +S1 = SBML.MathIdent(""S1"") + +sbmlfiles = [ + # sbml_test_suite case 00001 + ( + joinpath(@__DIR__, ""data"", ""00001-sbml-l3v2.xml""), + SBML.test_suite_url(1, level = 3, version = 2), + ""3e9a8bfe27343459d7a1e462fc3fd4eb2b01dc7b32af1db06a98f366287da01a"", + x -> nothing, + 1, + (""reaction1"", SBML.MathApply(""*"", [SBML.MathApply(""*"", [compartment, k1]), S1])), + (""S1"", 0.00015), + ), + # case 00001 in older level and version + ( + joinpath(@__DIR__, ""data"", ""00001-sbml-l2v1.xml""), + SBML.test_suite_url(1, level = 2, version = 1), + ""71a145c58b08e475d76bdec644589b2a55b5c5c2fee218274c91677c0f30b508"", + SBML.set_level_and_version(3, 2), + 1, + (""reaction1"", SBML.MathApply(""*"", [SBML.MathApply(""*"", [compartment, k1]), S1])), + (""S1"", 0.00015), + ), + # case 00057 with localParameters + ( + joinpath(@__DIR__, ""data"", ""00057-sbml-l3v2.xml""), + SBML.test_suite_url(57, level = 3, version = 2), + ""3e84e19cebbb79eea879847f541b1d22db6eb239f1f070ef4609f04c77688659"", + SBML.libsbml_convert(""promoteLocalParameters""), + 2, + ( + ""reaction1"", + SBML.MathApply(""*"", [SBML.MathApply(""*"", [compartment, reaction1_k]), S1]), + ), + (""S1"", 0.0003), + ), + # case 00025 with functionDefinition + ( + joinpath(@__DIR__, ""data"", ""00025-sbml-l3v2.xml""), + SBML.test_suite_url(25, level = 3, version = 2), + ""d3231ae3858d9e5dca1b106aa7b106a0caee9e6967ef8413de6b9acde9171c3e"", + SBML.libsbml_convert(""expandFunctionDefinitions""), + 1, + (""reaction1"", SBML.MathApply(""*"", [compartment, SBML.MathApply(""*"", [k1, S1])])), + (""S1"", 0.0015), + ), + # case 00036 with initialAssignment + ( + joinpath(@__DIR__, ""data"", ""00037-sbml-l3v2.xml""), + SBML.test_suite_url(37, level = 3, version = 2), + ""074f0caeaf2cdc390967bfdf06d80ccad519c648df7f421dc4e9c69e71551dff"", + SBML.libsbml_convert(""expandInitialAssignments""), + 2, + (""reaction1"", SBML.MathApply(""*"", [SBML.MathApply(""*"", [compartment, k2]), S1])), + (""S1"", 0.01125), + ), + # case 00928 with an ID-less event + ( + joinpath(@__DIR__, ""data"", ""00928-sbml-l3v2.xml""), + SBML.test_suite_url(928, level = 3, version = 2), + ""d2a95aee820712696a2056bb09fd7d3befcd99e331809105e12ee081073a4985"", + x -> nothing, + 1, + ( + ""reaction1"", + SBML.MathApply( + ""*"", + SBML.Math[ + SBML.MathApply( + ""*"", + SBML.Math[SBML.MathIdent(""C""), SBML.MathIdent(""k1"")], + ), + SBML.MathIdent(""S1""), + ], + ), + ), + (""S1"", 0.0), + ), +] + +@testset ""Loading of models from sbml_test_suite"" begin + for (sbmlfile, url, hash, converter, expected_par, expected_rxn, expected_u0) in + sbmlfiles + + if !isfile(sbmlfile) + Downloads.download(url, sbmlfile) + end + + cksum = bytes2hex(sha256(open(sbmlfile))) + if cksum != hash + @warn ""The downloaded model `$sbmlfile' seems to be different from the expected one. Tests will likely fail."" cksum + end + + @testset ""Loading of $sbmlfile"" begin + mdl = readSBML(sbmlfile, converter) + + @test typeof(mdl) == Model + + @test length(mdl.parameters) == expected_par + + id, math = expected_rxn + @test isequal(repr(mdl.reactions[id].kinetic_math), repr(math)) + + id, ic = expected_u0 + if basename(sbmlfile) == ""00037-sbml-l3v2.xml"" + # When expanding initial assignments with libsbml, the initial amount + # becomes empty. + @test_broken mdl.species[id].initial_amount == ic + else + @test mdl.species[id].initial_amount == ic + end + end + end +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","test/runtests.jl",".jl","750","35"," +using Test, SHA, SparseArrays, Downloads +using SBML +using SBML: Model, Reaction, Species +using Unitful + +# this can be easily switched off in case you need the tests run faster +const TEST_SYMBOLICS = true + +if TEST_SYMBOLICS + using Symbolics +else + macro variables(args...) + :() + end +end + +# Some utilities needed for testing +include(""common.jl"") + +@testset ""SBML test suite"" begin + include(""version.jl"") + + if TEST_SYMBOLICS + # this defines a few functions used also in loadmodels.jl + include(""symbolics.jl"") + end + + include(""ecoli_flux.jl"") + include(""loadmodels.jl"") + include(""writemodels.jl"") # depends on `sbmlfiles` from loadmodels.jl + include(""loaddynamicmodels.jl"") + include(""interpret.jl"") +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","test/symbolics.jl",".jl","1953","67"," +# Conversion to symbolics +symbolicsRateOf(x) = Symbolics.Differential(convert(Num, MathTime(""t"")))(x) + +symbolics_mapping = Dict(SBML.default_function_mapping..., ""rateOf"" => symbolicsRateOf) + +map_symbolics_time_ident(x) = begin + sym = Symbol(x.id) + Symbolics.unwrap(first(@variables $sym)) +end + +const interpret_as_num(x::SBML.Math) = SBML.interpret_math( + x; + map_apply = (x::SBML.MathApply, interpret::Function) -> + Num(symbolics_mapping[x.fn](interpret.(x.args)...)), + map_const = (x::SBML.MathConst) -> Num(SBML.default_constants[x.id]), + map_ident = map_symbolics_time_ident, + map_lambda = (_, _) -> + throw(ErrorException(""Symbolics.jl does not support lambda functions"")), + map_time = map_symbolics_time_ident, + map_value = (x::SBML.MathVal) -> Num(x.val), +) + +@testset ""Symbolics compatibility"" begin + + test = SBML.MathApply( + ""piecewise"", + SBML.Math[ + SBML.MathVal(123), + SBML.MathApply( + ""lt"", + SBML.Math[SBML.MathVal(2), SBML.MathVal(1), SBML.MathVal(0)], + ), + SBML.MathVal(456), + ], + ) + + @test isequal(interpret_as_num(test), 456) + + @variables A B C D Time + + test = SBML.MathApply( + ""*"", + SBML.Math[ + SBML.MathApply( + ""+"", + SBML.Math[ + SBML.MathApply( + ""*"", + SBML.Math[SBML.MathIdent(""A""), SBML.MathIdent(""B"")], + ), + SBML.MathApply( + ""-"", + SBML.Math[SBML.MathApply( + ""*"", + SBML.Math[SBML.MathIdent(""C""), SBML.MathIdent(""D"")], + )], + ), + ], + ), + SBML.MathTime(""Time""), + ], + ) + + @test isequal(interpret_as_num(test), (A * B - C * D) * Time) +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","test/interpret.jl",".jl","1226","40"," +@testset ""Math interpretation"" begin + + test = SBML.MathApply( + ""piecewise"", + SBML.Math[ + SBML.MathVal(123), + SBML.MathApply(""lt"", SBML.Math[SBML.MathVal(1), SBML.MathVal(0)]), + SBML.MathVal(456), + ], + ) + + @test isequal(SBML.interpret_math(test), 456) + + test = SBML.MathApply(""power"", SBML.Math[SBML.MathVal(2), SBML.MathVal(-1)]) + + @test isequal(SBML.interpret_math(test), 0.5) + + test = SBML.MathConst(""exponentiale"") + @test isequal(SBML.interpret_math(test), exp(1)) + + test = + SBML.MathApply(""gt"", SBML.Math[SBML.MathVal(2), SBML.MathVal(1), SBML.MathVal(0)]) + @test SBML.interpret_math(test) + test = + SBML.MathApply(""gt"", SBML.Math[SBML.MathVal(2), SBML.MathVal(1), SBML.MathVal(2)]) + @test !SBML.interpret_math(test) + + test = + SBML.MathApply(""neq"", SBML.Math[SBML.MathVal(2), SBML.MathVal(1), SBML.MathVal(0)]) + @test SBML.interpret_math(test) + test = + SBML.MathApply(""gt"", SBML.Math[SBML.MathVal(2), SBML.MathVal(1), SBML.MathVal(1)]) + @test !SBML.interpret_math(test) + + @variables x + @test isequal(SBML.sbmlPower(1, x.val), 1^x.val) + @test SBML.sbmlPower(Int(2), Int(-2)) == 0.25 +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","test/common.jl",".jl","1242","48","using ConstructionBase + +# For these types define `==` as `==` for all corresponding fields. +const NON_ANNOTATED_TYPES = Union{ + SBML.AlgebraicRule, + SBML.AssignmentRule, + SBML.Constraint, + SBML.CVTerm, + SBML.Event, + SBML.EventAssignment, + SBML.GeneProductAssociation, + SBML.MathApply, + SBML.MathLambda, + SBML.Objective, + SBML.RateRule, + SBML.Trigger, +} +function Base.:(==)(a::T, b::T) where {T<:NON_ANNOTATED_TYPES} + return getproperties(a) == getproperties(b) +end + +# Types for which we want `==` to be `==` for all fields except for the `annotation` field, +# for which we only check that both fields are either nothing or non-nothing. +const ANNOTATED_TYPES = Union{ + SBML.Compartment, + SBML.FunctionDefinition, + SBML.GeneProduct, + SBML.Group, + SBML.Member, + SBML.Model, + SBML.Parameter, + SBML.Reaction, + SBML.Species, + SBML.UnitDefinition, +} +function Base.:(==)(a::T, b::T) where {T<:ANNOTATED_TYPES} + nta = getproperties(a) + ntb = getproperties(b) + for k in keys(nta) + if k === :annotation + isnothing(nta[k]) == isnothing(ntb[k]) || return false + else + nta[k] == ntb[k] || return false + end + end + return true +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","test/ecoli_flux.jl",".jl","2355","74"," +sbmlfile = joinpath(@__DIR__, ""data"", ""Ec_core_flux1.xml"") + +if !isfile(sbmlfile) + Downloads.download( + ""http://systemsbiology.ucsd.edu/sites/systemsbiology.ucsd.edu/files/Attachments/Images/InSilicoOrganisms/Ecoli/Ecoli_SBML/Ec_core_flux1.xml"", + sbmlfile, + ) +end + +cksum = bytes2hex(sha256(open(sbmlfile))) +if cksum != ""01a883b364fa60582101ca1e270515e7fcb3fb2f60084d92e5ee45f9f72bbe50"" + @warn ""The downloaded E Coli core flux model seems to be different from the expected one. Tests will likely fail."" cksum +end + +@testset ""SBML flux model loading"" begin + mdl = readSBML(sbmlfile) + + @test typeof(mdl) == Model + + @test_throws AssertionError readSBML(sbmlfile * "".does.not.really.exist"") + + @test SBML.unitful(mdl.units[""mmol_per_gDW_per_hr""]) ≈ + 3.6001008028224795 * u""mol * g^-1 * s^-1"" + + @test SBML.unitful(mdl, (2.0, ""mmol_per_gDW_per_hr"")) ≈ + 7.200201605644959 * u""mol * g^-1 * s^-1"" + + @test SBML.unitful(mdl, (3.0, ""whatevs""), 1 * u""g"") ≈ 3.0 * u""g"" + + @test SBML.unitful(mdl, (3.0, ""the_flux_units""), ""mmol_per_gDW_per_hr"") ≈ + 10.800302408467438 * u""mol * g^-1 * s^-1"" + + @test length(mdl.compartments) == 2 + + mets, rxns, S = stoichiometry_matrix(mdl) + + @test typeof(S) <: SparseMatrixCSC{Float64} + + @test length(mets) == 77 + @test length(rxns) == 77 + @test size(S) == (length(mets), length(rxns)) + + # totally arbitrary value tests + @test isapprox(sum(S), 42.1479) + @test mets[10:12] == [""M_akg_e"", ""M_fum_c"", ""M_pyr_c""] + @test rxns[10:12] == [""R_H2Ot"", ""R_PGL"", ""R_EX_glc_e_""] + + lbs, ubs = flux_bounds(mdl) + ocs = flux_objective(mdl) + + @test length(ocs) == length(mets) + @test ocs[40] == 1.0 + deleteat!(ocs, 40) + @test all(ocs .== 0.0) + + @test length(flux_bounds(mdl)[1]) == length(rxns) + @test length(flux_bounds(mdl)[2]) == length(rxns) + + getunit((val, unit)) = unit + @test all([broadcast(getunit, lbs) broadcast(getunit, ubs)] .== ""mmol_per_gDW_per_hr"") + + getval((val, unit)) = val + lvals = broadcast(getval, lbs) + uvals = broadcast(getval, ubs) + @test isapprox(lvals[27], uvals[27]) + @test isapprox(lvals[27], 7.6) + @test isapprox(lvals[12], -10) + + @test count(isapprox.(lvals, -999999)) == 40 + @test count(isapprox.(lvals, 0)) == 35 + @test count(isapprox.(uvals, 999999)) == 76 +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","test/writemodels.jl",".jl","2887","78"," +function fix_constant!(model::SBML.Model) + # We only write SBML L3v2. If a model is L2 or less, the `constant` + # attributes may be missing (which is true for some models). We add the + # main problematic ones (in speciesReferences) here, to make sure the + # round trip has a chance to finish. + _clean(sr::SBML.SpeciesReference) = SBML.SpeciesReference( + species = sr.species, + stoichiometry = sr.stoichiometry, + constant = isnothing(sr.constant) ? true : sr.constant, + ) + for (_, r) in model.reactions + r.reactants .= map(_clean, r.reactants) + r.products .= map(_clean, r.products) + end +end + +function remove_some_annotation_strings!(model::SBML.Model) + gps = collect(keys(model.gene_products)) + for gp in gps + g = model.gene_products[gp] + if isempty(g.cv_terms) + # prevent comparison trouble (empty cvterms create empty annotation + # instead of ""empty XML"" annotation frame) + continue + end + model.gene_products[gp] = SBML.GeneProduct( + label = g.label, + name = g.name, + metaid = g.metaid, + notes = g.notes, + #no annotation here + sbo = g.sbo, + cv_terms = g.cv_terms, + ) + end +end + +@testset ""writeSBML"" begin + @testset ""Model Dasgupta2020.xml writes out as expected"" begin + model = readSBML(joinpath(@__DIR__, ""data"", ""Dasgupta2020.xml"")) + fix_constant!(model) + # uncomment the following line to re-create reference XML + #writeSBML(model, joinpath(@__DIR__, ""data"", ""Dasgupta2020-debug.xml"")) + expected = read(joinpath(@__DIR__, ""data"", ""Dasgupta2020-written.xml""), String) + # Remove carriage returns, if any + expected = replace(expected, '\r' => """") + @test @test_logs(writeSBML(model)) == expected + mktemp() do filename, _ + @test_logs(writeSBML(model, filename)) + content = read(filename, String) + # Remove carriage returns, if any + content = replace(content, '\r' => """") + @test content == expected + end + end + + # Make sure that the model we read from the written out file is consistent + # with the original model. + @testset ""Round-trip: $(basename(file))"" for file in first.(sbmlfiles) + round_trip_model_str = @test_logs writeSBML() do + readSBML(file) do m + fix_constant!(m) + remove_some_annotation_strings!(m) + # This is useful for debugging: + # writeSBML(model, file*""-debug.xml"") + return m + end + end + + # re-read the unmodified model, fix constantness and compare again + readSBML(file) do m + fix_constant!(m) + @test m == readSBMLFromString(round_trip_model_str) + end + end +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","test/loadmodels.jl",".jl","20341","552"," +sbmlfiles = [ + # a test model from BIGG + ( + joinpath(@__DIR__, ""data"", ""e_coli_core.xml""), + ""http://bigg.ucsd.edu/static/models/e_coli_core.xml"", + ""b4db506aeed0e434c1f5f1fdd35feda0dfe5d82badcfda0e9d1342335ab31116"", + 72, + 95, + fill(1000.0, 3), + ), + # a relatively new non-curated model from biomodels + ( + joinpath(@__DIR__, ""data"", ""T1M1133.xml""), + ""https://www.ebi.ac.uk/biomodels/model/download/MODEL1909260004.4?filename=T1M1133.xml"", + ""2b1e615558b6190c649d71052ac9e0dc1635e3ad281e541bc7d4fdf2892a5967"", + 2517, + 3956, + fill(1000.0, 3), + ), + # a curated model from biomodels + ( + joinpath(@__DIR__, ""data"", ""Dasgupta2020.xml""), + ""https://www.ebi.ac.uk/biomodels/model/download/BIOMD0000000973.3?filename=Dasgupta2020.xml"", + ""958b131d4df2f215dae68255433542f228601db0326d26a54efd08ddcf823489"", + 2, + 6, + fill(Inf, 3), + ), + # a highly curated model full of features + ( + joinpath(@__DIR__, ""data"", ""yeast-GEM.xml""), + ""https://raw.githubusercontent.com/SysBioChalmers/yeast-GEM/v9.0.0/model/yeast-GEM.xml"", + ""0e120b0d4015048ef2edaf86ea039c533a72827ff00a34ca35d9fbe87a2781e5"", + 2805, + 4130, + fill(1000.0, 3), + ), + # a cool model with `time` from SBML testsuite + ( + joinpath(@__DIR__, ""data"", ""00852-sbml-l3v2.xml""), + SBML.test_suite_url(852, level = 3, version = 2), + ""d013765aa358d265941420c2e3d81fcbc24b0aa4e9f39a8dc8852debd1addb60"", + 4, + 3, + fill(Inf, 3), + ), + # a cool model with assignmentRule for a compartment + ( + joinpath(@__DIR__, ""data"", ""00140-sbml-l3v2.xml""), + SBML.test_suite_url(140, level = 3, version = 2), + ""43f0151c4f414b610b46bb62033fdcc177f4ac5cc39f3fe8b208e2e335c8d847"", + 3, + 1, + fill(Inf, 1), + ), + # another model from SBML suite, with initial concentrations + ( + joinpath(@__DIR__, ""data"", ""00374-sbml-l3v2.xml""), + SBML.test_suite_url(374, level = 3, version = 2), + ""424683eea6bbb577aad855d95f2de5183a36e296b06ba18b338572cd7dba6183"", + 4, + 2, + fill(Inf, 2), + ), + # this contains some special math + ( + joinpath(@__DIR__, ""data"", ""01565-sbml-l3v1.xml""), + SBML.test_suite_url(1565, level = 3, version = 1), + ""14a80fbce316eea2adb566f67b4668ad151db8954e487309852ece7f730c8c99"", + 104, + 52, + fill(Inf, 3), + ), + # this contains l3v1-incompatible contents + ( + joinpath(@__DIR__, ""data"", ""01289-sbml-l3v2.xml""), + SBML.test_suite_url(1289, level = 3, version = 2), + ""35ffa072052970b92fa358ee0f5750394ad74958e889cb85c98ed238642de4d0"", + 0, + 0, + Float64[], + ), + # this contains a relational operator + ( + joinpath(@__DIR__, ""data"", ""00191-sbml-l3v2.xml""), + SBML.test_suite_url(191, level = 3, version = 2), + ""c474e94888767d70f9e9e03b32778f18069641563953de60dabac7daa7f481ce"", + 4, + 2, + fill(Inf, 2), + ), + # expandInitialAssignments converter gives some warning + ( + joinpath(@__DIR__, ""data"", ""01234-sbml-l3v2.xml""), + SBML.test_suite_url(1234, level = 3, version = 2), + ""9610ef29f2d767af627042a15bde505b068ab75bbf00b8983823800ea8ef67c8"", + 0, + 0, + Float64[], + ), + ( + joinpath(@__DIR__, ""data"", ""00489-sbml-l3v2.xml""), + SBML.test_suite_url(489, level = 3, version = 2), + ""dab2bce4e5036fa47ad8137055ca5f6dec6dfcb183542ce38573ca2e5a615813"", + 3, + 2, + fill(Inf, 2), + ), + # has listOfEvents + ( + joinpath(@__DIR__, ""data"", ""00026-sbml-l3v2.xml""), + SBML.test_suite_url(26, level = 3, version = 2), + ""991381015d9408164bf00206848ba5796d0c86dc055be91968cd7f0f68daa903"", + 2, + 1, + fill(Inf, 1), + ), + # has all rules types + ( + joinpath(@__DIR__, ""data"", ""00983-sbml-l3v2.xml""), + SBML.test_suite_url(983, level = 3, version = 2), + ""b84e53cc48edd5afc314e17f05c6a30a509aadb9486b3d788c7cf8df82a7527f"", + 0, + 0, + Float64[], + ), + # has all kinds of default model units + ( + joinpath(@__DIR__, ""data"", ""00054-sbml-l3v2.xml""), + SBML.test_suite_url(54, level = 3, version = 2), + ""987038ec9bb847123c41136928462d7ed05ad697cc414cab09fcce9f5bbc8e73"", + 3, + 2, + fill(Inf, 2), + ), + # has conversionFactor model attribute + ( + joinpath(@__DIR__, ""data"", ""00975-sbml-l3v2.xml""), + SBML.test_suite_url(975, level = 3, version = 2), + ""e32c12b7bebfa8f146b8860cd8b82d5cad326c96c6a0d8ceb191591ac4e2f5ac"", + 2, + 3, + fill(Inf, 3), + ), + # has conversionFactor species attribute + ( + joinpath(@__DIR__, ""data"", ""00976-sbml-l3v2.xml""), + SBML.test_suite_url(976, level = 3, version = 2), + ""6cec83157cd81a585597c02f225e814a9ce2a1c9255a039b3083c97cfe02dd00"", + 2, + 3, + fill(Inf, 3), + ), + # has the Avogadro ""constant"" + ( + joinpath(@__DIR__, ""data"", ""01323-sbml-l3v2.xml""), + SBML.test_suite_url(1323, level = 3, version = 2), + ""9d9121b4f1f38f827a81a884c106c8ade6a8db29e148611c76e515775923a7fc"", + 0, + 0, + [], + ), + # contains initialAssignment + ( + joinpath(@__DIR__, ""data"", ""00878-sbml-l3v2.xml""), + SBML.test_suite_url(878, level = 3, version = 2), + ""5f70555d27469a2fdc63dedcd8d02d50b6f4f1c760802cbb5e7bb17363c2e931"", + 2, + 1, + fill(Inf, 1), + ), +] + +@testset ""Loading of models from various sources - $(reader)"" for reader in ( + readSBML, + readSBMLFromString, +) + for (sbmlfile, url, hash, expected_mets, expected_rxns, expected_3_ubs) in sbmlfiles + if !isfile(sbmlfile) + Downloads.download(url, sbmlfile) + end + + cksum = bytes2hex(sha256(open(sbmlfile))) + if cksum != hash + @warn ""The downloaded model `$sbmlfile' seems to be different from the expected one. Tests will likely fail."" cksum + end + + @testset ""Loading of $sbmlfile"" begin + mdl = if reader === readSBML + readSBML(sbmlfile) + else + readSBMLFromString(readchomp(sbmlfile)) + end + + @test typeof(mdl) == Model + + mets, rxns, _ = stoichiometry_matrix(mdl) + + @test length(mets) == expected_mets + @test length(rxns) == expected_rxns + + lbs, ubs = flux_bounds(mdl) + @test length(lbs) == expected_rxns + @test length(ubs) == expected_rxns + @test first.(ubs)[1:min(3, length(ubs))] == expected_3_ubs + + ocs = flux_objective(mdl) + @test length(ocs) == expected_rxns + end + end +end + +@testset ""readSBMLFromString"" begin + @test_logs (:error, r""^SBML reported error"") @test_throws AssertionError readSBMLFromString( + """", + ) +end + +@testset ""Time variables in math"" begin + # this test is here mainly for keeping a magical constant that we need for + # parsing time synced with libsbml source + contains_time(x::SBML.MathTime) = true + contains_time(x::SBML.MathApply) = any(contains_time.(x.args)) + contains_time(_) = false + + m = readSBML(joinpath(@__DIR__, ""data"", ""00852-sbml-l3v2.xml"")) + @test all(contains_time.(r.kinetic_math for (_, r) in m.reactions)) +end + +@testset ""Units"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""00852-sbml-l3v2.xml"")) + @test SBML.unitful(m.units[""volume""]) == 1 * u""L"" + @test SBML.unitful(m.units[""time""]) == 1 * u""s"" + @test SBML.unitful(m.units[""substance""]) == 1 * u""mol"" + + m = readSBML(joinpath(@__DIR__, ""data"", ""custom.xml"")) + @test SBML.unitful(m.units[""non_existent""]) == 0.00314 + @test SBML.unitful(m.units[""no_dimensions""]) == 20.0 +end + +@testset ""Initial amounts and concentrations"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""00852-sbml-l3v2.xml"")) + + @test all(isnothing(ic) for (k, ic) in SBML.initial_concentrations(m)) + @test length(SBML.initial_amounts(m)) == 4 + @test isapprox(sum(ia for (sp, ia) in SBML.initial_amounts(m)), 0.001) + @test isapprox( + sum(ic for (sp, ic) in SBML.initial_concentrations(m, convert_amounts = true)), + 0.001, + ) + + m = readSBML(joinpath(@__DIR__, ""data"", ""00374-sbml-l3v2.xml"")) + + @test all(isnothing(ic) for (k, ic) in SBML.initial_amounts(m)) + @test length(SBML.initial_concentrations(m)) == 4 + @test isapprox(sum(ic for (sp, ic) in SBML.initial_concentrations(m)), 0.00208) + @test isapprox( + sum(ia for (sp, ia) in SBML.initial_amounts(m, convert_concentrations = true)), + 0.25 * 0.00208, + ) +end + +@testset ""Initial assignments"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""00489-sbml-l3v2.xml"")) + @test m.initial_assignments == + Dict(""S1"" => SBML.MathApply(""*"", [SBML.MathVal{Int32}(2), SBML.MathIdent(""p1"")])) + + m = readSBML(joinpath(@__DIR__, ""data"", ""01289-sbml-l3v2.xml"")) + @test m.initial_assignments == Dict( + ""p2"" => SBML.MathApply(""gt5"", [SBML.MathVal{Int32}(8)]), + ""p1"" => SBML.MathApply(""gt5"", [SBML.MathVal{Int32}(3)]), + ) +end + +@testset ""Rules"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""Dasgupta2020.xml"")) + @test m.rules == [ + SBML.AssignmentRule( + ""s"", + SBML.MathApply( + ""/"", + [ + SBML.MathApply( + ""-"", + [SBML.MathIdent(""ModelValue_6""), SBML.MathIdent(""P"")], + ), + SBML.MathIdent(""N""), + ], + ), + ), + ] + + m = readSBML(joinpath(@__DIR__, ""data"", ""00983-sbml-l3v2.xml"")) + @test m.rules == [ + SBML.RateRule(""x"", SBML.MathVal{Int32}(1)), + SBML.AlgebraicRule( + SBML.MathApply( + ""+"", + [ + SBML.MathApply(""*"", [SBML.MathVal{Int32}(-1), SBML.MathIdent(""temp"")]), + SBML.MathApply(""/"", [SBML.MathTime(""time""), SBML.MathVal{Int32}(2)]), + ], + ), + ), + SBML.AssignmentRule( + ""y"", + SBML.MathApply(""delay"", [SBML.MathIdent(""x""), SBML.MathIdent(""temp"")]), + ), + ] +end + +@testset ""Constraints"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""custom.xml"")) + @test only(m.constraints) == SBML.Constraint( + SBML.MathApply( + ""and"", + [ + SBML.MathApply(""lt"", [SBML.MathVal{Float64}(1.0), SBML.MathIdent(""S1"")]), + SBML.MathApply(""lt"", [SBML.MathIdent(""S1""), SBML.MathVal{Float64}(100.0)]), + ], + ), + "" Species S1 is out of range. "", + ) +end + +@testset ""Extensive kinetic math"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""00852-sbml-l3v2.xml"")) + + subterm = + SBML.extensive_kinetic_math(m, m.reactions[""reaction1""].kinetic_math).args[1].args[2] + @test subterm.fn == ""/"" + @test subterm.args[1] == SBML.MathIdent(""S1"") + @test subterm.args[2] == SBML.MathIdent(""C"") + + m = readSBML(joinpath(@__DIR__, ""data"", ""00140-sbml-l3v2.xml"")) + + subterm = SBML.extensive_kinetic_math(m, m.reactions[""reaction1""].kinetic_math).args[2] + @test subterm.fn == ""/"" + @test subterm.args[1] == SBML.MathIdent(""S1"") + @test subterm.args[2] == SBML.MathIdent(""compartment"") +end + +@testset ""logBase and root math functions"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""01565-sbml-l3v1.xml"")) + + if TEST_SYMBOLICS + @test interpret_as_num(m.reactions[""J23""].kinetic_math) == 0.0 + + @variables S29 S29b + @test isequal(interpret_as_num(m.reactions[""J29""].kinetic_math), 2.0 * S29 * S29b) + end +end + +@testset ""rationals in math"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""custom.xml"")) + @test m.reactions[""rationalTest""].kinetic_math.val == 1 // 5000 +end + +@testset ""converters work and fail gracefully"" begin + @test_logs (:error, r""^SBML reported error:"") (:error, r""^SBML reported error:"") @test_throws ErrorException readSBML( + joinpath(@__DIR__, ""data"", ""01289-sbml-l3v2.xml""), + doc -> begin + set_level_and_version(3, 1)(doc) + convert_simplify_math(doc) + end, + ) + + test_math = readSBML( + joinpath(@__DIR__, ""data"", ""00878-sbml-l3v2.xml""), + doc -> begin + set_level_and_version(3, 1)(doc) + convert_promotelocals_expandfuns(doc) + end, + ).initial_assignments[""S2""] + + @test test_math.fn == ""*"" + @test test_math.args[1].fn == ""*"" + @test test_math.args[1].args[1].id == ""p1"" + @test test_math.args[1].args[2].id == ""S1"" + @test test_math.args[2].id == ""time"" + + test_math = readSBML( + joinpath(@__DIR__, ""data"", ""01565-sbml-l3v1.xml""), + libsbml_convert(""expandInitialAssignments""), + ).reactions[""J31""].kinetic_math + + @test test_math.args[2].fn == ""sin"" + @test test_math.args[2].args[1].val == 2.1 + + @test_logs (:warn,) (:warn,) (:warn,) (:warn,) readSBML( + joinpath(@__DIR__, ""data"", ""01234-sbml-l3v2.xml""), + doc -> libsbml_convert( + ""expandInitialAssignments"", + report_severities = [""Fatal"", ""Error"", ""Warning""], + throw_severities = [""Fatal"", ""Error""], + )( + doc, + ), + ) +end + +@testset ""relational operators are decoded correctly"" begin + test_math = + readSBML(joinpath(@__DIR__, ""data"", ""00191-sbml-l3v2.xml"")).reactions[""reaction2""].kinetic_math + + @test test_math.args[2].fn == ""geq"" +end + +@testset ""custom show"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""custom.xml"")) + @test repr(MIME(""text/plain""), m) == + ""Model with 1 reactions, 0 species, and 0 parameters."" + @test eval(Meta.parse(repr(m))) isa SBML.Model +end + +@testset ""events"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""00026-sbml-l3v2.xml"")) + @test length(m.events) == 1 +end + +@testset ""model attributes"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""00054-sbml-l3v2.xml"")) + @test m.name == ""case00054"" + @test m.id == ""case00054"" + @test isnothing(m.conversion_factor) + @test m.area_units == ""area"" + @test m.extent_units == ""substance"" + @test m.length_units == ""metre"" + @test m.substance_units == ""substance"" + @test m.time_units == ""second"" + @test m.volume_units == ""volume"" + @test isnothing(m.active_objective) + + m = readSBML(joinpath(@__DIR__, ""data"", ""00975-sbml-l3v2.xml"")) + @test m.name == ""case00975"" + @test m.id == ""case00975"" + @test m.conversion_factor == ""modelconv"" + @test isnothing(m.area_units) + @test isnothing(m.extent_units) + @test isnothing(m.length_units) + @test isnothing(m.substance_units) + @test isnothing(m.time_units) + @test isnothing(m.volume_units) + @test isnothing(m.active_objective) + + m = readSBML(joinpath(@__DIR__, ""data"", ""00976-sbml-l3v2.xml"")) + @test m.species[""S1""].conversion_factor == ""S1conv"" +end + +@testset ""names and identifiers of objects"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""e_coli_core.xml"")) + @test m.compartments[""e""].name == ""extracellular space"" + @test m.species[""M_nh4_c""].name == ""Ammonium"" + @test m.species[""M_nh4_c""].sbo == ""SBO:0000247"" + @test length(m.species[""M_nh4_c""].cv_terms) == 1 + @test m.species[""M_nh4_c""].cv_terms[1].biological_qualifier == :is + @test issetequal( + [ + ""http://identifiers.org/bigg.metabolite/nh4"", + ""http://identifiers.org/biocyc/META:AMMONIA"", + ""http://identifiers.org/biocyc/META:AMMONIUM"", + ""http://identifiers.org/chebi/CHEBI:13405"", + ""http://identifiers.org/chebi/CHEBI:13406"", + ""http://identifiers.org/chebi/CHEBI:13407"", + ""http://identifiers.org/chebi/CHEBI:135980"", + ""http://identifiers.org/chebi/CHEBI:13771"", + ""http://identifiers.org/chebi/CHEBI:16134"", + ""http://identifiers.org/chebi/CHEBI:22533"", + ""http://identifiers.org/chebi/CHEBI:22534"", + ""http://identifiers.org/chebi/CHEBI:28938"", + ""http://identifiers.org/chebi/CHEBI:29337"", + ""http://identifiers.org/chebi/CHEBI:29340"", + ""http://identifiers.org/chebi/CHEBI:44269"", + ""http://identifiers.org/chebi/CHEBI:44284"", + ""http://identifiers.org/chebi/CHEBI:44404"", + ""http://identifiers.org/chebi/CHEBI:49783"", + ""http://identifiers.org/chebi/CHEBI:7434"", + ""http://identifiers.org/chebi/CHEBI:7435"", + ""http://identifiers.org/envipath/32de3cf4-e3e6-4168-956e-32fa5ddb0ce1/compound/41e4c903-407f-49f7-bf6b-0a94d39fa3a7"", + ""http://identifiers.org/envipath/5882df9c-dae1-4d80-a40e-db4724271456/compound/27a89bdf-42f7-478f-91d8-e39881581096"", + ""http://identifiers.org/envipath/650babc9-9d68-4b73-9332-11972ca26f7b/compound/96667bd9-aeae-4e8f-89d3-100d0396af05"", + ""http://identifiers.org/hmdb/HMDB00051"", + ""http://identifiers.org/hmdb/HMDB41827"", + ""http://identifiers.org/inchi_key/QGZKDVFQNNGYKY-UHFFFAOYSA-O"", + ""http://identifiers.org/kegg.compound/C00014"", + ""http://identifiers.org/kegg.compound/C01342"", + ""http://identifiers.org/kegg.drug/D02915"", + ""http://identifiers.org/kegg.drug/D02916"", + ""http://identifiers.org/metanetx.chemical/MNXM15"", + ""http://identifiers.org/reactome.compound/1132163"", + ""http://identifiers.org/reactome.compound/113561"", + ""http://identifiers.org/reactome.compound/140912"", + ""http://identifiers.org/reactome.compound/2022135"", + ""http://identifiers.org/reactome.compound/29382"", + ""http://identifiers.org/reactome.compound/31633"", + ""http://identifiers.org/reactome.compound/389843"", + ""http://identifiers.org/reactome.compound/5693978"", + ""http://identifiers.org/reactome.compound/76230"", + ""http://identifiers.org/sabiork/1268"", + ""http://identifiers.org/sabiork/43"", + ""http://identifiers.org/seed.compound/cpd00013"", + ""http://identifiers.org/seed.compound/cpd19013"", + ], + m.species[""M_nh4_c""].cv_terms[1].resource_uris, + ) + @test m.gene_products[""G_b1241""].name == ""adhE"" + @test m.gene_products[""G_b1241""].sbo == ""SBO:0000243"" + @test length(m.gene_products[""G_b1241""].cv_terms) == 1 + @test m.gene_products[""G_b1241""].cv_terms[1].biological_qualifier == :is + @test issetequal( + [ + ""http://identifiers.org/asap/ABE-0004164"", + ""http://identifiers.org/ecogene/EG10031"", + ""http://identifiers.org/ncbigene/945837"", + ""http://identifiers.org/ncbigi/16129202"", + ""http://identifiers.org/refseq_locus_tag/b1241"", + ""http://identifiers.org/refseq_name/adhE"", + ""http://identifiers.org/refseq_synonym/adhC"", + ""http://identifiers.org/refseq_synonym/ana"", + ""http://identifiers.org/refseq_synonym/ECK1235"", + ""http://identifiers.org/refseq_synonym/JW1228"", + ""http://identifiers.org/uniprot/P0A9Q7"", + ], + m.gene_products[""G_b1241""].cv_terms[1].resource_uris, + ) + @test m.reactions[""R_PFK""].name == ""Phosphofructokinase"" + @test m.reactions[""R_PFK""].sbo == ""SBO:0000176"" + @test length(m.reactions[""R_PFK""].cv_terms) == 1 + @test m.reactions[""R_PFK""].cv_terms[1].biological_qualifier == :is + @test issetequal( + [ + ""http://identifiers.org/bigg.reaction/PFK"", + ""http://identifiers.org/ec-code/2.7.1.11"", + ""http://identifiers.org/metanetx.reaction/MNXR102507"", + ""http://identifiers.org/rhea/16109"", + ""http://identifiers.org/rhea/16110"", + ""http://identifiers.org/rhea/16111"", + ""http://identifiers.org/rhea/16112"", + ], + m.reactions[""R_PFK""].cv_terms[1].resource_uris, + ) + @test m.parameters[""cobra_default_ub""].sbo == ""SBO:0000626"" + @test m.active_objective == ""obj"" +end + +@testset ""constantness"" begin + m = readSBML(joinpath(@__DIR__, ""data"", ""00975-sbml-l3v2.xml"")) + @test m.species[""S1""].constant == false + @test m.parameters[""S1conv""].constant == true +end +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","docs/make.jl",".jl","539","22","using Documenter, SBML + +makedocs( + modules = [SBML], + clean = false, + format = Documenter.HTML( + prettyurls = !(""local"" in ARGS), + canonical = ""https://lcsb-biocore.github.io/SBML.jl/stable/"", + ), + sitename = ""SBML.jl"", + authors = ""The developers of SBML.jl"", + linkcheck = !(""skiplinks"" in ARGS), + pages = [""Home"" => ""index.md"", ""Reference"" => ""functions.md""], +) + +deploydocs( + repo = ""github.com/LCSB-BioCore/SBML.jl.git"", + target = ""build"", + branch = ""gh-pages"", + push_preview = false, +) +","Julia" +"Metabolic","LCSB-BioCore/SBML.jl","docs/src/functions.md",".md","884","70"," +# Data types + +## Helper types + +```@autodocs +Modules = [SBML] +Pages = [""types.jl""] +``` + +## Model data structures + +```@autodocs +Modules = [SBML] +Pages = [""structs.jl""] +``` + +# Base functions + +```@autodocs +Modules = [SBML] +Pages = [""SBML.jl""] +``` + +## Loading, writing and versioning + +```@autodocs +Modules = [SBML] +Pages = [""readsbml.jl"", ""writesbml.jl"", ""version.jl""] +``` + +## `libsbml` representation converters + +The converters are intended to be used as parameters of [`readSBML`](@ref). + +```@autodocs +Modules = [SBML] +Pages = [""converters.jl""] +``` + +# Helper functions + +## Data accessors + +```@autodocs +Modules = [SBML] +Pages = [""utils.jl""] +``` + +## Units support + +```@autodocs +Modules = [SBML] +Pages = [""unitful.jl""] +``` + +## Math interpretation + +```@autodocs +Modules = [SBML] +Pages = [""interpret.jl""] +``` + +### Internal math helpers + +```@autodocs +Modules = [SBML] +Pages = [""math.jl""] +``` +","Markdown" +"Metabolic","LCSB-BioCore/SBML.jl","docs/src/index.md",".md","2301","73"," +# SBML.jl — load systems biology models from SBML files + +This package provides a straightforward way to load model- and +simulation-relevant information from SBML files. + +The representation does not follow the XML structure within SBML, but instead +translates the contents into native Julia structs. This makes the models much +easier to work with from Julia, + +## Quick-start + +The ""main"" function of the library is [`readSBML`](@ref), which does exactly +what it says: loads a SBML model from disk into the [`SBML.Model`](@ref): + +```julia +julia> using SBML +julia> mdl = readSBML(""Ec_core_flux1.xml"") +SBML.Model(…) + +julia> mdl.compartments +2-element Array{String,1}: + ""Extra_organism"" + ""Cytosol"" +``` + +There are several functions that help you with using the data in the usual +COBRA-style workflows, such as [`stoichiometry_matrix`](@ref). Others are +detailed in the relevant sections of the [function reference](functions.md). + +```julia +julia> metabolites, reactions, S = stoichiometry_matrix(mdl) +julia> metabolites +77-element Array{String,1}: + ""M_succoa_c"" + ""M_ac_c"" + ""M_etoh_c"" + ⋮ + +julia> S +77×77 SparseArrays.SparseMatrixCSC{Float64,Int64} with 308 stored entries: + [60, 1] = -1.0 + [68, 1] = 1.0 + [1 , 2] = 1.0 + [6 , 2] = -1.0 + ⋮ + [23, 76] = 1.0 + [56, 76] = -1.0 + [30, 77] = -1.0 + [48, 77] = 1.0 + +julia> Matrix(S) +77×77 Array{Float64,2}: + 0.0 1.0 0.0 0.0 0.0 0.0 0.0 … 0.0 0.0 0.0 0.0 0.0 0.0 0.0 + 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 + 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 + 0.0 0.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 + 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 + 0.0 -1.0 0.0 0.0 0.0 0.0 0.0 … 0.0 0.0 0.0 0.0 0.0 0.0 0.0 + 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 -1.0 0.0 0.0 0.0 + 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 + 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 + 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 -1.0 0.0 0.0 0.0 0.0 0.0 + ⋮ ⋮ ⋱ ⋮ ⋮ +``` + +## Table of contents + +```@contents +Pages = [""functions.md""] +Depth = 2 +``` +","Markdown" +"Metabolic","zhanglab/psamm","setup.py",".py","5852","147","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import print_function + +import sys +from setuptools import setup, find_packages +import pkg_resources + +# Read long description +with open('README.rst') as f: + long_description = f.read() + +# Test whether psamm-import is currently installed. Since the psamm-import +# functionality was moved to this package (except Excel importers), only newer +# versions of psamm-import are compatible with recent versions of PSAMM. +try: + pkg_resources.get_distribution('psamm-import <= 0.15.2') +except (pkg_resources.DistributionNotFound, + pkg_resources.VersionConflict): + pass +else: + msg = ( + 'Please upgrade or uninstall psamm-import before upgrading psamm:\n' + '$ pip install --upgrade psamm-import\n' + ' OR\n' + '$ pip uninstall psamm-import' + '\n\n' + ' The functionality of the psamm-import package has been moved into' + ' the psamm package, and the psamm-import package now only contains' + ' the model-specific Excel importers.') + print(msg, file=sys.stderr) + sys.exit(1) + + +setup( + name='psamm', + version='1.2.1', + description='PSAMM metabolic modeling tools', + maintainer='Jon Lund Steffensen', + maintainer_email='jon_steffensen@uri.edu', + url='https://github.com/zhanglab/psamm', + license='GNU GPLv3+', + + long_description=long_description, + + classifiers=[ + 'Development Status :: 4 - Beta', + ( + 'License :: OSI Approved :: ' + 'GNU General Public License v3 or later (GPLv3+)'), + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + ], + + package_data={'psamm': ['external-data/chebi_pH7_3_mapping.tsv', + 'external-data/biomass_compound_descriptions.tsv', + 'external-data/biomass_reaction_descriptions.tsv', + 'external-data/tcdb_substrates.tsv', + 'external-data/tcdb_families.tsv', + 'external-data/biomass_compound_descriptions.tsv', + 'external-data/biomass_reaction_descriptions.tsv']}, + + packages=find_packages(), + + entry_points=''' + [console_scripts] + psamm-model = psamm.command:main + psamm-sbml-model = psamm.command:main_sbml + psamm-list-lpsolvers = psamm.lpsolver.generic:list_solvers + psamm-import = psamm.importer:main + psamm-import-bigg = psamm.importer:main_bigg + psamm-generate-model = psamm.generate_model:main + + [psamm.commands] + chargecheck = psamm.commands.chargecheck:ChargeBalanceCommand + console = psamm.commands.console:ConsoleCommand + dupcheck = psamm.commands.duplicatescheck:DuplicatesCheck + excelexport = psamm.commands.excelexport:ExcelExportCommand + fastgapfill = psamm.commands.fastgapfill:FastGapFillCommand + fba = psamm.commands.fba:FluxBalanceCommand + fluxcheck = psamm.commands.fluxcheck:FluxConsistencyCommand + fluxcoupling = psamm.commands.fluxcoupling:FluxCouplingCommand + formulacheck = psamm.commands.formulacheck:FormulaBalanceCommand + fva = psamm.commands.fva:FluxVariabilityCommand + gapcheck = psamm.commands.gapcheck:GapCheckCommand + gapfill = psamm.commands.gapfill:GapFillCommand + genedelete = psamm.commands.genedelete:GeneDeletionCommand + gimme = psamm.commands.gimme:GimmeCommand + masscheck = psamm.commands.masscheck:MassConsistencyCommand + primarypairs = psamm.commands.primarypairs:PrimaryPairsCommand + randomsparse = psamm.commands.randomsparse:RandomSparseNetworkCommand + robustness = psamm.commands.robustness:RobustnessCommand + sbmlexport = psamm.commands.sbmlexport:SBMLExport + search = psamm.commands.search:SearchCommand + tableexport = psamm.commands.tableexport:ExportTableCommand + psammotate = psamm.commands.psammotate:PsammotateCommand + modelmapping = psamm.commands.model_mapping:ModelMappingCommand + vis = psamm.commands.vis:VisualizationCommand + tmfa = psamm.commands.tmfa:TMFACommand + + [psamm.importer] + JSON = psamm.importers.cobrajson:Importer + SBML = psamm.importers.sbml:NonstrictImporter + SBML-strict = psamm.importers.sbml:StrictImporter + MATLAB = psamm.importers.matlab:Importer + + [psamm.generate_model] + generate-database = psamm.generate_model:main_databaseCommand + generate-biomass = psamm.generate_biomass:main + generate-transporters = psamm.generate_model:main_transporterCommand + ''', + + test_suite='psamm.tests', + + install_requires=[ + 'pyyaml>=4.2b1', + 'six', + 'xlsxwriter', + 'numpy', + 'scipy', + 'future', + 'pandas', + ], + extras_require={ + 'docs': ['sphinx', 'sphinx_rtd_theme', 'mock'] + }) +","Python" +"Metabolic","zhanglab/psamm","NEWS.md",".md","32318","670","v1.2.1 (2022-05-12) +------------------ +- fix bug in `generate-database` +- revise formatting of doc + +v1.2 (2022-05-10) +------------------ + +- Adds the new `psamm-generate-model command` with the options of + `generate-database`, `generate-transporters`, and `generate-biomass`, + which construct metabolic models in the KEGG namespace +- Adds the new option _translated-reactions_ to the `tableexport` command +- Added translated reactions to `excelexport` +- Fixed compatibility in documentation for Gurobi for python versions 3.7 +- Adds support for Python 3.8 and 3.9 + + +v1.1.2 (2021-05-10) +------------------ + +- Drops support for Python 2.7 (deprecated Jan. 01, 2020), 3.3, and 3.4 +- Adds the --phin and --phout options to the `tmfa` command +- Adds descriptive counts of the number of reactions and compounds + curated in the _manual curation_ option of `modelmapping` + + +v1.1.1 (2020-12-18) +------------------ + +- Fix bug where the `psamm modelmapping translate_id` command requires + the undefined parameter `--dest-model` + + +v1.1 (2020-12-11) +------------------ + +- Adds the new `vis` command for visualizing metabolic pathways and + networks +- Adds the new `tmfa` command to implement the approach as described + in Henry et al., 2007 (PMID: 17172310) and Hamilton et al., 2013 + (PMID: 23870272). +- Performance updates to the `model-mapping` command +- Updates to export full models from `gimme` and `psammotate` +- Added the --fva option to the `robustness` command + + +v1.0 (2020-03-03) +------------------ + +- Adds the new `modelmapping` command for mapping reactions and + compounds ids between different GEMs. +- Adds the new `psammotate` command for generating draft GEMs + using a template model and a mapping of orthologous genes to + another organism. +- Adds the new `gimme` command which implements the GIMME algorithm + as described in Becker and Palsson, 2008 (PMID: 18483554). +- Updates the `search` command to allow for searching of strings + within any reaction or compound property. +- Updates to the `tableexport` and `excelexport` commands to allow + for the export of additional gene and reaction information. +- Adds new section to the tutorial to detail how to use the + `findprimarypairs` commands. +- Renamed `duplicatescheck` command to `dupcheck`. + +v0.31 (2017-06-30) +------------------ + +- The `psamm-import` tool has been moved from the `psamm-import` package to + the main PSAMM package. This means that to import SBML files the + `psamm-import` package is no longer needed. To use the model-specific Excel + importers, the `psamm-import` package is still needed. With this release + of PSAMM, the `psamm-import` package should be updated to at least 0.16. +- The tutorial was updated with additional sections on using gap-filling + procedures on models. + +v0.30 (2017-06-23) +------------------ + +- Adds the new command `primarypairs` for predicting reactant/product element + transfers using the new FindPrimaryPairs method as well as the MapMaker + method. +- A new option has been added to the `genedelete` command which allows use of + _minimization of metabolic adjustments_ to simulate biomass production for + gene knockouts. +- Fixes a bug where the epsilon parameter was accidentally ignored by + `fastgapfill`. +- Fixes a bug where the `psamm-sbml-model` command did not ignore boundary + species. With this change, the boundary species are also ignored by default + when using the API to read SBML models. +- Fixes a performance issues with gap-filling that made the `gapfill` and + `fastgapfill` commands take much longer time to run on large models than + necessary. + +v0.29 (2017-04-18) +------------------ + +- [The tutorial](https://psamm.readthedocs.io/en/stable/tutorial.html) in the + PSAMM documentation has been updated and expanded to include additional + information on using PSAMM for model curation and constraint-based analyses. +- The experimental command `psamm-sbml-model` was added which makes it possible + to run any command from `psamm-model` (e.g. `fba`, `robustness`, etc.) + directly on an SBML file. For now this only supports SBML level 3 files with + FBC. This provides a quick way of running basic analyses on SBML files. We + still recommend importing the SBML file to YAML format with `psamm-import` + for anyone wishing to make changes to a model. +- Fixes access to charge parameter parsed from SBML files. The charge is now + correctly imported with `psamm-import`. +- Fixes import of compartments from SBML files. The empty boundary compartments + are now no longer included in the import. +- Fixes bug in writing the reaction flux limits sheet of the `excelexport` + command. +- The `console` command was changed to only provide the `model` variable since + the metabolic model can easily be created. + +v0.28 (2017-03-03) +------------------ + +- The YAML model format now allows users to specify compartment information and + compartment boundaries in the `model.yaml` file. See the file format + documentation for more information. +- The `media` key in the `model.yaml` has changed name to `exchange` to + reflect the fact that not only uptake exchange must be defined here. The + `media` key is still supported but has been deprecated. +- The gap-filling command `gapfill` and `fastgapfill` now use the compartment + information to determine which artificial transport and exchange reactions + to add. This means that a model *must* specify compartments and compartment + boundaries when using gap-filling commands. +- The `gapcheck` command now has two new methods for detecting blocked + compounds. The new `prodcheck` is a more robust version of the GapFind check + which was previously used. The new `sinkcheck` method will find compounds + that cannot be produced in excess. This can find some additional blocked + compounds that were not detected by the other methods. +- The `gapcheck` command now reports blocked compounds in the extracellular + space. Previously, these compounds were excluded. An option is available to + switch back the old behavior of excluding these from the final output. +- The `gapcheck` command now has an option to run the check with unrestricted + exchange reactions. +- The `gapfill` command can now be run without implicit sinks. This makes it + possible to use this command to solve additional model gaps. It is still + recommended to first solve gaps using implicit sinks, then later disable + implicit sinks when all other gaps have been closed. +- The `gapfill` command now has an option to enable the bounds expansion + proposals (e.g. making irreversible reactions reversible). By default this + option is now off. +- The `fastgapfill` has improved output that contains less superfluous + information. The output format is now identical to the `gapfill` command. + The `fastgapfill` also no longer runs an FBA on the induced model since this + caused some confusion. +- Added new command `checkduplicates` which detects whether the model has + multiple reactions with the same (or similar) reaction equation. +- The `sbmlexport` command now allows the user to specify a file path. The + command can also optionally output the SBML file in a more readable format + with an option. +- Fixed support for the latest CPLEX release 12.7. A change in their API made + PSAMM incompatible with the 12.7 release. This is now fixed. +- We now officially support Python 3.5 and Python 3.6. + +v0.27 (2016-12-23) +------------------ + +- When exporting a model with `excelexport`, `sbmlexport` or `tableexport`, the + current Git commit ID of the model is now part of the export. +- The `gapfill` command has been split into two separate commands. The new + command `gapcheck` only reports which compounds are blocked without + trying to fill gaps. The `gapfill` command now only reports the suggested + reactions for gap-filling. +- The `tableexport` command has been made more robust when the model properties + contain special characters or structured data. Strings containing tabs or + newline characters are now quoted in the output. +- Improved error messages for multiple commands when reactions with forced + flux (e.g. ATP maintenance reactions) impose impossible constraints. + +v0.26 (2016-11-17) +------------------ + +- All commands that perform loop removal now use the option `--loop-removal` to + set the type of loop removal. The `--tfba` option is no longer available for + the `fva`, `fluxcheck` and `randomsparse` commands, instead + `--loop-removal=tfba` should be used. +- All simulation commands that perform a maximization of an objective now take + an `--objective` option that can be used to override the `biomass` reaction + set in the model. The commands `fba` and `fva` no longer allow positional + arguments to set the objective, instead the `--objective` option should be + used. +- All user data in the model is now exported with the `sbmlexport` command. + User data that cannot be translated into a standard machine-readable SBML + form will instead be stored in the SBML notes section. +- The output from the `gapfill` command now shows the complete induced model + (like `fastgapfill`) and also lists the compound IDs of the blocked + compounds. +- The `gapfill` command will now propose the removal of flux bounds if such a + modification can unblock the model. +- The `gapfill` command now excludes the biomass reaction from being modified + in the induced model. Previously the biomass reaction was sometimes reversed + in the induced model but this is usually not a desired solution. +- The `gapfill` command now allows the user to specify penalties on added or + modified reactions (like `fastgapfill`). +- The `gapfill` command was changed so the `--epsilon` option now + specifies the threshold for non-zero reaction fluxes (like the `--epsilon` + in other PSAMM commands). +- The `gapfill` command was changed to be more robust when handling small + epsilon values. It will now lower the solver thresholds if necessary and will + generate a warning when epsilon is too low. This fixes an issue where + `gapfill` would previously fail or generate incorrect results with some + models. +- Fixed: The `--exclude` option in the `formulacheck` command did not work + correctly. + +v0.25 (2016-10-28) +------------------ + +- Fixed an error parsing decimal values in reactions which resulted in a + failure to run FBA and other analyses on certain models. +- The `fastgapfill` command no longer tries to unblock exchange reactions by + default. Only internal reactions will be unblocked by default. +- The `fastgapfill` command has a new `--subset` option to explicitly specify + set of reactions to unblock. This means that the command can now be used to + unblock a specific reaction. +- The weight options on `fastgapfill` have changed name to `--db-penalty`, + `--tp-penalty` and `--ex-penalty` for consistency with the existing + `--penalty` option. +- Fixed an error in `gapfill` that in some cases would result in a compound + incorrectly marked as non-blocked. +- The `sbmlexport` command now follows the FBCv2 specification for writing + flux bounds, biomass reaction, gene products and various other properties to + SBML files. +- The `sbmlexport` command now uses the same ID for compartment IDs as used + in the YAML files. +- The order of compounds in the output from commands now reflects the order + of compounds in the reactions as specified in the model files. +- Experimental support for solving MILP problems with GLPK has been activated. + +v0.24 (2016-08-23) +------------------ +- When specifying flux bounds in media and limits, the `fixed` key can now be + used when lower and upper limits are the same. +- New column in output of `excelexport` and `tableexport` commands to + indicate if reactions and compounds are in the model. +- Zero mass compounds are now omitted from the output of the `massconsistency` + command. +- When exporting SBML file using the `sbmlexport` command, the exported + compounds and reactions now have IDs that are based on the YAML model IDs. + Characters that are not allowed in SBML IDs are transformed in a way that is + compatible with COBRA. + +v0.23 (2016-07-26) +------------------ + +- Fix a bug where no output of the `randomsparse` command was produced. +- Make Cplex interface in PSAMM compatible with earlier versions + (12.6 and 12.6.1) again. + +v0.22 (2016-07-01) +------------------ + +- Better unicode handling in commands. +- When running the `gapfill` command the epsilon parameter can now be + specified on the command line. +- When parsing reaction and compound entities from the YAML files, produce + better error messages when IDs are invalid. +- Work around a bug in Cplex that in rare causes a segmentation fault when a + linear programming problem is solved repeatedly. +- API: Add `fastgapfill` module which allows access to run the fastGapFill + algorithm. +- API: Add `randomsparse` module which allows access to generate a random + minimal model which satisfies the flux threshold of the objective reaction. + +v0.21 (2016-06-09) +------------------ + +- Add `genedelete` command to allow users to delete one or more genes and + perform a viability check on the model after all related reactions are + deleted. +- Add `balancecheck` module which allows API access to charge balance and + formula balance checks. +- When a compound in the extracellular space doesn't have an exchange reaction, + a warning would be provided so that the user may add the compound to the + medium. +- If a compartment is not given for a medium, it will now be assumed to have + the extracellular compartment. +- When using Gurobi and Cplex, the default optimality tolerance and feasibility + tolerance has been decreased to 1e-9. +- Fixed a bug where the reaction IDs are not printed properly in the result of + `chargecheck` command. + +v0.20 (2016-03-10) +------------------ + +- Added experimental support for GLPK solver. MILP problems are not yet + supported with this solver. GLPK also appears to have some issues with + `fastgapfill`. +- The `gapfill` command can now take a list of compounds on the command line + that it will try to unblock. If a list of compounds is given, the command + will not run GapFind but instead only use those compounds. +- Remove the assumption that the extracellular compartment is always called + `e`. The user can now specify the name of the extracellular compartment with + the option `extracellular` in `model.yaml`. +- In a previous release, the code interfacing with Cplex was updated and is now + using an interface in Cplex that was introduced in version 12.6.2. The + documentation now makes it clear that at least version 12.6.2 is required. +- Update YAML format documentation on the model definition table format. +- Work around issue with `pkg_resources` that resulted in import errors when + running from IPython. + +v0.19 (2016-02-01) +------------------ + +- When using Gurobi, the option `--solver threads=X` can now be used to specify + the maximum number of threads that Gurobi can use. +- The log messages from external libraries are more clearly marked as such. + In particular, there should now be less confusion about the origin of the + log messages from Cplex. +- Internally, the LP solvers now support quadratic objectives. This will be + used for various commands in the future. +- Fix an error where an empty reaction would internally be detected as an + exchange reaction. +- Fix a bug where the compounds in the extracellular compartment were not + correctly detected by `gapfill`. +- Update documentation with information on how to cite the PSAMM publication. + +v0.18 (2016-01-04) +------------------ + +- Several commands now support parallelization with the `--parallel` option + (`fva`, `fluxcheck`, `fluxcoupling`, `robustness`). +- A more robust reaction parser is now used to parse reaction equations in + YAML files. This also means that quoting compound names with pipes (`|`) is + now optional. + +v0.17 (2015-12-07) +------------------ + +- When loading native models, PSAMM now uses the PyYAML safe loader and also + uses the optimized CSafeLoader if present. This speeds up the start time of + commands. +- Various additional optimizations to model loading have been added. This + speeds up the start time of some commands. +- The `fba` command now shows the genes associated with each reaction for a + quick overview of which genes influence the flux solution. +- The `sbmlexport` command now properly exports gene association information. +- All commands better handle output that contains unicode characters. In + previous versions this would often fail when using Python 2. + +v0.16 (2015-12-01) +------------------ + +- Add an option to `randomsparse` to perform the deletion based on genes + instead of reactions. This uses the gene association expression defined in + the reaction property `genes`. +- Add threshold option to `fva` command. +- Fix bugs in `gapfill` that resulted in the procedure not detecting reactions + that could be reversed, and sometimes failing to find a result at all. +- Add epsilon option to `chargecheck` and ignore charge imbalances below the + epsilon value. +- Allow the `search` command to find reactions containing a specific compound + even when the compartment is not specified. +- Output more information is the result of the `search` command. +- Improved handling of flux bounds at infinity (e.g. with + `default_flux_limit = .inf` in `model.yaml`). + +v0.15 (2015-10-16) +------------------ + +- Add support for reading flux bounds and objectives from SBML files that are + using the FBC extension. +- Add a tutorial to the documentation at . +- Add command `tableexport` to export various parts of the model as a TSV file. +- Add command `excelexport` to export all parts of the model as an Excel file. +- Allow various parameters that take a reaction as an argument to also be able + to take a list of reactions from a file, using the `@` prefix. For example, + given a file `r.txt` with each reaction ID on a separate line, the reactions + can be excluded from the `masscheck` command by specifying + `--exclude @r.txt`. +- Allow reactions to be excluded from the `formulacheck` and `chargecheck` + commands. + +v0.14 (2015-10-05) +------------------ + +- Split the `masscheck` command into two parts. The compound check is run be + default or when `--type compound` is specified. The reaction check is run + when `--type reaction` is specified. This also changes the output of the + compound list to be TSV formatted. +- Change the default method of finding flux inconsistent reactions to simply + use FVA without constraints to determine whether reactions can take a + non-zero flux. This requires more LP optimizations to run but it turns out + to be faster in practice. To enable the old behavior where the number of LP + problems to solve is reduced, use `--reduce-lp`. +- Disable tFBA by default in the FBA performed as part of running + `fastgapfill`. +- Return non-zero from the `psamm-list-lpsolvers` when no solver is available. +- Report time to solve most commands excluding the time it takes to load the + model. +- Improve stability when using thermodynamic constraints. This means that + commands using thermodynamic constraints that previously failed with some + models will now work. +- Speed up changing the objective when using Cplex. This significantly speeds + up commands that reuse LP problem instances with different objectives (e.g. + `fva` and `fluxcheck`). +- Speed up fastcore algorithms (i.e. `fluxcheck --fastcore` and `fastgapfill`) + by reusing the LP problem instances. +- Propagate user aborts from Cplex to Python by raising `KeyboardInterrupt` + when a user abort is detected. This fixes a problem where a user abort would + result in a `FluxBalanceError`. +- Improve unit tests of commands, the `native` datasource module, + `fluxanalysis`, and various other parts of the software. + +v0.13 (2015-09-16) +------------------ + +- Change parsing of medium definitions to combine all parts of the medium into + one final medium used for simulations. Previously, the entries in the + `media` key would be considered as separate media and only the first entry + would be used. +- Fix parsing of limits table format to make it consistent with the medium + table format. +- Change the name of option `--reaction` to `--objective` for commands that + take an optional reaction flux to maximize. +- Change the default of commands that use thermodynamic constraints on FBA + problems to _not_ apply the additional constraints by default. The commands + have an option to enable thermodynamic constraints. +- Change the `--no-tfba` option of the commands `fba` to `robustness` to + `--loop-removal`. The loop removal option allows the L1 minimization method + to be selected as a loop removal method in addition to the thermodynamic + constraints. +- Add option to `robustness` command to print all fluxes. By default only the + objective is shown. +- In `robustness`, obtain the lower and upper bounds of the varying reaction + by minimizing and maximizing the reaction flux. This avoids trying to solve + many LP problems that are infeasible and instead provides more samples from + the flux range that is known to be feasible. +- Fix a bug in `robustness` that caused thermodynamic constraints to never be + enabled properly. +- Fix bug where parsing medium from table would fail. +- Produce a warning when a compound is referenced from a reaction but not + defined in the list of compounds. +- During SBML import produce a warning when `_b`-suffix compounds are + converted to boundary compounds in non-strict mode. +- Improve the efficiency of creating long linear expressions for the LP + solver interface. This should speed up certain procedures that use long + expression as objectives or constraints. +- Improve the efficiency of resolving variable names in Cplex LP problems by + using column indices directly. This significantly speeds up procedures using + many variables when using Cplex as the solver. + +v0.12.1 (2015-09-01) +-------------------- + +- Fix tiny bug in setup.py resulting in failure to upload the 0.12 package to + PyPI. + +v0.12 (2015-09-01) +------------------ + +- Add support for the Gurobi LP solver (Python 2.7 only). +- Fix a bug in the `fastgapfill` command that caused the biomass reaction to + never be found in the model. +- Add command line tool `psamm-list-lpsolvers` which will list the available + solvers, and report their attributes and whether they can be successfully + loaded. +- Change the way the threshold parameter on the `randomsparse` command is + parsed. A threshold relative to the maximum flux is now given using + percentage notation (e.g. `95%`) while an absolute flux threshold is given as + a number (e.g `1.34`). +- Log the model name at the beginning of every command. If the model exists in + a Git repository, the current Git commit ID is also reported. +- Produce warnings when encountering invalid SBML constructs using non-strict + parsing. Previously, some of these could only be noticed when using the + strict mode. +- Improve error reports from commands. This means that usage information is now + printed when a command fails to parse an argument. +- Improve the API in the `fluxanalysis` module to allow commands to more + easily reuse LP problems. This improves the speed of robustness analysis in + particular. +- Improve and expand the install instructions in the documentation. +- Reorganize implementations of commands into the `psamm.commands` package. The + commands are now discovered through the entry point mechanism from + `setuptools` allowing any package to install additional commands into the + PSAMM user interface. +- Use a simpler output format for log messages unless the environment variable + `PSAMM_DEBUG` is set. If set, this variable determines the logging level + (e.g. `PSAMM_DEBUG=debug` enables more messages). +- Include Python 3.3 in the tox test suite. + +v0.11 (2015-08-06) +------------------ + +- Add new flux coupling analysis command and API module. +- Add parser for KEGG reaction files. +- Export COBRA-compatible flux constraints when exporting to SBML. +- Improve the command descriptions in the command line interface. +- Extend the search command to report information on which file the + compound/reaction was parsed from. +- Add support for Python 3.4. +- Fix Fastcore unit tests that failed using an exact solver. +- Change unit tests to allow covering solvers other than Cplex. +- Optionally use tox for unit test management. This allows independently + testing with multiple versions of Python and with different solvers. +- Adapt code to conform to PEP-8. + +v0.10.2 (2015-05-22) +-------------------- + +- Various minor documentation and packaging updates. PSAMM is now available + through [PyPI](https://pypi.python.org/pypi/psamm) and the documentation has + been updated to reflect this. The documentation is available through + [Read the Docs](https://psamm.readthedocs.org/). Lastly, the test suite is + automatically run by [Travis CI](https://travis-ci.org/zhanglab/psamm). + +v0.10.1 (2015-05-21) +-------------------- + +- Update README with new repository names and improved install instructions. +- docs: Add improved install instructions based on README. + +v0.10 (2015-05-14) +------------------ + +- This software is now GPLv3 licensed. A copy of the license is included in + [LICENSE](LICENSE). +- Allow setting the default flux limit in `model.yaml`. Previously a limit + of 1000 units was used, and this value is still used if not specified. +- Allow setting the reaction name of the implicit exchange reactions + specified in the medium definition. +- sbml: Change the SBML writer to avoid negative values for reaction + stoichiometry. Some software packages do not handle negative values + correctly when loading SBML files. +- command: Add a new option to `fluxcheck` where the restrictions imposed on + the exchange reactions are removed before the consistency check. +- cplex: Use numerical emphasis mode by default. + +v0.9 (2015-05-07) +----------------- + +- Add methods the internal metabolic model representation to provide the + compartments. This is used by commands instead of hardcoding specific + model compartments when running `gapfill` or `fastgapfill`. +- docs: Update documentation on `psamm-model` commands. +- docs: Update information on installing the linear programming solvers. + +v0.8 (2015-04-30) +----------------- + +- The name of the project (in `setup.py`) changed name to `psamm`. +- The name of the main package changed from `metnet` to `psamm`. +- Remove unused scripts related to obsolete GAMS modeling. +- Assume TSV format for `.tsv` compound files. This removes the need for + explicitly specifying `format: tsv` in the include. +- By default FVA and the flux consistency check will apply thermodynamic + constraints. A command line option was added to go back to the previous + behavior. +- Properly report compound names when multiple files are included. +- Add possibility of supplying additional solver parameters through the command + line. Currently, the Cplex solver supports the parameters `threads` (the max + number of threads allowed globally) and `feasibility_tolerance` (how much the + basic variables of a model are allowed to violate their bounds). +- command: The command `randomsparse` now defaults to normal FBA without + thermodynamic constraints. This is much faster and the additional constraints + are guaranteed to not change the result in this case. +- docs: Enabled napoleon Sphinx extension for Google-style docstring support. + This makes docstrings more readable while at the same time improving the + generated docs. The `fluxanalysis` module was updated with additional + documentation in this format. +- fluxanalysis: Change the API so that the `tfba` parameter can be given to + functions that support thermodynamic constraints to select this mode. The + support for thermodynamic constraints was extended to the flux consistency + check and FVA. +- fluxanalysis: Slightly improve FVA by avoiding copying the model. +- sbml: Provide access to species charge. +- qsoptex: Fix error when calling the `status()` method of a result. +- command: Add option to see current version. + +v0.7 (2015-04-23) +----------------- + +- Change name of `model` script to `psamm-model`. +- native: Add YAML format for flux limits. The documentation has been updated + to include more information on this format. This changes the `limits` key in + `model.yaml` to a list of dicts. +- Add `--exchange` option to the `randomsparse` command to find random + minimal sets of exchange reactions. +- Change name of `fluxconsistency` command to `fluxcheck`. +- Allow compounds to be marked as zero-mass (e.g. photons) by setting + `zeromass: yes`. These compounds will be exempt from the mass requirements + in the `masscheck` command. +- sbml: Provide access to model ID and name. +- sbml: Add option to skip boundary condition species when parsing. +- massconsistency: Fix bugs occurring when zero-mass compounds are specified. +- command: Log number of consistent reactions in `masscheck`. +- sbml: Fix a number of minor bugs. +- command: Fix search command when no alternative compound names are present + +v0.6.1 (2015-04-20) +------------------- + +- sbml: Fix bug where boundary conditions were parsed incorrectly. + +v0.6 (2015-04-17) +----------------- + +- Apply changes to the SBML parser in order for it to interoperate with + `model-import`. This makes it easier to implement the SBML importer in + `model-import`. +- Add non-strict mode to the SBML parser. This makes it possible to load + almost-compliant SBML documents that are accepted by COBRA. +- `masscheck` command: Allow reactions to be marked as checked. +- cplex: Consider status `optimal_tolerance` to be successful. +- docs: Expand documentation on the `masscheck` command. +- docs: Change order of API documentation to `bysource`. + +v0.5 (2015-04-09) +----------------- + +- Add `sbmlexport` command to export current model as an SBML file. +- Add a generic interface to the linear programming solvers that delegates to + an actual solver that is installed and has the required features. This adds + a `--solver` option to a number of command which can be used to influence + which solver is selected. +- Add `--epsilon` option to a number of commands that previously had the + epsilon value hardcoded. +- Refactor functions in `fastcore` for easier use. +- docs: Extend docstring documentation of various modules. +- docs: Add DOI links for references. + +v0.4 (2015-04-06) +----------------- + +- Add documentation generated by Sphinx. The main contents of the + [README](README.md) file has been moved to the new documentation. +- Generate the entry-point script using `setup.py`. This ensures that the + package is correctly installed before the main script can be called. This + also changes the name of the entry-point from `model.py` to `model`. +- Refactor functions in `massconsistency` for easier use. +- Add `__version__` attribute to main module. +- docs: Move references to separate section. +- docs: Fix file format documentation for medium file. +- Unit tests: Skip tests requiring a linear programming solver if Cplex is + present. + +v0.3 (2015-03-27) +----------------- + +- Require reaction files to be explicitly listed in `model.yaml`. +- Add support for TSV reaction file format. +- Change format of YAML reactions (see [README](README.md) for details). +- Add tables of recognized compounds and reaction properties to + [README](README.md). +- `masscheck` command: Automatically exclude biomass reaction from check. + +v0.2 (2015-03-20) +----------------- + +- Allow compounds to be specified using YAML, TSV or ModelSEED format. This + changes the format of the `compounds` key in `model.yaml` (see + [README](README.md) for more information). +- Allow specifying biomass reaction in `model.yaml` using the `biomass` key. + The biomass reaction will be used by default for FBA, FVA, etc. +- Allow explicit definition of media. This can be defined using a table format + or YAML format. See [README](README.md) for more information. +- `chargecheck`/`formulacheck` commands: Only check reactions where all + compounds have charge/formula specified. The number of skipped reactions is + reported separately. +- `chargecheck` command: Use charge information from model definition instead + of requiring a separate charge table file. + +v0.1 (2015-03-18) +----------------- + +- Initial release. +","Markdown" +"Metabolic","zhanglab/psamm","psamm/findprimarypairs.py",".py","16926","460","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015-2017 Jon Lund Steffensen +# Copyright 2018-2020 Ke Zhang +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import division + +import logging +from itertools import product +from collections import Counter + +from six import iteritems +from six.moves import reduce + +from .formula import Formula, Atom + +from math import gcd + +logger = logging.getLogger(__name__) + + +def element_weight(element): + """"""Return default element weight. + + This is the default element weight function. + """""" + if element == Atom.H: + return 0.0 + elif element == Atom.C: + return 1.0 + return 0.82 + + +def _jaccard_similarity(f1, f2, weight_func): + """"""Calculate generalized Jaccard similarity of formulas. + + Returns the weighted similarity value or None if there is no overlap + at all. If the union of the formulas has a weight of zero (i.e. the + denominator in the Jaccard similarity is zero), a value of zero is + returned. + """""" + elements = set(f1) + elements.update(f2) + + count, w_count, w_total = 0, 0, 0 + for element in elements: + mi = min(f1.get(element, 0), f2.get(element, 0)) + mx = max(f1.get(element, 0), f2.get(element, 0)) + count += mi + w = weight_func(element) + w_count += w * mi + w_total += w * mx + + if count == 0: + return None + + return 0.0 if w_total == 0.0 else w_count / w_total + + +def _reaction_to_dicts(reaction): + """"""Convert a reaction to reduced left, right dictionaries. + + Returns a pair of (left, right) dictionaries mapping compounds to + normalized integer stoichiometric values. If a compound occurs multiple + times on one side, the occurences are combined into a single entry in the + dictionary. + """""" + def dict_from_iter_sum(it, div): + d = {} + for k, v in it: + if k not in d: + d[k] = 0 + d[k] += int(v / div) + return d + + div = reduce(gcd, (abs(v) for _, v in reaction.compounds), 0) + if div == 0: + raise ValueError('Empty reaction') + + left = dict_from_iter_sum(reaction.left, div) + right = dict_from_iter_sum(reaction.right, div) + + return left, right + + +class _CompoundInstance(object): + """"""Instance of a compound in a reaction during matching. + + A compound in a reaction has a number of instances corresponding to the + stoichiometric value. The instance is defined by the compound and index + number. The compound instance also has an attached formula which can be + updated through the ``formula`` property. The compound instance can be + created as a copy of an existing instance, or from a + :psamm:`psamm.reaction.Compound`, number, and + :psamm:`psamm.formula.Formula`. + """""" + def __init__(self, *args): + if len(args) == 1 and isinstance(args[0], _CompoundInstance): + self._compound = args[0]._compound + self._index = args[0]._index + self._formula = args[0]._formula + elif len(args) == 3: + self._compound = args[0] + self._index = args[1] + self._formula = args[2] + else: + raise ValueError('Invalid arguments') + + @property + def compound(self): + """"""Return the :class:`psamm.reaction.Compound`."""""" + return self._compound + + @property + def index(self): + """"""Return the index."""""" + return self._index + + @property + def formula(self): + """"""Return the formula."""""" + return self._formula + + @formula.setter + def formula(self, value): + self._formula = value + + def __repr__(self): + return str('<{} {} of {!r}>').format( + self.__class__.__name__, self._index, self._compound) + + def __eq__(self, other): + return (isinstance(other, self.__class__) and + self._compound == other._index and + self._index == other._index) + + def __hash__(self): + return hash((self._compound, self._index)) + + +def predict_compound_pairs_iterated( + reactions, formulas, ambiguous=False, prior=(1, 43), + max_iterations=None, element_weight=element_weight): + """"""Predict reaction pairs using iterated method. + + Returns a tuple containing a dictionary of predictions keyed by the + reaction IDs, and the final number of iterations. Each reaction prediction + entry contains a tuple with a dictionary of transfers and a dictionary of + unbalanced compounds. The dictionary of unbalanced compounds is empty only + if the reaction is balanced. + + Args: + reactions: Dictionary or pair-iterable of (id, equation) pairs. + IDs must be any hashable reaction identifier (e.g. string) and + equation must be :class:`psamm.reaction.Reaction` objects. + ambiguous: True or False value to indicate if the ambiguous + reactions should be printed in the debugging output. + formulas: Dictionary mapping compound IDs to + :class:`psamm.formula.Formula`. Formulas must be flattened. + prior: Tuple of (alpha, beta) parameters for the MAP inference. + If not provided, the default parameters will be used: (1, 43). + max_iterations: Maximum iterations to run before stopping. If the + stopping condition is reached before this number of iterations, + the procedure also stops. If None, the procedure only stops when + the stopping condition is reached. + element_weight: A function providing returning weight value for the + given :class:`psamm.formula.Atom` or + :class:`psamm.formula.Radical`. If not provided, the default weight + will be used (H=0, C=1, *=0.82) + """""" + prior_alpha, prior_beta = prior + reactions = dict(reactions) + + pair_reactions = {} + possible_pairs = Counter() + tie_breakers = {} + for reaction_id, equation in iteritems(reactions): + tie_breakers[reaction_id] = {} + for (c1, _), (c2, _) in product(equation.left, equation.right): + spair = tuple(sorted([c1.name, c2.name])) + possible_pairs[spair] += 1 + pair_reactions.setdefault(spair, set()).add(reaction_id) + + final_ambiguous_reactions = {} + + def print_ambiguous_summary(): + '''Function for summarizing and printing ambiguous compound pairs + + ''' + final_ambiguous_count = 0 + final_ambiguous_hydrogen = 0 + for reaction, pairs in sorted(iteritems(final_ambiguous_reactions)): + all_hydrogen = False + if len(pairs) > 0: + final_ambiguous_count += 1 + all_hydrogen = True + + for pair in pairs: + for _, _, formula in pair: + df = dict(formula.items()) + if len(df) > 1 or Atom.H not in df: + all_hydrogen = False + + if all_hydrogen: + final_ambiguous_hydrogen += 1 + logger.info('Ambiguous Hydrogen ' + 'Transfers in Reaction: {}'.format(reaction)) + else: + logger.info('Ambiguous Non-Hydrogen ' + 'Transfers in Reaction: {}'.format(reaction)) + + logger.info('{} reactions were decided with ambiguity'.format( + final_ambiguous_count)) + logger.info('Only hydrogen in decision: {} vs non hydrogen: {}'.format( + final_ambiguous_hydrogen, + final_ambiguous_count - final_ambiguous_hydrogen)) + + next_reactions = set(reactions) + pairs_predicted = None + prediction = {} + weights = {} + iteration = 0 + while len(next_reactions) > 0: + iteration += 1 + if max_iterations is not None and iteration > max_iterations: + break + + logger.info('Iteration {}: {} reactions...'.format( + iteration, len(next_reactions))) + + for reaction_id in next_reactions: + result = predict_compound_pairs( + reactions[reaction_id], formulas, weights, element_weight) + if result is None: + continue + + transfer, balance, ambiguous_pairs = result + final_ambiguous_reactions[reaction_id] = ambiguous_pairs + + rpairs = {} + for ((c1, _), (c2, _)), form in iteritems(transfer): + rpairs.setdefault((c1, c2), []).append(form) + + prediction[reaction_id] = rpairs, balance + if ambiguous is True: + logger.info('Ambiguous Reactions:') + print_ambiguous_summary() + + pairs_predicted = Counter() + for reaction_id, (rpairs, _) in iteritems(prediction): + for c1, c2 in rpairs: + spair = tuple(sorted([c1.name, c2.name])) + pairs_predicted[spair] += 1 + + next_reactions = set() + for spair, total in sorted(iteritems(possible_pairs)): + pred = pairs_predicted[spair] + + # The weight is set to the maximum a posteriori (MAP) estimate + # of the primary pair probability distribution. + posterior_alpha = prior_alpha + pred + posterior_beta = prior_beta + total - pred + pair_weight = ((posterior_alpha - 1) / + (posterior_alpha + posterior_beta - 2)) + + if (spair not in weights or + abs(pair_weight - weights[spair]) > 1e-5): + next_reactions.update(pair_reactions[spair]) + + c1, c2 = spair + weights[c1, c2] = pair_weight + weights[c2, c1] = pair_weight + + return prediction, iteration + + +def _match_greedily(reaction, compound_formula, score_func): + """"""Match compounds greedily based on score function. + + Args: + reaction: Reaction equation :class:`psamm.reaction.Reaction`. + compound_formula: Dictionary mapping compound IDs to + :class:`psamm.formula.Formula`. Formulas must be flattened. + score_func: Function that takes two :class:`_CompoundInstance` and + returns the score. + """""" + uninstantiated_left, uninstantiated_right = _reaction_to_dicts(reaction) + ambiguous_pairs = set() + + def compound_instances(uninstantiated): + instances = [] + for compound, value in iteritems(uninstantiated): + if value > 0: + f = compound_formula[compound.name] + instances.append(_CompoundInstance(compound, value, f)) + + for inst in instances: + uninstantiated[inst.compound] -= 1 + + return instances + + def instantiate(uninstantiated, compound): + n = uninstantiated[compound] + if n > 0: + f = compound_formula[compound.name] + inst = _CompoundInstance(compound, n, f) + uninstantiated[compound] -= 1 + return inst + + return None + + left = compound_instances(uninstantiated_left) + right = compound_instances(uninstantiated_right) + instances = left + right + + pairs = {} + for inst1, inst2 in product(left, right): + result = score_func(inst1, inst2) + if result is not None: + pairs[inst1, inst2] = result + + def inst_pair_sort_key(entry): + """"""Sort key for finding best match among instance pairs. + + Rank by score in general but always match identical compounds first + (these will always have score equal to one but are handled specially + to put them ahead of other compounds with score equal to one). Use + compound names to break ties to produce a deterministic result. + """""" + (inst1, inst2), score = entry + c1, c2 = inst1.compound, inst2.compound + same_compound = c1.name == c2.name and c1.compartment != c2.compartment + return same_compound, score, c1.name, c2.name + + transfer = {} + while len(pairs) > 0: + (inst1, inst2), _ = max(iteritems(pairs), key=inst_pair_sort_key) + common = inst1.formula & inst2.formula + sorted_pairs = sorted(iteritems(pairs), + key=inst_pair_sort_key, reverse=True) + max_sort_key = inst_pair_sort_key(sorted_pairs[0]) + + ambiguous_entry = {(inst1.compound, inst2.compound, common)} + for (other_inst1, other_inst2), other_score in sorted_pairs[1:]: + other_sort_key = inst_pair_sort_key( + ((other_inst1, other_inst2), other_score)) + if other_sort_key[:2] < max_sort_key[:2]: + break + + other_common = other_inst1.formula & other_inst2.formula + ambiguous_entry.add( + (other_inst1.compound, other_inst2.compound, other_common)) + + if len(ambiguous_entry) > 1: + ambiguous_pairs.add(tuple(ambiguous_entry)) + + key = (inst1.compound, inst1.index), (inst2.compound, inst2.index) + if key not in transfer: + transfer[key] = Formula() + transfer[key] |= common + + for inst in (inst1, inst2): + inst.formula -= common + + to_insert = set() + + inst = instantiate(uninstantiated_left, inst1.compound) + if inst is not None: + left.append(inst) + instances.append(inst) + to_insert.add(inst) + + inst = instantiate(uninstantiated_right, inst2.compound) + if inst is not None: + right.append(inst) + instances.append(inst) + to_insert.add(inst) + + to_update = {inst1, inst2} + + to_delete = set() + for inst1, inst2 in pairs: + if inst1 in to_update or inst2 in to_update: + if len(inst1.formula) > 0 and len(inst2.formula) > 0: + result = score_func(inst1, inst2) + if result is None: + to_delete.add((inst1, inst2)) + else: + pairs[inst1, inst2] = result + else: + to_delete.add((inst1, inst2)) + + for pair in to_delete: + del pairs[pair] + + for inst1, inst2 in product(left, right): + if inst1 in to_insert or inst2 in to_insert: + result = score_func(inst1, inst2) + if result is not None: + pairs[inst1, inst2] = result + + balance = {} + for inst in instances: + if len(inst.formula) > 0: + key = inst.compound, inst.index + balance[key] = inst.formula + + return transfer, balance, ambiguous_pairs + + +def predict_compound_pairs(reaction, compound_formula, pair_weights={}, + weight_func=element_weight): + """"""Predict compound pairs for a single reaction. + + Performs greedy matching on reaction compounds using a scoring function + that uses generalized Jaccard similarity corrected by the weights in the + given dictionary. Returns a tuple of a transfer dictionary and a dictionary + of unbalanced compounds. The dictionary of unbalanced compounds is empty + only if the reaction is balanced. + + Args: + reaction: :class:`psamm.reaction.Reaction`. + compound_formula: Dictionary mapping compound IDs to + :class:`psamm.formula.Formula`. Formulas must be flattened. + pair_weights: Dictionary mapping pairs of compound IDs to correction + values. This value is multiplied by the calculated Jaccard + similarity. If a pair is not in the dictionary, the value 1 is + used. Pairs are looked up in the weights dictionary as a tuple of + compound names (``c1``, ``c2``) where ``c1`` is the left-hand side + and ``c2`` is the right-hand side. + weight_func: Weight function for caclulating the generalized Jaccard + similarity. This function will be given an + :class:`psamm.formula.Atom` or :class:`psamm.formula.Radical` and + should return a corresponding weight. + """""" + def score_func(inst1, inst2): + score = _jaccard_similarity( + inst1.formula, inst2.formula, weight_func) + if score is None: + return None + pair = inst1.compound.name, inst2.compound.name + pair_weight = pair_weights.get(pair, 1.0) + return pair_weight * score + + return _match_greedily(reaction, compound_formula, score_func) +","Python" +"Metabolic","zhanglab/psamm","psamm/fastcore.py",".py","12506","361","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Fastcore module implementing the fastcore algorithm + +This is an implementation of the algorithms described in [Vlassis14]_. +Use the functions :func:`fastcore` and :func:`fastcc` to easily apply +these algorithms to a :class:`MetabolicModel`. +"""""" + +from __future__ import unicode_literals + +import logging + +from .fluxanalysis import FluxBalanceProblem + +# Module-level logging +logger = logging.getLogger(__name__) + + +class FastcoreError(Exception): + """"""Indicates an error while running Fastcore"""""" + + +class FastcoreProblem(FluxBalanceProblem): + """"""Represents a FastCore extension of a flux balance problem. + + Accepts the same arguments as :class:`FluxBalanceProblem`, and an + additional ``epsilon`` keyword argument. + + Args: + model: :class:`MetabolicModel` to solve. + solver: LP solver instance to use. + epsilon: Flux threshold value. + """""" + def __init__(self, *args, **kwargs): + self._epsilon = kwargs.pop('epsilon', 1e-5) + super(FastcoreProblem, self).__init__(*args, **kwargs) + self._zl = None + self._flipped = set() + + def _add_maximization_vars(self): + self._zl = self.prob.namespace( + self._model.reactions, lower=0, upper=self._epsilon) + + def lp7(self, reaction_subset): + """"""Approximately maximize the number of reaction with flux. + + This is similar to FBA but approximately maximizing the number of + reactions in subset with flux > epsilon, instead of just maximizing the + flux of one particular reaction. LP7 prefers ""flux splitting"" over + ""flux concentrating"". + """""" + + if self._zl is None: + self._add_maximization_vars() + + positive = set(reaction_subset) - self._flipped + negative = set(reaction_subset) & self._flipped + + v = self._v.set(positive) + zl = self._zl.set(positive) + cs = self._prob.add_linear_constraints(v >= zl) + self._temp_constr.extend(cs) + + v = self._v.set(negative) + zl = self._zl.set(negative) + cs = self._prob.add_linear_constraints(v <= -zl) + self._temp_constr.extend(cs) + + self._prob.set_objective(self._zl.sum(reaction_subset)) + + self._solve() + + def lp10(self, subset_k, subset_p, weights={}): + """"""Force reactions in K above epsilon while minimizing support of P. + + This program forces reactions in subset K to attain flux > epsilon + while minimizing the sum of absolute flux values for reactions + in subset P (L1-regularization). + """""" + + if self._z is None: + self._add_minimization_vars() + + positive = set(subset_k) - self._flipped + negative = set(subset_k) & self._flipped + + v = self._v.set(positive) + cs = self._prob.add_linear_constraints(v >= self._epsilon) + self._temp_constr.extend(cs) + + v = self._v.set(negative) + cs = self._prob.add_linear_constraints(v <= -self._epsilon) + self._temp_constr.extend(cs) + + self._prob.set_objective(self._z.expr( + (rxnid, -weights.get(rxnid, 1)) for rxnid in subset_p)) + + self._solve() + + def find_sparse_mode(self, core, additional, scaling, weights={}): + """"""Find a sparse mode containing reactions of the core subset. + + Return an iterator of the support of a sparse mode that contains as + many reactions from core as possible, and as few reactions from + additional as possible (approximately). A dictionary of weights can be + supplied which gives further penalties for including specific + additional reactions. + """""" + + if len(core) == 0: + return + + self.lp7(core) + k = set() + for reaction_id in core: + flux = self.get_flux(reaction_id) + if self.is_flipped(reaction_id): + flux *= -1 + if flux >= self._epsilon: + k.add(reaction_id) + + if len(k) == 0: + return + + self.lp10(k, additional, weights) + for reaction_id in self._model.reactions: + flux = self.get_flux(reaction_id) + if abs(flux) >= self._epsilon / scaling: + yield reaction_id + + def flip(self, reactions): + """"""Flip the specified reactions."""""" + for reaction in reactions: + if reaction in self._flipped: + self._flipped.remove(reaction) + else: + self._flipped.add(reaction) + + def is_flipped(self, reaction): + """"""Return true if reaction is flipped."""""" + return reaction in self._flipped + + +def fastcc(model, epsilon, solver): + """"""Check consistency of model reactions. + + Yield all reactions in the model that are not part of the consistent + subset. + + Args: + model: :class:`MetabolicModel` to solve. + epsilon: Flux threshold value. + solver: LP solver instance to use. + """""" + reaction_set = set(model.reactions) + subset = set(reaction_id for reaction_id in reaction_set + if model.limits[reaction_id].lower >= 0) + + logger.info('Checking {} irreversible reactions...'.format(len(subset))) + logger.debug('|J| = {}, J = {}'.format(len(subset), subset)) + + p = FastcoreProblem(model, solver, epsilon=epsilon) + p.lp7(subset) + + consistent_subset = set( + reaction_id for reaction_id in model.reactions + if abs(p.get_flux(reaction_id)) >= 0.999 * epsilon) + + logger.debug('|A| = {}, A = {}'.format( + len(consistent_subset), consistent_subset)) + + for reaction in subset - consistent_subset: + # Inconsistent reaction + yield reaction + + # Check remaining reactions + subset = (reaction_set - subset) - consistent_subset + + logger.info('Checking reversible reactions...') + logger.debug('|J| = {}, J = {}'.format(len(subset), subset)) + + flipped = False + singleton = False + while len(subset) > 0: + logger.info('{} reversible reactions left to check...'.format( + len(subset))) + if singleton: + reaction = next(iter(subset)) + subset_i = {reaction} + + logger.debug('LP3 on {}'.format(subset_i)) + p.maximize({reaction: -1 if p.is_flipped(reaction) else 1}) + else: + subset_i = subset + + logger.debug('LP7 on {}'.format(subset_i)) + p.lp7(subset_i) + + consistent_subset.update( + reaction_id for reaction_id in subset + if abs(p.get_flux(reaction_id) >= 0.999 * epsilon)) + + logger.debug('|A| = {}, A = {}'.format( + len(consistent_subset), consistent_subset)) + + if not subset.isdisjoint(consistent_subset): + subset -= consistent_subset + logger.debug('|J| = {}, J = {}'.format(len(subset), subset)) + flipped = False + else: + # TODO: irreversible reactions are taken care of before the + # loop so at this point all reactions in subset_i are reversble(?). + subset_rev_i = subset_i & model.reversible + if flipped or len(subset_rev_i) == 0: + flipped = False + if singleton: + subset -= subset_rev_i + for reaction in subset_rev_i: + logger.info('Inconsistent: {}'.format(reaction)) + yield reaction + else: + singleton = True + else: + p.flip(subset_rev_i) + flipped = True + logger.info('Flipped {} reactions'.format(len(subset_rev_i))) + + +def fastcc_is_consistent(model, epsilon, solver): + """"""Quickly check whether model is consistent + + Return true if the model is consistent. If it is only necessary to know + whether a model is consistent, this function is fast as it will return + the result as soon as it finds a single inconsistent reaction. + + Args: + model: :class:`MetabolicModel` to solve. + epsilon: Flux threshold value. + solver: LP solver instance to use. + """""" + for reaction in fastcc(model, epsilon, solver): + return False + return True + + +def fastcc_consistent_subset(model, epsilon, solver): + """"""Return consistent subset of model. + + The largest consistent subset is returned as + a set of reaction names. + + Args: + model: :class:`MetabolicModel` to solve. + epsilon: Flux threshold value. + solver: LP solver instance to use. + + Returns: + Set of reaction IDs in the consistent reaction subset. + """""" + reaction_set = set(model.reactions) + return reaction_set.difference(fastcc(model, epsilon, solver)) + + +def fastcore(model, core, epsilon, solver, scaling=1e5, weights={}): + """"""Find a flux consistent subnetwork containing the core subset. + + The result will contain the core subset and as few of the additional + reactions as possible. + + Args: + model: :class:`MetabolicModel` to solve. + core: Set of core reaction IDs. + epsilon: Flux threshold value. + solver: LP solver instance to use. + scaling: Scaling value to apply (see [Vlassis14]_ for more + information on this parameter). + weights: Dictionary with reaction IDs as keys and values as weights. + Weights specify the cost of adding a reaction to the consistent + subnetwork. Default value is 1. + + Returns: + Set of reaction IDs in the consistent reaction subset. + """""" + consistent_subset = set() + reaction_set = set(model.reactions) + + subset = core - model.reversible + logger.debug('|J| = {}, J = {}'.format(len(subset), subset)) + + penalty_set = reaction_set - core + logger.debug('|P| = {}, P = {}'.format(len(penalty_set), penalty_set)) + + p = FastcoreProblem(model, solver, epsilon=epsilon) + mode = set(p.find_sparse_mode(subset, penalty_set, scaling, weights)) + if not subset.issubset(mode): + raise FastcoreError('Inconsistent irreversible core reactions:' + ' {}'.format(subset - mode)) + + consistent_subset |= mode + logger.debug('|A| = {}, A = {}'.format( + len(consistent_subset), consistent_subset)) + + subset = core - mode + logger.debug('|J| = {}, J = {}'.format(len(subset), subset)) + + flipped = False + singleton = False + while len(subset) > 0: + penalty_set -= consistent_subset + if singleton: + subset_i = set((next(iter(subset)),)) + else: + subset_i = subset + + mode = set(p.find_sparse_mode(subset_i, penalty_set, scaling, weights)) + consistent_subset.update(mode) + logger.debug('|A| = {}, A = {}'.format( + len(consistent_subset), consistent_subset)) + + if not subset.isdisjoint(consistent_subset): + logger.debug('Subset improved {} -> {}'.format( + len(subset), len(subset - consistent_subset))) + subset -= consistent_subset + logger.debug('|J| = {}, J = {}'.format(len(subset), subset)) + flipped = False + else: + logger.debug('Nothing found, changing state...') + subset_rev_i = subset_i & model.reversible + if flipped or len(subset_rev_i) == 0: + if singleton: + raise FastcoreError('Global network inconsistent:' + ' {}'.format(subset_rev_i)) + + logger.debug('Going to non-flipped, singleton state...') + singleton = True + flipped = False + else: + p.flip(subset_rev_i) + flipped = True + logger.debug('Flipped {} reactions'.format( + len(subset_rev_i))) + + return consistent_subset +","Python" +"Metabolic","zhanglab/psamm","psamm/database.py",".py","12049","327","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Representation of metabolic network databases."""""" + +import abc +from collections.abc import Mapping +from collections import defaultdict, OrderedDict +from six import iteritems, add_metaclass + +from .reaction import Reaction, Direction + + +class StoichiometricMatrixView(Mapping): + """"""Provides a sparse matrix view on the stoichiometry of a database. + + This object is used internally in the database to expose a sparse matrix + view of the model stoichiometry. This class should not be instantied, + instead use the :attr:`MetabolicDatabase.matrix` property. Any compound, + reaction-pair can be looked up to obtain the corresponding stoichiometric + value. If the value is not defined (implicitly zero) a + :exc:`KeyError ` will be raised. + + In addition, instances also support the NumPy `__array__` protocol which + means that a :class:`numpy.array` can by created directly from the matrix. + + >>> model = MetabolicModel() + >>> matrix = numpy.array(model.matrix) + """""" + + def __init__(self, database): + super(StoichiometricMatrixView, self).__init__() + self._database = database + + def __getitem__(self, key): + if len(key) != 2: + raise KeyError(key) + compound, reaction = key + if not self._database.has_reaction(reaction): + raise KeyError(key) + reaction_values = dict(self._database.get_reaction_values(reaction)) + if compound not in reaction_values: + raise KeyError(key) + return reaction_values[compound] + + def __iter__(self): + for reaction in self._database.reactions: + for compound, _ in self._database.get_reaction_values(reaction): + yield compound, reaction + + def __len__(self): + return sum(sum(1 for _ in self._database.get_reaction_values(reaction)) + for reaction in self._database.reactions) + + def __array__(self): + """"""Return Numpy ndarray instance of matrix. + + The matrix is indexed by sorted compound, reaction-keys + """""" + import numpy # NumPy is only required for this method + + compound_list = sorted(self._database.compounds) + reaction_list = sorted(self._database.reactions) + matrix = numpy.zeros((len(compound_list), len(reaction_list))) + + compound_map = dict( + (compound, i) for i, compound in enumerate(compound_list)) + reaction_map = dict( + (reaction_id, i) for i, reaction_id in enumerate(reaction_list)) + + for reaction_id in self._database.reactions: + for compound, value in self._database.get_reaction_values( + reaction_id): + c_index = compound_map[compound] + r_index = reaction_map[reaction_id] + matrix[c_index, r_index] = value + + return matrix + + +@add_metaclass(abc.ABCMeta) +class MetabolicDatabase(object): + """"""Database of metabolic reactions."""""" + + @abc.abstractproperty + def reactions(self): + """"""Iterator of reactions IDs in the database."""""" + + @abc.abstractproperty + def compounds(self): + """"""Itertor of :class:`Compounds ` in the + database."""""" + + @abc.abstractproperty + def compartments(self): + """"""Iterator of compartment IDs in the database."""""" + + @abc.abstractmethod + def has_reaction(self, reaction_id): + """"""Whether the given reaction exists in the database."""""" + + @abc.abstractmethod + def is_reversible(self, reaction_id): + """"""Whether the given reaction is reversible."""""" + + @abc.abstractmethod + def get_reaction_values(self, reaction_id): + """"""Return an iterator of reaction compounds and stoichiometric values. + + The returned iterator contains + (:class:`Compound `, value)-tuples. The value + is negative for left-hand side compounds and positive for right-hand + side. + """""" + + @abc.abstractmethod + def get_compound_reactions(self, compound_id): + """"""Return an iterator of reactions containing the compound. + + Reactions are returned as IDs. + """""" + + @property + def reversible(self): + """"""The set of reversible reactions."""""" + return set(reaction_id for reaction_id in self.reactions + if self.is_reversible(reaction_id)) + + @property + def matrix(self): + """"""Mapping from compound, reaction to stoichiometric value. + + This is an instance of :class:`StoichiometricMatrixView`."""""" + return StoichiometricMatrixView(self) + + def get_reaction(self, reaction_id): + """"""Return reaction as a :class:`Reaction `."""""" + + direction = Direction.Forward + if self.is_reversible(reaction_id): + direction = Direction.Both + + return Reaction(direction, self.get_reaction_values(reaction_id)) + + +class DictDatabase(MetabolicDatabase): + """"""Metabolic database backed by in-memory dictionaries + + This is a subclass of :class:`MetabolicDatabase`."""""" + + def __init__(self): + super(DictDatabase, self).__init__() + self._reactions = OrderedDict() + self._compound_reactions = defaultdict(set) + self._reversible = set() + + @property + def reactions(self): + return iter(self._reactions) + + @property + def compounds(self): + return iter(self._compound_reactions) + + @property + def compartments(self): + compartment_set = set() + for compound in self.compounds: + if compound.compartment not in compartment_set: + compartment_set.add(compound.compartment) + yield compound.compartment + + def has_reaction(self, reaction_id): + return reaction_id in self._reactions + + def is_reversible(self, reaction_id): + return reaction_id in self._reversible + + def get_reaction_values(self, reaction_id): + if reaction_id not in self._reactions: + raise ValueError('Unknown reaction: {}'.format(repr(reaction_id))) + return iteritems(self._reactions[reaction_id]) + + def get_compound_reactions(self, compound_id): + return iter(self._compound_reactions[compound_id]) + + def set_reaction(self, reaction_id, reaction): + """"""Set the reaction ID to a reaction given by a + :class:`Reaction ` + + If an existing reaction exists with the given reaction ID it will be + overwritten. + """""" + + # Overwrite previous reaction if the same id is used + if reaction_id in self._reactions: + # Clean up compound to reaction mapping + for compound in self._reactions[reaction_id]: + self._compound_reactions[compound].remove(reaction_id) + + self._reversible.discard(reaction_id) + del self._reactions[reaction_id] + + self._reactions[reaction_id] = OrderedDict() + # Add values to global (sparse) stoichiometric matrix + # Compounds that occur on both sides will get a stoichiometric + # value based on the sum of the signed values on each side. + for compound, _ in reaction.compounds: + if compound not in self._reactions[reaction_id]: + self._reactions[reaction_id][compound] = 0 + self._compound_reactions[compound].add(reaction_id) + for compound, value in reaction.left: + self._reactions[reaction_id][compound] -= value + for compound, value in reaction.right: + self._reactions[reaction_id][compound] += value + + # Remove reaction from compound reactions if the resulting + # stoichiometric value turned out to be zero. + zero_compounds = set() + for compound, value in iteritems(self._reactions[reaction_id]): + if value == 0: + zero_compounds.add(compound) + + for compound in zero_compounds: + del self._reactions[reaction_id][compound] + self._compound_reactions[compound].remove(reaction_id) + + if reaction.direction != Direction.Forward: + self._reversible.add(reaction_id) + + +class ChainedDatabase(MetabolicDatabase): + """"""Links a number of databases so they can be treated a single database + + This is a subclass of :class:`MetabolicDatabase`."""""" + + def __init__(self, *databases): + self._databases = list(databases) + if len(self._databases) == 0: + self._databases.append(DictDatabase()) + + def _is_shadowed(self, reaction_id, database): + """"""Whether reaction in database is shadowed by another database"""""" + for other_database in self._databases: + if other_database == database: + break + if other_database.has_reaction(reaction_id): + return True + return False + + @property + def reactions(self): + # Make sure that we only yield each reaction once + reaction_set = set() + for database in self._databases: + for reaction in database.reactions: + if reaction not in reaction_set: + reaction_set.add(reaction) + yield reaction + + @property + def compounds(self): + # Make sure that we only yield each compound once + compound_set = set() + for database in self._databases: + for compound in database.compounds: + if compound not in compound_set: + compound_set.add(compound) + yield compound + + @property + def compartments(self): + # Make sure that we yield each compartment once + compartment_set = set() + for database in self._databases: + for compartment in database.compartments: + if compartment not in compartment_set: + compartment_set.add(compartment) + yield compartment + + def has_reaction(self, reaction_id): + return any(database.has_reaction(reaction_id) + for database in self._databases) + + def is_reversible(self, reaction_id): + for database in self._databases: + if database.has_reaction(reaction_id): + return database.is_reversible(reaction_id) + raise ValueError('Unknown reaction: {}'.format(reaction_id)) + + def get_reaction_values(self, reaction_id): + for database in self._databases: + if database.has_reaction(reaction_id): + return database.get_reaction_values(reaction_id) + raise ValueError('Unknown reaction: {}'.format(reaction_id)) + + def get_compound_reactions(self, compound): + # Make sure that we only yield each reaction once + reaction_set = set() + for database in self._databases: + for reaction in database.get_compound_reactions(compound): + if (reaction not in reaction_set and + not self._is_shadowed(reaction, database)): + reaction_set.add(reaction) + yield reaction + + def set_reaction(self, reaction_id, reaction): + if hasattr(self._databases[0], 'set_reaction'): + self._databases[0].set_reaction(reaction_id, reaction) + else: + raise ValueError('First database is immutable') +","Python" +"Metabolic","zhanglab/psamm","psamm/command.py",".py","22889","659","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Command line interface. + +Each command in the command line interface is implemented as a subclass of +:class:`Command`. Commands are also referenced from ``setup.py`` using the +entry point mechanism which allows the commands to be automatically +discovered. + +The :func:`.main` function is the entry point of command line interface. +"""""" + +from __future__ import division, unicode_literals + +import re +import os +import sys +import argparse +import logging +import abc +import pickle +from itertools import islice +import multiprocessing as mp + +import pkg_resources +from six import add_metaclass, iteritems, itervalues, text_type, PY3 + +from . import __version__ as package_version +from .datasource import native, sbml +from .datasource.context import FilePathContext +from .lpsolver import generic + +import codecs + +if PY3: + unicode = str +if not PY3: + if sys.stdout.encoding != 'UTF-8': + sys.stdout = codecs.getwriter('utf-8')(sys.stdout, 'strict') + +logger = logging.getLogger(__name__) + + +def convert_to_unicode(str_, encoding='UTF-8'): + if PY3 or bool(re.search(r'\\u', str_)): + try: + return str_.encode('latin-1').decode('unicode-escape') + except: + return str_ + else: + if isinstance(str_, unicode): + return str_ + return str_.decode(encoding) + + +class CommandError(Exception): + """"""Error from running a command. + + This should be raised from a ``Command.run()`` if any arguments are + misspecified. When the command is run and the ``CommandError`` is raised, + the caller will exit with an error code and print appropriate usage + information. + """""" + + +@add_metaclass(abc.ABCMeta) +class Command(object): + """"""Represents a command in the interface, operating on a model. + + The constructor will be given the NativeModel and the command line + namespace. The subclass must implement :meth:`run` to handle command + execution. The doc string will be used as documentation for the command + in the command line interface. + + In addition, :meth:`init_parser` can be implemented as a classmethod which + will allow the command to initialize an instance of + :class:`argparse.ArgumentParser` as desired. The resulting argument + namespace will be passed to the constructor. + """""" + + def __init__(self, model, args): + self._model = model + self._args = args + + if self._model.name is not None: + logger.info('Model: {}'.format(self._model.name)) + + if self._model.version_string is not None: + logger.info('Model version: {}'.format(self._model.version_string)) + + @classmethod + def init_parser(cls, parser): + """"""Initialize command line parser (:class:`argparse.ArgumentParser`)"""""" + + @abc.abstractmethod + def run(self): + """"""Execute command"""""" + + def argument_error(self, msg): + """"""Raise error indicating error parsing an argument."""""" + raise CommandError(msg) + + def fail(self, msg, exc=None): + """"""Exit command as a result of a failure."""""" + logger.error(msg) + if exc is not None: + logger.debug('Command failure caused by exception!', exc_info=exc) + sys.exit(1) + + +class MetabolicMixin(object): + """"""Mixin for commands that use a metabolic model representation."""""" + + def __init__(self, *args, **kwargs): + super(MetabolicMixin, self).__init__(*args, **kwargs) + + self._mm = self._model.create_metabolic_model() + + def report_flux_balance_error(self, exc=None): + to_check = set() + for reaction in self._mm.reactions: + lower, upper = self._mm.limits[reaction] + if upper < 0 or lower > 0: + to_check.add(reaction) + + message = 'Failed to solve flux balance problem!' + if len(to_check) > 0: + message += ' Please check reactions with forced flux: {}'.format( + ', '.join(sorted(to_check))) + self.fail(message, exc) + + +class ObjectiveMixin(object): + """"""Mixin for commands that use biomass as objective. + + Allows the user to override the default objective from the command line. + """""" + @classmethod + def init_parser(cls, parser): + parser.add_argument('--objective', type=convert_to_unicode, + help='Reaction to use as objective') + super(ObjectiveMixin, cls).init_parser(parser) + + def _get_objective(self, log=True): + if self._args.objective is not None: + reaction = self._args.objective + else: + reaction = self._model.biomass_reaction + if reaction is None: + self.argument_error('The objective reaction was not specified') + + if log: + logger.info('Using {} as objective'.format(reaction)) + + return reaction + + +class LoopRemovalMixin(object): + """"""Mixin for commands that perform loop removal."""""" + + _supported_loop_removal = ['none'] + + __all_methods = { + 'none': 'Loop removal disabled; spurious loops are allowed', + 'tfba': 'Loop removal using thermodynamic constraints', + 'l1min': 'Loop removal using L1 minimization' + } + + @classmethod + def init_parser(cls, parser): + supported = cls._supported_loop_removal + assert len(supported) > 0, 'No loop removal methods defined' + + invalid = set(supported).difference(cls.__all_methods) + assert len(invalid) == 0, 'Loop removal methods are invalid' + + if len(supported) >= 2: + supported_list = ', '.join(s + ' (default)' if i == 0 else s + for i, s in enumerate(supported)) + help_text = ( + 'Select type of loop removal to perform.' + ' Possible methods are: ' + supported_list) + parser.add_argument( + '--loop-removal', help=help_text, type=text_type, + default=supported[0], + metavar='METHOD', dest='hidden_mixin_loop_removal') + + super(LoopRemovalMixin, cls).init_parser(parser) + + def _get_loop_removal_option(self, log=True): + supported = self._supported_loop_removal + + if len(supported) >= 2: + loop_removal = self._args.hidden_mixin_loop_removal + else: + loop_removal = supported[0] + + if loop_removal not in self.__all_methods: + self.argument_error( + 'Unknown loop removal method: {}'.format(loop_removal)) + + if loop_removal not in supported: + self.argument_error( + 'The loop removal method {} is not possible' + ' with this command'.format(loop_removal)) + + if log: + logger.info(self.__all_methods[loop_removal]) + + return loop_removal + + +class SolverCommandMixin(object): + """"""Mixin for commands that use an LP solver. + + This adds a ``--solver`` parameter to the command that the user can use to + select a specific solver. It also adds the method :meth:`_get_solver` which + will return a solver with the specified default requirements. The user + requirements will override the default requirements. + """""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--solver', action='append', type=str, + help='Specify solver requirements (e.g. ""rational=yes"")\n' + 'Choices: \trational, integer, quadratic, ' + 'threads. feasibility_tolerance, optimality_tolerance, ' + 'integrality_tolerance') + super(SolverCommandMixin, cls).init_parser(parser) + + def __init__(self, *args, **kwargs): + super(SolverCommandMixin, self).__init__(*args, **kwargs) + self._solver_args = {} + if self._args.solver is not None: + for s in self._args.solver: + key, value = generic.parse_solver_setting(s) + self._solver_args[key] = value + + def _get_solver(self, **kwargs): + """"""Return a new :class:`psamm.lpsolver.lp.Solver` instance"""""" + solver_args = dict(kwargs) + solver_args.update(self._solver_args) + return generic.Solver(**solver_args) + + +class ParallelTaskMixin(object): + """"""Mixin for commands that run parallel computation tasks."""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--parallel', help='Set number of parallel processes (0=auto)', + type=int, default=0) + super(ParallelTaskMixin, cls).init_parser(parser) + + def _create_executor(self, handler, args, cpus_per_worker=1): + """"""Return a new :class:`.Executor` instance."""""" + if self._args.parallel > 0: + workers = self._args.parallel + else: + try: + workers = mp.cpu_count() // cpus_per_worker + except NotImplementedError: + workers = 1 + + if workers != 1: + logger.info('Using {} parallel worker processes...'.format( + workers)) + executor = ProcessPoolExecutor( + processes=workers, handler_init=handler, handler_args=args) + else: + logger.info('Using single worker...') + executor = SequentialExecutor( + handler_init=handler, handler_args=args) + + return executor + + +class FilePrefixAppendAction(argparse.Action): + """"""Action that appends one argument or multiple from a file. + + If the argument starts with a character in ``fromfile_prefix_chars`` + the remaining part of the argument is taken to be a file path. The file + is read and every line is appended. Otherwise, the argument is simply + appended. + """""" + def __init__(self, option_strings, dest, nargs=None, + fromfile_prefix_chars='@', **kwargs): + if nargs is not None: + raise ValueError('nargs not allowed') + + self.__fromfile_prefix_chars = fromfile_prefix_chars + self.__final_type = kwargs.get('type') + + super(FilePrefixAppendAction, self).__init__( + option_strings, dest, **kwargs) + + def __call__(self, parser, namespace, values, option_string=None): + arguments = getattr(namespace, self.dest) + if arguments is None or len(arguments) == 0: + arguments = [] + setattr(namespace, self.dest, arguments) + values = text_type(values) + if len(values) > 0 and values[0] in self.__fromfile_prefix_chars: + filepath = values[1:] + try: + with open(filepath, 'r') as f: + for line in f: + arguments.append(self.__final_type(line.strip())) + except IOError: + parser.error('Unable to read arguments from file: {}'.format( + filepath)) + else: + arguments.append(self.__final_type(values)) + + +class _ErrorMarker(object): + """"""Signals error in the child process."""""" + + def __init__(self, pickled_exc=None): + self.pickled_exception = pickled_exc + + +class ExecutorError(Exception): + """"""Error running tasks on executor."""""" + + +class _ExecutorProcess(mp.Process): + def __init__(self, task_queue, result_queue, handler_init, + handler_args=()): + super(_ExecutorProcess, self).__init__() + self._task_queue = task_queue + self._result_queue = result_queue + self._handler_init = handler_init + self._handler_args = handler_args + + def run(self): + try: + handler = self._handler_init(*self._handler_args) + for tasks in iter(self._task_queue.get, None): + results = [ + (task, handler.handle_task(*task)) for task in tasks] + self._result_queue.put(results) + except BaseException as e: + try: + pickled_exc = pickle.dumps(e, -1) + except Exception: + logger.warning(""Unpicklable exception raised: {}"".format(e)) + pickled_exc = None + self._result_queue.put(_ErrorMarker(pickled_exc)) + + +class Executor(object): + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + return False + + def close(self): + pass + + +class ProcessPoolExecutor(Executor): + def __init__(self, handler_init, handler_args=(), processes=None): + if processes is None: + try: + processes = mp.cpu_count() + except NotImplementedError: + processes = 1 + + self._process_count = processes + self._processes = [] + self._task_queue = mp.Queue() + self._result_queue = mp.Queue() + + for _ in range(self._process_count): + p = _ExecutorProcess( + self._task_queue, self._result_queue, handler_init, + handler_args) + p.start() + self._processes.append(p) + + def apply(self, task): + self._task_queue.put([task]) + results = self._result_queue.get() + if isinstance(results, _ErrorMarker): + exception = pickle.loads(results.pickled_exception) + raise exception + + return next(itervalues(results)) + + def imap_unordered(self, iterable, chunksize=1): + def iter_chunks(): + while True: + chunk = list(islice(iterable, chunksize)) + if len(chunk) == 0: + break + yield chunk + + it = iter_chunks() + workers = 0 + for i in range(self._process_count): + tasks = next(it, None) + if tasks is None: + break + + self._task_queue.put(tasks) + workers += 1 + + exception = None + while workers > 0: + results = self._result_queue.get() + if isinstance(results, _ErrorMarker): + if exception is None: + if results.pickled_exception is None: + exception = ExecutorError( + ""Unpicklable exception raised by child"") + else: + exception = pickle.loads(results.pickled_exception) + workers -= 1 + self._process_count -= 1 + continue + + if exception is not None: + continue + + tasks = next(it, None) + if tasks is None: + workers -= 1 + + self._task_queue.put(tasks) + + for task, result in results: + yield task, result + + if exception is not None: + raise exception + + def close(self): + for i in range(self._process_count): + self._task_queue.put(None) + + def join(self): + for p in self._processes: + p.join() + + +class SequentialExecutor(Executor): + def __init__(self, handler_init, handler_args=()): + self._handler = handler_init(*handler_args) + + def apply(self, task): + return self._handler.handle_task(*task) + + def imap_unordered(self, iterable, chunksize=1): + for task in iterable: + yield task, self._handler.handle_task(*task) + + def join(self): + pass + + +def _trim(docstring): + """"""Return a trimmed docstring. + + Code taken from 'PEP 257 -- Docstring Conventions' article. + """""" + if not docstring: + return '' + # Convert tabs to spaces (following the normal Python rules) + # and split into a list of lines: + lines = docstring.expandtabs().splitlines() + # Determine minimum indentation (first line doesn't count): + for line in lines[1:]: + stripped = line.lstrip() + if stripped: + indent = len(line) - len(stripped) + # Remove indentation (first line is special): + trimmed = [lines[0].strip()] + for line in lines[1:]: + trimmed.append(line[indent:].rstrip()) + # Strip off trailing and leading blank lines: + while trimmed and not trimmed[-1]: + trimmed.pop() + while trimmed and not trimmed[0]: + trimmed.pop(0) + # Return a single string: + return '\n'.join(trimmed) + + +def main(command_class=None, args=None): + """"""Run the command line interface with the given :class:`Command`. + + If no command class is specified the user will be able to select a specific + command through the first command line argument. If the ``args`` are + provided, these should be a list of strings that will be used instead of + ``sys.argv[1:]``. This is mostly useful for testing. + """""" + + # Set up logging for the command line interface + if 'PSAMM_DEBUG' in os.environ: + level = getattr(logging, os.environ['PSAMM_DEBUG'].upper(), None) + if level is not None: + logging.basicConfig(level=level) + else: + logging.basicConfig(level=logging.INFO) + base_logger = logging.getLogger('psamm') + if len(base_logger.handlers) == 0: + handler = logging.StreamHandler() + handler.setFormatter( + logging.Formatter(u'%(levelname)s: %(message)s')) + base_logger.addHandler(handler) + base_logger.propagate = False + + title = 'Metabolic modeling tools' + if command_class is not None: + title, _, _ = command_class.__doc__.partition('\n\n') + + parser = argparse.ArgumentParser(description=title) + parser.add_argument('--model', metavar='file', default='.', + help='Model definition') + parser.add_argument( + '-V', '--version', action='version', + version='%(prog)s ' + package_version) + + if command_class is not None: + # Command explicitly given, only allow that command + command_class.init_parser(parser) + parser.set_defaults(command=command_class) + else: + # Discover all available commands + commands = {} + for entry in pkg_resources.iter_entry_points('psamm.commands'): + canonical = entry.name.lower() + if canonical not in commands: + command_class = entry.load() + commands[canonical] = command_class + else: + logger.warning('Command {} was found more than once!'.format( + canonical)) + + # Create parsers for subcommands + subparsers = parser.add_subparsers(title='Commands', metavar='command') + for name, command_class in sorted(iteritems(commands)): + title, _, _ = command_class.__doc__.partition('\n\n') + subparser = subparsers.add_parser( + name, help=title.rstrip('.'), + formatter_class=argparse.RawDescriptionHelpFormatter, + description=_trim(command_class.__doc__)) + subparser.set_defaults(command=command_class) + command_class.init_parser(subparser) + + parsed_args = parser.parse_args(args) + + # Load model definition + model = native.ModelReader.reader_from_path( + parsed_args.model).create_model() + + # Instantiate command with model and run + command = parsed_args.command(model, parsed_args) + try: + command.run() + except CommandError as e: + parser.error(text_type(e)) + + +def main_sbml(command_class=None, args=None): + """"""Run the SBML command line interface."""""" + # Set up logging for the command line interface + if 'PSAMM_DEBUG' in os.environ: + level = getattr(logging, os.environ['PSAMM_DEBUG'].upper(), None) + if level is not None: + logging.basicConfig(level=level) + else: + logging.basicConfig(level=logging.INFO) + base_logger = logging.getLogger('psamm') + if len(base_logger.handlers) == 0: + handler = logging.StreamHandler() + handler.setFormatter( + logging.Formatter(u'%(levelname)s: %(message)s')) + base_logger.addHandler(handler) + base_logger.propagate = False + + title = 'Metabolic modeling tools (SBML)' + if command_class is not None: + title, _, _ = command_class.__doc__.partition('\n\n') + + parser = argparse.ArgumentParser(description=title) + parser.add_argument('model', metavar='file', help='SBML file') + parser.add_argument('--merge-compounds', action='store_true', + help=('Merge identical compounds occuring in various' + ' compartments.')) + parser.add_argument( + '-V', '--version', action='version', + version='%(prog)s ' + package_version) + + if command_class is not None: + # Command explicitly given, only allow that command + command_class.init_parser(parser) + parser.set_defaults(command=command_class) + else: + # Discover all available commands + commands = {} + for entry in pkg_resources.iter_entry_points('psamm.commands'): + canonical = entry.name.lower() + if canonical not in commands: + command_class = entry.load() + commands[canonical] = command_class + else: + logger.warning('Command {} was found more than once!'.format( + canonical)) + + # Create parsers for subcommands + subparsers = parser.add_subparsers(title='Commands', metavar='command') + for name, command_class in sorted(iteritems(commands)): + title, _, _ = command_class.__doc__.partition('\n\n') + subparser = subparsers.add_parser( + name, help=title.rstrip('.'), + formatter_class=argparse.RawDescriptionHelpFormatter, + description=_trim(command_class.__doc__)) + subparser.set_defaults(command=command_class) + command_class.init_parser(subparser) + + parsed_args = parser.parse_args(args) + + # Load model definition + context = FilePathContext(parsed_args.model) + with context.open('r') as f: + model = sbml.SBMLReader(f, context=context).create_model() + sbml.convert_sbml_model(model) + if parsed_args.merge_compounds: + sbml.merge_equivalent_compounds(model) + + # Instantiate command with model and run + command = parsed_args.command(model, parsed_args) + try: + command.run() + except CommandError as e: + parser.error(text_type(e)) +","Python" +"Metabolic","zhanglab/psamm","psamm/gapfill.py",".py","11063","275","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Identify blocked metabolites and possible reconstructions. + +This implements a variant of the algorithms described in [Kumar07]_. +"""""" + +import logging + +from six import iteritems, raise_from + +from .lpsolver import lp + +logger = logging.getLogger(__name__) + + +class GapFillError(Exception): + """"""Indicates an error while running GapFind/GapFill"""""" + + +def _find_integer_tolerance(epsilon, v_max, min_tol): + """"""Find appropriate integer tolerance for gap-filling problems."""""" + int_tol = min(epsilon / (10 * v_max), 0.1) + min_tol = max(1e-10, min_tol) + if int_tol < min_tol: + eps_lower = min_tol * 10 * v_max + logger.warning( + 'When the maximum flux is {}, it is recommended that' + ' epsilon > {} to avoid numerical issues with this' + ' solver. Results may be incorrect with' + ' the current settings!'.format(v_max, eps_lower)) + return min_tol + + return int_tol + + +def gapfind(model, solver, epsilon=0.001, v_max=1000, implicit_sinks=True): + """"""Identify compounds in the model that cannot be produced. + + Yields all compounds that cannot be produced. This method + assumes implicit sinks for all compounds in the model so + the only factor that influences whether a compound can be + produced is the presence of the compounds needed to produce it. + + Epsilon indicates the threshold amount of reaction flux for the products + to be considered non-blocked. V_max indicates the maximum flux. + + This method is implemented as a MILP-program. Therefore it may + not be efficient for larger models. + + Args: + model: :class:`MetabolicModel` containing core reactions and reactions + that can be added for gap-filling. + solver: MILP solver instance. + epsilon: Threshold amount of a compound produced for it to not be + considered blocked. + v_max: Maximum flux. + implicit_sinks: Whether implicit sinks for all compounds are included + when gap-filling (traditional GapFill uses implicit sinks). + """""" + prob = solver.create_problem() + + # Set integrality tolerance such that w constraints are correct + min_tol = prob.integrality_tolerance.min + int_tol = _find_integer_tolerance(epsilon, v_max, min_tol) + if int_tol < prob.integrality_tolerance.value: + prob.integrality_tolerance.value = int_tol + + # Define flux variables + v = prob.namespace() + for reaction_id in model.reactions: + lower, upper = model.limits[reaction_id] + v.define([reaction_id], lower=lower, upper=upper) + + # Define constraints on production of metabolites in reaction + w = prob.namespace(types=lp.VariableType.Binary) + binary_cons_lhs = {compound: 0 for compound in model.compounds} + for spec, value in iteritems(model.matrix): + compound, reaction_id = spec + if value != 0: + w.define([spec]) + w_var = w(spec) + + lower, upper = (float(x) for x in model.limits[reaction_id]) + if value > 0: + dv = v(reaction_id) + else: + dv = -v(reaction_id) + lower, upper = -upper, -lower + + prob.add_linear_constraints( + dv <= upper * w_var, + dv >= epsilon + (lower - epsilon) * (1 - w_var)) + + binary_cons_lhs[compound] += w_var + + xp = prob.namespace(model.compounds, types=lp.VariableType.Binary) + objective = xp.sum(model.compounds) + prob.set_objective(objective) + + for compound, lhs in iteritems(binary_cons_lhs): + prob.add_linear_constraints(lhs >= xp(compound)) + + # Define mass balance constraints + massbalance_lhs = {compound: 0 for compound in model.compounds} + for spec, value in iteritems(model.matrix): + compound, reaction_id = spec + massbalance_lhs[compound] += v(reaction_id) * value + for compound, lhs in iteritems(massbalance_lhs): + if implicit_sinks: + # The constraint is merely >0 meaning that we have implicit sinks + # for all compounds. + prob.add_linear_constraints(lhs >= 0) + else: + prob.add_linear_constraints(lhs == 0) + + # Solve + try: + result = prob.solve(lp.ObjectiveSense.Maximize) + except lp.SolverError as e: + raise_from(GapFillError('Failed to solve gapfill: {}'.format(e), e)) + + for compound in model.compounds: + if result.get_value(xp(compound)) < 0.5: + yield compound + + +def gapfill( + model, core, blocked, exclude, solver, epsilon=0.001, v_max=1000, + weights={}, implicit_sinks=True, allow_bounds_expansion=False): + """"""Find a set of reactions to add such that no compounds are blocked. + + Returns two iterators: first an iterator of reactions not in + core, that were added to resolve the model. Second, an + iterator of reactions in core that had flux bounds expanded (i.e. + irreversible reactions become reversible). Similarly to + GapFind, this method assumes, by default, implicit sinks for all compounds + in the model so the only factor that influences whether a compound + can be produced is the presence of the compounds needed to produce + it. This means that the resulting model will not necessarily be + flux consistent. + + This method is implemented as a MILP-program. Therefore it may + not be efficient for larger models. + + Args: + model: :class:`MetabolicModel` containing core reactions and reactions + that can be added for gap-filling. + core: The set of core (already present) reactions in the model. + blocked: The compounds to unblock. + exclude: Set of reactions in core to be excluded from gap-filling (e.g. + biomass reaction). + solver: MILP solver instance. + epsilon: Threshold amount of a compound produced for it to not be + considered blocked. + v_max: Maximum flux. + weights: Dictionary of weights for reactions. Weight is the penalty + score for adding the reaction (non-core reactions) or expanding the + flux bounds (all reactions). + implicit_sinks: Whether implicit sinks for all compounds are included + when gap-filling (traditional GapFill uses implicit sinks). + allow_bounds_expansion: Allow flux bounds to be expanded at the cost + of a penalty which can be specified using weights (traditional + GapFill does not allow this). This includes turning irreversible + reactions reversible. + """""" + prob = solver.create_problem() + + # Set integrality tolerance such that w constraints are correct + min_tol = prob.integrality_tolerance.min + int_tol = _find_integer_tolerance(epsilon, v_max, min_tol) + if int_tol < prob.integrality_tolerance.value: + prob.integrality_tolerance.value = int_tol + + # Define flux variables + v = prob.namespace(model.reactions, lower=-v_max, upper=v_max) + + # Add binary indicator variables + database_reactions = set(model.reactions).difference(core, exclude) + ym = prob.namespace(model.reactions, types=lp.VariableType.Binary) + yd = prob.namespace(database_reactions, types=lp.VariableType.Binary) + + objective = ym.expr( + (rxnid, weights.get(rxnid, 1)) for rxnid in model.reactions) + objective += yd.expr( + (rxnid, weights.get(rxnid, 1)) for rxnid in database_reactions) + prob.set_objective(objective) + + # Add constraints on all reactions + for reaction_id in model.reactions: + lower, upper = (float(x) for x in model.limits[reaction_id]) + + if reaction_id in exclude or not allow_bounds_expansion: + prob.add_linear_constraints( + upper >= v(reaction_id), v(reaction_id) >= lower) + else: + # Allow flux bounds to expand up to v_max with penalty + delta_lower = min(0, -v_max - lower) + delta_upper = max(0, v_max - upper) + prob.add_linear_constraints( + v(reaction_id) >= lower + ym(reaction_id) * delta_lower, + v(reaction_id) <= upper + ym(reaction_id) * delta_upper) + + # Add constraints on database reactions + for reaction_id in database_reactions: + lower, upper = model.limits[reaction_id] + prob.add_linear_constraints( + v(reaction_id) >= yd(reaction_id) * -v_max, + v(reaction_id) <= yd(reaction_id) * v_max) + + # Define constraints on production of blocked metabolites in reaction + w = prob.namespace(types=lp.VariableType.Binary) + binary_cons_lhs = {compound: 0 for compound in blocked} + for (compound, reaction_id), value in iteritems(model.matrix): + if reaction_id not in exclude and compound in blocked and value != 0: + w.define([(compound, reaction_id)]) + w_var = w((compound, reaction_id)) + + dv = v(reaction_id) if value > 0 else -v(reaction_id) + prob.add_linear_constraints( + dv <= v_max * w_var, + dv >= epsilon + (-v_max - epsilon) * (1 - w_var)) + + binary_cons_lhs[compound] += w_var + + for compound, lhs in iteritems(binary_cons_lhs): + prob.add_linear_constraints(lhs >= 1) + + # Define mass balance constraints + massbalance_lhs = {compound: 0 for compound in model.compounds} + for (compound, reaction_id), value in iteritems(model.matrix): + if reaction_id not in exclude: + massbalance_lhs[compound] += v(reaction_id) * value + for compound, lhs in iteritems(massbalance_lhs): + if implicit_sinks: + # The constraint is merely >0 meaning that we have implicit sinks + # for all compounds. + prob.add_linear_constraints(lhs >= 0) + else: + prob.add_linear_constraints(lhs == 0) + + # Solve + try: + prob.solve(lp.ObjectiveSense.Minimize) + except lp.SolverError as e: + raise_from(GapFillError('Failed to solve gapfill: {}'.format(e)), e) + + def added_iter(): + for reaction_id in database_reactions: + if yd.value(reaction_id) > 0.5: + yield reaction_id + + def no_bounds_iter(): + for reaction_id in model.reactions: + if ym.value(reaction_id) > 0.5: + yield reaction_id + + return added_iter(), no_bounds_iter() +","Python" +"Metabolic","zhanglab/psamm","psamm/bayesian_util.py",".py","5074","156","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2018-2020 Jing Wang + +""""""Utility functions."""""" +from __future__ import division +from future.utils import iteritems +from builtins import range + +import re +from itertools import product + +from psamm.formula import Atom +from psamm.expression.boolean import Expression + + +def id_equals(id1, id2): + """"""Return True if the two IDs are considered equal."""""" + return id1.lower() == id2.lower() + + +def name_equals(name1, name2): + """"""Return True if the two names are considered equal."""""" + if name1 is None or name2 is None: + return False + # remove special chars, translate to lower case + pattern = r'[^a-zA-Z0-9]' + name1 = re.sub(pattern, '', name1.lower()) + name2 = re.sub(pattern, '', name2.lower()) + # unify Coenzyme A and CoA + pattern = r'coenzymea' + name1 = re.sub(pattern, 'coa', name1.lower()) + name2 = re.sub(pattern, 'coa', name2.lower()) + return (name1 == name2) + + +def name_similar(name1, name2): + """"""Return the possibility that two names are considered equal."""""" + pattern = r'[()\[\]_, -]' + if name1 is None or name2 is None: + return 0.01 + name1 = re.sub(pattern, '', name1) + name2 = re.sub(pattern, '', name2) + return max(0.01, + (1 - float(levenshtein(name1, name2)) / + max(len(name1), len(name2)))) + + +def formula_equals(f1, f2, charge1, charge2): + """"""Return True if the two formulas are considered equal."""""" + if f1 is None or f2 is None: + return False + + def calc_formula(f, charge, neutral=False): + formula = {} + for e, value in iteritems(f): + if e != Atom('H') or charge is None or not neutral: + formula[e] = value + else: + formula[e] = value - charge # No. of H in neutral stat + return formula + + # in case some model doesn't provide charge for non-neutral formula + # compare original formula + formula1 = calc_formula(f1, charge1) + formula2 = calc_formula(f2, charge2) + # compare neutral formula + formula1_neutral = calc_formula(f1, charge1, neutral=True) + formula2_neutral = calc_formula(f2, charge2, neutral=True) + + return (formula1 == formula2) or (formula1_neutral == formula2_neutral) + + +def genes_equals(g1, g2, gene_map={}): + """"""Return True if the two gene association strings are considered equal. + + Args: + g1, g2: gene association strings + gene_map: a dict that maps gene ids in g1 to gene ids in g2 if + they have different naming system + """""" + if g1 is None or g2 is None: + return False + + e1 = Expression(g1) + e2 = Expression(g2) + + g_list = set([gene_map.get(v.symbol, v.symbol) for v in e2.variables]) + check1 = e1.substitute(lambda v: v.symbol in g_list) + + g_list = set([gene_map.get(v.symbol, v.symbol) for v in e1.variables]) + check2 = e2.substitute(lambda v: v.symbol in g_list) + + return check1.value and check2.value + + +def formula_exact(f1, f2): + """"""Return True if the two formulas are considered equal."""""" + if f1 is None or f2 is None: + return False + + formula1 = {e: value for e, value in iteritems(f1)} + formula2 = {e: value for e, value in iteritems(f2)} + return formula1 == formula2 + + +def pairwise_distance(i1, i2, distance, threshold=None): + """"""Pairwise distances."""""" + for c1, c2 in product(i1, i2): + score = distance(c1, c2) + if threshold is None or score < threshold: + yield (c1, c2), score + + +def levenshtein(s1, s2): + """"""Edit distance function."""""" + if len(s1) < len(s2): + return levenshtein(s2, s1) + + # len(s1) >= len(s2) + if len(s2) == 0: + return len(s1) + + previous_row = list(range(len(s2) + 1)) + for i, c1 in enumerate(s1.lower()): + current_row = [i + 1] + for j, c2 in enumerate(s2.lower()): + # We use j+1 instead of j since previous_row and current_row + # are one character longer than s2 + insertions = previous_row[j + 1] + 1 + deletions = current_row[j] + 1 + substitutions = previous_row[j] + (c1 != c2) + current_row.append(min(insertions, deletions, substitutions)) + previous_row = current_row + + return previous_row[-1] + + +def jaccard(s1, s2): + """"""Jaccard similarity function."""""" + return len(set(s1) & set(s2)) / len(set(s1) | set(s2)) +","Python" +"Metabolic","zhanglab/psamm","psamm/formula.py",".py","16789","512","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Parser and representation of chemical formulas. + +Chemical formulas (:class:`.Formula`) are represented as a number of +:class:`FormulaElements <.FormulaElement>` with associated counts. A +:class:`.Formula` is itself a :class:`.FormulaElement` so a formula can contain +subformulas. This allows some simple structure to be represented. +"""""" + +from __future__ import unicode_literals + +import re +from collections import Counter +import functools +import operator +import numbers + +import six +from six import iteritems +from six.moves import reduce + +from .expression.affine import Expression + + +class FormulaElement(object): + """"""Base class representing elements of a formula"""""" + + def __add__(self, other): + """"""Add formula elements creating subformulas"""""" + if isinstance(other, FormulaElement): + if self == other: + return Formula({self: 2}) + return Formula({self: 1, other: 1}) + return NotImplemented + + def __radd__(self, other): + return self + other + + def __or__(self, other): + """"""Merge formula elements into one formula"""""" + return Formula({self: 1}) | other + + def __ror__(self, other): + return self | other + + def __mul__(self, other): + """"""Multiply formula element by other"""""" + return Formula({self: other}) + + def __rmul__(self, other): + return self * other + + def repeat(self, count): + """"""Repeat formula element by creating a subformula"""""" + return Formula({self: count}) + + def variables(self): + """"""Iterator over variables in formula element"""""" + return iter([]) + + def substitute(self, mapping): + """"""Return formula element with substitutions performed"""""" + return self + + +class _AtomType(type): + """"""Metaclass that gives the Atom class properties for each element. + + A class based on this metaclass (i.e. :class:`.Atom`) will have singleton + elements with each name, and will have a property for each element which + contains the instance for that element. + """""" + + _ELEMENTS = set([ + 'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', + 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', + 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', + 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', + 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', + 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', + 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', + 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', + 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', + 'Ds', 'Rg', 'Cn', 'Uut', 'Fl', 'Uup', 'Lv', 'Uus', 'Uuo' + ]) + + _instances = {} + + def __call__(self, name, *args, **kwargs): + instances = _AtomType._instances.setdefault(self, {}) + if name not in instances: + instances[name] = super(_AtomType, self).__call__( + name, *args, **kwargs) + return instances[name] + + def __getattribute__(self, name): + if name in _AtomType._ELEMENTS: + return self(name) + return super(_AtomType, self).__getattribute__(name) + + +@six.python_2_unicode_compatible +@functools.total_ordering +@six.add_metaclass(_AtomType) +class Atom(FormulaElement): + """"""Represent an atom in a chemical formula + + >>> hydrogen = Atom.H + >>> oxygen = Atom.O + >>> str(oxygen | 2*hydrogen) + 'H2O' + """""" + + def __init__(self, symbol): + self._symbol = symbol + + @property + def symbol(self): + """"""Atom symbol + + >>> Atom.H.symbol + 'H' + """""" + + return self._symbol + + def __hash__(self): + return hash('Atom') ^ hash(self._symbol) + + def __eq__(self, other): + return isinstance(other, Atom) and self._symbol == other._symbol + + def __ne__(self, other): + return not self == other + + def __lt__(self, other): + if isinstance(other, Atom): + return self._symbol < other._symbol + return NotImplemented + + def __str__(self): + return self._symbol + + def __repr__(self): + return str('Atom({})').format(repr(self._symbol)) + + +@six.python_2_unicode_compatible +class Radical(FormulaElement): + """"""Represents a radical or other unknown subformula"""""" + + def __init__(self, symbol): + self._symbol = symbol + + @property + def symbol(self): + """"""Radical symbol + + >>> Radical('R1').symbol + 'R1' + """""" + + return self._symbol + + def __hash__(self): + return hash('Radical') ^ hash(self._symbol) + + def __eq__(self, other): + return isinstance(other, Radical) and self._symbol == other._symbol + + def __ne__(self, other): + return not self == other + + def __str__(self): + return self._symbol + + def __repr__(self): + return str('Radical({})').format(repr(self._symbol)) + + +@six.python_2_unicode_compatible +class Formula(FormulaElement): + """"""Representation of a chemial formula + + This is represented as a number of + :class:`FormulaElements <.FormulaElement>` with associated counts. + + >>> f = Formula({Atom.C: 6, Atom.H: 12, Atom.O: 6}) + >>> str(f) + 'C6H12O6' + """""" + + def __init__(self, values={}): + self._values = Counter() + self._variables = set() + + for element, value in iteritems(values): + if not isinstance(element, FormulaElement): + raise ValueError('Not a formula element: {}'.format( + repr(element))) + if (value != 0 and + (not isinstance(element, Formula) or len(element) > 0)): + self._values[element] = value + + if callable(getattr(value, 'variables', None)): + for var in value.variables(): + self._variables.add(var) + for var in element.variables(): + self._variables.add(var) + + def substitute(self, mapping): + result = self.__class__() + for element, value in iteritems(self._values): + if callable(getattr(value, 'substitute', None)): + value = value.substitute(mapping) + if isinstance(value, int) and value <= 0: + raise ValueError( + 'Expression evaluated to non-positive number') + # TODO does not merge correctly with subformulas + result += value * element.substitute(mapping) + return result + + def flattened(self): + """"""Return formula where subformulas have been flattened + + >>> str(Formula.parse('(CH2)(CH2)2').flattened()) + 'C3H6' + """""" + + stack = [(self, 1)] + result = Counter() + while len(stack) > 0: + var, value = stack.pop() + if isinstance(var, Formula): + for sub_var, sub_value in iteritems(var._values): + stack.append((sub_var, value*sub_value)) + else: + result[var] += value + return Formula(result) + + def variables(self): + return iter(self._variables) + + def __iter__(self): + return iter(self._values) + + def items(self): + """"""Iterate over (:class:`.FormulaElement`, value)-pairs"""""" + return iteritems(self._values) + + def is_variable(self): + return len(self._variables) > 0 + + def __contains__(self, element): + return element in self._values + + def get(self, element, default=None): + """"""Return value for element or default if not in the formula."""""" + return self._values.get(element, default) + + def __getitem__(self, element): + if element not in self._values: + raise KeyError(repr(element)) + return self._values[element] + + def __len__(self): + return len(self._values) + + def __str__(self): + """"""Return formula represented using Hill notation system + + >>> str(Formula({Atom.C: 6, Atom.H: 12, Atom.O: 6})) + 'C6H12O6' + """""" + + def hill_sorted_elements(values): + def element_sort_key(pair): + element, value = pair + if isinstance(element, Atom): + return 0, element.symbol + elif isinstance(element, Radical): + return 1, element.symbol + else: + return 2, None + + if Atom.C in values: + yield Atom.C, values[Atom.C] + if Atom.H in values: + yield Atom.H, values[Atom.H] + for element, value in sorted( + iteritems(values), key=element_sort_key): + if element not in (Atom.C, Atom.H): + yield element, value + else: + for element, value in sorted( + iteritems(values), key=element_sort_key): + yield element, value + + s = '' + for element, value in hill_sorted_elements(self._values): + def grouped(element, value): + return '({}){}'.format(element, value if value != 1 else '') + + def nongrouped(element, value): + return '{}{}'.format(element, value if value != 1 else '') + + if isinstance(element, Radical): + if len(element.symbol) == 1: + s += nongrouped(element, value) + else: + s += grouped(element, value) + elif isinstance(element, Atom): + s += nongrouped(element, value) + else: + s += grouped(element, value) + return s + + def __repr__(self): + return str('Formula({})').format(repr(dict(self._values))) + + def __and__(self, other): + """"""Intersection of formula elements."""""" + if isinstance(other, Formula): + return Formula(self._values & other._values) + elif isinstance(other, FormulaElement): + return Formula(self._values & Counter([other])) + return NotImplemented + + def __or__(self, other): + """"""Merge formulas into one formula."""""" + # Note: This operator corresponds to the add-operator on Counter not + # the or-operator! The add-operator is used here (on the superclass) + # to compose formula elements into subformulas. + if isinstance(other, Formula): + return Formula(self._values + other._values) + elif isinstance(other, FormulaElement): + return Formula(self._values + Counter([other])) + return NotImplemented + + def __sub__(self, other): + """"""Substract other formula from this formula."""""" + if isinstance(other, Formula): + return Formula(self._values - other._values) + elif isinstance(other, FormulaElement): + return Formula(self._values - Counter([other])) + return NotImplemented + + def __mul__(self, other): + """"""Multiply formula element by other."""""" + values = {key: value*other for key, value in iteritems(self._values)} + return Formula(values) + + def __hash__(self): + h = hash('Formula') + for element, value in iteritems(self._values): + h ^= hash(element) ^ hash(value) + return h + + def __eq__(self, other): + return isinstance(other, Formula) and self._values == other._values + + def __ne__(self, other): + return not self == other + + @classmethod + def parse(cls, s): + """"""Parse a formula string (e.g. C6H10O2)."""""" + return _parse_formula(s) + + @classmethod + def balance(cls, lhs, rhs): + """"""Return formulas that need to be added to balance given formulas + + Given complete formulas for right side and left side of a reaction, + calculate formulas for the missing compounds on both sides. Return + as a left, right tuple. Formulas can be flattened before balancing + to disregard grouping structure. + """""" + + def missing(formula, other): + for element, value in iteritems(formula._values): + if element not in other._values: + yield value*element + else: + delta = value - other._values[element] + if isinstance(delta, numbers.Number) and delta > 0: + yield delta*element + + return (reduce(operator.or_, missing(rhs, lhs), Formula()), + reduce(operator.or_, missing(lhs, rhs), Formula())) + + +class ParseError(Exception): + """"""Signals error parsing formula."""""" + + def __init__(self, *args, **kwargs): + self._span = kwargs.pop('span', None) + super(ParseError, self).__init__(*args, **kwargs) + + @property + def indicator(self): + if self._span is None: + return None + pre = ' ' * self._span[0] + ind = '^' * max(1, self._span[1] - self._span[0]) + return pre + ind + + +def _parse_formula(s): + """"""Parse formula string."""""" + scanner = re.compile(r''' + (\s+) | # whitespace + (\(|\)) | # group + ([A-Z][a-z]*) | # element + (\d+) | # number + ([a-z]) | # variable + (\Z) | # end + (.) # error + ''', re.DOTALL | re.VERBOSE) + + def transform_subformula(form): + """"""Extract radical if subformula is a singleton with a radical."""""" + if isinstance(form, dict) and len(form) == 1: + # A radical in a singleton subformula is interpreted as a + # numbered radical. + element, value = next(iteritems(form)) + if isinstance(element, Radical): + return Radical('{}{}'.format(element.symbol, value)) + return form + + stack = [] + formula = {} + expect_count = False + + def close(formula, count=1): + if len(stack) == 0: + raise ParseError('Unbalanced parenthesis group in formula') + subformula = transform_subformula(formula) + if isinstance(subformula, dict): + subformula = Formula(subformula) + + formula = stack.pop() + if subformula not in formula: + formula[subformula] = 0 + formula[subformula] += count + return formula + + for match in re.finditer(scanner, s): + (whitespace, group, element, number, variable, end, + error) = match.groups() + + if error is not None: + raise ParseError( + 'Invalid token in formula string: {!r}'.format(match.group(0)), + span=(match.start(), match.end())) + elif whitespace is not None: + continue + elif group is not None and group == '(': + if expect_count: + formula = close(formula) + stack.append(formula) + formula = {} + expect_count = False + elif group is not None and group == ')': + if expect_count: + formula = close(formula) + expect_count = True + elif element is not None: + if expect_count: + formula = close(formula) + stack.append(formula) + if element in 'RX': + formula = Radical(element) + else: + formula = Atom(element) + expect_count = True + elif number is not None and expect_count: + formula = close(formula, int(number)) + expect_count = False + elif variable is not None and expect_count: + formula = close(formula, Expression(variable)) + expect_count = False + elif end is not None: + if expect_count: + formula = close(formula) + else: + raise ParseError( + 'Invalid token in formula string: {!r}'.format(match.group(0)), + span=(match.start(), match.end())) + + if len(stack) > 0: + raise ParseError('Unbalanced parenthesis group in formula') + + return Formula(formula) +","Python" +"Metabolic","zhanglab/psamm","psamm/generate_model.py",".py","52137","1311","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2019-2022 Christopher Powers +# Copyright 2021-2022 Jason Vailionis + +from __future__ import unicode_literals +import logging +import argparse +import yaml +import os +import sys +from collections import defaultdict +from collections import OrderedDict +import re +from six import iteritems +from psamm.datasource.native import parse_reaction_equation_string +from psamm.datasource.native import ModelReader +from psamm.datasource.entry import (DictReactionEntry as ReactionEntry) +from psamm.datasource.context import FileMark +from psamm.datasource.reaction import Reaction, Compound, Direction +from psamm.formula import Formula, ParseError +from pkg_resources import resource_filename +import pkg_resources +from psamm.command import _trim +from six import add_metaclass, iteritems, text_type +import abc +from urllib.error import HTTPError +logger = logging.getLogger(__name__) +if sys.version_info.minor > 5: + try: + from Bio.KEGG import REST + except ImportError: + logger.warning(""WARNING: Biopython package not found! "" + ""Some functions will be unusable"") + try: + from libchebipy._chebi_entity import ChebiEntity + except ImportError: + logger.warning(""WARNING: The Chebi API package not found! "" + ""Some functions will be unusable"") + + +class ParseError2(Exception): + """"""Exception used to signal errors while parsing"""""" + + +class VersionError(Exception): + """"""Exception used to signal incorrect python version"""""" + + +class CommandError(Exception): + """"""Error from running a command. + + This should be raised from a ``Command.run()`` if any arguments are + misspecified. When the command is run and the ``CommandError`` is raised, + the caller will exit with an error code and print appropriate usage + information. + """""" + + +class InputError(Exception): + """"""Exception used to signal a general input error. Exiting..."""""" + + +def dict_representer(dumper, data): + return dumper.represent_dict(data.items()) + + +def dict_constructor(loader, node): + return OrderedDict(loader.construct_pairs(node)) + + +@add_metaclass(abc.ABCMeta) +class Command(object): + """"""Represents a command in the interface, operating on a model. + + The constructor will be given the NativeModel and the command + linenamespace. The subclass must implement :meth:`run` to + handle commandexecution. The doc string will be used as + documentation for the command in the command line interface. + + In addition, :meth:`init_parser` can be implemented as a + classmethod which will allow the command to initialize an + instance of :class:`argparse.ArgumentParser` as desired. + The resulting argumentnamespace will be passed to the + constructor. + """""" + + def __init__(self, args): + self._args = args + + @classmethod + def init_parser(cls, parser): + """"""Initialize command line parser (:class:`argparse.ArgumentParser`)"""""" + + @abc.abstractmethod + def run(self): + """"""Execute command"""""" + + def argument_error(self, msg): + """"""Raise error indicating error parsing an argument."""""" + raise CommandError(msg) + + def fail(self, msg, exc=None): + """"""Exit command as a result of a failure."""""" + logger.error(msg) + if exc is not None: + logger.debug('Command failure caused by exception!', exc_info=exc) + sys.exit(1) + + +def parse_orthology(orthology, type, col): + ''' + function to parse orthology tables. The default format for these + tables is the default eggnog output, but custom colummn numers can be + passed through the --col argument + ''' + # Dictionary of reactions to genes + asso_dict = defaultdict(lambda: []) + # Populate the dictionary + with open(orthology, ""r"") as infile: + for line in infile: + if line.startswith('#'): + continue + line = line.rstrip() + listall = re.split(""\t"", line) + # Add handling for a provided column number. + if col: + if len(listall[col-1]) > 0: + keys = listall[col-1].split(',') + else: + keys = [] + else: + if type == ""R"": + keys = listall[14].split(',') + elif type == ""EC"": + keys = listall[10].split(',') + elif type == ""KO"": + keys = listall[11].split(',') + elif type == ""tcdb"": + if listall[17] == '-': + continue + keys = listall[17].split(',') + if len(keys) == 0: + continue + for k in keys: + asso_dict[k].append(listall[0]) + return(asso_dict) + + +def model_reactions(reaction_entry_list): + ''' + Function to sort the downloaded kegg object into a format + that is compatible with the psamm api for storage in + a reactions.yaml file. + ''' + for reaction in reaction_entry_list: + + d = OrderedDict() + d['id'] = reaction.id + + enzymes_list = [] + for i in reaction.enzymes: + enzymes_list.append(i) + + pathways_list = [] + if reaction.pathways is not None: + for i in reaction.pathways: + pathways_list.append(i[1]) + if len(pathways_list) == 0: + pathways_list = None + + orth_list = [] + for i in reaction.orthology: + orth_list.append(i) + if len(orth_list) == 0: + orth_list = None + + if hasattr(reaction, 'name') and reaction.name is not None: + d['name'] = reaction.name + if hasattr(reaction, 'names') and reaction.names is not None: + names_l = [] + for i in reaction.names: + names_l.append(i) + d['names'] = names_l + if hasattr(reaction, 'equation') and reaction.equation is not None: + d['equation'] = str(reaction.equation) + if hasattr(reaction, 'definition') and reaction.definition is not None: + d['KEGG_definition'] = reaction.definition + if hasattr(reaction, 'enzymes') and reaction.enzymes is not None: + d['enzymes'] = enzymes_list + if hasattr(reaction, 'pathways') and reaction.pathways is not None: + d['pathways'] = pathways_list + if hasattr(reaction, 'comment') and reaction.comment is not None: + d['comment'] = str(reaction.comment) + if hasattr(reaction, 'tcdb_family') and \ + reaction.tcdb_family is not None: + d['tcdb_family'] = str(reaction.tcdb_family) + if hasattr(reaction, 'substrates') and \ + reaction.substrates is not None: + d['substrates'] = reaction.substrates + if hasattr(reaction, 'genes') and \ + reaction.genes is not None: + d['genes'] = str(reaction.genes) + if hasattr(reaction, 'orthology') and \ + reaction.orthology is not None: + d['orthology'] = orth_list + yield d + + +def clean_reaction_equations(reaction_entry_list): + ''' + This function handles specific edge cases in the kegg + format of reaction equations that are incompatible with + the psamm format. Takes the downloaded dictionary of reactions + and returns the same dictionary with modified equations, + if necessary. + ''' + generic = [] + for reaction in reaction_entry_list: + equation = re.sub(r'\(.*?\)', lambda x: ''.join(x.group(0).split()), + str(reaction.equation)) + equation_out = [] + comp = re.split("" "", equation) + comp = comp + [""""] + + for i in range(0, len(comp)-1): + # Handles unusual stoichiometry at the beginning of compounds + if ""("" in comp[i] and ""C"" in comp[i+1]: + if i > 0: + if ""="" in comp[i-1] or ""+"" in comp[i-1]: + equation_out.append(comp[i]) + continue + else: + equation_out.append(comp[i]) + continue + generic.append(reaction.id) + # special handling to retain stoichiometry of (n+1) and (n-1), etc. + # at the end of the compound + if ""("" in comp[i]: # and (not ""(n+"" in i or not ""(n-"" in i): + comp[i] = comp[i].replace(""("", ""["") + comp[i] = comp[i].replace("")"", ""]"") + generic.append(reaction.id) + equation_out.append(comp[i]) + equation = ' '.join(equation_out) + reaction.__dict__['values']['equation'] = [equation] + + return(reaction_entry_list, generic) + + +def create_model_api(out, rxn_mapping, verbose, use_rhea, default_compartment): + ''' + This function creates a draft model based on the reactions:genes + file specified in the rxn variable. This function generates + reaction and compound information by utilizing the kegg + REST api to download the reaction information and uses psamm + functions to parse out the kegg data. + ''' + with open(os.path.join(out, ""log.tsv""), ""a+"") as f: + f.write(""List of invalid Kegg IDs: \n"") + + if verbose: + logger.info(""There are {} reactions to download"" + ""."".format(len(rxn_mapping))) + # Generate the yaml file for the reactions + reaction_entry_list = [] + count = 0 + for entry in _download_kegg_entries(out, rxn_mapping, None, ReactionEntry): + reaction_entry_list.append(entry) + count += 1 + if verbose and count % 25 == 0: + logger.info(""{}/{} reactions downloaded..."" + .format(count, len(rxn_mapping))) + + # Clean up the kegg reaction dict. + reaction_entry_list, gen = clean_reaction_equations(reaction_entry_list) + + # Sets up the yaml object for the reactions and writes + # out the parsed reaction information to a reactions.yaml + # file + yaml.add_representer(OrderedDict, dict_representer) + yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, + dict_constructor) + yaml_args = {'default_flow_style': False, + 'encoding': 'utf-8', + 'allow_unicode': True} + + # Load database once if --rhea is given + if use_rhea: + rhea_db = RheaDb(resource_filename('psamm', + 'external-data/chebi_pH7_3_mapping.tsv')) + else: + rhea_db = None + + compound_entry_list = [] + compound_set = set() + for reaction in reaction_entry_list: + eq = parse_reaction_equation_string(reaction.equation, 'c') + for i in eq.compounds: + compound_set.add(str(i[0].name)) + if verbose: + logger.info(""There are {} compounds to download."" + .format(len(compound_set))) + count = 0 + logger.info(""Downloading kegg entries and performing charge correction"") + for entry in _download_kegg_entries(out, compound_set, + rhea_db, CompoundEntry): + compound_entry_list.append(entry) + count += 1 + if verbose and count % 25 == 0: + logger.info(""{}/{} compounds downloaded..."". + format(count, len(compound_set))) + with open(os.path.join(out, 'compounds.yaml'), 'w+') as f: + yaml.dump(list(model_compounds(compound_entry_list)), f, **yaml_args) + + # generate a yaml file for all generic compounds + generic_compounds_list = check_generic_compounds(compound_entry_list) + generic_entry_list = [] + logger.info(""Downloading kegg entries for generic compounds and "" + ""performing charge correction"") + for entry in _download_kegg_entries(out, generic_compounds_list, rhea_db, + CompoundEntry): + generic_entry_list.append(entry) + with open(os.path.join(out, 'compounds_generic.yaml'), 'w+') as f: + yaml.dump(list(model_generic_compounds(generic_entry_list)), + f, **yaml_args) + with open(os.path.join(out, 'log.tsv'), ""a+"") as f: + f.write(""\nThere are {} generic compounds in the model\n"".format(str( + len(generic_compounds_list)))) + f.write(""Generic compounds:\n"") + for i in generic_entry_list: + f.write(""{}"".format(i.id)) + if i.name: + f.write(""|{}"".format(i.name)) + else: + f.write(""|"") + if i.formula: + f.write(""|{}\n"".format(i.formula)) + else: + f.write(""|\n"") + + # generate a yaml for the reactions containing generic compounds and + # and reactions without without generic compounds + reaction_list_out = [] + reaction_list_generic = [] + compound_list_out = set() + + with open(os.path.join(out, 'log.tsv'), 'a+') as f: + f.write(""\nThe reactions containing these generic compounds are: \n"") + for reaction in reaction_entry_list: + if any(i in str(reaction.equation) + for i in generic_compounds_list) or reaction.id in gen: + f.write(""{}"".format(reaction.id)) + if reaction.name: + f.write(""|{}"".format(reaction.name)) + else: + f.write(""|"") + if reaction.equation: + f.write(""|{}\n"".format(reaction.equation)) + else: + f.write(""|\n"") + reaction_list_generic.append(reaction) + else: + reaction_list_out.append(reaction) + for c in str(reaction.equation): + compound_list_out.add(str(c)) + + with open(os.path.join(out, 'reactions.yaml'), 'w+') as f: + yaml.dump(list(model_reactions(reaction_list_out)), f, **yaml_args) + with open(os.path.join(out, 'reactions_generic.yaml'), 'w+') as f: + yaml.dump(list(model_reactions(reaction_list_generic)), f, **yaml_args) + + # Create a model.yaml file + with open('{}/model.yaml'.format(out), mode='w') as myam: + myam.write('default_flux_limit: 100\n') + myam.write('default_compartment: {}\n'.format(default_compartment)) + myam.write('extracellular: null\n') + myam.write('biomass: null\n') + myam.write('compounds:\n') + myam.write('- include: ./compounds.yaml\n') + myam.write('reactions:\n') + myam.write('- include: ./reactions.yaml\n') + myam.write('- include: ./gene-association.tsv\n') + myam.write(' format: tsv\n') + myam.write('model:\n') + myam.write('- include: model_def.tsv\n') + + with open('{}/gene-association.tsv'.format(out), mode='w') as outfile: + outfile.write('id\tgenes\n') + for reaction in reaction_list_out: + if len(rxn_mapping[reaction.id]) == 1: + gene_asso = rxn_mapping[reaction.id] + else: + gene_asso = ['({})'.format(gene) + for gene in rxn_mapping[reaction.id]] + outfile.write('{}\t{}\n'.format(reaction.id, + ' or '.join(gene_asso))) + + with open('{}/gene-association_generic.tsv'.format(out), mode='w') \ + as outfile: + outfile.write('id\tgenes\n') + for reaction in reaction_list_generic: + if len(rxn_mapping[reaction.id]) == 1: + gene_asso = rxn_mapping[reaction.id] + else: + gene_asso = ['({})'.format(gene) + for gene in rxn_mapping[reaction.id]] + outfile.write('{}\t{}\n'.format(reaction.id, + ' or '.join(gene_asso))) + + # Create a model_def file with all of the new reactions + with open('{}/model_def.tsv'.format(out), mode='w') as f: + for reaction in reaction_list_out: + f.write('{}\n'.format(reaction.id)) + + # Write out some final statistics for the model + with open(os.path.join(out, 'log.tsv'), 'a+') as f: + f.write(""\nThere are {} reactions in the model"".format(str( + len(reaction_list_out)))) + f.write(""\nThere are {} compounds in the model\n"".format(str( + len(compound_list_out)))) + if verbose: + logger.info(""\nThere are {} reactions in the model"".format(str( + len(reaction_list_out)))) + logger.info(""\nThere are {} compounds in the model\n"".format(str( + len(compound_entry_list)))) + + +def model_compounds(compound_entry_list): + ''' + Function to sort the downloaded kegg object into a format + that is compatible with the psamm api for storage in + a compounds.yaml file. + ''' + non_gen_compounds = [] + for compound in compound_entry_list: + try: + form = Formula.parse(str(compound.formula)) + if form.is_variable(): + continue + elif compound.formula is None: + continue + elif 'R' in str(compound.formula): + continue + else: + d = OrderedDict() + d['id'] = compound.id + non_gen_compounds.append(compound.id) + if hasattr(compound, 'name') and compound.name is not None: + d['name'] = compound.name + if hasattr(compound, 'names') and \ + compound.names is not None: + names_l = [] + for i in compound.names: + names_l.append(i) + d['names'] = names_l + if hasattr(compound, 'formula') and \ + compound.formula is not None: + d['formula'] = str(compound.formula) + if hasattr(compound, 'mol_weight') and \ + compound.mol_weight is not None: + d['mol_weight'] = compound.mol_weight + if hasattr(compound, 'comment') and \ + compound.comment is not None: + d['comment'] = str(compound.comment) + if hasattr(compound, 'dblinks') and \ + compound.dblinks is not None: + for key, value in compound.dblinks: + if key != 'ChEBI': + d['{}'.format(key)] = value + if hasattr(compound, 'chebi') \ + and compound.chebi is not None: + d['ChEBI'] = compound.chebi + if hasattr(compound, 'chebi_all') \ + and compound.chebi_all is not None: + d['ChEBI_all'] = compound.chebi_all + if hasattr(compound, 'charge') \ + and compound.charge is not None: + d['charge'] = compound.charge + yield d + except ParseError: + logger.warning(""import of {} failed"" + "" and will not be imported into compounds.yaml "" + ""or compounds_generic.yaml"".format(compound.id)) + continue + + +def check_generic_compounds(compound_entry_list): + ''' + Function for checking if the compound formulation is + compatible with psamm. generalized rules for this are + that compounds must have a formula, the formula cannot + be variable (e.g. presence of X), and R groups are + generally discouraged. + ''' + generic_compounds_list = [] + for compound in compound_entry_list: + try: + form = Formula.parse(str(compound.formula)) + if form.is_variable(): + generic_compounds_list.append(compound.id) + elif compound.formula is None: + generic_compounds_list.append(compound.id) + elif 'R' in str(compound.formula): + generic_compounds_list.append(compound.id) + else: + continue + except ParseError: + generic_compounds_list.append(compound.id) + return(generic_compounds_list) + + +def model_generic_compounds(compound_entry_list): + ''' + Function to sort the downloaded kegg object into a format + that is compatible with the psamm api for storage in + a generic_compounds.yaml file. This function contains + special error handling for improperly formatted compounds + ''' + non_gen_compounds = [] + for compound in compound_entry_list: + try: + d = OrderedDict() + d['id'] = compound.id + non_gen_compounds.append(compound.id) + if hasattr(compound, 'name') and compound.name is not None: + d['name'] = compound.name + if hasattr(compound, 'names') and compound.names is not None: + names_l = [] + for i in compound.names: + names_l.append(i) + d['names'] = names_l + if hasattr(compound, 'formula') and compound.formula is not None: + d['formula'] = str(compound.formula) + if hasattr(compound, 'mol_weight') and \ + compound.mol_weight is not None: + d['mol_weight'] = compound.mol_weight + if hasattr(compound, 'comment') and compound.comment is not None: + d['comment'] = str(compound.comment) + if hasattr(compound, 'dblinks') and compound.dblinks is not None: + for key, value in compound.dblinks: + if key != 'ChEBI': + d['{}'.format(key)] = value + if hasattr(compound, 'chebi') and compound.chebi is not None: + d['ChEBI'] = compound.chebi + if hasattr(compound, 'chebi_all') and \ + compound.chebi_all is not None: + d['ChEBI_all'] = compound.chebi_all + if hasattr(compound, 'charge') and compound.charge is not None: + d['charge'] = compound.charge + yield d + except ParseError: + logger.warning(""{} is improperly formatted "" + "" and will not be imported into "" + ""compounds_generic.yaml"".format(compound.id)) + continue + + +def _download_kegg_entries(out, rxn_mapping, rhea, entry_class, context=None): + ''' + Downloads the kegg entry associated with a reaction or + a compound and stores each line in an object that can + be parsed as a reaction or a compound, depending on the + input + ''' + # go through the rxn mapping dict and pull all of the + # reaction information out of the Kegg API + with open(os.path.join(out, 'log.tsv'), ""a+"") as f: + for reactions in rxn_mapping: + # Check for standard formatting of R and C. These can be treated + # the same way + if reactions[0] == ""R"" or reactions[0] == ""C"": + # Try except loop to catch a failure to download. + # On a failure, the failure gets recorded in the log + try: + request = REST.kegg_get(reactions) + except HTTPError: + f.write("""".join(["" - "", reactions, ""\n""])) + continue + entry_line = None + section_id = None + reaction = {} + for lineno, line in enumerate(request): + line = line.rstrip() + if line == ""///"": + continue + if entry_line is None: + entry_line = lineno + # Look for the beginning of the section + m = re.match(r'([A-Z_]+)\s+(.*)', line.rstrip()) + if m is not None: + section_id = m.group(1).lower() + reaction[section_id] = [m.group(2)] + elif section_id is not None: + reaction[section_id].append(line.strip()) + else: + raise ParseError2( + 'Missing section identifier at line \ + {}'.format(lineno)) + mark = FileMark(context, entry_line, 0) + yield entry_class(reaction, rhea, filemark=mark) + + +def parse_rxns_from_EC(rxn_mapping, out, verbose): + """""" + Functions converts gene associations to EC into gene + associations for reaction IDs. Returns a dictionary + of Reaction IDs to genes. + """""" + rxn_dict = defaultdict(lambda: []) + if verbose: + logger.info(""Downloading reactions associated with EC..."") + logger.info(""There are {} ECs download"".format(len(rxn_mapping))) + count = 0 + with open(os.path.join(out, ""log.tsv""), ""a+"") as f: + for reactions in rxn_mapping: + if verbose: + if count % 25 == 0: + logger.info(""{}/{} have been downloaded"".format(count, + len(rxn_mapping))) + count += 1 + try: + request = REST.kegg_get(reactions) + except HTTPError: + f.write("""".join(["" - "", reactions, ""\n""])) + continue + entry_line = None + section_id = None + reaction = {} + for lineno, line in enumerate(request): + line = line.rstrip() + if line == ""///"": + continue + if entry_line is None: + entry_line = lineno + # Look for the beginning of the section + m = re.match(r'([A-Z_]+)\s+(.*)', line.rstrip()) + if m is not None: + section_id = m.group(1).lower() + reaction[section_id] = [m.group(2)] + elif section_id is not None: + reaction[section_id].append(line.strip()) + else: + raise ParseError2('Missing section identifier at line ' + '{}'.format(lineno)) + if ""all_reac"" in reaction: + listall = re.split("" "", reaction[""all_reac""][0]) + for r in listall: + if r[0] == ""R"": + rxn_dict[r] += rxn_mapping[reactions] + + return(rxn_dict) + + +def parse_rxns_from_KO(rxn_mapping, out, verbose): + """""" + Functions converts gene associations to EC into gene + associations for reaction IDs. Returns a dictionary + of Reaction IDs to genes. + """""" + rxn_dict = defaultdict(lambda: []) + if verbose: + logger.info(""Downloading reactions associated with KO..."") + logger.info(""There are {} KOs download"".format(len(rxn_mapping))) + count = 0 + with open(os.path.join(out, ""log.tsv""), ""a+"") as f: + for reactions in rxn_mapping: + if verbose: + if count % 25 == 0: + logger.info(""{}/{} have been downloaded"".format(count, + len(rxn_mapping))) + count += 1 + try: + request = REST.kegg_get(reactions) + except HTTPError: + f.write("""".join(["" - "", reactions, ""\n""])) + continue + entry_line = None + section_id = None + reaction = {} + for lineno, line in enumerate(request): + line = line.rstrip() + if line == ""///"": + continue + if entry_line is None: + entry_line = lineno + # Look for the beginning of the section + m = re.match(r'([A-Z_]+)\s+(.*)', line.rstrip()) + if m is not None: + section_id = m.group(1).lower() + reaction[section_id] = [m.group(2)] + elif section_id is not None: + reaction[section_id].append(line.strip()) + else: + raise ParseError2( + 'Missing section identifier at line \ + {}'.format(lineno)) + if ""dblinks"" in reaction: + for i in reaction[""dblinks""]: + if i[0:2] == ""RN"": + listall = re.split("" "", i[1:]) + for r in listall: + if r[0] == ""R"": + rxn_dict[r] += rxn_mapping[reactions] + return(rxn_dict) + + +def gen_transporters(path, gene_asso, tp_sub_dict, tp_fam_dict, chebi_dict, + compartment_in, compartment_out): + with open(os.path.join(path, ""transporter_log.tsv""), 'w') \ + as log: + log.write(""compounds for which transporters were predicted, but"" + "" are not found in the model:\n"") + eq = defaultdict(lambda: []) + for id, genes in gene_asso.items(): + # if there is just one substrate and it is in the porin family + # assume passive diffusion/porin behavior + if len(tp_sub_dict[id]) == 1: # id[0] == ""1"" and + for cpd in tp_sub_dict[id]: + if cpd in chebi_dict: + eq[id].append((""{}_diff"".format(chebi_dict[cpd][0]), + Reaction(Direction.Both, + {Compound(chebi_dict[cpd][0]). + in_compartment(compartment_in): -1, + Compound(chebi_dict[cpd][0]). + in_compartment(compartment_out): 1}))) + else: + log.write(""{}\t{}\n"".format(""Compound not in "" + ""model: "", cpd, id)) + # Otherwise, create a template reaction entry with no + # formulation for user curation + else: + eq[id].append((""TP_{}"".format(id), + Reaction(Direction.Both, + {Compound("""").in_compartment( + compartment_in): -1, + Compound("""").in_compartment( + compartment_out): 1}))) + + # Sets up the yaml object for the reactions and writes + # out the parsed reaction information to a reactions.yaml + # file + yaml.add_representer(OrderedDict, dict_representer) + yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, + dict_constructor) + yaml_args = {'default_flow_style': False, + 'encoding': 'utf-8', + 'allow_unicode': True} + + # construct a new reactions.yaml file based on this. + reaction_entry_list = [] + mark = FileMark(None, 0, 0) + rhea = None + with open(os.path.join(path, ""transporters.yaml""), + ""w"") as f: + for tcdb in eq: + for rxn in eq[tcdb]: + fam_id = ""."".join(tcdb.split(""."")[0:3]) + reaction = {'transport_name': rxn[0], 'entry': [rxn[0]], + 'name': [tp_fam_dict[fam_id]], + 'equation': [str(rxn[1])], + 'enzyme': [tcdb], + 'tcdb_family': tp_fam_dict[fam_id], + 'substrates': tp_sub_dict[tcdb], + 'genes': ""({})"".format("" or "".join( + gene_asso[tcdb]))} + entry = ReactionEntry(reaction, rhea, filemark=mark) + reaction_entry_list.append(entry) + + yaml.dump(list(model_reactions(reaction_entry_list)), f, + **yaml_args) + + +class main_transporterCommand(Command): + """"""Predicts the function of transporter reactions. + + Output based on algorithm outlined in PMID: 18586723"""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument('--annotations', metavar='path', + help='Path to the annotation file from eggnog') + parser.add_argument('--db_substrates', type=str, + help='OPTIONAL. Path to a custom substrate file.') + parser.add_argument('--db_families', type=str, + help='OPTIONAL. Path to a custom family file.') + parser.add_argument('--model', metavar='path', + help='Path to the model directory') + parser.add_argument('--compartment_in', default='c', + help='abbreviation for the internal compartment') + parser.add_argument('--compartment_out', default='e', + help='abbreviation for the external compartment') + parser.add_argument('--col', default=None, help='If providing your own' + ' annotation table, specify column for the R, EC, ' + 'or KO number. The default is to parse eggnog' + ' output.', type=int) + super(main_transporterCommand, cls).init_parser(parser) + + def run(self): + if sys.version_info.minor < 6: + raise VersionError(""Biopython only compatible with python > 3.5."") + '''Entry point for the transporter assignment''' + + # Check the validity of the input values + if not self._args.annotations: + raise InputError('Please specify a path to the annotations') + if self._args.db_substrates: + logger.info(""Using custom transporter families"") + substrate = self._args.db_substrates + else: + logger.info(""Using the default transporter families from TCDB. "" + ""Downloaded from: "") + logger.info(""http://www.tcdb.org/cgi-bin/projectv/public/"" + ""getSubstrates.py"") + substrate = resource_filename('psamm', + 'external-data/tcdb_substrates.tsv') + if self._args.db_families: + logger.info(""Using custom transporter families"") + family = self._args.db_families + else: + logger.info(""Using the default transporter families from TCDB. "" + ""Downloaded from: "") + logger.info(""http://www.tcdb.org/cgi-bin/projectv/public/"" + ""families.py"") + family = resource_filename('psamm', + 'external-data/tcdb_families.tsv') + if not self._args.model: + raise InputError('Please specify a directory to an existing model') + + # read in the model and build a dictionary of Chebi IDs + mr = ModelReader.reader_from_path(self._args.model) + nm = mr.create_model() + + chebi_dict = defaultdict(lambda: []) + for cpd in nm.compounds: + if 'ChEBI' in cpd.__dict__['_properties']: + chebi = re.split(' ', cpd.__dict__['_properties']['ChEBI']) + for i in chebi: + chebi_dict[""CHEBI:{}"".format(i)].append(cpd.id) + + # Read in the reaction substrates + tp_sub_dict = defaultdict(lambda: []) + with open(substrate, 'r', encoding=""utf8"") as infile: + for line in infile: + line = line.rstrip() + listall = re.split(""\t"", line) + substrates = re.split(r""\|"", listall[1]) + sub_out = [] + for i in substrates: + sub_out.append(re.split("";"", i)[0]) + tp_sub_dict[listall[0]] = sub_out + + # read in the reaction families + tp_fam_dict = defaultdict(lambda: '') + with open(family, 'r', encoding=""utf8"") as infile: + for line in infile: + line = line.rstrip() + listall = re.split(""\t"", line) + tp_fam_dict[listall[0]] = listall[1] + + # build a gene association dictionary + # Launch the parse_orthology function to contruct a gene + # association file + gene_asso = parse_orthology(self._args.annotations, ""tcdb"", + self._args.col) + + # Build the transporter databse based on what is in + # the annotations + if ""model.yaml"" in self._args.model: + path = self._args.model.rstrip(""model.yaml"") + else: + path = self._args.model + gen_transporters(path, gene_asso, tp_sub_dict, tp_fam_dict, + chebi_dict, self._args.compartment_in, + self._args.compartment_out) + + +class main_databaseCommand(Command): + """"""Generate a database of compounds and reactions"""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument('--annotations', metavar='path', + help='Path to the annotation file from Eggnog') + parser.add_argument('--type', type=str, + help='Define whether to build the model on' + ' reaction ID, KO, or EC.\noptions are: ' + '[R, KO, EC]') + parser.add_argument('--out', metavar='out', + help='Path to the output location for the model ' + 'directory. This will be created for you.') + parser.add_argument('--col', default=None, help='If providing your ' + 'own annotation table, specify column for the R, ' + 'EC, or KO number. The default is to parse eggnog' + ' output.', type=int) + parser.add_argument('--verbose', help='Report progress verbose mode', + action='store_true') + parser.add_argument('--default_compartment', + help='Define abbreviation for the default ' + 'compartment', + default='c') + parser.add_argument('--rhea', help='Resolve protonation states ' + 'using major microspecies at pH 7.3 using ' + 'Rhea-ChEBI mappings', action='store_true') + parser.add_argument('--force', help='force rewrite of existing ' + 'directories', action='store_true') + super(main_databaseCommand, cls).init_parser(parser) + + def run(self): + """"""Entry point for the database generation script"""""" + # check if required packages are installed + if 'Bio.KEGG.REST' not in sys.modules: + quit('No biopython package found. ' + 'Please run ''') + if ""libchebipy._chebi_entity"" not in sys.modules: + quit('The Chebi API is not installed. ' + 'Please run ') + if sys.version_info.minor < 6: + raise VersionError(""Biopython only compatible with python > 3.5."") + + # Check the validity of the input values + if not self._args.annotations: + raise InputError('Please specify a path to the eggnog annotations') + if not self._args.type: + raise InputError('Please specify one of R, KO, or EC as the type') + if not self._args.out: + raise InputError('Please specify an output directory') + if os.path.exists(self._args.out) and not self._args.force: + raise InputError('The output directory already exists! Exiting...') + exit() + elif os.path.exists(self._args.out) is False: + os.mkdir(self._args.out) + + # Check the format of the eggnog annotation file. + # Add some code here to check the input file. + + # Launch the parse_orthology function to contruct a + # gene association file + ortho_dict = parse_orthology(self._args.annotations, self._args.type, + self._args.col) + + # convert EC to reactions + if self._args.type == ""EC"": + ortho_dict = parse_rxns_from_EC(ortho_dict, self._args.out, + self._args.verbose) + elif self._args.type == ""KO"": + ortho_dict = parse_rxns_from_KO(ortho_dict, self._args.out, + self._args.verbose) + + # Create the model using the kegg api + create_model_api(self._args.out, ortho_dict, self._args.verbose, + self._args.rhea, self._args.default_compartment) + + +def main(command_class=None, args=None): + """"""Run the command line interface with the given :class:`Command`. + + If no command class is specified the user will be able to select a specific + command through the first command line argument. If the ``args`` are + provided, these should be a list of strings that will be used instead of + ``sys.argv[1:]``. This is mostly useful for testing. + """""" + + # Set up logging for the command line interface + if 'PSAMM_DEBUG' in os.environ: + level = getattr(logging, os.environ['PSAMM_DEBUG'].upper(), None) + if level is not None: + logging.basicConfig(level=level) + else: + logging.basicConfig( + level=logging.INFO, format='%(levelname)s: %(message)s') + + parser = argparse.ArgumentParser(description='Options to generate ' + 'a metabolic model') + + if command_class is not None: + # Command explicitly given, only allow that command + command_class.init_parser(parser) + parser.set_defaults(command=command_class) + else: + # Discover all available options + commands = {} + for entry in pkg_resources.iter_entry_points( + 'psamm.generate_model'): + canonical = entry.name.lower() + if canonical not in commands: + command_class = entry.load() + commands[canonical] = command_class + else: + logger.warning('Option {} was found more than once!'.format( + canonical.name)) + + # Create parsers for subcommands + subparsers = parser.add_subparsers(title='Commands', + metavar='command') + for name, command_class in sorted(iteritems(commands)): + title, _, _ = command_class.__doc__.partition('\n\n') + subparser = subparsers.add_parser( + name, help=title.rstrip('.'), + formatter_class=argparse.RawDescriptionHelpFormatter, + description=_trim(command_class.__doc__)) + subparser.set_defaults(command=command_class) + command_class.init_parser(subparser) + + parsed_args = parser.parse_args(args) + command = parsed_args.command(parsed_args) + try: + command.run() + except CommandError as e: + parser.error(text_type(e)) + + +class ReactionEntry(object): + """"""Representation of entry in KEGG reaction file"""""" + + def __init__(self, values, rhea, filemark=None): + self.values = dict(values) + if 'entry' not in values: + raise ParseError2('Missing reaction identifier') + if 'transport_name' in values: + self._id = values['transport_name'] + else: + self._id, _ = values['entry'][0].split(None, 1) + self._filemark = filemark + + @property + def id(self): + return self._id + + @property + def name(self): + try: + return next(self.names) + except StopIteration: + return None + + @property + def names(self): + if 'name' in self.values: + for line in self.values['name']: + for name in line.rstrip(';').split(';'): + yield name.strip() + + @property + def definition(self): + if 'definition' not in self.values: + return None + return self.values['definition'][0] + + @property + def equation(self): + if 'equation' not in self.values: + return None + return self.values['equation'][0] + + @property + def enzymes(self): + if 'enzyme' in self.values: + for line in self.values['enzyme']: + for enzyme in line.split(): + yield enzyme + + @property + def pathways(self): + if 'pathway' in self.values: + for line in self.values['pathway']: + pathway, name = line.split(None, 1) + yield pathway, name + + @property + def comment(self): + if 'comment' not in self.values: + return None + return '\n'.join(self.values['comment']) + + @property + def tcdb_family(self): + if 'tcdb_family' not in self.values: + return None + return self.values['tcdb_family'] + + @property + def substrates(self): + if 'substrates' not in self.values: + return None + return self.values['substrates'] + + @property + def genes(self): + if 'genes' not in self.values: + return None + return self.values['genes'] + + @property + def orthology(self): + if 'orthology' in self.values: + for line in self.values['orthology']: + split = line.split(None, 1) + yield split[0] + + def __getitem__(self, name): + if name not in self.values: + raise AttributeError('Attribute does not exist: {}'.format(name)) + return self._values[name] + + @property + def filemark(self): + return self._filemark + + def __repr__(self): + return ''.format(self.id) + + +class CompoundEntry(object): + """"""Representation of entry in KEGG compound file"""""" + + def __init__(self, values, rhea, filemark=None): + self.values = dict(values) + if 'entry' not in values: + raise ParseError2('Missing compound identifier') + self._id, _ = values['entry'][0].split(None, 1) + self._filemark = filemark + self._charge = None + self._chebi = None + self._chebi_all = None + self.rhea = rhea + self.initialize_charge() + + def initialize_charge(self): + """""" + Sets the _charge, _chebi, and _chebi_all attributes + 'rhea_db' is initialized as a global in generate_model_api + if --rhea is supplied this funcion looks for rhea_db in the + global namespace decide if rhea is used + --- Logic for selecting the best chebi ID --- + if not using rhea: + use the first chebi ID given by KEGG + elif using rhea: + if all KEGG-chebi IDs map to same ID in rhea: + use the single ID + elif KEGG-chebi IDs map to different IDs in rhea: + use the first chebi ID given by KEGG + elif the KEGG-chebi IDs don't have mappings in rhea: + use the first chebi ID given by KEGG + """""" + if self.rhea is not None: + use_rhea = True + rhea_db = self.rhea + else: + use_rhea = False + for DB, ID in self.dblinks: + if DB == ""ChEBI"": + id_list = ID.split("" "") + if use_rhea: + rhea_id_list = rhea_db.select_chebi_id(id_list) + if len(rhea_id_list) == 0: # no chebis map to rhea + self._chebi = id_list[0] + self._chebi_all = id_list + elif len(set(rhea_id_list)) == 1: # chebi map to same rhea + self._chebi = rhea_id_list[0] + self._chebi_all = set(id_list + [rhea_id_list[0]]) + else: # chebis map to different rheas + self._chebi = id_list[0] + self._chebi_all = set(id_list + rhea_id_list) + else: # --rhea not given + self._chebi = id_list[0] + self._chebi_all = list(id_list) + + # libchebipy update charge and formula + if self._chebi is not None: + this_chebi_entity = ChebiEntity(self._chebi) + try: + try: + # libchebipy sometimes fails with an index error + # on the first time running. We have not been able + # to fix the source of this error, but catching the + # index error and repeating the operation appears to + # fix this + self._charge = int(this_chebi_entity.get_charge()) + self.values['formula'] = [this_chebi_entity.get_formula()] + except IndexError: + self._charge = int(this_chebi_entity.get_charge()) + self.values['formula'] = [this_chebi_entity.get_formula()] + except ValueError: # chebi entry has no charge; leave as None + pass + + @property + def id(self): + return self._id + + @property + def name(self): + try: + return next(self.names) + except StopIteration: + return None + + @property + def names(self): + if 'name' in self.values: + for line in self.values['name']: + for name in line.rstrip(';').split(';'): + yield name.strip() + + @property + def reactions(self): + if 'reaction' in self.values: + for line in self.values['reaction']: + for rxnid in line.split(): + yield rxnid + + @property + def enzymes(self): + if 'enzyme' in self.values: + for line in self.values['enzyme']: + for enzyme in line.split(): + yield enzyme + + @property + def formula(self): + if 'formula' not in self.values: + return None + return self.values['formula'][0] + + @property + def mol_weight(self): + if 'mol_weight' not in self.values: + return None + return float(self.values['mol_weight'][0]) + + @property + def dblinks(self): + if 'dblinks' in self.values: + for line in self.values['dblinks']: + database, entry = line.split(':', 1) + yield database.strip(), entry.strip() + else: + return None + + @property + def charge(self): + return self._charge + + @property + def chebi(self): + return self._chebi + + @property + def chebi_all(self): + if self._chebi_all is not None: + return ', '.join(self._chebi_all) + else: + return None + + @property + def comment(self): + if 'comment' not in self.values: + return None + try: + return '\n'.join(self.values['comment']) + except TypeError: + return self.values['comment'] + + def __getitem__(self, name): + if name not in self.values: + raise AttributeError('Attribute does not exist: {}'.format(name)) + return self._values[name] + + @property + def filemark(self): + return self._filemark + + def __repr__(self): + return ''.format(self.id) + + +class RheaDb(object): + """"""Allows storing and searching Rhea db"""""" + + def __init__(self, filepath): + self._values = self._parse_db_from_tsv(filepath) + + def _parse_db_from_tsv(self, filepath): + db = {} + with open(filepath, 'r') as f: + for line in f: + split = line.split('\t') + db[split[0]] = split[1] + return db + + def select_chebi_id(self, id_list): + rhea_id_list = [] + for x in id_list: + try: + rhea_id_list.append(self._values[x]) + except KeyError: + pass + return rhea_id_list +","Python" +"Metabolic","zhanglab/psamm","psamm/moma.py",".py","13868","363","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2016-2017 Jon Lund Steffensen +# Copyright 2016-2017 Brian Bishop +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Implementation of Minimization of Metabolic Adjustments (MOMA)."""""" + +import logging +from itertools import product + +from six import iteritems, text_type, raise_from + +from psamm.lpsolver import lp + +logger = logging.getLogger(__name__) + + +class MOMAError(Exception): + """"""Error indicating an error solving MOMA."""""" + + +class ConstraintGroup(object): + """"""Constraints that will be imposed on the model when solving. + + Args: + moma: MOMAProblem object for the proposed constraints. + *args: The constraints that are imposed on the model. + """""" + def __init__(self, moma, *args): + self._moma = moma + self._constrs = [] + if len(args) > 0: + self.add(*args) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.delete() + + def add(self, *args): + """"""Add constraints to the model."""""" + self._constrs.extend(self._moma._prob.add_linear_constraints(*args)) + + def delete(self): + """"""Set up the constraints to get deleted on the next solve."""""" + self._moma._remove_constr.extend(self._constrs) + + +class MOMAProblem(object): + """"""Model as a flux optimization problem with minimal flux redistribution. + + Create a representation of the model as an LP optimization problem with + steady state assumption and a minimal redistribution of metabolic fluxes + with respect to the wild type configuration. + + The problem can be solved using any of the four MOMA variants described in + [Segre02]_ and [Mo09]_. MOMA is formulated to avoid the FBA assumption that + that growth efficiency has evolved to an optimal point directly following + model perturbation. MOMA finds the optimal solution for a model with + minimal flux redistribution with respect to the wild type flux + configuration. + + MOMA is implemented with two variations of a linear optimization problem + (:meth:`.lin_moma` and :meth:`.lin_moma2`) and two variations of a + quadratic optimization problem (:meth:`.moma` and :meth:`.moma2`). + Further information on these methods can be found within their respective + documentation. + + The problem can be modified and solved as many times as needed. The flux + of a reaction can be obtained after solving using :meth:`.get_flux`. + + Args: + model: :class:`MetabolicModel` to solve. + solver: LP solver instance to use. + """""" + def __init__(self, model, solver): + self._prob = solver.create_problem() + self._model = model + + self._remove_constr = [] + + self._v_wt = v_wt = self._prob.namespace(name='v_wt') + self._v = v = self._prob.namespace(name='v') + self._z = z = self._prob.namespace(name='z') + self._z_diff = z_diff = self._prob.namespace(name='z_diff') + + # Define flux variables + for reaction_id in self._model.reactions: + lower, upper = self._model.limits[reaction_id] + v_wt.define([reaction_id], lower=lower, upper=upper) + v.define([reaction_id], lower=lower, upper=upper) + z.define([reaction_id], lower=0, upper=max(abs(lower), abs(upper))) + + flux_range = float(upper) - float(lower) + z_diff.define([reaction_id], lower=0, upper=flux_range) + + # Define constraints + mass_balance = self.constraints() + massbalance_lhs = { + spec: 0 for spec in product(model.compounds, ('wt', 'mod'))} + for (compound, reaction_id), value in iteritems(self._model.matrix): + massbalance_lhs[compound, 'wt'] += v_wt[reaction_id] * value + massbalance_lhs[compound, 'mod'] += v[reaction_id] * value + for compound, lhs in iteritems(massbalance_lhs): + mass_balance.add(lhs == 0) + + @property + def prob(self): + """"""Return the underlying LP problem."""""" + return self._prob + + def constraints(self, *args): + """"""Return a constraint object."""""" + return ConstraintGroup(self, *args) + + def _adjustment_reactions(self): + """"""Yield all the non exchange reactions in the model."""""" + for reaction_id in self._model.reactions: + if not self._model.is_exchange(reaction_id): + yield reaction_id + + def _solve(self, sense=None): + """"""Remove old constraints and then solve the current problem. + + Args: + sense: Minimize or maximize the objective. + (:class:`.lp.ObjectiveSense) + + Returns: + The Result object for the solved LP problem + """""" + # Remove the constraints from the last run + while len(self._remove_constr) > 0: + self._remove_constr.pop().delete() + + try: + return self._prob.solve(sense=sense) + except lp.SolverError as e: + raise_from(MOMAError(text_type(e)), e) + finally: + self._remove_constr = [] + + def solve_fba(self, objective): + """"""Solve the wild type problem using FBA. + + Args: + objective: The objective reaction to be maximized. + + Returns: + The LP Result object for the solved FBA problem. + """""" + self._prob.set_objective(self._v_wt[objective]) + return self._solve(lp.ObjectiveSense.Maximize) + + def get_fba_flux(self, objective): + """"""Return a dictionary of all the fluxes solved by FBA. + + Dictionary of fluxes is used in :meth:`.lin_moma` and :meth:`.moma` + to minimize changes in the flux distributions following model + perturbation. + + Args: + objective: The objective reaction that is maximized. + + Returns: + Dictionary of fluxes for each reaction in the model. + """""" + flux_result = self.solve_fba(objective) + fba_fluxes = {} + + # Place all the flux values in a dictionary + for key in self._model.reactions: + fba_fluxes[key] = flux_result.get_value(self._v_wt[key]) + return fba_fluxes + + def get_minimal_fba_flux(self, objective): + """"""Find the FBA solution that minimizes all the flux values. + + Maximize the objective flux then minimize all other fluxes + while keeping the objective flux at the maximum. + + Args: + objective: The objective reaction that is maximized. + + Returns: + A dictionary of all the reactions and their minimized fluxes. + """""" + # Define constraints + vs_wt = self._v_wt.set(self._model.reactions) + zs = self._z.set(self._model.reactions) + + wt_obj_flux = self.get_fba_obj_flux(objective) + + with self.constraints() as constr: + constr.add( + zs >= vs_wt, vs_wt >= -zs, + self._v_wt[objective] >= wt_obj_flux) + self._prob.set_objective(self._z.sum(self._model.reactions)) + result = self._solve(lp.ObjectiveSense.Minimize) + + fba_fluxes = {} + for key in self._model.reactions: + fba_fluxes[key] = result.get_value(self._v_wt[key]) + return fba_fluxes + + def get_fba_obj_flux(self, objective): + """"""Return the maximum objective flux solved by FBA."""""" + flux_result = self.solve_fba(objective) + return flux_result.get_value(self._v_wt[objective]) + + def lin_moma(self, wt_fluxes): + """"""Minimize the redistribution of fluxes using a linear objective. + + The change in flux distribution is mimimized by minimizing the sum + of the absolute values of the differences of wild type FBA solution + and the knockout strain flux solution. + + This formulation bases the solution on the wild type fluxes that + are specified by the user. If these wild type fluxes were calculated + using FBA, then an arbitrary flux vector that optimizes the objective + function is used. See [Segre`_02] for more information. + + Args: + wt_fluxes: Dictionary of all the wild type fluxes. Use + :meth:`.get_fba_flux(objective)` to return a dictionary of + fluxes found by FBA. + """""" + reactions = set(self._adjustment_reactions()) + + z_diff = self._z_diff + v = self._v + + with self.constraints() as constr: + for f_reaction, f_value in iteritems(wt_fluxes): + if f_reaction in reactions: + # Add the constraint that finds the optimal solution, such + # that the difference between the wildtype flux is similar + # to the knockout flux. + constr.add( + z_diff[f_reaction] >= f_value - v[f_reaction], + f_value - v[f_reaction] >= -z_diff[f_reaction]) + + # If we minimize the sum of the z vector then we will minimize + # the |vs_wt - vs| from above + self._prob.set_objective(z_diff.sum(reactions)) + + self._solve(lp.ObjectiveSense.Minimize) + + def lin_moma2(self, objective, wt_obj): + """"""Find the smallest redistribution vector using a linear objective. + + The change in flux distribution is mimimized by minimizing the sum + of the absolute values of the differences of wild type FBA solution + and the knockout strain flux solution. + + Creates the constraint that the we select the optimal flux vector that + is closest to the wildtype. This might still return an arbitrary flux + vector the maximizes the objective function. + + Args: + objective: Objective reaction for the model. + wt_obj: The flux value for your wild type objective reactions. + Can either use an expiremental value or on determined by FBA + by using :meth:`.get_fba_obj_flux(objective)`. + """""" + reactions = set(self._adjustment_reactions()) + + z_diff = self._z_diff + v = self._v + v_wt = self._v_wt + + with self.constraints() as constr: + for f_reaction in reactions: + # Add the constraint that finds the optimal solution, such + # that the difference between the wildtype flux + # is similar to the knockout flux. + constr.add( + z_diff[f_reaction] >= v_wt[f_reaction] - v[f_reaction], + v_wt[f_reaction] - v[f_reaction] >= -z_diff[f_reaction]) + + # If we minimize the sum of the z vector then we will minimize + # the |v_wt - v| from above + self._prob.set_objective(z_diff.sum(reactions)) + + constr.add(self._v_wt[objective] >= wt_obj) + + self._solve(lp.ObjectiveSense.Minimize) + + def moma(self, wt_fluxes): + """"""Minimize the redistribution of fluxes using Euclidean distance. + + Minimizing the redistribution of fluxes using a quadratic objective + function. The distance is minimized by minimizing the sum of + (wild type - knockout)^2. + + Args: + wt_fluxes: Dictionary of all the wild type fluxes that will be + used to find a close MOMA solution. Fluxes can be expiremental + or calculated using :meth: get_fba_flux(objective). + """""" + reactions = set(self._adjustment_reactions()) + v = self._v + + obj_expr = 0 + for f_reaction, f_value in iteritems(wt_fluxes): + if f_reaction in reactions: + # Minimize the Euclidean distance between the two vectors + obj_expr += (f_value - v[f_reaction])**2 + + self._prob.set_objective(obj_expr) + self._solve(lp.ObjectiveSense.Minimize) + + def moma2(self, objective, wt_obj): + """"""Find the smallest redistribution vector using Euclidean distance. + + Minimizing the redistribution of fluxes using a quadratic objective + function. The distance is minimized by minimizing the sum of + (wild type - knockout)^2. + + Creates the constraint that the we select the optimal flux vector that + is closest to the wildtype. This might still return an arbitrary flux + vector the maximizes the objective function. + + Args: + objective: Objective reaction for the model. + wt_obj: The flux value for your wild type objective reactions. + Can either use an expiremental value or on determined by FBA + by using :meth:`.get_fba_obj_flux(objective)`. + """""" + obj_expr = 0 + for reaction in self._adjustment_reactions(): + v_wt = self._v_wt[reaction] + v = self._v[reaction] + obj_expr += (v_wt - v)**2 + + self._prob.set_objective(obj_expr) + + with self.constraints(self._v_wt[objective] >= wt_obj): + self._solve(lp.ObjectiveSense.Minimize) + + def get_flux(self, reaction): + """"""Return the knockout flux for a specific reaction."""""" + return self._prob.result.get_value(self._v[reaction]) + + def get_flux_var(self, reaction): + """"""Return the LP variable for a specific reaction."""""" + return self._v[reaction] +","Python" +"Metabolic","zhanglab/psamm","psamm/bayesian.py",".py","35065","948","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2018-2020 Jing Wang + +""""""Calculate model mapping likelihood with bayesian."""""" +from __future__ import print_function, division +from future.utils import itervalues + +from builtins import object, range +from itertools import product +from multiprocessing import Pool +import operator +import sys +from collections import namedtuple, defaultdict +import pandas as pd +import time + +import psamm.bayesian_util as util +from psamm.formula import Formula +from psamm.expression.boolean import Expression +from functools import reduce + +import logging +logger = logging.getLogger(__name__) + + +CompoundEntry = namedtuple( + 'CompoundEntry', + ['id', 'name', 'formula', 'charge', 'kegg', 'cas']) + +ReactionEntry = namedtuple( + 'ReactionEntry', + ['id', 'name', 'genes', 'equation', 'subsystem', 'ec']) + + +class MappingModel(object): + """"""Generate the internal structure for model mapping. + + Args: + model: :class:`psamm.datasource.native.NativeModel` + """""" + + def __init__(self, model): + self._name = model.name + self._read_compounds(model.compounds) + self._read_reactions(model.reactions) + + self._genes = set() + self._has_gene = list() + for r in itervalues(self._reactions): + if r.genes is not None: + self._has_gene.append(r.id) + e = Expression(r.genes) + self._genes.update([g.symbol for g in e.variables]) + + def _read_compounds(self, it): + self._compounds = {} + for compound in it: + formula = getattr(compound, 'formula', None) + if formula is not None: + formula = Formula.parse(formula) + else: + formula = None + + if 'kegg' in compound.properties: + compound_kegg = compound.properties['kegg'] + else: + compound_kegg = None + + compound_id = compound.id + entry = CompoundEntry( + id=compound_id, name=getattr(compound, 'name', None), + formula=formula, charge=getattr(compound, 'charge', None), + kegg=compound_kegg, + cas=getattr(compound, 'cas', None)) + self._compounds[compound_id] = entry + + def _read_reactions(self, it): + self._reactions = {} + for reaction in it: + genes = getattr(reaction, 'genes', None) + reaction_id = reaction.id + equation = getattr(reaction, 'equation', None) + entry = ReactionEntry( + id=reaction_id, name=getattr(reaction, 'name', None), + genes=genes, equation=equation, + subsystem=getattr(reaction, 'subsystem', None), + ec=getattr(reaction, 'ec', None)) + self._reactions[reaction_id] = entry + + @property + def name(self): + return self._name + + @property + def reactions(self): + return self._reactions + + @property + def compounds(self): + return self._compounds + + @property + def genes(self): + return self._genes + + def print_summary(self): + """"""Print model summary"""""" + print('Model: {}'.format(self.name)) + print('- Compounds: {}'.format(len(self.compounds))) + print('- Reactions: {}'.format(len(self.reactions))) + print('- Genes: {}'.format(len(self.genes))) + print('- Reactions with gene association: {}'.format( + len(self._has_gene))) + + def check_reaction_compounds(self): + """"""Check that reaction compounds are defined in the model"""""" + print('Checking model: {}'.format(self.name)) + consistent = True + undefined_cpds = [] + for reaction in itervalues(self.reactions): + if reaction.equation is not None: + for compound, value in reaction.equation.compounds: + if compound.name not in self.compounds: + undefined_cpds.append(compound.name) + logger.error(( + '{} in reaction {} is not defined in compound ' + 'list (such as compounds.yaml), please define it ' + 'in compound list before running modelmapping' + ).format(compound.name, reaction.id)) + consistent = False + return consistent + + +class BayesianCompoundPredictor(object): + """"""Predict model compound mappings based on a Bayesian model. + + Args: + model1: :class:`psamm.bayesian.MappingModel`. + model2: :class:`psamm.bayesian.MappingModel`. + nproc: number of processes used for mapping. + outpath: the path to output the detailed log file. + log: whether to output log file of the p_match and p_no_match. + kegg: whether to compare the KEGG id. + """""" + + def __init__(self, model1, model2, nproc=1, + outpath='.', log=False, kegg=False): + self._model1 = model1 + self._model2 = model2 + self._column_list = [ + 'p', 'p_id', 'p_name', 'p_charge', 'p_formula', 'p_kegg'] + self._compound_map_p = map_model_compounds( + self._model1, self._model2, nproc, outpath, log=log, kegg=kegg) + + @property + def model1(self): + return self._model1 + + @property + def model2(self): + return self._model2 + + def map(self, c1, c2): + return self._compound_map_p[0][c1, c2] + + def get_raw_map(self): + """"""Return pandas.DataFrame style of raw mapping table."""""" + compound_result = pd.DataFrame({ + self._column_list[i]: self._compound_map_p[i] + for i in range(len(self._column_list)) + }) + return compound_result + + def get_best_map(self, threshold_compound=0): + """"""Return :class:`pandas.DataFrame` style of best mapping for each + query."""""" + raw_map = self.get_raw_map() + query = [i for i, j in raw_map.index.values] + # use rank instead of idxmax to output multiple top-hitts + best_index = raw_map.iloc[:, 0].groupby(query).rank( + method='min', ascending=False).loc[lambda x: x == 1].index.values + compound_best = raw_map.loc[best_index] + compound_best.query( + 'p >= @threshold_compound', inplace=True) + return compound_best + + def get_cpd_pred(self, threshold_compound=0): + """"""Return the cpd_pred used for reaction mapping."""""" + return self.get_best_map(threshold_compound).loc[:, 'p'] + + +class BayesianReactionPredictor(object): + """"""Predict model reaction mappings based on a Bayesian model. + + Args: + model1: :class:`psamm.bayesian.MappingModel`. + model2: :class:`psamm.bayesian.MappingModel`. + cpd_pred: :class:`pandas.Series` with compound pairs as index, + compound mapping score as value. + nproc: number of processes used for mapping. + outpath: the path to output the detailed log file. + log: whether to output log file of the p_match and p_no_match. + gene: whether to compare the gene association. + compartment_map: dictionary mapping compartment id in the query model + to the id in the target model. + gene_map: dictionary mapping gene id in the query model to the id in + the target model. + """""" + + def __init__(self, model1, model2, cpd_pred, nproc=1, + outpath='.', log=False, gene=False, + compartment_map={}, gene_map={}): + self._model1 = model1 + self._model2 = model2 + self._parse_cpd_pred(cpd_pred) + self._column_list = ['p', 'p_id', 'p_name', 'p_equation', 'p_genes'] + gene_map = self._reversible_map(gene_map) + self._reaction_map_p = map_model_reactions( + self._model1, self._model2, self._cpd_map, self._cpd_score, nproc, + outpath, log=log, gene=gene, compartment_map=compartment_map, + gene_map=gene_map) + + @property + def model1(self): + return self._model1 + + @property + def model2(self): + return self._model2 + + def map(self, r1, r2): + return self._reaction_map_p[0][r1, r2] + + def _reversible_map(self, genemap): + newmap = {} + for k, v in genemap.items(): + newmap[k] = v + newmap[v] = k + return newmap + + def _parse_cpd_pred(self, cpd_pred): + self._cpd_map = defaultdict(set) + self._cpd_score = dict() + for pair, score in cpd_pred.items(): + self._cpd_map[pair[0]].add(pair[1]) + self._cpd_score[pair[0]] = score + + def get_raw_map(self): + """"""Return pandas.DataFrame style of raw mapping table."""""" + reaction_result = pd.DataFrame({ + self._column_list[i]: self._reaction_map_p[i] + for i in range(len(self._column_list)) + }) + return reaction_result + + def get_best_map(self, threshold_reaction=0): + """"""Return pandas.DataFrame style of best mapping for each query."""""" + raw_map = self.get_raw_map() + query = [i for i, j in raw_map.index.values] + # use rank instead of idxmax to output multiple top-hitts + best_index = raw_map.iloc[:, 0].groupby(query).rank( + method='min', ascending=False).loc[lambda x: x == 1].index.values + reaction_best = raw_map.loc[best_index] + reaction_best.query( + 'p >= @threshold_reaction', inplace=True) + return reaction_best + + +def compound_id_likelihood(c1, c2, compound_prior, compound_id_marg): + if util.id_equals(c1.id, c2.id): + p_match = 0.4 + p_marg = compound_id_marg + p_no_match = max( + 0, (p_marg - p_match * compound_prior) / (1.0 - compound_prior)) + else: + p_match = 0.6 + p_marg = 1.0 - compound_id_marg + p_no_match = max( + 0, (p_marg - p_match * compound_prior) / (1.0 - compound_prior)) + + return p_match, p_no_match + + +def compound_name_likelihood(c1, c2, compound_prior, compound_name_marg): + if util.name_equals(c1.name, c2.name): + p_match = 0.60 + p_marg = compound_name_marg + p_no_match = max( + 0, (p_marg - p_match * compound_prior) / (1.0 - compound_prior)) + else: + p_match = 0.40 + p_marg = 1.0 - compound_name_marg + p_no_match = max( + 0, (p_marg - p_match * compound_prior) / (1.0 - compound_prior)) + + return p_match, p_no_match # , p_marg + + +def compound_charge_likelihood( + c1, c2, compound_prior, + compound_charge_equal_marg, compound_charge_not_equal_marg): + if c1.charge is None or c2.charge is None: + # p value of observing undefined charge + # it is independent of the condition of match or not + p_match = 1 + p_no_match = 1 + elif c1.charge == c2.charge: + p_match = 0.9 + p_no_match = max( + 0, + ((compound_charge_equal_marg - p_match * compound_prior) / + (1.0 - compound_prior))) + else: + p_match = 0.1 + p_no_match = max( + 0, + ((compound_charge_not_equal_marg - p_match * compound_prior) / + (1.0 - compound_prior))) + + return p_match, p_no_match + + +def compound_formula_likelihood( + c1, c2, compound_prior, + compound_formula_equal_marg, compound_formula_not_equal_marg): + if c1.formula is None or c2.formula is None: + # p value of observing undefined formula + # it is independent of the condition of match or not + p_match = 1 + p_no_match = 1 + elif util.formula_equals(c1.formula, c2.formula, c1.charge, c2.charge): + p_match = 0.9 + p_no_match = max( + 0, + ((compound_formula_equal_marg - p_match * compound_prior) / + (1.0 - compound_prior))) + else: + p_match = 0.1 + p_no_match = max( + 0, + ((compound_formula_not_equal_marg - p_match * compound_prior) / + (1.0 - compound_prior))) + + return p_match, p_no_match + + +def compound_kegg_likelihood( + c1, c2, compound_prior, + compound_kegg_equal_marg, compound_kegg_not_equal_marg): + if c1.kegg is None or c2.kegg is None: + # p value of observing undefined KEGG + # it is independent of the condition of match or not + p_match = 1 + p_no_match = 1 + elif c1.kegg == c2.kegg: + p_match = 0.65 + p_no_match = max( + 0, + ((compound_kegg_equal_marg - p_match * compound_prior) / + (1.0 - compound_prior))) + else: + p_match = 0.35 + p_no_match = max( + 0, + ((compound_kegg_not_equal_marg - p_match * compound_prior) / + (1.0 - compound_prior))) + + return p_match, p_no_match + + +def reaction_id_likelihood( + r1, r2, reaction_prior, + reaction_id_equal_marg, reaction_id_not_equal_marg): + if util.id_equals(r1.id, r2.id): + p_match = 0.3 + p_no_match = max( + 0, + ((reaction_id_equal_marg - p_match * reaction_prior) / + (1.0 - reaction_prior))) + else: + p_match = 0.7 + p_no_match = max( + 0, + ((reaction_id_not_equal_marg - p_match * reaction_prior) / + (1.0 - reaction_prior))) + + return p_match, p_no_match + + +def reaction_name_likelihood(r1, r2, reaction_prior, reaction_name_marg): + if util.name_equals(r1.name, r2.name): + p_match = 0.2 + p_no_match = max( + 0, + ((reaction_name_marg - p_match * reaction_prior) / + (1.0 - reaction_prior))) + else: + p_match = 0.8 + p_no_match = max( + 0, + ((1.0 - reaction_name_marg - p_match * reaction_prior) / + (1.0 - reaction_prior))) + + return p_match, p_no_match + + +def reaction_equation_mapping_approx_max_likelihood( + cpd_set1, cpd_set2, cpd_map, cpd_score, compartment_map={}): + """"""Calculate equation likelihood based on compound mapping."""""" + p_match = 1.0 + p_no_match = 1.0 + + compartment_dict = defaultdict(set) + for c in cpd_set2: + compartment_dict[c.name].add(c.compartment) + + # get the possible best-match pairs, score as the key + best_match = defaultdict(set) + for c1 in cpd_set1: + for c2 in cpd_map[c1.name].intersection(compartment_dict.keys()): + # the compound pair should be in the same compartment + if (compartment_map.get(c1.compartment, c1.compartment) + in compartment_dict[c2]): + best_match[cpd_score[c1.name]].add((c1.name, c2)) + + # translate each element to compound id + cpd_set1 = set(c.name for c in cpd_set1) + cpd_set2 = set(c.name for c in cpd_set2) + + # sort by scores, get the most possible compound pairs first + for score in sorted(best_match.keys(), reverse=True): + for c1, c2 in best_match[score]: + if (c1 in cpd_set1) and (c2 in cpd_set2): + # the possibility that compounds are equal + p_match *= score * 0.9 + (1 - score) * 0.1 + p_no_match *= score * 0.1 + (1 - score) * 0.9 + cpd_set1.remove(c1) + cpd_set2.remove(c2) + if len(cpd_set1) == 0 or len(cpd_set2) == 0: + break + + for c in cpd_set1: + p_match *= 0.1 + p_no_match *= 0.9 + for c in cpd_set2: + p_match *= 0.1 + p_no_match *= 0.9 + + return p_match, p_no_match + + +def reaction_equation_compound_mapping_likelihood( + r1, r2, *args, **kwargs): + """"""Get the likelihood of reaction equations + + Args: + r1, r2: two `RactionEntry` objects to be compared + args, kwargs: + cpd_map: dictionary mapping compound id in the query model to a set + of best-mapping compound ids in the target model. + cpd_score: dictionary mapping compound id in the query model to + its best mapping score during compound mapping. + compartment_map: dictionary mapping compartment id in the query model + to the id in the target model. + """""" + if r1.equation is None or r2.equation is None: + # p value of observing undefined equation + # it is independent of the condition of match or not + p_match = 1 + p_no_match = 1 + else: + p_match, p_no_match = get_best_p_value_set(r1, r2, *args, **kwargs) + + return p_match, p_no_match + + +def get_best_p_value_set(r1, r2, *args, **kwargs): + """"""Assume equations may have reversed direction, report best mapping p."""""" + cpd_set1_left = get_cpd_set(r1.equation, left=True) + cpd_set1_right = get_cpd_set(r1.equation, left=False) + cpd_set2_left = get_cpd_set(r2.equation, left=True) + cpd_set2_right = get_cpd_set(r2.equation, left=False) + + # assume equations have the same direction + p_forward_match, p_forward_no_match = merge_partial_p_set( + cpd_set1_left, cpd_set2_left, + cpd_set1_right, cpd_set2_right, *args, **kwargs) + # assume equations have the reversed direction + p_reverse_match, p_reverse_no_match = merge_partial_p_set( + cpd_set1_left, cpd_set2_right, + cpd_set1_right, cpd_set2_left, *args, **kwargs) + + # maintain the direction with better p values + if (p_forward_match / p_forward_no_match >= + p_reverse_match / p_reverse_no_match): + p_match = p_forward_match + p_no_match = p_forward_no_match + else: + p_match = p_reverse_match + p_no_match = p_reverse_no_match + + return p_match, p_no_match + + +def merge_partial_p_set(cpd_set1_left, cpd_set2_left, + cpd_set1_right, cpd_set2_right, *args, **kwargs): + """"""Merge the left hand side and right hand side p values together. + + The compound mapping is done separately on left hand side and + right hand side. + Then the corresponding p_match and p_no_match are merged together. + """""" + p_set_left = \ + reaction_equation_mapping_approx_max_likelihood( + cpd_set1_left, cpd_set2_left, *args, **kwargs) + p_set_right = \ + reaction_equation_mapping_approx_max_likelihood( + cpd_set1_right, cpd_set2_right, *args, **kwargs) + p_match = p_set_left[0] * p_set_right[0] + p_no_match = p_set_left[1] * p_set_right[1] + return p_match, p_no_match + + +def get_cpd_set(equation, left=True): + if left: # value of left-side compound is negtive + coef = 1 + else: # value of right-side compound is positive + coef = -1 + # pick compounds at one side only + cpd_set = set( + compound + for compound, value in equation.compounds + if coef * value < 0) + return cpd_set + + +def reaction_genes_likelihood(r1, r2, reaction_prior, reaction_genes_marg, + reaction_genes_not_equal_marg, gene_map={}): + if r1.genes is None or r2.genes is None: + p_match = 1 + p_no_match = 1 + elif util.genes_equals(r1.genes, r2.genes, gene_map): + p_match = 0.2 + p_no_match = max( + 0, + ((reaction_genes_marg - p_match * reaction_prior) / + (1.0 - reaction_prior))) + else: + p_match = 0.8 + p_no_match = max( + 0, + ((reaction_genes_not_equal_marg - p_match * reaction_prior) / + (1.0 - reaction_prior))) + + return p_match, p_no_match + + +def fake_likelihood(e1, e2): + """"""Generate fake likelihood if corresponding mapping is not required."""""" + return 1, 1 + + +def generate_likelihood(tasks): + pair, likelihood, args, kwargs = tasks + e1, e2 = pair + p1, p2 = likelihood(e1, e2, *args, **kwargs) + return e1.id, e2.id, p1, p2 + + +def pairwise_likelihood(pool, chunksize, model1, model2, likelihood, + *args, **kwargs): + """"""Compute likelihood of all pairwise comparisons. + + Returns likelihoods as a dataframe with a column for each hypothesis. + """""" + tasks = (((e1, e2), likelihood, args, kwargs) + for e1, e2 in product(itervalues(model1), itervalues(model2))) + result = pool.map(generate_likelihood, tasks, chunksize=chunksize) + return pd.DataFrame.from_records(result, index=('e1', 'e2'), + columns=('e1', 'e2', 'p1', 'p2')) + + +def likelihood_products(likelihood_dfs): + """"""Combine likelihood dataframes."""""" + return reduce(operator.mul, likelihood_dfs, 1.0) + + +def bayes_posterior(prior, likelihood_df): + """"""Calculate posterior given likelihoods and prior."""""" + p_1 = prior * likelihood_df.iloc[:, 0] + p_2 = (1.0 - prior) * likelihood_df.iloc[:, 1] + return p_1 / (p_1 + p_2) + + +def parallel_equel(tasks): + func, params = tasks + return func(*params) + + +def map_model_compounds(model1, model2, nproc=1, outpath='.', + log=False, kegg=False): + """"""Map compounds of two models."""""" + compound_pairs = len(model1.compounds) * len(model2.compounds) + + # Compound prior + # For the prior, use a guesstimate that 95% of the + # smaller model can be mapped. + compound_prior = (0.95 * min(len(model1.compounds), + len(model2.compounds))) / compound_pairs + + # Initialize parallel pool of workers + chunksize = compound_pairs // nproc + pool = Pool(nproc) + + t = time.time() + # Compound ID + print('Calculating compound ID likelihoods...', end=' ') + sys.stdout.flush() + + # Marginal probability of observing two equal compound IDs + tasks = ((util.id_equals, (c1.id, c2.id)) for c1, c2 in product( + itervalues(model1.compounds), itervalues(model2.compounds))) + result = pool.map(parallel_equel, tasks, chunksize=chunksize) + compound_id_marg = sum(result) / float(compound_pairs) + + compound_id_likelihoods = pairwise_likelihood( + pool, chunksize, model1.compounds, model2.compounds, + compound_id_likelihood, compound_prior, compound_id_marg) + + print('%.2f seconds' % (time.time() - t)) + t = time.time() + # Compound name + print('Calculating compound name likelihoods...', end=' ') + sys.stdout.flush() + + # Marginal probability of observing two similar names + tasks = ((util.name_equals, (c1.name, c2.name)) for c1, c2 in product( + itervalues(model1.compounds), itervalues(model2.compounds))) + result = pool.map(parallel_equel, tasks, chunksize=chunksize) + compound_name_marg = sum(result) / float(compound_pairs) + + compound_name_likelihoods = pairwise_likelihood( + pool, chunksize, model1.compounds, model2.compounds, + compound_name_likelihood, compound_prior, compound_name_marg) + + print('%.2f seconds' % (time.time() - t)) + t = time.time() + + # Compound charge + print('Calculating compound charge likelihoods...', end=' ') + sys.stdout.flush() + + # Marginal probability of observing two compounds with the same charge + compound_charge_equal_marg = sum( + c1.charge is not None and + c2.charge is not None and + c1.charge == c2.charge + for c1, c2 in product( + itervalues(model1.compounds), itervalues(model2.compounds)) + ) / compound_pairs + + # Marginal probability of observing two compounds with different charge + compound_charge_not_equal_marg = sum( + c1.charge is not None and + c2.charge is not None and + c1.charge != c2.charge + for c1, c2 in product( + itervalues(model1.compounds), itervalues(model2.compounds)) + ) / compound_pairs + + compound_charge_likelihoods = pairwise_likelihood( + pool, chunksize, model1.compounds, model2.compounds, + compound_charge_likelihood, + compound_prior, + compound_charge_equal_marg, + compound_charge_not_equal_marg) + + print('%.2f seconds' % (time.time() - t)) + t = time.time() + + # Compound formula + print('Calculating compound formula likelihoods...', end=' ') + sys.stdout.flush() + + # Marginal probability of observing two compounds with the same formula + tasks = (( + util.formula_equals, + (c1.formula, c2.formula, c1.charge, c2.charge)) + for c1, c2 in product( + itervalues(model1.compounds), itervalues(model2.compounds))) + result = pool.map(parallel_equel, tasks, chunksize=chunksize) + compound_formula_equal_marg = sum(result) / float(compound_pairs) + + # Marginal probability of observing two compounds with different formula + compound_formula_not_equal_marg = 1.0 - compound_formula_equal_marg - ( + sum(c1.formula is None or c2.formula is None + for c1, c2 in product(itervalues(model1.compounds), + itervalues(model2.compounds))) / + compound_pairs) + + compound_formula_likelihoods = pairwise_likelihood( + pool, chunksize, model1.compounds, model2.compounds, + compound_formula_likelihood, + compound_prior, compound_formula_equal_marg, + compound_formula_not_equal_marg) + + print('%.2f seconds' % (time.time() - t)) + t = time.time() + + # Compound KEGG id + if kegg: # run KEGG id mapping + print('Calculating compound KEGG ID likelihoods...', end=' ') + sys.stdout.flush() + + # Marginal probability of observing two compounds + # where KEGG ids are equal + compound_kegg_equal_marg = sum( + c1.kegg is not None and + c2.kegg is not None and + c1.kegg == c2.kegg + for c1, c2 in product( + itervalues(model1.compounds), + itervalues(model2.compounds)) + ) / compound_pairs + + # Marginal probability of observing two compounds + # where KEGG ids are different + compound_kegg_not_equal_marg = sum( + c1.kegg is not None and + c2.kegg is not None and + c1.kegg != c2.kegg for c1, c2 in product( + itervalues(model1.compounds), + itervalues(model2.compounds)) + ) / compound_pairs + + compound_kegg_likelihoods = pairwise_likelihood( + pool, chunksize, model1.compounds, model2.compounds, + compound_kegg_likelihood, + compound_prior, compound_kegg_equal_marg, + compound_kegg_not_equal_marg) + + print('%.2f seconds' % (time.time() - t)) + t = time.time() + else: # run fake mapping + compound_kegg_likelihoods = pairwise_likelihood( + pool, chunksize, model1.compounds, model2.compounds, + fake_likelihood) + + pool.close() + pool.join() + + if log: + merge_result = pd.merge(compound_id_likelihoods, + compound_name_likelihoods, + left_index=True, right_index=True, + suffixes=('_id', '_name')) + merge_result = pd.merge(merge_result, compound_charge_likelihoods, + left_index=True, right_index=True, + suffixes=('_name', '_charge')) + merge_result = pd.merge(merge_result, compound_formula_likelihoods, + left_index=True, right_index=True, + suffixes=('_charge', '_formula')) + merge_result = pd.merge(merge_result, compound_kegg_likelihoods, + left_index=True, right_index=True, + suffixes=('_formula', '_kegg')) + + merge_result.to_csv(outpath + '/compound_log.tsv', sep='\t') + + all_likelihoods = [compound_id_likelihoods, + compound_name_likelihoods, + compound_charge_likelihoods, + compound_formula_likelihoods, + compound_kegg_likelihoods] + + return (bayes_posterior(compound_prior, + likelihood_products(all_likelihoods)), + bayes_posterior(compound_prior, compound_id_likelihoods), + bayes_posterior(compound_prior, compound_name_likelihoods), + bayes_posterior(compound_prior, compound_charge_likelihoods), + bayes_posterior(compound_prior, compound_formula_likelihoods), + bayes_posterior(compound_prior, compound_kegg_likelihoods)) + + +def map_model_reactions(model1, model2, cpd_map, cpd_score, nproc=1, + outpath='.', log=False, gene=False, compartment_map={}, + gene_map={}): + """"""Map reactions of two models."""""" + # Mapping of reactions + reaction_pairs = len(model1.reactions) * len(model2.reactions) + + # Reaction prior + # For the prior, use a guesstimate that 95% + # of the smaller model can be mapped. + reaction_prior = (0.95 * min(len(model1.reactions), + len(model2.reactions))) / reaction_pairs + + # Initialize parallel pool of workers + chunksize = reaction_pairs // nproc + pool = Pool(nproc) + + # Reaction ID + t = time.time() + print('Calculating reaction ID likelihoods...', end=' ') + sys.stdout.flush() + + # Marginal probability of observing two reactions with the same ids. + tasks = ((util.id_equals, (r1.id, r2.id)) for r1, r2 in product( + itervalues(model1.reactions), + itervalues(model2.reactions))) + result = pool.map(parallel_equel, tasks, chunksize=chunksize) + reaction_id_equal_marg = sum(result) / float(reaction_pairs) + + # Marginal probability of observing two reactions with different ids. + reaction_id_not_equal_marg = 1.0 - reaction_id_equal_marg + + reaction_id_likelihoods = pairwise_likelihood( + pool, chunksize, model1.reactions, model2.reactions, + reaction_id_likelihood, + reaction_prior, reaction_id_equal_marg, reaction_id_not_equal_marg) + + print('%.2f seconds' % (time.time() - t)) + t = time.time() + # Reaction name + print('Calculating reaction name likelihoods...', end=' ') + sys.stdout.flush() + + # Marginal probability of observing two reactions with the same name. + tasks = ((util.name_equals, (r1.name, r2.name)) for r1, r2 in product( + itervalues(model1.reactions), + itervalues(model2.reactions))) + result = pool.map(parallel_equel, tasks, chunksize=chunksize) + reaction_name_equal_marg = sum(result) / float(reaction_pairs) + + reaction_name_likelihoods = pairwise_likelihood( + pool, chunksize, model1.reactions, model2.reactions, + reaction_name_likelihood, reaction_prior, reaction_name_equal_marg) + + print('%.2f seconds' % (time.time() - t)) + t = time.time() + + # Reaction equation + + print('Calculating reaction equation likelihoods...', end=' ') + sys.stdout.flush() + reaction_equation_likelihoods = pairwise_likelihood( + pool, chunksize, model1.reactions, model2.reactions, + reaction_equation_compound_mapping_likelihood, + cpd_map, cpd_score, compartment_map) + + print('%.2f seconds' % (time.time() - t)) + t = time.time() + + # Reaction genes + # For each gene, the marginal probability of observing that gene + # in each model. We use this as an approximation of the probability of + # observing a pair of genes in two reactions given that the reaction + # do _not_ match. + if gene: + print('Calculating reaction genes likelihoods...', end=' ') + sys.stdout.flush() + + # Marginal probability of observing two reactions with + # equal gene associations. + tasks = ((util.genes_equals, (r1.genes, r2.genes)) + for r1, r2 in product( + itervalues(model1.reactions), + itervalues(model2.reactions))) + result = pool.map(parallel_equel, tasks, chunksize=chunksize) + reaction_genes_equal_marg = sum(result) / float(reaction_pairs) + + # Marginal probability of observing two reactions with unequal + # gene associations. + reaction_genes_not_equal_marg = 1.0 - reaction_genes_equal_marg - ( + sum(r1.genes is None or r2.genes is None + for r1, r2 in product(itervalues(model1.reactions), + itervalues(model2.reactions))) / + reaction_pairs) + + reaction_genes_likelihoods = pairwise_likelihood( + pool, chunksize, model1.reactions, model2.reactions, + reaction_genes_likelihood, + reaction_prior, reaction_genes_equal_marg, + reaction_genes_not_equal_marg, gene_map) + + print('%.2f seconds' % (time.time() - t)) + t = time.time() + else: + reaction_genes_likelihoods = pairwise_likelihood( + pool, chunksize, model1.reactions, model2.reactions, + fake_likelihood) + + pool.close() + pool.join() + + if log: + merge_result = pd.merge(reaction_id_likelihoods, + reaction_name_likelihoods, + left_index=True, right_index=True, + suffixes=('_id', '_name')) + merge_result = pd.merge(merge_result, reaction_equation_likelihoods, + left_index=True, right_index=True, + suffixes=('_name', '_equation')) + merge_result = pd.merge(merge_result, reaction_genes_likelihoods, + left_index=True, right_index=True, + suffixes=('_equation', '_genes')) + + merge_result.to_csv(outpath + '/reaction_log.tsv', sep='\t') + + all_likelihoods = [reaction_id_likelihoods, + reaction_name_likelihoods, + reaction_equation_likelihoods, + reaction_genes_likelihoods] + + return (bayes_posterior(reaction_prior, + likelihood_products(all_likelihoods)), + bayes_posterior(reaction_prior, reaction_id_likelihoods), + bayes_posterior(reaction_prior, reaction_name_likelihoods), + bayes_posterior(reaction_prior, reaction_equation_likelihoods), + bayes_posterior(reaction_prior, reaction_genes_likelihoods)) + + +def check_cpd_charge(compound, source): + if compound.charge is not None: + if isinstance(compound.charge, int): + return True + else: + logger.warning( + ""Compound charge should be an integer, however, charge of "" + ""compound '{}' in '{}' model is '{}', which is invalid. "" + ""Please remove or fix it before running modelmapping "" + ""command."".format(compound.id, source, compound.charge)) + return False +","Python" +"Metabolic","zhanglab/psamm","psamm/__init__.py",".py","931","28","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen + +""""""Metabolic networks module."""""" + +from pkg_resources import get_distribution, DistributionNotFound + +__version__ = None + +try: + __version__ = get_distribution('psamm').version +except DistributionNotFound: + pass +","Python" +"Metabolic","zhanglab/psamm","psamm/massconsistency.py",".py","7176","188","# -*- coding: utf-8 -*- +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Mass consistency analysis of metabolic databases + +A stoichiometric matrix, S, is said to be mass-consistent if +S^Tm = 0 has a positive solution (m_i > 0). This corresponds to +assigning a positive mass to each compound in the stoichiometric +matrix and having each reaction preserve mass. Exchange reactions +will have to be excluded from this check, as they are not able to +preserve mass (by definition). In addition some databases may contain +pseudo-compounds (e.g. ""photon"") that also has to be excluded. +"""""" + +from .lpsolver import lp + +from six import iteritems, raise_from + + +class MassConsistencyError(Exception): + """"""Indicates an error while checking for mass consistency"""""" + + +def _non_localized_compounds(database): + """"""Return set of non-localized compounds in database"""""" + return set(c.in_compartment(None) for c in database.compounds) + + +def is_consistent(database, solver, exchange=set(), zeromass=set()): + """"""Try to assign a positive mass to each compound + + Return True if successful. The masses are simply constrained by m_i > 1 and + finding a solution under these conditions proves that the database is mass + consistent. + """""" + + prob = solver.create_problem() + compound_set = _non_localized_compounds(database) + mass_compounds = compound_set.difference(zeromass) + + # Define mass variables + m = prob.namespace(mass_compounds, lower=1) + prob.set_objective(m.sum(mass_compounds)) + + # Define constraints + massbalance_lhs = {reaction: 0 for reaction in database.reactions} + for (compound, reaction), value in iteritems(database.matrix): + if compound not in zeromass: + mass = m(compound.in_compartment(None)) + massbalance_lhs[reaction] += mass * value + for reaction, lhs in iteritems(massbalance_lhs): + if reaction not in exchange: + prob.add_linear_constraints(lhs == 0) + + result = prob.solve_unchecked(lp.ObjectiveSense.Minimize) + return result.success + + +def check_reaction_consistency(database, solver, exchange=set(), + checked=set(), zeromass=set(), weights={}): + """"""Check inconsistent reactions by minimizing mass residuals + + Return a reaction iterable, and compound iterable. The reaction iterable + yields reaction ids and mass residuals. The compound iterable yields + compound ids and mass assignments. + + Each compound is assigned a mass of at least one, and the masses are + balanced using the stoichiometric matrix. In addition, each reaction has a + residual mass that is included in the mass balance equations. The L1-norm + of the residuals is minimized. Reactions in the checked set are assumed to + have been manually checked and therefore have the residual fixed at zero. + """""" + + # Create Flux balance problem + prob = solver.create_problem() + compound_set = _non_localized_compounds(database) + mass_compounds = compound_set.difference(zeromass) + + # Define mass variables + m = prob.namespace(mass_compounds, lower=1) + + # Define residual mass variables and objective constriants + z = prob.namespace(database.reactions, lower=0) + r = prob.namespace(database.reactions) + + objective = z.expr((reaction_id, weights.get(reaction_id, 1)) + for reaction_id in database.reactions) + prob.set_objective(objective) + + rs = r.set(database.reactions) + zs = z.set(database.reactions) + prob.add_linear_constraints(zs >= rs, rs >= -zs) + + massbalance_lhs = {reaction_id: 0 for reaction_id in database.reactions} + for (compound, reaction_id), value in iteritems(database.matrix): + if compound not in zeromass: + mass_var = m(compound.in_compartment(None)) + massbalance_lhs[reaction_id] += mass_var * value + for reaction_id, lhs in iteritems(massbalance_lhs): + if reaction_id not in exchange: + if reaction_id not in checked: + prob.add_linear_constraints(lhs + r(reaction_id) == 0) + else: + prob.add_linear_constraints(lhs == 0) + + # Solve + try: + prob.solve(lp.ObjectiveSense.Minimize) + except lp.SolverError as e: + raise_from( + MassConsistencyError('Failed to solve mass consistency: {}'.format( + e)), e) + + def iterate_reactions(): + for reaction_id in database.reactions: + residual = r.value(reaction_id) + yield reaction_id, residual + + def iterate_compounds(): + for compound in mass_compounds: + yield compound, m.value(compound) + + return iterate_reactions(), iterate_compounds() + + +def check_compound_consistency(database, solver, exchange=set(), + zeromass=set()): + """"""Yield each compound in the database with assigned mass + + Each compound will be assigned a mass and the number of compounds having a + positive mass will be approximately maximized. + + This is an implementation of the solution originally proposed by + [Gevorgyan08]_ but using the new method proposed by [Thiele14]_ to avoid + MILP constraints. This is similar to the way Fastcore avoids MILP + contraints. + """""" + + # Create mass balance problem + prob = solver.create_problem() + compound_set = _non_localized_compounds(database) + mass_compounds = compound_set.difference(zeromass) + + # Define mass variables + m = prob.namespace(mass_compounds, lower=0) + + # Define z variables + z = prob.namespace(mass_compounds, lower=0, upper=1) + prob.set_objective(z.sum(mass_compounds)) + + prob.add_linear_constraints(m.set(mass_compounds) >= z.set(mass_compounds)) + + massbalance_lhs = {reaction_id: 0 for reaction_id in database.reactions} + for (compound, reaction_id), value in iteritems(database.matrix): + if compound not in zeromass: + mass_var = m(compound.in_compartment(None)) + massbalance_lhs[reaction_id] += mass_var * value + for reaction_id, lhs in iteritems(massbalance_lhs): + if reaction_id not in exchange: + prob.add_linear_constraints(lhs == 0) + + # Solve + try: + prob.solve(lp.ObjectiveSense.Maximize) + except lp.SolverError as e: + raise_from( + MassConsistencyError('Failed to solve mass consistency: {}'.format( + e)), e) + + for compound in mass_compounds: + yield compound, m.value(compound) +","Python" +"Metabolic","zhanglab/psamm","psamm/randomsparse.py",".py","10522","308","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2016 Chao Liu + +from __future__ import unicode_literals + +import random +import logging + +from . import fluxanalysis +from .expression import boolean + +from six import iteritems, string_types + +logger = logging.getLogger(__name__) + + +class ReactionDeletionStrategy(object): + """"""Deleting reactions strategy class. + + When initializing instances of this class, + :func:`.get_exchange_reactions` can be useful if exchange reactions + are used as the test set. + """""" + + def __init__(self, model, reaction_set=None): + self._model = model + if reaction_set is None: + self._test_set = set(self._model.reactions) + else: + self._test_set = set(reaction_set) + self._reactions = set(self._test_set) + + @property + def entities(self): + return self._reactions + + def iter_tests(self): + while len(self._test_set) > 0: + reaction = random.choice(tuple(self._test_set)) + self._test_set.remove(reaction) + yield reaction, {reaction} + + def delete(self, entity, deleted_reactions): + pass + + +class GeneDeletionStrategy(object): + """"""Deleting genes strategy class. + + When initializing instances of this class, :func:`get_gene_associations` + can be called to obtain the gene association dict from the model. + """""" + + def __init__(self, model, gene_assoc): + self._model = model + self._genes = set() + self._gene_assoc = dict(gene_assoc) + + for reaction, assoc in iteritems(self._gene_assoc): + self._genes.update(v.symbol for v in assoc.variables) + + self._reactions = set(self._model.reactions) + self._test_set = set(self._genes) + + @property + def entities(self): + return set(self._genes) + + def iter_tests(self): + while len(self._test_set) > 0: + gene = random.choice(tuple(self._test_set)) + self._test_set.remove(gene) + + deleted_reactions = set() + self._new_gene_assoc = {} + for reaction in self._reactions: + if reaction not in self._gene_assoc: + continue + assoc = self._gene_assoc[reaction] + if boolean.Variable(gene) in assoc.variables: + new_assoc = assoc.substitute( + lambda v: v if v.symbol != gene else False) + if new_assoc.has_value() and not new_assoc.value: + deleted_reactions.add(reaction) + else: + self._new_gene_assoc[reaction] = new_assoc + else: + self._new_gene_assoc[reaction] = assoc + + yield gene, deleted_reactions + + def delete(self, entity, deleted_reactions): + self._reactions -= deleted_reactions + self._gene_assoc = self._new_gene_assoc + + +def get_gene_associations(model): + """"""Create gene association for class :class:`.GeneDeletionStrategy`. + + Return a dict mapping reaction IDs to + :class:`psamm.expression.boolean.Expression` objects, + representing relationships between reactions and related genes. This helper + function should be called when creating :class:`.GeneDeletionStrategy` + objects. + + Args: + model: :class:`psamm.datasource.native.NativeModel`. + """""" + + for reaction in model.reactions: + assoc = None + if reaction.genes is None: + continue + elif isinstance(reaction.genes, string_types): + assoc = boolean.Expression(reaction.genes) + else: + variables = [boolean.Variable(g) for g in reaction.genes] + assoc = boolean.Expression(boolean.And(*variables)) + yield reaction.id, assoc + + +def get_exchange_reactions(model): + """"""Yield IDs of all exchange reactions from model. + + This helper function would be useful when creating + :class:`.ReactionDeletionStrategy` objects. + + Args: + model: :class:`psamm.metabolicmodel.MetabolicModel`. + """""" + for reaction_id in model.reactions: + if model.is_exchange(reaction_id): + yield reaction_id + + +def random_sparse(strategy, prob, obj_reaction, flux_threshold): + """"""Find a random minimal network of model reactions. + + Given a reaction to optimize and a threshold, delete entities randomly + until the flux of the reaction to optimize falls under the threshold. + Keep deleting until no more entities can be deleted. It works + with two strategies: deleting reactions or deleting genes (reactions + related to certain genes). + + Args: + strategy: :class:`.ReactionDeletionStrategy` or + :class:`.GeneDeletionStrategy`. + prob: :class:`psamm.fluxanalysis.FluxBalanceProblem`. + obj_reaction: objective reactions to optimize. + flux_threshold: threshold of max reaction flux. + """""" + + essential = set() + deleted = set() + for entity, deleted_reactions in strategy.iter_tests(): + if obj_reaction in deleted_reactions: + logger.info( + 'Marking entity {} as essential because the objective' + ' reaction depends on this entity...'.format(entity)) + essential.add(entity) + continue + + if len(deleted_reactions) == 0: + logger.info( + 'No reactions were removed when entity {}' + ' was deleted'.format(entity)) + deleted.add(entity) + strategy.delete(entity, deleted_reactions) + continue + + logger.info('Deleted reactions: {}'.format( + ', '.join(deleted_reactions))) + + constr = [] + for r in deleted_reactions: + flux_var = prob.get_flux_var(r) + c, = prob.prob.add_linear_constraints(flux_var == 0) + constr.append(c) + + logger.info('Trying FBA without reactions {}...'.format( + ', '.join(deleted_reactions))) + + try: + prob.maximize(obj_reaction) + except fluxanalysis.FluxBalanceError: + logger.info( + 'FBA is infeasible, marking {} as essential'.format( + entity)) + for c in constr: + c.delete() + essential.add(entity) + continue + + logger.debug('Reaction {} has flux {}'.format( + obj_reaction, prob.get_flux(obj_reaction))) + + if prob.get_flux(obj_reaction) < flux_threshold: + for c in constr: + c.delete() + essential.add(entity) + logger.info('Entity {} was essential'.format( + entity)) + else: + deleted.add(entity) + strategy.delete(entity, deleted_reactions) + logger.info('Entity {} was deleted'.format(entity)) + + return essential, deleted + + +def random_sparse_return_all(strategy, prob, obj_reaction, flux_threshold): + """"""Find a random minimal network of model reactions. + + Given a reaction to optimize and a threshold, delete entities randomly + until the flux of the reaction to optimize falls under the threshold. + Keep deleting until no more entities can be deleted. It works + with two strategies: deleting reactions or deleting genes (reactions + related to certain genes). + + Args: + strategy: :class:`.ReactionDeletionStrategy` or + :class:`.GeneDeletionStrategy`. + prob: :class:`psamm.fluxanalysis.FluxBalanceProblem`. + obj_reaction: objective reactions to optimize. + flux_threshold: threshold of max reaction flux. + """""" + + essential = set() + deleted = set() + essential_rxn = set() + deleted_rxn = set() + for entity, deleted_reactions in strategy.iter_tests(): + if obj_reaction in deleted_reactions: + logger.info( + 'Marking entity {} as essential because the objective' + ' reaction depends on this entity...'.format(entity)) + essential.add(entity) + continue + + if len(deleted_reactions) == 0: + logger.info( + 'No reactions were removed when entity {}' + ' was deleted'.format(entity)) + deleted.add(entity) + strategy.delete(entity, deleted_reactions) + continue + + logger.info('Deleted reactions: {}'.format( + ', '.join(deleted_reactions))) + + constr = [] + for r in deleted_reactions: + flux_var = prob.get_flux_var(r) + c, = prob.prob.add_linear_constraints(flux_var == 0) + constr.append(c) + + logger.info('Trying FBA without reactions {}...'.format( + ', '.join(deleted_reactions))) + + try: + prob.maximize(obj_reaction) + except fluxanalysis.FluxBalanceError: + logger.info( + 'FBA is infeasible, marking {} as essential'.format( + entity)) + for c in constr: + c.delete() + essential.add(entity) + for r in deleted_reactions: + essential_rxn.add(r) + continue + + logger.debug('Reaction {} has flux {}'.format( + obj_reaction, prob.get_flux(obj_reaction))) + + if prob.get_flux(obj_reaction) < flux_threshold: + for c in constr: + c.delete() + essential.add(entity) + logger.info('Entity {} was essential'.format( + entity)) + for r in deleted_reactions: + essential_rxn.add(r) + else: + deleted.add(entity) + strategy.delete(entity, deleted_reactions) + logger.info('Entity {} was deleted'.format(entity)) + for r in deleted_reactions: + deleted_rxn.add(r) + + return essential_rxn, deleted_rxn +","Python" +"Metabolic","zhanglab/psamm","psamm/reaction.py",".py","13960","412","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2020 Elysha Sameth + +""""""Definitions related to reaction equations and parsing of such equations."""""" + +from __future__ import unicode_literals + +import re +import functools +import enum +import numbers +from collections import Counter + +import six +from six import text_type, iteritems + + +@six.python_2_unicode_compatible +@functools.total_ordering +class Compound(object): + """"""Represents a compound in a reaction equation + + A compound is a named entity in the reaction equations representing a + chemical compound. A compound can represent a generalized chemical entity + (e.g. polyphosphate) and the arguments can be used to instantiate a + specific chemical entity (e.g. polyphosphate(3)) by passing a number as an + argument or a partially specified entity by passing an expression (e.g. + polyphosphate(n)). + """""" + + def __init__(self, name, compartment=None, arguments=()): + self._name = name + self._compartment = None + if compartment is not None: + self._compartment = compartment + self._arguments = tuple(arguments) + + @property + def name(self): + """"""Name of compound"""""" + return self._name + + @property + def compartment(self): + """"""Compartment of compound"""""" + return self._compartment + + @property + def arguments(self): + """"""Expression argument for generalized compounds"""""" + return self._arguments + + def translate(self, func): + """"""Translate compound name using given function + + >>> Compound('Pb').translate(lambda x: x.lower()) + Compound('pb') + """""" + return self.__class__( + func(self._name), self._compartment, self._arguments) + + def in_compartment(self, compartment): + """"""Return an instance of this compound in the specified compartment + + >>> Compound('H+').in_compartment('e') + Compound('H+', 'e') + """""" + return self.__class__(self._name, compartment, self._arguments) + + def __eq__(self, other): + return (isinstance(other, Compound) and + self._name == other._name and + self._compartment == other._compartment and + self._arguments == other._arguments) + + def __ne__(self, other): + return not self == other + + def __lt__(self, other): + if isinstance(other, Compound): + def tuple_repr(c): + comp = c._compartment if c._compartment is not None else '' + return (c._name, comp, c._arguments) + return tuple_repr(self) < tuple_repr(other) + return NotImplemented + + def __hash__(self): + return (hash('Compound') ^ hash(self._name) ^ + hash(self._compartment) ^ hash(self._arguments)) + + def __str__(self): + """"""String representation of compound + + >>> str(Compound('Phosphate')) + 'Phosphate' + >>> str(Compound('Phosphate', 'e')) + 'Phosphate[e]' + >>> str(Compound('Polyphosphate', None, [Expression('n')])) + 'Polyphosphate(n)' + >>> str(Compound('Polyphosphate', 'p', [Expression('n')])) + 'Polyphosphate(n)[p]' + """""" + s = self._name + if len(self._arguments) > 0: + s += '({})'.format( + ', '.join(text_type(a) for a in self._arguments)) + if self._compartment is not None: + s += '[{}]'.format(self._compartment) + return s + + def __repr__(self): + def str_repr(*args): + return str('Compound({})').format(', '.join(repr(a) for a in args)) + + if len(self._arguments) == 0: + if self._compartment is None: + return str_repr(self._name) + return str_repr(self._name, self._compartment) + return str_repr(self._name, self._compartment, self._arguments) + + +class Direction(enum.Enum): + """"""Directionality of reaction equation."""""" + Forward = False, True + Reverse = True, False + Both = True, True + + Right = False, True + Left = True, False + Bidir = True, True + + @property + def forward(self): + """"""Whether this direction includes forward direction."""""" + return self.value[1] + + @property + def reverse(self): + """"""Whether this direction includes reverse direction."""""" + return self.value[0] + + def flipped(self): + """"""Return the flipped version of this direction."""""" + forward, reverse = self.value + return self.__class__((reverse, forward)) + + @property + def symbol(self): + """"""Return string symbol for direction."""""" + if self == Direction.Forward: + return '=>' + elif self == Direction.Reverse: + return '<=' + else: + return '<=>' + + +@six.python_2_unicode_compatible +class Reaction(object): + """"""Reaction equation representation. + + Each compound is associated with a stoichiometric value and the reaction + has a :class:`.Direction`. The reaction is created in one of the three + following ways. + + It can be created from a direction and two iterables of compound, + value pairs representing the left-hand side and the right-hand side of + the reaction: + + >>> r = Reaction(Direction.Both, [(Compound('A'), 1), (Compound('B', 2))], + [(Compound('C'), 1)]) + >>> str(r) + '|A| + (2) |B| <=> |C|' + + It can also be created from a single dict or iterable of compound, value + pairs where the left-hand side compounds have negative values and the + right-hand side compounds have positive values: + + >>> r = Reaction(Direction.Forward, { + Compound('A'): -1, + Compound('B'): -2, + Compound('C'): 1 + }) + >>> str(r) + '|A| + (2) |B| <=> |C|' + + Lastly, the reaction can be created from an existing reaction object, + creating a copy of that reaction. + + >>> r = Reaction(Direction.Forward, {Compound('A'): -1, Compound('B'): 1}) + >>> r2 = Reaction(r) + >>> str(r2) + '|A| => |B|' + + Reactions can be added to produce combined reactions. + + >>> r = Reaction(Direction.Forward, {Compound('A'): -1, Compound('B'): 1}) + >>> s = Reaction(Direction.Forward, {Compound('B'): -1, Compound('C'): 1}) + >>> str(r + s) + '|A| => |C|' + + Reactions can also be multiplied by a number to produce a new reaction + with scaled stoichiometry. + + >>> r = Reaction(Direction.Forward, {Compound('A'): -1, Compound('B'): 2}) + >>> str(2 * r) + '(2) |A| => (4) |B|' + + Multiplying with a negative value will also flip the reaction, and as a + special case, negating a reaction will simply flip it. + + >>> r = Reaction(Direction.Forward, {Compound('A'): -1, Compound('B'): 2}) + >>> str(r) + '|A| => (2) |B|' + >>> str(-r) + '(2) |B| <= |A|' + """""" + + def __init__(self, *args): + if len(args) == 1: + # Initialize from Reaction object + if not isinstance(args[0], self.__class__): + raise TypeError('Single argument must be of type {}'.format( + self.__class__.__name__)) + + self._direction = args[0].direction + self._left = tuple(args[0].left) + self._right = tuple(args[0].right) + elif len(args) == 2: + # Initialize from direction and dict or single iterable + if not isinstance(args[0], Direction): + raise TypeError('First argument must be a Direction') + self._direction = args[0] + + values = args[1] + if isinstance(values, dict): + values = iteritems(values) + + left, right = [], [] + for compound, value in values: + if not isinstance(value, numbers.Number): + raise TypeError('Values must be numeric') + if value < 0: + left.append((compound, -value)) + elif value > 0: + right.append((compound, value)) + + self._left = tuple(left) + self._right = tuple(right) + elif len(args) == 3: + # Initialize from direction and two iterables + if not isinstance(args[0], Direction): + raise TypeError('First argument must be a Direction') + self._direction = args[0] + + left, right = [], [] + for compound, value in args[1]: + if isinstance(value, numbers.Number) and value < 0: + raise ValueError('Value must not be negative') + elif value != 0: + left.append((compound, value)) + + for compound, value in args[2]: + if isinstance(value, numbers.Number) and value < 0: + raise ValueError('Value must not be negative') + elif value != 0: + right.append((compound, value)) + + self._left = tuple(left) + self._right = tuple(right) + else: + raise TypeError('Too many arguments (one, two or three' + ' arguments required)') + + @property + def direction(self): + """"""Direction of reaction equation"""""" + return self._direction + + @property + def left(self): + """"""Compounds on the left-hand side of the reaction equation."""""" + return self._left + + @property + def right(self): + """"""Compounds on the right-hand side of the reaction equation."""""" + return self._right + + @property + def compounds(self): + """"""Sequence of compounds on both sides of the reaction equation + + The sign of the stoichiometric values reflect whether the compound is + on the left-hand side (negative) or the right-hand side (positive). + """""" + return tuple((c, -v) for c, v in self._left) + self._right + + def normalized(self): + """"""Return normalized reaction + + The normalized reaction will be bidirectional or a forward reaction + (i.e. reverse reactions are flipped). + """""" + + if self._direction == Direction.Reverse: + return self.__class__( + self._direction.flipped(), self._right, self._left) + + return self + + def translated_compounds(self, translate): + """"""Return reaction where compound names have been translated. + + For each compound the translate function is called with the compound + name and the returned value is used as the new compound name. A new + reaction is returned with the substituted compound names. + """""" + compounds = ((compound.translate(translate), value) + for compound, value in self.compounds) + return Reaction(self._direction, compounds) + + def __str__(self): + # Use the same format as ModelSEED + def format_compound(compound, count): + """"""Format compound"""""" + cpdspec = text_type(compound) + + if re.search(r'\s', cpdspec): + cpdspec = '|{}|'.format(cpdspec) + if count != 1: + return '({}) {}'.format(count, cpdspec) + return cpdspec + + def format_compound_list(cmpds): + """"""Format compound list"""""" + return ' + '.join(format_compound(compound, count) + for compound, count in cmpds) + + s = text_type(self._direction.symbol) + if len(self._left) > 0: + s = format_compound_list(self._left) + ' ' + s + if len(self._right) > 0: + s += ' ' + format_compound_list(self._right) + return s + + def __repr__(self): + return str('Reaction({}, {}, {})').format( + repr(self._direction), repr(self._left), repr(self._right)) + + def __eq__(self, other): + """"""Indicate equality of self and other"""""" + return (isinstance(other, self.__class__) and + self._direction == other._direction and + self._left == other._left and + self._right == other._right) + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return (hash('Reaction') ^ hash(self._direction) ^ + hash(self._left) ^ hash(self._right)) + + def __add__(self, other): + if isinstance(other, Reaction): + reverse = self.direction.reverse and other.direction.reverse + forward = self.direction.forward and other.direction.forward + if not reverse and not forward: + raise ValueError('Reactions have incompatible directions') + + direction = Direction((reverse, forward)) + values = Counter(dict(self.compounds)) + values.update(dict(other.compounds)) + return Reaction(direction, values) + + return NotImplemented + + def __sub__(self, other): + return self + -other + + def __neg__(self): + return -1 * self + + def __mul__(self, other): + if isinstance(other, numbers.Number): + direction = ( + self.direction if other > 0 else self.direction.flipped()) + return self.__class__( + direction, ((c, other * v) for c, v in self.compounds)) + + return NotImplemented + + def __rmul__(self, other): + return self * other +","Python" +"Metabolic","zhanglab/psamm","psamm/fastgapfill.py",".py","2300","61","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2016 Chao Liu +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Implementation of fastGapFill. + +Described in [Thiele14]_. +"""""" + +from __future__ import unicode_literals + +import logging + +from .fastcore import fastcore + +logger = logging.getLogger(__name__) + + +def fastgapfill(model_extended, core, solver, weights={}, epsilon=1e-5): + """"""Run FastGapFill gap-filling algorithm by calling + :func:`psamm.fastcore.fastcore`. + + FastGapFill will try to find a minimum subset of reactions that includes + the core reactions and it also has no blocked reactions. + Return the set of reactions in the minimum subset. An extended model that + includes artificial transport and exchange reactions can be generated by + calling :func:`.create_extended_model`. + + Args: + model: :class:`psamm.metabolicmodel.MetabolicModel`. + core: reactions in the original metabolic model. + weights: a weight dictionary for reactions in the model. + solver: linear programming library to use. + epsilon: float number, threshold for Fastcore algorithm. + """""" + + # Run Fastcore and print the induced reaction set + logger.info('Calculating Fastcore induced set on model') + induced = fastcore( + model_extended, core, epsilon=epsilon, weights=weights, solver=solver) + logger.debug('Result: |A| = {}, A = {}'.format(len(induced), induced)) + added_reactions = induced - core + logger.debug('Extended: |E| = {}, E = {}'.format( + len(added_reactions), added_reactions)) + return induced +","Python" +"Metabolic","zhanglab/psamm","psamm/fluxanalysis.py",".py","17534","482","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Implementation of Flux Balance Analysis."""""" + +from __future__ import unicode_literals + +import logging +import random + +from .lpsolver import lp + +from six import iteritems, raise_from + +# Module-level logging +logger = logging.getLogger(__name__) + +_INF = float('inf') + + +def _get_fba_problem(model, tfba, solver): + """"""Convenience function for returning the right FBA problem instance"""""" + p = FluxBalanceProblem(model, solver) + if tfba: + p.add_thermodynamic() + return p + + +class FluxBalanceError(Exception): + """"""Error indicating that a flux balance cannot be solved."""""" + + def __init__(self, *args, **kwargs): + self._result = kwargs.pop('result') + super(FluxBalanceError, self).__init__(*args, **kwargs) + + @property + def result(self): + return self._result + + +class FluxBalanceProblem(object): + """"""Model as a flux optimization problem with steady state assumption. + + Create a representation of the model as an LP optimization problem with + steady state assumption, i.e. the concentrations of compounds are always + zero. + + The problem can be modified and solved as many times as needed. The flux + of a reaction can be obtained after solving using :meth:`.get_flux`. + + Args: + model: :class:`MetabolicModel` to solve. + solver: LP solver instance to use. + """""" + + def __init__(self, model, solver): + self._prob = solver.create_problem() + self._model = model + + self._z = None + self._v = v = self._prob.namespace() + + self._has_minimization_vars = False + + # We keep track of temporary constraints from the last optimization so + # that we can remove them during the next call to solve(). This is + # necessary because removing the constraint immediately after solving + # a model can invalidate the solution in some solvers. + self._temp_constr = [] + self._remove_constr = [] + + # Define flux variables + for reaction_id in self._model.reactions: + lower, upper = self._model.limits[reaction_id] + v.define([reaction_id], lower=lower, upper=upper) + + # Define constraints + massbalance_lhs = {compound: 0 for compound in model.compounds} + for spec, value in iteritems(self._model.matrix): + compound, reaction_id = spec + massbalance_lhs[compound] += v(reaction_id) * value + for compound, lhs in iteritems(massbalance_lhs): + self._prob.add_linear_constraints(lhs == 0) + + @property + def prob(self): + """"""Return the underlying LP problem. + + This can be used to add additional constraints on the problem. Calling + solve on the underlying problem is not guaranteed to work correctly, + instead use the methods on this object that solves the problem or + make a subclass with a method that calls :meth:`_solve`. + """""" + return self._prob + + def add_thermodynamic(self, em=1000): + """"""Apply thermodynamic constraints to the model. + + Adding these constraints restricts the solution space to only + contain solutions that have no internal loops [Schilling00]_. This is + solved as a MILP problem as described in [Muller13]_. The time to solve + a problem with thermodynamic constraints is usually much longer than a + normal FBA problem. + + The ``em`` parameter is the upper bound on the delta mu reaction + variables. This parameter has to be balanced based on the model size + since setting the value too low can result in the correct solutions + being infeasible and setting the value too high can result in + numerical instability which again makes the correct solutions + infeasible. The default value should work in all cases as long as the + model is not unusually large. + """""" + + internal = set(r for r in self._model.reactions + if not self._model.is_exchange(r)) + + # Reaction fluxes + v = self._v + + # Indicator variable + alpha = self._prob.namespace(internal, types=lp.VariableType.Binary) + + # Delta mu is the stoichiometrically weighted sum of the compound mus. + dmu = self._prob.namespace(internal) + + for reaction_id in self._model.reactions: + if not self._model.is_exchange(reaction_id): + flux = v(reaction_id) + alpha_r = alpha(reaction_id) + dmu_r = dmu(reaction_id) + + lower, upper = self._model.limits[reaction_id] + + # Constrain the reaction to a direction determined by alpha + # and contrain the delta mu to a value in [-em; -1] if + # alpha is one, otherwise in [1; em]. + self._prob.add_linear_constraints( + flux >= lower * (1 - alpha_r), + flux <= upper * alpha_r, + dmu_r >= -em * alpha_r + (1 - alpha_r), + dmu_r <= em * (1 - alpha_r) - alpha_r) + + # Define mu variables + mu = self._prob.namespace(self._model.compounds) + + tdbalance_lhs = {reaction_id: 0 + for reaction_id in self._model.reactions} + for spec, value in iteritems(self._model.matrix): + compound, reaction_id = spec + if not self._model.is_exchange(reaction_id): + tdbalance_lhs[reaction_id] += mu(compound) * value + for reaction_id, lhs in iteritems(tdbalance_lhs): + if not self._model.is_exchange(reaction_id): + self._prob.add_linear_constraints(lhs == dmu(reaction_id)) + + def maximize(self, reaction): + """"""Solve the model by maximizing the given reaction. + + If reaction is a dictionary object, each entry is interpreted as a + weight on the objective for that reaction (non-existent reaction will + have zero weight). + """""" + + self._prob.set_objective(self.flux_expr(reaction)) + self._solve() + + def flux_bound(self, reaction, direction): + """"""Return the flux bound of the reaction. + + Direction must be a positive number to obtain the upper bound or a + negative number to obtain the lower bound. A value of inf or -inf is + returned if the problem is unbounded. + """""" + try: + self.maximize({reaction: direction}) + except FluxBalanceError as e: + if not e.result.unbounded: + raise + return direction * _INF + else: + return self.get_flux(reaction) + + def _add_minimization_vars(self): + """"""Add variables and constraints for L1 norm minimization."""""" + + self._z = self._prob.namespace(self._model.reactions, lower=0) + + # Define constraints + v = self._v.set(self._model.reactions) + z = self._z.set(self._model.reactions) + + self._prob.add_linear_constraints(z >= v, v >= -z) + + def minimize_l1(self, weights={}): + """"""Solve the model by minimizing the L1 norm of the fluxes. + + If the weights dictionary is given, the weighted L1 norm if minimized + instead. The dictionary contains the weights of each reaction + (default 1). + """""" + + if self._z is None: + self._add_minimization_vars() + + objective = self._z.expr( + (reaction_id, -weights.get(reaction_id, 1)) + for reaction_id in self._model.reactions) + self._prob.set_objective(objective) + + self._solve() + + def max_min_l1(self, reaction, weights={}): + """"""Maximize flux of reaction then minimize the L1 norm. + + During minimization the given reaction will be fixed at the maximum + obtained from the first solution. If reaction is a dictionary object, + each entry is interpreted as a weight on the objective for that + reaction (non-existent reaction will have zero weight). + """""" + + self.maximize(reaction) + + if isinstance(reaction, dict): + reactions = list(reaction) + else: + reactions = [reaction] + + # Save flux values before modifying the LP problem + fluxes = {r: self.get_flux(r) for r in reactions} + + # Add constraints on the maximized reactions + for r in reactions: + flux_var = self.get_flux_var(r) + c, = self._prob.add_linear_constraints(flux_var == fluxes[r]) + self._temp_constr.append(c) + + self.minimize_l1(weights) + + def check_constraints(self): + """"""Optimize without objective to check that solution is possible. + + Raises :class:`FluxBalanceError` if no flux solution is possible. + """""" + self._prob.set_objective(0) + self._solve() + + def _solve(self): + """"""Solve the problem with the current objective."""""" + + # Remove temporary constraints + while len(self._remove_constr) > 0: + self._remove_constr.pop().delete() + + try: + self._prob.solve(lp.ObjectiveSense.Maximize) + except lp.SolverError as e: + raise_from(FluxBalanceError('Failed to solve: {}'.format( + e), result=self._prob.result), e) + finally: + # Set temporary constraints to be removed on next solve call + self._remove_constr = self._temp_constr + self._temp_constr = [] + + def get_flux_var(self, reaction): + """"""Get LP variable representing the reaction flux."""""" + return self._v(reaction) + + def flux_expr(self, reaction): + """"""Get LP expression representing the reaction flux."""""" + if isinstance(reaction, dict): + return self._v.expr(iteritems(reaction)) + return self._v(reaction) + + def get_flux(self, reaction): + """"""Get resulting flux value for reaction."""""" + return self._prob.result.get_value(self._v(reaction)) + + +def flux_balance(model, reaction, tfba, solver): + """"""Run flux balance analysis on the given model. + + Yields the reaction id and flux value for each reaction in the model. + + This is a convenience function for sertting up and running the + FluxBalanceProblem. If the FBA is solved for more than one parameter + it is recommended to setup and reuse the FluxBalanceProblem manually + for a speed up. + + This is an implementation of flux balance analysis (FBA) as described in + [Orth10]_ and [Fell86]_. + + Args: + model: MetabolicModel to solve. + reaction: Reaction to maximize. If a dict is given, this instead + represents the objective function weights on each reaction. + tfba: If True enable thermodynamic constraints. + solver: LP solver instance to use. + + Returns: + Iterator over reaction ID and reaction flux pairs. + """""" + + fba = _get_fba_problem(model, tfba, solver) + fba.maximize(reaction) + for reaction in model.reactions: + yield reaction, fba.get_flux(reaction) + + +def flux_variability(model, reactions, fixed, tfba, solver): + """"""Find the variability of each reaction while fixing certain fluxes. + + Yields the reaction id, and a tuple of minimum and maximum value for each + of the given reactions. The fixed reactions are given in a dictionary as + a reaction id to value mapping. + + This is an implementation of flux variability analysis (FVA) as described + in [Mahadevan03]_. + + Args: + model: MetabolicModel to solve. + reactions: Reactions on which to report variablity. + fixed: dict of additional lower bounds on reaction fluxes. + tfba: If True enable thermodynamic constraints. + solver: LP solver instance to use. + + Returns: + Iterator over pairs of reaction ID and bounds. Bounds are returned as + pairs of lower and upper values. + """""" + + fba = _get_fba_problem(model, tfba, solver) + # fba.prob.integrality_tolerance.value = 0.0 + if solver._properties['name'] == 'gurobi': + fba.prob.integrality_tolerance.value = 1e-9 + logger.warning( + 'Gurobi supports minimum integrality tolerance of 1e-9. This may ' + 'affect the results from this simulation') + elif solver._properties['name'] == 'glpk': + fba.prob.integrality_tolerance.value = 1e-21 + else: + fba.prob.integrality_tolerance.value = 0 + print(fba.prob.integrality_tolerance.value) + for reaction_id, value in iteritems(fixed): + flux = fba.get_flux_var(reaction_id) + fba.prob.add_linear_constraints(flux >= value) + + def min_max_solve(reaction_id): + for direction in (-1, 1): + yield fba.flux_bound(reaction_id, direction) + + # Solve for each reaction + for reaction_id in reactions: + yield reaction_id, tuple(min_max_solve(reaction_id)) + + +def flux_minimization(model, fixed, solver, weights={}): + """"""Minimize flux of all reactions while keeping certain fluxes fixed. + + The fixed reactions are given in a dictionary as reaction id + to value mapping. The weighted L1-norm of the fluxes is minimized. + + Args: + model: MetabolicModel to solve. + fixed: dict of additional lower bounds on reaction fluxes. + solver: LP solver instance to use. + weights: dict of weights on the L1-norm terms. + + Returns: + An iterator of reaction ID and reaction flux pairs. + """""" + + fba = FluxBalanceProblem(model, solver) + + for reaction_id, value in iteritems(fixed): + flux = fba.get_flux_var(reaction_id) + fba.prob.add_linear_constraints(flux >= value) + + fba.minimize_l1() + + return ((reaction_id, fba.get_flux(reaction_id)) + for reaction_id in model.reactions) + + +def flux_randomization(model, threshold, tfba, solver): + """"""Find a random flux solution on the boundary of the solution space. + + The reactions in the threshold dictionary are constrained with the + associated lower bound. + + Args: + model: MetabolicModel to solve. + threshold: dict of additional lower bounds on reaction fluxes. + tfba: If True enable thermodynamic constraints. + solver: LP solver instance to use. + + Returns: + An iterator of reaction ID and reaction flux pairs. + """""" + + optimize = {} + for reaction_id in model.reactions: + if model.is_reversible(reaction_id): + optimize[reaction_id] = 2 * random.random() - 1.0 + else: + optimize[reaction_id] = random.random() + + fba = _get_fba_problem(model, tfba, solver) + for reaction_id, value in iteritems(threshold): + fba.prob.add_linear_constraints(fba.get_flux_var(reaction_id) >= value) + + fba.maximize(optimize) + for reaction_id in model.reactions: + yield reaction_id, fba.get_flux(reaction_id) + + +def consistency_check(model, subset, epsilon, tfba, solver): + """"""Check that reaction subset of model is consistent using FBA. + + Yields all reactions that are *not* flux consistent. A reaction is + consistent if there is at least one flux solution to the model that both + respects the model constraints and also allows the reaction in question to + have non-zero flux. + + This can be determined by running FBA on each reaction in turn + and checking whether the flux in the solution is non-zero. Since FBA + only tries to maximize the flux (and the flux can be negative for + reversible reactions), we have to try to both maximize and minimize + the flux. An optimization to this method is implemented such that if + checking one reaction results in flux in another unchecked reaction, + that reaction will immediately be marked flux consistent. + + Args: + model: MetabolicModel to check for consistency. + subset: Subset of model reactions to check. + epsilon: The threshold at which the flux is considered non-zero. + tfba: If True enable thermodynamic constraints. + solver: LP solver instance to use. + + Returns: + An iterator of flux inconsistent reactions in the subset. + """""" + + fba = _get_fba_problem(model, tfba, solver) + + subset = set(subset) + while len(subset) > 0: + reaction = next(iter(subset)) + + logger.info('{} left, checking {}...'.format(len(subset), reaction)) + + fba.maximize(reaction) + subset = set(reaction_id for reaction_id in subset + if abs(fba.get_flux(reaction_id)) <= epsilon) + if reaction not in subset: + continue + elif model.is_reversible(reaction): + fba.maximize({reaction: -1}) + subset = set(reaction_id for reaction_id in subset + if abs(fba.get_flux(reaction_id)) <= epsilon) + if reaction not in subset: + continue + + logger.info('{} not consistent!'.format(reaction)) + + yield reaction + subset.remove(reaction) +","Python" +"Metabolic","zhanglab/psamm","psamm/gapfilling.py",".py","8696","240","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2016 Chao Liu +# Copyright 2020 Christopher Powers +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Functionality related to gap-filling in general. + +This module contains some general functions for preparing models for +gap-filling. Specific gap-filling methods are implemented in the ``gapfill`` +and ``fastgapfill`` modules. +"""""" + +from __future__ import unicode_literals + +import logging + +from six import iteritems + +from .metabolicmodel import create_exchange_id, create_transport_id +from .reaction import Reaction, Direction + +logger = logging.getLogger(__name__) + + +def add_all_database_reactions(model, compartments): + """"""Add all reactions from database that occur in given compartments. + + Args: + model: :class:`psamm.metabolicmodel.MetabolicModel`. + """""" + + added = set() + for rxnid in model.database.reactions: + reaction = model.database.get_reaction(rxnid) + if all(compound.compartment in compartments + for compound, _ in reaction.compounds): + if not model.has_reaction(rxnid): + added.add(rxnid) + model.add_reaction(rxnid) + + return added + + +def add_all_exchange_reactions(model, compartment, allow_duplicates=False): + """"""Add all exchange reactions to database and to model. + + Args: + model: :class:`psamm.metabolicmodel.MetabolicModel`. + """""" + + all_reactions = {} + if not allow_duplicates: + # TODO: Avoid adding reactions that already exist in the database. + # This should be integrated in the database. + for rxnid in model.database.reactions: + rx = model.database.get_reaction(rxnid) + all_reactions[rx] = rxnid + + added = set() + added_compounds = set() + initial_compounds = set(model.compounds) + reactions = set(model.database.reactions) + for model_compound in initial_compounds: + compound = model_compound.in_compartment(compartment) + if compound in added_compounds: + continue + + rxnid_ex = create_exchange_id(reactions, compound) + + reaction_ex = Reaction(Direction.Both, {compound: -1}) + if reaction_ex not in all_reactions: + model.database.set_reaction(rxnid_ex, reaction_ex) + reactions.add(rxnid_ex) + else: + rxnid_ex = all_reactions[reaction_ex] + + if not model.has_reaction(rxnid_ex): + added.add(rxnid_ex) + model.add_reaction(rxnid_ex) + added_compounds.add(compound) + + return added + + +def add_all_transport_reactions(model, boundaries, allow_duplicates=False): + """"""Add all transport reactions to database and to model. + + Add transport reactions for all boundaries. Boundaries are defined + by pairs (2-tuples) of compartment IDs. Transport reactions are + added for all compounds in the model, not just for compounds in the + two boundary compartments. + + Args: + model: :class:`psamm.metabolicmodel.MetabolicModel`. + boundaries: Set of compartment boundary pairs. + + Returns: + Set of IDs of reactions that were added. + """""" + + all_reactions = {} + if not allow_duplicates: + # TODO: Avoid adding reactions that already exist in the database. + # This should be integrated in the database. + for rxnid in model.database.reactions: + rx = model.database.get_reaction(rxnid) + all_reactions[rx] = rxnid + + boundary_pairs = set() + for source, dest in boundaries: + if source != dest: + boundary_pairs.add(tuple(sorted((source, dest)))) + + added = set() + added_pairs = set() + initial_compounds = set(model.compounds) + reactions = set(model.database.reactions) + for compound in initial_compounds: + for c1, c2 in boundary_pairs: + compound1 = compound.in_compartment(c1) + compound2 = compound.in_compartment(c2) + pair = compound1, compound2 + if pair in added_pairs: + continue + + rxnid_tp = create_transport_id(reactions, compound1, compound2) + + reaction_tp = Reaction(Direction.Both, { + compound1: -1, + compound2: 1 + }) + if reaction_tp not in all_reactions: + model.database.set_reaction(rxnid_tp, reaction_tp) + reactions.add(rxnid_tp) + else: + rxnid_tp = all_reactions[reaction_tp] + + if not model.has_reaction(rxnid_tp): + added.add(rxnid_tp) + model.add_reaction(rxnid_tp) + added_pairs.add(pair) + + return added + + +def create_extended_model(model, db_penalty=None, ex_penalty=None, + tp_penalty=None, penalties=None): + """"""Create an extended model for gap-filling. + + Create a :class:`psamm.metabolicmodel.MetabolicModel` with + all reactions added (the reaction database in the model is taken + to be the universal database) and also with artificial exchange + and transport reactions added. Return the extended + :class:`psamm.metabolicmodel.MetabolicModel` + and a weight dictionary for added reactions in that model. + + Args: + model: :class:`psamm.datasource.native.NativeModel`. + db_penalty: penalty score for database reactions, default is `None`. + ex_penalty: penalty score for exchange reactions, default is `None`. + tb_penalty: penalty score for transport reactions, default is `None`. + penalties: a dictionary of penalty scores for database reactions. + """""" + + # Create metabolic model + model_extended = model.create_metabolic_model() + extra_compartment = model.extracellular_compartment + + compartment_ids = set(c.id for c in model.compartments) + + # Add database reactions to extended model + if len(compartment_ids) > 0: + logger.info( + 'Using all database reactions in compartments: {}...'.format( + ', '.join('{}'.format(c) for c in compartment_ids))) + db_added = add_all_database_reactions(model_extended, compartment_ids) + else: + logger.warning( + 'No compartments specified in the model; database reactions will' + ' not be used! Add compartment specification to model to include' + ' database reactions for those compartments.') + db_added = set() + + # Add exchange reactions to extended model + logger.info( + 'Using artificial exchange reactions for compartment: {}...'.format( + extra_compartment)) + ex_added = add_all_exchange_reactions( + model_extended, extra_compartment, allow_duplicates=False) + + # Add transport reactions to extended model + boundaries = model.compartment_boundaries + if len(boundaries) > 0: + logger.info( + 'Using artificial transport reactions for the compartment' + ' boundaries: {}...'.format( + '; '.join('{}<->{}'.format(c1, c2) for c1, c2 in boundaries))) + tp_added = add_all_transport_reactions( + model_extended, boundaries, allow_duplicates=True) + else: + logger.warning( + 'No compartment boundaries specified in the model;' + ' artificial transport reactions will not be used!') + tp_added = set() + + # Add penalty weights on reactions + weights = {} + if db_penalty is not None: + weights.update((rxnid, db_penalty) for rxnid in db_added) + else: + weights.update((rxnid, 1) for rxnid in db_added) + if tp_penalty is not None: + weights.update((rxnid, tp_penalty) for rxnid in tp_added) + else: + weights.update((rxnid, 1) for rxnid in tp_added) + if ex_penalty is not None: + weights.update((rxnid, ex_penalty) for rxnid in ex_added) + else: + weights.update((rxnid, 1) for rxnid in ex_added) + + if penalties is not None: + for rxnid, penalty in iteritems(penalties): + weights[rxnid] = penalty + return model_extended, weights +","Python" +"Metabolic","zhanglab/psamm","psamm/manual_curation.py",".py","10151","276","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2018-2020 Jing Wang +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2021 Elysha Sameth + +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +import errno +import pandas as pd +import re +from future import standard_library +standard_library.install_aliases() + + +class Curator(object): + """"""Parse and save mapping files during manual curation. + + Use :meth:`.add_mapping` to add new curated pairs. Save current progress + into files by :meth:`.save`. + + Besides the curated mapping files, the :class:`Curator` will also store + false mappings into `.false` files, and compounds and reactions + to be ignored can be stored + in `.ignore` files. For example, if the `curated_compound_map_file` is set + to `curated_compound_mapping.tsv`, then the false mappings will be stored + in `curated_compound_mapping.tsv.false`, and the pairs to be ignored + should be stored in `curated_compound_mapping.tsv.ignore`. + + If the curated files already exist, the :class:`Curator` will consider them + as the previous progress, then append new curation results. + + Args: + compound_map_file: .tsv file of compound mapping result + reaction_map_file: .tsv file of reaction mapping result + curated_compound_map_file: .tsv file of curated compound mapping result + curated_reaction_map_file: .tsv file of curated reaction mapping result + """""" + + def __init__(self, + compound_map_file, reaction_map_file, + curated_compound_map_file, curated_reaction_map_file): + self.compound_map_file = compound_map_file + self.reaction_map_file = reaction_map_file + self.curated_compound_map_file = curated_compound_map_file + self.curated_reaction_map_file = curated_reaction_map_file + self.false_compound_map_file = curated_compound_map_file + '.false' + self.false_reaction_map_file = curated_reaction_map_file + '.false' + self.ignore_compound_file = curated_compound_map_file + '.ignore' + self.ignore_reaction_file = curated_reaction_map_file + '.ignore' + + self.compound_map = read_mapping(self.compound_map_file, [0, 1]) + self.compound_map.sort_values(by='p', inplace=True, ascending=False) + self.reaction_map = read_mapping(self.reaction_map_file, [0, 1]) + self.reaction_map.sort_values(by='p', inplace=True, ascending=False) + self.curated_compound_map = read_mapping( + self.curated_compound_map_file, [0, 1]) + self.curated_reaction_map = read_mapping( + self.curated_reaction_map_file, [0, 1]) + self.false_compound_map = read_mapping( + self.false_compound_map_file, [0, 1]) + self.false_reaction_map = read_mapping( + self.false_reaction_map_file, [0, 1]) + self.ignore_compound = read_ignore(self.ignore_compound_file) + self.ignore_reaction = read_ignore(self.ignore_reaction_file) + + self.num_curated_compounds = len(self.curated_compound_map.index) + self.num_curated_compounds_left = \ + self.compound_map.index.get_level_values(0).nunique() - \ + self.num_curated_compounds + self.num_curated_reactions = len(self.curated_reaction_map.index) + self.num_curated_reactions_left = \ + self.reaction_map.index.get_level_values(0).nunique() - \ + self.num_curated_reactions + + def reaction_checked(self, id): + """"""Return True if reaction pair has been checked. + + Args: + id: one reaction id or a tuple of id pair + """""" + return (id in self.curated_reaction_map.index or + id in self.false_reaction_map.index) + + def reaction_ignored(self, id): + """"""Return True if reaction id is in ignore list."""""" + return id in self.ignore_reaction + + def compound_checked(self, id): + """"""Return True if compound pair has been checked. + + Args: + id: one compound id or a tuple of id pair + """""" + return (id in self.curated_compound_map.index or + id in self.false_compound_map.index) + + def compound_ignored(self, id): + """"""Return True if compound id is in ignore list."""""" + return id in self.ignore_compound + + def add_mapping(self, id, type, correct): + """"""Add new mapping result to curated list. + + Args: + id: tuple of id pair + type: 'c' for compound mapping, 'r' for reaction mapping + correct: True if the mapping pair is correct + """""" + if type == 'c': + if correct: + self.curated_compound_map = add_mapping( + self.curated_compound_map, + self.compound_map.loc[id] + ) + else: + self.false_compound_map = add_mapping( + self.false_compound_map, + self.compound_map.loc[id] + ) + if type == 'r': + if correct: + self.curated_reaction_map = add_mapping( + self.curated_reaction_map, + self.reaction_map.loc[id] + ) + else: + self.false_reaction_map = add_mapping( + self.false_reaction_map, + self.reaction_map.loc[id] + ) + + def add_ignore(self, id, type): + """"""Add id to ignore list. + + Args: + id: id to be ignored + type: 'c' for compound mapping, 'r' for reaction mapping + """""" + if type == 'c': + self.ignore_compound.append(id) + if type == 'r': + self.ignore_reaction.append(id) + + def save(self): + """"""Save current curator to files."""""" + if len(self.curated_compound_map) > 0: + self.curated_compound_map.to_csv( + self.curated_compound_map_file, sep='\t' + ) + if len(self.curated_reaction_map) > 0: + self.curated_reaction_map.to_csv( + self.curated_reaction_map_file, sep='\t' + ) + if len(self.false_compound_map) > 0: + self.false_compound_map.to_csv( + self.false_compound_map_file, sep='\t' + ) + if len(self.false_reaction_map) > 0: + self.false_reaction_map.to_csv( + self.false_reaction_map_file, sep='\t' + ) + if len(self.ignore_compound) > 0: + write_ignore(self.ignore_compound, self.ignore_compound_file) + if len(self.ignore_reaction) > 0: + write_ignore(self.ignore_reaction, self.ignore_reaction_file) + print('Progress saved\n') + + +def read_mapping(file, index_col): + try: + df = pd.read_csv(file, sep='\t', index_col=index_col) + except IOError as e: + if e.errno != errno.ENOENT: + raise + df = pd.DataFrame() + return df + + +def add_mapping(map, row): + return map.append(pd.DataFrame(row).T) + + +def read_ignore(file): + ignore = list() + try: + with open(file) as f: + for r in f: + ignore.append(r.strip()) + except IOError as e: + if e.errno != errno.ENOENT: + raise + return ignore + + +def write_ignore(ignore, file): + with open(file, 'w') as o: + for i in ignore: + o.write('%s\n' % str(i)) + + +def filter_search_term(s): + return re.sub(r'[^a-z0-9]+', '', s.lower()) + + +def search_compound(model, id): + """"""Search a set of compounds, then print detailed properties. + + Args: + id: a list of compound ids + """""" + selected_compounds = set() + + for compound in model.compounds: + if len(id) > 0: + if any(c == compound.id for c in id): + selected_compounds.add(compound) + continue + + # Show results + for compound in selected_compounds: + props = set(compound.properties) - {'id'} + if compound.filemark is not None: + print('Defined in {}'.format(compound.filemark)) + print('id: {}'.format(compound.id)) + for prop in sorted(props): + print('{}: {}'.format(prop, compound.properties[prop])) + print('\n') + + +def search_reaction(model, ids): + """"""Search a set of reactions, print detailed properties, then return a + generator. Each item in the generator is a list of compounds in the + corresponding reaction. + + Args: + ids: a list of reaction ids + """""" + selected_reactions = set() + for r in ids: + if r in model.reactions: + selected_reactions.add(model.reactions[r]) + + # Show results + for reaction in selected_reactions: + props = set(reaction.properties) - {'id', 'equation'} + if reaction.filemark is not None: + print('Defined in {}'.format(reaction.filemark)) + print('id: {}'.format(reaction.id)) + print('equation: {}'.format( + reaction.equation)) + translated_equation = reaction.equation.translated_compounds( + lambda c: model.compounds[c].name) + if reaction.equation != translated_equation: + print('equation (compound names): {}'.format( + translated_equation)) + for prop in sorted(props): + print('{}: {}'.format(prop, reaction.properties[prop])) + print('\n') + yield [c for c, v in reaction.equation.compounds] +","Python" +"Metabolic","zhanglab/psamm","psamm/fluxcoupling.py",".py","4700","148","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Flux coupling analysis + +Described in [Burgard04]_. +"""""" + +import enum +import logging + +from six import iteritems + +from psamm.lpsolver import lp + + +logger = logging.getLogger(__name__) + + +@enum.unique +class CouplingClass(enum.Enum): + """"""Enumeration of coupling types."""""" + + Inconsistent = 0 + """"""Reaction is flux inconsistent (v1 is always zero)."""""" + + Uncoupled = 1 + """"""Uncoupled reactions."""""" + + DirectionalForward = 2 # v1 -> v2 + """"""Directionally coupled from reaction 1 to 2."""""" + + DirectionalReverse = 3 # v2 -> v1 + """"""Directionally coupled from reaction 2 to 1."""""" + + Partial = 4 # v1 <-> v2 + """"""Partially coupled reactions."""""" + + Full = 5 # v1 <=> v2 + """"""Fully coupled reactions."""""" + + +class FluxCouplingProblem(object): + """"""A specific flux coupling analysis applied to a metabolic model. + + Args: + model: MetabolicModel to apply the flux coupling problem to + bounded: Dictionary of reactions with minimum flux values + solver: LP solver instance to use. + """""" + + def __init__(self, model, bounded, solver): + self._prob = solver.create_problem() + + # Define t variable + self._prob.define('t') + t = self._prob.var('t') + + self._vbow = self._prob.namespace(model.reactions) + + # Define flux bounds + for reaction_id in model.reactions: + lower, upper = model.limits[reaction_id] + if reaction_id in bounded: + lower = bounded[reaction_id] + flux_bow = self._vbow(reaction_id) + self._prob.add_linear_constraints( + flux_bow >= t * lower, flux_bow <= t * upper) + + # Define mass balance constraints + massbalance_lhs = {compound: 0 for compound in model.compounds} + for (compound, reaction_id), value in iteritems(model.matrix): + flux_bow = self._vbow(reaction_id) + massbalance_lhs[compound] += flux_bow * value + for compound, lhs in iteritems(massbalance_lhs): + self._prob.add_linear_constraints(lhs == 0) + + self._reaction_constr = None + + def solve(self, reaction_1, reaction_2): + """"""Return the flux coupling between two reactions + + The flux coupling is returned as a tuple indicating the minimum and + maximum value of the v1/v2 reaction flux ratio. A value of None as + either the minimum or maximum indicates that the interval is unbounded + in that direction. + """""" + # Update objective for reaction_1 + self._prob.set_objective(self._vbow(reaction_1)) + + # Update constraint for reaction_2 + if self._reaction_constr is not None: + self._reaction_constr.delete() + + self._reaction_constr, = self._prob.add_linear_constraints( + self._vbow(reaction_2) == 1) + + results = [] + for sense in (lp.ObjectiveSense.Minimize, lp.ObjectiveSense.Maximize): + try: + result = self._prob.solve(sense) + except lp.SolverError: + results.append(None) + else: + results.append(result.get_value(self._vbow(reaction_1))) + + return tuple(results) + + +def classify_coupling(coupling): + """"""Return a constant indicating the type of coupling. + + Depending on the type of coupling, one of the constants from + :class:`.CouplingClass` is returned. + + Args: + coupling: Tuple of minimum and maximum flux ratio + """""" + lower, upper = coupling + + if lower is None and upper is None: + return CouplingClass.Uncoupled + elif lower is None or upper is None: + return CouplingClass.DirectionalReverse + elif lower == 0.0 and upper == 0.0: + return CouplingClass.Inconsistent + elif lower <= 0.0 and upper >= 0.0: + return CouplingClass.DirectionalForward + elif abs(lower - upper) < 1e-6: + return CouplingClass.Full + else: + return CouplingClass.Partial +","Python" +"Metabolic","zhanglab/psamm","psamm/util.py",".py","7861","269","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Various utilities."""""" + +from __future__ import unicode_literals + +import os +import errno +import re +import math +import subprocess +import collections + +import six +from six import iteritems, text_type + + +def mkdir_p(path): + """"""Make directory path if it does not already exist."""""" + try: + os.makedirs(path) + except OSError as e: + if e.errno != errno.EEXIST or not os.path.isdir(path): + raise + + +class LoggerFile(object): + """"""File-like object that forwards to a logger. + + The Cplex API takes a file-like object for writing log output. + This class allows us to forward the Cplex messages to the + Python logging system. + """""" + + def __init__(self, logger, level): + self._logger = logger + self._level = level + + def write(self, s): + """"""Write message to logger."""""" + for line in re.split(r'\n+', s): + if line != '': + self._logger.log(self._level, line) + + def flush(self): + """"""Flush stream. + + This is a noop."""""" + + +@six.python_2_unicode_compatible +class MaybeRelative(object): + """"""Helper type for parsing possibly relative parameters. + + >>> arg = MaybeRelative('40%') + >>> arg.reference = 200.0 + >>> float(arg) + 80.0 + + >>> arg = MaybeRelative('24.5') + >>> arg.reference = 150.0 + >>> float(arg) + 24.5 + """""" + + def __init__(self, s): + try: + self._value = float(s) + self._relative = False + except ValueError: + self._value = self._parse_percentage(s) + self._relative = self._value != 0.0 + + self._reference = None + + @classmethod + def _parse_percentage(cls, s): + """"""Parse string as a percentage (e.g. '42.0%') and return as float."""""" + m = re.match('^(.+)%$', s) + if not m: + raise ValueError('Unable to parse as percentage: {}'.format( + repr(s))) + + return float(m.group(1)) / 100.0 + + @property + def relative(self): + """"""Whether the parsed number was relative."""""" + return self._relative + + @property + def reference(self): + """"""The reference used for converting to absolute value."""""" + return self._reference + + @reference.setter + def reference(self, value): + self._reference = value + + def __float__(self): + if self._relative: + if self._reference is None: + raise ValueError('Reference not set!') + return self._reference * self._value + else: + return self._value + + def __str__(self): + if self._relative: + f = None if self._reference is None else float(self) + return '{:.1%} of {} = {}'.format( + self._value, self._reference, f) + else: + return text_type(self._value) + + def __repr__(self): + return str('<{}, {}>').format(self.__class__.__name__, str(self)) + + +class FrozenOrderedSet(collections.abc.Set, collections.abc.Hashable): + """"""An immutable set that retains insertion order."""""" + + def __init__(self, seq=[]): + self.__map = collections.OrderedDict() + for e in seq: + self.__map[e] = None + + def __contains__(self, element): + return element in self.__map + + def __iter__(self): + return iter(self.__map) + + def __len__(self): + return len(self.__map) + + def __hash__(self): + h = 0 + for e in self: + h ^= 31 * hash(e) + return h + + def __repr__(self): + return str('{}({})').format(self.__class__.__name__, list(self)) + + +class DictView(collections.abc.Mapping): + """"""An immutable wrapper around another dict-like object."""""" + + def __init__(self, d): + self.__d = d + + def __getitem__(self, key): + return self.__d[key] + + def __iter__(self): + return iter(self.__d) + + def __len__(self): + return len(self.__d) + + +def create_unique_id(prefix, existing_ids): + """"""Return a unique string ID from the prefix. + + First check if the prefix is itself a unique ID in the set-like parameter + existing_ids. If not, try integers in ascending order appended to the + prefix until a unique ID is found. + """""" + if prefix in existing_ids: + suffix = 1 + while True: + new_id = '{}_{}'.format(prefix, suffix) + if new_id not in existing_ids: + return new_id + suffix += 1 + + return prefix + + +def git_try_describe(repo_path): + """"""Try to describe the current commit of a Git repository. + + Return a string containing a string with the commit ID and/or a base tag, + if successful. Otherwise, return None. + """""" + try: + p = subprocess.Popen(['git', 'describe', '--always', '--dirty'], + cwd=repo_path, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + output, _ = p.communicate() + except: + return None + else: + if p.returncode == 0: + return output.strip() + + return None + + +def convex_cardinality_relaxed(f, epsilon=1e-5): + """"""Transform L1-norm optimization function into cardinality optimization. + + The given function must optimize a convex problem with + a weighted L1-norm as the objective. The transformed function + will apply the iterated weighted L1 heuristic to approximately + optimize the cardinality of the solution. This method is + described by S. Boyd, ""L1-norm norm methods for convex cardinality + problems."" Lecture Notes for EE364b, Stanford University, 2007. + Available online at www.stanford.edu/class/ee364b/. + + The given function must take an optional keyword parameter weights + (dictionary), and the weights must be set to one if not specified. + The function must return the non-weighted solution as an iterator + over (identifier, value)-tuples, either directly or as the first + element of a tuple. + """""" + + def convex_cardinality_wrapper(*args, **kwargs): + def dict_result(r): + if isinstance(r, tuple): + return dict(r[0]) + return dict(r) + + # Initial run with default weights + full_result = f(*args, **kwargs) + result = dict_result(full_result) + + def update_weight(value): + return 1/(epsilon + abs(value)) + + # Iterate until the difference from one iteration to + # the next is less than epsilon. + while True: + weights = {identifier: update_weight(value) + for identifier, value in iteritems(result)} + kwargs['weights'] = weights + + last_result = result + full_result = f(*args, **kwargs) + result = dict_result(full_result) + + delta = math.sqrt(sum(pow(value - last_result[identifier], 2) + for identifier, value in iteritems(result))) + if delta < epsilon: + break + + if isinstance(full_result, tuple): + return (iteritems(result),) + full_result[1:] + return iteritems(result) + + return convex_cardinality_wrapper +","Python" +"Metabolic","zhanglab/psamm","psamm/generate_biomass.py",".py","19641","473","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2021-2022 Jason Vailionis + +from psamm.datasource.reaction import Reaction, Compound, Direction +from psamm.datasource import native +from collections import Counter +from six import add_metaclass +from pkg_resources import resource_filename +import logging +import sys +import os +import abc +import yaml +import pandas as pd +import numpy as np +if sys.version_info.minor > 5: + try: + from Bio import SeqIO + from Bio import Seq + except ImportError: + quit(""No biopython package found. "" + ""Please run "") + +logger = logging.getLogger(__name__) + + +@add_metaclass(abc.ABCMeta) +class Command(object): + """"""Represents a command in the interface, operating on a model. + + The constructor will be given the NativeModel and the command line + namespace. The subclass must implement :meth:`run` to handle command + execution. The doc string will be used as documentation for the command + in the command line interface. + + In addition, :meth:`init_parser` can be implemented as a classmethod which + will allow the command to initialize an instance of + :class:`argparse.ArgumentParser` as desired. The resulting argument + namespace will be passed to the constructor. + """""" + + def __init__(self, args): + self._args = args + + @classmethod + def init_parser(cls, parser): + """"""Initialize command line parser (:class:`argparse.ArgumentParser`)"""""" + + @abc.abstractmethod + def run(self): + """"""Execute command"""""" + + def argument_error(self, msg): + """"""Raise error indicating error parsing an argument."""""" + raise CommandError(msg) + + def fail(self, msg, exc=None): + """"""Exit command as a result of a failure."""""" + logger.error(msg) + if exc is not None: + logger.debug(""Command failure caused by exception!"", exc_info=exc) + sys.exit(1) + + +class InputError(Exception): + """"""Exception used to signal a general input error."""""" + + +class CommandError(Exception): + """"""Error from running a command. + + This should be raised from a ``Command.run()`` if any arguments are + misspecified. When the command is run and the ``CommandError`` is raised, + the caller will exit with an error code and print appropriate usage + information. + """""" + + +# Returns df with additional columns for stoichiometry +def calc_stoichiometry_df(df, counts): + df[""counts""] = pd.Series(counts) + df[""composition""] = df.counts / df.counts.sum() + df[""mass""] = df.mol_weight*df.composition + df[""stoichiometry""] = df.composition / df.mass.sum() + df = df.fillna(0) + return df + + +def load_compound_data(): + df = pd.read_csv(resource_filename(""psamm"", + ""external-data/biomass_compound_descriptions.tsv""), + sep=""\t"", na_values=[""None""]) + df.set_index(df.id.values, inplace=True) + return df + + +def make_template(compounds_df): + template = compounds_df[[""id"", ""name""]] + template[""custom_id""] = np.nan + return template + + +def apply_config(df, config_path): + config = pd.read_csv(config_path) + save_index = df.index + df = pd.merge(df, config, how=""left"", on=[""id"", ""name""]) + df.set_index(save_index, inplace=True) + df.custom_id = df.custom_id.fillna(df.id) + df.id = df.custom_id + return df + +# return model_dict + + +def load_model(model_path): + with open(model_path, ""r"") as f: + model_dict = yaml.safe_load(f) + return model_dict + + +def check_missing_cpds(model_path, df, config, yaml_args): + # Check if needed compounds are in the model, add them if not + model_dir = os.path.dirname(model_path) + model_reader = native.ModelReader.reader_from_path(model_path) + compounds = [r.id for r in model_reader.parse_compounds()] + if len(compounds) > 0: + missing_cpds = df.query(""id not in @compounds"") + droplist = [""type"", ""code""] + if config: + droplist.append(""custom_id"") + missing_cpds = missing_cpds.drop(columns=droplist) + if len(missing_cpds) > 0: + logger.warning(""\033[1mThe following compounds are required for "" + ""biomass equations but are missing from the model: "" + ""\033[0m{}\n\033[1mPredefined versions of these "" + ""compounds will be generated in {}. To use custom "" + ""biomass compound IDs, use --config\033[0m"" + """".format(list(missing_cpds.id), + os.path.join(model_dir, + ""biomass_compounds.yaml""))) + missing_cpd_entries = [v.dropna().to_dict() + for k, v in missing_cpds.iterrows()] + with open(os.path.join(model_dir, + ""biomass_compounds.yaml""), ""a+"") as f: + yaml.dump(missing_cpd_entries, f, **yaml_args) + + +def fix_cell_compartment(model_dict): + try: + cell_compartment = model_dict[""default_compartment""] + except KeyError: + cell_compartment = ""c"" + model_dict[""default_compartment""] = ""c"" + if cell_compartment is None: + cell_compartment = ""c"" + model_dict[""default_compartment""] = ""c"" + return cell_compartment + + +def update_model_yaml(model_path, model_dict, cell_compartment, + biomass_name, yaml_args): + exists = False # Checking if biomass_reactions.yaml already included + for file in model_dict[""reactions""]: + if ""biomass_reactions.yaml"" in file[""include""]: + exists = True + if not exists: + model_dict[""reactions""].append({""include"": + ""./biomass_reactions.yaml""}) + + exists = False # Checking if biomass_compounds.yaml already included + for file in model_dict[""compounds""]: + if ""biomass_compounds.yaml"" in file[""include""]: + exists = True + if not exists: + model_dict[""compounds""].append({""include"": + ""./biomass_compounds.yaml""}) + + model_dict[""biomass""] = biomass_name + + os.rename(model_path, model_path + "".tmp"") + with open(model_path, ""w"") as f: + yaml.dump(model_dict, f, **yaml_args) + os.remove(model_path + "".tmp"") + + +def count_DNA(genome, df, cell_compartment, decimals=6): + DNA = df[df.type == ""DNA""].copy().set_index(""code"") + DNA_counts = Counter() + for seq in genome: + DNA_counts += Counter(genome[seq].seq) + + calc_stoichiometry_df(DNA, DNA_counts) + total = DNA.stoichiometry.sum() + ids_fwd = list(DNA.id) + list(df.loc[[""C00002"", ""C00001""]].id.values) + stoich_fwd = list(DNA.stoichiometry) + [2*total, 2*total] + compound_fwd = {Compound(id).in_compartment(cell_compartment): + round(-1*n, decimals) for id, n in zip(ids_fwd, + stoich_fwd)} + ids_rev = list(df.loc[[""dna"", ""C00008"", ""C00009"", ""C00013""]].id.values) + stoich_rev = [1, 2*total, 2*total, total] + compound_rev = {Compound(id).in_compartment(cell_compartment): + round(n, decimals) for id, n in zip(ids_rev, stoich_rev)} + dna_rxn = Reaction(Direction.Forward, {**compound_fwd, **compound_rev}) + dna_rxn_entry = {""id"": ""dna_met"", + ""name"": ""DNA"", + ""equation"": str(dna_rxn), + ""pathways"": [""Biomass""]} + return dna_rxn_entry + + +def count_Prot(proteome, df, cell_compartment, decimals=6): + Prot = df[df.type == ""Prot""].copy().set_index(""code"") + Prot_counts = Counter() + for seq in proteome: + Prot_counts += Counter(proteome[seq].seq) + + # Protein Reaction formation + calc_stoichiometry_df(Prot, Prot_counts) + total = Prot.stoichiometry.sum() + ids_fwd = list(df[df.type == ""aatrna""].id) + \ + list(df.loc[[""C00044"", ""C00001""]].id.values) + stoich_fwd = list(Prot.stoichiometry) + [2*total, 2*total] + compound_fwd = {Compound(id).in_compartment(cell_compartment): + round(-1*n, decimals) for id, n in zip(ids_fwd, + stoich_fwd)} + ids_rev = list(df[df.type == ""trna""].id) +\ + list(df.loc[[""protein"", ""C00035"", ""C00009""]].id.values) + stoich_rev = list(Prot.stoichiometry) + [1, 2*total, 2*total] + compound_rev = {Compound(id).in_compartment(cell_compartment): + round(n, decimals) for id, n in zip(ids_rev, stoich_rev)} + prot_rxn = Reaction(Direction.Forward, {**compound_fwd, **compound_rev}) + prot_rxn_entry = {""id"": ""pro_met"", + ""name"": ""Protein"", + ""equation"": str(prot_rxn), + ""pathways"": [""Biomass""]} + return prot_rxn_entry + + +def count_RNA(genome, gff, df, cell_compartment, decimals=6): + RNA = df[df.type == ""RNA""].copy().set_index(""code"") + RNA_counts = Counter() + # Parsing through the gff and counting bases in coding regions to get + # the total RNA base counts + with open(gff, ""r"") as gff_file: + for line in gff_file: + if not line.startswith(""#""): + L = line.strip().split(""\t"") + if L[2] == ""CDS"": + try: + seq_entry = genome[L[0]] + except KeyError: + logger.warning(""The annotation {s} does not match "" + ""any sequence names in genome file, "" + ""ignoring..."".format(s=L[0])) + # FIX STRANDEDNESS: if - use reverse complement + if L[6] == ""-"": + RNA_counts += Counter(Seq.complement( + seq_entry.seq[int(L[3]):int(L[4])])) + else: + RNA_counts += Counter( + seq_entry.seq[int(L[3]):int(L[4])]) + try: + RNA_counts[""U""] = RNA_counts.pop(""T"") # renames T to U for RNA + except KeyError: + pass # If there are no T's, pass + + # RNA Reaction formation + calc_stoichiometry_df(RNA, RNA_counts) + total = RNA.stoichiometry.sum() + ids_fwd = list(RNA.id) + list(df.loc[[""C00001""]].id.values) + stoich_fwd = [RNA.loc[""A""].stoichiometry + 2*total] +\ + list(RNA.stoichiometry)[1:] + [2*total] + compound_fwd = {Compound(id).in_compartment(cell_compartment): + round(-1*n, decimals) for id, n in zip(ids_fwd, + stoich_fwd)} + ids_rev = list(df.loc[[""rna"", ""C00008"", ""C00009"", ""C00013""]].id.values) + stoich_rev = [1, 2*total, 2*total, total] + compound_rev = {Compound(id).in_compartment(cell_compartment): + round(n, decimals) for id, n in zip(ids_rev, stoich_rev)} + rna_rxn = Reaction(Direction.Forward, {**compound_fwd, **compound_rev}) + rna_rxn_entry = {""id"": ""rna_met"", + ""name"": ""RNA"", + ""equation"": str(rna_rxn), + ""pathways"": [""Biomass""]} + return rna_rxn_entry + + +def return_biomass_rxn(df, biomass_name, cell_compartment): + # Biomass reaction formation + compound_fwd = {Compound(id).in_compartment(cell_compartment): -1 + for id in list(df.loc[[""dna"", + ""rna"", ""protein""]].id.values)} + compound_rev = { + Compound(df.loc[""biomass""].id).in_compartment(cell_compartment): 1} + bio_rxn = Reaction(Direction.Forward, {**compound_fwd, **compound_rev}) + + bio_rxn_entry = {""id"": biomass_name, + ""name"": ""Biomass"", + ""equation"": str(bio_rxn), + ""pathways"": [""Biomass""]} + return bio_rxn_entry + + +def return_bio_sink_rxn(df, cell_compartment): + # Biomass sink reaction + bio_sink = Reaction(Direction.Forward, { + Compound(df.loc[""biomass""].id).in_compartment(cell_compartment): -1}) + + bio_sink_entry = {""id"": ""sink_biomass"", + ""name"": ""Biomass accumulation"", + ""equation"": str(bio_sink), + ""pathways"": [""Biomass""]} + return bio_sink_entry + + +def return_trna_rxns(df, cell_compartment): + # tRNA charging reactions + tRNA_rxns = [] + df_reac = pd.read_csv( + resource_filename(""psamm"", + ""external-data/biomass_reaction_descriptions.tsv""), + sep=""\t"") + for index, row in df_reac.iterrows(): + fwd, rev = row.equation.split("" <=> "") + ids_fwd = fwd.split("" + "") + ids_rev = rev.split("" + "") + compound_fwd = {Compound(id).in_compartment(cell_compartment): -1 + for id in list(df.loc[ids_fwd].id)} + compound_rev = {Compound(id).in_compartment(cell_compartment): 1 + for id in list(df.loc[ids_rev].id)} + tRNA_rxn = Reaction(Direction.Both, {**compound_fwd, **compound_rev}) + tRNA_rxn_entry = {""id"": row.id, + ""name"": row[""name""], + ""equation"": str(tRNA_rxn), + ""enzyme"": row[""enzymes""], + ""pathways"": [""Biomass""]} + tRNA_rxns.append(tRNA_rxn_entry) + return tRNA_rxns + + +class main(Command): + """"""Generate a database of compounds and reactions"""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument(""--genome"", metavar=""path"", + help=""[REQUIRED] Path to the genome "" + ""in fasta format"") + parser.add_argument(""--proteome"", metavar=""path"", + help=""[REQUIRED] Path to the proteome "" + ""in fasta format"") + parser.add_argument(""--gff"", metavar=""path"", + help=""[REQUIRED] Specify path to gff containing "" + ""transcript annotations. Only annotations "" + ""specified as \""CDS\"" in the third column will be "" + ""used. Annotations must correspond to sequences in"" + "" the --genome file."") + parser.add_argument(""--model"", metavar=""path"", + help=""[REQUIRED] Path to the model file"") + parser.add_argument(""--biomass"", metavar=""name"", default=""biomass"", + help=""Name to use for the biomass reaction, "" + ""default 'biomass'"") + parser.add_argument(""--config"", metavar=""path"", + help=""If you are using custom compound names for "" + ""the biomass-related compounds (e.g. amino acids, "" + ""DNA bases), specify them via a 3-column config "" + ""file. Use --generate-config to create a template "" + ""file."") + parser.add_argument(""--generate-config"", action=""store_true"", + help=""Makes a template config file for --config. "" + ""Compound IDs added in the third column will "" + ""replace the default kegg IDs for the compound."") + super(main, cls).init_parser(parser) + + def run(self): + """"""Entry point for the biomass reaction generation script"""""" + + if not self._args.generate_config: + if not self._args.genome: + raise InputError(""Please specify a path to the genome "" + ""in fasta format with --genome"") + if not self._args.proteome: + raise InputError(""Specify path to proteome in fasta format "" + ""with --proteome"") + if not self._args.gff: + raise InputError(""Specify path to gff containing transcript "" + ""annotations with --gff."") + if not self._args.model: + raise InputError(""Please specify the path to an existing "" + ""model with --model"") + if os.path.isdir(self._args.model): + if os.path.exists(os.path.join(self._args.model, + ""model.yaml"")): + model_path = os.path.join(self._args.model, ""model.yaml"") + else: + raise InputError(""No model.yaml file found!"") + else: + model_path = self._args.model + + # SETTING UP DATA + pd.options.mode.chained_assignment = None + df = load_compound_data() + if self._args.generate_config: + template = make_template(df) + template.to_csv(sys.stdout, index=False) + quit() + + faa = self._args.proteome + fna = self._args.genome + gff = self._args.gff + model_dir = os.path.dirname(model_path) + + yaml_args = {""default_flow_style"": False, + ""sort_keys"": False, + ""encoding"": ""utf-8"", + ""allow_unicode"": True, + ""width"": float(""inf"")} + + # Handling the config file + if self._args.config: + df = apply_config(df, self._args.config) + + # Adds missing compounds, updates model.yaml + # Makes biomass compounds and reactions yamls + logger.info(""Checking for existing compounds in the model"") + check_missing_cpds(model_path, df, self._args.config, yaml_args) + model_dict = load_model(model_path) + cell_compartment = fix_cell_compartment(model_dict) + + logger.info(""Updating {}"".format(os.path.abspath(model_path))) + update_model_yaml(model_path, model_dict, cell_compartment, + self._args.biomass, yaml_args) + + # Counting bases/amino acids and making reaction entries + genome = {seq.name: seq.upper() for seq in SeqIO.parse(fna, ""fasta"")} + proteome = {seq.name: seq.upper() for seq in SeqIO.parse(faa, ""fasta"")} + + logger.info(""Calculating stoichiometry for DNA, RNA, and amino acids"") + dna_rxn_entry = count_DNA(genome, df, cell_compartment) + prot_rxn_entry = count_Prot(proteome, df, cell_compartment) + rna_rxn_entry = count_RNA(genome, gff, df, cell_compartment) + + # Making the reaction entries for other biomass rxns + bio_rxn_entry = return_biomass_rxn( + df, self._args.biomass, cell_compartment) + bio_sink_entry = return_bio_sink_rxn(df, cell_compartment) + tRNA_rxns = return_trna_rxns(df, cell_compartment) + + # GENERATING biomass_reactions.yaml + logger.info(""Generating new biomass reactions in "" + ""{}/biomass_reactions.yaml"".format( + os.path.abspath(model_dir))) + + with open(os.path.join(model_dir, ""biomass_reactions.yaml""), ""w"") as f: + yaml.dump([dna_rxn_entry, rna_rxn_entry, + prot_rxn_entry, bio_rxn_entry, + bio_sink_entry] + tRNA_rxns, + f, **yaml_args) +","Python" +"Metabolic","zhanglab/psamm","psamm/mapmaker.py",".py","8498","263","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2016-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Functions for predicting compound pairs using the MapMaker algorithm. + +The MapMaker algorithm is described in [Tervo16]_. +"""""" + +from itertools import product + +from six import iteritems + +from .lpsolver import lp +from .formula import Atom, Radical, Formula + + +def default_weight(element): + """"""Return weight of formula element. + + This implements the default weight proposed for MapMaker. + """""" + if element in (Atom.N, Atom.O, Atom.P): + return 0.4 + elif isinstance(element, Radical): + return 40.0 + return 1.0 + + +def _weighted_formula(form, weight_func): + """"""Yield weight of each formula element."""""" + for e, mf in form.items(): + if e == Atom.H: + continue + + yield e, mf, weight_func(e) + + +def _transfers(reaction, delta, elements, result, epsilon): + """"""Yield transfers obtained from result."""""" + left = set(c for c, _ in reaction.left) + right = set(c for c, _ in reaction.right) + for c1, c2 in product(left, right): + items = {} + for e in elements: + v = result.get_value(delta[c1, c2, e]) + nearest_int = round(v) + if abs(v - nearest_int) < epsilon: + v = int(nearest_int) + if v >= epsilon: + items[e] = v + + if len(items) > 0: + yield (c1, c2), Formula(items) + + +def _reaction_to_dicts(reaction): + """"""Convert a reaction to reduced left, right dictionaries."""""" + + def dict_from_iter_sum(it): + d = {} + for k, v in it: + if k not in d: + d[k] = 0 + d[k] += v + return d + + left = dict_from_iter_sum(reaction.left) + right = dict_from_iter_sum(reaction.right) + + return left, right + + +class UnbalancedReactionError(ValueError): + """"""Raised when an unbalanced reaction is provided."""""" + + +def predict_compound_pairs(reaction, compound_formula, solver, epsilon=1e-5, + alt_elements=None, weight_func=default_weight): + """"""Predict compound pairs of reaction using MapMaker. + + Yields all solutions as dictionaries with compound pairs as keys and + formula objects as values. + + Args: + reaction: :class:`psamm.reaction.Reaction` object. + compound_formula: Dictionary mapping compound IDs to formulas. Formulas + must be flattened. + solver: LP solver (MILP). + epsilon: Threshold for rounding floating-point values to integers in + the predicted transfers. + alt_elements: Iterable of elements to consider for alternative + solutions. Only alternate solutions that have different transfers + of these elements will be returned (default=all elements). + weight_func: Optional function that returns a weight for a formula + element (should handle specific Atom and Radical objects). By + default, the standard MapMaker weights will be used + (H=0, R=40, N=0.4, O=0.4, P=0.4, *=1). + """""" + elements = set() + for compound, value in reaction.compounds: + if compound.name not in compound_formula: + return + + f = compound_formula[compound.name] + elements.update(e for e, _, _ in _weighted_formula(f, weight_func)) + + if len(elements) == 0: + return + + p = solver.create_problem() + + x = p.namespace(name='x') + y = p.namespace(name='y') + m = p.namespace(name='m') + q = p.namespace(name='q') + omega = p.namespace(name='omega') + gamma = p.namespace(name='gamma') + delta = p.namespace(name='delta') + + left, right = _reaction_to_dicts(reaction) + + objective = 0 + for c1, c2 in product(left, right): + m.define([(c1, c2)], lower=0) + q.define([(c1, c2)], lower=0) + omega.define([(c1, c2)], types=lp.VariableType.Binary) + + objective += 100 * m[c1, c2] + 90 * q[c1, c2] - 0.1 * omega[c1, c2] + + gamma.define(((c1, c2, e) for e in elements), + types=lp.VariableType.Binary) + delta.define(((c1, c2, e) for e in elements), lower=0) + + # Eq 12 + x.define([(c1, c2)], types=lp.VariableType.Binary) + y.define([(c1, c2)], types=lp.VariableType.Binary) + p.add_linear_constraints(y[c1, c2] <= 1 - x[c1, c2]) + + # Eq 6, 9 + delta_wsum = delta.expr( + ((c1, c2, e), weight_func(e)) for e in elements) + p.add_linear_constraints( + m[c1, c2] <= delta_wsum, q[c1, c2] <= delta_wsum) + + objective -= gamma.sum((c1, c2, e) for e in elements) + + p.set_objective(objective) + + # Eq 3 + zs = {} + for c1, v in iteritems(left): + f = compound_formula[c1.name] + for e in elements: + mf = f.get(e, 0) + delta_sum = delta.sum((c1, c2, e) for c2 in right) + try: + p.add_linear_constraints(delta_sum == v * mf) + except ValueError: + raise UnbalancedReactionError('Unable to add constraint') + + # Eq 8, 11 + x_sum = x.sum((c1, c2) for c2 in right) + y_sum = y.sum((c1, c2) for c2 in right) + p.add_linear_constraints(x_sum <= 1, y_sum <= 1) + + # Eq 13 + zs[c1] = 0 + for e, mf, w in _weighted_formula(f, weight_func): + zs[c1] += w * mf + + # Eq 2 + for c2, v in iteritems(right): + f = compound_formula[c2.name] + for e in elements: + mf = f.get(e, 0) + delta_sum = delta.sum((c1, c2, e) for c1 in left) + try: + p.add_linear_constraints(delta_sum == v * mf) + except ValueError: + raise UnbalancedReactionError('Unable to add constraint') + + for c1, v1 in iteritems(left): + for c2 in right: + f1 = compound_formula[c1.name] + f2 = compound_formula[c2.name] + for e in elements: + mf = f1.get(e, 0) + + # Eq 4 + p.add_linear_constraints( + delta[c1, c2, e] <= float(v1) * mf * omega[c1, c2]) + + # Eq 5 + if e in f2: + p.add_linear_constraints( + delta[c1, c2, e] <= float(v1) * mf * gamma[c1, c2, e]) + + # Eq 7, 10 + p.add_linear_constraints( + m[c1, c2] <= float(v1) * zs[c1] * x[c1, c2], + q[c1, c2] <= float(v1) * zs[c1] * y[c1, c2]) + + try: + result = p.solve(lp.ObjectiveSense.Maximize) + except lp.SolverError: + raise UnbalancedReactionError('Unable to solve') + + first_objective = result.get_value(objective) + + # Yield the first result + yield dict(_transfers(reaction, delta, elements, result, epsilon)) + + # Find alternative solutions + if alt_elements is None: + alt_elements = elements + else: + alt_elements = elements.intersection(alt_elements) + + if len(alt_elements) == 0: + return + + # Add a constraint that disallows the current transfer solution until no + # alternative solutions are left. + add_objective_constraint = True + while True: + elem_vars = 0 + elem_count = 0 + for c1, c2 in product(left, right): + for e in alt_elements: + if result.get_value(gamma[c1, c2, e]) > 0.5: + elem_count += 1 + elem_vars += gamma[c1, c2, e] + + if elem_count == 0: + break + + if add_objective_constraint: + p.add_linear_constraints(objective >= first_objective) + add_objective_constraint = False + + p.add_linear_constraints(elem_vars <= elem_count - 1) + try: + result = p.solve(lp.ObjectiveSense.Maximize) + except lp.SolverError: + break + + yield dict(_transfers(reaction, delta, elements, result, epsilon)) +","Python" +"Metabolic","zhanglab/psamm","psamm/graph.py",".py","38397","939","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2018-2020 Ke Zhang +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2020 Elysha Sameth + +from __future__ import unicode_literals + +from itertools import count +from six import iteritems, text_type +from collections import defaultdict, Counter + +from . import findprimarypairs + +import logging + +from .formula import Formula, Atom, ParseError +from .reaction import Direction, Reaction + + +logger = logging.getLogger(__name__) + + +def _graphviz_prop_string(d): + return ','.join('{}=""{}""'.format(k, text_type(v)) for k, v + in sorted(iteritems(d))) + + +class Entity(object): + """"""Base class for graph entities."""""" + + def __init__(self, props={}): + self._props = dict(props) + + @property + def props(self): + return self._props + + def __repr__(self): + return '<{} id={}>'.format( + self.__class__.__name__, self._props.get('id')) + + +class Graph(Entity): + """"""Graph entity representing a collection of nodes and edges."""""" + + def __init__(self, props={}): + super(Graph, self).__init__(props) + self._nodes = set() + self._edges = {} + self._node_edges = {} + self._edge_count = 0 + self._default_node_props = {} + self._default_edge_props = {} + self._nodes_id = {} + self._nodes_original_id = defaultdict(list) + + def add_node(self, node): + """"""add node to a Graph entity. + node: Node entity. + """""" + self._nodes.add(node) + self._nodes_id[node.props['id']] = node + if 'type' in node.props: + self.set_original_id(node) + else: + self._nodes_original_id[node.props['id']].append(node) + + def set_original_id(self, node): + if node.props['type'] == 'cpd': + original_id_string = ','.join([c.id for c in node.props['entry']]) + else: + if node.props['type'] == 'Ex_rxn': + original_id_string = node.props['id'] + else: + original_id_string = ','.join( + [r.id for r in node.props['entry']]) + self._nodes_original_id[original_id_string].append(node) + + def get_node(self, node_id): + """"""get Node object. + Args: + node_id: text_type(compound object) or text_type(a string that + contains single or multiple reaction IDs). + """""" + return self._nodes_id[node_id] + + def add_edge(self, edge): + if edge.source not in self._nodes or edge.dest not in self._nodes: + raise ValueError('Edge nodes not in graph') + + s_nodes = tuple([edge.source, edge.dest]) + self._edges.setdefault(s_nodes, set()).add(edge) + self._edge_count += 1 + + self._node_edges.setdefault(edge.source, {}).setdefault( + edge.dest, set()).add(edge) + self._node_edges.setdefault(edge.dest, {}).setdefault( + edge.source, set()).add(edge) + + @property + def nodes(self): + return iter(self._nodes) + + @property + def node_count(self): + return len(self._nodes) + + @property + def nodes_id_dict(self): + return self._nodes_id + + @property + def nodes_original_id_dict(self): + return self._nodes_original_id + + @property + def edges(self): + for pair, edges in iteritems(self._edges): + for edge in edges: + yield edge + + @property + def edge_count(self): + return self._edge_count + + def edges_for(self, node): + return iteritems(self._node_edges.get(node, {})) + + @property + def default_node_props(self): + return self._default_node_props + + @property + def default_edge_props(self): + return self._default_edge_props + + def write_graphviz(self, f, width, height): + """""" Write the nodes and edges information into a dot file. + + Print a given graph object to a graph file in the dot format. + This graph can then be converted to an image file using the + graphviz program. + + Args: + self: Graph entity, including nodes and edges entities. + f: An empty file. + width: Width of final metabolic map. + height: Height of final metabolic map. + """""" + f.write('digraph {\n') + if width is not None and height is not None: + f.write('size = ""{}, {}""; ratio = fill;\n'.format(width, height)) + + if len(self._default_node_props) > 0: + f.write(' node[{}];\n'.format( + _graphviz_prop_string(self._default_node_props))) + + if len(self._default_edge_props) > 0: + f.write(' edge[{}];\n'.format( + _graphviz_prop_string(self._default_edge_props))) + + for k, v in iteritems(self.props): + f.write(' {}=""{}"";\n'.format(k, v)) + + for node in sorted(self.nodes, key=lambda k: k.props['id']): + f.write(' ""{}""[{}]\n'.format(node.props['id'], + _graphviz_prop_string(node.props))) + + for edge in sorted(self.edges, key=lambda k: ( + k.source.props['id'], k.dest.props['id'], k.props.get('dir'))): + f.write(' ""{}"" -> ""{}""[{}]\n'.format( + edge.source.props['id'], edge.dest.props['id'], + _graphviz_prop_string(edge.props))) + + f.write('}\n') + + def write_graphviz_compartmentalized(self, f, compartment_tree, + extracellular, width, height): + """"""Function to write compartmentalized version of dot file + for graph. + + Print a given graph object to a graph file in the dot format. + In this graph, reaction nodes will be separated into different + areas in the visualization based on the defined cellular + compartments in the GEM. + + Args: + self: Graph entity. + f: An empty file. + compartment_tree: a defaultdict of set, each element + represents a compartment and its adjacent compartments. + extracellular: the extracellular compartment in the model + width: Width of final metabolic map. + height: Height of final metabolic map.. + """""" + f.write('digraph {\n') + if width is not None and height is not None: + f.write('size=""{},{}""; ratio = fill;\n'.format(width, height)) + + if len(self._default_node_props) > 0: + f.write(' node[{}];\n'.format( + _graphviz_prop_string(self._default_node_props))) + + if len(self._default_edge_props) > 0: + f.write(' edge[{}];\n'.format( + _graphviz_prop_string(self._default_edge_props))) + + for k, v in iteritems(self.props): + f.write(' {}=""{}"";\n'.format(k, v)) + + next_id = count(0) + node_dicts = defaultdict(list) + + for node in self.nodes: + node_dicts[node.props['compartment']].append(node) + + def edit_labels(string): + return string.replace('-', '_') + + def write_node_props(f, node_list): + for node in node_list: + if 'id' not in node.props: + node.props['id'] = 'n{}'.format(next(next_id)) + f.write(' ""{}""[{}]\n'.format( + node.props['id'], _graphviz_prop_string(node.props))) + + def dfs_recursive(graph, vertex, node_dict, + extracellular, f, path=[]): + path.append(vertex) + if vertex == extracellular: + f.write(''.join( + [' subgraph cluster_{} '.format(edit_labels(vertex)), + '{\n style=solid;\n color=black;\n penwidth=4;\n ' + 'fontsize=35;\n', + ' label = ""Compartment: {}""\n'.format + (edit_labels(vertex))])) + for x in sorted(node_dict[vertex], + key=lambda k: k.props['id']): + f.write(' ""{}""[{}]\n'.format( + x.props['id'], _graphviz_prop_string(x.props))) + elif vertex != extracellular: + f.write(''.join( + [' subgraph cluster_{} '.format(edit_labels(vertex)), + '{\n style=dashed;\n color=black;\n ' + 'penwidth=4;\n fontsize=35;\n', + ' label = ""Compartment: {}""\n'.format + (edit_labels(vertex))])) + for x in sorted(node_dict[vertex], + key=lambda k: k.props['id']): + f.write(' ""{}""[{}]\n'.format( + x.props['id'], _graphviz_prop_string(x.props))) + for neighbor in graph[vertex]: + if neighbor not in path: + path = dfs_recursive(graph, neighbor, node_dict, path, f) + f.write('}') + return path + + dfs_recursive(compartment_tree, extracellular, node_dicts, + extracellular, f) + + for edge in sorted(self.edges, key=lambda k: (k.source.props['id'], + k.dest.props['id'], + k.props.get('dir'))): + f.write(' ""{}"" -> ""{}""[{}]\n'.format( + edge.source.props['id'], edge.dest.props['id'], + _graphviz_prop_string(edge.props))) + + f.write('}\n') + + def write_nodes_tables(self, f): + """"""write a table file (.tsv) that contains nodes information. + + Write all node information from a given graph object into a + tab separated table. This table will include IDs, shapes, + fill colors, and labels. This table can be used to import + the graph information to other programs. + + Args: + self: Graph entity. + f: An empty file. + """""" + + properties = set() + for node in self.nodes: + if 'label' not in node.props: + node.props['label'] = node.props['id'] + properties.update(node.props) + if 'id' in properties: + properties.remove('id') + if 'label' in properties: + properties.remove('label') + if 'original_id' in properties: + properties.remove('original_id') + if 'entry' in properties: + properties.remove('entry') + properties = ['id'] + sorted(properties) + ['label'] + f.write('\t'.join(properties) + '\n') + + for node in sorted(self.nodes, key=lambda k: k.props['id']): + # a = '\t'.join(text_type(node.props.get(x)) + # for x in properties if x != 'label') + a = '\t'.join(text_type(node.props.get(x)) + for x in properties if x not in ['label', 'entry']) + b = node.props['label'].replace('\n', ',') + f.write('{}\t{}\n'.format(a, b)) + + def write_edges_tables(self, f): + """""" Write a tab separated table that contains edges information, + including edge source, edge dest, and edge properties. + + Write all edge information from a given graph object into a + tab separated table. This table will include IDs, source nodes + and destination nodes. This table can be used to import + the graph information to other programs. + + Args: + self: Graph entity. + f: An empty TSV file. + """""" + properties = set() + for edge in self.edges: + properties.update(edge.props) + + properties = sorted(properties) + header = ['source', 'target'] + properties + f.write('\t'.join(header) + '\n') + for edge in sorted(self.edges, key=lambda k: (edge.source.props['id'], + edge.dest.props['id'], + edge.props.get('dir'))): + f.write('{}\t{}\t{}\n'.format( + edge.source.props['id'], edge.dest.props['id'], + '\t'.join( + text_type(edge.props.get(x)) for x in properties))) + + +class Node(Entity): + """"""Node entity represents a vertex in the graph."""""" + __hash__ = Entity.__hash__ + + def __init__(self, props={}): + super(Node, self).__init__(props) + + def __eq__(self, other): + if isinstance(other, self.__class__): + return other._props == self._props + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + +class Edge(Entity): + """"""Edge entity represents a connection between nodes."""""" + __hash__ = Entity.__hash__ + + def __init__(self, source, dest, props={}): + super(Edge, self).__init__(props) + self.source = source + self.dest = dest + + def __eq__(self, other): + if isinstance(other, self.__class__): + a = self._props == other._props + b = self.source == other.source + c = self.dest == other.dest + if all(i is True for i in [a, b, c]): + return True + else: + return False + + def __ne__(self, other): + return not self.__eq__(other) + + +def get_compound_dict(model): + """""" Parse through model compounds and return a formula dict. + + This function will parse the compound information + in a given model and return a dictionary of compound IDs to + compound formula objects. + + Args: + model: + """""" + compound_formula = {} + for compound in model.compounds: + if compound.formula is not None: + try: + f = Formula.parse(compound.formula).flattened() + if not f.is_variable(): + compound_formula[compound.id] = f + else: + logger.warning( + 'Skipping variable formula {}: {}'.format( + compound.id, compound.formula)) + except ParseError as e: + msg = ( + 'Error parsing formula' + ' for compound {}:\n{}\n{}'.format( + compound.id, e, compound.formula)) + if e.indicator is not None: + msg += '\n{}'.format(e.indicator) + logger.warning(msg) + return compound_formula + + +def make_network_dict(nm, mm, subset=None, method='fpp', element=None, + excluded_reactions=[], reaction_dict={}, analysis=None): + """"""Create a dictionary of reactant/product pairs to reaction directions. + + Returns a dictionary that connects predicted reactant/product pairs + to their original reaction directions. This dictionary is used when + generating bipartite graph objects. This can be done either using + the FindPrimaryPairs method to predict reactant/product pairs or + by mapping all possible pairs. + + Args: + nm: , the native model + mm: , the metabolic model. + subset: None or path to a file that contains a list of reactions or + compound ids. By default, it is None. It defines which reaction + need to be visualized. + method: 'fpp' or 'no-fpp', the method used for visualization. + element: Symbol of chemical atom, such as 'C' ('C' indicates carbon). + excluded_reactions: a list that contains reactions excluded from + visualization. + reaction_dict: dictionary of FBA or FVA results. By default it is an + empty dictionary. + analysis: ""None"" type or a string indicates if FBA or FVA file is + given in command line. + """""" + compound_formula = get_compound_dict(nm) + if not compound_formula and (method == 'fpp' or element): + logger.error( + 'Compound formulas are required for fpp or specific element ' + 'visualizations, try --element all to visualize all pathways ' + 'without compound formula input.') + exit(1) + + if subset is not None: + testing_list_raw = [] + for rxn in mm.reactions: + if rxn in nm.reactions or mm.is_exchange(rxn): + if rxn in subset: + if rxn not in excluded_reactions: + testing_list_raw.append(rxn) + else: + logger.warning( + 'Reaction {} is in the subset and exclude file. ' + 'Reaction will be excluded.'.format(rxn)) + else: + testing_list_raw = [rxn for rxn in mm.reactions + if (rxn in nm.reactions or mm.is_exchange(rxn)) and + rxn not in excluded_reactions] + + reaction_data = {} + style_flux_dict = {} + + for rxn in testing_list_raw: + flux = 0 + style = 'solid' if analysis is None else 'dotted' + # direction = nm.reactions[rxn].equation.direction + direction = mm.get_reaction(rxn).direction + if rxn in reaction_dict: + style = 'solid' + reaction = mm.get_reaction(rxn) + lower = reaction_dict[rxn][0] + upper = reaction_dict[rxn][1] + flux = lower * upper + + if flux == 0: + if analysis == 'fba' or (lower == 0 and upper == 0): + style = 'dotted' + elif lower == 0: + direction = Direction.Forward + else: + direction = Direction.Reverse + elif flux > 0: + direction = Direction.Forward if ( + analysis == 'fba' or lower > 0) else Direction.Reverse + else: + direction = Direction.Reverse if analysis == 'fba' \ + else Direction.Both + + r = Reaction(direction, reaction.left, reaction.right) + r_id = rxn + mm.remove_reaction(rxn) + mm.database.set_reaction(r_id, r) + mm.add_reaction(r_id) + if rxn in nm.reactions: + nm.reactions[rxn].equation = r + if rxn in nm.reactions: + reaction_data[rxn] = (nm.reactions[rxn], direction) + style_flux_dict[rxn] = (style, abs(flux)) + + flux_list = sorted([f for s, f in style_flux_dict.values()]) + median = 1 + flux_list = list(filter(lambda x: x != 0, flux_list)) + + testing_list = [rxn for rxn in testing_list_raw if not mm.is_exchange(rxn)] + + if flux_list: + mid = len(flux_list) // 2 + median = flux_list[mid] if len(flux_list) % 2 else float( + flux_list[mid-1] + flux_list[mid]) / 2.0 + if median < 1: + median = 1 + + for rxn, (style, flux) in style_flux_dict.items(): + new_flux = float(5 * flux) / float(median) + new_flux = max(min(10, new_flux), 1) + style_flux_dict.update({rxn: (style, new_flux)}) + + full_pairs_dict = {} + if method == 'fpp': + element_weight = findprimarypairs.element_weight + testing_list_update = [] + for r in testing_list: + if all(cpd.name in compound_formula + for cpd, _ in nm.reactions[r].equation.compounds): + testing_list_update.append(r) + else: + logger.warning( + 'Reaction {} is excluded from visualization due to ' + 'missing or undefined compound formula'.format(r)) + reaction_pairs = [(r, nm.reactions[r].equation) + for r in testing_list_update] + fpp_dict, _ = findprimarypairs.predict_compound_pairs_iterated( + reaction_pairs, compound_formula, element_weight=element_weight) + + for rxn_id, fpp_pairs in iteritems(fpp_dict): + compound_pairs = [] + for cpd_pair, transfer in iteritems(fpp_pairs[0]): + if element is None: + compound_pairs.append(cpd_pair) + else: + if any(Atom(element) in k for k in transfer): + compound_pairs.append(cpd_pair) + (rxn_entry, rxn_dir) = reaction_data[rxn_id] + full_pairs_dict[rxn_entry] = (sorted(compound_pairs), rxn_dir) + + elif method == 'no-fpp': + for reaction in testing_list: + compound_pairs = [] + for substrate in nm.reactions[reaction].equation.left: + for product in nm.reactions[reaction].equation.right: + if element is None: + compound_pairs.append((substrate[0], product[0])) + else: + if Atom(element) in \ + compound_formula[substrate[0].name] and \ + Atom(element) in \ + compound_formula[product[0].name]: + compound_pairs.append((substrate[0], product[0])) + full_pairs_dict[nm.reactions[reaction]] = \ + (sorted(compound_pairs), + nm.reactions[reaction].equation.direction) + + return full_pairs_dict, style_flux_dict + + +def write_network_dict(network_dict): + """"""Print out network dictionary object to a tab separated table. + + Print information from the dictionary ""network_dict"". This information + includes four items: reaction ID, reactant, product, and direction. + this can table can be used as an input to other graph visualization + and analysis software. + + + Args: + network_dict: Dictionary object from make_network_dict() + """""" + for key, value in sorted(iteritems(network_dict), key=lambda x: str(x)): + (cpair_list, dir) = value + for (c1, c2) in cpair_list: + print('{}\t{}\t{}\t{}'.format(key.id, c1, c2, dir_value(dir))) + + +def make_cpair_dict(filter_dict, args_method, args_combine, style_flux_dict, + hide_edges=[]): + """"""Create a mapping from compound pair to a defaultdict containing + lists of reactions for the forward, reverse, and both directions. + + Returns a dictionary that connects reactant/product pair to all reactions + that contain this pair. Those reactions are stored in a dictionary and + classified by reaction direction. For example: + {(c1, c2): {'forward': [rxn1], 'back': [rxn3], 'both': [rxn4, rxn5]}, + (c3, c4): {...}, ...} + + Args: + filter_dict: A dictionary mapping reaction entry to + compound pairs (inside of the pairs there are cpd + objects, not cpd IDs) + args_method: a string, including 'fpp' and 'no-fpp'. + args_combine: combine level, default = 0, optional: 1 and 2. + style_flux_dict: a dictionary to set the edge style when fba or + fva input is given. + hide_edges: to determine edges between which compound pair need + to be hidden. + """""" + + new_id_mapping = {} + new_style_flux_dict = {} + rxn_count = Counter() + cpair_dict = defaultdict(lambda: defaultdict(list)) + + def make_mature_cpair_dict(cpair_dict, hide): + new_cpair_dict = {} + cpair_list = [] + for (c1, c2), rxns in sorted(iteritems(cpair_dict)): + if (c1, c2) not in cpair_list and (text_type(c1), + text_type(c2)) not in hide: + new_rxns = rxns + if (c2, c1) in cpair_dict: + if len(cpair_dict[(c2, c1)]['forward']) > 0: + for r in cpair_dict[(c2, c1)]['forward']: + new_rxns['back'].append(r) + if len(cpair_dict[(c2, c1)]['back']) > 0: + for r in cpair_dict[(c2, c1)]['back']: + new_rxns['forward'].append(r) + if len(cpair_dict[(c2, c1)]['both']) > 0: + for r in cpair_dict[(c2, c1)]['both']: + new_rxns['both'].append(r) + new_cpair_dict[(c1, c2)] = new_rxns + cpair_list.append((c1, c2)) + cpair_list.append((c2, c1)) + else: + new_cpair_dict[(c1, c2)] = new_rxns + cpair_list.append((c1, c2)) + + rxns_sorted_cpair_dict = defaultdict(lambda: defaultdict(list)) + for (c1, c2), rxns in sorted(iteritems(new_cpair_dict)): + for direction, rlist in iteritems(rxns): + rxns_sorted_cpair_dict[(c1, c2)][direction] = sorted(rlist) + + return rxns_sorted_cpair_dict + + if args_method != 'no-fpp': + if args_combine == 0: + for rxn, cpairs_dir in iteritems(filter_dict): + have_visited = set() + sub_pro = defaultdict(list) + rxn_mixcpairs = defaultdict(list) + for (c1, c2) in sorted(cpairs_dir[0]): + sub_pro[c1].append(c2) + for k1, v1 in sorted(iteritems(sub_pro)): + if k1 not in have_visited: + rxn_count[rxn] += 1 + have_visited.add(k1) + r_id = '{}_{}'.format(rxn.id, rxn_count[rxn]) + new_id_mapping[r_id] = rxn + new_style_flux_dict[r_id] = style_flux_dict[rxn.id] + for v in v1: + rxn_mixcpairs[r_id].append((k1, v)) + for k2, v2 in iteritems(sub_pro): + if k2 not in have_visited: + if k2 != k1: + if v1 == v2: + have_visited.add(k2) + for vtest in v2: + rxn_mixcpairs[r_id].append( + (k2, vtest)) + for rxn_id, cpairs in iteritems(rxn_mixcpairs): + for (c1, c2) in cpairs: + if cpairs_dir[1] == Direction.Forward: + cpair_dict[(c1, c2)]['forward'].append(rxn_id) + elif cpairs_dir[1] == Direction.Reverse: + cpair_dict[(c1, c2)]['back'].append(rxn_id) + else: + cpair_dict[(c1, c2)]['both'].append(rxn_id) + + elif args_combine == 1 or args_combine == 2: + for rxn, cpairs_dir in iteritems(filter_dict): + cpd_rid = {} + have_visited = set() + for (c1, c2) in sorted(cpairs_dir[0]): + if c1 not in have_visited: + if c2 not in have_visited: + rxn_count[rxn] += 1 + rxn_id = '{}_{}'.format( + rxn.id, rxn_count[rxn]) + new_id_mapping[rxn_id] = rxn + new_style_flux_dict[rxn_id] = \ + style_flux_dict[rxn.id] + have_visited.add(c1) + have_visited.add(c2) + cpd_rid[c1] = rxn_id + cpd_rid[c2] = rxn_id + else: + rxn_id = cpd_rid[c2] + have_visited.add(c1) + cpd_rid[c1] = rxn_id + else: + rxn_id = cpd_rid[c1] + have_visited.add(c2) + cpd_rid[c2] = rxn_id + + if cpairs_dir[1] == Direction.Forward: + cpair_dict[(c1, c2)]['forward'].append(rxn_id) + elif cpairs_dir[1] == Direction.Reverse: + cpair_dict[(c1, c2)]['back'].append(rxn_id) + else: + cpair_dict[(c1, c2)]['both'].append(rxn_id) + else: + for rxn, cpairs_dir in iteritems(filter_dict): + for (c1, c2) in cpairs_dir[0]: + r_id = rxn.id + new_id_mapping[r_id] = rxn + new_style_flux_dict[r_id] = style_flux_dict[rxn.id] + if cpairs_dir[1] == Direction.Forward: + cpair_dict[(c1, c2)]['forward'].append(r_id) + elif cpairs_dir[1] == Direction.Reverse: + cpair_dict[(c1, c2)]['back'].append(r_id) + else: + cpair_dict[(c1, c2)]['both'].append(r_id) + + rxns_sorted_cpair_dict = make_mature_cpair_dict(cpair_dict, hide_edges) + return rxns_sorted_cpair_dict, new_id_mapping, new_style_flux_dict + + +def make_bipartite_graph_object(cpairs_dict, new_id_mapping, method, + args_combine, model_compound_entries, + new_style_flux_dict, analysis=None): + """""" Makes a bipartite graph object from a cpair_dict object. + + Start from empty graph() and cpair dict to make a graph object. + Nodes only have rxn/cpd ID and rxn/cpd entry info in this initial + graph. The information can be modified to add on other properties + like color, or names. + + Args: + cpairs_dict: defaultdict of compound_pair: + defaultdict of direction: reaction list. + e.g. {(c1, c2): {'forward"":[rx1], + 'both':[rx2}}. + new_id_mapping: dictionary of rxn_id_suffix: rxn_id. + method: options=['fpp', 'no-fpp', file_path]. + args_combine: Command line argument, could be 0, 1, 2. + model_compound_entries: dict of cpd_id:compound_entry. + new_style_flux_dict: a dictionary to determine the edge style with + the new reaction IDs. + return: A graph object that contains basic nodes and edges. + only ID and rxn/cpd entry are in node properties, + no features like color, shape. + """""" + g = Graph() + g._default_node_props['fontname'] = 'Arial' + g._default_node_props['fontsize'] = 12 + + def add_graph_nodes(g, cpairs_dict, method, new_id_mapping, args_combine, + model_compound_entries): + """""" Create compound and reaction nodes, adding them to + empty graph object. + + Args: + g: An empty Graph object. + cpairs_dict: defaultdict of compound_pair: + defaultdict of direction: + reaction list. e.g. {(c1, c2): {'forward"":[rx1], + 'both':[rx2}}. + method: Command line argument, + options=['fpp', 'no-fpp', file_path]. + new_id_mapping: dictionary of rxn_id_suffix: rxn_id. + args_combine: Command line argument, + could be 0, 1, 2. By default it is 0. + model_compound_entries: cpd id map to cpd entry of native model. + return: A graph object that contains a set of nodes. + """""" + graph_nodes = set() + for cpair, reactions in sorted(iteritems(cpairs_dict)): + for c in cpair: + if c not in graph_nodes: + node = Node({ + 'id': text_type(c), + 'entry': [model_compound_entries[c.name]], + 'compartment': c.compartment, + 'type': 'cpd'}) + g.add_node(node) + graph_nodes.add(c) + for direction, rlist in iteritems(reactions): + if method != 'no-fpp' and args_combine == 2: + real_rxns = [new_id_mapping[r] for r in rlist] + rxn_string = text_type(','.join(rlist)) + if rxn_string not in graph_nodes: + rnode = Node({ + 'id': text_type(','.join(rlist)), + 'entry': real_rxns, + 'compartment': c.compartment, + 'type': 'rxn'}) + g.add_node(rnode) + graph_nodes.add(rxn_string) + else: + for sub_rxn in rlist: + rxn_ob = new_id_mapping[sub_rxn] + if sub_rxn not in graph_nodes: + rnode = Node({ + 'id': text_type(sub_rxn), + 'entry': [rxn_ob], + 'compartment': c.compartment, + 'type': 'rxn'}) + g.add_node(rnode) + graph_nodes.add(sub_rxn) + return g + + def add_edges(g, cpairs_dict, method, args_combine, new_style_flux_dict, + analysis): + """""" Add edges to the graph object obtained in last step. + + Args: + g: A graph object contains a set of nodes. + cpairs_dict: A defaultdict of compound_pair: defaultdict + of direction: reaction list. e.g. {(c1, c2): + {'forward"":[rx1], 'both':[rx2}}. + method: Command line argument, options= + ['fpp', 'no-fpp', file_path]. + # split: Command line argument, True or False. + By default split = False. + args_combine: Command line argument, an + integer(could be 0, 1 or 2). + new_style_flux_dict: A dictsionary of reaction is maps to edge + style and edge width. + analysis: ""None"" type or a string indicates if FBA or FVA file is + given in command line. + """""" + edge_list = [] + for (c1, c2), value in iteritems(cpairs_dict): + for direction, rlist in iteritems(value): + new_rlist = ','.join(rlist) + if args_combine == 0 or args_combine == 1 or \ + method == 'no-fpp': + for sub_rxn in rlist: + test1 = c1, sub_rxn + if test1 not in edge_list: + edge_list.append(test1) + g.add_edge(Edge( + g.get_node(text_type(c1)), + g.get_node(text_type(sub_rxn)), + {'dir': direction, + 'style': new_style_flux_dict[sub_rxn][0], + 'penwidth': new_style_flux_dict[sub_rxn][1]})) + + test2 = c2, sub_rxn + if test2 not in edge_list: + edge_list.append(test2) + g.add_edge(Edge( + g.get_node(text_type(sub_rxn)), + g.get_node(text_type(c2)), + {'dir': direction, + 'style': new_style_flux_dict[sub_rxn][0], + 'penwidth': new_style_flux_dict[sub_rxn][1]})) + + else: + test1 = c1, new_rlist + test2 = c2, new_rlist + sub_rxn = list(new_rlist.split(',')) + + style_list = set(new_style_flux_dict[rxn][0] for rxn in + sub_rxn) + style = style_list.pop() if len(set(style_list)) == 1 \ + else 'solid' + + flux = sum([new_style_flux_dict[rxn][1] for rxn in + sub_rxn], 0) if analysis else 0 + flux = max(min(10, flux), 1) + + if test1 not in edge_list: + edge_list.append(test1) + g.add_edge(Edge( + g.get_node(text_type(c1)), + g.get_node(text_type(new_rlist)), + {'dir': direction, 'style': style, + 'penwidth': flux})) + + if test2 not in edge_list: + edge_list.append(test2) + g.add_edge(Edge( + g.get_node(text_type(new_rlist)), + g.get_node(text_type(c2)), + {'dir': direction, 'style': style, + 'penwidth': flux})) + return g + + g = add_graph_nodes(g, cpairs_dict, method, new_id_mapping, + args_combine, model_compound_entries) + g = add_edges(g, cpairs_dict, method, args_combine, new_style_flux_dict, + analysis) + return g + + +def make_compound_graph(network_dictionary): + g = Graph() + compound_nodes = [] + edge_list = [] + for reaction, (cpair_list, dir) in iteritems(network_dictionary): + for (c1, c2) in cpair_list: + if c1 not in compound_nodes: + g.add_node(Node({'id': text_type(c1), 'entry': c1})) + compound_nodes.append(c1) + if c2 not in compound_nodes: + g.add_node(Node({'id': text_type(c2), 'entry': c2})) + compound_nodes.append(c2) + cpair_sorted = sorted([c1.name, c2.name]) + edge = Edge(g.get_node(text_type(c1)), + g.get_node(text_type(c2)), + props={'id': '{}_{}_{}'.format( + cpair_sorted[0], cpair_sorted[1], + dir_value(dir)), 'dir': dir_value(dir)}) + if edge.props['id'] not in edge_list: + g.add_edge(edge) + edge_list.append(edge.props['id']) + return g + + +def dir_value(direction): + """""" Assign value to different reaction directions"""""" + if direction == Direction.Forward: + return 'forward' + elif direction == Direction.Reverse: + return 'back' + else: + return 'both' +","Python" +"Metabolic","zhanglab/psamm","psamm/metabolicmodel.py",".py","22174","595","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Representation of metabolic network models."""""" + +from __future__ import unicode_literals + +from collections.abc import Mapping + +from .database import MetabolicDatabase, StoichiometricMatrixView +from .reaction import Reaction, Direction +from .util import create_unique_id + + +def create_exchange_id(existing_ids, compound): + """"""Create unique ID for exchange of compound."""""" + return create_unique_id(u'EX_{}'.format(compound), existing_ids) + + +def create_transport_id(existing_ids, compound_1, compound_2): + """"""Create unique ID for transport reaction of compounds."""""" + return create_unique_id( + u'TP_{}_{}'.format(compound_1, compound_2), existing_ids) + + +class FluxBounds(object): + """"""Represents lower and upper bounds of flux as a mutable object + + This object is used internally in the model representation. Changing + the state of the object will change the underlying model parameters. + Deleting a value will reset that value to the defaults. + """""" + + def __init__(self, model, reaction): + self._model = model + self._reaction = reaction + + def __iter__(self): + '''Iterator over lower and upper value''' + yield self.lower + yield self.upper + + def _assign_lower(self, value): + self._model._limits_lower[self._reaction] = value + + def _assign_upper(self, value): + self._model._limits_upper[self._reaction] = value + + def _assign_both(self, lower, upper): + self._assign_lower(lower) + self._assign_upper(upper) + + def _check_bounds(self, lower, upper): + if lower > upper: + raise ValueError('Lower bound larger than upper bound') + + @property + def lower(self): + '''Lower bound''' + try: + return self._model._limits_lower[self._reaction] + except KeyError: + if self._model.is_reversible(self._reaction): + return -self._model._v_max + else: + return 0 + + @lower.setter + def lower(self, value): + self._check_bounds(value, self.upper) + self._assign_lower(value) + + @lower.deleter + def lower(self): + self._model._limits_lower.pop(self._reaction, None) + + @property + def upper(self): + '''Upper bound''' + try: + return self._model._limits_upper[self._reaction] + except KeyError: + return self._model._v_max + + @upper.setter + def upper(self, value): + self._check_bounds(self.lower, value) + self._assign_upper(value) + + @upper.deleter + def upper(self): + self._model._limits_upper.pop(self._reaction, None) + + @property + def bounds(self): + '''Bounds as a tuple''' + return self.lower, self.upper + + @bounds.setter + def bounds(self, value): + lower, upper = value + self._check_bounds(lower, upper) + self._assign_both(lower, upper) + + @bounds.deleter + def bounds(self): + del self.lower + del self.upper + + def __eq__(self, other): + """"""Equality test"""""" + return (isinstance(other, FluxBounds) and + self.lower == other.lower and + self.upper == other.upper) + + def __ne__(self, other): + """"""Inequality test"""""" + return not self == other + + def __repr__(self): + return u'{}({!r}, {!r})'.format( + self.__class__.__name__, self.lower, self.upper) + + +class LimitsView(Mapping): + """"""Provides a view of the flux bounds defined in the model + + This object is used internally in MetabolicModel to + expose a dictonary view of the FluxBounds associated + with the model reactions. + """""" + + def __init__(self, model): + super(LimitsView, self).__init__() + self._model = model + + def _create_bounds(self, reaction): + return FluxBounds(self._model, reaction) + + def __getitem__(self, key): + if not self._model.has_reaction(key): + raise KeyError(key) + return self._create_bounds(key) + + def __iter__(self): + return self._model.reactions + + def __len__(self): + return sum(1 for _ in self._model.reactions) + + +class MetabolicModel(MetabolicDatabase): + """"""Represents a metabolic model containing a set of reactions + + The model contains a list of reactions referencing the reactions + in the associated database. + """""" + + def __init__(self, database, v_max=1000): + self._database = database + self._limits_lower = {} + self._limits_upper = {} + + self._reaction_set = set() + self._compound_set = set() + + self._v_max = v_max + + @property + def database(self): + return self._database + + @property + def reactions(self): + return iter(self._reaction_set) + + @property + def compounds(self): + return iter(self._compound_set) + + @property + def compartments(self): + compartment_set = set() + for compound in self.compounds: + if compound.compartment not in compartment_set: + compartment_set.add(compound.compartment) + yield compound.compartment + + def has_reaction(self, reaction_id): + return reaction_id in self._reaction_set + + def has_compound(self, compound_id): + return compound_id in [str(i) for i in self._compound_set] + + def get_reaction(self, reaction_id): + if reaction_id not in self._reaction_set: + raise ValueError(u'Reaction not in model: {}'.format(reaction_id)) + return self._database.get_reaction(reaction_id) + + def get_reaction_values(self, reaction_id): + """"""Return stoichiometric values of reaction as a dictionary"""""" + if reaction_id not in self._reaction_set: + raise ValueError(u'Unknown reaction: {}'.format(repr(reaction_id))) + return self._database.get_reaction_values(reaction_id) + + def get_compound_reactions(self, compound_id): + """"""Iterate over all reaction ids the includes the given compound"""""" + if compound_id not in self._compound_set: + raise ValueError(u'Compound not in model: {}'.format(compound_id)) + + for reaction_id in self._database.get_compound_reactions(compound_id): + if reaction_id in self._reaction_set: + yield reaction_id + + def is_reversible(self, reaction_id): + """"""Whether the given reaction is reversible"""""" + if reaction_id not in self._reaction_set: + raise ValueError(u'Reaction not in model: {}'.format(reaction_id)) + return self._database.is_reversible(reaction_id) + + def is_exchange(self, reaction_id): + """"""Whether the given reaction is an exchange reaction."""""" + reaction = self.get_reaction(reaction_id) + return (len(reaction.left) == 0) != (len(reaction.right) == 0) + + @property + def limits(self): + return LimitsView(self) + + def add_reaction(self, reaction_id): + """"""Add reaction to model"""""" + + if reaction_id in self._reaction_set: + return + + reaction = self._database.get_reaction(reaction_id) + self._reaction_set.add(reaction_id) + for compound, _ in reaction.compounds: + self._compound_set.add(compound) + + def remove_reaction(self, reaction): + """"""Remove reaction from model"""""" + + if reaction not in self._reaction_set: + return + + self._reaction_set.remove(reaction) + self._limits_lower.pop(reaction, None) + self._limits_upper.pop(reaction, None) + + # Remove compound from compound_set if it is not referenced + # by any other reactions in the model. + for compound, value in self._database.get_reaction_values(reaction): + reactions = frozenset( + self._database.get_compound_reactions(compound)) + if all(other_reaction not in self._reaction_set + for other_reaction in reactions): + self._compound_set.remove(compound) + + def copy(self): + """"""Return copy of model"""""" + + model = self.__class__(self._database) + model._limits_lower = dict(self._limits_lower) + model._limits_upper = dict(self._limits_upper) + model._reaction_set = set(self._reaction_set) + model._compound_set = set(self._compound_set) + return model + + @classmethod + def load_model(cls, database, reaction_iter=None, exchange=None, + limits=None, v_max=None): + """"""Get model from reaction name iterator. + + The model will contain all reactions of the iterator. + """""" + + model_args = {} + if v_max is not None: + model_args['v_max'] = v_max + + model = cls(database, **model_args) + if reaction_iter is None: + reaction_iter = iter(database.reactions) + for reaction_id in reaction_iter: + model.add_reaction(reaction_id) + + # Apply reaction limits + if limits is not None: + for reaction_id, lower, upper in limits: + if lower is not None: + model.limits[reaction_id].lower = lower + if upper is not None: + model.limits[reaction_id].upper = upper + + # TODO: Currently we just create a new exchange reaction in the + # database and add it to the model. Ideally, we should not modify + # the database. The exchange reaction could be created on the + # fly when required. + if exchange is not None: + for compound, reaction_id, lower, upper in exchange: + # Create exchange reaction + if reaction_id is None: + reaction_id = create_exchange_id( + model.database.reactions, compound) + model.database.set_reaction( + reaction_id, Reaction(Direction.Both, {compound: -1})) + model.add_reaction(reaction_id) + if lower is not None: + model.limits[reaction_id].lower = lower + if upper is not None: + model.limits[reaction_id].upper = upper + + return model + + def make_irreversible(self, gene_dict={}, exclude_list=[], lumped_rxns={}, + all_reversible=False): + """"""Creates a new metabolic models with only irreversible reactions. + + This function will find every reversible reaction in the + model and split it into two reactions with the + {rxnid}_forward or {rxnid}_reverse as the IDs. + + Args: + self: A metabolicmodel object + gene_dict: A dictionary stores reaction ids as keys and + corresponding gene association as values, it's + required only in GIMME function + exclude_list: list of reactions to exclude in TMFA simulation + all_reversible: if True make all reactions in model reversible. + + Values: + mm_irrev: A new metabolic model with only irreversible reactions + gene_dict_reversible: A dictionary mapping irreversible reaction + ids to gene associations, used only + in GIMME function + split_rxns: A list of splitted reactions, each element is a tuple + of ({rxnid}_forward, {rxnid}_reverse) + """""" + split_reversible = set() + mm_irrev = self.copy() + reversible_gene_dict = {} + new_lump_rxn_dict = {} + for rxn in self.reactions: + upper = self.limits[rxn].upper + lower = self.limits[rxn].lower + mm_irrev.limits[rxn].upper = upper + mm_irrev.limits[rxn].lower = lower + + reaction = mm_irrev.get_reaction(rxn) + if rxn not in exclude_list: + r = Reaction(Direction.Forward, reaction.left, reaction.right) + r2 = Reaction(Direction.Forward, reaction.right, reaction.left) + r_id = u'{}_forward'.format(rxn) + r2_id = u'{}_reverse'.format(rxn) + if reaction.direction == Direction.Forward: + if all_reversible is False: + reversible_gene_dict[rxn] = gene_dict.get(rxn) + continue + else: + mm_irrev.remove_reaction(rxn) + mm_irrev.database.set_reaction(r_id, r) + mm_irrev.database.set_reaction(r2_id, r2) + mm_irrev.add_reaction(r_id) + mm_irrev.add_reaction(r2_id) + split_reversible.add((r_id, r2_id)) + reversible_gene_dict[r_id] = gene_dict.get(rxn) + reversible_gene_dict[r2_id] = gene_dict.get(rxn) + elif reaction.direction == Direction.Both: + mm_irrev.remove_reaction(rxn) + mm_irrev.database.set_reaction(r_id, r) + mm_irrev.database.set_reaction(r2_id, r2) + mm_irrev.add_reaction(r_id) + mm_irrev.add_reaction(r2_id) + split_reversible.add((r_id, r2_id)) + reversible_gene_dict[r_id] = gene_dict.get(rxn) + reversible_gene_dict[r2_id] = gene_dict.get(rxn) + if lower >= 0: + mm_irrev.limits[r_id].upper = upper + mm_irrev.limits[r_id].lower = lower + mm_irrev.limits[r2_id].upper = 0 + mm_irrev.limits[r2_id].lower = 0 + elif upper <= 0: + mm_irrev.limits[r_id].upper = 0 + mm_irrev.limits[r_id].lower = 0 + mm_irrev.limits[r2_id].upper = - lower + mm_irrev.limits[r2_id].lower = - upper + else: + mm_irrev.limits[r_id].upper = upper + mm_irrev.limits[r_id].lower = 0 + mm_irrev.limits[r2_id].upper = - lower + mm_irrev.limits[r2_id].lower = 0 + + elif rxn in lumped_rxns.keys(): + final_sub_rxn_list = [] + sub = lumped_rxns[rxn] + check = 0 + for (x, y) in sub: + rn = mm_irrev.get_reaction(x) + if rn.direction != Direction.Both: + check += 1 + if reaction.direction == Direction.Forward or check != 0: + mm_irrev.limits[rxn].upper = 0 + mm_irrev.limits[rxn].lower = 0 + sub_rxn_list = lumped_rxns[rxn] + for entry in sub_rxn_list: + (subrxn, dir) = entry + final_sub_rxn_list.append(subrxn) + new_lump_rxn_dict[rxn] = final_sub_rxn_list + elif reaction.direction == Direction.Both: + # split the lump reaction itself + r = Reaction(Direction.Forward, reaction.left, + reaction.right) + r2 = Reaction(Direction.Forward, reaction.right, + reaction.left) + r_id = u'{}_forward'.format(rxn) + r2_id = u'{}_reverse'.format(rxn) + mm_irrev.remove_reaction(rxn) + mm_irrev.database.set_reaction(r_id, r) + mm_irrev.database.set_reaction(r2_id, r2) + mm_irrev.add_reaction(r_id) + mm_irrev.add_reaction(r2_id) + split_reversible.add((r_id, r2_id)) + + sub_rxn_list = lumped_rxns[rxn] + for_sub_rxn_list = [] + rev_sub_rxn_list = [] + mm_irrev.limits[r_id].upper = 0 + mm_irrev.limits[r_id].lower = 0 + mm_irrev.limits[r2_id].upper = 0 + mm_irrev.limits[r2_id].lower = 0 + for entry in sub_rxn_list: + (subrxn, dir) = entry + dir = int(dir) + # subreaction = mm.get_reaction(subrxn) + subreaction = self.get_reaction(subrxn) + sub_r1 = Reaction(Direction.Forward, + subreaction.left, subreaction.right) + sub_r1_id = u'{}_forward'.format(subrxn) + sub_r2 = Reaction(Direction.Forward, + subreaction.right, subreaction.left) + sub_r2_id = u'{}_reverse'.format(subrxn) + + split_reversible.add((sub_r1_id, sub_r2_id)) + if dir == 1: + for_sub_rxn_list.append(sub_r1_id) + rev_sub_rxn_list.append(sub_r2_id) + mm_irrev.database.set_reaction(sub_r1_id, sub_r1) + mm_irrev.add_reaction(sub_r1_id) + mm_irrev.database.set_reaction(sub_r2_id, sub_r2) + mm_irrev.add_reaction(sub_r2_id) + elif dir == -1: + for_sub_rxn_list.append(sub_r2_id) + rev_sub_rxn_list.append(sub_r1_id) + mm_irrev.database.set_reaction(sub_r1_id, sub_r1) + mm_irrev.add_reaction(sub_r1_id) + mm_irrev.database.set_reaction(sub_r2_id, sub_r2) + mm_irrev.add_reaction(sub_r2_id) + mm_irrev.limits[sub_r1_id].lower = 0 + mm_irrev.limits[sub_r1_id].upper = 100 + mm_irrev.limits[sub_r2_id].lower = 0 + mm_irrev.limits[sub_r2_id].upper = 100 + new_lump_rxn_dict[r_id] = for_sub_rxn_list + new_lump_rxn_dict[r2_id] = rev_sub_rxn_list + + return \ + mm_irrev, reversible_gene_dict, split_reversible, new_lump_rxn_dict + + +class FlipableFluxBounds(FluxBounds): + """"""FluxBounds object for a FlipableModelView. + + This object is used internally in the FlipableModelView to represent + the bounds of flux on a reaction that can be flipped. + """""" + + def __init__(self, view, reaction): + super(FlipableFluxBounds, self).__init__(view._model, reaction) + self._view = view + + def _assign_lower(self, value): + if self._reaction in self._view._flipped: + super(FlipableFluxBounds, self)._assign_upper(-value) + else: + super(FlipableFluxBounds, self)._assign_lower(value) + + def _assign_upper(self, value): + if self._reaction in self._view._flipped: + super(FlipableFluxBounds, self)._assign_lower(-value) + else: + super(FlipableFluxBounds, self)._assign_upper(value) + + @property + def lower(self): + """"""Lower bound"""""" + if self._reaction in self._view._flipped: + return -super(FlipableFluxBounds, self).upper + return super(FlipableFluxBounds, self).lower + + @property + def upper(self): + """"""Upper bound"""""" + if self._reaction in self._view._flipped: + return -super(FlipableFluxBounds, self).lower + return super(FlipableFluxBounds, self).upper + + +class FlipableStoichiometricMatrixView(StoichiometricMatrixView): + """"""Provides a matrix view that flips with the flipable model view. + + This object is used internally in FlipableModelView to + expose a matrix view that negates the stoichiometric + values of flipped reactions. + """""" + + def __init__(self, view): + super(FlipableStoichiometricMatrixView, self).__init__(view._model) + self._view = view + + def _value_mul(self, reaction): + return -1 if reaction in self._view._flipped else 1 + + def __getitem__(self, key): + if len(key) != 2: + raise KeyError(key) + compound, reaction = key + orig_value = ( + super(FlipableStoichiometricMatrixView, self).__getitem__(key)) + return self._value_mul(reaction) * orig_value + + +class FlipableLimitsView(LimitsView): + """"""Provides a limits view that flips with the flipable model view. + + This object is used internally in FlipableModelView to + expose a limits view that flips the bounds of all flipped + reactions. + """""" + + def __init__(self, view): + super(FlipableLimitsView, self).__init__(view._model) + self._view = view + + def _create_bounds(self, reaction): + return FlipableFluxBounds(self._view, reaction) + + +class FlipableModelView(object): + """"""Proxy wrapper of model objects allowing a flipped set of reactions. + + The proxy will forward all properties normally except + that flipped reactions will appear to have stoichiometric + values negated in the matrix property, and have bounds in + the limits property flipped. This view is needed for + some algorithms. + """""" + + def __init__(self, model, flipped=set()): + self._model = model + self._flipped = set(flipped) + + @property + def matrix(self): + return FlipableStoichiometricMatrixView(self) + + @property + def limits(self): + return FlipableLimitsView(self) + + def flip(self, subset): + self._flipped ^= subset + + def __getattr__(self, name): + return getattr(self._model, name) + + +if __name__ == '__main__': + import doctest + doctest.testmod() +","Python" +"Metabolic","zhanglab/psamm","psamm/balancecheck.py",".py","3910","119","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2016 Jon Lund Steffensen +# Copyright 2016 Chao Liu +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import operator +import logging + +from six.moves import reduce + +from .formula import Formula, ParseError + +logger = logging.getLogger(__name__) + + +def reaction_charge(reaction, compound_charge): + """"""Calculate the overall charge for the specified reaction. + + Args: + reaction: :class:`psamm.reaction.Reaction`. + compound_charge: a map from each compound to charge values. + """""" + + charge_sum = 0.0 + for compound, value in reaction.compounds: + charge = compound_charge.get(compound.name, float('nan')) + charge_sum += charge * float(value) + return charge_sum + + +def charge_balance(model): + """"""Calculate the overall charge for all reactions in the model. + + Yield (reaction, charge) pairs. + + Args: + model: :class:`psamm.datasource.native.NativeModel`. + """""" + + compound_charge = {} + for compound in model.compounds: + if compound.charge is not None: + compound_charge[compound.id] = compound.charge + + for reaction in model.reactions: + charge = reaction_charge(reaction.equation, compound_charge) + yield reaction, charge + + +def reaction_formula(reaction, compound_formula): + """"""Calculate formula compositions for both sides of the specified reaction. + + If the compounds in the reaction all have formula, then calculate and + return the chemical compositions for both sides, otherwise return `None`. + + Args: + reaction: :class:`psamm.reaction.Reaction`. + compound_formula: a map from compound id to formula. + """""" + + def multiply_formula(compound_list): + for compound, count in compound_list: + yield count * compound_formula[compound.name] + + for compound, _ in reaction.compounds: + if compound.name not in compound_formula: + return None + else: + left_form = reduce( + operator.or_, multiply_formula(reaction.left), Formula()) + right_form = reduce( + operator.or_, multiply_formula(reaction.right), Formula()) + return left_form, right_form + + +def formula_balance(model): + """"""Calculate formula compositions for each reaction. + + Call :func:`reaction_formula` for each reaction. + Yield (reaction, result) pairs, where result has two formula compositions + or `None`. + + Args: + model: :class:`psamm.datasource.native.NativeModel`. + """""" + + # Mapping from compound id to formula + compound_formula = {} + for compound in model.compounds: + if compound.formula is not None: + try: + f = Formula.parse(compound.formula).flattened() + compound_formula[compound.id] = f + except ParseError as e: + msg = 'Error parsing formula for compound {}:\n{}\n{}'.format( + compound.id, e, compound.formula) + if e.indicator is not None: + msg += '\n{}'.format(e.indicator) + logger.warning(msg) + + for reaction in model.reactions: + yield reaction, reaction_formula(reaction.equation, compound_formula) +","Python" +"Metabolic","zhanglab/psamm","psamm/translate_id.py",".py","8741","211","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2018-2020 Jing Wang + +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from builtins import open +from builtins import super +import csv +import logging +from psamm.datasource.native import NativeModel +from psamm.importer import write_yaml_model +from psamm.util import mkdir_p +from future import standard_library +standard_library.install_aliases() # noqa + + +def read_mapping(mapping): + with open(mapping) as mapping_file: + mapping_id = {} + for row in csv.reader(mapping_file, delimiter='\t'): + if row[1] == '': + continue + else: + mapping_id[row[0]] = row[1] + return(mapping_id) + + +def translate_id(id, mapping): + if id not in list(mapping): + return id + return mapping[id] + + +class TranslatedModel(NativeModel): + """"""A :class:`NativeModel` with translated ids based on reference model. + + The compound_map, reaction_map and compartment_map are three `dict` + that use original id as key and new id as value. + Use :meth:`.write_model` to output yaml files. + """""" + + def __init__(self, ref_model, + compound_map, reaction_map, compartment_map=None): + super().__init__() + self._cpd_mapping_id = compound_map + self._rxn_mapping_id = reaction_map + if compartment_map is None: + self._compartment_mapping_id = dict() + else: + self._compartment_mapping_id = compartment_map + + # initial a logger + self._logger = logging.getLogger(__name__) + + # inherit properties + self._properties = ref_model._properties + self.version_string = 'model mapped from: %s' % self.version_string + self.biomass_reaction = translate_id( + ref_model.biomass_reaction, self.rxn_mapping_id) + + # translate ids + self._translate_compartment(ref_model) + self._translate_compounds(ref_model) + self._translate_reactions(ref_model) + self._translate_exchange(ref_model) + self._translate_limits(ref_model) + + @property + def compartment_mapping_id(self): + return self._compartment_mapping_id + + @property + def cpd_mapping_id(self): + return self._cpd_mapping_id + + @property + def rxn_mapping_id(self): + return self._rxn_mapping_id + + def _translate_compartment(self, ref_model): + """"""Translate compartment ids."""""" + # change compartments + for comp in ref_model.compartments: + new_id = translate_id(comp.id, self.compartment_mapping_id) + comp.properties['id'] = new_id + comp.properties['original_id'] = [comp.id] + comp = comp.__class__(comp.properties, filemark=comp.filemark) + self.compartments.add_entry(comp) + # change comparment_boundaries + for c1, c2 in ref_model.compartment_boundaries: + c1 = translate_id(c1, self.compartment_mapping_id) + c2 = translate_id(c2, self.compartment_mapping_id) + self.compartment_boundaries.add((c1, c2)) + self.extracellular_compartment = translate_id( + ref_model.extracellular_compartment, self.compartment_mapping_id) + + def _translate_compounds(self, ref_model): + """"""Translate compound ids and corresponding exchange reactions."""""" + for cpd in ref_model.compounds: + new_id = translate_id(cpd.id, self.cpd_mapping_id) + if new_id not in self.compounds: # do not duplicate compounds + cpd.properties['id'] = new_id + cpd.properties['original_id'] = [cpd.id] + # refresh with changed properties + cpd = cpd.__class__(cpd.properties, filemark=cpd.filemark) + self.compounds.add_entry(cpd) + else: + self.compounds[new_id].properties['original_id'].append(cpd.id) + self._logger.warning( + 'Multiple compounds: %s will be translated to %s', + self.compounds[new_id].properties['original_id'], + new_id) + + def _compound_trans(self, id): + """"""Make a directly callable method for compound.translate()"""""" + return translate_id(id, self.cpd_mapping_id) + + def _translate_reactions(self, ref_model): + """"""Translate reaction ids and equations."""""" + + for rxn in ref_model.reactions: + new_id = translate_id(rxn.id, self.rxn_mapping_id) + if new_id not in self.reactions: # do not duplicate reactions + rxn.properties['id'] = new_id + rxn.properties['original_id'] = rxn.id + compounds = list() + for cpd, v in rxn.equation.compounds: + cpd = cpd.translate(self._compound_trans) + cpd = cpd.in_compartment( + translate_id(cpd.compartment, + self.compartment_mapping_id) + ) + compounds.append((cpd, v)) + rxn.equation = rxn.equation.__class__( + rxn.equation.direction, compounds + ) + # test whether the same compound occurs at both sides + compound_left = set((c for c, _ in rxn.equation.left)) + compound_right = set((c for c, _ in rxn.equation.right)) + compound_common = compound_left.intersection(compound_right) + if len(compound_common) > 0: + self._logger.error(( + 'Reaction %s will have ' + 'the same compounds %s on both sides: %s'), + rxn.id, compound_common, rxn.equation) + # refresh with changed properties + rxn = rxn.__class__(rxn.properties, filemark=rxn.filemark) + self.reactions.add_entry(rxn) + else: + self._logger.error( + ('Reaction %s is omitted because its new id %s has been ' + 'assigned to %s'), + rxn.id, + new_id, + self.reactions[new_id].properties['original_id']) + + def _translate_exchange(self, ref_model): + """"""Translate exchange reactions."""""" + # cpd is :class:`Compound(name, compartment)` + for cpd in ref_model.exchange: + new_cpd = cpd.translate(self._compound_trans) + new_cpd = new_cpd.in_compartment(self.extracellular_compartment) + if new_cpd not in self.exchange: # do not duplicate exchange + lower, upper = ref_model.exchange[cpd][2:] + name = 'EX_%s(%s)' % (new_cpd.name, + self.extracellular_compartment) + self.exchange[new_cpd] = (new_cpd, name, lower, upper) + else: + self._logger.error( + ('Exchange reaction of compound %s is omitted because ' + 'its new id %s has been assigned multiple compounds: %s'), + cpd.name, + new_cpd.name, + self.compounds[new_cpd.name].properties['original_id']) + + def _translate_limits(self, ref_model): + """"""""Translate reaction limits."""""" + for rxn in ref_model.limits: + new_rxn = translate_id(rxn, self.rxn_mapping_id) + if new_rxn not in self.limits: # do not duplicate limits + lower, upper = ref_model.limits[rxn][1:] + self.limits[new_rxn] = (new_rxn, lower, upper) + else: + self._logger.error( + ('Limits of reaction %s is omitted because its new id %s ' + 'has been assigned to %s'), + rxn, + new_rxn, + self.reactions[new_rxn].properties['original_id']) + + def write_model(self, dest, **kwargs): + """"""Output model into YAML files."""""" + mkdir_p(dest) + write_yaml_model(self, dest, **kwargs) +","Python" +"Metabolic","zhanglab/psamm","psamm/importer.py",".py","30622","825","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Entry points and functionality for importing models. + +This module contains entry points for the psamm-import programs and +functionality to assist in importing external file formats, converting +them into proper native models and writing those models to files. +"""""" + +from __future__ import print_function, unicode_literals + +import sys +import os +import argparse +import logging +import math +import re +import json +import codecs +from itertools import product +from collections import OrderedDict, Counter +from decimal import Decimal + +import yaml +import pkg_resources +from six import iteritems, itervalues, text_type +from six.moves.urllib.request import urlopen +from six.moves.urllib.parse import quote as url_quote + +from .datasource.native import ModelWriter +from .datasource.reaction import (parse_reaction, + ParseError as ReactionParseError) +from .datasource.entry import DictCompartmentEntry +from .datasource import sbml +from .expression import boolean +from . import formula + +from .util import mkdir_p + +# Threshold for putting reactions into subsystem files +_MAX_REACTION_COUNT = 3 + +# Threshold for converting reactions into dictionary representation. +_MAX_REACTION_LENGTH = 10 + +logger = logging.getLogger(__name__) + + +class ImportError(Exception): + """"""Exception used to signal a general import error."""""" + + +class ModelLoadError(ImportError): + """"""Exception used to signal an error loading the model files."""""" + + +class ParseError(ImportError): + """"""Exception used to signal an error parsing the model files."""""" + + +class Importer(object): + """"""Base importer class."""""" + + def _try_parse_formula(self, compound_id, s): + """"""Try to parse the given compound formula string. + + Logs a warning if the formula could not be parsed. + """""" + s = s.strip() + if s == '': + return None + + try: + # Do not return the parsed formula. For now it is better to keep + # the original formula string unchanged in all cases. + formula.Formula.parse(s) + except formula.ParseError: + logger.warning('Unable to parse compound formula {}: {}'.format( + compound_id, s)) + + return s + + def _try_parse_reaction(self, reaction_id, s, + parser=parse_reaction, **kwargs): + """"""Try to parse the given reaction equation string. + + Returns the parsed Reaction object, or raises an error if the reaction + could not be parsed. + """""" + try: + return parser(s, **kwargs) + except ReactionParseError as e: + if e.indicator is not None: + logger.error('{}\n{}\n{}'.format( + str(e), s, e.indicator)) + raise ParseError('Unable to parse reaction {}: {}'.format( + reaction_id, s)) + + def _try_parse_gene_association(self, reaction_id, s): + """"""Try to parse the given gene association rule. + + Logs a warning if the association rule could not be parsed and returns + the original string. Otherwise, returns the boolean.Expression object. + """""" + s = s.strip() + if s == '': + return None + + try: + return boolean.Expression(s) + except boolean.ParseError as e: + msg = 'Failed to parse gene association for {}: {}'.format( + reaction_id, text_type(e)) + if e.indicator is not None: + msg += '\n{}\n{}'.format(s, e.indicator) + logger.warning(msg) + + return s + + +# Define custom dict representers for YAML +# This allows reading/writing Python OrderedDicts in the correct order. +# See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts # noqa +def _dict_representer(dumper, data): + return dumper.represent_dict(iteritems(data)) + + +def _dict_constructor(loader, node): + return OrderedDict(loader.construct_pairs(node)) + + +def _set_representer(dumper, data): + return dumper.represent_list(iter(data)) + + +def _boolean_expression_representer(dumper, data): + return dumper.represent_unicode(text_type(data)) + + +def _decimal_representer(dumper, data): + # Code from float_representer in PyYAML. + if data % 1 == 0: + return dumper.represent_int(int(data)) + elif math.isnan(data): + value = '.nan' + elif data == float('inf'): + value = '.inf' + elif data == float('-inf'): + value = '-.inf' + else: + value = text_type(data).lower() + if '.' not in value and 'e' in value: + value = value.replace('e', '.0e', 1) + return dumper.represent_scalar('tag:yaml.org,2002:float', value) + + +def get_default_compartment(model): + """"""Return what the default compartment should be set to. + + If some compounds have no compartment, unique compartment + name is returned to avoid collisions. + """""" + default_compartment = 'c' + default_key = set() + for reaction in model.reactions: + equation = reaction.equation + if equation is None: + continue + + for compound, _ in equation.compounds: + default_key.add(compound.compartment) + + if None in default_key and default_compartment in default_key: + suffix = 1 + while True: + new_key = '{}_{}'.format(default_compartment, suffix) + if new_key not in default_key: + default_compartment = new_key + break + suffix += 1 + + if None in default_key: + logger.warning( + 'Compound(s) found without compartment, default' + ' compartment is set to {}.'.format(default_compartment)) + return default_compartment + + +def detect_best_flux_limit(model): + """"""Detect the best default flux limit to use for model output. + + The default flux limit does not change the model but selecting a good + value reduced the amount of output produced and reduces clutter in the + output files. + """""" + flux_limit_count = Counter() + + for reaction in model.reactions: + if reaction.id not in model.limits: + continue + + equation = reaction.properties['equation'] + if equation is None: + continue + + _, lower, upper = model.limits[reaction.id] + if upper is not None and upper > 0 and equation.direction.forward: + flux_limit_count[upper] += 1 + if lower is not None and -lower > 0 and equation.direction.reverse: + flux_limit_count[-lower] += 1 + + if len(flux_limit_count) == 0: + return None + + best_flux_limit, _ = flux_limit_count.most_common(1)[0] + return best_flux_limit + + +def reactions_to_files(model, dest, writer, split_subsystem): + """"""Turn the reaction subsystems into their own files. + + If a subsystem has a number of reactions over the threshold, it gets its + own YAML file. All other reactions, those that don't have a subsystem or + are in a subsystem that falls below the threshold, get added to a common + reaction file. + + Args: + model: :class:`psamm_import.model.MetabolicModel`. + dest: output path for model files. + writer: :class:`psamm.datasource.native.ModelWriter`. + split_subsystem: Divide reactions into multiple files by subsystem. + """""" + def safe_file_name(origin_name): + safe_name = re.sub( + r'\W+', '_', origin_name, flags=re.UNICODE) + safe_name = re.sub( + r'_+', '_', safe_name.lower(), flags=re.UNICODE) + safe_name = safe_name.strip('_') + return safe_name + + common_reactions = [] + reaction_files = [] + if not split_subsystem: + common_reactions = sorted(model.reactions, key=lambda r: r.id) + if len(common_reactions) > 0: + reaction_file = 'reactions.yaml' + with open(os.path.join(dest, reaction_file), 'w') as f: + writer.write_reactions(f, common_reactions) + reaction_files.append(reaction_file) + else: + subsystems = {} + for reaction in sorted(model.reactions, key=lambda r: r.id): + if 'subsystem' in reaction.properties: + subsystem_file = safe_file_name( + reaction.properties['subsystem']) + subsystems.setdefault(subsystem_file, []).append(reaction) + else: + common_reactions.append(reaction) + + subsystem_folder = 'reactions' + sub_existance = False + for subsystem_file, reactions in iteritems(subsystems): + if len(reactions) < _MAX_REACTION_COUNT: + for reaction in reactions: + common_reactions.append(reaction) + else: + if len(reactions) > 0: + mkdir_p(os.path.join(dest, subsystem_folder)) + subsystem_file = os.path.join( + subsystem_folder, '{}.yaml'.format(subsystem_file)) + + with open(os.path.join(dest, subsystem_file), 'w') as f: + writer.write_reactions(f, reactions) + reaction_files.append(subsystem_file) + sub_existance = True + + reaction_files.sort() + if sub_existance: + reaction_file = os.path.join( + subsystem_folder, 'other_reactions.yaml') + else: + reaction_file = 'reactions.yaml' + if len(common_reactions) > 0: + with open(os.path.join(dest, reaction_file), 'w') as f: + writer.write_reactions(f, common_reactions) + reaction_files.append(reaction_file) + + return reaction_files + + +def _get_output_limit(limit, default_limit): + """"""Return limit to output given default limit."""""" + return limit if limit != default_limit else None + + +def _generate_limit_items(lower, upper): + """"""Yield key, value pairs for limits dictionary. + + Yield pairs of key, value where key is ``lower``, ``upper`` or ``fixed``. + A key, value pair is emitted if the bounds are not None. + """""" + # Use value + 0 to convert any -0.0 to 0.0 which looks better. + if lower is not None and upper is not None and lower == upper: + yield 'fixed', upper + 0 + else: + if lower is not None: + yield 'lower', lower + 0 + if upper is not None: + yield 'upper', upper + 0 + + +def model_exchange(model): + """"""Return exchange definition as YAML dict."""""" + # Determine the default flux limits. If the value is already at the + # default it does not need to be included in the output. + lower_default, upper_default = None, None + if model.default_flux_limit is not None: + lower_default = -model.default_flux_limit + upper_default = model.default_flux_limit + + compounds = [] + for compound, reaction_id, lower, upper in sorted( + itervalues(model.exchange)): + d = OrderedDict([('id', compound.name)]) + if reaction_id is not None: + d['reaction'] = reaction_id + + lower = _get_output_limit(lower, lower_default) + upper = _get_output_limit(upper, upper_default) + d.update(_generate_limit_items(lower, upper)) + + compounds.append(d) + + return OrderedDict([('compounds', compounds)]) + + +def model_reaction_limits(model): + """"""Yield model reaction limits as YAML dicts."""""" + for reaction in sorted(model.reactions, key=lambda r: r.id): + equation = reaction.properties.get('equation') + if equation is None: + continue + + # Determine the default flux limits. If the value is already at the + # default it does not need to be included in the output. + lower_default, upper_default = None, None + if model.default_flux_limit is not None: + if equation.direction.reverse: + lower_default = -model.default_flux_limit + else: + lower_default = 0.0 + + if equation.direction.forward: + upper_default = model.default_flux_limit + else: + upper_default = 0.0 + + lower_flux, upper_flux = None, None + if reaction.id in model.limits: + _, lower, upper = model.limits[reaction.id] + lower_flux = _get_output_limit(lower, lower_default) + upper_flux = _get_output_limit(upper, upper_default) + + if lower_flux is not None or upper_flux is not None: + d = OrderedDict([('reaction', reaction.id)]) + d.update(_generate_limit_items(lower_flux, upper_flux)) + + yield d + + +def infer_compartment_entries(model): + """"""Infer compartment entries for model based on reaction compounds."""""" + compartment_ids = set() + for reaction in model.reactions: + equation = reaction.equation + if equation is None: + continue + + for compound, _ in equation.compounds: + compartment = compound.compartment + if compartment is None: + compartment = model.default_compartment + + if compartment is not None: + compartment_ids.add(compartment) + + for compartment in compartment_ids: + if compartment in model.compartments: + continue + + entry = DictCompartmentEntry(dict(id=compartment)) + model.compartments.add_entry(entry) + + +def infer_compartment_adjacency(model): + """"""Infer compartment adjacency for model based on reactions."""""" + def reaction_compartments(seq): + for compound, _ in seq: + compartment = compound.compartment + if compartment is None: + compartment = model.default_compartment + + if compartment is not None: + yield compartment + + for reaction in model.reactions: + equation = reaction.equation + if equation is None: + continue + + left = reaction_compartments(equation.left) + right = reaction_compartments(equation.right) + for c1, c2 in product(left, right): + if c1 == c2: + continue + model.compartment_boundaries.add((c1, c2)) + model.compartment_boundaries.add((c2, c1)) + + +def count_genes(model): + """"""Count the number of distinct genes in model reactions."""""" + genes = set() + for reaction in model.reactions: + if reaction.genes is None: + continue + + if isinstance(reaction.genes, boolean.Expression): + genes.update(v.symbol for v in reaction.genes.variables) + else: + gene_exp = boolean.Expression(reaction.genes) + genes.update(v.symbol for v in gene_exp.variables) + # genes.update(reaction.genes) + + return len(genes) + + +def write_yaml_model(model, dest='.', convert_exchange=True, + split_subsystem=True): + """"""Write the given NativeModel to YAML files in dest folder. + + The parameter ``convert_exchange`` indicates whether the exchange reactions + should be converted automatically to an exchange file. + """""" + yaml.SafeDumper.add_representer(OrderedDict, _dict_representer) + yaml.SafeDumper.add_representer(set, _set_representer) + yaml.SafeDumper.add_representer(frozenset, _set_representer) + yaml.SafeDumper.add_representer( + boolean.Expression, _boolean_expression_representer) + yaml.SafeDumper.add_representer(Decimal, _decimal_representer) + + yaml.SafeDumper.ignore_aliases = lambda *args: True + + yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, + _dict_constructor) + + yaml_args = {'default_flow_style': False, + 'encoding': 'utf-8', + 'allow_unicode': True, + 'width': 79} + + # The ModelWriter from PSAMM is not yet able to write the full model but + # only reactions and compounds. + writer = ModelWriter() + + with open(os.path.join(dest, 'compounds.yaml'), 'w+') as f: + writer.write_compounds(f, sorted(model.compounds, key=lambda c: c.id)) + + if model.default_flux_limit is None: + model.default_flux_limit = detect_best_flux_limit(model) + + if model.extracellular_compartment is None: + model.extracellular_compartment = ( + sbml.detect_extracellular_compartment(model)) + + if model.default_compartment is None: + model.default_compartment = get_default_compartment(model) + + if model.default_flux_limit is not None: + logger.info('Using default flux limit of {}'.format( + model.default_flux_limit)) + + if convert_exchange: + logger.info('Converting exchange reactions to exchange file') + sbml.convert_exchange_to_compounds(model) + + if len(model.compartments) == 0: + infer_compartment_entries(model) + logger.info('Inferred {} compartments: {}'.format( + len(model.compartments), + ', '.join(c.id for c in model.compartments))) + + if len(model.compartments) != 0 and len(model.compartment_boundaries) == 0: + infer_compartment_adjacency(model) + + reaction_files = reactions_to_files(model, dest, writer, split_subsystem) + + if len(model.exchange) > 0: + with open(os.path.join(dest, 'exchange.yaml'), 'w+') as f: + yaml.safe_dump(model_exchange(model), f, **yaml_args) + + reaction_limits = list(model_reaction_limits(model)) + if len(reaction_limits) > 0: + with open(os.path.join(dest, 'limits.yaml'), 'w+') as f: + yaml.safe_dump(reaction_limits, f, **yaml_args) + + model_d = OrderedDict() + if model.name is not None: + model_d['name'] = model.name + + if model.biomass_reaction is not None: + model_d['biomass'] = model.biomass_reaction + if model.default_flux_limit is not None: + model_d['default_flux_limit'] = model.default_flux_limit + if model.extracellular_compartment != 'e': + model_d['extracellular'] = model.extracellular_compartment + if model.default_compartment != 'c': + model_d['default_compartment'] = model.default_compartment + + if len(model.compartments) > 0: + adjacency = {} + for c1, c2 in model.compartment_boundaries: + adjacency.setdefault(c1, set()).add(c2) + adjacency.setdefault(c2, set()).add(c1) + + compartment_list = [] + for compartment in sorted(model.compartments, key=lambda c: c.id): + adjacent = adjacency.get(compartment.id) + if adjacent is not None and len(adjacent) == 1: + adjacent = next(iter(adjacent)) + compartment_list.append(writer.convert_compartment_entry( + compartment, adjacent)) + + model_d['compartments'] = compartment_list + + model_d['compounds'] = [{'include': 'compounds.yaml'}] + model_d['reactions'] = [] + for reaction_file in reaction_files: + model_d['reactions'].append({'include': reaction_file}) + + if len(model.exchange) > 0: + model_d['exchange'] = [{'include': 'exchange.yaml'}] + + if len(reaction_limits) > 0: + model_d['limits'] = [{'include': 'limits.yaml'}] + + with open(os.path.join(dest, 'model.yaml'), 'w+') as f: + yaml.safe_dump(model_d, f, **yaml_args) + + +def main(importer_class=None, args=None): + """"""Entry point for import program. + + If the ``args`` are provided, these should be a list of strings that will + be used instead of ``sys.argv[1:]``. This is mostly useful for testing. + """""" + parser = argparse.ArgumentParser( + description='Import from external model formats') + parser.add_argument('--source', metavar='path', default='.', + help='Source directory or file') + parser.add_argument('--dest', metavar='path', default='.', + help='Destination directory (default is ""."")') + parser.add_argument('--no-exchange', action='store_true', + help=('Disable importing exchange reactions as' + ' exchange compound file.')) + parser.add_argument('--split-subsystem', action='store_true', + help='Enable splitting reaction files by subsystem') + parser.add_argument('--merge-compounds', action='store_true', + help=('Merge identical compounds occuring in various' + ' compartments.')) + parser.add_argument('--force', action='store_true', + help='Enable overwriting model files') + parser.add_argument('--model-name', type=str, + help=('specify model name if multiple models ' + 'are stored in the .mat file')) + + if importer_class is None: + parser.add_argument( + 'format', help='Format to import (""list"" to see all)') + + args = parser.parse_args(args) + + # Set up logging for the command line interface + if 'PSAMM_DEBUG' in os.environ: + level = getattr(logging, os.environ['PSAMM_DEBUG'].upper(), None) + if level is not None: + logging.basicConfig(level=level) + else: + logging.basicConfig( + level=logging.INFO, format='%(levelname)s: %(message)s') + + if importer_class is None: + # Discover all available model importers + importers = {} + for importer_entry in pkg_resources.iter_entry_points( + 'psamm.importer'): + canonical = importer_entry.name.lower() + if canonical not in importers: + importers[canonical] = importer_entry + else: + logger.warning('Importer {} was found more than once!'.format( + importer_entry.name)) + + # Print list of importers + if args.format in ('list', 'help'): + if len(importers) == 0: + logger.error('No importers found!') + else: + importer_classes = [] + for name, entry in iteritems(importers): + importer_class = entry.load() + title = getattr(importer_class, 'title', None) + generic = getattr(importer_class, 'generic', False) + if title is not None: + importer_classes.append( + (title, generic, name, importer_class)) + + print('Generic importers:') + for title, _, name, importer_class in sorted( + c for c in importer_classes if c[1]): + print('{:<12} {}'.format(name, title)) + + print() + print('Model-specific importers:') + for title, _, name, importer_class in sorted( + c for c in importer_classes if not c[1]): + print('{:<12} {}'.format(name, title)) + sys.exit(0) + + importer_name = args.format.lower() + if importer_name not in importers: + logger.error('Importer {} not found!'.format(importer_name)) + logger.info('Use ""list"" to see available importers.') + sys.exit(-1) + + importer_class = importers[importer_name].load() + + importer = importer_class() + + try: + if importer.name == 'matlab' and args.model_name is not None: + model = importer.import_model(args.source, args.model_name) + else: + model = importer.import_model(args.source) + except ModelLoadError as e: + logger.error('Failed to load model!', exc_info=True) + importer.help() + parser.error(text_type(e)) + except ParseError as e: + logger.error('Failed to parse model!', exc_info=True) + logger.error(text_type(e)) + sys.exit(-1) + except Exception: + importer.help() + + if args.merge_compounds: + compounds_before = len(model.compounds) + sbml.merge_equivalent_compounds(model) + if len(model.compounds) < compounds_before: + logger.info( + 'Merged {} compound entries into {} entries by' + ' removing duplicates in various compartments'.format( + compounds_before, len(model.compounds))) + + print('Model: {}'.format(model.name)) + print('- Biomass reaction: {}'.format(model.biomass_reaction)) + print('- Compartments: {}'.format(len(model.compartments))) + print('- Compounds: {}'.format(len(model.compounds))) + print('- Reactions: {}'.format(len(model.reactions))) + print('- Genes: {}'.format(count_genes(model))) + + # Check if dest directory is empty. If we get an error assume that the + # directory does not exist. + dest_is_empty = False + try: + dest_is_empty = len(os.listdir(args.dest)) == 0 + except OSError: + dest_is_empty = True + + if not dest_is_empty: + if not args.force: + logger.error('Destination directory is not empty. Use --force' + ' option to proceed anyway, overwriting any existing' + ' files in {}'.format(args.dest)) + return 1 + else: + logger.warning('Destination directory is not empty, overwriting' + ' existing files in {}'.format(args.dest)) + + # Create destination directory if not exists + dest = args.dest + mkdir_p(dest) + + convert_exchange = not args.no_exchange + write_yaml_model(model, dest, convert_exchange=convert_exchange, + split_subsystem=args.split_subsystem) + + +def main_bigg(args=None, urlopen=urlopen): + """"""Entry point for BiGG import program. + + If the ``args`` are provided, these should be a list of strings that will + be used instead of ``sys.argv[1:]``. This is mostly useful for testing. + """""" + parser = argparse.ArgumentParser( + description='Import from BiGG database') + parser.add_argument('--dest', metavar='path', default='.', + help='Destination directory (default is ""."")') + parser.add_argument('--no-exchange', action='store_true', + help=('Disable importing exchange reactions as' + ' exchange compound file.')) + parser.add_argument('--split-subsystem', action='store_true', + help='Enable splitting reaction files by subsystem') + parser.add_argument('--merge-compounds', action='store_true', + help=('Merge identical compounds occuring in various' + ' compartments.')) + parser.add_argument('--force', action='store_true', + help='Enable overwriting model files') + parser.add_argument('id', help='BiGG model to import (""list"" to see all)') + + args = parser.parse_args(args) + + # Set up logging for the command line interface + if 'PSAMM_DEBUG' in os.environ: + level = getattr(logging, os.environ['PSAMM_DEBUG'].upper(), None) + if level is not None: + logging.basicConfig(level=level) + else: + logging.basicConfig( + level=logging.INFO, format='%(levelname)s: %(message)s') + + # Print list of available models + if args.id == 'list': + print('Available models:') + f = urlopen('http://bigg.ucsd.edu/api/v2/models') + doc = json.loads(f.read().decode('utf-8')) + results = doc['results'] + id_width = min(max(len(result['bigg_id']) for result in results), 16) + for result in sorted(results, key=lambda x: x.get('organism')): + print('{} {}'.format( + result.get('bigg_id').ljust(id_width), result.get('organism'))) + return 0 + + importer_entry = None + try: + importer_entry = next( + pkg_resources.iter_entry_points('psamm.importer', 'JSON')) + except StopIteration: + logger.error('Failed to locate the COBRA JSON model importer!') + sys.exit(-1) + + importer_class = importer_entry.load() + importer = importer_class() + + try: + f = urlopen( + 'http://bigg.ucsd.edu/api/v2/models/{}/download'.format( + url_quote(args.id))) + model = importer.import_model(codecs.getreader('utf-8')(f)) + except ModelLoadError as e: + logger.error('Failed to load model!', exc_info=True) + importer.help() + parser.error(text_type(e)) + except ParseError as e: + logger.error('Failed to parse model!', exc_info=True) + logger.error(text_type(e)) + sys.exit(-1) + + if args.merge_compounds: + compounds_before = len(model.compounds) + sbml.merge_equivalent_compounds(model) + if len(model.compounds) < compounds_before: + logger.info( + 'Merged {} compound entries into {} entries by' + ' removing duplicates in various compartments'.format( + compounds_before, len(model.compounds))) + + print('Model: {}'.format(model.name)) + print('- Biomass reaction: {}'.format(model.biomass_reaction)) + print('- Compartments: {}'.format(len(model.compartments))) + print('- Compounds: {}'.format(len(model.compounds))) + print('- Reactions: {}'.format(len(model.reactions))) + print('- Genes: {}'.format(count_genes(model))) + + # Check if dest directory is empty. If we get an error assume that the + # directory does not exist. + dest_is_empty = False + try: + dest_is_empty = len(os.listdir(args.dest)) == 0 + except OSError: + dest_is_empty = True + + if not dest_is_empty: + if not args.force: + logger.error('Destination directory is not empty. Use --force' + ' option to proceed anyway, overwriting any existing' + ' files in {}'.format(args.dest)) + return 1 + else: + logger.warning('Destination directory is not empty, overwriting' + ' existing files in {}'.format(args.dest)) + + # Create destination directory if not exists + dest = args.dest + mkdir_p(dest) + + convert_exchange = not args.no_exchange + write_yaml_model(model, dest, convert_exchange=convert_exchange, + split_subsystem=args.split_subsystem) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/sbmlexport.py",".py","1552","43","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import sys +import argparse + +from ..datasource import sbml +from ..command import MetabolicMixin, Command + + +class SBMLExport(MetabolicMixin, Command): + """"""Export model as SBML level 3 file."""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + 'file', type=argparse.FileType('w'), nargs='?', default=sys.stdout, + help='File path for writing the SBML file' + ' (use ""-"" for standard output)') + parser.add_argument( + '--pretty', action='store_true', + help='Format output for readability') + super(SBMLExport, cls).init_parser(parser) + + def run(self): + writer = sbml.SBMLWriter() + writer.write_model(self._args.file, self._model, self._args.pretty) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/excelexport.py",".py","7510","197","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2017 Jon Lund Steffensen + +from __future__ import unicode_literals + +import logging + +from six import text_type, itervalues, string_types +from collections import defaultdict + +from ..command import Command +from ..expression import boolean + +try: + import xlsxwriter +except ImportError: + xlsxwriter = None + +logger = logging.getLogger(__name__) + + +class ExcelExportCommand(Command): + """"""Export the metabolic model as an Excel workbook."""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + 'file', type=text_type, + help='File path for writing the Excel workbook') + + def run(self): + model = self._model + if xlsxwriter is None: + self.fail( + 'Excel export requires the XlsxWriter python module' + ' (""pip install xlsxwriter"")') + + workbook = xlsxwriter.Workbook(self._args.file) + + model_info = workbook.add_worksheet(name='Model Info') + + model_info.write(0, 0, ('Model Name: {}'.format(model.name))) + model_info.write( + 1, 0, ('Biomass Reaction: {}'.format(model.biomass_reaction))) + model_info.write( + 2, 0, ('Default Flux Limits: {}'.format(model.default_flux_limit))) + if model.version_string is not None: + model_info.write( + 3, 0, ('Version: {}'.format(model.version_string))) + + reaction_sheet = workbook.add_worksheet(name='Reactions') + + # get compound name dict + compounds_name = {} + for cpd in model.compounds: + if cpd.name: + compounds_name[cpd.id] = cpd.name + else: + compounds_name[cpd.id] = cpd.id + + property_set = set() + for reaction in model.reactions: + property_set.update(reaction.properties) + property_list = list(property_set) + property_list_sorted = sorted(property_list, + key=lambda x: (x != 'id', + x != 'equation', x)) + model_reactions = set(model.model) + for z, i in enumerate(property_list_sorted + ['in_model'] + + ['translated_equation']): + reaction_sheet.write_string(0, z, text_type(i)) + gene_rxn = defaultdict(list) + for x, i in enumerate(model.reactions): + # get translated equation + rx = i.equation + translated_equation = str(rx.translated_compounds( + lambda x: compounds_name.get(x, x))) + + for y, j in enumerate(property_list_sorted): + value = i.properties.get(j) + if value is not None: + reaction_sheet.write_string(x+1, y, text_type(value)) + reaction_sheet.write_string( + x+1, len(property_list_sorted), + text_type(i.id in model_reactions)) + reaction_sheet.write_string( + x+1, len(property_list_sorted)+1, + translated_equation) + assoc = None + if i.genes is None: + continue + elif isinstance(i.genes, string_types): + assoc = boolean.Expression(i.genes) + for j in assoc.variables: + gene_rxn[str(j)].append(i.id) + else: + variables = [boolean.Variable(g) for g in i.genes] + assoc = boolean.Expression(boolean.And(*variables)) + for j in assoc.variables: + gene_rxn[str(j)].append(i.id) + + compound_sheet = workbook.add_worksheet(name='Compounds') + + compound_set = set() + for compound in model.compounds: + compound_set.update(compound.properties) + + compound_list_sorted = sorted(compound_set, + key=lambda x: (x != 'id', + x != 'name', x)) + + metabolic_model = self._model.create_metabolic_model() + model_compounds = set(x.name for x in metabolic_model.compounds) + for z, i in enumerate(compound_list_sorted + ['in_model']): + compound_sheet.write_string(0, z, text_type(i)) + for x, i in enumerate(model.compounds): + for y, j in enumerate(compound_list_sorted): + value = i.properties.get(j) + if value is not None: + compound_sheet.write_string(x+1, y, text_type(value)) + compound_sheet.write_string( + x+1, len(compound_list_sorted), + text_type(i.id in model_compounds)) + + gene_sheet = workbook.add_worksheet(name='Genes') + gene_sheet.write_string(0, 0, 'Gene') + gene_sheet.write_string(0, 1, 'Reaction_in_model') + gene_sheet.write_string(0, 2, 'Reaction_not_in_model') + for x, i in enumerate(sorted(gene_rxn)): + gene_sheet.write_string(x+1, 0, i) + in_model = [] + not_in_model = [] + for r in gene_rxn.get(i): + if r in model_reactions: + in_model.append(r) + else: + not_in_model.append(r) + gene_sheet.write_string(x+1, 1, '#'.join(in_model)) + gene_sheet.write_string(x+1, 2, '#'.join(not_in_model)) + + exchange_sheet = workbook.add_worksheet(name='Exchange') + + exchange_sheet.write_string(0, 0, 'Compound ID') + exchange_sheet.write_string(0, 1, 'Reaction ID') + exchange_sheet.write_string(0, 2, 'Lower Limit') + exchange_sheet.write_string(0, 3, 'Upper Limit') + + default_flux = model.default_flux_limit + + for x, (compound, reaction, lower, upper) in enumerate( + itervalues(model.exchange)): + if lower is None: + lower = -default_flux + + if upper is None: + upper = default_flux + + exchange_sheet.write(x+1, 0, text_type(compound)) + exchange_sheet.write(x+1, 1, text_type(reaction)) + exchange_sheet.write(x+1, 2, text_type(lower)) + exchange_sheet.write(x+1, 3, text_type(upper)) + + limits_sheet = workbook.add_worksheet(name='Limits') + + limits_sheet.write_string(0, 0, 'Reaction ID') + limits_sheet.write_string(0, 1, 'Lower Limit') + limits_sheet.write_string(0, 2, 'Upper Limit') + + for x, limit in enumerate(itervalues(model.limits)): + reaction_id, lower, upper = limit + if lower is None: + lower = -default_flux + + if upper is None: + upper = default_flux + + limits_sheet.write(x+1, 0, reaction_id) + limits_sheet.write(x+1, 1, lower) + limits_sheet.write(x+1, 2, upper) + + workbook.close() +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/fba.py",".py","5804","170","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import time +import logging + +from ..command import (LoopRemovalMixin, ObjectiveMixin, SolverCommandMixin, + MetabolicMixin, Command) +from .. import fluxanalysis + +logger = logging.getLogger(__name__) + + +class FluxBalanceCommand(MetabolicMixin, LoopRemovalMixin, ObjectiveMixin, + SolverCommandMixin, Command): + """"""Run flux balance analysis on the model."""""" + + _supported_loop_removal = ['none', 'tfba', 'l1min'] + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--all-reactions', help='Show all reaction fluxes', + action='store_true') + parser.add_argument( + '--epsilon', type=float, + help='Threshold for non-zero reaction fluxes', default=1e-5) + super(FluxBalanceCommand, cls).init_parser(parser) + + def run(self): + """"""Run flux analysis command."""""" + + # Load compound information + def compound_name(id): + if id not in self._model.compounds: + return id + return self._model.compounds[id].properties.get('name', id) + + # Reaction genes information + def reaction_genes_string(id): + if id not in self._model.reactions: + return '' + return self._model.reactions[id].properties.get('genes', '') + + reaction = self._get_objective() + if not self._mm.has_reaction(reaction): + self.fail( + 'Specified reaction is not in model: {}'.format(reaction)) + + loop_removal = self._get_loop_removal_option() + if loop_removal == 'none': + result = self.run_fba(reaction) + elif loop_removal == 'l1min': + result = self.run_fba_minimized(reaction) + elif loop_removal == 'tfba': + result = self.run_tfba(reaction) + + optimum = None + total_reactions = 0 + nonzero_reactions = 0 + for reaction_id, flux in sorted(result): + total_reactions += 1 + if abs(flux) > self._args.epsilon: + nonzero_reactions += 1 + + if abs(flux) > self._args.epsilon or self._args.all_reactions: + rx = self._mm.get_reaction(reaction_id) + rx_trans = rx.translated_compounds(compound_name) + genes = reaction_genes_string(reaction_id) + print('{}\t{}\t{}\t{}'.format( + reaction_id, flux, rx_trans, genes)) + + # Remember flux of requested reaction + if reaction_id == reaction: + optimum = flux + + logger.info('Objective flux: {}'.format(optimum)) + logger.info('Reactions at zero flux: {}/{}'.format( + total_reactions - nonzero_reactions, total_reactions)) + + def run_fba(self, reaction): + """"""Run standard FBA on model."""""" + solver = self._get_solver() + p = fluxanalysis.FluxBalanceProblem(self._mm, solver) + + start_time = time.time() + + try: + p.maximize(reaction) + except fluxanalysis.FluxBalanceError as e: + self.report_flux_balance_error(e) + + logger.info('Solving took {:.2f} seconds'.format( + time.time() - start_time)) + + for reaction_id in self._mm.reactions: + yield reaction_id, p.get_flux(reaction_id) + + def run_fba_minimized(self, reaction): + """"""Run normal FBA and flux minimization on model."""""" + + epsilon = self._args.epsilon + solver = self._get_solver() + + p = fluxanalysis.FluxBalanceProblem(self._mm, solver) + + start_time = time.time() + + # Maximize reaction flux + try: + p.maximize(reaction) + except fluxanalysis.FluxBalanceError as e: + self.report_flux_balance_error(e) + + fluxes = {r: p.get_flux(r) for r in self._mm.reactions} + + # Run flux minimization + flux_var = p.get_flux_var(reaction) + p.prob.add_linear_constraints(flux_var == p.get_flux(reaction)) + p.minimize_l1() + + logger.info('Solving took {:.2f} seconds'.format( + time.time() - start_time)) + + count = 0 + for reaction_id in self._mm.reactions: + flux = p.get_flux(reaction_id) + if abs(flux - fluxes[reaction_id]) > epsilon: + count += 1 + yield reaction_id, flux + logger.info('Minimized reactions: {}'.format(count)) + + def run_tfba(self, reaction): + """"""Run FBA and tFBA on model."""""" + + solver = self._get_solver(integer=True) + p = fluxanalysis.FluxBalanceProblem(self._mm, solver) + + start_time = time.time() + + p.add_thermodynamic() + + try: + p.maximize(reaction) + except fluxanalysis.FluxBalanceError as e: + self.report_flux_balance_error(e) + + logger.info('Solving took {:.2f} seconds'.format( + time.time() - start_time)) + + for reaction_id in self._mm.reactions: + yield reaction_id, p.get_flux(reaction_id) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/fluxcheck.py",".py","7703","204","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import time +import logging +from itertools import product + +from six import text_type + +from ..command import (Command, MetabolicMixin, LoopRemovalMixin, + SolverCommandMixin, ParallelTaskMixin) +from .. import fluxanalysis, fastcore + +logger = logging.getLogger(__name__) + + +class FluxConsistencyCommand(MetabolicMixin, LoopRemovalMixin, + SolverCommandMixin, ParallelTaskMixin, Command): + """"""Check that reactions are flux consistent in a model. + + A reaction is flux consistent if there exists any steady-state flux + solution where the flux of the given reaction is non-zero. The + bounds on the exchange reactions can be removed when performing the + consistency check by providing the ``--unrestricted`` option. + """""" + + _supported_loop_removal = ['none', 'tfba'] + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--fastcore', help='Enable use of Fastcore algorithm', + action='store_true') + parser.add_argument( + '--reduce-lp', + help='Try to reduce the number of LP problems to solve', + action='store_true') + parser.add_argument( + '--epsilon', type=float, help='Flux threshold', + default=1e-5) + parser.add_argument( + '--unrestricted', action='store_true', + help='Remove limits on exchange reactions before checking') + super(FluxConsistencyCommand, cls).init_parser(parser) + + def run(self): + """"""Run flux consistency check command"""""" + + # Load compound information + def compound_name(id): + if id not in self._model.compounds: + return id + return self._model.compounds[id].properties.get('name', id) + + epsilon = self._args.epsilon + + if self._args.unrestricted: + # Allow all exchange reactions with no flux limits + for reaction in self._mm.reactions: + if self._mm.is_exchange(reaction): + del self._mm.limits[reaction].bounds + + loop_removal = self._get_loop_removal_option() + enable_tfba = loop_removal == 'tfba' + enable_fastcore = self._args.fastcore + + if enable_tfba and enable_fastcore: + self.argument_error( + 'Using Fastcore with thermodynamic constraints' + ' is not supported!') + start_time = time.time() + + if enable_fastcore: + solver = self._get_solver() + try: + inconsistent = set(fastcore.fastcc( + self._mm, epsilon, solver=solver)) + except fluxanalysis.FluxBalanceError as e: + self.report_flux_balance_error(e) + else: + if enable_tfba: + solver = self._get_solver(integer=True) + else: + solver = self._get_solver() + + if self._args.reduce_lp: + logger.info('Running with reduced number of LP problems.') + try: + inconsistent = set( + fluxanalysis.consistency_check( + self._mm, self._mm.reactions, epsilon, + tfba=enable_tfba, solver=solver)) + except fluxanalysis.FluxBalanceError as e: + self.report_flux_balance_error(e) + else: + logger.info('Using flux bounds to determine consistency.') + try: + inconsistent = set(self._run_fva_fluxcheck( + self._mm, solver, enable_tfba, epsilon)) + except FluxCheckFVATaskError: + self.report_flux_balance_error() + + logger.info('Solving took {:.2f} seconds'.format( + time.time() - start_time)) + + # Count the number of reactions that are fixed at zero. While these + # reactions are still inconsistent, they are inconsistent because they + # have been explicitly disabled. + disabled_exchange = 0 + disabled_internal = 0 + + count_exchange = 0 + total_exchange = 0 + + count_internal = 0 + total_internal = 0 + + # Print result + for reaction in sorted(self._mm.reactions): + disabled = self._mm.limits[reaction].bounds == (0, 0) + + if self._mm.is_exchange(reaction): + total_exchange += 1 + count_exchange += int(reaction in inconsistent) + disabled_exchange += int(disabled) + else: + total_internal += 1 + count_internal += int(reaction in inconsistent) + disabled_internal += int(disabled) + + if reaction in inconsistent: + rx = self._mm.get_reaction(reaction) + rxt = rx.translated_compounds(compound_name) + print('{}\t{}'.format(reaction, rxt)) + + logger.info('Model has {}/{} inconsistent internal reactions' + ' ({} disabled by user)'.format( + count_internal, total_internal, disabled_internal)) + logger.info('Model has {}/{} inconsistent exchange reactions' + ' ({} disabled by user)'.format( + count_exchange, total_exchange, disabled_exchange)) + + def _run_fva_fluxcheck(self, model, solver, enable_tfba, epsilon): + handler_args = model, solver, enable_tfba + executor = self._create_executor( + FluxCheckFVATaskHandler, handler_args, cpus_per_worker=2) + + results = {} + with executor: + for (reaction_id, direction), value in executor.imap_unordered( + product(model.reactions, (1, -1)), 16): + + if reaction_id not in results: + results[reaction_id] = value + continue + + other_value = results[reaction_id] + if direction == -1: + bounds = value, other_value + else: + bounds = other_value, value + + lower, upper = bounds + if abs(lower) < epsilon and abs(upper) < epsilon: + yield reaction_id + + executor.join() + + +class FluxCheckFVATaskError(Exception): + """"""Error raised from parallel flux check task on failure."""""" + + +class FluxCheckFVATaskHandler(object): + def __init__(self, model, solver, enable_tfba): + self._problem = fluxanalysis.FluxBalanceProblem(model, solver) + if enable_tfba: + self._problem.add_thermodynamic() + + def handle_task(self, reaction_id, direction): + try: + return self._problem.flux_bound(reaction_id, direction) + except fluxanalysis.FluxBalanceError as e: + # FluxBalanceError is not picklable. Reraise as picklable + # exception. + raise FluxCheckFVATaskError(text_type(e)) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/genedelete.py",".py","5988","150","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals, division + +import time +import logging + +from ..command import (Command, MetabolicMixin, ObjectiveMixin, + SolverCommandMixin, FilePrefixAppendAction) +from .. import fluxanalysis +from .. import moma +from ..expression import boolean + +from six import string_types, text_type + +logger = logging.getLogger(__name__) + + +class GeneDeletionCommand(MetabolicMixin, ObjectiveMixin, SolverCommandMixin, + Command): + """"""Find reactions requiring a specified gene and delete them from model. + + Reports the new objective flux after the gene was deleted. + """""" + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--gene', metavar='genes', action=FilePrefixAppendAction, + type=str, default=[], help='Delete multiple genes from model') + parser.add_argument( + '--method', metavar='method', + choices=['fba', 'lin_moma', 'lin_moma2', 'moma', 'moma2'], + type=text_type, default='fba', + help='Select which method to use. (fba, lin_moma, lin_moma2, ' + 'moma, moma2)') + super(GeneDeletionCommand, cls).init_parser(parser) + + def run(self): + """"""Delete the specified gene and solve using the desired method."""""" + obj_reaction = self._get_objective() + + genes = set() + gene_assoc = {} + for reaction in self._model.reactions: + assoc = None + if reaction.genes is None: + continue + elif isinstance(reaction.genes, string_types): + assoc = boolean.Expression(reaction.genes) + else: + variables = [boolean.Variable(g) for g in reaction.genes] + assoc = boolean.Expression(boolean.And(*variables)) + genes.update(v.symbol for v in assoc.variables) + gene_assoc[reaction.id] = assoc + + reactions = set(self._mm.reactions) + start_time = time.time() + testing_genes = set(self._args.gene) + deleted_reactions = set() + + logger.info('Trying model without genes: {}...'.format( + ', '.join(sorted(testing_genes)))) + + for reaction in reactions: + if reaction not in gene_assoc: + continue + assoc = gene_assoc[reaction] + if any(boolean.Variable(gene) in assoc.variables + for gene in testing_genes): + new_assoc = assoc.substitute( + lambda v: v if v.symbol not in testing_genes else False) + if new_assoc.has_value() and not new_assoc.value: + logger.info('Deleting reaction {}...'.format(reaction)) + deleted_reactions.add(reaction) + + if self._args.method in ['moma', 'moma2']: + solver = self._get_solver(quadratic=True) + else: + solver = self._get_solver() + + if self._args.method == 'fba': + logger.info('Solving using FBA...') + prob = fluxanalysis.FluxBalanceProblem(self._mm, solver) + + try: + prob.maximize(obj_reaction) + except fluxanalysis.FluxBalanceError as e: + self.report_flux_balance_error(e) + + wild = prob.get_flux(obj_reaction) + + for reaction in deleted_reactions: + flux_var = prob.get_flux_var(reaction) + prob.prob.add_linear_constraints(flux_var == 0) + + prob.maximize(obj_reaction) + deleteflux = prob.get_flux(obj_reaction) + elif self._args.method in ['lin_moma', 'lin_moma2', 'moma', 'moma2']: + prob = moma.MOMAProblem(self._mm, solver) + wt_fluxes = prob.get_minimal_fba_flux(obj_reaction) + wild = wt_fluxes[obj_reaction] + + for reaction in deleted_reactions: + flux_var = prob.get_flux_var(reaction) + prob.prob.add_linear_constraints(flux_var == 0) + + try: + if self._args.method == 'moma': + logger.info('Solving using MOMA...') + prob.moma(wt_fluxes) + elif self._args.method == 'lin_moma': + logger.info('Solving using linear MOMA...') + prob.lin_moma(wt_fluxes) + elif self._args.method == 'moma2': + logger.info('Solving using combined-model MOMA...') + prob.moma2(obj_reaction, wild) + elif self._args.method == 'lin_moma2': + logger.info('Solving using combined-model linear MOMA...') + prob.lin_moma2(obj_reaction, wild) + except moma.MOMAError: + self.fail('Error computing the MOMA result.') + + deleteflux = prob.get_flux(obj_reaction) + + logger.info( + 'Solving took {:.2f} seconds'.format(time.time() - start_time)) + logger.info( + 'Objective reaction after gene deletion has flux {}'.format( + deleteflux + 0)) + if wild != 0: + logger.info( + 'Objective reaction has {:.2%} flux of wild type flux'.format( + abs(deleteflux / wild))) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/gapfill.py",".py","6271","155","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import logging +import argparse + +from six import text_type + +from ..command import (Command, MetabolicMixin, SolverCommandMixin, + FilePrefixAppendAction) +from ..gapfill import gapfill, GapFillError +from ..datasource.reaction import parse_compound +from ..gapfilling import create_extended_model + +logger = logging.getLogger(__name__) + + +class GapFillCommand(MetabolicMixin, SolverCommandMixin, Command): + """"""Run the GapFill algorithms on the model."""""" + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--compound', metavar='compound', action=FilePrefixAppendAction, + type=parse_compound, default=[], + help='Select compounds to try to unblock') + parser.add_argument( + '--penalty', metavar='file', type=argparse.FileType('r'), + help='List of penalty scores for database reactions') + parser.add_argument( + '--db-penalty', metavar='penalty', type=float, + help='Default penalty for database reactions') + parser.add_argument( + '--tp-penalty', metavar='penalty', type=float, + help='Default penalty for transport reactions') + parser.add_argument( + '--ex-penalty', metavar='penalty', type=float, + help='Default penalty for exchange reactions') + parser.add_argument( + '--epsilon', type=float, default=1e-5, + help='Threshold for reaction flux') + parser.add_argument( + '--no-implicit-sinks', action='store_true', + help='Do not include implicit sinks when gap-filling') + parser.add_argument( + '--allow-bounds-expansion', action='store_true', + help=('Allow GapFill to propose expansion of flux bounds. This' + ' includes turning irreversible reactions reversible.')) + super(GapFillCommand, cls).init_parser(parser) + + def run(self): + """"""Run GapFill command"""""" + + # Load compound information + def compound_name(id): + if id not in self._model.compounds: + return id + return self._model.compounds[id].properties.get('name', id) + + # Calculate penalty if penalty file exists + penalties = {} + if self._args.penalty is not None: + for line in self._args.penalty: + line, _, comment = line.partition('#') + line = line.strip() + if line == '': + continue + rxnid, penalty = line.split(None, 1) + penalties[rxnid] = float(penalty) + + core = set(self._mm.reactions) + + solver = self._get_solver(integer=True) + default_comp = self._model.default_compartment + epsilon = self._args.epsilon + v_max = float(self._model.default_flux_limit) + + blocked = set() + for compound in self._args.compound: + if compound.compartment is None: + compound = compound.in_compartment(default_comp) + blocked.add(compound) + + if len(blocked) > 0: + logger.info('Unblocking compounds: {}...'.format( + ', '.join(text_type(c) for c in sorted(blocked)))) + else: + logger.info( + 'Unblocking all compounds in model. Use --compound option to' + ' unblock specific compounds.') + blocked = set(self._mm.compounds) + + exclude = set() + if self._model.biomass_reaction is not None: + exclude.add(self._model.biomass_reaction) + + # Add exchange and transport reactions to database + model_complete, weights = create_extended_model( + self._model, + db_penalty=self._args.db_penalty, + ex_penalty=self._args.ex_penalty, + tp_penalty=self._args.tp_penalty, + penalties=penalties) + + implicit_sinks = not self._args.no_implicit_sinks + + logger.info('Searching for reactions to fill gaps') + try: + added_reactions, no_bounds_reactions = gapfill( + model_complete, core, blocked, exclude, solver=solver, + epsilon=epsilon, v_max=v_max, weights=weights, + implicit_sinks=implicit_sinks, + allow_bounds_expansion=self._args.allow_bounds_expansion) + except GapFillError as e: + self._log_epsilon_and_fail(epsilon, e) + + for reaction_id in sorted(self._mm.reactions): + rx = self._mm.get_reaction(reaction_id) + rxt = rx.translated_compounds(compound_name) + print('{}\t{}\t{}\t{}'.format(reaction_id, 'Model', 0, rxt)) + + for rxnid in sorted(added_reactions): + rx = model_complete.get_reaction(rxnid) + rxt = rx.translated_compounds(compound_name) + print('{}\t{}\t{}\t{}'.format( + rxnid, 'Add', weights.get(rxnid, 1), rxt)) + + for rxnid in sorted(no_bounds_reactions): + rx = model_complete.get_reaction(rxnid) + rxt = rx.translated_compounds(compound_name) + print('{}\t{}\t{}\t{}'.format( + rxnid, 'Remove bounds', weights.get(rxnid, 1), rxt)) + + def _log_epsilon_and_fail(self, epsilon, exc): + msg = ('Finding blocked compounds failed with epsilon set to {}. Try' + ' lowering the epsilon value to reduce artifical constraints on' + ' the model.'.format(epsilon)) + self.fail(msg, exc) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/vis.py",".py","28012","668","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2018-2020 Ke Zhang +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2020 Elysha Sameth + +from __future__ import unicode_literals + +import logging +import io +import os +import csv +import argparse +from collections import defaultdict, Counter +from six import text_type +from ..command import MetabolicMixin, Command, FilePrefixAppendAction, \ + convert_to_unicode +from .. import graph +import sys +from ..formula import Atom, _AtomType +try: + from graphviz import render, FORMATS +except ImportError: + render = None + FORMATS = None + +logger = logging.getLogger(__name__) + +REACTION_COLOR = '#c9fccd' +COMPOUND_COLOR = '#ffd8bf' +ACTIVE_COLOR = '#90f998' +ALT_COLOR = '#b3fcb8' + +EPSILON = 1e-5 + + +class VisualizationCommand(MetabolicMixin, + Command, FilePrefixAppendAction): + """"""Generate graphical representations of the model"""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--method', type=str, default='fpp', + help='Compound pair prediction method', + choices=['fpp', 'no-fpp']) + parser.add_argument( + '--exclude', metavar='reaction', type=convert_to_unicode, + default=[], action=FilePrefixAppendAction, + help='Reaction(s) to exclude from metabolite pair prediction') + parser.add_argument( + '--element', type=str, default='C', + help='Element transfer to show on the graph (C, N, O, S).') + parser.add_argument( + '--cpd-detail', type=str, default=None, action='append', + nargs='+', help='List of properties to include on ' + 'compound nodes.') + parser.add_argument( + '--rxn-detail', type=str, default=None, action='append', + nargs='+', help='List of properties to include on reaction ' + 'nodes.') + parser.add_argument( + '--subset', type=argparse.FileType('rU'), default=None, + help='File containing a list of reactions IDs or compound IDs ' + '(with compartment). This file determines which reactions ' + 'will be visualized') + parser.add_argument( + '--color', type=argparse.FileType('rU'), default=None, nargs='+', + help='File containing node color mappings') + parser.add_argument( + '--image', metavar='Image Format', type=str, choices=FORMATS, + required='--image-size' in sys.argv, + help='Image output file format ' + '(e.g. pdf, png, eps)') + parser.add_argument( + '--hide-edges', type=argparse.FileType('rU'), default=None, + help='File containing compound edges to exclude ' + 'from visualization') + parser.add_argument( + '--combine', metavar='Combine Level', type=int, choices=range(3), + default=0, help='Combined reaction nodes in three ' + 'different levels.') + parser.add_argument( + '--compartment', action='store_true', + help='Include compartments in final visualization') + parser.add_argument( + '--output', type=str, + help='Full path for visualization outputs, including prefix of ' + 'output files. ' + 'e.g. ""--output /output-prefix""') + parser.add_argument( + '--image-size', metavar=('Width', 'Height'), + default=('None', 'None'), nargs=2, type=float, + help='Set the width and height of the graph image. ' + '(width height)(inches)') + parser.add_argument( + '--array', type=int, default=None, + help='The number of columns to use in the final ' + 'network image') + group = parser.add_mutually_exclusive_group() + group.add_argument( + '--fba', type=argparse.FileType('rU'), default=None, + help='File containing fba reaction flux') + group.add_argument( + '--fva', type=argparse.FileType('rU'), default=None, + help='File containing fva reaction flux') + + super(VisualizationCommand, cls).init_parser(parser) + + def run(self): + """"""Run visualization command."""""" + for reaction in self._model.reactions: + if reaction.equation is None: + logger.warning( + 'Reaction {} was excluded from visualization due to ' + 'missing reaction equation'.format(reaction.id)) + + compound_formula = graph.get_compound_dict(self._model) + + vis_rxns = rxnset_for_vis( + self._mm, self._args.subset, self._args.exclude) + + if self._args.array is not None and int(self._args.array) <= 0: + logger.error( + ""'--array' should be followed by a positive integer, number "" + ""'{}' is invalid. Visualization has stopped, please fix the "" + ""number first"".format(self._args.array)) + quit() + + if self._args.element.lower() == 'all': + self._args.element = None + else: + if self._args.element not in _AtomType._ELEMENTS: + logger.error( + ""Given element '{}' doesn't represent any chemical element"" + "", visualization has terminated. Please check your "" + ""--element parameter"".format(self._args.element)) + quit() + + self.analysis = None + reaction_dict = {} + if self._args.fba is not None: + self.analysis = 'fba' + for row in csv.reader(self._args.fba, delimiter=str('\t')): + row[0] = convert_to_unicode(row[0]) + if row[0] in vis_rxns: + try: + if abs(float(row[1])) <= EPSILON: + row[1] = 0 + except ValueError: + logger.warning( + 'Reaction {} has an invalid flux value of {} ' + 'and will be considered as a flux of 0'.format( + row[0], row[1])) + row[1] = 0 + reaction_dict[row[0]] = (float(row[1]), 1) + else: + logger.warning( + 'Reaction {} in input fba file was excluded from ' + 'visualization'.format(row[0])) + + if self._args.fva is not None: + self.analysis = 'fva' + for row in csv.reader(self._args.fva, delimiter=str('\t')): + row[0] = convert_to_unicode(row[0]) + if row[0] in vis_rxns: + try: + if abs(float(row[1])) <= EPSILON: + row[1] = 0 + if abs(float(row[2])) <= EPSILON: + row[2] = 0 + except ValueError: + logger.warning( + 'Reaction {} has an invalid flux value of {},{} ' + 'and will be considered as a flux of 0,0'.format( + row[0], row[1], row[2])) + row[1], row[2] = 0, 0 + reaction_dict[row[0]] = (float(row[1]), float(row[2])) + else: + logger.warning( + 'Reaction {} in input fva file was excluded from ' + 'visualization due to not being defined in the ' + 'model'.format(row[0])) + + exclude_for_fpp = [self._model.biomass_reaction] + self._args.exclude + filter_dict, style_flux_dict = graph.make_network_dict( + self._model, self._mm, vis_rxns, self._args.method, + self._args.element, exclude_for_fpp, reaction_dict, self.analysis) + + model_compound_entries, model_reaction_entries = {}, {} + for c in self._model.compounds: + model_compound_entries[c.id] = c + for r in self._model.reactions: + model_reaction_entries[r.id] = r + + hide_edges = [] + if self._args.hide_edges is not None: + for row in csv.reader(self._args.hide_edges, delimiter=str('\t')): + hide_edges.append((row[0], row[1])) + hide_edges.append((row[1], row[0])) + + cpair_dict, new_id_mapping, new_style_flux_dict = \ + graph.make_cpair_dict( + filter_dict, self._args.method, self._args.combine, + style_flux_dict, hide_edges) + + g = graph.make_bipartite_graph_object( + cpair_dict, new_id_mapping, self._args.method, self._args.combine, + model_compound_entries, new_style_flux_dict, self.analysis) + + exchange_cpds = set() + for rid in vis_rxns: + if self._mm.is_exchange(rid) and rid != \ + self._model.biomass_reaction: + exchange_rxn = self._mm.get_reaction(rid) + for c, _ in exchange_rxn.compounds: + if c not in g.nodes_id_dict: + g = add_ex_cpd(g, c, model_compound_entries[c.name], + compound_formula, self._args.element) + exchange_cpds.add(c) + g = add_exchange_rxns( + g, rid, exchange_rxn, style_flux_dict) + + recolor_dict = {} + if self._args.color is not None: + for f in self._args.color: + for row in csv.reader(f, delimiter=str('\t')): + recolor_dict[row[0]] = row[1] + g = add_node_props(g, recolor_dict) + g = add_node_label(g, self._args.cpd_detail, self._args.rxn_detail) + bio_cpds_sub = set() + bio_cpds_pro = set() + + if self._model.biomass_reaction in vis_rxns: + if self._model.biomass_reaction in model_reaction_entries: + nm_biomass_rxn = \ + model_reaction_entries[self._model.biomass_reaction] + g = add_biomass_rxns(g, nm_biomass_rxn) + for cpd, _ in nm_biomass_rxn.equation.left: + bio_cpds_sub.add(text_type(cpd)) + for cpd, _ in nm_biomass_rxn.equation.right: + bio_cpds_pro.add(text_type(cpd)) + else: + logger.warning( + 'Biomass reaction {} was excluded from visualization ' + 'due to missing reaction entry'.format( + self._model.biomass_reaction)) + + for node in g.nodes: + if node.props['id'] in bio_cpds_sub: + node.props['type'] = 'cpd_biomass_substrate' + elif node.props['id'] in bio_cpds_pro: + node.props['type'] = 'cpd_biomass_product' + elif node.props['id'] in exchange_cpds: + node.props['type'] = 'cpd_exchange' + else: + continue + + if self._args.method == 'no-fpp' and self._args.combine != 0: + logger.warning( + '--combine option is not compatible with no-fpp method') + + hw = self._args.image_size + width = hw[0] + height = hw[1] + + if self._args.output is not None: + output = self._args.output + else: + output = 'reactions' + + if self._args.compartment: + boundaries, extracellular = get_cpt_boundaries(self._model) + boundary_tree, extracellular = make_cpt_tree(boundaries, + extracellular) + with io.open('{}.dot'.format(output), 'w', encoding='utf-8', + errors='backslashreplace') as f: + g.write_graphviz_compartmentalized( + f, boundary_tree, extracellular, width, height) + else: + with io.open('{}.dot'.format(output), 'w', encoding='utf-8', + errors='backslashreplace') as f: + g.write_graphviz(f, width, height) + with io.open('{}.nodes.tsv'.format(output), 'w', encoding='utf-8', + errors='backslashreplace') as f: + g.write_nodes_tables(f) + with io.open('{}.edges.tsv'.format(output), 'w', encoding='utf-8', + errors='backslashreplace') as f: + g.write_edges_tables(f) + + if self._args.image is not None: + if render is None: + raise ImportError( + 'Making an image directly requires the ' + 'graphviz python bindings and the graphviz program ' + 'to be installed (""pip install graphviz"")') + else: + if len(g.nodes_id_dict) > 700: + logger.info( + 'This graph contains {} reactions, ' + 'graphs of this size may take a long time to ' + 'create'.format(len(filter_dict.keys()))) + if self._args.array is None: + render('dot', self._args.image, '{}.dot'.format(output)) + else: + out = '{}.dot'.format(output) + format = self._args.image + image = '{}.dot.{}'.format(output, format) + os.system(""ccomps -x {} |dot |gvpack -array{} |neato "" + ""-T{} -n2 -o {}"".format(out, self._args.array, + format, image)) + else: + if self._args.array is not None: + out = '{}.dot'.format(output) + os.system(""ccomps -x {} |dot |gvpack -array{} "" + "">{}_new.dot"".format(out, self._args.array, output)) + os.system(""mv {}_new.dot {}.dot"".format(output, output)) + + +def rxnset_for_vis(mm, subset_file, exclude): + """""" Create a collection of reaction IDs that need to be visualized. + + Generate a set that contains IDs of all reactions that need to be + visualized. This set can be generated from a file containing + reaction or compound IDs. + + Args: + mm: Metabolic model, class 'psamm.metabolicmodel.MetabolicModel'. + subset_file: None or an open file containing a list of reactions + or compound ids. + exclude: rxns to exclude + """""" + all_cpds = set() + for cpd in mm.compounds: + all_cpds.add(text_type(cpd)) + if subset_file is None: + if len(exclude) == 0: + final_rxn_set = set(mm.reactions) + else: + final_rxn_set = set( + [rxn for rxn in mm.reactions if rxn not in exclude]) + else: + final_rxn_set = set() + cpd_set = set() + rxn_set = set() + for line in subset_file.readlines(): + if not convert_to_unicode(line).startswith('#'): + value = convert_to_unicode(line).strip() + if value in all_cpds: + cpd_set.add(value) + elif mm.has_reaction(value): + rxn_set.add(value) + else: + raise ValueError(u'{} is in subset file but is not a ' + 'compound or reaction ID'.format(value)) + + if all(i > 0 for i in [len(cpd_set), len(rxn_set)]): + raise ValueError('Subset file is a mixture of reactions and ' + 'compounds.') + else: + if len(cpd_set) > 0: + for rx in mm.reactions: + rxn = mm.get_reaction(rx) + if any(text_type(c) in cpd_set + for (c, _) in rxn.compounds): + final_rxn_set.add(rx) + elif len(rxn_set) > 0: + final_rxn_set = rxn_set + + return final_rxn_set + + +def add_biomass_rxns(g, nm_bio_reaction): + """""" Adds biomass reaction nodes and edges to a graph object. + + This function is used to add nodes and edges of biomass reaction to + the graph object. All the following properties are defined + for added nodes: shape, style(filled), fill color, label. + + Args: + g: Graph object. + nm_bio_reaction: Biomass reaction DictReactionEntry. + """""" + bio_reaction = nm_bio_reaction.equation + biomass_rxn_id = nm_bio_reaction.id + direction = graph.dir_value(bio_reaction.direction) + reactant_list, product_list = [], [] + for c, _ in bio_reaction.left: + reactant_list.append(c) + for c, _ in bio_reaction.right: + product_list.append(c) + bio_pair = Counter() + for c, _ in bio_reaction.compounds: + if text_type(c) in g.nodes_id_dict: + bio_pair[biomass_rxn_id] += 1 + node_bio = graph.Node({ + 'id': u'{}_{}'.format(biomass_rxn_id, + bio_pair[biomass_rxn_id]), + 'entry': [nm_bio_reaction], + 'shape': 'box', + 'style': 'filled', + 'label': biomass_rxn_id, + 'type': 'bio_rxn', + 'fillcolor': ALT_COLOR, + 'compartment': c.compartment}) + g.add_node(node_bio) + + if c in reactant_list: + g.add_edge(graph.Edge(g.get_node(text_type(c)), node_bio, + {'dir': direction})) + if c in product_list: + g.add_edge(graph.Edge(node_bio, g.get_node(text_type(c)), + {'dir': direction})) + return g + + +def add_ex_cpd(g, mm_cpd, nm_cpd, compound_formula, element): + node_dict = {'id': text_type(mm_cpd), + 'entry': [nm_cpd], + 'compartment': mm_cpd.compartment, + 'type': 'cpd'} + if element is not None: + if mm_cpd.name not in compound_formula: + logger.error(u'Compound formulas are required for fpp or specific ' + 'element visualizations, but compound {} does not ' + 'have valid formula, add its formula, or try ' + '--element all to visualize all pathways without ' + 'compound formula input.'.format(mm_cpd.name)) + else: + if Atom(element) in compound_formula[mm_cpd.name]: + node = graph.Node(node_dict) + g.add_node(node) + else: + node = graph.Node(node_dict) + g.add_node(node) + return g + + +def add_node_props(g, recolor_dict): + """""" Update node color in Graph object based on a mapping dictionary + + This function adds shape and style(filled) properties to nodes in a graph. + + Args: + g: A Graph object that contains nodes and edges. + recolor_dict: dict of rxn_id/cpd_id[compartment] : hex color code. + return: a graph object that contains a set of node with defined color. + """""" + cpd_types = ['cpd', 'cpd_biomass_substrate', + 'cpd_biomass_product', 'cpd_exchange'] + for node in g.nodes: + node.props['style'] = 'filled' + if node.props['type'] in cpd_types: + node.props['fillcolor'] = COMPOUND_COLOR + node.props['shape'] = 'ellipse' + elif node.props['type'] == 'rxn': + node.props['fillcolor'] = REACTION_COLOR + node.props['shape'] = 'box' + else: + if node.props['type'] not in ['bio_rxn', 'Ex_rxn']: + logger.error('invalid nodes:', type( + node.props['entry']), node.props['entry']) + for r_id in recolor_dict: + if r_id in g.nodes_original_id_dict: + for node in g.nodes_original_id_dict[r_id]: + node.props['fillcolor'] = recolor_dict[r_id] + return g + + +def add_node_label(g, cpd_detail, rxn_detail): + """""" Set label of nodes in graph object, + + Set the label of nodes in a graph object based on compound/reaction + properties provided through the cpd_detail or rxn_detail arguments. + + Args: + g: A graph object, contain a set of nodes and a dictionary of edges. + cpd_detail: A list that contains only one + element, this element is a compound properties name list, + e.g. detail = [['id', 'name', 'formula']]. + rxn_detail: A list that contains only one + element, this element is a reaction properties name list, + e.g. detail = [['id', genes', 'equation']]. + """""" + for node in g.nodes: + if node.props['type'] == 'cpd': + node.props['label'] = node.props['id'] + elif node.props['type'] == 'rxn': + node.props['label'] = '\n'.join( + obj.id for obj in node.props['entry']) + + # update node label based on what users provide in command line + if cpd_detail is not None: + if node.props['type'] == 'cpd': + pre_label = '\n'.join( + (node.props['entry'][0].properties.get(value)) for + value in cpd_detail[0] if value != 'id' and + value in node.props['entry'][0].properties) + if 'id' in cpd_detail[0]: + label = u'{}\n{}'.format(node.props['id'], pre_label) + else: + label = pre_label + + # if all required properties are not in the compound entry, + # then print compound id + if label == '': + label = node.props['id'] + + node.props['label'] = label + + if rxn_detail is not None: + if node.props['type'] == 'rxn': + if len(node.props['entry']) == 1: + pre_label = u'\n'.join( + node.props['entry'][0].properties.get(value) + for value in rxn_detail[0] if + value != 'equation' and + value != 'id' and value in + node.props['entry'][0].properties) + if 'id' in rxn_detail[0]: + label = u'{}\n{}'.format( + node.props['entry'][0].properties['id'], pre_label) + else: + label = pre_label + + if 'equation' in rxn_detail[0]: + label += u'\n{}'.format( + node.props['entry'][0].properties.get('equation')) + + # if all required properties are not in the reaction entry, + # then print reaction id + if label == '': + label = node.props['id'] + + node.props['label'] = label + return g + + +def make_cpt_tree(boundaries, extracellular): + """""" This function will create a tree-like dictionary that can be used to + determine compartment location. + + This function will take a list of compartment boundary tuples + (eg: [(c, e), (c, p)]) and use this data to construct a tree like + dictionary of parent compartments to lists of compartments they are + adjacent to. An extracellular compartment will also be set to use as + a starting point for the 'outermost' compartment in the model. If + none is explicitly defined then 'e' will be used by default. + If an 'e' compartment is not in the model either then a random + compartment will be used as a starting point. + + args: + boundaries: a list of tuples of adjacent compartment ids. + extracellular: the extracellular compartment in the model. + """""" + children = defaultdict(set) + compartments = set() + for (j, k) in boundaries: + compartments.add(j) + compartments.add(k) + if extracellular not in compartments: + etmp = sorted(list(compartments), reverse=True) + extracellular = etmp[0] + logger.warning('No extracellular compartment was defined in the ' + 'model.yaml file and no ""e"" compartment in the model. ' + 'Trying to use {} as the extracellular compartment.' + .format(etmp[0])) + for cpt in compartments: + for (j, k) in boundaries: + j = text_type(j) + k = text_type(k) + if j == cpt: + children[cpt].add(k) + elif k == cpt: + children[cpt].add(j) + return children, extracellular + + +def get_cpt_boundaries(model): + """"""This function will determine the compartment boundaries in a model + + This function will take a native model object and determine the + compartment boundaries either based on the predefined compartments in + the model.yaml or based on the reaction equations in the model. + + args: + model: Native model, class 'psamm.datasource.native.NativeModel'. + """""" + if model.extracellular_compartment is not None: + extracellular = model.extracellular_compartment + else: + extracellular = 'e' + + if len(model.compartment_boundaries) != 0: + boundaries = model.compartment_boundaries + else: + boundaries = set() + for rxn in model.reactions: + cpd_cpt = set() + for cpd in rxn.equation.compounds: + cpd_cpt.add(cpd[0].compartment) + if len(cpd_cpt) > 1: + cpd_cpt = list(cpd_cpt) + boundaries.add(tuple(sorted((cpd_cpt[0], cpd_cpt[1])))) + return boundaries, extracellular + + +def add_exchange_rxns(g, rxn_id, reaction, style_flux_dict): + """""" Add exchange reaction nodes and edges to graph object. + + This function is used to add nodes and edges of exchange reactions to + the graph object. It will return an updated graph object that contains + nodes representing exchange reactions. + + Args: + g: A graph object that contains a set of nodes and some edges. + rxn_id: Exchange reaction id, + reaction: Exchange reaction object(metabolic model reaction), + class 'psamm.reaction.Reaction'. + style_flux_dict: dictionary of reaction ID maps to edge style and + edge width. + analysis: ""None"" type or a string indicates if FBA or FVA file is + given in command line. + """""" + direction = graph.dir_value(reaction.direction) + for c, _ in reaction.compounds: + if text_type(c) in g.nodes_id_dict: + node_ex = graph.Node({ + 'id': text_type(rxn_id), + 'entry': [reaction], + 'shape': 'box', + 'style': 'filled', + 'label': rxn_id, + 'type': 'Ex_rxn', + 'fillcolor': ACTIVE_COLOR, + 'compartment': c.compartment}) + g.add_node(node_ex) + + for c1, _ in reaction.left: + g.add_edge(graph.Edge( + g.get_node(text_type(c1)), node_ex, { + 'dir': direction, + 'style': style_flux_dict[rxn_id][0], + 'penwidth': style_flux_dict[rxn_id][1] + })) + for c2, _ in reaction.right: + g.add_edge(graph.Edge( + node_ex, g.get_node(text_type(c2)), { + 'dir': direction, + 'style': style_flux_dict[rxn_id][0], + 'penwidth': style_flux_dict[rxn_id][1] + })) + return g +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/formulacheck.py",".py","2828","79","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import logging + +from ..command import Command, FilePrefixAppendAction, convert_to_unicode +from ..formula import Formula +from ..balancecheck import formula_balance + +logger = logging.getLogger(__name__) + + +class FormulaBalanceCommand(Command): + """"""Check whether reactions in the model are elementally balanced. + + Balanced reactions are those reactions where the number of elements + (atoms) is consistent on the left and right side of the reaction equation. + Reactions that are not balanced will be printed out. + """""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--exclude', metavar='reaction', action=FilePrefixAppendAction, + type=convert_to_unicode, default=[], + help='Exclude reaction from balance check') + super(FormulaBalanceCommand, cls).init_parser(parser) + + def run(self): + """"""Run formula balance command"""""" + + # Create a set of excluded reactions + exclude = set(self._args.exclude) + count = 0 + unbalanced = 0 + unchecked = 0 + for reaction, result in formula_balance(self._model): + count += 1 + + if reaction.id in exclude or reaction.equation is None: + continue + + if result is None: + unchecked += 1 + continue + + left_form, right_form = result + if right_form != left_form: + unbalanced += 1 + right_missing, left_missing = Formula.balance( + right_form, left_form) + + print('{}\t{}\t{}\t{}\t{}'.format( + reaction.id, left_form, right_form, + left_missing, right_missing)) + + logger.info('Unbalanced reactions: {}/{}'.format(unbalanced, count)) + logger.info('Unchecked reactions due to missing formula: {}/{}'.format( + unchecked, count)) + logger.info('Reactions excluded from check: {}/{}'.format( + len(exclude), count)) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/__init__.py",".py","0","0","","Python" +"Metabolic","zhanglab/psamm","psamm/commands/psammotate.py",".py","11472","270","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2019-2020 Jing Wang + +from __future__ import print_function +from collections import defaultdict +import argparse +import re +import csv +import logging +from os import path, mkdir + +from ..command import Command +from ..expression import boolean +from psamm.datasource.native import ModelWriter +from psamm.importer import write_yaml_model +logger = logging.getLogger(__name__) + + +class PsammotateCommand(Command): + """"""Generate draft model from a template using provided gene mapping. + + This function will take a provided reciprocal best hit file + """""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--rbh', metavar='file', type=argparse.FileType('r'), + help=('A two column mapping of genes from the template ' + 'organism to the target organism.')) + parser.add_argument( + '--template', type=int, + help=('The column of the RBH file where the template model ' + 'genes are listed, starts from 1.')) + parser.add_argument( + '--target', type=int, + help=('The column of the RBH file where the target ' + 'model genes are listed, starts from 1.')) + parser.add_argument( + '--ignore-na', action='store_true', + help=('Ignore the reactions that do not have gene association. ' + '(default: retain these reactions in new reactions file)')) + parser.add_argument( + '--suffix', type=str, default=None, + help='Suffix to append to end of reaction IDs and compartments.') + g = parser.add_mutually_exclusive_group() + g.add_argument( + '--export-model', type=str, default=None, + help='Path to directory for full model export. Cannot be specified' + ' with --output option.') + g.add_argument( + '--output', type=str, default='homolo_reactions', + help=('The prefix of output YAML file, ' + '(default: homolo_reactions). Cannot be specified with ' + '--export-model option.')) + super(PsammotateCommand, cls).init_parser(parser) + + def run(self): + """"""Run psammotate command"""""" + + if self._args.export_model is None: + if path.exists('{}.yaml'.format(self._args.output)): + logger.warning('File {}.yaml already exists. ' + 'Please choose a different file name ' + 'through the --output ' + 'option.'.format(self._args.output)) + quit() + elif self._args.export_model is not None: + if path.exists('{}'.format(self._args.export_model)): + logger.warning('Output directory {} already exists.'.format( + self._args.export_model)) + quit() + if self._args.suffix: + if any(i in self._args.suffix for i in [' ', '|', ':', ';', ',']): + logger.error('Special character or space found ' + 'in provided suffix') + tdict = app_reader(self._args.rbh, self._args.target - 1, + self._args.template - 1) + trans_genes_dict = model_loader(self._model, + self._args.ignore_na, tdict, + self._args.suffix) + homolo_reactions = list() + for r in self._model.reactions: + if r.id in self._model.model: + if trans_genes_dict[r][2]: + r.properties['genes'] = remove_gap( + str(trans_genes_dict[r][1])) + if self._args.suffix: + r.properties['id'] += '_{}'.format(self._args.suffix) + for cpd, v in r.equation.compounds: + cpd._compartment += '_{}'.format(self._args.suffix) + homolo_reactions.append(r) + if self._args.export_model is None: + with open(self._args.output + '.yaml', 'w') as o: + ModelWriter().write_reactions(o, homolo_reactions) + elif self._args.export_model is not None: + mkdir('{}'.format(self._args.export_model)) + reaction_list = [i.id for i in homolo_reactions] + original_reactions = [i.id for i in self._model.reactions] + for reaction in original_reactions: + self._model.reactions.discard(reaction) + for reaction in homolo_reactions: + self._model.reactions.add_entry(reaction) + compound_set = set() + for reaction in self._model.reactions: + for compound in reaction.equation.compounds: + compound_set.add(compound[0].name) + compound_removal_set = set() + for compound in self._model.compounds: + if compound.id not in compound_set: + compound_removal_set.add(compound.id) + for cpd in compound_removal_set: + self._model.compounds.discard(cpd) + exchange_del_set = set() + for key in self._model.exchange: + if key.name not in compound_set: + exchange_del_set.add(key) + for ex in exchange_del_set: + del self._model.exchange[ex] + lim_del_set = set() + for key in self._model.limits: + if key not in reaction_list: + lim_del_set.add(key) + for lim in lim_del_set: + del self._model.exchange[lim] + write_yaml_model(self._model, dest='{}'.format( + self._args.export_model), split_subsystem=False) + + +def app_reader(app_file, query, template): + '''This function will read in a gene mapping file and produce a + gene to gene dictionary. + + The input is the app_file argument that the user enters, the query genome, + which is the number of the genome that the user wishes to make a model of, + and the number of the template genome which the user wishes to use to + create the new model from. + ''' + trans_dict = defaultdict(list) + # Check what csv.reader in Python 3 takes (byte string or unicode string) + for x, row in enumerate(csv.reader(app_file, delimiter='\t')): + temp_l = [] + quer_l = [] + temp = row[template] + quer = row[query] + if temp != '-': + if ',' in temp: + temp_split = temp.split(',') + else: + temp_split = [temp] + for i in temp_split: + temp_l.append(i.strip()) + if ',' in quer: + quer_split = quer.split(',') + else: + quer_split = [quer] + for i in quer_split: + quer_l.append(i.strip()) + for i in temp_l: + for j in quer_l: + trans_dict[i].append(j) + return trans_dict + + +def model_loader(nm, ignore_na, translation_dict, suffix=None): + '''This function will translate genes in one model + based on a gene to gene mapping dictionary. + + The function takes a native model object, a true or false + ignore_na argument, and a gene mapping dictionary translation_dict + that is made by the app_reader function. The ignore_na argument + will determine if reactions with no genes will be kept in the final + translated model or not. This function will then translate the gene + associations based on the gene mapping dictionary and produce a + new set of gene associations based on the mapped associations. The + gene expressions are evaluated based on the logic to see if they should + be included in the new model. + ''' + new_translation_dict = {} + translated_genes = {} + target_genes_l = {} + target_model_reactions = [] + translation_dict.pop('-', None) + for key, value in translation_dict.items(): + if len(value) > 1: + value_s = '({})'.format(' or '.join(value)) + else: + value_s, = value + new_translation_dict[key] = value_s + for i in value: + target_genes_l[i] = True + mm = nm.create_metabolic_model() + model_rxns = [i for i in mm.reactions] + print('ReactionID\tOriginal_Genes\tTranslated_Genes\tIn_final_model') + for entry in nm.reactions: + if entry.id in model_rxns: + if entry.genes is None: + target_model_reactions.append(entry.id) + translated_genes[entry] = [None, None, + not ignore_na] + id = entry.id + if suffix is not None: + id = id + '_{}'.format(suffix) + print(u'{}\t{}\t{}\t{}'.format( + id, entry.genes, 'None', + not ignore_na)) + elif entry.genes is not None: + genes = re.sub(r'\?', '', entry.genes) + e = boolean.Expression(genes) + e_1 = e.substitute( + lambda v: new_translation_dict.get( + v.symbol, '-') != '-') + genes_1 = entry.genes + gene_list = get_gene_list(genes) + for g in gene_list: + if g in new_translation_dict: + genes = re.sub(r'\b' + g + r'\b', + new_translation_dict[g], genes) + else: + genes = re.sub(r'\b' + g + r'\b', + '-', genes) + id = entry.id + if suffix is not None: + id = id + '_{}'.format(suffix) + print(u'{}\t{}\t{}\t{}'.format( + id, entry.genes, genes, e_1.value)) + translated_genes[entry] = [genes_1, genes, e_1.value] + return translated_genes + + +def get_gene_list(genes): + '''This function is used to get a list of genes from a gene expression + ''' + gene_list = re.sub(r'[,()\']*', '', genes) + gene_list = re.sub(r'\band\b', '', gene_list) + gene_list = re.sub(r'\bor\b', '', gene_list) + gene_list = re.split(r'\s+', gene_list) # Transfer string to list + gene_list = frozenset(gene_list) + return gene_list + + +def remove_gap(string): + '''This function is used to simplify translated gene expression strings. + ''' + while True: + prev = string + string = re.sub(r'or - or', 'or', string) + string = re.sub(r' or -', '', string) + string = re.sub(r'\(-\)', '-', string) + string = re.sub(r'- or ', '', string) + string = re.sub(r'\(\)', '', string) + string = re.sub(r'\'\'', '', string) + if prev == string: + return string +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/console.py",".py","2723","71","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +from ..command import Command + + +class ConsoleCommand(Command): + """"""Start an interactive Python console with the model loaded."""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--type', choices=('python', 'ipython', 'ipython-kernel'), + default='python', help='type of console to open') + + def open_python(self, message, namespace): + """"""Open interactive python console"""""" + + # Importing readline will in some cases print weird escape + # characters to stdout. To avoid this we only import readline + # and related packages at this point when we are certain + # they are needed. + from code import InteractiveConsole + import readline + import rlcompleter + + readline.set_completer(rlcompleter.Completer(namespace).complete) + readline.parse_and_bind('tab: complete') + console = InteractiveConsole(namespace) + console.interact(message) + + def open_ipython(self, message, namespace): + from IPython.terminal.embed import InteractiveShellEmbed + console = InteractiveShellEmbed(user_ns=namespace, banner2=message) + console() + + def open_ipython_kernel(self, message, namespace): + from IPython import embed_kernel + embed_kernel(local_ns=namespace) + + def run(self): + message = ('Model has been loaded into: ""model""\n' + + 'Use ""model.create_metabolic_model() to create the' + ' low-level metabolic model representation.') + namespace = {'model': self._model} + console_type = self._args.type + + if console_type == 'python': + self.open_python(message, namespace) + elif console_type == 'ipython': + self.open_ipython(message, namespace) + elif console_type == 'ipython-kernel': + self.open_ipython_kernel(message, namespace) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/model_mapping.py",".py","27088","678","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2018-2020 Jing Wang +# Copyright 2020-2021 Elysha Sameth + +# -*- coding: utf-8 -*- + +""""""Generate a common model for two distinct metabolic models."""""" + +from __future__ import print_function, division + +from builtins import object, input +import operator +from itertools import product +import time +import sys + +import psamm.bayesian as bayesian +import psamm.translate_id as tr_id +import psamm.manual_curation as curation +from psamm.util import mkdir_p +from psamm.datasource.native import ModelReader +from psamm.command import Command +from psamm.datasource.reaction import Compound + + +class ModelMappingCommand(Command): + """"""Generate a common model for two distinct metabolic models."""""" + + @classmethod + def init_parser(cls, parser): + """"""Initialize argument parser"""""" + subparsers = parser.add_subparsers(title=""Tools"") + + # model mapping subcommand + parser_mm = subparsers.add_parser( + 'map', help='Bayesian model mapping') + parser_mm.set_defaults(which='mm') + parser_mm.add_argument( + '--dest-model', type=str, required=True, help='Model to map to') + parser_mm.add_argument( + '--compound-map', type=str, nargs='?', + help='Actual compound mapping, evaluation only') + parser_mm.add_argument( + '--reaction-map', type=str, nargs='?', + help='Actual reaction mapping, evaluation only') + parser_mm.add_argument( + '-c', '--consistency-check', action='store_true', + help=( + 'Check the consistency of compound id ' + 'between compounds.yaml and reactions.yaml')) + parser_mm.add_argument( + '-n', '--nproc', type=int, action='store', default=1, + help='Number of processes to use (default = 1)') + parser_mm.add_argument( + '-o', '--outpath', type=str, + action='store', default='.', + help=( + 'Path to store output files ' + '(default = current position)')) + parser_mm.add_argument( + '--threshold-compound', type=float, default=0, + help=( + 'likelihood threshold for compound mapping ' + '(default = 0)')) + parser_mm.add_argument( + '--threshold-reaction', type=float, default=0, + help=( + 'likelihood threshold for reaction mapping ' + '(default = 0)')) + parser_mm.add_argument( + '--map-compound-kegg', action='store_true', + help='Compare KEGG id during compound mapping') + parser_mm.add_argument( + '--map-reaction-gene', action='store_true', + help='Compare gene list during reaction mapping') + parser_mm.add_argument( + '--raw', action='store_true', + help=( + 'Output raw pairwise mapping results as well, ' + 'may be very big with large models')) + parser_mm.add_argument( + '--log', action='store_true', + help=( + 'Output log file of the p_match and p_no_match ' + 'for each feature, ' + 'may be very big with large models')) + parser_mm.add_argument( + '--compartment-map-file', type=str, + help=( + 'A tab delimited file (.tsv) listing the compartment ids of ' + 'query model in the first column, and the corresponding ' + 'compartment ids of dest model in the second column. Required ' + 'if the compartment ids in the two models are not consistent.' + ) + ) + parser_mm.add_argument( + '--gene-map-file', type=str, + help=( + 'A tab delimited file (.tsv) listing the gene ids of ' + 'query model in the first column, and the corresponding ' + 'gene ids of dest model in the second column. Required ' + 'if the gene ids in the two models are not consistent.' + ) + ) + + # manual curation subcommand + parser_c = subparsers.add_parser( + 'manual_curation', + help='Interactive mode to check mapping result') + parser_c.set_defaults(which='curation') + parser_c.add_argument( + '--dest-model', type=str, required=True, help='Model to map to') + parser_c.add_argument( + '--compound-map', type=str, required=True, + help='Compound model mapping result') + parser_c.add_argument( + '--reaction-map', type=str, required=True, + help='Reaction model mapping result') + parser_c.add_argument( + '--curated-compound-map', type=str, required=True, + help=( + 'File to store curated compound mapping, if file exists, ' + 'resume previous curation')) + parser_c.add_argument( + '--curated-reaction-map', type=str, required=True, + help=( + 'File to store curated reaction mapping, if file exists, ' + 'resume previous curation')) + parser_c.add_argument( + '--compartment-map', type=str, + help=( + 'A tab delimited file (.tsv) listing the compartment ids of ' + 'query model in the first column, and the corresponding ' + 'compartment ids of dest model in the second column. Required ' + 'if the compartment ids in the two models are not consistent.' + ) + ) + parser_c.add_argument( + '--compound-only', action='store_true', + help='Set to only curate compound maps.') + + # translate id subcommand + parser_t = subparsers.add_parser( + 'translate_id', help='Translate ids based on mapping result') + parser_t.set_defaults(which='translateid') + parser_t.add_argument( + '--compound-map', type=str, required=True, + help=( + 'Tab-delimited table, the first two columns store the ' + 'original and target ids')) + parser_t.add_argument( + '--reaction-map', type=str, required=True, + help=( + 'Tab-delimited table, the first two columns store the ' + 'original and target ids')) + parser_t.add_argument( + '--compartment-map', type=str, required=False, + help=( + 'Tab-delimited table, the first two columns store the ' + 'original and target ids')) + parser_t.add_argument( + '-o', '--outpath', type=str, + action='store', default='.', + help=( + 'Path to store output files ' + '(default = current position)')) + + def run(self): + """"""Run model mapping command."""""" + + which_command = self._args.which + if which_command == 'mm': + self._model_mapping() + if which_command == 'translateid': + self._translate_id() + if which_command == 'curation': + self._curation() + + def _model_mapping(self): + """"""Run model mapping"""""" + # Parse models + model1 = ModelReader.reader_from_path( + self._args.model).create_model() + model2 = ModelReader.reader_from_path( + self._args.dest_model).create_model() + + # Check if any compound charge is not integer + invalid_cpd = [] + for compound in model1.compounds: + result = bayesian.check_cpd_charge(compound, model1.name) + if not result: + invalid_cpd.append(compound.id) + for compound in model2.compounds: + result = bayesian.check_cpd_charge(compound, model2.name) + if not result: + invalid_cpd.append(compound.id) + if len(invalid_cpd) != 0: + quit() + + # Read model into internal format + model1 = bayesian.MappingModel(model1) + model2 = bayesian.MappingModel(model2) + + # Model summaries + model1.print_summary() + print('\n') + model2.print_summary() + print('\n') + + # Load actual model mappings + actual_compound_mapping = None + if self._args.compound_map is not None: + with open(self._args.compound_map, 'r') as f: + actual_compound_mapping = dict(read_mapping_file(f)) + + actual_reaction_mapping = None + if self._args.reaction_map is not None: + with open(self._args.reaction_map, 'r') as f: + actual_reaction_mapping = dict(read_mapping_file(f)) + + # Load compartment mapping + compartment_map = {} + if self._args.compartment_map_file is not None: + with open(self._args.compartment_map_file, 'r') as f: + for row in f: + source, target = row.strip().split() + compartment_map[source] = target + + # Load gene mapping + gene_map = {} + if self._args.gene_map_file is not None: + with open(self._args.gene_map_file, 'r') as f: + for row in f: + source, target = row.strip().split() + gene_map[source] = target + + # Check models + if (not (model1.check_reaction_compounds() and + model2.check_reaction_compounds())): + quit(( + '\nError: ' + 'equations have something not listed in compounds.yaml, ' + 'please check it!')) + + mkdir_p(self._args.outpath) + + if actual_compound_mapping is not None: + mkdir_p(self._args.outpath + '/roc') + + # Bayesian classifier + print('Using %i processes...' % (self._args.nproc)) + t = time.time() + cpd_bayes_pred = bayesian.BayesianCompoundPredictor( + model1, model2, self._args.nproc, self._args.outpath, + log=self._args.log, kegg=self._args.map_compound_kegg) + print( + 'It took %.2f seconds to calculate compound mapping...' + % (time.time() - t)) + + print('Writing output...') + sys.stdout.flush() + t = time.time() + # Write out ROC curve results + if actual_compound_mapping is not None: + with open(self._args.outpath + + '/roc/compound_bayes.tsv', 'w') as f: + write_roc_curve(f, cpd_bayes_pred.model1.compounds, + cpd_bayes_pred.model2.compounds, + cpd_bayes_pred, + actual_compound_mapping) + + # Parse and output raw mapping + if self._args.raw: + cpd_bayes_pred.get_raw_map().to_csv( + self._args.outpath + '/bayes_compounds.tsv', sep='\t', + encoding='utf-8') + + # Output best mapping + compound_best = cpd_bayes_pred.get_best_map( + self._args.threshold_compound) + compound_best.to_csv( + self._args.outpath + '/bayes_compounds_best.tsv', sep='\t', + encoding='utf-8') + print('It took %.2f seconds to write output...' % (time.time() - t)) + sys.stdout.flush() + + # Bayesian classifier + t = time.time() + rxn_bayes_pred = bayesian.BayesianReactionPredictor( + model1, model2, compound_best.loc[:, 'p'], + self._args.nproc, self._args.outpath, + log=self._args.log, gene=self._args.map_reaction_gene, + compartment_map=compartment_map, gene_map=gene_map) + print( + 'It took %.2f seconds to calculate reaction mapping...' + % (time.time() - t)) + + print('Writing output...') + sys.stdout.flush() + t = time.time() + # Write out ROC curve results + if actual_reaction_mapping is not None: + with open(self._args.outpath + + '/roc/reaction_bayes.tsv', 'w') as f: + write_roc_curve(f, rxn_bayes_pred.model1.reactions, + rxn_bayes_pred.model2.reactions, + rxn_bayes_pred, + actual_reaction_mapping) + + # Parse and output raw mapping + if self._args.raw: + rxn_bayes_pred.get_raw_map().to_csv( + self._args.outpath + '/bayes_reactions.tsv', sep='\t', + encoding='utf-8') + + # Output best mapping + reaction_best = rxn_bayes_pred.get_best_map( + self._args.threshold_reaction) + reaction_best.to_csv( + self._args.outpath + '/bayes_reactions_best.tsv', sep='\t', + encoding='utf-8') + print('It took %.2f seconds to write output...' % (time.time() - t)) + sys.stdout.flush() + + def _curation(self): + # read models + model1 = ModelReader.reader_from_path(self._args.model) + model1 = model1.create_model() + model2 = ModelReader.reader_from_path(self._args.dest_model) + model2 = model2.create_model() + + # initiate curator + curator = curation.Curator( + self._args.compound_map, self._args.reaction_map, + self._args.curated_compound_map, self._args.curated_reaction_map) + + # read compartment map + compartment_map = {} + if self._args.compartment_map is not None: + with open(self._args.compartment_map) as f: + for row in f: + old, new = row.strip().split() + compartment_map[old] = new + + if self._args.compound_only: + self._curate_compound(curator, model1, model2) + else: + self._curate_reaction(curator, model1, model2, compartment_map) + + def _curate_reaction(self, curator, model1, model2, compartment_map): + print('Starting to do manual curation...\n') + print('Type ""stop"" to stop\n') + # iterate through reaction mapping + for rmap in curator.reaction_map.iterrows(): + # skip already curated reactions + if (curator.reaction_checked(rmap[0]) or + curator.reaction_ignored(rmap[0][0])): + continue + print('You have mapped %i reactions. ' + 'There are %i reactions unmapped.' + % (curator.num_curated_reactions, + curator.num_curated_reactions_left)) + print('\n') + # check the compound mapping in current reaction + compounds = curation.search_reaction(model1, [rmap[0][0]]) + compounds = [c.name for c in next(compounds)] + dest_compounds = curation.search_reaction(model2, [rmap[0][1]]) + dest_compounds = [c.name for c in next(dest_compounds)] + print('\n', '*' * 60, '\n') + print('Below are the compound mapping involved:\n') + for compound in compounds: + for cmap in curator.compound_map.loc[compound].iterrows(): + if (cmap is None or + cmap[0] not in dest_compounds or + curator.compound_checked((compound, cmap[0])) or + curator.compound_ignored(compound)): + continue + print('You have mapped %i compounds. ' + 'There are %i compounds unmapped.' + % (curator.num_curated_compounds, + curator.num_curated_compounds_left)) + print('\n') + print('-' * 30) + print(cmap[1]) + print('-' * 30) + print('\n') + curation.search_compound(model1, [compound]) + curation.search_compound(model2, [cmap[0]]) + # waiting for legal curation input + while True: + ask = input( + ('True compound match? (y/n/ignore/save/stop, ' + 'type ignore to ignore this compound in future, ' + 'type save to save current progress, ' + 'type stop to save and exit): ')) + if ask.lower() == 'n': + curator.add_mapping( + (compound, cmap[0]), + 'c', + False + ) + break + if ask.lower() == 'y': + curator.add_mapping( + (compound, cmap[0]), + 'c', + True + ) + curator.num_curated_compounds += 1 + curator.num_curated_compounds_left -= 1 + break + if ask.lower() == 'ignore': + curator.add_ignore(compound, 'c') + break + if ask.lower() == 'stop': + curator.save() + exit(0) + if ask.lower() == 'save': + curator.save() + + print('\n') + print('You have mapped %i reactions. ' + 'There are %i reactions unmapped.' + % (curator.num_curated_reactions, + curator.num_curated_reactions_left)) + print('\n') + print('Here is the reaction mapping:') + print('-' * 30) + print(rmap[1]) + print('-' * 30) + print('\n') + compounds = curation.search_reaction(model1, [rmap[0][0]]) + compounds = [c for c in next(compounds)] + dest_compounds = curation.search_reaction(model2, [rmap[0][1]]) + dest_compounds = [c for c in next(dest_compounds)] + print(('These two reactions have the following curated compound ' + 'pairs:\n')) + count = 0 + compounds_curated = set() + dest_compounds_curated = set() + for compound in compounds: + if compound.name in curator.curated_compound_map.index: + for cmap in curator.curated_compound_map.loc[ + compound.name].iterrows(): + compartment = compartment_map.get( + compound.compartment, compound.compartment + ) + dest_compound = Compound(cmap[0], compartment) + if dest_compound in dest_compounds: + print(compound, dest_compound, cmap[1]['p']) + compounds_curated.add(compound) + dest_compounds_curated.add(dest_compound) + count += 1 + print('\n') + print('%i compounds in %s' % (len(compounds), rmap[0][0])) + unpaired = set(compounds) - compounds_curated + if len(unpaired) > 0: + print('Unpaired compounds: %s\n' % ', '.join( + [str(c) for c in unpaired])) + print('%i compounds in %s' % (len(dest_compounds), rmap[0][1])) + unpaired = set(dest_compounds) - dest_compounds_curated + if len(unpaired) > 0: + print('Unpaired compounds: %s\n' % ', '.join( + [str(c) for c in unpaired])) + print('%i curated compound pairs\n' % count) + ask = '' + # waiting for legal curation input + while ask not in ['y', 'n', 'stop']: + ask = input( + ('True reaction match? (y/n/ignore/save/stop, ' + 'type ignore to ignore this reaction in future, ' + 'type save to save current progress, ' + 'type stop to save and exit): ') + ) + if ask.lower() == 'n': + curator.add_mapping(rmap[0], 'r', False) + break + if ask.lower() == 'y': + curator.add_mapping(rmap[0], 'r', True) + curator.num_curated_reactions += 1 + curator.num_curated_reactions_left -= 1 + break + if ask.lower() == 'ignore': + curator.add_ignore(rmap[0][0], 'r') + break + if ask.lower() == 'stop': + curator.save() + exit(0) + if ask.lower() == 'save': + curator.save() + print('\n', '=' * 60, '\n') + curator.save() + + def _curate_compound(self, curator, model1, model2): + for cmap in curator.compound_map.iterrows(): + if (curator.compound_checked(cmap[0]) or + curator.compound_ignored(cmap[0][0])): + continue + print('You have mapped %i compounds. ' + 'There are %i compounds unmapped.' + % (curator.num_curated_compounds, + curator.num_curated_compounds_left)) + print('-' * 30) + print(cmap[1]) + print('-' * 30) + print('\n') + curation.search_compound(model1, [cmap[0][0]]) + curation.search_compound(model2, [cmap[0][1]]) + # waiting for legal curation input + while True: + ask = input( + ('True compound match? (y/n/ignore/save/stop, ' + 'type ignore to ignore this compound in future, ' + 'type save to save current progress, ' + 'type stop to save and exit): ')) + if ask.lower() == 'n': + curator.add_mapping( + cmap[0], + 'c', + False + ) + break + if ask.lower() == 'y': + curator.add_mapping( + cmap[0], + 'c', + True + ) + curator.num_curated_compounds += 1 + curator.num_curated_compounds_left -= 1 + break + if ask.lower() == 'ignore': + curator.add_ignore(cmap[0][0], 'c') + break + if ask.lower() == 'stop': + curator.save() + exit(0) + if ask.lower() == 'save': + curator.save() + print('\n', '=' * 60, '\n') + + def _translate_id(self): + """"""Translate ids"""""" + # make output dir + mkdir_p(self._args.outpath) + + # read mapping files + cpd_mapping_id = tr_id.read_mapping(self._args.compound_map) + rxn_mapping_id = tr_id.read_mapping(self._args.reaction_map) + if self._args.compartment_map is not None: + compartment_mapping_id = tr_id.read_mapping( + self._args.compartment_map) + else: + compartment_mapping_id = None + + # make output model + out_nm = tr_id.TranslatedModel( + self._model, + cpd_mapping_id, + rxn_mapping_id, + compartment_mapping_id + ) + + out_nm.write_model(dest=self._args.outpath, split_subsystem=False) + + +def read_mapping_file(f): + """"""Read a mapping file and yield source, target-set tuples"""""" + for line in f: + source, target = line.strip().split(None, 1) + if target == '-': + target_set = None + else: + target_set = set(s for s in target.split(',')) + yield source, target_set + + +class Confusion(object): + """"""Confusion matrix."""""" + + def __init__(self, tp=0, tn=0, fp=0, fn=0): + self.tp, self.tn, self.fp, self.fn = tp, tn, fp, fn + + @property + def positive(self): + return self.tp + self.fn + + @property + def negative(self): + return self.fp + self.tn + + @property + def total(self): + return self.tp + self.tn + self.fp + self.fn + + @property + def tp_rate(self): + return self.tp if self.tp == 0 else self.tp / self.positive + + @property + def fp_rate(self): + return self.fp if self.fp == 0 else self.fp / self.negative + + @property + def specificity(self): + return self.tn if self.tn == 0 else self.tn / self.negative + + @property + def precision(self): + return self.tp if self.tp == 0 else self.tp / (self.tp + self.fp) + + @property + def accuracy(self): + return (self.tp + self.tn) / self.total + + @property + def balanced_accuracy(self): + return (self.tp_rate + self.specificity) / 2.0 + + @property + def informedness(self): + return self.tp_rate + self.specificity - 1.0 + + def __repr__(self): + return 'Confusion(tp={}, tn={}, fp={}, fn={})'.format( + self.tp, self.tn, self.fp, self.fn) + + +def evaluate_roc_points(model1, model2, predictor, actual): + """"""Return confusion matrix for each point on the ROC curve"""""" + + # Count total positive and negative pairs + positive, negative = 0, 0 + for e1, e2 in product(model1, model2): + correct = e1 in actual and actual[e1] is not None and e2 in actual[e1] + positive += correct + negative += not correct + + tp, fp = 0, 0 + p_prev = None + for pair, p in sorted((((e1, e2), predictor.map(e1, e2)) + for e1, e2 in product(model1, model2)), + key=operator.itemgetter(1), reverse=True): + e1, e2 = pair + if p != p_prev: + yield p, Confusion( + tp=tp, fp=fp, fn=positive - tp, tn=negative - fp) + p_prev = p + correct = e1 in actual and actual[e1] is not None and e2 in actual[e1] + tp += correct + fp += not correct + + cf = Confusion(tp=tp, fp=fp, fn=positive - tp, tn=negative - fp) + yield -float('inf'), cf + + +def write_roc_curve(out_file, model1, model2, predictor, actual): + """"""Calculate ROC points and write them to file"""""" + for p, conf in evaluate_roc_points(model1, model2, + predictor, actual): + out_file.write('{}\t{}\t{}\t{}\t{}\n'.format( + p, conf.tp, conf.tn, conf.fp, conf.fn)) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/randomsparse.py",".py","5120","130","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2016 Chao Liu +from __future__ import unicode_literals + +import logging + +from ..command import (Command, MetabolicMixin, LoopRemovalMixin, + ObjectiveMixin, SolverCommandMixin) +from .. import fluxanalysis, util +from .. import randomsparse + +logger = logging.getLogger(__name__) + + +class RandomSparseNetworkCommand(MetabolicMixin, LoopRemovalMixin, + ObjectiveMixin, SolverCommandMixin, Command): + """"""Find a random minimal network of model reactions. + + Given a reaction to optimize and a threshold, delete reactions randomly + until the flux of the reaction to optimize falls under the threshold. + Keep deleting reactions until no more reactions can be deleted. By default + this uses standard FBA (not tFBA). Since the internal fluxes are irrelevant + the FBA and tFBA are equivalent for this purpose. + + The threshold can be specified as an absolute flux (e.g. '1.23') or a + relative flux of the full model flux (e.g. '40.5%'). + """""" + + _supported_loop_removal = ['none', 'tfba'] + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + 'threshold', help='Threshold of objective reaction ' + 'flux. Can be an absolute flux value ' + '(0.25) or percentage of maximum ' + 'biomass', + type=util.MaybeRelative) + parser.add_argument( + '--type', help='Type of deletion to perform', + choices=['reactions', 'exchange', 'genes', 'rxgenes'], type=str, + required=True) + super(RandomSparseNetworkCommand, cls).init_parser(parser) + + def run(self): + reaction = self._get_objective() + if not self._mm.has_reaction(reaction): + self.fail( + 'Specified reaction is not in model: {}'.format(reaction)) + + loop_removal = self._get_loop_removal_option() + enable_tfba = loop_removal == 'tfba' + if not enable_tfba: + solver = self._get_solver() + else: + solver = self._get_solver(integer=True) + + p = fluxanalysis.FluxBalanceProblem(self._mm, solver) + + if enable_tfba: + p.add_thermodynamic() + + try: + p.maximize(reaction) + except fluxanalysis.FluxBalanceError as e: + self.report_flux_balance_error(e) + + threshold = self._args.threshold + if threshold.relative: + threshold.reference = p.get_flux(reaction) + + flux_threshold = float(threshold) + + logger.info('Flux threshold for {} is {}'.format( + reaction, flux_threshold)) + + if self._args.type == 'exchange': + strategy = randomsparse.ReactionDeletionStrategy( + self._mm, randomsparse.get_exchange_reactions(self._mm)) + entity = 'reactions' + elif self._args.type == 'reactions': + strategy = randomsparse.ReactionDeletionStrategy( + self._mm) + entity = 'reactions' + elif self._args.type == 'rxgenes': + strategy = randomsparse.GeneDeletionStrategy( + self._mm, randomsparse.get_gene_associations(self._model)) + entity = 'genes' + else: + strategy = randomsparse.GeneDeletionStrategy( + self._mm, randomsparse.get_gene_associations(self._model)) + entity = 'genes' + + if self._args.type == 'rxgenes': + essential, deleted = randomsparse.random_sparse_return_all( + strategy, p, reaction, flux_threshold) + for i in self._mm.reactions: + if i in deleted: + print('{}\t{}'.format(i, 0)) + else: + print('{}\t{}'.format(i, 1)) + else: + essential, deleted = randomsparse.random_sparse( + strategy, p, reaction, flux_threshold) + + logger.info('Essential {}: {}/{}'.format( + entity, len(essential), len(strategy.entities))) + logger.info('Deleted {}: {}/{}'.format( + entity, len(deleted), len(strategy.entities))) + + for entity_id in sorted(strategy.entities): + value = 0 if entity_id in deleted else 1 + print('{}\t{}'.format(entity_id, value)) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/fastgapfill.py",".py","4730","123","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import argparse +import logging + +from ..command import Command, MetabolicMixin, SolverCommandMixin +from ..fastgapfill import fastgapfill +from ..gapfilling import create_extended_model + +logger = logging.getLogger(__name__) + + +class FastGapFillCommand(MetabolicMixin, SolverCommandMixin, Command): + """"""Run the FastGapFill gap-filling algorithm on model."""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--subset', metavar='file', type=argparse.FileType('r'), + help='specify core reaction subset to use') + parser.add_argument( + '--penalty', metavar='file', type=argparse.FileType('r'), + help='List of penalty scores for database reactions') + parser.add_argument( + '--db-penalty', metavar='penalty', type=float, + help='Default penalty for database reactions') + parser.add_argument( + '--tp-penalty', metavar='penalty', type=float, + help='Default penalty for transport reactions') + parser.add_argument( + '--ex-penalty', metavar='penalty', type=float, + help='Default penalty for exchange reactions') + parser.add_argument( + '--epsilon', type=float, help='Threshold for Fastcore', + default=1e-5) + super(FastGapFillCommand, cls).init_parser(parser) + + def run(self): + """"""Run FastGapFill command"""""" + + # Create solver + solver = self._get_solver() + + # Load compound information + def compound_name(id): + if id not in self._model.compounds: + return id + return self._model.compounds[id].properties.get('name', id) + + # TODO: The exchange and transport reactions have tuple names. This + # means that in Python 3 the reactions can no longer be directly + # compared (e.g. while sorting) so define this helper function as a + # workaround. + def reaction_key(r): + return r if isinstance(r, tuple) else (r,) + + # Calculate penalty if penalty file exists + penalties = {} + for id in sorted(self._mm.reactions): + penalties[id] = 0 + if self._args.penalty is not None: + for line in self._args.penalty: + line, _, comment = line.partition('#') + line = line.strip() + if line == '': + continue + rxnid, penalty = line.split(None, 1) + penalties[rxnid] = float(penalty) + + model_extended, weights = create_extended_model( + self._model, + db_penalty=self._args.db_penalty, + ex_penalty=self._args.ex_penalty, + tp_penalty=self._args.tp_penalty, + penalties=penalties) + + epsilon = self._args.epsilon + core = set() + if self._args.subset is None: + for r in self._mm.reactions: + if not self._mm.is_exchange(r): + core.add(r) + else: + for line in self._args.subset: + line = line.strip() + if line == '': + continue + core.add(line) + induced = fastgapfill(model_extended, core, weights=weights, + epsilon=epsilon, solver=solver) + + for reaction_id in sorted(self._mm.reactions): + rx = self._mm.get_reaction(reaction_id) + rxt = rx.translated_compounds(compound_name) + print('{}\t{}\t{}\t{}'.format( + reaction_id, 'Model', weights[reaction_id], rxt)) + + for rxnid in sorted(induced, key=reaction_key): + if self._mm.has_reaction(rxnid): + continue + rx = model_extended.get_reaction(rxnid) + rxt = rx.translated_compounds(compound_name) + print('{}\t{}\t{}\t{}'.format( + rxnid, 'Add', weights.get(rxnid), rxt)) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/chargecheck.py",".py","3117","84","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import math +import logging + +from ..command import Command, FilePrefixAppendAction, convert_to_unicode +from ..balancecheck import charge_balance + +logger = logging.getLogger(__name__) + + +class ChargeBalanceCommand(Command): + """"""Check whether compound charge is balanced. + + Balanced reactions are those reactions where the total charge + is consistent on the left and right side of the reaction equation. + Reactions that are not balanced will be printed out. + """""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--exclude', metavar='reaction', type=convert_to_unicode, + action=FilePrefixAppendAction, + default=[], help='Exclude reaction from balance check') + parser.add_argument( + '--epsilon', metavar='epsilon', type=float, default=1e-6, + help='Threshold for charge imbalance to be considered zero' + ) + super(ChargeBalanceCommand, cls).init_parser(parser) + + def run(self): + """"""Run charge balance command"""""" + + # Load compound information + def compound_name(id): + if id not in self._model.compounds: + return id + return self._model.compounds[id].properties.get('name', id) + + # Create a set of excluded reactions + exclude = set(self._args.exclude) + count = 0 + unbalanced = 0 + unchecked = 0 + for reaction, charge in charge_balance(self._model): + count += 1 + + if reaction.id in exclude or reaction.equation is None: + continue + + if math.isnan(charge): + logger.debug('Not checking reaction {};' + ' missing charge'.format(reaction.id)) + unchecked += 1 + elif abs(charge) > self._args.epsilon: + unbalanced += 1 + rxt = reaction.equation.translated_compounds(compound_name) + print('{}\t{}\t{}'.format(reaction.id, charge, rxt)) + + logger.info('Unbalanced reactions: {}/{}'.format(unbalanced, count)) + logger.info('Unchecked reactions due to missing charge: {}/{}'.format( + unchecked, count)) + logger.info('Reactions excluded from check: {}/{}'.format( + len(exclude), count)) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/fluxcoupling.py",".py","6753","163","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import logging + +from ..command import (Command, SolverCommandMixin, MetabolicMixin, + ParallelTaskMixin) +from .. import fluxanalysis, fluxcoupling + +logger = logging.getLogger(__name__) + + +class FluxCouplingCommand(MetabolicMixin, SolverCommandMixin, + ParallelTaskMixin, Command): + """"""Find flux coupled reactions in the model. + + This identifies any reaction pairs where the flux of one reaction + constrains the flux of another reaction. The reactions can be coupled in + three distinct ways depending on the ratio between the reaction fluxes. + The reactions can be fully coupled (the ratio is static and non-zero); + partially coupled (the ratio is bounded and non-zero); or directionally + coupled (the ratio is non-zero). + """""" + + def run(self): + solver = self._get_solver() + + max_reaction = self._model.biomass_reaction + if max_reaction is None: + self.fail('The biomass reaction was not specified') + + try: + fba_fluxes = dict(fluxanalysis.flux_balance( + self._mm, max_reaction, tfba=False, solver=solver)) + except fluxanalysis.FluxBalanceError as e: + self.report_flux_balance_error(e) + optimum = fba_fluxes[max_reaction] + + handler_args = self._mm, {max_reaction: 0.999 * optimum}, solver + executor = self._create_executor( + FluxCouplingTaskHandler, handler_args, cpus_per_worker=2) + + self._coupled = {} + self._groups = [] + + def iter_reaction_pairs(): + reactions = sorted(self._mm.reactions) + for i, reaction1 in enumerate(reactions): + if reaction1 in self._coupled: + continue + + for reaction2 in reactions[i+1:]: + if (reaction2 in self._coupled and + (self._coupled[reaction2] == + self._coupled.get(reaction1))): + continue + + yield reaction1, reaction2 + + with executor: + for task, bounds in executor.imap_unordered( + iter_reaction_pairs(), 16): + reaction1, reaction2 = task + self._check_reactions(reaction1, reaction2, bounds) + + executor.join() + + logger.info('Coupled groups:') + for i, group in enumerate(self._groups): + if group is not None: + logger.info('{}: {}'.format(i, ', '.join(sorted(group)))) + + def _check_reactions(self, reaction1, reaction2, bounds): + logger.debug('Solved for {}, {}'.format(reaction1, reaction2)) + lower, upper = bounds + + logger.debug('Result: {}, {}'.format(lower, upper)) + + coupling = fluxcoupling.classify_coupling((lower, upper)) + if coupling in (fluxcoupling.CouplingClass.DirectionalForward, + fluxcoupling.CouplingClass.DirectionalReverse): + text = 'Directional, v1 / v2 in [{}, {}]'.format(lower, upper) + if (coupling == fluxcoupling.CouplingClass.DirectionalReverse and + not self._mm.is_reversible(reaction1) and lower == 0.0): + return + elif coupling == fluxcoupling.CouplingClass.Full: + text = 'Full: v1 / v2 = {}'.format(lower) + self._couple_reactions(reaction1, reaction2) + elif coupling == fluxcoupling.CouplingClass.Partial: + text = 'Partial: v1 / v2 in [{}; {}]'.format(lower, upper) + self._couple_reactions(reaction1, reaction2) + else: + return + + print('{}\t{}\t{}\t{}\t{}'.format( + reaction1, reaction2, lower, upper, text)) + + def _couple_reactions(self, reaction1, reaction2): + logger.debug('Couple {} and {}'.format(reaction1, reaction2)) + + if reaction1 in self._coupled and reaction2 in self._coupled: + if self._coupled[reaction1] == self._coupled[reaction2]: + return + logger.debug('Merge groups {}, {}'.format( + self._coupled[reaction1], self._coupled[reaction2])) + group_index = len(self._groups) + group = (self._groups[self._coupled[reaction1]] | + self._groups[self._coupled[reaction2]]) + logger.debug('New group is {}: {}'.format( + group_index, sorted(group))) + self._groups.append(group) + self._groups[self._coupled[reaction1]] = None + self._groups[self._coupled[reaction2]] = None + for reaction in group: + self._coupled[reaction] = group_index + elif reaction1 in self._coupled: + group_index = self._coupled[reaction1] + group = self._groups[group_index] + logger.debug('Put {} into existing group {}: {}'.format( + reaction2, self._coupled[reaction1], group)) + self._coupled[reaction2] = group_index + group.add(reaction2) + elif reaction2 in self._coupled: + group_index = self._coupled[reaction2] + group = self._groups[group_index] + logger.debug('Put {} into existing group {}: {}'.format( + reaction1, self._coupled[reaction2], group)) + self._coupled[reaction1] = group_index + group.add(reaction1) + else: + group = set([reaction1, reaction2]) + group_index = len(self._groups) + logger.debug('Creating new group {}'.format(group_index)) + self._coupled[reaction1] = group_index + self._coupled[reaction2] = group_index + self._groups.append(group) + + +class FluxCouplingTaskHandler(object): + def __init__(self, model, thresholds, solver): + self._problem = fluxcoupling.FluxCouplingProblem( + model, thresholds, solver) + + def handle_task(self, reaction_1, reaction_2): + return self._problem.solve(reaction_1, reaction_2) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/gimme.py",".py","12546","313","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2019-2020 Keith Dufault-Thompson + +""""""Implementation of Flux Balance Analysis."""""" + +from __future__ import unicode_literals + +import logging +import csv +from os import mkdir, path +from ..lpsolver import lp +import argparse +from six import iteritems +from ..expression import boolean +from ..lpsolver.lp import Expression, ObjectiveSense +from ..fluxanalysis import FluxBalanceProblem +from ..command import (ObjectiveMixin, SolverCommandMixin, + MetabolicMixin, Command) +from psamm.importer import write_yaml_model +from ..util import MaybeRelative + +logger = logging.getLogger(__name__) + + +class GimmeCommand(MetabolicMixin, ObjectiveMixin, + SolverCommandMixin, Command): + """"""Subset a metabolic model based on gene expression data."""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--biomass-threshold', help='Threshold of objective reaction ' + 'flux. Can be an absolute flux value ' + 'or percentage with percent sign.', + type=MaybeRelative, default=MaybeRelative('100%')) + parser.add_argument( + '--expression-threshold', type=float, + help='Threshold for gene expression') + parser.add_argument( + '--transcriptome-file', type=argparse.FileType('r'), + help='Two column file of gene ID to expression') + parser.add_argument('--detail', action='store_true', + help='Show model statistics.') + parser.add_argument( + '--export-model', type=str, default=None, + help='Path to directory for full model export.') + super(GimmeCommand, cls).init_parser(parser) + + def run(self): + solver = self._get_solver() + model = self._model + mm = model.create_metabolic_model() + + if self._args.export_model is not None: + if path.exists('{}'.format(self._args.export_model)): + logger.warning('Output directory {} already exists.'.format( + self._args.export_model)) + quit() + + base_gene_dict = {} + for rxn in model.reactions: + base_gene_dict[rxn.id] = rxn.genes + + threshold_value = parse_transcriptome_file( + self._args.transcriptome_file, + self._args.expression_threshold) + + exchange_exclude = [rxn for rxn in mm.reactions + if mm.is_exchange(rxn)] + exchange_exclude.append(self._get_objective()) + mm_irreversible, reversible_gene_assoc, split_rxns, _ = \ + mm.make_irreversible(base_gene_dict, + exclude_list=exchange_exclude) + + p = FluxBalanceProblem(mm_irreversible, solver) + + final_model, used_exchange, below_threshold_ids, \ + incon_score = \ + solve_gimme_problem(p, mm_irreversible, + self._get_objective(), + reversible_gene_assoc, + split_rxns, threshold_value, + self._args.biomass_threshold) + + print('# internal Reactions') + for reaction in sorted(final_model): + print(reaction) + print('# Exchange Reactions') + for reaction in used_exchange: + print(reaction) + used_below = str(len([x for x in + below_threshold_ids if x in final_model])) + below = str(len(below_threshold_ids)) + if self._args.detail: + logger.info('Used {} below threshold reactions out of {} total ' + 'below threshold reactions'.format(used_below, below)) + logger.info('Inconsistency Score: {}'.format(incon_score)) + if self._args.export_model: + mkdir('{}'.format(self._args.export_model)) + reactions_to_discard = [] + for reaction in self._model.reactions: + if reaction.id not in final_model: + reactions_to_discard.append(reaction.id) + for rid in reactions_to_discard: + self._model.reactions.discard(rid) + compound_set = set() + for reaction in self._model.reactions: + for compound in reaction.equation.compounds: + compound_set.add(compound[0].name) + compounds_to_discard = [] + for compound in self._model.compounds: + if compound.id not in compound_set: + compounds_to_discard.append(compound.id) + for cid in compounds_to_discard: + self._model.compounds.discard(cid) + exchanges_to_discard = [] + for key in self._model.exchange: + if key.name not in compound_set: + exchanges_to_discard.append(key) + for key in exchanges_to_discard: + del self._model.exchange[key] + limits_to_discard = [] + for key in self._model.limits: + if key not in final_model: + limits_to_discard.append(key) + for key in limits_to_discard: + del self._model.limits[key] + write_yaml_model(self._model, dest=self._args.export_model, + split_subsystem=False) + + +def solve_gimme_problem(problem, mm, biomass, reversible_gene_assoc, + split_rxns, transcript_values, threshold): + """"""Formulates and Solves a GIMME model. + + Implementation of the GIMME algorithm (Becker and Pallson 2008). + Accepts an irreversible metabolic model, LP problem, and GIMME specific + data. Will add in relevant GIMME constraints to the LP problem and + generates a contextualized model based on the media constraints and the + transcriptome data provided. + + Args: + problem: :class:`FluxBalanceProblem` to solve. + mm: An irreversible metabolic model. + biomass: Biomass reaction ID. + reversible_gene_assoc: A dictionary of gene IDs from make_irreversible. + split_rxns: A set of tuples of reaction IDs from make_irreversible. + transcript_values: A dictionary returned from parse_transcriptome_file. + threshold: A threshold that the biomass flux needs to stay above. + """""" + ci_dict = {} + for reaction in mm.reactions: + gene_string = reversible_gene_assoc.get(reaction) + if gene_string is None: + continue + else: + e = boolean.Expression(gene_string) + ci = get_rxn_value(e._root, transcript_values) + if ci is not None: + ci_dict[reaction] = ci + + gimme_objective = Expression() + + threshold = threshold + problem.maximize(biomass) + if threshold.relative: + threshold.reference = problem.get_flux(biomass) + + logger.info('Setting objective threshold to {}'.format( + threshold)) + + if problem.get_flux(biomass) < float(threshold): + logger.warning('Input threshold ' + 'greater than maximum ' + 'biomass: {}'.format(problem.get_flux(biomass))) + quit() + problem.prob.add_linear_constraints( + problem.get_flux_var(biomass) >= float(threshold)) + + for key, value in iteritems(ci_dict): + gimme_objective += problem.get_flux_var(key) * value + problem.prob.define('gimme_objective', types=lp.VariableType.Continuous) + obj = problem.prob.var('gimme_objective') + problem.prob.add_linear_constraints(obj == gimme_objective) + problem.prob.set_objective(obj) + problem.prob.set_objective_sense(ObjectiveSense.Minimize) + problem.prob.solve() + used_rxns = set() + sum_fluxes = 0 + for reaction in mm.reactions: + if abs(problem.get_flux(reaction)) > 1e-12: + original_id = reaction.replace('_forward', '') + original_id = original_id.replace('_reverse', '') + used_rxns.add(original_id) + sum_fluxes += abs(problem.get_flux(reaction)) + used_below = 0 + used_above = 0 + off_below = 0 + off_above = 0 + final_model = set() + original_reaction_set = set() + for reaction in mm.reactions: + if mm.is_exchange(reaction): + continue + else: + reaction = reaction.replace('_forward', '') + reaction = reaction.replace('_reverse', '') + original_reaction_set.add(reaction) + below_threshold_ids = set() + for reaction in ci_dict.keys(): + reaction = reaction.replace('_forward', '') + reaction = reaction.replace('_reverse', '') + below_threshold_ids.add(reaction) + + used_below_list = [] + for reaction in original_reaction_set: + if reaction in used_rxns: + if reaction in below_threshold_ids: + used_below += 1 + used_below_list.append(reaction) + final_model.add(reaction) + else: + used_above += 1 + final_model.add(reaction) + else: + if reaction in below_threshold_ids: + off_below += 1 + else: + off_above += 1 + final_model.add(reaction) + used_exchange = used_rxns - original_reaction_set + + return final_model, used_exchange, below_threshold_ids, \ + problem.prob.result.get_value(obj) + + +def parse_transcriptome_file(f, threshold): + """"""Parses a file containing a gene to expression mapping. + + Parses a tab separated two column table. The first column contains gene + IDs while the second column contains expression values. Will compare the + expression values to the given threshold and return a dict with any + genes that fall under the expression threshold, and the amount that they + fall under the threshold. + + Args: + f: a file containing a two column gene to expression table. + threshold: Expression threshold value. + """""" + threshold_value = {} + for row in csv.reader(f, delimiter=str('\t')): + try: + gene = row[0] + gene = gene.replace('""', '') + if float(row[1]) < threshold: + threshold_value[gene] = threshold - float(row[1]) + elif float(row[1]) >= threshold: + continue + except ValueError: + logger.warning('Invalid expression value ' + 'provided: gene: {} ' + 'value: {}'.format(row[0], row[1])) + return threshold_value + + +def get_rxn_value(root, gene_dict): + """"""Gets overall expression value for a reaction gene association. + + Recursive function designed to parse a gene expression and return + a penalty value to use in the GIMME algorithm. This function is + designed to return the value directly if the expression only has + one gene. If the expression has multiple genes related by 'OR' + associations, then it will return the highest lowest penalty value. + If the genes are associated with 'AND' logic then the function + will return the highest penalty value of the set of values. + + Args: + root: object of boolean.Expression()._root + gene_dict: dict of gene expression from parse_transcriptome_file + """""" + if type(root) == boolean.Variable: + return gene_dict.get(root.symbol) + elif type(root) is boolean.And: + val_list = [x for x in + [get_rxn_value(i, gene_dict) for i in root._terms] + if x is not None] + if len(val_list) == 0: + return None + else: + return max(x for x in val_list if x is not None) + elif type(root) is boolean.Or: + val_list = [x for x in + [get_rxn_value(i, gene_dict) + for i in root._terms]] + if None in val_list: + return None + else: + return min(x for x in val_list if x is not None) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/robustness.py",".py","10520","264","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2020 Ke Zhang + +from __future__ import unicode_literals + +import time +import logging + +from ..command import (Command, MetabolicMixin, LoopRemovalMixin, + ObjectiveMixin, SolverCommandMixin, + ParallelTaskMixin, convert_to_unicode) +from .. import fluxanalysis + +from six.moves import range + +logger = logging.getLogger(__name__) + + +class RobustnessCommand(MetabolicMixin, LoopRemovalMixin, ObjectiveMixin, + SolverCommandMixin, ParallelTaskMixin, Command): + """"""Run robustness analysis on the model. + + Given a reaction to maximize and a reaction to vary, + the robustness analysis will run FBA while fixing the + reaction to vary at each iteration. The reaction will + be fixed at the specified number of steps between the + minimum and maximum flux value specified in the model. + """""" + + _supported_loop_removal = ['none', 'tfba', 'l1min'] + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--steps', metavar='N', type=int, default=10, + help='Number of flux value steps for varying reaction') + parser.add_argument( + '--minimum', metavar='V', type=float, + help='Minumum flux value of varying reaction') + parser.add_argument( + '--maximum', metavar='V', type=float, + help='Maximum flux value of varying reaction') + parser.add_argument( + '--all-reaction-fluxes', + help='Print reaction flux for all model reactions', + action='store_true') + parser.add_argument('varying', type=convert_to_unicode, + help='Reaction to vary') + parser.add_argument( + '--fva', action='store_true', + help='Run FVA and print flux range instead of flux value') + super(RobustnessCommand, cls).init_parser(parser) + + def run(self): + """"""Run robustness command."""""" + + reaction = self._get_objective() + if not self._mm.has_reaction(reaction): + self.fail('Specified biomass reaction is not in model: {}'.format( + reaction)) + + varying_reaction = self._args.varying + if not self._mm.has_reaction(varying_reaction): + self.fail('Specified varying reaction is not in model: {}'.format( + varying_reaction)) + + steps = self._args.steps + if steps <= 0: + self.argument_error('Invalid number of steps: {}\n'.format(steps)) + + loop_removal = self._get_loop_removal_option() + solver = self._get_solver() + if loop_removal != 'none': + if self._args.fva is not True: + if loop_removal == 'tfba': + solver = self._get_solver(integer=True) + else: + solver = self._get_solver() + else: + logger.warning( + 'The loop removal method {} is not possible with --fva ' + 'option in this command'.format(loop_removal)) + quit() + + p = fluxanalysis.FluxBalanceProblem(self._mm, solver) + if loop_removal == 'tfba': + p.add_thermodynamic() + + try: + p.check_constraints() + except fluxanalysis.FluxBalanceError as e: + self.report_flux_balance_error(e) + + # Determine minimum and maximum flux for varying reaction + if self._args.maximum is None: + p.maximize(varying_reaction) + flux_max = p.get_flux(varying_reaction) + else: + flux_max = self._args.maximum + + if self._args.minimum is None: + p.maximize({varying_reaction: -1}) + flux_min = p.get_flux(varying_reaction) + else: + flux_min = self._args.minimum + + if flux_min > flux_max: + self.argument_error('Invalid flux range: {}, {}\n'.format( + flux_min, flux_max)) + + logger.info('Varying {} in {} steps between {} and {}'.format( + varying_reaction, steps, flux_min, flux_max)) + + start_time = time.time() + + handler_args = ( + self._mm, solver, loop_removal, self._args.all_reaction_fluxes) + + def iter_tasks(): + for i in range(steps): + fixed_flux = flux_min + i*(flux_max - flux_min)/float(steps-1) + constraint = varying_reaction, fixed_flux + yield constraint, reaction + + # Run FBA on model at different fixed flux values + if self._args.fva is not True: + executor = self._create_executor( + RobustnessTaskHandler, handler_args, cpus_per_worker=2) + with executor: + for task, result in executor.imap_unordered(iter_tasks(), 16): + (varying_reaction, fixed_flux), _ = task + if result is None: + logger.warning('No solution found for {} at {}'.format( + varying_reaction, fixed_flux)) + elif self._args.all_reaction_fluxes: + for other_reaction in self._mm.reactions: + print('{}\t{}\t{}'.format( + other_reaction, fixed_flux, + result[other_reaction])) + else: + print('{}\t{}'.format(fixed_flux, result)) + + executor.join() + + logger.info('Solving took {:.2f} seconds'.format( + time.time() - start_time)) + + # Run FVA on model at different fixed flux values + else: + executor_fva = self._create_executor( + RobustnessTaskHandlerFva, handler_args, cpus_per_worker=2) + with executor_fva: + for task, result in executor_fva.imap_unordered( + iter_tasks(), 16): + (varying_reaction, fixed_flux), _ = task + if result is None: + logger.warning('No solution found for {} at {}'.format( + varying_reaction, fixed_flux)) + elif self._args.all_reaction_fluxes: + for other_reaction in self._mm.reactions: + print('{}\t{}\t{}\t{}'.format( + other_reaction, fixed_flux, + result[other_reaction][0], + result[other_reaction][1])) + else: + print('{}\t{}\t{}'.format( + fixed_flux, result[reaction][0], + result[reaction][1])) + + executor_fva.join() + + logger.info('Solving took {:.2f} seconds'.format( + time.time() - start_time)) + + +class RobustnessTaskHandler(object): + def __init__(self, model, solver, loop_removal, all_reactions): + self._problem = fluxanalysis.FluxBalanceProblem(model, solver) + + if loop_removal == 'none': + self._run_fba = self._problem.maximize + elif loop_removal == 'l1min': + self._run_fba = self._problem.max_min_l1 + elif loop_removal == 'tfba': + self._problem.add_thermodynamic() + self._run_fba = self._problem.maximize + + self._reactions = list(model.reactions) if all_reactions else None + + def handle_task(self, constraint, reaction): + varying_reaction, fixed_flux = constraint + flux_var = self._problem.get_flux_var(varying_reaction) + c, = self._problem.prob.add_linear_constraints(flux_var == fixed_flux) + + try: + self._run_fba(reaction) + if self._reactions is not None: + return {reaction: self._problem.get_flux(reaction) + for reaction in self._reactions} + else: + return self._problem.get_flux(reaction) + except fluxanalysis.FluxBalanceError: + return None + finally: + c.delete() + + +class RobustnessTaskHandlerFva(object): + def __init__(self, model, solver, loop_removal, all_reactions): + self._problem = fluxanalysis.FluxBalanceProblem(model, solver) + + if loop_removal == 'none': + self._run_fba = self._problem.maximize + # elif loop_removal == 'l1min': + # self._run_fba = self._problem.max_min_l1 + elif loop_removal == 'tfba': + self._problem.add_thermodynamic() + self._run_fba = self._problem.maximize + + self._reactions = list(model.reactions) if all_reactions else None + + def handle_task(self, constraint, reaction): + d = None + varying_reaction, fixed_flux = constraint + flux_var = self._problem.get_flux_var(varying_reaction) + c, = self._problem.prob.add_linear_constraints(flux_var == fixed_flux) + try: + self._problem.maximize(reaction) + obj_flux = self._problem.get_flux(reaction) + d, = self._problem.prob.add_linear_constraints( + self._problem.get_flux_var(reaction) == obj_flux) + if self._reactions is not None: + all_rxn_fluxes = {} + for rxn in self._reactions: + all_rxn_fluxes[rxn] = ( + self._problem.flux_bound(rxn, -1), + self._problem.flux_bound(rxn, 1)) + return all_rxn_fluxes + else: + return {reaction: (self._problem.flux_bound(reaction, -1), + self._problem.flux_bound(reaction, 1))} + except fluxanalysis.FluxBalanceError: + return None + finally: + c.delete() + if d is not None: + d.delete() +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/masscheck.py",".py","5455","147","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import time +import logging + +from six import iteritems + +from ..command import (Command, SolverCommandMixin, MetabolicMixin, + FilePrefixAppendAction, convert_to_unicode) +from .. import massconsistency +from ..reaction import Compound + +logger = logging.getLogger(__name__) + + +class MassConsistencyCommand(MetabolicMixin, SolverCommandMixin, Command): + """"""Check whether the model is mass consistent."""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--exclude', metavar='reaction', action=FilePrefixAppendAction, + type=convert_to_unicode, default=[], + help='Exclude reaction from mass consistency') + parser.add_argument( + '--epsilon', type=float, help='Mass threshold', + default=1e-5) + parser.add_argument( + '--checked', metavar='reaction', action=FilePrefixAppendAction, + type=convert_to_unicode, default=[], + help='Mark reaction as already checked (no residual)') + parser.add_argument( + '--type', choices=['compound', 'reaction'], + default='compound', help='Type of check to perform') + super(MassConsistencyCommand, cls).init_parser(parser) + + def _compound_name(self, id): + if id not in self._model.compounds: + return id + return self._model.compounds[id].properties.get('name', id) + + def run(self): + # Load compound information + zeromass = set() + for compound in self._model.compounds: + if compound.properties.get('zeromass', False): + zeromass.add(Compound(compound.id)) + + # Create a set of known mass-inconsistent reactions + exchange = set() + for reaction_id in self._mm.reactions: + if self._mm.is_exchange(reaction_id): + exchange.add(reaction_id) + + # Create a set of excluded reactions + exclude = set(self._args.exclude) + + # Add biomass reaction to be excluded + biomass_reaction = self._model.biomass_reaction + if biomass_reaction is not None: + exclude.add(biomass_reaction) + + solver = self._get_solver() + + known_inconsistent = exclude | exchange + + if self._args.type == 'compound': + self._check_compounds(known_inconsistent, zeromass, solver) + elif self._args.type == 'reaction': + self._check_reactions(known_inconsistent, zeromass, solver) + else: + self.argument_error( + 'Invalid type of check: {}'.format(self._args.type)) + + def _check_compounds(self, known_inconsistent, zeromass, solver): + logger.info('Checking stoichiometric consistency of compounds...') + + epsilon = self._args.epsilon + + start_time = time.time() + + masses = dict(massconsistency.check_compound_consistency( + self._mm, solver, known_inconsistent, zeromass)) + + logger.info('Solving took {:.2f} seconds'.format( + time.time() - start_time)) + + good = 0 + total = 0 + for compound, mass in sorted( + iteritems(masses), key=lambda x: (x[1], x[0]), reverse=True): + if mass >= 1-epsilon or compound.name in zeromass: + good += 1 + total += 1 + print('{}\t{}\t{}'.format( + compound, mass, compound.translate(self._compound_name))) + logger.info('Consistent compounds: {}/{}'.format(good, total)) + + def _check_reactions(self, known_inconsistent, zeromass, solver): + logger.info('Checking stoichiometric consistency of reactions...') + + # Create a set of checked reactions + checked = set(self._args.checked) + + epsilon = self._args.epsilon + + start_time = time.time() + + reaction_iter, compound_iter = ( + massconsistency.check_reaction_consistency( + self._mm, solver=solver, exchange=known_inconsistent, + checked=checked, zeromass=zeromass)) + + logger.info('Solving took {:.2f} seconds'.format( + time.time() - start_time)) + + good = 0 + total = 0 + for reaction_id, residual in sorted( + reaction_iter, key=lambda x: abs(x[1]), reverse=True): + total += 1 + if abs(residual) >= epsilon: + reaction = self._mm.get_reaction(reaction_id) + rxt = reaction.translated_compounds(self._compound_name) + print('{}\t{}\t{}'.format(reaction_id, residual, rxt)) + else: + good += 1 + logger.info('Consistent reactions: {}/{}'.format(good, total)) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/tmfa.py",".py","43136","977","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2017-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals +import logging +from ..command import SolverCommandMixin, MetabolicMixin, \ + Command, ObjectiveMixin, convert_to_unicode +from ..reaction import Compound +from ..lpsolver import lp +from ..datasource.reaction import parse_reaction +from decimal import Decimal +import csv +import math +import random +import yaml +import argparse +from psamm.datasource.entry import (DictReactionEntry as ReactionEntry) +from six import iteritems +logger = logging.getLogger(__name__) + + +class TMFACommand(MetabolicMixin, SolverCommandMixin, ObjectiveMixin, Command): + """"""Run TMFA on the model."""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument('--config', type=argparse.FileType('r'), + help='Config file for TMFA settings') + parser.add_argument('--threshold', default=None, type=Decimal, + help='value to fix biomass flux to during ' + 'tmfa simulations (default = max biomass)') + parser.add_argument('--temp', help='Temperature in Celsius', + default=25) + parser.add_argument('--hamilton', action='store_true', + help='run model using Hamilton TMFA method') + parser.add_argument('--err', action='store_true', + help='use error estimates when running TMFA') + parser.add_argument('--phin', default='4,11', + help='Allowable range for internal compartment pH ' + 'format: Lower,Upper') + parser.add_argument('--phout', default='4,11', + help='Allowable range for external compartment pH ' + 'format: Lower,Upper') + + subparsers = parser.add_subparsers(title='Functions', dest='which') + parser_util = subparsers.add_parser('util', help='Utility functions') + + parser_util.add_argument('--generate-config', action='store_true') + parser_util.add_argument('--random-addition', action='store_true', + help='perform random reaction constraint ' + 'addition in model') + + parser_sim = subparsers.add_parser('simulation', + help='Simulation Functions') + parser_sim.add_argument('--single-solution', type=str, default=None, + choices=['fba', 'l1min', 'random'], + help='get a single TMFA solution') + + super(TMFACommand, cls).init_parser(parser) + + def run(self): + """"""Run TMFA command."""""" + solver = self._get_solver() + if solver._properties['name'] not in ['cplex', 'gurobi']: + raise ImportError( + 'Unable to find an LP solver that satisfy the requirement of ' + 'TMFA function (TMFA requires Cplex or Gurobi as LP solver)') + + mm = self._mm + which_command = self._args.which + + if which_command == 'util': + if self._args.generate_config: + with open('./example-config.yaml', mode='w') as f: + f.write('deltaG: \n') + f.write('exclude: \n') + f.write('transporters: \n') + f.write('concentrations: \n') + f.write('proton-in: \n') + f.write('proton-out: \n') + f.write('proton-other:\n') + f.write(' - \n') + f.write('water:\n') + f.write(' - = v, v >= -z) + + objective = _z.expr( + (reaction_id, -1) + for reaction_id in mm.reactions) + prob.set_objective(objective) + result = prob.solve_unchecked(lp.ObjectiveSense.Maximize) + if not result.success: + logger.error(u'Solution not optimal: {}'.format(result.status)) + quit() + for rxn in mm.reactions: + print(u'Flux\t{}\t{}'.format(rxn, result.get_value(_v(rxn)))) + if rxn in split_reversible_list: + if '_reverse' in rxn: + rxn_f = rxn + rxn_f = rxn_f.replace('_reverse', '') + rxn_f += '_forward' + print(u'DGR\t{}\t{}'.format( + rxn, -1*result.get_value(_dgri(rxn_f)))) + else: + print(u'DGR\t{}\t{}'.format( + rxn, result.get_value(_dgri(rxn)))) + else: + print(u'DGR\t{}\t{}'.format( + rxn, result.get_value(_dgri(rxn)))) + print(u'Zi\t{}\t{}'.format(rxn, result.get_value(_zi(rxn)))) + for cp in cp_list: + if cp not in excluded_compounds: + print(u'CPD\t{}\t{}'.format(cp, result.get_value(_xij(cp)))) + elif simulation == 'random': + optimize = None + for rxn_id in mm.reactions: + if optimize is None: + optimize = _v(rxn_id) * random.random() + else: + optimize += _v(rxn_id) * random.random() + prob.add_linear_constraints( + _v(objective) == result.get_value(_v(objective))) + + prob.set_objective(optimize) + + result = prob.solve_unchecked() + for rxn in mm.reactions: + print(u'Flux\t{}\t{}'.format(rxn, result.get_value(_v(rxn)))) + if rxn in split_reversible_list: + if '_reverse' in rxn: + rxn_f = rxn + rxn_f = rxn_f.replace('_reverse', '') + rxn_f += '_forward' + print(u'DGR\t{}\t{}'.format( + rxn, -1*result.get_value(_dgri(rxn_f)))) + else: + print(u'DGR\t{}\t{}'.format( + rxn, result.get_value(_dgri(rxn)))) + else: + print(u'DGR\t{}\t{}'.format(rxn, result.get_value(_dgri(rxn)))) + print(u'Zi\t{}\t{}'.format(rxn, result.get_value(_zi(rxn)))) + for cp in cp_list: + if cp not in excluded_compounds: + print(u'CPD\t{}\t{}'.format(cp, result.get_value(_xij(cp)))) + + +def lump_parser(lump_file): + """"""Parses a supplied file and returns + dictionaries containing lump information. + + The supplied file should be in a tab separated table in the format of + lumpID lump_deltaG rxn1:1,rxn2:-1,rxn3:1 lumpRXN + Returns dictionaries storing this information, linking reactions to the + lumps. + """""" + rxn_to_lump_id = {} + lump_to_rxn = {} + lump_to_rxnids = {} + lump_to_rxnids_dir = {} + for row in csv.reader(lump_file, delimiter=str('\t')): + lump_id, lump_rxn_list, lump_rxn = row + rx_dir_list = [] + rx_list = [] + for i in lump_rxn_list.split(','): + subrxn, dir = convert_to_unicode(i).split(':') + rx_dir_list.append((subrxn, dir)) + rx_list.append(subrxn) + rxn_to_lump_id[i] = lump_id + lump_to_rxn[lump_id] = lump_rxn + lump_to_rxnids[lump_id] = rx_list + lump_to_rxnids_dir[lump_id] = rx_dir_list + return lump_to_rxn, rxn_to_lump_id, lump_to_rxnids, lump_to_rxnids_dir + + +def parse_tparam_file(file): + """"""Parse a transport parameter file. + + This file contains reaction IDs, net charge transported into + the cell, and net protons transported into the cell. + + """""" + t_param = {} + if file is not None: + for row in csv.reader(file, delimiter=str('\t')): + rxn, c, h = row + rxn = convert_to_unicode(rxn) + t_param[rxn] = (Decimal(c), Decimal(h)) + t_param[u'{}_forward'.format(rxn)] = (Decimal(c), Decimal(h)) + t_param[u'{}_reverse'.format(rxn)] = (-Decimal(c), -Decimal(h)) + return t_param + + +def parse_dgf(mm, dgf_file): + """"""A function that will parse a supplied deltaG of formation file. + + Compound IDs in this file do not need to contain the compartments. + compound deltaGf values should be in Kcal/mol + + Args: + mm: a metabolic model object + dgf_file: a file that containing 2 columns of + compound ids and deltaGf values + """""" + + cpd_dgf_dict = {} + for row in csv.reader(dgf_file, delimiter=str('\t')): + for cpt in mm.compartments: + try: + dg = Decimal(row[1]) + derr = Decimal(row[2]) + cpd_dgf_dict[Compound(row[0], cpt)] = (dg, derr) + except: + logger.info(u'Compound {} has an assigned detltGf value ' + 'of {}. This is not an number and will be treated ' + 'as a missing ' + 'value.'.format(Compound(row[0], cpt), row[1])) + return cpd_dgf_dict + + +def add_conc_constraints(xij, problem, cpd_conc_dict, + cp_list, water, hin, hout, hother): + """"""Add concentration constraints to TMFA problem + based on parsed concentration dictionary. + + """""" + # Water and hydrogen need to be excluded from + # these concentration constraints. + excluded_cpd_list = [] + excluded_cpd_list.append(hin) + excluded_cpd_list.append(hout) + excluded_cpd_list.append(hother) + for wat in water: + excluded_cpd_list.append(wat) + cpdid_xij_dict = {} + for cp in cp_list: + # define concentration variable for compound. + cpdid_xij_dict[cp] = xij(cp) + var = xij(cp) + # Define default constraints for anything not set in the conc file + if cp not in cpd_conc_dict.keys(): + if cp not in excluded_cpd_list: + # Add concentration constraints as the + # ln of the concentration (M). + problem.add_linear_constraints(var >= math.log(0.00001)) + problem.add_linear_constraints(var <= math.log(0.02)) + elif cp in cpd_conc_dict.keys(): + if cp not in excluded_cpd_list: + conc_limits = cpd_conc_dict[cp] + if conc_limits[0] > conc_limits[1]: + logger.error(u'lower bound for {} concentration higher ' + 'than upper bound'.format(cp)) + quit() + if Decimal(conc_limits[0]) == Decimal(conc_limits[1]): + problem.add_linear_constraints( + var == math.log(Decimal(conc_limits[0]))) + else: + problem.add_linear_constraints( + var >= math.log(Decimal(conc_limits[0]))) + problem.add_linear_constraints( + var <= math.log(Decimal(conc_limits[1]))) + return problem, cpdid_xij_dict + + +def parse_dgr_file(dgr_file, mm): + """"""Parses DeltaG of reaction file and returns a dictionary of the values. + + """""" + def is_number(val): + try: + float(val) + return True + except ValueError: + return False + dgr_dict = {} + for row in csv.reader(dgr_file, delimiter=str('\t')): + rxn, dgr, err = row + rxn = convert_to_unicode(rxn) + if is_number(dgr): + if is_number(err): + err = Decimal(err) + else: + err = Decimal(2) + if rxn in mm.reactions: + dgr_dict[rxn] = (Decimal(dgr), err) + elif '{}_forward'.format(rxn) in mm.reactions: + dgr_dict[u'{}_forward'.format(rxn)] = (Decimal(dgr), err) + dgr_dict[u'{}_reverse'.format(rxn)] = (-Decimal(dgr), err) + else: + logger.info( + u'Reaction {} was provided with dgr value of {}'.format( + rxn, dgr)) + return dgr_dict + + +def calculate_dgr(mm, dgf_dict, excluded_reactions, + transport_parameters, ph_difference_rxn, scaled_compounds): + """"""Calculates DeltaG values from DeltaG of formation values of compounds. + + """""" + dgf_scaling = {} + if scaled_compounds is not None: + scaled_compounds.seek(0) + for row in csv.reader(scaled_compounds, delimiter=str('\t')): + dgf_scaling[row[0]] = Decimal(row[1]) + + dgr_dict = {} + for reaction in mm.reactions: + if reaction not in excluded_reactions: + dgr = 'NA' + dgerr = 0 + rxn = mm.get_reaction(reaction) + if any(dgf_dict.get(j[0]) is None for j in rxn.compounds): + for j in rxn.compounds: + if j[0] not in dgf_dict.keys(): + print(j[0]) + if reaction not in ph_difference_rxn: + logger.error(u'Reaction {} contains at least 1 compound ' + 'with an unknown deltaGf ' + 'value'.format(reaction)) + quit() + else: + dgr = 0 + # Make a variable dgf_sum that represents + # the sum of sij * (stoichiometry * + # deltaGf for reaction j. + for cpd in rxn.compounds: + cpd_0 = convert_to_unicode(str(cpd[0])) + if cpd_0 in dgf_scaling.keys(): + dgscale = dgf_scaling[cpd_0] + else: + dgscale = 1 + (dg, dge) = dgf_dict[cpd[0].name] + dgs = Decimal(dg) * (Decimal(cpd[1])*dgscale) + dgr += dgs + dgerr += Decimal(cpd[1])*Decimal(dgscale) * dge + dgr_dict[reaction] = (dgr, dgerr) + return dgr_dict + + +def add_reaction_constraints( + problem, _v, _zi, _dgri, _xij, mm, exclude_lumps, exclude_unknown, + exclude_lumps_unknown, dgr_dict, lump_rxn_list, split_rxns, + transport_parameters, testing_list, scaled_compounds, water, hin, + hout, hother, ph, temp, err_est=False, hamilton=False): + """"""Adds reaction constraints to a TMFA problem + + This function will add in gibbs free energy constraints to a TMFA flux + problem. These constraints will be added based on provided Gibbs free + energy values and temperature. + + Args: + problem: :class:`psamm.lpsolver.lp.Problem`. + mm: :class:`psamm.metabolicmodel.MetabolicModel`. + _v: variable namespace for flux variables. + _dgri: variable namespace for gibbs free energy variables + _zi: variables namespace for indicator variables + _xij: variable namespace for concentrations + exclude_unknown: List of reactions excluded from thermo constraints. + exclude_lumps_unknown: List of excluded reactions and lumped reactions. + dgr_dict: dictionary where keys are reaction ids and values + are deltag values. + lump_rxn_list: List of lump reaction IDs. + split_rxns: List of tuples of (reaction_forward, reaction_reverse) + transport_parameters: dictionary of reaction IDs to proton + transport and charge transport values. + testing_list: List of reactions to add deltaG constraints for. + water: list of water compound IDs. + hin: ID of proton compound from inside cell compartment + hout: ID of proton compound from outside cell compartment + hother: List of other proton IDs + ph: list of two tuples containing pH bounds. [(in_lower, in_upper), + (out_lower, out_upper)] + temp: Temperature in Celsius + err_est: True or False for using error estimates for deltaG values. + hamilton: True or False for using Hamilton TMFA method. + + """""" + dgf_scaling = {} + if scaled_compounds is not None: + scaled_compounds.seek(0) + for row in csv.reader(scaled_compounds, delimiter=str('\t')): + dgf_scaling[row[0]] = Decimal(row[1]) + + # ""idg"" is the ideal gas constant in units of kJ/mol + idg = Decimal(8.3144621 / 1000) # kJ/mol + # R = Decimal(1.987 / 1000) kcal/mol + + # ""tkelvin"" is the temperature on the Kelvin scale + tkelvin = Decimal(temp) + Decimal(273.15) + + k = 500 + epsilon = 0.000001 + ph_in = ph[0] + ph_out = ph[0] + h_p = _xij(str(hout)) + + problem.add_linear_constraints(h_p <= ph_out[1]) + problem.add_linear_constraints(h_p >= ph_out[0]) + + h_c = _xij(str(hin)) + + problem.add_linear_constraints(h_c >= ph_in[0]) + problem.add_linear_constraints(h_c <= ph_in[1]) + delta_ph = (h_c - h_p) + + # ""fc"" is the Faraday constant in units of kcal/(mV*mol) + fc = Decimal(0.02306) + + excluded_cpd_list = [] + excluded_cpd_list.append(hin) + excluded_cpd_list.append(hout) + if hother is not None: + excluded_cpd_list.append(hother) + for wat in water: + excluded_cpd_list.append(wat) + logger.info(u'Excluded compounds: {}'.format(','.join(excluded_cpd_list))) + logger.info(u'Temperature: {}'.format(tkelvin)) + logger.info(u'using h in {}'.format(hin)) + logger.info(u'using h out {}'.format(hout)) + logger.info(u'using water {}'.format(water)) + logger.info(u'using ph range of {} to {} for internal compartment'.format( + ph_in[0], ph_in[1])) + logger.info(u'using ph range of {} to {} for external compartment'.format( + ph_out[0], ph_out[1])) + # for (f, r) in split_rxns: + # split_list.append(f) + # split_list.append(r) + # if f not in exclude_unknown: + # dgrif = _dgri(f) + # dgrir = _dgri(r) + # problem.add_linear_constraints(dgrif == dgrir * -1) + + new_excluded_reactions = [] + for reaction in mm.reactions: + if reaction not in exclude_unknown: + rxn = mm.get_reaction(reaction) + rhs_check = 0 + lhs_check = 0 + for (cpd, stoich) in rxn.compounds: + if stoich < 0: + if str(cpd) not in excluded_cpd_list: + lhs_check += 1 + if stoich > 0: + if str(cpd) not in excluded_cpd_list: + rhs_check += 1 + if rhs_check == 0 or lhs_check == 0: + new_excluded_reactions.append(reaction) + + zi = _zi(reaction) + split_rxns_l = [] + for (f, r) in split_rxns: + split_rxns_l.append(f) + split_rxns_l.append(r) + if reaction in split_rxns_l: + if '_reverse' in reaction: + f_rxn = reaction.replace('_reverse', '') + f_rxn = f_rxn+'_forward' + dgri = -1*_dgri(reaction) + else: + dgri = _dgri(reaction) + else: + dgri = _dgri(reaction) + vi = _v(reaction) + vmax = mm.limits[reaction].upper + if reaction in testing_list: + if reaction in transport_parameters.keys(): + (c, h) = transport_parameters[reaction] + ddph = Decimal(-2.3)*Decimal(h)*idg*tkelvin*delta_ph + dpsi = Decimal(33.33) * delta_ph - Decimal(143.33) + ddpsi = dpsi * Decimal(c) * Decimal(fc) + dgr_trans = ddph + ddpsi + else: + dgr_trans = 0 + (dgr0, err) = dgr_dict[reaction] + ssxi = 0 + + if err_est: + problem.define(u'dgr_err_{}'.format(reaction), + types=lp.VariableType.Continuous, + lower=-1000, upper=1000) + dgr_err = problem.var(u'dgr_err_{}'.format(reaction)) + problem.add_linear_constraints(dgr_err <= 2*err) + problem.add_linear_constraints(dgr_err >= -2*err) + else: + dgr_err = 0 + + for (cpd, stoich) in rxn.compounds: + cpd = convert_to_unicode(str(cpd)) + if cpd not in excluded_cpd_list: + scale = dgf_scaling.get(cpd, 1) + ssxi += _xij(cpd) * Decimal(stoich) * scale + + problem.add_linear_constraints( + dgri == dgr0 + (idg * tkelvin * ssxi + ) + dgr_err + dgr_trans) + if hamilton: + problem.add_linear_constraints(dgri <= 300-epsilon) + problem.add_linear_constraints(dgri >= -300+epsilon) + + if reaction not in exclude_lumps_unknown: + if rhs_check != 0 and lhs_check != 0: + problem.add_linear_constraints( + dgri - k + (k * zi) <= -epsilon) + problem.add_linear_constraints(vi <= zi * vmax) + + if reaction in lump_rxn_list.keys(): + problem.define(u'yi_{}'.format(reaction), lower=int(0), + upper=int(1), types=lp.VariableType.Binary) + if reaction not in new_excluded_reactions: + vi = _v(reaction) + yi = problem.var(u'yi_{}'.format(reaction)) + dgri = _dgri(reaction) + problem.add_linear_constraints(vi == 0) + problem.add_linear_constraints(dgri - (k * yi) <= - epsilon) + sub_rxn_list = lump_rxn_list[reaction] + sszi = 0 + for sub_rxn in sub_rxn_list: + sszi += _zi(sub_rxn) + problem.add_linear_constraints( + yi + sszi <= len(sub_rxn_list)) + + for (forward, reverse) in split_rxns: + problem.add_linear_constraints( + _zi(forward) + _zi(reverse) <= int(1)) + return problem, excluded_cpd_list +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/search.py",".py","10048","233","# coding=utf-8 +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2020 Elysha Sameth + +from __future__ import print_function, unicode_literals +import re + +from six import text_type + +from ..command import Command, FilePrefixAppendAction, convert_to_unicode +from ..datasource.reaction import parse_compound + + +def filter_search_term(s): + return re.sub(r'[^a-z0-9]+', '', s.lower()) + + +class SearchCommand(Command): + """"""Search for reactions and compounds in the model."""""" + + @classmethod + def init_parser(cls, parser): + """"""Initialize argument parser"""""" + subparsers = parser.add_subparsers(title='Search domain') + + # Compound subcommand + parser_compound = subparsers.add_parser( + 'compound', help='Search in compounds') + parser_compound.set_defaults(which='compound') + parser_compound.add_argument( + '--id', '-i', dest='id', metavar='id', + action=FilePrefixAppendAction, type=convert_to_unicode, default=[], + help='Compound ID') + parser_compound.add_argument( + '--name', '-n', dest='name', metavar='name', + action=FilePrefixAppendAction, type=convert_to_unicode, default=[], + help='Name of compound') + parser_compound.add_argument( + '--key', dest='key', metavar='key', + type=convert_to_unicode, default=None, + help='String to search for within compound ' + 'properties. (case insensitive). Only one --key allowed') + parser_compound.add_argument( + '--exact', action='store_true', + help='Match full compound property') + parser_compound.add_argument( + '--inmodel', action='store_true', + help='Only search compounds in the model reactions') + + # Reaction subcommand + parser_reaction = subparsers.add_parser( + 'reaction', help='Search in reactions') + parser_reaction.set_defaults(which='reaction') + parser_reaction.add_argument( + '--id', '-i', dest='id', metavar='id', + action=FilePrefixAppendAction, type=convert_to_unicode, default=[], + help='Reaction ID') + parser_reaction.add_argument( + '--compound', '-c', dest='compound', metavar='compound', + action=FilePrefixAppendAction, type=convert_to_unicode, default=[], + help='Comma-separated list of compound IDs') + parser_reaction.add_argument( + '--key', dest='key', metavar='key', + type=convert_to_unicode, default=None, + help='String to search for within reaction properties. ' + '(case insensitive). Only one --key allowed') + parser_reaction.add_argument( + '--exact', action='store_true', + help='Match full reaction property') + parser_reaction.add_argument( + '--inmodel', action='store_true', + help='Only search reactions in the model') + + def run(self): + """"""Run search command."""""" + self._mm = self._model.create_metabolic_model() + which_command = self._args.which + if which_command == 'compound': + self._search_compound() + elif which_command == 'reaction': + self._search_reaction() + + def _search_compound(self): + selected_compounds = set() + for compound in self._model.compounds: + if len(self._args.id) > 0: + if any(c == compound.id for c in self._args.id): + selected_compounds.add(compound) + continue + + if len(self._args.name) > 0: + names = set() + if 'name' in compound.properties: + names.add(compound.properties['name']) + names.update(compound.properties.get('names', [])) + names = set(filter_search_term(n) for n in names) + if any(filter_search_term(n) in names + for n in self._args.name): + selected_compounds.add(compound) + continue + + # find compounds that contains any of given properties + if self._args.key is not None: + # prepare s list of all compound properties + compound_prop_list = [] + for cpd_property in compound.properties.values(): + if isinstance(cpd_property, list): + for i in cpd_property: + compound_prop_list.append(convert_to_unicode( + text_type(i)).lower()) + else: + compound_prop_list.append(convert_to_unicode( + text_type(cpd_property)).lower()) + + # find compound entry based on given property argument + if self._args.exact: + if self._args.key.lower() in compound_prop_list: + selected_compounds.add(compound) + else: + if self._args.key.lower() in \ + ('|'.join(compound_prop_list)): + selected_compounds.add(compound) + + # Show results + if self._args.inmodel: + model_compounds = set(x.name for x in self._mm.compounds) + final_compounds = [i for i in selected_compounds + if i.id in model_compounds] + else: + final_compounds = selected_compounds + + for compound in final_compounds: + props = set(compound.properties) - {'id'} + print('id: {}'.format(compound.id)) + for prop in sorted(props): + print('{}: {}'.format(prop, compound.properties[prop])) + if compound.filemark is not None: + print('Defined in {}'.format(compound.filemark)) + print() + + def _search_reaction(self): + selected_reactions = set() + + # Prepare translation table from compound id to name + compound_name = {} + for compound in self._model.compounds: + if 'name' in compound.properties: + compound_name[compound.id] = compound.properties['name'] + + # Prepare sets of matched compounds + search_compounds = [] + for compound_list in self._args.compound: + compound_set = set() + for compound_spec in compound_list.split(','): + compound_set.add(parse_compound(compound_spec.strip())) + search_compounds.append(compound_set) + + for reaction in self._model.reactions: + if len(self._args.id) > 0: + if any(r == reaction.id for r in self._args.id): + selected_reactions.add(reaction) + continue + + if len(search_compounds) > 0: + compounds = set(c for c, _ in reaction.equation.compounds) + compounds.update(c.in_compartment(None) for c, _ in + reaction.equation.compounds) + if any(c.issubset(compounds) for c in search_compounds): + selected_reactions.add(reaction) + continue + + if self._args.key is not None: + # prepare a list of all reaction properties + raw_reaction_prop_list = [ + reaction.properties[key] for key in reaction.properties] + reaction_prop_list = [] + for rxn_property in raw_reaction_prop_list: + if isinstance(rxn_property, list): + for i in rxn_property: + reaction_prop_list.append(convert_to_unicode( + text_type(i)).lower()) + + else: + reaction_prop_list.append(convert_to_unicode( + text_type(rxn_property)).lower()) + + # find reaction based on given property argument + if self._args.exact: + if self._args.key.lower() in reaction_prop_list: + selected_reactions.add(reaction) + continue + else: + if self._args.key.lower() in '|'.join(reaction_prop_list): + selected_reactions.add(reaction) + if self._args.inmodel: + final_reactions = [i for i in selected_reactions + if i.id in self._mm.reactions] + else: + final_reactions = selected_reactions + + # Show results + for reaction in final_reactions: + props = set(reaction.properties) - {'id', 'equation'} + print('id: {}'.format(reaction.id)) + print('equation: {}'.format( + reaction.equation)) + translated_equation = reaction.equation.translated_compounds( + lambda x: compound_name.get(x, x)) + if reaction.equation != translated_equation: + print('equation (compound names): {}'.format( + translated_equation)) + for prop in sorted(props): + print('{}: {}'.format(prop, reaction.properties[prop])) + if reaction.filemark is not None: + print('Defined in {}'.format(reaction.filemark)) + print() +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/gapcheck.py",".py","9041","224","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import logging +from six import iteritems + +from ..command import Command, MetabolicMixin, SolverCommandMixin +from ..gapfill import gapfind, GapFillError +from ..lpsolver import lp + +logger = logging.getLogger(__name__) + + +class GapCheckCommand(MetabolicMixin, SolverCommandMixin, Command): + """"""Check for compound production gaps in model."""""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--method', choices=['gapfind', 'prodcheck', 'sinkcheck'], + default='prodcheck', + help='Method to use for gap checking (default: prodcheck)') + parser.add_argument( + '--no-implicit-sinks', action='store_true', + help='Do not include implicit sinks when gap-filling') + parser.add_argument( + '--unrestricted-exchange', action='store_true', + help='Remove all limits on exchange reactions while gap checking') + parser.add_argument( + '--exclude-extracellular', action='store_true', + help='Exclude extracellular compounds from the result') + parser.add_argument( + '--epsilon', type=float, default=1e-5, + help='Threshold for compound production') + + super(GapCheckCommand, cls).init_parser(parser) + + def run(self): + # Load compound information + def compound_name(id): + if id not in self._model.compounds: + return id + return self._model.compounds[id].properties.get('name', id) + + extracellular_comp = self._model.extracellular_compartment + epsilon = self._args.epsilon + v_max = float(self._model.default_flux_limit) + + implicit_sinks = not self._args.no_implicit_sinks + + if self._args.unrestricted_exchange: + # Allow all exchange reactions with no flux limits + for reaction in self._mm.reactions: + if self._mm.is_exchange(reaction): + del self._mm.limits[reaction].bounds + + logger.info('Searching for blocked compounds...') + + if self._args.method == 'gapfind': + # Run GapFind on model + solver = self._get_solver(integer=True) + try: + blocked = sorted(gapfind( + self._mm, solver=solver, epsilon=epsilon, v_max=v_max, + implicit_sinks=implicit_sinks)) + except GapFillError as e: + self._log_epsilon_and_fail(epsilon, e) + elif self._args.method == 'prodcheck': + # Run production check on model + solver = self._get_solver() + blocked = self.run_reaction_production_check( + self._mm, solver=solver, threshold=self._args.epsilon, + implicit_sinks=implicit_sinks) + elif self._args.method == 'sinkcheck': + # Run sink check on model + solver = self._get_solver() + blocked = self.run_sink_check( + self._mm, solver=solver, threshold=self._args.epsilon, + implicit_sinks=implicit_sinks) + else: + self.argument_error('Invalid method: {}'.format(self._args.method)) + + # Show result + count = 0 + for compound in blocked: + if (self._args.exclude_extracellular and + compound.compartment == extracellular_comp): + continue + + count += 1 + print('{}\t{}'.format(compound, compound_name(compound.name))) + + logger.info('Blocked compounds: {}'.format(count)) + + def run_sink_check(self, model, solver, threshold, implicit_sinks=True): + """"""Run sink production check method."""""" + prob = solver.create_problem() + + # Create flux variables + v = prob.namespace() + for reaction_id in model.reactions: + lower, upper = model.limits[reaction_id] + v.define([reaction_id], lower=lower, upper=upper) + + # Build mass balance constraints + massbalance_lhs = {compound: 0 for compound in model.compounds} + for spec, value in iteritems(model.matrix): + compound, reaction_id = spec + massbalance_lhs[compound] += v(reaction_id) * value + + mass_balance_constrs = {} + for compound, lhs in iteritems(massbalance_lhs): + if implicit_sinks: + # The constraint is merely >0 meaning that we have implicit + # sinks for all compounds. + prob.add_linear_constraints(lhs >= 0) + else: + # Save these constraints so we can temporarily remove them + # to create a sink. + c, = prob.add_linear_constraints(lhs == 0) + mass_balance_constrs[compound] = c + + for compound, lhs in sorted(iteritems(massbalance_lhs)): + if not implicit_sinks: + mass_balance_constrs[compound].delete() + + prob.set_objective(lhs) + try: + result = prob.solve(lp.ObjectiveSense.Maximize) + except lp.SolverError as e: + logger.warning('Failed to solve for compound: {} ({})'.format( + compound, e)) + + if result.get_value(lhs) < threshold: + yield compound + + if not implicit_sinks: + # Restore mass balance constraint. + c, = prob.add_linear_constraints(lhs == 0) + mass_balance_constrs[compound] = c + + def run_reaction_production_check(self, model, solver, threshold, + implicit_sinks=True): + """"""Run reaction production check method."""""" + prob = solver.create_problem() + + # Create flux variables + v = prob.namespace() + for reaction_id in model.reactions: + lower, upper = model.limits[reaction_id] + v.define([reaction_id], lower=lower, upper=upper) + + # Build mass balance constraints + massbalance_lhs = {compound: 0 for compound in model.compounds} + for spec, value in iteritems(model.matrix): + compound, reaction_id = spec + massbalance_lhs[compound] += v(reaction_id) * value + + # Create production variables and apply constraints + for compound, lhs in iteritems(massbalance_lhs): + if implicit_sinks: + # The constraint is merely >0 meaning that we have implicit + # sinks for all compounds. + prob.add_linear_constraints(lhs >= 0) + else: + prob.add_linear_constraints(lhs == 0) + + confirmed_production = set() + for reaction in model.reactions: + if all(c in confirmed_production for c, _ in + model.get_reaction_values(reaction)): + continue + + prob.set_objective(v(reaction)) + for sense in (lp.ObjectiveSense.Maximize, + lp.ObjectiveSense.Minimize): + try: + result = prob.solve(sense) + except lp.SolverError as e: + self.fail( + 'Failed to solve for compound, reaction: {}, {}:' + ' {}'.format(compound, reaction, e)) + + flux = result.get_value(v(reaction)) + for compound, value in model.get_reaction_values(reaction): + if compound in confirmed_production: + continue + + production = 0 + if sense == lp.ObjectiveSense.Maximize and flux > 0: + production = float(value) * flux + elif sense == lp.ObjectiveSense.Minimize and flux < 0: + production = float(value) * flux + + if production >= threshold: + confirmed_production.add(compound) + + for compound in sorted(model.compounds): + if compound not in confirmed_production: + yield compound + + def _log_epsilon_and_fail(self, epsilon, exc): + msg = ('Finding blocked compounds failed with epsilon set to {}. Try' + ' lowering the epsilon value to reduce artifical constraints' + ' on the model.'.format(epsilon)) + self.fail(msg, exc) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/primarypairs.py",".py","10601","255","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import logging +import random + +from ..command import Command, SolverCommandMixin, \ + FilePrefixAppendAction, convert_to_unicode +from ..formula import Formula, Atom, Radical, ParseError +from .. import findprimarypairs +from .. import mapmaker + +from six import text_type, iteritems + +logger = logging.getLogger(__name__) + + +class PrimaryPairsCommand(SolverCommandMixin, Command): + """"""Predict primary pairs of reactions. + + This command is used to predict element-transferring reactant/product pairs + in the reactions of the model. This can be used to determine the flow of + elements through reactions. + """""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--method', + choices=['fpp', 'mapmaker'], + default='fpp', help='Primary pair prediction method') + parser.add_argument( + '--exclude', metavar='reaction', type=convert_to_unicode, + default=[], action=FilePrefixAppendAction, + help=('Reaction to exclude (e.g. biomass reactions or' + ' macromolecule synthesis)')) + parser.add_argument( + '--report-element', metavar='element', type=text_type, default=[], + action='append', help=('Only output pairs predicted to transfer' + ' this element (e.g. C, N, P)')) + parser.add_argument( + '--report-all-transfers', action='store_true', + help=('Report all transfers instead of combining elements for' + ' each pair (only available for fpp).')) + parser.add_argument( + '--ambiguous', action='store_true', + help=('Report additional information about reactions where' + 'primary pair identification was ambiguous')) + parser.add_argument( + '--weights', action='append', default=[], type=text_type, + help=('Set weights for elements for inferring compound' + ' similarities (e.g. --weights N=0.4,C=1,H=0,R=20,*=0.6).' + ' The default value depends on the prediction method.')) + super(PrimaryPairsCommand, cls).init_parser(parser) + + def run(self): + # Check that elements are valid + elements = set() + for element in self._args.report_element: + if not hasattr(Atom, element): + self.argument_error('Invalid element: {}'.format(element)) + elements.add(Atom(element)) + + # Check that method can report all transfers if requested + if self._args.report_all_transfers and self._args.method != 'fpp': + self.argument_error( + 'Reporting all transfers is not available for this method:' + ' {}'.format(self._args.method)) + + if len(self._args.weights) > 0: + weights_dict, r_group_weight, default_weight = _parse_weights( + self._args.weights, default_weight=0.6) + + def element_weight(element): + if isinstance(element, Radical): + return r_group_weight + return weights_dict.get(element, default_weight) + else: + if self._args.method == 'fpp': + logger.info( + 'Using default element weights for {}:' + ' C=1, H=0, *=0.82'.format(self._args.method)) + element_weight = findprimarypairs.element_weight + elif self._args.method == 'mapmaker': + logger.info( + 'Using default element weights for {}:' + ' H=0, N=0.4, O=0.4, P=0.4, R=40, *=1'.format( + self._args.method)) + element_weight = mapmaker.default_weight + + # Mapping from compound id to formula + compound_formula = {} + for compound in self._model.compounds: + if compound.formula is not None: + try: + f = Formula.parse(compound.formula).flattened() + if not f.is_variable(): + compound_formula[compound.id] = f + else: + logger.warning( + 'Skipping variable formula {}: {}'.format( + compound.id, compound.formula)) + except ParseError as e: + msg = ( + 'Error parsing formula' + ' for compound {}:\n{}\n{}'.format( + compound.id, e, compound.formula)) + if e.indicator is not None: + msg += '\n{}'.format(e.indicator) + logger.warning(msg) + + # Set of excluded reactions + exclude = set(self._args.exclude) + + def iter_reactions(): + for reaction in self._model.reactions: + if (reaction.id not in self._model.model or + reaction.id in exclude): + continue + + if reaction.equation is None: + logger.warning( + 'Reaction {} has no reaction equation'.format( + reaction.id)) + continue + + if any(c.name not in compound_formula + for c, _ in reaction.equation.compounds): + logger.warning( + 'Reaction {} has compounds with undefined' + ' formula'.format(reaction.id)) + continue + + yield reaction + + if self._args.method == 'fpp': + result = self._run_find_primary_pairs( + compound_formula, iter_reactions(), element_weight) + elif self._args.method == 'mapmaker': + result = self._run_mapmaker( + compound_formula, iter_reactions(), element_weight) + else: + self.argument_error('Unknown method: {}'.format(self._args.method)) + + if not self._args.report_all_transfers: + result = self._combine_transfers(result) + + for reaction_id, c1, c2, form in result: + if len(elements) == 0 or any(e in form for e in elements): + print('{}\t{}\t{}\t{}'.format(reaction_id, c1, c2, form)) + + def _combine_transfers(self, result): + """"""Combine multiple pair transfers into one."""""" + transfers = {} + for reaction_id, c1, c2, form in result: + key = reaction_id, c1, c2 + combined_form = transfers.setdefault(key, Formula()) + transfers[key] = combined_form | form + + for (reaction_id, c1, c2), form in iteritems(transfers): + yield reaction_id, c1, c2, form + + def _run_find_primary_pairs( + self, compound_formula, reactions, element_weight): + reaction_pairs = [(r.id, r.equation) for r in reactions] + ambig = self._args.ambiguous + prediction, _ = findprimarypairs.predict_compound_pairs_iterated( + reaction_pairs, compound_formula, + ambig, element_weight=element_weight) + + for reaction_id, _ in reaction_pairs: + if reaction_id not in prediction: + logger.warning('Failed to predict pairs for {}'.format( + reaction_id)) + continue + + pairs, balance = prediction[reaction_id] + if len(balance) > 0: + logger.warning('Reaction {} is not balanced!'.format( + reaction_id)) + + for (c1, c2), forms in sorted(iteritems(pairs)): + for form in forms: + yield reaction_id, c1, c2, form + + def _run_mapmaker(self, compound_formula, reactions, element_weight): + solver = self._get_solver(integer=True) + ambiguous = set() + for reaction in reactions: + logger.info('Predicting reaction {}...'.format(reaction.id)) + try: + transfer = list(mapmaker.predict_compound_pairs( + reaction.equation, compound_formula, solver, + weight_func=element_weight)) + if self._args.ambiguous: + if len(transfer) > 1: + ambiguous.add(reaction.id) + except mapmaker.UnbalancedReactionError: + logger.info('Reaction {} is not balanced! Skipping...'.format( + reaction.id)) + continue + if len(transfer) == 0: + logger.warning('Reaction {} has no predicted transfer!'.format( + reaction.id)) + continue + + for (c1, c2), form in sorted( + iteritems(random.sample(transfer, 1)[0])): + yield reaction.id, c1, c2, form + if self._args.ambiguous: + for rxn_ambig in ambiguous: + logger.info('Ambiguous Transfers ' + 'in Reaction: {}'.format(rxn_ambig)) + + +def _parse_weights(weight_args, default_weight=0.6): + """"""Parse list of weight assignments."""""" + weights_dict = {} + r_group_weight = default_weight + for weight_arg in weight_args: + for weight_assignment in weight_arg.split(','): + if '=' not in weight_assignment: + raise ValueError( + 'Invalid weight assignment: {}'.format(weight_assignment)) + + key, value = weight_assignment.split('=', 1) + value = float(value) + if key == 'R': + r_group_weight = value + elif key == '*': + default_weight = value + elif hasattr(Atom, key): + weights_dict[Atom(key)] = value + else: + raise ValueError('Invalid element: {}'.format(key)) + + return weights_dict, r_group_weight, default_weight +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/tableexport.py",".py","8860","234","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015-2020 Keith Dufault-Thompson +# copyright 2017 Jon Lund Steffensen +# Copyright 2020 Christopher Powers +# Copyright 2020 Elysha Sameth + +from __future__ import unicode_literals + +import re +import json +import logging + +from collections import defaultdict +from six import text_type, string_types, integer_types, itervalues + +from ..command import Command +from ..expression import boolean + +logger = logging.getLogger(__name__) + + +_JSON_TYPES = string_types + integer_types + ( + dict, list, tuple, float, bool, type(None)) +_QUOTE_REGEXP = re.compile(r'[\t\n]') + + +def _encode_value(value): + if value is None: + return '' + if not isinstance(value, _JSON_TYPES): + value = text_type(value) + if (isinstance(value, string_types) and not _QUOTE_REGEXP.search(value) and + value != ''): + return value + return json.dumps(value) + + +class ExportTableCommand(Command): + """"""Export parts of the model as tab separated tables. + + This command can export various parts of the model as a TSV table. + The output is written to standard output. The type argument is used + to determine which part of the model to export: + + - reactions: Export reactions and reaction metadata + - translated-reactions: Export reactions with translated compounds + - compounds: Export compounds and compound metadata + - exchange: Export the list of exchange compounds/reactions + - limits: Export list of internal flux limits + - metadata: Export general model metadata + - genes: Export list of genes to reactions + """""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + 'export', metavar='export_type', + choices=['reactions', 'compounds', 'medium', 'exchange', 'limits', + 'metadata', 'genes', 'translated-reactions'], + help='Type of model data to export') + + def run(self): + export_type = self._args.export + if export_type == 'reactions': + self._reaction_export() + elif export_type == 'translated-reactions': + self._reaction_translated_export() + elif export_type == 'compounds': + self._compound_export() + elif export_type == 'exchange' or export_type == 'medium': + self._exchange_export() + elif export_type == 'limits': + self._limits_export() + elif export_type == 'metadata': + self._metadata_export() + elif export_type == 'genes': + self._gene_export() + + def _reaction_export(self): + property_set = set() + for reaction in self._model.reactions: + property_set.update(reaction.properties) + + property_list_sorted = sorted( + property_set, key=lambda x: (x != 'id', x != 'equation', x)) + + print('\t'.join( + [text_type(x) for x in property_list_sorted] + ['in_model'])) + + model_reactions = set(self._model.model) + for reaction in self._model.reactions: + line_content = [reaction.properties.get(property) + for property in property_list_sorted] + in_model = reaction.id in model_reactions + line_content.append(in_model) + print('\t'.join(_encode_value(value) for value in line_content)) + + def _reaction_translated_export(self): + property_set = set() + for reaction in self._model.reactions: + property_set.update(reaction.properties) + + property_list_sorted = sorted( + property_set, key=lambda x: (x != 'id', x != 'equation', x)) + + print('\t'.join( + [text_type(x) for x in property_list_sorted] + ['in_model'] + + ['translated_equation'])) + + compounds_name = {} + for cpd in self._model.compounds: + if cpd.name: + compounds_name[cpd.id] = cpd.name + else: + compounds_name[cpd.id] = cpd.id + + model_reactions = set(self._model.model) + for reaction in self._model.reactions: + # get translated equation + rx = reaction.equation + translated_equation = str(rx.translated_compounds( + lambda x: compounds_name.get(x, x))) + + line_content = [reaction.properties.get(property) + for property in property_list_sorted] + in_model = reaction.id in model_reactions + line_content.append(in_model) + line_content.append(translated_equation) + print('\t'.join(_encode_value(value) for value in line_content)) + + def _compound_export(self): + compound_set = set() + for compound in self._model.compounds: + compound_set.update(compound.properties) + + compound_list_sorted = sorted( + compound_set, key=lambda x: (x != 'id', x != 'name', x)) + + print('\t'.join( + [text_type(x) for x in compound_list_sorted] + ['in_model'])) + + metabolic_model = self._model.create_metabolic_model() + model_compounds = set(x.name for x in metabolic_model.compounds) + for compound in self._model.compounds: + line_content = [compound.properties.get(property) + for property in compound_list_sorted] + in_model = compound.id in model_compounds + line_content.append(in_model) + print('\t'.join(_encode_value(value) for value in line_content)) + + def _exchange_export(self): + print('{}\t{}\t{}\t{}'.format('Compound ID', 'Reaction ID', + 'Lower Limit', 'Upper Limit')) + default_flux = self._model.default_flux_limit + + for compound, reaction, lower, upper in itervalues( + self._model.exchange): + if lower is None: + lower = -1 * default_flux + + if upper is None: + upper = default_flux + + print('\t'.join(_encode_value(value) for value in ( + compound, reaction, lower, upper))) + + def _limits_export(self): + print('{}\t{}\t{}'.format( + 'Reaction ID', 'Lower Limits', 'Upper Limits')) + for reaction, lower, upper in itervalues(self._model.limits): + print('\t'.join(_encode_value(value) for value in ( + reaction, lower, upper))) + + def _metadata_export(self): + print('Model Name\t{}'.format( + _encode_value(self._model.name))) + print('Biomass Reaction\t{}'.format( + _encode_value(self._model.biomass_reaction))) + print('Default Flux Limits\t{}'.format( + _encode_value(self._model.default_flux_limit))) + + if self._model.version_string is not None: + print('Model version\t{}'.format( + _encode_value(self._model.version_string))) + + def _gene_export(self): + gene_assoc = defaultdict(list) + + model_reactions = set(self._model.model) + + for reaction in self._model.reactions: + assoc = None + if reaction.genes is None: + continue + elif isinstance(reaction.genes, string_types): + assoc = boolean.Expression(reaction.genes) + else: + variables = [boolean.Variable(g) for g in reaction.genes] + assoc = boolean.Expression(boolean.And(*variables)) + + for gene in assoc.variables: + gene_assoc[gene].append(reaction.id) + + print('{}\t{}\t{}'.format( + 'gene_id', 'reaction_in_model', 'reaction_not_in_model')) + + for gene, reaction in gene_assoc.items(): + in_model = [] + not_in_model = [] + for r in reaction: + if r in model_reactions: + in_model.append(r) + else: + not_in_model.append(r) + print('{}\t{}\t{}'.format( + str(gene), '#'.join([_encode_value(rxn) for rxn in in_model]), + '#'.join([_encode_value(rxn) for rxn in not_in_model]))) + # print('{}\t{}'.format(str(gene), ( + # '#'.join([_encode_value(value) for value in reaction])))) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/fva.py",".py","4785","131","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import time +import logging +from itertools import product + +from ..command import (Command, SolverCommandMixin, MetabolicMixin, + ObjectiveMixin, LoopRemovalMixin, ParallelTaskMixin) +from ..util import MaybeRelative +from .. import fluxanalysis + +logger = logging.getLogger(__name__) + + +class FluxVariabilityCommand(MetabolicMixin, SolverCommandMixin, + LoopRemovalMixin, ObjectiveMixin, + ParallelTaskMixin, Command): + """"""Run flux variablity analysis on the model."""""" + + _supported_loop_removal = ['none', 'tfba'] + + @classmethod + def init_parser(cls, parser): + parser.add_argument('--threshold', + help='Threshold of objective reaction ' + 'flux. Can be an absolute flux value ' + '(0.25) or percentage of maximum ' + 'biomass.)', + type=MaybeRelative, + default=MaybeRelative('100%')) + super(FluxVariabilityCommand, cls).init_parser(parser) + + def run(self): + """"""Run flux variability command"""""" + + # Load compound information + def compound_name(id): + if id not in self._model.compounds: + return id + return self._model.compounds[id].properties.get('name', id) + + reaction = self._get_objective() + if not self._mm.has_reaction(reaction): + self.fail( + 'Specified reaction is not in model: {}'.format(reaction)) + + loop_removal = self._get_loop_removal_option() + enable_tfba = loop_removal == 'tfba' + if enable_tfba: + solver = self._get_solver(integer=True) + else: + solver = self._get_solver() + + start_time = time.time() + + try: + fba_fluxes = dict(fluxanalysis.flux_balance( + self._mm, reaction, tfba=False, solver=solver)) + except fluxanalysis.FluxBalanceError as e: + self.report_flux_balance_error(e) + + threshold = self._args.threshold + if threshold.relative: + threshold.reference = fba_fluxes[reaction] + + logger.info('Setting objective threshold to {}'.format( + threshold)) + + handler_args = ( + self._mm, solver, enable_tfba, float(threshold), reaction) + executor = self._create_executor( + FVATaskHandler, handler_args, cpus_per_worker=2) + + def iter_results(): + results = {} + with executor: + for (reaction_id, direction), value in executor.imap_unordered( + product(self._mm.reactions, (1, -1)), 16): + if reaction_id not in results: + results[reaction_id] = value + continue + + other_value = results[reaction_id] + if direction == -1: + bounds = value, other_value + else: + bounds = other_value, value + + yield reaction_id, bounds + + executor.join() + + for reaction_id, (lower, upper) in iter_results(): + rx = self._mm.get_reaction(reaction_id) + rxt = rx.translated_compounds(compound_name) + print('{}\t{}\t{}\t{}'.format(reaction_id, lower, upper, rxt)) + + logger.info('Solving took {:.2f} seconds'.format( + time.time() - start_time)) + + +class FVATaskHandler(object): + def __init__(self, model, solver, enable_tfba, threshold, reaction): + self._problem = fluxanalysis.FluxBalanceProblem(model, solver) + if enable_tfba: + self._problem.add_thermodynamic() + + self._problem.prob.add_linear_constraints( + self._problem.get_flux_var(reaction) >= threshold) + + def handle_task(self, reaction_id, direction): + return self._problem.flux_bound(reaction_id, direction) +","Python" +"Metabolic","zhanglab/psamm","psamm/commands/duplicatescheck.py",".py","2688","70","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import logging + +from six import itervalues + +from ..command import Command +from psamm.datasource.native import reaction_signature + +logger = logging.getLogger(__name__) + + +class DuplicatesCheck(Command): + """"""Check for duplicated reactions in the model. + + This command reports any reactions in the model that appear more than + once. Stoichiometry and reaction directionality is by default disregarded + when checking for duplicates but can be enabled using the options. + """""" + + @classmethod + def init_parser(cls, parser): + parser.add_argument( + '--compare-direction', action='store_true', + help='Take reaction directionality into consideration.') + parser.add_argument( + '--compare-stoichiometry', action='store_true', + help='Take stoichiometry into consideration.') + super(DuplicatesCheck, cls).init_parser(parser) + + def run(self): + """"""Run check for duplicates"""""" + + # Create dictonary of signatures + database_signatures = {} + for entry in self._model.reactions: + signature = reaction_signature( + entry.equation, direction=self._args.compare_direction, + stoichiometry=self._args.compare_stoichiometry) + database_signatures.setdefault(signature, set()).add( + (entry.id, entry.equation, entry.filemark)) + + for reaction_set in itervalues(database_signatures): + if len(reaction_set) > 1: + print('Found {} duplicate reactions:'.format( + len(reaction_set))) + for reaction, equation, filemark in reaction_set: + result = ' - {}: {}'.format(reaction, equation) + if filemark is not None: + result += ' (found in {})'.format(filemark) + print(result) +","Python" +"Metabolic","zhanglab/psamm","psamm/lpsolver/glpk.py",".py","15096","449","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Linear programming solver using GLPK."""""" + +from __future__ import absolute_import + +import logging +from itertools import repeat, count +import numbers + +from six.moves import zip + +import swiglpk + +from .lp import Solver as BaseSolver +from .lp import Constraint as BaseConstraint +from .lp import Problem as BaseProblem +from .lp import Result as BaseResult +from .lp import (Expression, RelationSense, ObjectiveSense, VariableType, + InvalidResultError, ranged_property, SolverError) + +# Module-level logging +logger = logging.getLogger(__name__) + +# Logger specific to log messages from GLPK library +_glpk_logger = logging.getLogger('glpk') + + +# Redirect GLPK terminal output to logger +def _term_hook(s): + _glpk_logger.debug(s.rstrip()) + + +swiglpk.glp_term_hook(_term_hook) + + +_INF = float('inf') + + +class GLPKError(SolverError): + """"""Error from calling GLPK library."""""" + + +class Solver(BaseSolver): + """"""Represents an LP-solver using GLPK."""""" + + def __init__(self): + super(Solver, self).__init__() + logger.warning('Support for GLPK solver is experimental!') + + def create_problem(self, **kwargs): + """"""Create a new LP-problem using the solver."""""" + return Problem(**kwargs) + + +class Problem(BaseProblem): + """"""Represents an LP-problem of a :class:`.Solver`."""""" + + VARTYPE_MAP = { + VariableType.Continuous: swiglpk.GLP_CV, + VariableType.Binary: swiglpk.GLP_BV, + VariableType.Integer: swiglpk.GLP_IV + } + + OBJ_SENSE_MAP = { + ObjectiveSense.Maximize: swiglpk.GLP_MAX, + ObjectiveSense.Minimize: swiglpk.GLP_MIN + } + + def __init__(self, **kwargs): + self._p = swiglpk.glp_create_prob() + + self._variables = {} + self._constraints = {} + + self._do_presolve = True + + # Initialize simplex tolerances to default values + parm = swiglpk.glp_smcp() + swiglpk.glp_init_smcp(parm) + self._feasibility_tolerance = parm.tol_bnd + self._optimality_tolerance = parm.tol_dj + + # Initialize mip tolerance to default value + parm = swiglpk.glp_iocp() + swiglpk.glp_init_iocp(parm) + self._integrality_tolerance = parm.tol_int + + self._result = None + + def __del__(self): + swiglpk.glp_delete_prob(self._p) + + @property + def glpk(self): + """"""The underlying GLPK (SWIG) object."""""" + return self._p + + def define(self, *names, **kwargs): + """"""Define a variable in the problem. + + Variables must be defined before they can be accessed by var() or + set(). This function takes keyword arguments lower and upper to define + the bounds of the variable (default: -inf to inf). The keyword argument + types can be used to select the type of the variable (Continuous + (default), Binary or Integer). Setting any variables different than + Continuous will turn the problem into an MILP problem. Raises + ValueError if a name is already defined. + """""" + names = tuple(names) + for name in names: + if name in self._variables: + raise ValueError('Variable already defined: {!r}'.format(name)) + + lower = kwargs.get('lower', None) + upper = kwargs.get('upper', None) + vartype = kwargs.get('types', None) + + # Repeat values if a scalar is given + if lower is None or isinstance(lower, numbers.Number): + lower = repeat(lower, len(names)) + if upper is None or isinstance(upper, numbers.Number): + upper = repeat(upper, len(names)) + if vartype is None or vartype in ( + VariableType.Continuous, VariableType.Binary, + VariableType.Integer): + vartype = repeat(vartype, len(names)) + + # Assign default values + vartype = tuple(VariableType.Continuous if value is None else value + for value in vartype) + + if len(names) == 0: + return + + var_indices = count(swiglpk.glp_add_cols(self._p, len(names))) + + for i, name, lb, ub, vt in zip( + var_indices, names, lower, upper, vartype): + self._variables[name] = i + + lb = None if lb == -_INF else lb + ub = None if ub == _INF else ub + + if lb is None and ub is None: + swiglpk.glp_set_col_bnds(self._p, i, swiglpk.GLP_FR, 0, 0) + elif lb is None: + swiglpk.glp_set_col_bnds( + self._p, i, swiglpk.GLP_UP, 0, float(ub)) + elif ub is None: + swiglpk.glp_set_col_bnds( + self._p, i, swiglpk.GLP_LO, float(lb), 0) + elif lb == ub: + swiglpk.glp_set_col_bnds( + self._p, i, swiglpk.GLP_FX, float(lb), 0) + else: + swiglpk.glp_set_col_bnds( + self._p, i, swiglpk.GLP_DB, float(lb), float(ub)) + + if vt != VariableType.Continuous: + swiglpk.glp_set_col_kind(self._p, i, self.VARTYPE_MAP[vt]) + + self._do_presolve = True + + def has_variable(self, name): + """"""Check whether variable is defined in the model."""""" + return name in self._variables + + def _add_constraints(self, relation): + """"""Add the given relation as one or more constraints. + + Return a list of the names of the constraints added. + """""" + + expression = relation.expression + constr_count = sum(True for _ in expression.value_sets()) + if constr_count == 0: + return [] + + row_indices = count(swiglpk.glp_add_rows(self._p, constr_count)) + + names = [] + for i, value_set in zip(row_indices, expression.value_sets()): + value_set = list(value_set) + var_indices = swiglpk.intArray(1 + len(value_set)) + var_values = swiglpk.doubleArray(1 + len(value_set)) + for j, (variable, coeff) in enumerate(value_set): + var_indices[1 + j] = self._variables[variable] + var_values[1 + j] = float(coeff) + + swiglpk.glp_set_mat_row( + self._p, i, len(value_set), var_indices, var_values) + + if relation.sense == RelationSense.Greater: + swiglpk.glp_set_row_bnds( + self._p, i, swiglpk.GLP_LO, -float(expression.offset), 0) + elif relation.sense == RelationSense.Less: + swiglpk.glp_set_row_bnds( + self._p, i, swiglpk.GLP_UP, 0, -float(expression.offset)) + else: + swiglpk.glp_set_row_bnds( + self._p, i, swiglpk.GLP_FX, -float(expression.offset), 0) + + names.append(i) + + self._do_presolve = True + + return names + + def add_linear_constraints(self, *relations): + """"""Add constraints to the problem. + + Each constraint is represented by a Relation, and the + expression in that relation can be a set expression. + """""" + constraints = [] + + for relation in relations: + if self._check_relation(relation): + constraints.append(Constraint(self, None)) + else: + for name in self._add_constraints(relation): + constraints.append(Constraint(self, name)) + + return constraints + + def set_objective(self, expression): + """"""Set objective of problem."""""" + + if isinstance(expression, numbers.Number): + # Allow expressions with no variables as objective, + # represented as a number + expression = Expression(offset=expression) + + # Clear previous objective + for i in range(swiglpk.glp_get_num_cols(self._p)): + swiglpk.glp_set_obj_coef(self._p, 1 + i, 0) + + for variable, value in expression.values(): + var_index = self._variables[variable] + swiglpk.glp_set_obj_coef(self._p, var_index, float(value)) + + swiglpk.glp_set_obj_coef(self._p, 0, float(expression.offset)) + + set_linear_objective = set_objective + """"""Set objective of the problem. + + .. deprecated:: 0.19 + Use :meth:`set_objective` instead. + """""" + + def set_objective_sense(self, sense): + """"""Set type of problem (maximize or minimize)."""""" + + if sense not in (ObjectiveSense.Minimize, ObjectiveSense.Maximize): + raise ValueError('Invalid objective sense') + + swiglpk.glp_set_obj_dir(self._p, self.OBJ_SENSE_MAP[sense]) + + def solve_unchecked(self, sense=None): + """"""Solve problem and return result. + + The user must manually check the status of the result to determine + whether an optimal solution was found. A :class:`SolverError` may still + be raised if the underlying solver raises an exception. + """""" + if sense is not None: + self.set_objective_sense(sense) + + parm = swiglpk.glp_smcp() + swiglpk.glp_init_smcp(parm) + if self._do_presolve: + parm.presolve = swiglpk.GLP_ON + self._do_presolve = False + else: + parm.presolve = swiglpk.GLP_OFF + + parm.tol_bnd = self._feasibility_tolerance + parm.tol_dj = self._optimality_tolerance + + logger.debug('Solving using glp_simplex()') + r = swiglpk.glp_simplex(self._p, parm) + if r in (swiglpk.GLP_ENOPFS, swiglpk.GLP_ENODFS): + self._result = Result(self, r) + return self._result + elif r != 0: + raise GLPKError('glp_simplex: {}'.format(r)) + + if swiglpk.glp_get_num_int(self._p) == 0: + self._result = Result(self) + else: + # The intopt MILP solver needs an optimal solution to the LP + # relaxation. Therefore, glp_simplex has to run before glp_intopt + # for MILP problems. + logger.debug('Solving using glp_intopt()') + parm = swiglpk.glp_iocp() + swiglpk.glp_init_iocp(parm) + parm.tol_int = self._integrality_tolerance + r = swiglpk.glp_intopt(self._p, parm) + if r != 0: + raise GLPKError('glp_intopt: {}'.format(r)) + + self._result = MIPResult(self) + + return self._result + + @property + def result(self): + return self._result + + @ranged_property(min=None, max=None) + def feasibility_tolerance(self): + """"""Feasibility tolerance."""""" + return self._feasibility_tolerance + + @feasibility_tolerance.setter + def feasibility_tolerance(self, value): + logger.info('Setting feasibility tolerance to {!r}'.format(value)) + self._feasibility_tolerance = value + + @ranged_property(min=None, max=None) + def optimality_tolerance(self): + """"""Optimality tolerance."""""" + return self._optimality_tolerance + + @optimality_tolerance.setter + def optimality_tolerance(self, value): + logger.info('Setting optimality tolerance to {!r}'.format(value)) + self._optimality_tolerance = value + + @ranged_property(min=None, max=None) + def integrality_tolerance(self): + """"""Integrality tolerance."""""" + return self._integrality_tolerance + + @integrality_tolerance.setter + def integrality_tolerance(self, value): + logger.info('Setting integrality tolerance to {!r}'.format(value)) + self._integrality_tolerance = value + + +class Constraint(BaseConstraint): + """"""Represents a constraint in a :class:`.Problem`."""""" + + def __init__(self, prob, name): + self._prob = prob + self._name = name + + def delete(self): + if self._name is not None: + swiglpk.glp_set_row_bnds( + self._prob._p, self._name, swiglpk.GLP_FR, 0, 0) + + +class Result(BaseResult): + """"""Represents the solution to a :class:`.Problem`. + + This object will be returned from the solve() method on :class:`.Problem` + or by accessing the result property on :class:`.Problem` after solving a + problem. This class should not be instantiated manually. + + Result will evaluate to a boolean according to the success of the + solution, so checking the truth value of the result will immediately + indicate whether solving was successful. + """""" + + def __init__(self, prob, ret_val=0): + self._problem = prob + self._ret_val = ret_val + + def _check_valid(self): + if self._problem.result != self: + raise InvalidResultError() + + @property + def success(self): + """"""Return boolean indicating whether a solution was found."""""" + self._check_valid() + if self._ret_val != 0: + return False + return swiglpk.glp_get_status(self._problem._p) == swiglpk.GLP_OPT + + @property + def unbounded(self): + """"""Whether solution is unbounded"""""" + self._check_valid() + if self._ret_val != 0: + return self._ret_val == swiglpk.GLP_ENODFS + return swiglpk.glp_get_status(self._problem._p) == swiglpk.GLP_UNBND + + @property + def status(self): + """"""Return string indicating the error encountered on failure."""""" + self._check_valid() + if self._ret_val == swiglpk.GLP_ENOPFS: + return 'No primal feasible solution' + elif self._ret_val == swiglpk.GLP_ENODFS: + return 'No dual feasible solution' + return str(swiglpk.glp_get_status(self._problem._p)) + + def _has_variable(self, variable): + """"""Whether variable exists in the solution."""""" + return self._problem.has_variable(variable) + + def _get_value(self, variable): + """"""Return value of variable in solution."""""" + return swiglpk.glp_get_col_prim( + self._problem._p, self._problem._variables[variable]) + + def get_value(self, expression): + """"""Return value of expression."""""" + self._check_valid() + return super(Result, self).get_value(expression) + + +class MIPResult(Result): + """"""Specialization of Result for MIP problems."""""" + + @property + def success(self): + self._check_valid() + return swiglpk.glp_mip_status(self._problem._p) == swiglpk.GLP_OPT + + @property + def status(self): + self._check_valid() + return str(swiglpk.glp_mip_status(self._problem._p)) + + def _get_value(self, variable): + """"""Return value of variable in solution."""""" + return swiglpk.glp_mip_col_val( + self._problem._p, self._problem._variables[variable]) +","Python" +"Metabolic","zhanglab/psamm","psamm/lpsolver/cplex.py",".py","17049","473","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Linear programming solver using Cplex."""""" + +from __future__ import absolute_import + +import logging +from itertools import repeat, count +import numbers + +from six import text_type, raise_from +from six.moves import zip +import cplex as cp + +from .lp import Solver as BaseSolver +from .lp import Constraint as BaseConstraint +from .lp import Problem as BaseProblem +from .lp import Result as BaseResult +from .lp import (SolverError, Expression, Product, RelationSense, + ObjectiveSense, VariableType, InvalidResultError, + RangedProperty) +from ..util import LoggerFile + +# Module-level logging +logger = logging.getLogger(__name__) + +_INF = float('inf') + + +class Solver(BaseSolver): + """"""Represents an LP-solver using Cplex"""""" + + def create_problem(self, **kwargs): + """"""Create a new LP-problem using the solver"""""" + return Problem(**kwargs) + + +class CplexRangedProperty(RangedProperty): + """"""Decorator for translating Cplex ranged properties."""""" + def __init__(self, get_prop, doc=None): + if doc is None: + doc = get_prop.__doc__ + + def fset(obj, value): + prop = get_prop(obj) + prop_name = '.'.join(text_type(prop).split('.')[1:]) + logger.info('Setting {} to {!r}'.format(prop_name, value)) + prop.set(value) + + super(CplexRangedProperty, self).__init__( + fget=lambda obj: get_prop(obj).get(), + fset=fset, + fdel=lambda obj: get_prop(obj).reset(), + fmin=lambda obj: get_prop(obj).min(), + fmax=lambda obj: get_prop(obj).max(), + doc=doc) + + +class Problem(BaseProblem): + """"""Represents an LP-problem of a cplex.Solver"""""" + + VARTYPE_MAP = { + VariableType.Continuous: 'C', + VariableType.Binary: 'B', + VariableType.Integer: 'I' + } + + CONSTR_SENSE_MAP = { + RelationSense.Equals: 'E', + RelationSense.Greater: 'G', + RelationSense.Less: 'L' + } + + def __init__(self, **kwargs): + self._cp = cp.Cplex() + + # Set up output to go to logging streams + cplex_logger = logging.getLogger('cplex') + log_stream = LoggerFile(cplex_logger, logging.DEBUG) + warning_stream = LoggerFile(cplex_logger, logging.WARNING) + error_stream = LoggerFile(cplex_logger, logging.ERROR) + + self._cp.set_log_stream(log_stream) + self._cp.set_results_stream(log_stream) + self._cp.set_warning_stream(warning_stream) + self._cp.set_error_stream(error_stream) + + # Set tolerances. By default, we decrease to 1e-9. + self.feasibility_tolerance.value = ( + kwargs.get('feasibility_tolerance', 1e-9)) + self.optimality_tolerance.value = ( + kwargs.get('optimality_tolerance', 1e-9)) + + # Set number of threads + if 'threads' in kwargs: + logger.info('Setting threads to {!r}'.format(kwargs['threads'])) + self._cp.parameters.threads.set(kwargs['threads']) + + self._cp.parameters.emphasis.numerical.set(True) + + self._variables = {} + self._var_names = (i for i in count(0)) + self._constr_names = ('c'+str(i) for i in count(1)) + + # Keep track of the objective variables that are non-zero + self._non_zero_objective = set() + + self._result = None + self._solve_count = 0 + + @property + def cplex(self): + """"""The underlying Cplex object"""""" + return self._cp + + def define(self, *names, **kwargs): + """"""Define a variable in the problem. + + Variables must be defined before they can be accessed by var() or + set(). This function takes keyword arguments lower and upper to define + the bounds of the variable (default: -inf to inf). The keyword argument + types can be used to select the type of the variable (Continuous + (default), Binary or Integer). Setting any variables different than + Continuous will turn the problem into an MILP problem. Raises + ValueError if a name is already defined. + """""" + names = tuple(names) + for name in names: + if name in self._variables: + raise ValueError('Variable already defined: {!r}'.format(name)) + + lower = kwargs.get('lower', None) + upper = kwargs.get('upper', None) + vartype = kwargs.get('types', None) + + # Repeat values if a scalar is given + if lower is None or isinstance(lower, numbers.Number): + lower = repeat(lower, len(names)) + if upper is None or isinstance(upper, numbers.Number): + upper = repeat(upper, len(names)) + if vartype is None or vartype in ( + VariableType.Continuous, VariableType.Binary, + VariableType.Integer): + vartype = repeat(vartype, len(names)) + + lp_names = tuple(next(self._var_names) for name in names) + + # Assign default values + lower = (-cp.infinity if value is None or value == -_INF + else float(value) for value in lower) + upper = (cp.infinity if value is None or value == _INF + else float(value) for value in upper) + vartype = tuple(VariableType.Continuous if value is None else value + for value in vartype) + + args = {'lb': tuple(lower), 'ub': tuple(upper)} + if any(value != VariableType.Continuous for value in vartype): + # Set types only if some are integer (otherwise Cplex will change + # the solver to MILP). + args['types'] = tuple(Problem.VARTYPE_MAP[t] for t in vartype) + + self._variables.update(zip(names, lp_names)) + self._cp.variables.add(**args) + + def has_variable(self, name): + """"""Check whether variable is defined in the model."""""" + return name in self._variables + + def _add_constraints(self, relation): + """"""Add the given relation as one or more constraints + + Return a list of the names of the constraints added. + """""" + expression = relation.expression + pairs = [] + for value_set in expression.value_sets(): + ind, val = zip(*((self._variables[variable], float(value)) + for variable, value in value_set)) + pairs.append(cp.SparsePair(ind=ind, val=val)) + + names = [next(self._constr_names) for _ in pairs] + + sense = self.CONSTR_SENSE_MAP[relation.sense] + self._cp.linear_constraints.add( + names=names, lin_expr=pairs, + senses=tuple(repeat(sense, len(pairs))), + rhs=tuple(repeat(float(-expression.offset), len(pairs)))) + + return names + + def add_linear_constraints(self, *relations): + """"""Add constraints to the problem + + Each constraint is represented by a Relation, and the + expression in that relation can be a set expression. + """""" + constraints = [] + + for relation in relations: + if self._check_relation(relation): + constraints.append(Constraint(self, None)) + else: + for name in self._add_constraints(relation): + constraints.append(Constraint(self, name)) + + return constraints + + def set_objective(self, expression): + """"""Set objective expression of the problem."""""" + + if isinstance(expression, numbers.Number): + # Allow expressions with no variables as objective, + # represented as a number + expression = Expression(offset=expression) + + linear = [] + quad = [] + + # Reset previous objective. + for var in self._non_zero_objective: + if var not in expression: + if not isinstance(var, Product): + linear.append((self._variables[var], 0)) + else: + t = self._variables[var[0]], self._variables[var[1]], 0 + quad.append(t) + + self._non_zero_objective.clear() + + # Set actual objective values + for var, value in expression.values(): + if not isinstance(var, Product): + self._non_zero_objective.add(var) + linear.append((self._variables[var], float(value))) + else: + if len(var) > 2: + raise ValueError('Invalid objective: {}'.format(var)) + self._non_zero_objective.add(var) + var1 = self._variables[var[0]] + var2 = self._variables[var[1]] + if var1 == var2: + value *= 2 + quad.append((var1, var2, float(value))) + + # We have to build the set of variables to + # update so that we can avoid calling set_linear if the set is empty. + # This is due to set_linear failing if the input is an empty + # iterable. + if len(linear) > 0: + self._cp.objective.set_linear(linear) + if len(quad) > 0: + self._cp.objective.set_quadratic_coefficients(quad) + + if hasattr(self._cp.objective, 'set_offset'): + self._cp.objective.set_offset(float(expression.offset)) + + set_linear_objective = set_objective + """"""Set objective of the problem. + + .. deprecated:: 0.19 + Use :meth:`set_objective` instead. + """""" + + def set_objective_sense(self, sense): + """"""Set type of problem (maximize or minimize)"""""" + if sense == ObjectiveSense.Minimize: + self._cp.objective.set_sense(self._cp.objective.sense.minimize) + elif sense == ObjectiveSense.Maximize: + self._cp.objective.set_sense(self._cp.objective.sense.maximize) + else: + raise ValueError('Invalid objective sense') + + def _reset_problem_type(self): + """"""Reset problem type to whatever is appropriate."""""" + + # Only need to reset the type after the first solve. This also works + # around a bug in Cplex where get_num_binary() is some rare cases + # causes a segfault. + if self._solve_count > 0: + integer_count = 0 + for func in (self._cp.variables.get_num_binary, + self._cp.variables.get_num_integer, + self._cp.variables.get_num_semicontinuous, + self._cp.variables.get_num_semiinteger): + integer_count += func() + + integer = integer_count > 0 + quad_constr = self._cp.quadratic_constraints.get_num() > 0 + quad_obj = self._cp.objective.get_num_quadratic_variables() > 0 + + if not integer: + if quad_constr: + new_type = self._cp.problem_type.QCP + elif quad_obj: + new_type = self._cp.problem_type.QP + else: + new_type = self._cp.problem_type.LP + else: + if quad_constr: + new_type = self._cp.problem_type.MIQCP + elif quad_obj: + new_type = self._cp.problem_type.MIQP + else: + new_type = self._cp.problem_type.MILP + + logger.debug('Setting problem type to {}...'.format( + self._cp.problem_type[new_type])) + self._cp.set_problem_type(new_type) + else: + logger.debug('Problem type is {}'.format( + self._cp.problem_type[self._cp.get_problem_type()])) + + # Force QP/MIQP solver to look for global optimum. We set it here only + # for QP/MIQP problems to avoid the warnings generated for other + # problem types when this parameter is set. + quad_obj = self._cp.objective.get_num_quadratic_variables() > 0 + + if hasattr(self._cp.parameters, 'optimalitytarget'): + target_param = self._cp.parameters.optimalitytarget + else: + target_param = self._cp.parameters.solutiontarget + + if quad_obj: + target_param.set(target_param.values.optimal_global) + else: + target_param.set(target_param.values.auto) + + def _solve(self): + self._reset_problem_type() + try: + self._cp.solve() + except cp.exceptions.CplexSolverError as e: + raise_from(SolverError('Unable to solve: {}'.format(e)), e) + + self._solve_count += 1 + if (self._cp.solution.get_status() == + self._cp.solution.status.abort_user): + raise KeyboardInterrupt() + + def solve_unchecked(self, sense=None): + """"""Solve problem and return result. + + The user must manually check the status of the result to determine + whether an optimal solution was found. A :class:`SolverError` may still + be raised if the underlying solver raises an exception. + """""" + if sense is not None: + self.set_objective_sense(sense) + + self._solve() + self._result = Result(self) + + return self._result + + @property + def result(self): + return self._result + + @CplexRangedProperty + def feasibility_tolerance(self): + """"""Feasibility tolerance."""""" + return self._cp.parameters.simplex.tolerances.feasibility + + @CplexRangedProperty + def optimality_tolerance(self): + """"""Optimality tolerance."""""" + return self._cp.parameters.simplex.tolerances.optimality + + @CplexRangedProperty + def integrality_tolerance(self): + """"""Integrality tolerance."""""" + return self._cp.parameters.mip.tolerances.integrality + + +class Constraint(BaseConstraint): + """"""Represents a constraint in a cplex.Problem"""""" + + def __init__(self, prob, name): + self._prob = prob + self._name = name + + def delete(self): + if self._name is not None: + self._prob._cp.linear_constraints.delete(self._name) + + +class Result(BaseResult): + """"""Represents the solution to a cplex.Problem + + This object will be returned from the cplex.Problem.solve() method or by + accessing the cplex.Problem.result property after solving a problem. This + class should not be instantiated manually. + + Result will evaluate to a boolean according to the success of the + solution, so checking the truth value of the result will immediately + indicate whether solving was successful. + """""" + + def __init__(self, prob): + self._problem = prob + + def _check_valid(self): + if self._problem.result != self: + raise InvalidResultError() + + @property + def success(self): + """"""Return boolean indicating whether a solution was found"""""" + self._check_valid() + return self._problem._cp.solution.get_status() in ( + self._problem._cp.solution.status.optimal, + self._problem._cp.solution.status.optimal_tolerance, + self._problem._cp.solution.status.MIP_optimal) + + @property + def status(self): + """"""Return string indicating the error encountered on failure"""""" + self._check_valid() + return self._problem._cp.solution.get_status_string() + + @property + def unbounded(self): + """"""Whether solution is unbounded"""""" + self._check_valid() + + cp = self._problem._cp + status = cp.solution.get_status() + presolve = cp.parameters.preprocessing.presolve.get() + if (status == cp.solution.status.infeasible_or_unbounded and + presolve): + # Disable presolve to obtain a definitive answer + logger.info('Disabling presolver and solving again to determine' + ' whether objective is unbounded.') + cp.parameters.preprocessing.presolve.set(False) + try: + self._problem._solve() + finally: + cp.parameters.preprocessing.presolve.set(True) + + status = cp.solution.get_status() + + return status == cp.solution.status.unbounded + + def _get_value(self, var): + """"""Return value of variable in solution."""""" + return self._problem._cp.solution.get_values( + self._problem._variables[var]) + + def _has_variable(self, var): + """"""Whether variable exists in the solution."""""" + return self._problem.has_variable(var) + + def get_value(self, expression): + """"""Return value of expression."""""" + self._check_valid() + return super(Result, self).get_value(expression) +","Python" +"Metabolic","zhanglab/psamm","psamm/lpsolver/__init__.py",".py","755","19","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen + +""""""Linear programming solver module"""""" +","Python" +"Metabolic","zhanglab/psamm","psamm/lpsolver/lp.py",".py","30327","901","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Base objects for representation of LP problems. + +A linear programming problem is built from a number of constraints and an +objective function. The objective function is a linear expression represented +by :class:`.Expression`. The constraints are represented by :class:`.Relation`, +created from a linear expression and a relation sense (equals, greater, less). + +Expressions are built from variables defined in the :class:`.Problem` instance. +In addition, an expression can contain a :class:`.VariableSet` instead of a +single variable. This allows many similar expressions to be represented by one +:class:`.Expression` instance which means that the LP problem can be +constructed faster. +"""""" + +from __future__ import unicode_literals + +import math +import numbers +import operator +from collections import Counter, defaultdict +import abc +import enum +from fractions import Fraction +from decimal import Decimal + +import six +from six import add_metaclass, iteritems, viewkeys, viewitems, text_type +from six.moves import range, reduce + +_INF = float('inf') + + +class SolverError(Exception): + """"""Error wrapping solver specific errors."""""" + + +class VariableSet(tuple): + """"""A tuple used to represent sets of variables."""""" + + +class Product(tuple): + """"""A tuple used to represent a variable product."""""" + + +class _RangedAccessor(object): + """"""Accessor to value bounded by minimum/maximum."""""" + def __init__(self, obj, prop): + self._obj = obj + self._prop = prop + + @property + def value(self): + """"""Value of property."""""" + if self._prop.fget is None: + raise AttributeError('Unable to read attribute') + return self._prop.fget(self._obj) + + @value.setter + def value(self, v): + if self._prop.fset is None: + raise AttributeError('Unable to write attribute') + self._prop.fset(self._obj, v) + + @value.deleter + def value(self): + if self._prop.fdel is None: + raise AttributeError('Unable to delete attribute') + self._prop.fdel(self._obj) + + @property + def min(self): + """"""Minimum value."""""" + if self._prop.fmin is None: + return -_INF + return self._prop.fmin(self._obj) + + @property + def max(self): + """"""Maximum value."""""" + if self._prop.fmax is None: + return _INF + return self._prop.fmax(self._obj) + + +class RangedProperty(object): + """"""Numeric property with minimum and maximum values. + + The value attribute is used to get/set the actual value of the propery. + The min/max attributes are used to get the bounds. The range is not + automatically enforced when the value is set. + """""" + def __init__(self, fget=None, fset=None, fdel=None, + fmin=None, fmax=None, doc=None): + self.fget = fget + self.fset = fset + self.fdel = fdel + self.fmin = fmin + self.fmax = fmax + + if doc is None and fget is not None: + doc = fget.__doc__ + self.__doc__ = doc + + def __get__(self, obj, objtype=None): + if obj is None: + return self + return _RangedAccessor(obj, self) + + def __set__(self, obj, value): + raise AttributeError('Unable to set attribute (try value property)') + + def __delete__(self, obj): + raise AttributeError('Unable to delete attribute (try value property)') + + def getter(self, fget): + return type(self)( + fget, self.fset, self.fdel, self.fmin, self.fmax, self.__doc__) + + def setter(self, fset): + return type(self)( + self.fget, fset, self.fdel, self.fmin, self.fmax, self.__doc__) + + def deleter(self, fdel): + return type(self)( + self.fget, self.fset, fdel, self.fmin, self.fmax, self.__doc__) + + +def ranged_property(min=None, max=None): + """"""Decorator for creating ranged property with fixed bounds."""""" + min_value = -_INF if min is None else min + max_value = _INF if max is None else max + return lambda fget: RangedProperty( + fget, fmin=lambda obj: min_value, fmax=lambda obj: max_value) + + +@six.python_2_unicode_compatible +class Expression(object): + """"""Represents a linear expression + + The variables can be any hashable objects. If one or more variables are + instead :class:`VariableSets <.VariableSet>`, this will be taken to + represent a set of expressions separately using a different element of the + :class:`.VariableSet`. + + >>> e = Expression({'x': 2, 'y': 3}) + >>> str(e) + '2*x + 3*y' + + In order to provide a more natural syntax for creating + :class:`Relations <.Relation>` the binary relation operators have been + overloaded to return :class:`.Relation` instances. + + >>> rel = Expression({'x': 2}) >= Expression({'y': 3}) + >>> str(rel) + '2*x - 3*y >= 0' + + .. warning:: + + Chained relations cannot be converted to multiple + relations, e.g. ``4 <= e <= 10`` will fail to produce the intended + relations! + """""" + + def __init__(self, variables={}, offset=0): + self._variables = Counter(variables) + self._offset = offset + + @property + def offset(self): + """"""Value of the offset"""""" + return self._offset + + def variables(self): + """"""Return immutable view of variables in expression."""""" + return viewkeys(self._variables) + + def values(self): + """"""Return immutable view of (variable, value)-pairs in expression."""""" + return viewitems(self._variables) + + def value(self, variable): + return self._variables.get(variable, 0) + + def value_sets(self): + """"""Iterator of expression sets + + This will yield an iterator of (variable, value)-pairs for each + expression in the expression set (each equivalent to values()). If none + of the variables is a set variable then a single iterator will be + yielded. + """""" + count = max(1 if not isinstance(var, VariableSet) else + len(var) for var in self._variables) + + def value_set(n): + for variable, value in iteritems(self._variables): + if isinstance(variable, VariableSet): + yield variable[n], value + else: + yield variable, value + for i in range(count): + yield value_set(i) + + def __contains__(self, variable): + return variable in self._variables + + def __add__(self, other): + """"""Add expression with a number or another expression"""""" + + if isinstance(other, numbers.Number): + if math.isinf(self._offset) or math.isinf(other): + return self.__class__(offset=self._offset + other) + return self.__class__(self._variables, self._offset + other) + elif isinstance(other, self.__class__): + if math.isinf(self._offset) or math.isinf(other._offset): + return self.__class__(offset=self._offset + other._offset) + variables = Counter(self._variables) + variables.update(other._variables) + return self.__class__(variables, self._offset + other._offset) + return NotImplemented + + __radd__ = __add__ + + def __iadd__(self, other): + if isinstance(other, numbers.Number): + if math.isinf(self._offset) or math.isinf(other): + self._variables = {} + self._offset += other + elif isinstance(other, self.__class__): + self._offset += other._offset + if math.isinf(self._offset) or math.isinf(other._offset): + self._variables = {} + else: + self._variables.update(other._variables) + else: + return NotImplemented + + return self + + def __sub__(self, other): + return self + -other + + def __rsub__(self, other): + return -self + other + + def __isub__(self, other): + self += -other + return self + + def __mul__(self, other): + if isinstance(other, numbers.Number): + if math.isinf(other): + return self.__class__(offset=float('nan')) + + return self.__class__( + {var: value * other for var, value in + iteritems(self._variables)}, self._offset * other) + elif isinstance(other, self.__class__): + variables = defaultdict(int) + for v1, value1 in iteritems(self._variables): + for v2, value2 in iteritems(other._variables): + p1 = v1 if isinstance(v1, Product) else Product((v1,)) + p2 = v2 if isinstance(v2, Product) else Product((v2,)) + product = Product(sorted(p1 + p2, key=text_type)) + variables[product] += value1 * value2 + + if other._offset != 0: + variables[v1] += value1 * other._offset + + if self._offset != 0: + for v2, value2 in iteritems(other._variables): + variables[v2] += value2 * self._offset + + offset = self._offset * other._offset + return self.__class__(variables, offset=offset) + else: + return NotImplemented + + __rmul__ = __mul__ + + def __imul__(self, other): + if isinstance(other, numbers.Number): + if math.isinf(other): + self._variables = {} + self._offset = float('nan') + else: + for var in self._variables: + self._variables[var] *= other + self._offset *= other + elif isinstance(other, self.__class__): + variables = defaultdict(int) + for v1, value1 in iteritems(self._variables): + for v2, value2 in iteritems(other._variables): + p1 = v1 if isinstance(v1, Product) else Product((v1,)) + p2 = v2 if isinstance(v2, Product) else Product((v2,)) + product = Product(sorted(p1 + p2, key=text_type)) + variables[product] += value1 * value2 + + if other._offset != 0: + variables[v1] += value1 * other._offset + + if self._offset != 0: + for v2, value2 in iteritems(other._variables): + variables[v2] += value2 * self._offset + + self._offset *= other._offset + self._variables = dict(variables) + else: + return NotImplemented + + return self + + def __neg__(self): + return self.__class__( + {var: -value for var, value in iteritems(self._variables)}, + -self._offset) + + def __pow__(self, other): + if isinstance(other, int): + if other < 0: + raise ValueError('Exponent must be positive') + elif other == 0: + return self.__class__(offset=1) + + r = self.__class__(self._variables, self._offset) + for i in range(other - 1): + r.__imul__(self) + + return r + else: + return NotImplemented + + def __rpow__(self, other): + return pow(other, self) + + def __ipow__(self, other): + if isinstance(other, int): + if other < 0: + raise ValueError('Exponent must be positive') + elif other == 0: + self._variables = {} + self._offset = 1 + else: + tmp = self.__class__(self._variables, self._offset) + for i in range(other - 1): + self.__imul__(tmp) + else: + return NotImplemented + + return self + + def __eq__(self, other): + """"""Return equality relation (equation): self == other + + This method is overloaded so that relations can be + formed using a natural syntax. + """""" + + return Relation(RelationSense.Equals, self - other) + + def __ge__(self, other): + """"""Return greater-than relation (inequality): self >= other + + This method is overloaded so that relations can be + formed using a natural syntax. + """""" + + return Relation(RelationSense.Greater, self - other) + + def __le__(self, other): + """"""Return less-than relation (inequality): self <= other + + This method is overloaded so that relations can be + formed using a natural syntax. + """""" + + return Relation(RelationSense.Less, self - other) + + def __gt__(self, other): + """"""Return strictly greater-than relation (inequality): self > other + + This method is overloaded so that relations can be + formed using a natural syntax. + """""" + + return Relation(RelationSense.StrictlyGreater, self - other) + + def __lt__(self, other): + """"""Return strictly less-than relation (inequality): self < other + + This method is overloaded so that relations can be + formed using a natural syntax. + """""" + + return Relation(RelationSense.StrictlyLess, self - other) + + def __str__(self): + """"""Return string representation of expression"""""" + + def sort_key_variable(item): + key, _ = item + is_product = isinstance(key, Product) + return is_product, text_type(key) + + def all_terms(): + count_vars = 0 + for name, value in sorted( + iteritems(self._variables), key=sort_key_variable): + if value != 0: + count_vars += 1 + if isinstance(name, VariableSet): + yield '', value + elif isinstance(name, Product): + yield '*'.join(text_type(n) for n in name), value + else: + yield name, value + if self._offset != 0 or count_vars == 0: + yield None, self._offset + + terms = [] + for i, (name, value) in enumerate(all_terms()): + if i == 0: + # First term is special + if name is None: + terms.append('{}'.format(value)) + elif abs(value) == 1: + terms.append( + text_type(name) if value > 0 else '-{}'.format(name)) + else: + terms.append('{}*{}'.format(value, name)) + else: + prefix = '+' if value >= 0 else '-' + if name is None: + terms.append('{} {}'.format(prefix, abs(value))) + elif abs(value) == 1: + terms.append('{} {}'.format(prefix, name)) + else: + terms.append('{} {}*{}'.format(prefix, abs(value), name)) + return ' '.join(terms) + + def __repr__(self): + return str('<{} {}>').format( + self.__class__.__name__, repr(str(self))) + + +@enum.unique +class RelationSense(enum.Enum): + Equals = '==' + Greater = '>=' + Less = '<=' + StrictlyGreater = '>' + StrictlyLess = '<' + + +@six.python_2_unicode_compatible +class Relation(object): + """"""Represents a binary relation (equation or inequality) + + Relations can be equalities or inequalities. All relations + of this type can be represented as a left-hand side expression + and the type of relation. In this representation, the right-hand + side is always zero. + """""" + + def __init__(self, sense, expression): + self._sense = sense + self._expression = expression + + @property + def sense(self): + """"""Type of relation (equality or inequality) + + Can be one of Equal, Greater or Less, or one of the + strict relations, StrictlyGreater or StrictlyLess. + """""" + return self._sense + + @property + def expression(self): + """"""Left-hand side expression"""""" + return self._expression + + def __str__(self): + """"""Convert relation to string representation"""""" + var_expr = Expression(dict(self._expression.values())) + return '{} {} {}'.format( + str(var_expr), self._sense.value, -self._expression.offset) + + def __repr__(self): + return str('<{} {}>').format(self.__class__.__name__, repr(str(self))) + + def __nonzero__(self): + # Override __nonzero__ (and __bool__) here so we can avoid bugs when a + # user mistakenly thinks that ""4 <= x <= 100"" should work. + # This kind of expression expands to ""4 <= x and x <= 100"" and since we + # cannot override the ""and"" operator, the relation ""4 <= x"" is + # converted to a bool. Override here to raise an error to make sure + # that this syntax always fails. + raise ValueError('Unable to convert relation to bool') + + __bool__ = __nonzero__ + + +@enum.unique +class ObjectiveSense(enum.Enum): + """"""Enumeration of objective sense values"""""" + + Minimize = -1 + """"""Minimize objective function"""""" + + Maximize = 1 + """"""Maximize objective function"""""" + + +@enum.unique +class VariableType(enum.Enum): + """"""Enumeration of variable types"""""" + + Continuous = 'C' + """"""Continuous variable type"""""" + + Integer = 'I' + """"""Integer variable type"""""" + + Binary = 'B' + """"""Binary variable type (0 or 1)"""""" + + +@add_metaclass(abc.ABCMeta) +class Solver(object): + """"""Factory for LP Problem instances"""""" + + @abc.abstractmethod + def create_problem(self): + """"""Create a new :class:`.Problem` instance"""""" + + +@add_metaclass(abc.ABCMeta) +class Constraint(object): + """"""Represents a constraint within an LP Problem"""""" + + @abc.abstractmethod + def delete(self): + """"""Remove constraint from Problem instance"""""" + + +class VariableNamespace(object): + """"""Namespace for defining variables. + + Namespaces are always unique even if two namespaces have the same name. + Variables defined within a namespace will never clash with a global + variable name or a name defined in another namespace. Namespaces should + be created using the :meth:`.Problem.namespace`. + + >>> v = prob.namespace(name='v') + >>> v.define([1, 2, 5], lower=0, upper=10) + >>> prob.set_objective(v[1] + 3*v[2] - 5 * v[5]) + """""" + def __init__(self, problem, **kwargs): + self._name = kwargs.pop('name', None) + self._problem = problem + self._define_kwargs = kwargs + + def define(self, names, **kwargs): + """"""Define variables within the namespace. + + This is similar to :meth:`.Problem.define` except that names must be + given as an iterable. This method accepts the same keyword arguments + as :meth:`.Problem.define`. + """""" + define_kwargs = dict(self._define_kwargs) + define_kwargs.update(kwargs) + self._problem.define( + *((self, name) for name in names), **define_kwargs) + + def __getitem__(self, key): + return self._problem.var((self, key)) + + def __contains__(self, key): + return self._problem.has_variable((self, key)) + + def has_variable(self, name): + return self._problem.has_variable((self, name)) + + def __call__(self, name): + return self._problem.var((self, name)) + + def set(self, names): + """"""Return a variable set of the given names in the namespace. + + >>> v = prob.namespace(name='v') + >>> v.define([1, 2, 5], lower=0, upper=10) + >>> prob.add_linear_constraints(v.set([1, 2]) >= 4) + """""" + return self._problem.set((self, name) for name in names) + + def sum(self, names): + """"""Return the sum of the given names in the namespace. + + >>> v = prob.namespace(name='v') + >>> v.define([1, 2, 5], lower=0, upper=10) + >>> prob.set_objective(v.sum([2, 5])) # v[2] + v[5] + """""" + return Expression({(self, name): 1 for name in names}) + + def expr(self, items): + """"""Return the sum of each name multiplied by a coefficient. + + >>> v = prob.namespace(name='v') + >>> v.define(['a', 'b', 'c'], lower=0, upper=10) + >>> prob.set_objective(v.expr([('a', 2), ('b', 1)])) + """""" + return Expression({(self, name): value for name, value in items}) + + def value(self, name): + """"""Return value of given variable in namespace. + + >>> v = prob.namespace(name='v') + >>> v.define([1, 2, 5], lower=0, upper=10) + >>> prob.solve() + >>> print(v.value(2)) + """""" + return self._problem.result.get_value((self, name)) + + def __repr__(self): + name = repr(self._name) if self._name is not None else 'Unnamed' + return str('<{}: {}>').format(self.__class__.__name__, name) + + +@add_metaclass(abc.ABCMeta) +class Problem(object): + """"""Representation of LP Problem instance + + Variable names in the problem can be any hashable object. It is the + responsibility of the solver interface to translate the object into a + unique string if required by the underlying LP solver. + """""" + + @abc.abstractmethod + def define(self, *names, **kwargs): + """"""Define a variable in the problem. + + Variables must be defined before they can be accessed by var() or + set(). This function takes keyword arguments lower and upper to define + the bounds of the variable (default: -inf to inf). The keyword argument + types can be used to select the type of the variable (Continuous + (default), Binary or Integer). Setting any variables different than + Continuous will turn the problem into an MILP problem. Raises + ValueError if a name is already defined. + """""" + + @abc.abstractmethod + def has_variable(self, name): + """"""Check whether a variable is defined in the problem."""""" + + def namespace(self, names=None, **kwargs): + """"""Return namespace for this problem. + + If names is given it should be an iterable of names to define in the + namespace. Other keyword arguments can be specified which will be + used to define the names given as well as being used as default + parameters for names that are defined later. + + >>> v = prob.namespace(name='v') + >>> v.define([1, 2, 5], lower=0, upper=10) + >>> prob.set_objective(v[1] + 3*v[2] - 5 * v[5]) + """""" + ns = VariableNamespace(self, **kwargs) + if names is not None: + ns.define(names) + return ns + + def var(self, name): + """"""Return variable as an :class:`.Expression`."""""" + if not self.has_variable(name): + raise ValueError('Undefined variable: {}'.format(name)) + return Expression({name: 1}) + + def expr(self, values, offset=0): + """"""Return the given dictionary of values as an :class:`.Expression`."""""" + if isinstance(values, dict): + for name in values: + if not self.has_variable(name): + raise ValueError('Undefined variable: {}'.format(name)) + return Expression(values, offset=offset) + + if not self.has_variable(values): + raise ValueError('Undefined variable: {}'.format(values)) + return Expression({values: 1}, offset=offset) + + def set(self, names): + """"""Return variables as a set expression. + + This returns an :class:`.Expression` containing a + :class:`.VariableSet`. + """""" + names = tuple(names) + if any(not self.has_variable(name) for name in names): + raise ValueError('Undefined variables: {}'.format( + set(names) - set(self._variables))) + return Expression({VariableSet(names): 1}) + + def _check_relation(self, relation): + """"""Check whether the given relation is valid. + + Return false normally, or true if the relation is determined to be + tautologically true. Raises ``ValueError`` if the relation is + tautologically false. This includes relations given as a ``False`` bool + value or certain types of relations that have an infinity offset. + """""" + if isinstance(relation, bool): + if not relation: + raise ValueError('Unsatisfiable relation added') + return True + + if relation.sense in ( + RelationSense.StrictlyGreater, RelationSense.StrictlyLess): + raise ValueError( + 'Strict relations are invalid in LP-problems:' + ' {}'.format(relation)) + + if relation.expression.offset == -_INF: + if relation.sense == RelationSense.Less: + return True + else: + raise ValueError('Unsatisfiable relation added: {}'.format( + relation)) + elif relation.expression.offset == _INF: + if relation.sense == RelationSense.Greater: + return True + else: + raise ValueError('Unsatisfiable relation added: {}'.format( + relation)) + + return False + + @abc.abstractmethod + def add_linear_constraints(self, *relations): + """"""Add constraints to the problem. + + Each constraint is given as a :class:`.Relation`, and the expression + in that relation can be a set expression. Returns a sequence of + :class:`Constraints <.Constraint>`. + """""" + + @abc.abstractmethod + def set_objective(self, expression): + """"""Set objective of the problem to the given :class:`.Expression`."""""" + + set_linear_objective = set_objective + """"""Set objective of the problem. + + .. deprecated:: 0.19 + Use :meth:`set_objective` instead. + """""" + + @abc.abstractmethod + def set_objective_sense(self, sense): + """"""Set type of problem (minimize or maximize)"""""" + + def solve(self, sense=None): + """"""Solve problem and return result. + + Raises :class:`SolverError` if the solution is not optimal. + """""" + result = self.solve_unchecked(sense) + if not result: + raise SolverError('Solution not optimal: {}'.format(result.status)) + + return result + + @abc.abstractmethod + def solve_unchecked(self, sense=None): + """"""Solve problem and return result. + + The user must manually check the status of the result to determine + whether an optimal solution was found. A :class:`SolverError` may still + be raised if the underlying solver raises an exception. + """""" + + @abc.abstractproperty + def result(self): + """"""Result of solved problem"""""" + + @ranged_property(min=None, max=None) + def feasibility_tolerance(self): + raise NotImplementedError('Feasiblity tolerance not available') + + @ranged_property(min=None, max=None) + def optimality_tolerance(self): + raise NotImplementedError('Optimality tolerance not available') + + @ranged_property(min=None, max=None) + def integrality_tolerance(self): + raise NotImplementedError('Integrality tolerance not available') + + +class InvalidResultError(Exception): + """"""Raised when a result that has been invalidated is accessed"""""" + + def __init__(self, msg=None): + if msg is None: + msg = ('Previous result is no longer valid as problem' + ' has been solved again') + super(InvalidResultError, self).__init__(msg) + + +class Result(object): + """"""Result of solving an LP problem + + The result is tied to the solver instance and is valid at least until the + problem is solved again. If the problem has been solved again an + :class:`InvalidResultError` may be raised. + """""" + + @abc.abstractproperty + def success(self): + """"""Whether solution was optimal"""""" + + def __nonzero__(self): + """"""Whether solution was optimal"""""" + return self.success + + __bool__ = __nonzero__ + + @abc.abstractproperty + def status(self): + """"""String indicating the status of the problem result"""""" + + @abc.abstractproperty + def unbounded(self): + """"""Whether solution is unbounded"""""" + + @abc.abstractmethod + def _get_value(self, var): + """"""Return the solution value of a single variable."""""" + + @abc.abstractmethod + def _has_variable(self, var): + """"""Return whether variable exists in the solution."""""" + + def _evaluate_expression(self, expr): + """"""Evaluate an :class:`.Expression` using :meth:`_get_value`."""""" + def cast_value(v): + # Convert Decimal to Fraction to allow successful multiplication + # by either float (most solvers) or Fraction (exact solver). + # Multiplying Fraction and float results in a float, and + # multiplying Fraction and Fraction result in Fraction, which are + # exactly the types of results we want. + if isinstance(v, Decimal): + return Fraction(v) + return v + + total = cast_value(expr.offset) + for var, value in expr.values(): + value = cast_value(value) + if not isinstance(var, Product): + total += self._get_value(var) * value + else: + total += reduce( + operator.mul, (self._get_value(v) for v in var), value) + return total + + def get_value(self, expression): + """"""Get value of variable or expression in result + + Expression can be an object defined as a name in the problem, in which + case the corresponding value is simply returned. If expression is an + actual :class:`.Expression` object, it will be evaluated using the + values from the result. + """""" + if isinstance(expression, Expression): + return self._evaluate_expression(expression) + elif not self._has_variable(expression): + raise ValueError('Unknown expression: {}'.format(expression)) + + return self._get_value(expression) + + +if __name__ == '__main__': + import doctest + doctest.testmod() +","Python" +"Metabolic","zhanglab/psamm","psamm/lpsolver/generic.py",".py","9262","280","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2020 Elysha Sameth + +""""""Generic interface to LP solver instantiation."""""" + +from __future__ import absolute_import, print_function + +import argparse +import os +import logging + +from .lp import Solver as BaseSolver + +from six import iteritems + +logger = logging.getLogger(__name__) +_solvers = [] +_solver_import_errors = {} + + +# Try to load Cplex solver +try: + from . import cplex + _solvers.append({ + 'class': cplex.Solver, + 'name': 'cplex', + 'integer': True, + 'quadratic': True, + 'rational': False, + 'priority': 10, + 'feasibility_tolerance': True, + 'optimality_tolerance': True, + 'integrality_tolerance': True, + 'threads': True + }) +except ImportError as e: + _solver_import_errors['cplex'] = str(e) + +# Try to load QSopt_ex solver +try: + from . import qsoptex + _solvers.append({ + 'class': qsoptex.Solver, + 'name': 'qsoptex', + 'integer': False, + 'quadratic': False, + 'rational': True, + 'priority': 5, + 'feasibility_tolerance': True, + 'optimality_tolerance': True, + 'integrality_tolerance': False, + 'threads': False + }) +except ImportError as e: + _solver_import_errors['qsoptex'] = str(e) + +# Try to load Gurobi solver +try: + from . import gurobi + _solvers.append({ + 'class': gurobi.Solver, + 'name': 'gurobi', + 'integer': True, + 'quadratic': False, + 'rational': False, + 'priority': 9, + 'feasibility_tolerance': True, + 'optimality_tolerance': True, + 'integrality_tolerance': True, + 'threads': True + }) +except ImportError as e: + _solver_import_errors['gurobi'] = str(e) + +# Try to load GLPK solver +try: + from . import glpk + _solvers.append({ + 'class': glpk.Solver, + 'name': 'glpk', + 'integer': True, + 'quadratic': False, + 'rational': False, + 'priority': 8, + 'feasibility_tolerance': True, + 'optimality_tolerance': True, + 'integrality_tolerance': True, + 'threads': False + }) +except ImportError as e: + _solver_import_errors['glpk'] = str(e) + + +class RequirementsError(Exception): + """"""Error resolving solver requirements"""""" + + +def filter_solvers(solvers, requirements): + """"""Yield solvers that fullfil the requirements."""""" + for solver in solvers: + for req, value in iteritems(requirements): + if (req in ('threads', 'feasibility_tolerance', + 'optimality_tolerance', + 'integrality_tolerance') and solver[req] is True): + continue + elif solver[req] != value: + break + else: + yield solver + + +class Solver(BaseSolver): + """"""Generic solver interface based on requirements + + Use the any of the following keyword arguments to restrict which + underlying solver is used: + + - `integer`: Use a solver that support integer variables (MILP) + - `rational`: Use a solver that returns rational results + - `quadratic`: Use a solver that supports quadratic objective/constraints + - `name`: Select a specific solver based on the name + """""" + + def __init__(self, **kwargs): + if len(_solvers) == 0: + raise RequirementsError('No solvers available') + + self._requirements = {key: value for key, value in iteritems(kwargs) + if value is not None} + solvers = list(filter_solvers(_solvers, self._requirements)) + + # Obtain solver priority from environment variable, if specified. + priority = {} + if 'PSAMM_SOLVER' in os.environ: + solver_names = os.environ['PSAMM_SOLVER'].split(',') + for i, solver_name in enumerate(solver_names): + priority[solver_name] = len(solver_names) - i + solvers = [s for s in solvers if s['name'] in priority] + else: + # Use built-in priorities + for solver in solvers: + priority[solver['name']] = solver['priority'] + + if len(solvers) == 0: + raise RequirementsError( + 'Unable to find a solver matching the specified requirements:' + ' {}'.format(self._requirements)) + + solver = max(solvers, key=lambda s: priority.get(s['name'], 0)) + logger.debug('Using solver {}'.format(solver['name'])) + + self._properties = solver + self._solver = solver['class']() + + @property + def properties(self): + return self._properties + + def create_problem(self): + """"""Create a :class:`Problem ` instance"""""" + return self._solver.create_problem(**self._requirements) + + +def parse_solver_setting(s): + """"""Parse a string containing a solver setting"""""" + + try: + key, value = s.split('=', 1) + except ValueError: + key, value = s, 'yes' + + if key in ('rational', 'integer', 'quadratic'): + value = value.lower() in ('1', 'yes', 'true', 'on') + elif key in ('threads',): + value = int(value) + elif key in ('feasibility_tolerance', 'optimality_tolerance', + 'integrality_tolerance'): + value = float(value) + elif key in ('name',): + pass + else: + raise RequirementsError( + '{} is not a solver parameter option'.format(key)) + + return key, value + + +def list_solvers(args=None): + """"""Entry point for listing available solvers."""""" + parser = argparse.ArgumentParser( + description='''List LP solver available in PSAMM. This will produce a + list of all of the available LP solvers in prioritized + order. Addtional requirements can be imposed with the + arguments (e.g. integer=yes to select only solvers that + support MILP problems). The list will also be influenced + by the PSAMM_SOLVER environment variable which can be + used to only allow specific solvers (e.g. + PSAMM_SOLVER=cplex).''') + parser.add_argument( + 'requirement', nargs='*', type=str, + help='Additional requirements on the selected solvers') + parsed_args = parser.parse_args(args) + + requirements = {} + for arg in parsed_args.requirement: + try: + key, value = parse_solver_setting(arg) + except ValueError as e: + parser.error(str(e)) + else: + requirements[key] = value + + solvers = list(filter_solvers(_solvers, requirements)) + solver_names = set(solver['name'] for solver in solvers) + + # Obtain solver priority from environment variable, if specified. + priority = {} + if 'PSAMM_SOLVER' in os.environ: + names = os.environ['PSAMM_SOLVER'].split(',') + for i, solver_name in enumerate(names): + priority[solver_name] = len(names) - i + solvers = [s for s in solvers if s['name'] in priority] + solver_names = set(priority) + else: + # Use built-in priorities + for solver in solvers: + priority[solver['name']] = solver['priority'] + + solvers = sorted(solvers, key=lambda s: priority.get(s['name'], 0), + reverse=True) + + status = 0 + + if len(solvers) > 0: + print('Prioritized solvers:') + for solver in solvers: + print('Name: {}'.format(solver['name'])) + print('Priority: {}'.format(solver['priority'])) + print('MILP (integer) problem support: {}'.format( + solver['integer'])) + print('QP (quadratic) problem support: {}'.format( + solver['quadratic'])) + print('Rational solution: {}'.format(solver['rational'])) + print('Class: {}'.format(solver['class'])) + print() + else: + status = 1 + print('No solvers fullfil the requirements!') + print() + + filtered_solvers_count = len(_solvers) - len(solvers) + if filtered_solvers_count > 0 or len(_solver_import_errors) > 0: + print('Unavailable solvers:') + for solver in _solvers: + if solver['name'] not in solver_names: + print('{}: Does not fullfil the specified requirements'.format( + solver['name'])) + + for solver, error in iteritems(_solver_import_errors): + print('{}: Error loading solver: {}'.format(solver, error)) + + if status != 0: + parser.exit(status) +","Python" +"Metabolic","zhanglab/psamm","psamm/lpsolver/qsoptex.py",".py","9240","271","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Linear programming solver using QSopt_ex."""""" + +from __future__ import absolute_import + +from itertools import repeat, count +import numbers + +from six import iteritems +from six.moves import zip +import qsoptex + +from .lp import Solver as BaseSolver +from .lp import Constraint as BaseConstraint +from .lp import Problem as BaseProblem +from .lp import Result as BaseResult +from .lp import (Expression, RelationSense, ObjectiveSense, VariableType, + InvalidResultError, ranged_property) + + +class Solver(BaseSolver): + """"""Represents an LP solver using QSopt_ex"""""" + + def create_problem(self, **kwargs): + """"""Create a new LP-problem using the solver"""""" + return Problem(**kwargs) + + +class Problem(BaseProblem): + """"""Represents an LP-problem of a qsoptex.Solver"""""" + + CONSTR_SENSE_MAP = { + RelationSense.Equals: qsoptex.ConstraintSense.EQUAL, + RelationSense.Greater: qsoptex.ConstraintSense.GREATER, + RelationSense.Less: qsoptex.ConstraintSense.LESS + } + + def __init__(self, **kwargs): + self._p = qsoptex.ExactProblem() + self._p.set_param(qsoptex.Parameter.SIMPLEX_DISPLAY, 1) + + self._variables = {} + self._var_names = ('x'+str(i) for i in count(1)) + self._constr_names = ('c'+str(i) for i in count(1)) + + self._result = None + + @property + def qsoptex(self): + """"""The underlying qsoptex.ExactProblem object"""""" + return self._p + + def define(self, *names, **kwargs): + """"""Define a variable in the problem. + + Variables must be defined before they can be accessed by var() or + set(). This function takes keyword arguments lower and upper to define + the bounds of the variable (default: -inf to inf). The keyword argument + types can be used to select the type of the variable (only Continuous + is supported). Raises ValueError if a name is already defined. + """""" + names = tuple(names) + for name in names: + if name in self._variables: + raise ValueError('Variable already defined: {!r}'.format(name)) + + lower = kwargs.get('lower', None) + upper = kwargs.get('upper', None) + vartype = kwargs.get('types', None) + + # Repeat values if a scalar is given + if lower is None or isinstance(lower, numbers.Number): + lower = repeat(lower, len(names)) + if upper is None or isinstance(upper, numbers.Number): + upper = repeat(upper, len(names)) + if vartype is None or vartype in ( + VariableType.Continuous, VariableType.Binary, + VariableType.Integer): + vartype = repeat(vartype, len(names)) + + lp_names = tuple(next(self._var_names) for name in names) + + # Assign default values + vartype = (VariableType.Continuous if value is None else value + for value in vartype) + + self._variables.update(zip(names, lp_names)) + for name, lower, upper, t in zip(lp_names, lower, upper, vartype): + if t != VariableType.Continuous: + raise ValueError( + 'Solver does not support non-continuous types') + self._p.add_variable(0, lower, upper, name) + + def has_variable(self, name): + """"""Check whether variable is defined in the model."""""" + return name in self._variables + + def _add_constraints(self, relation): + """"""Add the given relation as one or more constraints + + Return a list of the names of the constraints added. + """""" + expression = relation.expression + names = [] + for value_set in expression.value_sets(): + values = ((self._variables[variable], value) + for variable, value in value_set) + constr_name = next(self._constr_names) + sense = self.CONSTR_SENSE_MAP[relation.sense] + self._p.add_linear_constraint( + sense=sense, values=values, rhs=-expression.offset, + name=constr_name) + names.append(constr_name) + + return names + + def add_linear_constraints(self, *relations): + """"""Add constraints to the problem + + Each constraint is represented by a Relation, and the + expression in that relation can be a set expression. + """""" + constraints = [] + + for relation in relations: + if self._check_relation(relation): + constraints.append(Constraint(self, None)) + else: + for name in self._add_constraints(relation): + constraints.append(Constraint(self, name)) + + return constraints + + def set_objective(self, expression): + """"""Set linear objective of problem"""""" + + if isinstance(expression, numbers.Number): + # Allow expressions with no variables as objective, + # represented as a number + expression = Expression() + + self._p.set_linear_objective( + (lp_name, expression.value(var)) + for var, lp_name in iteritems(self._variables)) + + set_linear_objective = set_objective + """"""Set objective of the problem. + + .. deprecated:: 0.19 + Use :meth:`set_objective` instead. + """""" + + def set_objective_sense(self, sense): + """"""Set type of problem (maximize or minimize)"""""" + if sense == ObjectiveSense.Minimize: + self._p.set_objective_sense(qsoptex.ObjectiveSense.MINIMIZE) + elif sense == ObjectiveSense.Maximize: + self._p.set_objective_sense(qsoptex.ObjectiveSense.MAXIMIZE) + else: + raise ValueError('Invalid objective sense') + + def solve_unchecked(self, sense=None): + """"""Solve problem and return result. + + The user must manually check the status of the result to determine + whether an optimal solution was found. A :class:`SolverError` may still + be raised if the underlying solver raises an exception. + """""" + if sense is not None: + self.set_objective_sense(sense) + self._p.solve() + + self._result = Result(self) + return self._result + + @property + def result(self): + return self._result + + @ranged_property(min=0, max=0) + def feasibility_tolerance(self): + """"""Feasibility tolerance."""""" + return 0 + + @ranged_property(min=0, max=0) + def optimality_tolerance(self): + """"""Optimality tolerance."""""" + return 0 + + +class Constraint(BaseConstraint): + """"""Represents a constraint in a qsoptex.Problem"""""" + + def __init__(self, prob, name): + self._prob = prob + self._name = name + + def delete(self): + if self._name is not None: + self._prob._p.delete_linear_constraint(self._name) + + +class Result(BaseResult): + """"""Represents the solution to a qsoptex.Problem + + This object will be returned from the Problem.solve() method or by + accessing the Problem.result property after solving a problem. This + class should not be instantiated manually. + + Result will evaluate to a boolean according to the success of the + solution, so checking the truth value of the result will immediately + indicate whether solving was successful. + """""" + + def __init__(self, prob): + self._problem = prob + + def _check_valid(self): + if self._problem.result != self: + raise InvalidResultError() + + @property + def success(self): + """"""Return boolean indicating whether a solution was found"""""" + self._check_valid() + return self._problem._p.get_status() == qsoptex.SolutionStatus.OPTIMAL + + @property + def unbounded(self): + """"""Whether the solution is unbounded"""""" + self._check_valid() + return (self._problem._p.get_status() == + qsoptex.SolutionStatus.UNBOUNDED) + + @property + def status(self): + """"""Return string indicating the error encountered on failure"""""" + self._check_valid() + return 'Status: {}'.format(self._problem._p.get_status()) + + def _get_value(self, var): + """"""Return value of variable in solution."""""" + return self._problem._p.get_value(self._problem._variables[var]) + + def _has_variable(self, var): + """"""Whether variable exists in the solution."""""" + return self._problem.has_variable(var) + + def get_value(self, expression): + """"""Return value of expression"""""" + + self._check_valid() + return super(Result, self).get_value(expression) +","Python" +"Metabolic","zhanglab/psamm","psamm/lpsolver/gurobi.py",".py","13086","376","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Linear programming solver using Gurobi."""""" + +from __future__ import absolute_import + +import logging +from itertools import repeat, count +import numbers + +from six import raise_from +from six.moves import zip + +import gurobipy + +from .lp import Solver as BaseSolver +from .lp import Constraint as BaseConstraint +from .lp import Problem as BaseProblem +from .lp import Result as BaseResult +from .lp import (Expression, Product, RelationSense, ObjectiveSense, + VariableType, InvalidResultError, ranged_property) + +# Module-level logging +logger = logging.getLogger(__name__) + + +class Solver(BaseSolver): + """"""Represents an LP-solver using Gurobi."""""" + + def create_problem(self, **kwargs): + """"""Create a new LP-problem using the solver."""""" + return Problem(**kwargs) + + +class Problem(BaseProblem): + """"""Represents an LP-problem of a gurobi.Solver."""""" + + VARTYPE_MAP = { + VariableType.Continuous: gurobipy.GRB.CONTINUOUS, + VariableType.Binary: gurobipy.GRB.BINARY, + VariableType.Integer: gurobipy.GRB.INTEGER + } + + CONSTR_SENSE_MAP = { + RelationSense.Equals: gurobipy.GRB.EQUAL, + RelationSense.Greater: gurobipy.GRB.GREATER_EQUAL, + RelationSense.Less: gurobipy.GRB.LESS_EQUAL + } + + OBJ_SENSE_MAP = { + ObjectiveSense.Maximize: gurobipy.GRB.MAXIMIZE, + ObjectiveSense.Minimize: gurobipy.GRB.MINIMIZE + } + + def __init__(self, **kwargs): + self._p = gurobipy.Model() + + # TODO Logging should use the Python logging system like every other + # part of PSAMM. Unfortunately, Gurobi does not make this easy as the + # logging output is directed to stdout/(stderr?) and/or a file. For + # now, let's just disable logging to console so we don't mess up any + # of our output. This can be done with the LogToConsole parameter which + # disables output to console EXCEPT that when this parameter is set + # a log message is generated explaining that the parameter was + # changed... We are fortunate enough that this does not happen when + # using the OutputFlag parameter but instead we lose the log file. + self._p.params.OutputFlag = 0 + + # Set tolerances. By default, we decrease to 1e-9. + self.feasibility_tolerance.value = kwargs.get( + 'feasibility_tolerance', 1e-9) + self.optimality_tolerance.value = kwargs.get( + 'optimality_tolerance', 1e-9) + + # Set number of threads + if 'threads' in kwargs: + logger.info('Setting threads to {!r}'.format(kwargs['threads'])) + self._p.params.Threads = kwargs['threads'] + + self._variables = {} + self._var_names = ('x'+str(i) for i in count(1)) + self._constr_names = ('c'+str(i) for i in count(1)) + + self._result = None + + @property + def gurobi(self): + """"""The underlying Gurobi Model object."""""" + return self._p + + def define(self, *names, **kwargs): + """"""Define a variable in the problem. + + Variables must be defined before they can be accessed by var() or + set(). This function takes keyword arguments lower and upper to define + the bounds of the variable (default: -inf to inf). The keyword argument + types can be used to select the type of the variable (Continuous + (default), Binary or Integer). Setting any variables different than + Continuous will turn the problem into an MILP problem. Raises + ValueError if a name is already defined. + """""" + names = tuple(names) + for name in names: + if name in self._variables: + raise ValueError('Variable already defined: {!r}'.format(name)) + + lower = kwargs.get('lower', None) + upper = kwargs.get('upper', None) + vartype = kwargs.get('types', None) + + # Repeat values if a scalar is given + if lower is None or isinstance(lower, numbers.Number): + lower = repeat(lower, len(names)) + if upper is None or isinstance(upper, numbers.Number): + upper = repeat(upper, len(names)) + if vartype is None or vartype in ( + VariableType.Continuous, VariableType.Binary, + VariableType.Integer): + vartype = repeat(vartype, len(names)) + + lp_names = tuple(next(self._var_names) for name in names) + + # Assign default values + lower = (-gurobipy.GRB.INFINITY if value is None else float(value) + for value in lower) + upper = (gurobipy.GRB.INFINITY if value is None else float(value) + for value in upper) + vartype = tuple(VariableType.Continuous if value is None else value + for value in vartype) + + self._variables.update(zip(names, lp_names)) + for name, lb, ub, vt in zip(lp_names, lower, upper, vartype): + self._p.addVar(name=name, lb=lb, ub=ub, vtype=self.VARTYPE_MAP[vt]) + + self._p.update() + + def has_variable(self, name): + """"""Check whether variable is defined in the model."""""" + return name in self._variables + + def _grb_expr_from_value_set(self, value_set): + linear = [] + quad = [] + + for var, val in value_set: + if not isinstance(var, Product): + linear.append(( + float(val), self._p.getVarByName(self._variables[var]))) + else: + if len(var) > 2: + raise ValueError('Invalid objective: {}'.format(var)) + quad.append(( + float(val), self._p.getVarByName(self._variables[var[0]]), + self._p.getVarByName(self._variables[var[1]]))) + + if len(quad) > 0: + expr = gurobipy.QuadExpr() + if len(linear) > 0: + expr.addTerms(*zip(*linear)) + expr.addTerms(*zip(*quad)) + else: + expr = gurobipy.LinExpr(linear) + + return expr + + def _add_constraints(self, relation): + """"""Add the given relation as one or more constraints. + + Return a list of the names of the constraints added. + """""" + names = [] + expression = relation.expression + for value_set in expression.value_sets(): + name = next(self._constr_names) + self._p.addConstr( + self._grb_expr_from_value_set(value_set), + self.CONSTR_SENSE_MAP[relation.sense], + -float(expression.offset), name) + names.append(name) + + self._p.update() + + return names + + def add_linear_constraints(self, *relations): + """"""Add constraints to the problem. + + Each constraint is represented by a Relation, and the + expression in that relation can be a set expression. + """""" + constraints = [] + + for relation in relations: + if self._check_relation(relation): + constraints.append(Constraint(self, None)) + else: + for name in self._add_constraints(relation): + constraints.append(Constraint(self, name)) + + return constraints + + def set_objective(self, expression): + """"""Set linear objective of problem."""""" + + if isinstance(expression, numbers.Number): + # Allow expressions with no variables as objective, + # represented as a number + expression = Expression() + + self._p.setObjective( + self._grb_expr_from_value_set(expression.values())) + + set_linear_objective = set_objective + """"""Set objective of the problem. + + .. deprecated:: 0.19 + Use :meth:`set_objective` instead. + """""" + + def set_objective_sense(self, sense): + """"""Set type of problem (maximize or minimize)."""""" + + if sense not in (ObjectiveSense.Minimize, ObjectiveSense.Maximize): + raise ValueError('Invalid objective sense') + + self._p.ModelSense = self.OBJ_SENSE_MAP[sense] + + def solve_unchecked(self, sense=None): + """"""Solve problem and return result. + + The user must manually check the status of the result to determine + whether an optimal solution was found. A :class:`SolverError` may still + be raised if the underlying solver raises an exception. + """""" + if sense is not None: + self.set_objective_sense(sense) + self._p.optimize() + + self._result = Result(self) + return self._result + + @property + def result(self): + return self._result + + @ranged_property(min=1e-9, max=1e-2) + def feasibility_tolerance(self): + """"""Feasibility tolerance."""""" + return self._p.params.FeasibilityTol + + @feasibility_tolerance.setter + def feasibility_tolerance(self, value): + logger.info('Setting feasibility tolerance to {!r}'.format(value)) + try: + self._p.params.FeasibilityTol = value + except gurobipy.GurobiError as e: + raise_from(ValueError(e.message), e) + + @ranged_property(min=1e-9, max=1e-2) + def optimality_tolerance(self): + """"""Optimality tolerance."""""" + return self._p.params.OptimalityTol + + @optimality_tolerance.setter + def optimality_tolerance(self, value): + logger.info('Setting optimality tolerance to {!r}'.format(value)) + try: + self._p.params.OptimalityTol = value + except gurobipy.GurobiError as e: + raise_from(ValueError(e.message), e) + + @ranged_property(min=1e-9, max=1e-1) + def integrality_tolerance(self): + """"""Integrality tolerance."""""" + return self._p.params.IntFeasTol + + @integrality_tolerance.setter + def integrality_tolerance(self, value): + logger.info('Setting integrality tolerance to {!r}'.format(value)) + try: + self._p.params.IntFeasTol = value + except gurobipy.GurobiError as e: + raise_from(ValueError(e.message), e) + + +class Constraint(BaseConstraint): + """"""Represents a constraint in a gurobi.Problem."""""" + + def __init__(self, prob, name): + self._prob = prob + self._name = name + + def delete(self): + if self._name is not None: + self._prob._p.remove(self._prob._p.getConstrByName(self._name)) + + +class Result(BaseResult): + """"""Represents the solution to a gurobi.Problem. + + This object will be returned from the gurobi.Problem.solve() method or by + accessing the gurobi.Problem.result property after solving a problem. This + class should not be instantiated manually. + + Result will evaluate to a boolean according to the success of the + solution, so checking the truth value of the result will immediately + indicate whether solving was successful. + """""" + + def __init__(self, prob): + self._problem = prob + + def _check_valid(self): + if self._problem.result != self: + raise InvalidResultError() + + @property + def success(self): + """"""Return boolean indicating whether a solution was found."""""" + self._check_valid() + return self._problem._p.Status == gurobipy.GRB.OPTIMAL + + @property + def unbounded(self): + """"""Whether solution is unbounded"""""" + self._check_valid() + + status = self._problem._p.Status + if (status == gurobipy.GRB.INF_OR_UNBD and + self._problem._p.params.DualReductions): + # Disable dual reductions to obtain a definitve answer + self._problem._p.params.DualReductions = 0 + try: + self._problem._p.optimize() + finally: + self._problem._p.params.DualReductions = 1 + + status = self._problem._p.Status + return status == gurobipy.GRB.UNBOUNDED + + @property + def status(self): + """"""Return string indicating the error encountered on failure."""""" + self._check_valid() + return str(self._problem._p.Status) + + def _get_value(self, var): + """"""Return value of variable in solution."""""" + return self._problem._p.getVarByName(self._problem._variables[var]).x + + def _has_variable(self, var): + """"""Whether variable exists in the solution."""""" + return self._problem.has_variable(var) + + def get_value(self, expression): + """"""Return value of expression."""""" + + self._check_valid() + return super(Result, self).get_value(expression) +","Python" +"Metabolic","zhanglab/psamm","psamm/expression/__init__.py",".py","755","19","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen + +""""""Expression representation module"""""" +","Python" +"Metabolic","zhanglab/psamm","psamm/expression/affine.py",".py","12674","384","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Representations of affine expressions and variables. + +These classes can be used to represent affine expressions +and do manipulation and evaluation with substitutions of +particular variables. +"""""" + +from __future__ import unicode_literals + +import re +import numbers +import functools +from collections import Counter, defaultdict + +import six +from six import string_types, iteritems, iterkeys, itervalues + + +@six.python_2_unicode_compatible +@functools.total_ordering +class Variable(object): + """"""Represents a variable in an expression + + Equality of variables is based on the symbol. + """""" + + def __init__(self, symbol): + """"""Create variable with given symbol + + Symbol must start with a letter or underscore but + can contain numbers in other positions. + + >>> Variable('x') + Variable('x') + """""" + + if not re.match(r'^[^\d\W]\w*\Z', symbol): + raise ValueError('Invalid symbol {}'.format(symbol)) + self._symbol = str(symbol) + + @property + def symbol(self): + """"""Symbol of variable + + >>> Variable('x').symbol + 'x' + """""" + return self._symbol + + def simplify(self): + """"""Return simplified expression + + The simplified form of a variable is always the + variable itself. + + >>> Variable('x').simplify() + Variable('x') + """""" + return self + + def substitute(self, mapping): + """"""Return expression with variables substituted + + >>> Variable('x').substitute(lambda v: {'x': 567}.get(v.symbol, v)) + 567 + >>> Variable('x').substitute(lambda v: {'y': 42}.get(v.symbol, v)) + Variable('x') + >>> Variable('x').substitute( + ... lambda v: {'x': 123, 'y': 56}.get(v.symbol, v)) + 123 + """""" + + return mapping(self) + + def __add__(self, other): + return Expression({self: 1}) + other + + def __radd__(self, other): + return self + other + + def __sub__(self, other): + return Expression({self: 1}) - other + + def __rsub__(self, other): + return -self + other + + def __mul__(self, other): + return Expression({self: 1}) * other + + def __rmul__(self, other): + return self * other + + def __div__(self, other): + return Expression({self: 1}) / other + + __truediv__ = __div__ + + def __floordiv__(self, other): + return Expression({self: 1}) // other + + def __neg__(self): + return Expression({self: -1}) + + def __eq__(self, other): + """"""Check equality of variables"""""" + if isinstance(other, Expression): + return other == self + return isinstance(other, Variable) and self._symbol == other._symbol + + def __ne__(self, other): + return not self == other + + def __lt__(self, other): + if isinstance(other, Variable): + return self._symbol < other._symbol + return NotImplemented + + def __hash__(self): + return hash('Variable') ^ hash(self._symbol) + + def __str__(self): + return self._symbol + + def __repr__(self): + return str('Variable({})').format(repr(self._symbol)) + + +@six.python_2_unicode_compatible +class Expression(object): + """"""Represents an affine expression (e.g. 2x + 3y - z + 5)"""""" + + def __init__(self, *args): + """"""Create new expression + + >>> Expression({ Variable('x'): 2 }, 3) + Expression('2x + 3') + >>> Expression({ Variable('x'): 1, Variable('y'): 1 }) + Expression('x + y') + """""" + + if len(args) == 1 and isinstance(args[0], string_types): + # Parse as string + self._variables, self._offset = self._parse_string(args[0]) + elif len(args) <= 2: + self._variables = {} + self._offset = args[1] if len(args) >= 2 else 0 + + variables = args[0] if len(args) >= 1 else {} + for var, value in iteritems(variables): + if not isinstance(var, Variable): + raise ValueError('Not a variable: {}'.format(var)) + if value != 0: + self._variables[var] = value + else: + raise TypeError('Expression() requires one or two arguments') + + def _parse_string(self, s): + """"""Parse expression string + + Variables must be valid variable symbols and + coefficients must be integers. + """""" + + scanner = re.compile(r''' + (\s+) | # whitespace + ([^\d\W]\w*) | # variable + (\d+) | # number + ([+-]) | # sign + (\Z) | # end + (.) # error + ''', re.DOTALL | re.VERBOSE) + + variables = defaultdict(int) + offset = 0 + + # Parse using four states: + # 0: expect sign, variable, number or end (start state) + # 1: expect sign or end + # 2: expect variable or number + # 3: expect sign, variable or end + # All whitespace is ignored + state = 0 + state_number = 1 + for match in re.finditer(scanner, s): + whitespace, variable, number, sign, end, error = match.groups() + if error is not None: + raise ValueError( + 'Invalid token in expression string: {}'.format( + match.group(0))) + elif whitespace is not None: + continue + elif variable is not None and state in (0, 2, 3): + variables[Variable(variable)] += state_number + state = 1 + elif sign is not None and state in (0, 1, 3): + if state == 3: + offset += state_number + state_number = 1 if sign == '+' else -1 + state = 2 + elif number is not None and state in (0, 2): + state_number = state_number * int(number) + state = 3 + elif end is not None and state in (0, 1, 3): + if state == 3: + offset += state_number + else: + raise ValueError( + 'Invalid token in expression string: {}'.format( + match.group(0))) + + # Remove zero-coefficient elements + variables = {var: value for var, value in iteritems(variables) + if value != 0} + return variables, offset + + def simplify(self): + """"""Return simplified expression. + + If the expression is of the form 'x', the variable will be returned, + and if the expression contains no variables, the offset will be + returned as a number. + """""" + result = self.__class__(self._variables, self._offset) + if len(result._variables) == 0: + return result._offset + elif len(result._variables) == 1 and result._offset == 0: + var, value = next(iteritems(result._variables)) + if value == 1: + return var + return result + + def substitute(self, mapping): + """"""Return expression with variables substituted + + >>> Expression('x + 2y').substitute( + ... lambda v: {'y': -3}.get(v.symbol, v)) + Expression('x - 6') + >>> Expression('x + 2y').substitute( + ... lambda v: {'y': Variable('z')}.get(v.symbol, v)) + Expression('x + 2z') + """""" + expr = self.__class__() + for var, value in iteritems(self._variables): + expr += value * var.substitute(mapping) + return (expr + self._offset).simplify() + + def variables(self): + """"""Return iterator of variables in expression"""""" + return iter(self._variables) + + def __add__(self, other): + """"""Add expressions, variables or numbers"""""" + + if isinstance(other, numbers.Number): + return self.__class__(self._variables, self._offset + other) + elif isinstance(other, Variable): + return self + Expression({other: 1}) + elif isinstance(other, Expression): + variables = Counter(self._variables) + variables.update(other._variables) + variables = {var: value for var, value in iteritems(variables) + if value != 0} + return self.__class__(variables, self._offset + other._offset) + return NotImplemented + + def __radd__(self, other): + return self + other + + def __sub__(self, other): + """"""Subtract expressions, variables or numbers"""""" + return self + -other + + def __rsub__(self, other): + return -self + other + + def __mul__(self, other): + """"""Multiply by scalar"""""" + if isinstance(other, numbers.Number): + if other == 0: + return self.__class__() + return self.__class__({var: value * other for var, value + in iteritems(self._variables)}, + self._offset * other) + return NotImplemented + + def __rmul__(self, other): + return self * other + + def __div__(self, other): + """"""Divide by scalar"""""" + if isinstance(other, numbers.Number): + return self.__class__({var: value / other for var, value + in iteritems(self._variables)}, + self._offset / other) + return NotImplemented + + __truediv__ = __div__ + + def __floordiv__(self, other): + if isinstance(other, numbers.Number): + return self.__class__({var: value // other for var, value + in iteritems(self._variables)}, + self._offset // other) + return NotImplemented + + def __neg__(self): + return self * -1 + + def __eq__(self, other): + """"""Expression equality"""""" + if isinstance(other, Expression): + return (self._variables == other._variables and + self._offset == other._offset) + elif isinstance(other, Variable): + # Check that there is just one variable in the expression + # with a coefficient of one. + return (self._offset == 0 and len(self._variables) == 1 and + next(iterkeys(self._variables)) == other and + next(itervalues(self._variables)) == 1) + elif isinstance(other, numbers.Number): + return len(self._variables) == 0 and self._offset == other + return False + + def __ne__(self, other): + return not self == other + + def __str__(self): + def all_terms(): + count_vars = 0 + for symbol, value in sorted((var.symbol, value) for var, value + in iteritems(self._variables)): + if value != 0: + count_vars += 1 + yield symbol, value + if self._offset != 0 or count_vars == 0: + yield None, self._offset + + terms = [] + for i, spec in enumerate(all_terms()): + symbol, value = spec + if i == 0: + # First term is special + if symbol is None: + terms.append('{}'.format(value)) + elif abs(value) == 1: + terms.append(symbol if value > 0 else '-'+symbol) + else: + terms.append('{}{}'.format(value, symbol)) + else: + prefix = '+' if value >= 0 else '-' + if symbol is None: + terms.append('{} {}'.format(prefix, abs(value))) + elif abs(value) == 1: + terms.append('{} {}'.format(prefix, symbol)) + else: + terms.append('{} {}{}'.format(prefix, abs(value), symbol)) + return ' '.join(terms) + + def __repr__(self): + return str('Expression({})').format(repr(str(self))) + + +if __name__ == '__main__': + import doctest + doctest.testmod() +","Python" +"Metabolic","zhanglab/psamm","psamm/expression/boolean.py",".py","13650","411","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Representations of boolean expressions and variables. + +These classes can be used to represent simple boolean +expressions and do evaluation with substitutions of +particular variables. +"""""" + +from __future__ import unicode_literals + +import re + +import six +from six import text_type, string_types + +from ..util import FrozenOrderedSet + + +@six.python_2_unicode_compatible +class Variable(object): + """"""Represents a variable in a boolean expression"""""" + + def __init__(self, symbol): + self._symbol = text_type(symbol) + + @property + def symbol(self): + return self._symbol + + def __repr__(self): + return str('Variable({})').format(repr(self._symbol)) + + def __str__(self): + return self._symbol + + def __eq__(self, other): + return isinstance(other, Variable) and self._symbol == other._symbol + + def __ne__(self, other): + return not self == other + + def __hash__(self): + return hash('Variable') ^ hash(self._symbol) + + +class _OperatorTerm(object): + """"""Composite operator term."""""" + def __init__(self, *args): + terms = list() + for arg in args: + if isinstance(arg, self.__class__): + terms.extend(arg) + elif isinstance(arg, (bool, Variable, _OperatorTerm)): + terms.append(arg) + else: + raise ValueError('Invalid term: {!r}'.format(arg)) + self._terms = FrozenOrderedSet(terms) + + def __iter__(self): + return iter(self._terms) + + def __hash__(self): + return hash(self._terms) + + def __len__(self): + return len(self._terms) + + def __eq__(self, other): + return (isinstance(other, self.__class__) and + self._terms == other._terms) + + def __ne__(self, other): + return not self == other + + +class And(_OperatorTerm): + """"""Represents an AND term in an expression."""""" + + +class Or(_OperatorTerm): + """"""Represents an OR term in an expression."""""" + + +class SubstitutionError(Exception): + """"""Error substituting into expression."""""" + + +@six.python_2_unicode_compatible +class Expression(object): + """"""Boolean expression representation. + + The expression can be constructed from an expression string of + variables, operators (""and"", ""or"") and parenthesis groups. For example, + + >>> e = Expression('a and (b or c)') + """""" + + def __init__(self, arg, _vars=None): + if isinstance(arg, (_OperatorTerm, Variable, bool)): + self._root = arg + elif isinstance(arg, string_types): + self._root = _parse_expression(arg) + else: + raise TypeError('Unexpected arguments to Expression: {}'.format( + repr(arg))) + + # If present use _vars to create the set of variables directly. This + # saves a loop over the tree nodes when the variables are already + # known. + if _vars is None: + variables = [] + if isinstance(self._root, (_OperatorTerm, Variable)): + stack = [self._root] + while len(stack) > 0: + term = stack.pop() + if isinstance(term, Variable): + variables.append(term) + elif isinstance(term, _OperatorTerm): + stack.extend(reversed(list(term))) + else: + raise ValueError( + 'Invalid node in expression tree: {!r}'.format( + term)) + + self._variables = FrozenOrderedSet(variables) + else: + self._variables = FrozenOrderedSet(_vars) + + @property + def root(self): + """"""Return root term, variable or boolean of the expression."""""" + return self._root + + @property + def variables(self): + """"""Immutable set of variables in the expression."""""" + return self._variables + + def has_value(self): + """"""Return True if the expression has no variables."""""" + return isinstance(self._root, bool) + + @property + def value(self): + """"""The value of the expression if fully evaluated."""""" + if not self.has_value(): + raise ValueError('Expression is not fully evaluated') + return self._root + + def substitute(self, mapping): + """"""Substitute variables using mapping function."""""" + next_terms = iter([self._root]) + output_stack = [] + current_type = None + terms = [] + variables = [] + term = None + + while True: + try: + term = next(next_terms) + except StopIteration: + term = None + + if term is None: + if current_type is None: + term = terms[0] + break + else: + if len(terms) == 0: + if current_type == And: + term = True + elif current_type == Or: + term = False + elif len(terms) == 1: + term = terms[0] + else: + term = current_type(*terms) + current_type, next_terms, terms = output_stack.pop() + else: + if isinstance(term, _OperatorTerm): + output_stack.append((current_type, next_terms, terms)) + current_type = term.__class__ + terms = [] + next_terms = iter(term) + continue + + # Substitute variable + if isinstance(term, Variable): + term = mapping(term) + if not isinstance(term, (_OperatorTerm, Variable, bool)): + raise SubstitutionError( + 'Expected Variable or bool from substitution,' + ' got: {!r}'.format(term)) + + # Check again after substitution + if isinstance(term, Variable): + variables.append(term) + + # Short circuit with booleans + while isinstance(term, bool): + if current_type == And: + if not term: + current_type, next_terms, terms = output_stack.pop() + continue + else: + break + elif current_type == Or: + if term: + current_type, next_terms, terms = output_stack.pop() + continue + else: + break + else: + terms.append(term) + break + else: + terms.append(term) + + return self.__class__(term, _vars=variables) + + def __repr__(self): + if isinstance(self._root, bool): + arg = self._root + else: + arg = text_type(self) + return str('{}({!r})').format(self.__class__.__name__, arg) + + def __str__(self): + next_terms = iter([self._root]) + output_stack = [] + current_type = None + terms = [] + term = None + + while True: + try: + term = next(next_terms) + except StopIteration: + term = None + + if term is None: + if current_type is None: + term = terms[0] + break + elif current_type == And: + term = ' and '.join(t for t in terms) + elif current_type == Or: + term = ' or '.join(t for t in terms) + current_type, next_terms, terms = output_stack.pop() + + # Break on None here to avoid wrapping the outermost term in + # parentheses. + if current_type is None: + break + + terms.append('(' + term + ')') + else: + if isinstance(term, _OperatorTerm): + output_stack.append((current_type, next_terms, terms)) + current_type = term.__class__ + terms = [] + next_terms = iter(term) + else: + terms.append(text_type(term)) + + return term + + def __eq__(self, other): + if isinstance(other, self.__class__): + return self._root == other._root + return NotImplemented + + def __ne__(self, other): + if isinstance(other, self.__class__): + return not self == other + return NotImplemented + + +class ParseError(Exception): + """"""Signals error parsing boolean expression."""""" + + def __init__(self, *args, **kwargs): + self._span = kwargs.pop('span', None) + super(ParseError, self).__init__(*args, **kwargs) + + @property + def indicator(self): + if self._span is None: + return None + pre = ' ' * self._span[0] + ind = '^' * max(1, self._span[1] - self._span[0]) + return pre + ind + + +def _parse_expression(s): + """"""Parse boolean expression containing and/or operators"""""" + + # Converters for opeartor clauses + operators = { + 'and': And, + 'or': Or, + None: lambda *args: args[0] + } + + # Pairing of end group symbols with start group symbols + group_pairs = { + ')': '(', + ']': '[' + } + + scanner = re.compile(r''' + (\s+) | # space + (\(|\[) | # group_start + (\)|\]) | # group_end + ((?:or|and)\b) | # operator + ([^\s\(\)\[\]]+) | # variable + (\Z) | # end + (.) # error + ''', re.DOTALL | re.VERBOSE | re.UNICODE | re.IGNORECASE) + + # Parsed using two states and a stack of open clauses + # At state 0 (not expect_operator): Expect variable, or parenthesis group + # start. + # At state 1 (expect_operator): Expect operator, parenthesis group end, or + # end. + expect_operator = False + clause_stack = [] + current_clause = [] + clause_operator = None + clause_symbol = None + + def close(): + prev_op, prev_symbol, prev_clause = clause_stack.pop() + prev_clause.append(operators[clause_operator](*current_clause)) + return prev_op, prev_symbol, prev_clause + + for match in re.finditer(scanner, s): + (space, group_start, group_end, operator, variable, end, + error) = match.groups() + + if error is not None: + raise ParseError('Invalid token in expression string: {}'.format( + repr(match.group(0))), span=(match.start(), match.end())) + elif space is not None: + continue + elif expect_operator and operator is not None: + operator = operator.lower() + if operator == 'and' and clause_operator != 'and': + prev_term = current_clause.pop() + clause_stack.append( + (clause_operator, clause_symbol, current_clause)) + current_clause = [prev_term] + elif operator == 'or' and clause_operator == 'and': + clause_operator, clause_symbol, current_clause = close() + clause_operator = operator + expect_operator = False + elif expect_operator and group_end is not None: + if clause_operator == 'and': + clause_operator, clause_symbol, current_clause = close() + if len(clause_stack) == 0: + raise ParseError( + 'Unbalanced parenthesis group in expression', + span=(match.start(), match.end())) + if group_pairs[group_end] != clause_symbol: + raise ParseError( + 'Group started with {} ended with {}'.format( + clause_symbol, group_end), + span=(match.start(), match.end())) + clause_operator, clause_symbol, current_clause = close() + elif expect_operator and end is not None: + if clause_operator == 'and': + clause_operator, clause_symbol, current_clause = close() + elif not expect_operator and variable is not None: + current_clause.append(Variable(variable)) + expect_operator = True + elif not expect_operator and group_start is not None: + clause_stack.append( + (clause_operator, clause_symbol, current_clause)) + current_clause = [] + clause_operator = None + clause_symbol = group_start + else: + raise ParseError( + 'Invalid token in expression string: {!r}'.format( + match.group(0)), + span=(match.start(), match.end())) + + if len(clause_stack) > 0: + raise ParseError('Unbalanced parenthesis group in expression') + + expr = operators[clause_operator](*current_clause) + return expr +","Python" +"Metabolic","zhanglab/psamm","psamm/importers/cobrajson.py",".py","6788","182","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Importer for the COBRApy JSON format."""""" + +import os +import glob +import json +import logging +import decimal + +from six import iteritems + +from ..reaction import Reaction, Compound, Direction +from ..datasource import native +from ..datasource.entry import (DictCompoundEntry as CompoundEntry, + DictReactionEntry as ReactionEntry, + DictCompartmentEntry as CompartmentEntry) + +from ..importer import Importer as BaseImporter, ModelLoadError + +logger = logging.getLogger(__name__) + + +def _float_parser(num_str): + num = float(num_str) + if num.is_integer(): + return int(num) + else: + return decimal.Decimal(num_str) + + +class Importer(BaseImporter): + """"""Read metabolic model from COBRApy JSON format."""""" + + name = 'json' + title = 'COBRApy JSON' + generic = True + + def help(self): + """"""Print help text for importer."""""" + print('Source must contain the model definition in COBRApy JSON' + ' format.\n' + 'Expected files in source directory:\n' + '- *.json') + + def _resolve_source(self, source): + """"""Resolve source to filepath if it is a directory."""""" + if os.path.isdir(source): + sources = glob.glob(os.path.join(source, '*.json')) + if len(sources) == 0: + raise ModelLoadError('No .json file found in source directory') + elif len(sources) > 1: + raise ModelLoadError( + 'More than one .json file found in source directory') + return sources[0] + return source + + def _import(self, file): + model_doc = json.load(file, parse_float=_float_parser) + model = native.NativeModel() + model.compartments.update(self._read_compartments(model_doc)) + model.compounds.update(self._read_compounds(model_doc)) + + for reaction, lower, upper in self._read_reactions(model_doc): + model.reactions.add_entry(reaction) + if lower is not None and upper is not None: + model.limits[reaction.id] = reaction.id, lower, upper + + model.name = model_doc.get('id', 'COBRA JSON model') + + biomass_reaction = None + objective_reactions = set() + for reaction in model_doc['reactions']: + if reaction.get('objective_coefficient', 0) != 0: + objective_reactions.add(reaction['id']) + + if len(objective_reactions) == 1: + biomass_reaction = next(iter(objective_reactions)) + logger.info('Detected biomass reaction: {}'.format( + biomass_reaction)) + elif len(objective_reactions) > 1: + logger.warning( + 'Multiple reactions are used as the' + ' biomass reaction: {}'.format(objective_reactions)) + + model.biomass_reaction = biomass_reaction + + # Set compartment in reaction compounds + compound_compartment = {} + for compound in model.compounds: + compartment = compound.properties.pop('compartment') + compound_compartment[compound.id] = compartment + + for reaction in model.reactions: + equation = reaction.equation + if equation is None: + continue + + # Translate compartments in reaction + left = ((c.in_compartment(compound_compartment[c.name]), v) for + c, v in equation.left) + right = ((c.in_compartment(compound_compartment[c.name]), v) for + c, v in equation.right) + reaction.properties['equation'] = Reaction( + equation.direction, left, right) + + return model + + def _read_compartments(self, doc): + for compartment, name in iteritems(doc.get('compartments', {})): + yield CompartmentEntry(dict(id=compartment, name=name)) + + def _read_compounds(self, doc): + for compound in doc['metabolites']: + entry = CompoundEntry(compound) + if 'formula' in entry.properties: + formula = self._try_parse_formula( + entry.id, entry.properties['formula']) + if formula is not None: + entry.properties['formula'] = formula + yield entry + + def _parse_reaction_equation(self, entry): + metabolites = entry.properties.pop('metabolites') + compounds = ((Compound(metabolite), value) + for metabolite, value in iteritems(metabolites)) + if (entry.properties.get('lower_bound') == 0 and + entry.properties.get('upper_bound') != 0): + direction = Direction.Forward + elif (entry.properties.get('lower_bound') != 0 and + entry.properties.get('upper_bound') == 0): + direction = Direction.Reverse + else: + direction = Direction.Both + return Reaction(direction, compounds) + + def _read_reactions(self, doc): + for reaction in doc['reactions']: + entry = ReactionEntry(reaction) + + entry.properties['equation'] = ( + self._parse_reaction_equation(entry)) + + lower, upper = None, None + + if 'lower_bound' in entry.properties: + lower = entry.properties.pop('lower_bound') + if 'upper_bound' in entry.properties: + upper = entry.properties.pop('upper_bound') + + if 'gene_reaction_rule' in entry.properties: + genes = self._try_parse_gene_association( + entry.id, entry.properties.pop('gene_reaction_rule')) + if genes is not None: + entry.properties['genes'] = genes + + yield entry, lower, upper + + def import_model(self, source): + """"""Import and return model instance."""""" + if not hasattr(source, 'read'): # Not a File-like object + with open(self._resolve_source(source), 'r') as f: + return self._import(f) + else: + return self._import(source) +","Python" +"Metabolic","zhanglab/psamm","psamm/importers/matlab.py",".py","13100","303","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015-2017 Jon Lund Steffensen +# Copyright 2019-2020 Jing Wang + +""""""Importer for the COBRApy MAT format."""""" + +from psamm.importer import Importer as BaseImporter, ModelLoadError +from psamm.datasource.entry import (DictCompoundEntry as CompoundEntry, + DictReactionEntry as ReactionEntry, + DictCompartmentEntry as CompartmentEntry) +from psamm.datasource import native +from psamm.reaction import Reaction, Compound, Direction +import re +import numpy as np +from scipy.io import loadmat +import decimal +import logging +import glob +import os + + +logger = logging.getLogger(__name__) + + +def _float_parser(num_str): + num = float(num_str) + if num.is_integer(): + return int(num) + else: + return decimal.Decimal(num_str) + + +class Importer(BaseImporter): + """"""Read metabolic model from COBRA MATLAB mat format."""""" + + name = 'matlab' + title = 'COBRA MATLAB mat' + generic = True + + def help(self): + """"""Print help text for importer."""""" + print('Source must contain the model definition in COBRA MATLAB mat' + ' format.\n' + 'Expected files in source directory:\n' + '- *.mat') + + def _resolve_source(self, source): + """"""Resolve source to filepath if it is a directory."""""" + if os.path.isdir(source): + sources = glob.glob(os.path.join(source, '*.mat')) + if len(sources) == 0: + raise ModelLoadError('No .mat file found in source directory') + elif len(sources) > 1: + raise ModelLoadError( + 'More than one .mat file found in source directory') + return sources[0] + return source + + def _import(self, file, name): + model_doc = loadmat(file) + if name is None: + names = [k for k in model_doc.keys() + if k not in ['__header__', '__version__', '__globals__']] + modelnames = list() + for i in names: + if (isinstance(model_doc[i], np.ndarray) and + len(model_doc[i].dtype) > 1): + modelnames.append(i) + if len(modelnames) == 1: + name = str(modelnames[0]) + model_doc = model_doc[modelnames[0]] + elif len(modelnames) > 1: + raise ModelLoadError( + ('More than one model exist, ' + 'please choose from: %s ' + 'using --model-name' % modelnames)) + else: + raise ModelLoadError('Incorrect format') + else: + if name not in model_doc.keys(): + raise ModelLoadError('Incorrect model name specified') + else: + model_doc = model_doc[name] + if not (isinstance(model_doc, np.ndarray) and + len(model_doc.dtype) > 1): + raise ModelLoadError('Incorrect format') + model = native.NativeModel() + model.name = name + self._compartments_from_compound = set() + self._origid_compound = dict() + model.compounds.update(self._read_compounds(model_doc)) + model.compartments.update(self._compartments_from_compound) + + self._boundary_compartment = None + # Add model level compartment information + if all(var in model_doc.dtype.names for var in ['comps', 'compNames']): + model.compartments.update(self._read_compartments(model_doc)) + for comp in model.compartments: + if comp.name.lower() == 'boundary': # has boundary compartment + self._boundary_compartment = comp.id + model.compartments.discard(self._boundary_compartment) + + for reaction, lower, upper in self._read_reactions(model_doc): + model.reactions.add_entry(reaction) + if lower is not None and upper is not None: + model.limits[reaction.id] = reaction.id, lower, upper + + biomass_reaction = None + objective_reactions = set() + if 'c' in model_doc.dtype.names: + for i in range(len(model_doc['c'][0, 0])): + if model_doc['c'][0, 0][i][0] != 0: + objective_reactions.add( + str(model_doc['rxns'][0, 0][i][0][0])) + if len(objective_reactions) == 1: + biomass_reaction = next(iter(objective_reactions)) + logger.info('Detected biomass reaction: {}'.format( + biomass_reaction)) + elif len(objective_reactions) > 1: + logger.warning( + 'Multiple reactions are used as the' + ' biomass reaction: {}'.format(objective_reactions)) + else: + logger.warning('No objective reaction') + + model.biomass_reaction = biomass_reaction + + return model + + def _read_compartments(self, doc): + for i in range(len(doc['comps'][0, 0])): + compartment = str(doc['comps'][0, 0][i][0][0]) + name = str(doc['compNames'][0, 0][i][0][0]) + yield CompartmentEntry(dict(id=compartment, name=name)) + + def _read_compounds(self, doc): + for i in range(len(doc['mets'][0, 0])): + properties = dict() + id = doc['mets'][0, 0][i][0][0] + match = re.search(r'\[[0-9a-zA-Z]+\]$', id) # e.g. h2o[c] + uniqid = id + compartment = None + if match is not None: # compartment information in id + compartment = match.group().strip('[]') + self._compartments_from_compound.add( + CompartmentEntry(dict(id=compartment, name=''))) + uniqid = re.sub(r'\[[0-9a-zA-Z]+\]$', '', id) + else: + match = re.search(r'_[0-9a-zA-Z]+$', id) # e.g. h2o_c + if match is not None: # compartment information in id + compartment = match.group().strip('_') + self._compartments_from_compound.add( + CompartmentEntry( + dict(id=compartment, name=''))) + uniqid = re.sub(r'_[0-9a-zA-Z]+$', '', id) + else: + match = re.search(r'\([0-9a-zA-Z]+\)$', id) # e.g. h2o(c) + if match is not None: # compartment information in id + compartment = match.group().strip('()') + self._compartments_from_compound.add( + CompartmentEntry(dict(id=compartment, name=''))) + uniqid = re.sub(r'\([0-9a-zA-Z]+\)$', '', id) + else: + match = re.search(r'[0-9][a-z]$', id) # e.g. cpd100c + if match is not None: + compartment = str(match.group()[1]) + self._compartments_from_compound.add( + CompartmentEntry( + dict(id=compartment, name=''))) + uniqid = id[:len(id) - 1] + properties['id'] = uniqid + self._origid_compound[id] = Compound(uniqid, compartment) + for dtype in doc.dtype.names: + if dtype.startswith('met') and dtype != 'mets': + # Compound related dtypes + if dtype == 'metFormulas': + if len(doc['metFormulas'][0, 0][i][0]) > 0: + properties[ + 'formula'] = doc['metFormulas'][0, 0][i][0][0] + elif dtype == 'metCharges': + properties['charge'] = _float_parser( + doc['metCharges'][0, 0][i][0]) + elif dtype == 'metNames': + properties['name'] = str( + doc['metNames'][0, 0][i][0][0]) + else: # other dtypes + value = doc[dtype][0, 0][i][0] + if isinstance(value, np.ndarray): + if len(value) == 1: + value = value[0] + elif len(value) == 0: + continue + dtype = dtype.lstrip('met') + properties[dtype] = str(value) + + entry = CompoundEntry(properties) + if 'formula' in entry.properties: + formula = self._try_parse_formula( + entry.id, entry.properties['formula']) + if formula is not None: + entry.properties['formula'] = formula + yield entry + + def _read_reactions(self, doc): + for i in range(len(doc['rxns'][0, 0])): + properties = dict() + properties['id'] = str(doc['rxns'][0, 0][i][0][0]) + + for dtype in doc.dtype.names: + if dtype.startswith('rxn') and dtype != 'rxns': + # reaction related dtypes + if dtype == 'rxnNames': + if len(doc['rxnNames'][0, 0][i][0]) > 0: + properties['name'] = str( + doc['rxnNames'][0, 0][i][0][0]) + else: # other dtypes + value = doc[dtype][0, 0][i][0] + if isinstance(value, np.ndarray): + if len(value) == 1: + value = value[0] + elif len(value) == 0: + continue + dtype = dtype.lstrip('rxn') + properties[dtype] = str(value) + + lower = float(doc['lb'][0, 0][i][0]) + upper = float(doc['ub'][0, 0][i][0]) + if lower == 0 and upper != 0: + direction = Direction.Forward + elif lower != 0 and upper == 0: + direction = Direction.Reverse + else: + direction = Direction.Both + + # parse equation + compounds = list() + try: + # incase it's a sparse matrix + rows = doc['S'][0, 0][:, i].indices + except AttributeError: + # incase it's an ndarray + rows = np.flatnonzero(doc['S'][0, 0][:, i]) + for j in rows: + cpd = self._origid_compound.get( + doc['mets'][0, 0][j][0][0] + ) + if cpd.compartment == self._boundary_compartment: + # skip compound that is out of boundary + continue + compounds.append( + ( + cpd, # compound id + float(doc['S'][0, 0][j, i]) # stochiometry + ) + ) + properties['equation'] = (Reaction(direction, compounds)) + + # parse genes + if 'grRules' in doc.dtype.names: + if len(doc['grRules'][0, 0][i][0]) > 0: + genes = doc['grRules'][0, 0][i][0][0] + if isinstance(genes, np.unicode_): + properties['genes'] = self._try_parse_gene_association( + properties['id'], genes + ) + + # parse subsystem + if 'subSystems' in doc.dtype.names: + if doc['subSystems'][0, 0][i][0].size > 0: + # the subSystem has either 2 levels or 4 levels + # check which level to obtain + if isinstance(doc['subSystems'][0, 0][i][0][0], str): + properties['subsystem'] = str( + doc['subSystems'][0, 0][i][0][0]) + elif len(doc['subSystems'][0, 0][i][0][0][0]) > 0: + properties['subsystem'] = str( + doc['subSystems'][0, 0][i][0][0][0][0]) + + entry = ReactionEntry(properties) + yield entry, lower, upper + + def import_model(self, source, model_name=None): + """"""Import and return model instance."""""" + if not hasattr(source, 'read'): # Not a File-like object + with open(self._resolve_source(source), 'rb') as f: + return self._import(f, model_name) + else: + return self._import(source, model_name) +","Python" +"Metabolic","zhanglab/psamm","psamm/importers/__init__.py",".py","768","19","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen + +""""""Importers for various external model formats."""""" +","Python" +"Metabolic","zhanglab/psamm","psamm/importers/sbml.py",".py","4224","125","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""SBML importers."""""" + +import os +import glob +import logging + + +from ..datasource import sbml +from ..datasource.context import FilePathContext +from ..datasource.entry import (DictCompartmentEntry, DictCompoundEntry, + DictReactionEntry) + +from ..importer import Importer, ParseError, ModelLoadError + +logger = logging.getLogger(__name__) + + +class BaseImporter(Importer): + """"""Base importer for reading metabolic model from an SBML file."""""" + + def help(self): + """"""Print importer help text."""""" + print('Source must contain the model definition in SBML format.\n' + 'Expected files in source directory:\n' + '- *.sbml') + + def _resolve_source(self, source): + """"""Resolve source to filepath if it is a directory."""""" + if os.path.isdir(source): + sources = glob.glob(os.path.join(source, '*.sbml')) + if len(sources) == 0: + raise ModelLoadError('No .sbml file found in source directory') + elif len(sources) > 1: + raise ModelLoadError( + 'More than one .sbml file found in source directory') + return sources[0] + return source + + def _get_reader(self, f): + raise NotImplementedError('Subclasses must implement _get_reader()') + + def import_model(self, source): + """"""Import and return model instance."""""" + source = self._resolve_source(source) + self._context = FilePathContext(source) + with self._context.open() as f: + self._reader = self._open_reader(f) + + return self._reader.create_model() + + +class StrictImporter(BaseImporter): + """"""Read metabolic model from an SBML file using strict parser."""""" + + name = 'SBML-strict' + title = 'SBML model (strict)' + generic = True + + def _open_reader(self, f): + try: + return sbml.SBMLReader(f, strict=True, ignore_boundary=True) + except sbml.ParseError as e: + raise ParseError(e) + + def _translate_compartment(self, entry, new_id): + return DictCompartmentEntry(entry, new_id) + + def _translate_compound(self, entry, new_id, compartment_map): + return DictCompoundEntry(entry, new_id) + + def _translate_reaction( + self, entry, new_id, compartment_map, compound_map): + return DictReactionEntry(entry, new_id) + + def import_model(self, source): + """"""Import and return model instance."""""" + model = super(StrictImporter, self).import_model(source) + + # Translate entries into dict-based entries. + sbml.convert_model_entries( + model, convert_id=lambda entry: entry.id, + translate_compartment=self._translate_compartment, + translate_compound=self._translate_compound, + translate_reaction=self._translate_reaction) + + return model + + +class NonstrictImporter(BaseImporter): + """"""Read metabolic model from an SBML file using non-strict parser."""""" + + name = 'SBML' + title = 'SBML model (non-strict)' + generic = True + + def _open_reader(self, f): + try: + return sbml.SBMLReader(f, strict=False, ignore_boundary=True) + except sbml.ParseError as e: + raise ParseError(e) + + def import_model(self, source): + """"""Import and return model instance."""""" + model = super(NonstrictImporter, self).import_model(source) + sbml.convert_sbml_model(model) + return model +","Python" +"Metabolic","zhanglab/psamm","psamm/datasource/modelseed.py",".py","3528","113","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2016 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Module related to loading ModelSEED database files."""""" + +import csv +import re + +from .context import FileMark +from .entry import CompoundEntry as BaseCompoundEntry + + +class ParseError(Exception): + """"""Exception used to signal errors while parsing"""""" + + +def decode_name(s): + """"""Decode names in ModelSEED files"""""" + # Some names contain XML-like entity codes + return re.sub(r'&#(\d+);', lambda x: chr(int(x.group(1))), s) + + +class CompoundEntry(BaseCompoundEntry): + """"""Representation of entry in a ModelSEED compound table"""""" + + def __init__(self, id, names, formula, filemark=None): + self._id = id + self._properties = { + 'id': self._id, + 'names': list(names), + 'formula': formula + } + + # Find shortest name + # Usually the best name is the shortest one, + # but in the case of ties, the best one is + # usually the last one to appear in the list. + # Since the sort is stable we can obtain this + # by first reversing the list, then sorting + # by length. + names = self._properties['names'] + self._properties['name'] = None + if len(self._properties['names']) > 0: + name = sorted(reversed(names), key=lambda x: len(x))[0] + self._properties['name'] = name + + self._filemark = filemark + + @property + def id(self): + return self._id + + @property + def name(self): + return self._properties.get('name') + + @property + def names(self): + return iter(self._properties.get('names')) + + @property + def formula(self): + return self._properties.get('formula') + + @property + def properties(self): + return dict(self._properties) + + @property + def filemark(self): + return self._filemark + + +def parse_compound_file(f, context=None): + """"""Iterate over the compound entries in the given file"""""" + + f.readline() # Skip header + for lineno, row in enumerate(csv.reader(f, delimiter='\t')): + compound_id, names, formula = row[:3] + names = (decode_name(name) for name in names.split(',
')) + + # ModelSEED sometimes uses an asterisk and number at + # the end of formulas. This seems to have a similar + # meaning as '(...)n'. + m = re.match(r'^(.*)\*(\d*)$', formula) + if m is not None: + if m.group(2) != '': + formula = '({}){}'.format(m.group(1), m.group(2)) + else: + formula = '({})n'.format(m.group(1)) + + formula = formula.strip() + if formula == '' or formula == 'noformula': + formula = None + + mark = FileMark(context, lineno, 0) + yield CompoundEntry(compound_id, names, formula, filemark=mark) +","Python" +"Metabolic","zhanglab/psamm","psamm/datasource/entry.py",".py","7044","216","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2016-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2020 Elysha Sameth + +""""""Representation of compound/reaction entries in models."""""" + +from __future__ import unicode_literals + +import abc +from collections.abc import Mapping + +from six import add_metaclass + + +@add_metaclass(abc.ABCMeta) +class ModelEntry(object): + """"""Abstract model entry. + + Provdides a base class for model entries which are representations of + any entity (such as compound, reaction or compartment) in a model. An + entity has an ID, and may have a name and filemark. The ID is a unique + string identified within a model. The name is a string identifier for + human consumption. The filemark indicates where the entry originates from + (e.g. file name and line number). Any additional properties for an + entity exist in ``properties`` which is any dict-like object mapping + from string keys to any value type. The ``name`` entry in the dictionary + corresponds to the name. Entries can be mutable, where the + properties can be modified, or immutable, where the properties cannot be + modified or where modifications are ignored. The ID is always immutable. + """""" + @abc.abstractproperty + def id(self): + """"""Identifier of entry."""""" + + @property + def name(self): + """"""Name of entry (or None)."""""" + return self.properties.get('name') + + @abc.abstractproperty + def properties(self): + """"""Properties of entry as a :class:`Mapping` subclass (e.g. dict). + + Note that the properties are not generally mutable but may be mutable + for specific subclasses. If the ``id`` exists in this dictionary, it + must never change the actual entry ID as obtained from the ``id`` + property, even if other properties are mutable. + """""" + + @abc.abstractproperty + def filemark(self): + """"""Position of entry in the source file (or None)."""""" + + def __repr__(self): + return str('<{} id={!r}>').format(self.__class__.__name__, self.id) + + +class CompoundEntry(ModelEntry): + """"""Abstract compound entry. + + Entry subclass for representing compounds. This standardizes the properties + ``formula`` and ``charge``. + """""" + @property + def formula(self): + """"""Chemical formula of compound."""""" + return self.properties.get('formula') + + @property + def charge(self): + """"""Compound charge value."""""" + return self.properties.get('charge') + + +class ReactionEntry(ModelEntry): + """"""Abstract reaction entry. + + Entry subclass for representing compounds. This standardizes the properties + ``equation`` and ``genes``. + """""" + @property + def equation(self): + """"""Reaction equation."""""" + return self.properties.get('equation') + + @property + def genes(self): + """"""Gene association expression."""""" + return self.properties.get('genes') + + +class CompartmentEntry(ModelEntry): + """"""Abstract compartment entry. + + Entry subclass for representing compartments. + """""" + + +class _BaseDictEntry(ModelEntry): + """"""Base class for concrete entries based on dictionary. + + The properties are mutable for this subclass. If ``id`` is None, the + value corresponding to the ``id`` key in the dictionary is used. If this is + not defined, a :class:`ValueError` is raised. + """""" + def __init__(self, abstract_type, properties={}, filemark=None, id=None): + if isinstance(properties, abstract_type): + self._id = id + if self._id is None: + self._id = properties.id + self._properties = dict(properties.properties) + if filemark is None: + filemark = properties.filemark + elif isinstance(properties, Mapping): + self._id = id + if self._id is None: + if 'id' not in properties: + raise ValueError('id not defined in properties') + self._id = properties['id'] + self._properties = dict(properties) + else: + raise ValueError('Invalid type of properties object') + + self._properties['id'] = self._id + self._filemark = filemark + + @property + def id(self): + return self._id + + @ModelEntry.name.setter + def name(self, value): + self._properties['name'] = value + + @property + def properties(self): + return self._properties + + @property + def filemark(self): + return self._filemark + + +class DictCompoundEntry(CompoundEntry, _BaseDictEntry): + """"""Compound entry backed by dictionary. + + The given properties dictionary must contain a key ``id`` with the + identifier. + + Args: + properties: dict or :class:`CompoundEntry` to construct from. + filemark: Where the entry was parsed from (optional) + """""" + def __init__(self, *args, **kwargs): + super(DictCompoundEntry, self).__init__(CompoundEntry, *args, **kwargs) + + @CompoundEntry.formula.setter + def formula(self, value): + self._properties['formula'] = value + + @CompoundEntry.charge.setter + def charge(self, value): + self._properties['charge'] = value + + +class DictReactionEntry(ReactionEntry, _BaseDictEntry): + """"""Reaction entry backed by dictionary. + + The given properties dictionary must contain a key ``id`` with the + identifier. + + Args: + properties: dict or :class:`ReactionEntry` to construct from. + filemark: Where the entry was parsed from (optional) + """""" + def __init__(self, *args, **kwargs): + super(DictReactionEntry, self).__init__(ReactionEntry, *args, **kwargs) + + @ReactionEntry.equation.setter + def equation(self, value): + self._properties['equation'] = value + + @ReactionEntry.genes.setter + def genes(self, value): + self._properties['genes'] = value + + +class DictCompartmentEntry(CompartmentEntry, _BaseDictEntry): + """"""Compartment entry backed by dictionary. + + The given properties dictionary must contain a key ``id`` with the + identifier. + + Args: + properties: dict or :class:`CompartmentEntry` to construct from. + filemark: Where the entry was parsed from (optional) + """""" + def __init__(self, *args, **kwargs): + super(DictCompartmentEntry, self).__init__( + CompartmentEntry, *args, **kwargs) +","Python" +"Metabolic","zhanglab/psamm","psamm/datasource/context.py",".py","3490","118","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Utilities for keeping track of parsing context."""""" + +from __future__ import unicode_literals + +import os +import six +from six import string_types, text_type + + +class ContextError(Exception): + """"""Raised when a context failure occurs."""""" + + +@six.python_2_unicode_compatible +class FilePathContext(object): + """"""File context that keeps track of contextual information. + + When a file is loaded, all files specified in that file must be loaded + relative to the first file. This is made possible by keeping a context + that remembers where a file was loaded so that other files can be loaded + relatively. + """""" + + def __init__(self, arg): + """"""Create new context from a path or existing context"""""" + + if arg is not None: + if isinstance(arg, string_types): + self._filepath = arg + else: + self._filepath = arg.filepath + + if self._filepath is not None: + self._basepath = os.path.dirname(self._filepath) + else: + self._basepath = None + else: + self._filepath = None + self._basepath = None + + @property + def filepath(self): + return self._filepath + + @property + def basepath(self): + return self._basepath + + def resolve(self, relpath): + if self._basepath is None: + raise ContextError('Context is a null context') + return FilePathContext(os.path.join(self._basepath, relpath)) + + def open(self, mode='r'): + if self._basepath is None: + raise ContextError('Context is a null context') + return open(self.filepath, mode) + + def __str__(self): + return text_type(self._filepath) + + +@six.python_2_unicode_compatible +class FileMark(object): + """"""Marks a position in a file. + + This is used when parsing input files, to keep track of the position that + generates an entry. + """""" + + def __init__(self, filecontext, line, column): + self._filecontext = filecontext + self._line = line + self._column = column + + @property + def filecontext(self): + return self._filecontext + + @property + def line(self): + return self._line + + @property + def column(self): + return self._column + + def __str__(self): + result = text_type(self._filecontext) + if self._line is not None: + result += ':{}'.format(self._line) + if self._column is not None: + result += ':{}'.format(self._column) + return result + + def __repr__(self): + return str('{}({}, {}, {})').format( + self.__class__.__name__, repr(self._filecontext), repr(self._line), + repr(self._column)) +","Python" +"Metabolic","zhanglab/psamm","psamm/datasource/__init__.py",".py","0","0","","Python" +"Metabolic","zhanglab/psamm","psamm/datasource/sbml.py",".py","71214","1892","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Parser for SBML model files."""""" + +from __future__ import unicode_literals + +from decimal import Decimal +from fractions import Fraction +from functools import partial +import logging +import re +import json +from collections import OrderedDict, Counter + +# Import ElementTree XML parser. The lxml etree implementation may also be +# used with SBMLReader but has compatibility issues with SBMLWriter. +try: + import xml.etree.cElementTree as ETree +except ImportError: + import xml.etree.ElementTree as ETree + +from six import itervalues, iteritems, text_type, PY3 + +from .context import FileMark +from .entry import (CompoundEntry as BaseCompoundEntry, + ReactionEntry as BaseReactionEntry, + CompartmentEntry as BaseCompartmentEntry, + DictReactionEntry, DictCompoundEntry, + DictCompartmentEntry) +from .native import NativeModel +from ..reaction import Reaction, Compound, Direction +from ..metabolicmodel import create_exchange_id +from ..expression.boolean import Expression, And, Or, Variable +from .. import util + +logger = logging.getLogger(__name__) + +# Level 1 namespaces +SBML_NS_L1 = 'http://www.sbml.org/sbml/level1' + +# Level 2 namespaces +SBML_NS_L2 = 'http://www.sbml.org/sbml/level2' +SBML_NS_L2_V2 = 'http://www.sbml.org/sbml/level2/version2' +SBML_NS_L2_V3 = 'http://www.sbml.org/sbml/level2/version3' +SBML_NS_L2_V4 = 'http://www.sbml.org/sbml/level2/version4' +SBML_NS_L2_V5 = 'http://www.sbml.org/sbml/level2/version5' + +# Level 3 namespaces +SBML_NS_L3_V1_CORE = 'http://www.sbml.org/sbml/level3/version1/core' + +MATHML_NS = 'http://www.w3.org/1998/Math/MathML' +XHTML_NS = 'http://www.w3.org/1999/xhtml' + +# FBC namespaces +FBC_V1 = 'http://www.sbml.org/sbml/level3/version1/fbc/version1' +FBC_V2 = 'http://www.sbml.org/sbml/level3/version1/fbc/version2' + + +# COBRA ID mappings +_COBRA_DECODE_ESCAPES = { + '_DASH_': '-', + '_FSLASH_': '/', + '_BSLASH_': '\\', + '_LPAREN_': '(', + '_RPAREN_': ')', + '_LSQBKT_': '[', + '_RSQBKT_': ']', + '_COMMA_': ',', + '_PERIOD_': '.', + '_APOS_': ""'"" +} + + +def _tag(tag, namespace=None): + """"""Prepend namespace to tag name"""""" + if namespace is None: + return text_type(tag) + return '{{{}}}{}'.format(namespace, tag) + + +class ParseError(Exception): + """"""Error parsing SBML file"""""" + + +class _SBMLEntry(object): + """"""Base class for compound and reaction entries."""""" + + def __init__(self, reader, root): + self._reader = reader + self._root = root + self._id = self._element_get_id(root) + + def _element_get_id(self, element): + """"""Get id of reaction or species element. + + In old levels the name is used as the id. This method returns the + correct attribute depending on the level. + """""" + if self._reader._level > 1: + entry_id = element.get('id') + else: + entry_id = element.get('name') + return entry_id + + @property + def id(self): + """"""Entity ID"""""" + return self._id + + @property + def xml_notes(self): + """"""Access the entity notes as an XML document fragment."""""" + return self._root.find(self._reader._sbml_tag('notes')) + + @property + def xml_annotation(self): + """"""Access the entity annotation as an XML document fragment."""""" + return self._root.find(self._reader._sbml_tag('annotation')) + + +class SBMLSpeciesEntry(_SBMLEntry, BaseCompoundEntry): + """"""Species entry in the SBML file"""""" + + def __init__(self, reader, root, filemark=None): + super(SBMLSpeciesEntry, self).__init__(reader, root) + + self._name = root.get('name') + self._comp = root.get('compartment') + + if self._comp is None: + msg = 'Species {} has no compartment!'.format(self.id) + if self._reader._strict: + raise ParseError(msg) + else: + logger.warning(msg) + + self._boundary = root.get('boundaryCondition', 'false') == 'true' + + # In non-strict mode the species that ends with _b are considered + # boundary conditions. + if not self._reader._strict and self._id.endswith('_b'): + logger.warning('Species {} was converted to boundary condition' + ' because of ""_b"" suffix'.format(self.id)) + self._boundary = True + + self._filemark = filemark + + @property + def name(self): + """"""Species name"""""" + return self._name + + @property + def compartment(self): + """"""Species compartment"""""" + return self._comp + + def _parse_charge_string(self, s): + try: + return int(s) + except ValueError: + if self._reader._strict: + raise ParseError('Invalid charge for species {}'.format( + self.id)) + else: + return None + + @property + def charge(self): + """"""Species charge"""""" + if self._reader._level == 3: + # Look for FBC charge + for ns in (FBC_V2, FBC_V1): + charge = self._root.get(_tag('charge', ns)) + if charge is not None: + return self._parse_charge_string(charge) + else: + charge = self._root.get('charge') + if charge is not None: + return self._parse_charge_string(charge) + + return None + + @property + def formula(self): + """"""Species formula"""""" + if self._reader._level == 3: + for ns in (FBC_V2, FBC_V1): + formula = self._root.get(_tag('chemicalFormula', ns)) + if formula is not None: + return formula + + return None + + @property + def boundary(self): + """"""Whether this compound is a boundary condition"""""" + return self._boundary + + @property + def properties(self): + """"""All species properties as a dict"""""" + properties = {'id': self._id, + 'boundary': self._boundary} + if 'name' in self._root.attrib: + properties['name'] = self._root.get('name') + if 'compartment' in self._root.attrib: + properties['compartment'] = self._root.get('compartment') + + charge = self.charge + if charge is not None: + properties['charge'] = charge + + formula = self.formula + if formula is not None: + properties['formula'] = formula + + return properties + + @property + def filemark(self): + return self._filemark + + +class SBMLReactionEntry(_SBMLEntry, BaseReactionEntry): + """"""Reaction entry in SBML file"""""" + + def __init__(self, reader, root, filemark=None): + super(SBMLReactionEntry, self).__init__(reader, root) + + self._name = self._root.get('name') + self._rev = self._root.get('reversible', 'true') == 'true' + + left, right = [], [] + for side, tag_name in ((left, 'listOfReactants'), + (right, 'listOfProducts')): + for species_id, value in self._parse_species_references(tag_name): + try: + species_entry = self._reader.get_species(species_id) + if (self._reader._ignore_boundary and + species_entry.boundary): + # Skip boundary species when ignoring these + continue + except KeyError: + message = ('Reaction {} references non-existent' + ' species {}'.format(self._id, species_id)) + if not self._reader._strict: + # In non-strict mode simply skip these references + logger.warn(message) + continue + raise ParseError(message) + + species_id, species_comp = ( + species_entry.id, species_entry.compartment) + compound = Compound(species_id, compartment=species_comp) + side.append((compound, value)) + + direction = Direction.Both if self._rev else Direction.Forward + self._equation = Reaction(direction, left, right) + + # Parse flux bounds of reaction + self._lower_flux = None + self._upper_flux = None + + if reader._level == 3: + lower = self._root.get(_tag('lowerFluxBound', FBC_V2)) + if lower is not None: + if lower not in reader._model_constants: + raise ParseError( + 'Lower flux parameter of {} is not defined in' + ' model parameter constants'.format(self.id)) + self._lower_flux = reader._model_constants[lower] + + upper = self._root.get(_tag('upperFluxBound', FBC_V2)) + if upper is not None: + if upper not in reader._model_constants: + raise ParseError( + 'Upper flux parameter of {} is not defined in' + ' model parameter constants'.format(self.id)) + self._upper_flux = reader._model_constants[upper] + + if (lower is None and upper is None and + self.id in reader._reaction_flux_bounds): + # Parse bounds from listOfFluxBounds in FBCv1 + for bound in reader._reaction_flux_bounds[self.id]: + if bound.operation == 'equal': + self._lower_flux = bound.value + self._upper_flux = bound.value + elif bound.operation == 'lessEqual': + self._upper_flux = bound.value + elif bound.operation == 'greaterEqual': + self._lower_flux = bound.value + + self._filemark = filemark + + def _parse_species_references(self, name): + """"""Yield species id and parsed value for a speciesReference list"""""" + for species in self._root.iterfind('./{}/{}'.format( + self._reader._sbml_tag(name), + self._reader._sbml_tag('speciesReference'))): + + species_id = species.get('species') + + if self._reader._level == 1: + # In SBML level 1 only positive integers are allowed for + # stoichiometry but a positive integer denominator can be + # specified. + try: + value = int(species.get('stoichiometry', 1)) + denom = int(species.get('denominator', 1)) + species_value = Fraction(value, denom) + except ValueError: + message = ('Non-integer stoichiometry is not allowed in' + ' SBML level 1 (reaction {})'.format(self.id)) + if self._reader._strict: + raise ParseError(message) + else: + logger.warning(message) + species_value = Decimal(species.get('stoichiometry', 1)) + elif self._reader._level == 2: + # Stoichiometric value is a double but can alternatively be + # specified using math (not implemented). + value_str = species.get('stoichiometry', None) + if value_str is None: + if 'stoichiometryMath' in species: + raise ParseError('stoichiometryMath in ' + 'speciesReference is not implemented') + species_value = 1 + else: + species_value = Decimal(value_str) + elif self._reader._level == 3: + # Stoichiometric value is a double but can alternatively be + # specified using initial assignment (not implemented). + value_str = species.get('stoichiometry', None) + if value_str is None: + raise ParseError('Missing stoichiometry in' + ' speciesReference is not implemented') + species_value = Decimal(value_str) + + if species_value % 1 == 0: + species_value = int(species_value) + + yield species_id, species_value + + @property + def id(self): + """"""Reaction ID"""""" + return self._id + + @property + def name(self): + """"""Reaction name"""""" + return self._name + + @property + def reversible(self): + """"""Whether the reaction is reversible"""""" + return self._rev + + @property + def equation(self): + """"""Reaction equation is a :class:`Reaction ` + object"""""" + return self._equation + + @property + def kinetic_law_reaction_parameters(self): + """"""Iterator over the values of kinetic law reaction parameters"""""" + + for parameter in self._root.iterfind( + './{}/{}/{}'.format(self._reader._sbml_tag('kineticLaw'), + self._reader._sbml_tag('listOfParameters'), + self._reader._sbml_tag('parameter'))): + param_id = parameter.get('id') + param_name = parameter.get('name') + param_value = Decimal(parameter.get('value')) + param_units = parameter.get('units') + + yield param_id, param_name, param_value, param_units + + @property + def properties(self): + """"""All reaction properties as a dict"""""" + properties = {'id': self._id, + 'reversible': self._rev, + 'equation': self._equation} + if 'name' in self._root.attrib: + properties['name'] = self._root.get('name') + if self._lower_flux is not None: + properties['lower_flux'] = self._lower_flux + if self._upper_flux is not None: + properties['upper_flux'] = self._upper_flux + + return properties + + @property + def filemark(self): + return self._filemark + + +class SBMLCompartmentEntry(_SBMLEntry, BaseCompartmentEntry): + """"""Compartment entry in the SBML file"""""" + + def __init__(self, reader, root, filemark=None): + super(SBMLCompartmentEntry, self).__init__(reader, root) + + self._name = self._root.get('name') + self._filemark = filemark + + @property + def properties(self): + """"""All compartment properties as a dict."""""" + properties = {'id': self._id} + if self._name is not None: + properties['name'] = self._name + + return properties + + @property + def filemark(self): + return self._filemark + + +class SBMLObjectiveEntry(object): + """"""Flux objective defined with FBC"""""" + + def __init__(self, reader, namespace, root): + self._reader = reader + self._root = root + self._namespace = namespace + + self._id = self._root.get(_tag('id', self._namespace)) + if self._id is None: + raise ParseError('Objective has no ""id"" attribute') + + self._name = self._root.get(_tag('name', self._namespace)) + self._type = self._root.get(_tag('type', self._namespace)) + + if self._type is None: + raise ParseError( + 'Missing ""type"" attribute on objective: {}'.format(self.id)) + + # Find flux objectives + self._reactions = {} + for fo in self._root.iterfind('./{}/{}'.format( + _tag('listOfFluxObjectives', self._namespace), + _tag('fluxObjective', self._namespace))): + reaction = fo.get(_tag('reaction', self._namespace)) + coefficient = Decimal(fo.get(_tag('coefficient', self._namespace))) + if reaction is None or coefficient is None: + raise ParseError( + 'Missing attributes on flux objective: {}'.format(self.id)) + + if coefficient != 0: + self._reactions[reaction] = coefficient + + @property + def id(self): + return self._id + + @property + def name(self): + return self._name + + @property + def type(self): + return self._type + + @property + def reactions(self): + return iteritems(self._reactions) + + +class SBMLFluxBoundEntry(object): + """"""Flux bound defined with FBC V1. + + Flux bounds defined with FBC V2 are instead encoded as ``upper_flux`` and + ``lower_flux`` properties on the ReactionEntry objects. + """""" + + LESS_EQUAL = 'lessEqual' + GREATER_EQUAL = 'greaterEqual' + EQUAL = 'equal' + + def __init__(self, reader, namespace, root): + self._reader = reader + self._root = root + self._namespace = namespace + + self._id = self._root.get(_tag('id', self._namespace)) + self._name = self._root.get(_tag('name', self._namespace)) + + self._reaction = self._root.get(_tag('reaction', self._namespace)) + if self._reaction is None: + raise ParseError('Flux bound is missing ""reaction"" attribute') + + self._operation = self._root.get(_tag('operation', self._namespace)) + if self._operation is None: + raise ParseError('Flux bound is missing ""operation"" attribute') + elif self._operation not in { + self.LESS_EQUAL, self.GREATER_EQUAL, self.EQUAL}: + raise ParseError('Invalid flux bound operation: {}'.format( + self._operation)) + + value = self._root.get(_tag('value', self._namespace)) + if value is None: + raise ParseError('Flux bound is missing ""value"" attribute') + try: + self._value = Decimal(value) + except ValueError: + raise ParseError('Unable to parse flux bound value') + + @property + def id(self): + """"""Return ID of flux bound."""""" + return self._id + + @property + def name(self): + """"""Return name of flux bound."""""" + return self._name + + @property + def reaction(self): + """"""Return reaction ID that the flux bound pertains to."""""" + return self._reaction + + @property + def operation(self): + """"""Return the operation of the flux bound. + + Returns one of LESS_EQUAL, GREATER_EQUAL or EQUAL. + """""" + return self._operation + + @property + def value(self): + """"""Return the flux bound value."""""" + return self._value + + +class SBMLReader(object): + """"""Reader of SBML model files + + The constructor takes a file-like object which will be parsed as XML and + then as SBML according to the specification. If the ``strict`` parameter is + set to False, the parser will revert to a more lenient parsing which is + required for many older models. This tries to mimic the inconsistencies + employed by COBRA when parsing models. + + If ``ignore_boundary`` is ``True``, the species that are marked as + boundary conditions will simply be dropped from the species list and from + the reaction equations, and any boundary compartment will be dropped too. + Otherwise the boundary species will be retained. Retaining these is only + useful to extract specific information from those species objects. + + Args: + file: File-like object to parse XML SBML content from. + strict: Indicating whether strict parsing is enabled. + ignore_boundary: Indicating whether boundary species are dropped. + context: Optional file parsing context from + :mod:`psamm.datasource.context`. + """""" + + def __init__(self, file, strict=False, ignore_boundary=True, + context=None): + # Parse SBML file + tree = ETree.parse(file) + root = tree.getroot() + + self._strict = strict + self._ignore_boundary = ignore_boundary + self._context = context + + # Parse level and version + self._sbml_tag = None + self._level = int(root.get('level')) + self._version = int(root.get('version')) + + if self._level == 1: + self._sbml_tag = partial(_tag, namespace=SBML_NS_L1) + elif self._level == 2: + if self._version == 1: + self._sbml_tag = partial(_tag, namespace=SBML_NS_L2) + elif self._version == 2: + self._sbml_tag = partial(_tag, namespace=SBML_NS_L2_V2) + elif self._version == 3: + self._sbml_tag = partial(_tag, namespace=SBML_NS_L2_V3) + elif self._version == 4: + self._sbml_tag = partial(_tag, namespace=SBML_NS_L2_V4) + elif self._version == 5: + self._sbml_tag = partial(_tag, namespace=SBML_NS_L2_V5) + else: + if self._strict: + raise ParseError('SBML level 2, version {}' + ' not implemented'.format(self._version)) + # Assume latest version + self._version = 5 + self._sbml_tag = partial(_tag, namespace=SBML_NS_L2_V5) + elif self._level == 3: + if self._version == 1: + self._sbml_tag = partial(_tag, namespace=SBML_NS_L3_V1_CORE) + else: + if self._strict: + raise ParseError('SBML level 3, version {}' + ' not implemented'.format(self._version)) + # Assume latest version + self._version = 1 + self._sbml_tag = partial(_tag, namespace=SBML_NS_L3_V1_CORE) + else: + if self._strict: + raise ParseError('SBML level {} not implemented'.format( + self._level)) + # Assume level 1 + self._level = 1 + self._sbml_tag = partial(_tag, namespace=SBML_NS_L1) + + self._model = root.find(self._sbml_tag('model')) + + # Parameters + self._model_constants = {} + params = self._model.find(self._sbml_tag('listOfParameters')) + if params is not None: + for param in params.iterfind(self._sbml_tag('parameter')): + if param.get('constant') == 'true': + param_id = param.get('id') + value = Decimal(param.get('value')) + self._model_constants[param_id] = value + + # Flux bounds + self._flux_bounds = [] + self._reaction_flux_bounds = {} + if self._level == 3: + # Only represented with this tag in FBC V1. In FBC V2 the flux + # bounds are instead represented in the global listOfParameters + # and referenced by attributes on the reactions. Only with FBC V1 + # are FluxBoundEntry objects created. + flux_bounds = self._model.find(_tag('listOfFluxBounds', FBC_V1)) + if flux_bounds is not None: + for flux_bound in flux_bounds.iterfind( + _tag('fluxBound', FBC_V1)): + entry = SBMLFluxBoundEntry(self, FBC_V1, flux_bound) + self._flux_bounds.append(entry) + + # Create reference from reaction to flux bound + entries = self._reaction_flux_bounds.setdefault( + entry.reaction, []) + entries.append(entry) + + # Compartments + self._model_compartments = {} + self._compartments = self._model.find( + self._sbml_tag('listOfCompartments')) + for compartment in self._compartments.iterfind( + self._sbml_tag('compartment')): + filemark = FileMark( + self._context, self._get_sourceline(compartment), None) + entry = SBMLCompartmentEntry(self, compartment, filemark=filemark) + self._model_compartments[entry.id] = entry + + # Species + self._model_species = {} + self._species = self._model.find(self._sbml_tag('listOfSpecies')) + for species in self._species.iterfind(self._sbml_tag('species')): + filemark = FileMark( + self._context, self._get_sourceline(species), None) + entry = SBMLSpeciesEntry(self, species, filemark=filemark) + self._model_species[entry.id] = entry + + # Reactions + self._model_reactions = {} + self._reactions = self._model.find(self._sbml_tag('listOfReactions')) + for reaction in self._reactions.iterfind(self._sbml_tag('reaction')): + filemark = FileMark( + self._context, self._get_sourceline(reaction), None) + entry = SBMLReactionEntry(self, reaction, filemark=filemark) + self._model_reactions[entry.id] = entry + + if self._ignore_boundary: + # Remove compartments that only contain boundary compounds + empty_compartments = set(self._model_compartments) + valid_compartments = set() + for species in itervalues(self._model_species): + empty_compartments.discard(species.compartment) + if not species.boundary: + valid_compartments.add(species.compartment) + + boundary_compartments = ( + set(self._model_compartments) - empty_compartments - + valid_compartments) + for compartment in boundary_compartments: + logger.info('Ignoring boundary compartment: {}'.format( + compartment)) + del self._model_compartments[compartment] + + # Objectives + self._model_objectives = {} + self._active_objective = None + if self._level == 3: + objectives = None + for fbc_ns in (FBC_V2, FBC_V1): + objectives = self._model.find(_tag('listOfObjectives', fbc_ns)) + if objectives is not None: + break + + if objectives is not None: + for objective in objectives.iterfind( + _tag('objective', fbc_ns)): + entry = SBMLObjectiveEntry(self, fbc_ns, objective) + self._model_objectives[entry.id] = entry + + active = objectives.get(_tag('activeObjective', fbc_ns)) + if active is None or active not in self._model_objectives: + raise ParseError('Active objective is invalid: {}'.format( + active)) + + self._active_objective = self._model_objectives[active] + + def _get_sourceline(self, element): + """"""Get source line of element (only supported by lxml)."""""" + return getattr(element, 'sourceline', None) + + def get_compartment(self, compartment_id): + """"""Return :class:`.CompartmentEntry` corresponding to id."""""" + return self._model_compartments[compartment_id] + + def get_reaction(self, reaction_id): + """"""Return :class:`.SBMLReactionEntry` corresponding to reaction_id"""""" + return self._model_reactions[reaction_id] + + def get_species(self, species_id): + """"""Return :class:`.SBMLSpeciesEntry` corresponding to species_id"""""" + return self._model_species[species_id] + + def get_objective(self, objective_id): + """"""Return :class:`.SBMLObjectiveEntry` corresponding to objective_id"""""" + return self._model_objectives[objective_id] + + def get_active_objective(self): + return self._active_objective + + @property + def compartments(self): + """"""Iterator over :class:`.SBMLCompartmentEntry` entries."""""" + return itervalues(self._model_compartments) + + @property + def reactions(self): + """"""Iterator over :class:`ReactionEntries <.SBMLReactionEntry>`"""""" + return itervalues(self._model_reactions) + + @property + def species(self): + """"""Iterator over :class:`SpeciesEntries <.SpeciesEntry>` + + This will not yield boundary condition species if those are ignored. + """""" + return (c for c in itervalues(self._model_species) + if not self._ignore_boundary or not c.boundary) + + @property + def objectives(self): + """"""Iterator over :class:`.SBMLObjectiveEntry`"""""" + return itervalues(self._model_objectives) + + @property + def flux_bounds(self): + """"""Iterator over :class:`.SBMLFluxBoundEntry`"""""" + return iter(self._flux_bounds) + + @property + def id(self): + """"""Model ID"""""" + return self._model.get('id', None) + + @property + def name(self): + """"""Model name"""""" + return self._model.get('name', None) + + def create_model(self): + """"""Create model from reader. + + Returns: + :class:`psamm.datasource.native.NativeModel`. + """""" + properties = { + 'name': self.name, + 'default_flux_limit': 1000 + } + + # Load objective as biomass reaction + objective = self.get_active_objective() + if objective is not None: + reactions = dict(objective.reactions) + if len(reactions) == 1: + reaction, value = next(iteritems(reactions)) + if ((value < 0 and objective.type == 'minimize') or + (value > 0 and objective.type == 'maximize')): + properties['biomass'] = reaction + + model = NativeModel(properties) + + # Load compartments into model + for compartment in self.compartments: + model.compartments.add_entry(compartment) + + # Load compounds into model + for compound in self.species: + model.compounds.add_entry(compound) + + # Load reactions into model + for reaction in self.reactions: + model.reactions.add_entry(reaction) + + # Create model reaction set + for reaction in model.reactions: + model.model[reaction.id] = None + + # Convert reaction limits properties to proper limits + for reaction in model.reactions: + props = reaction.properties + if 'lower_flux' in props or 'upper_flux' in props: + lower = props.get('lower_flux') + upper = props.get('upper_flux') + model.limits[reaction.id] = reaction.id, lower, upper + + # Load model limits from FBC V1 bounds if present, i.e. if FBC V1 is + # used instead of V2. + limits_lower = {} + limits_upper = {} + for bounds in self.flux_bounds: + reaction = bounds.reaction + if reaction in model.limits: + continue + + if bounds.operation == SBMLFluxBoundEntry.LESS_EQUAL: + if reaction not in limits_upper: + limits_upper[reaction] = bounds.value + else: + raise ParseError( + 'Conflicting bounds for {}'.format(reaction)) + elif bounds.operation == SBMLFluxBoundEntry.GREATER_EQUAL: + if reaction not in limits_lower: + limits_lower[reaction] = bounds.value + else: + raise ParseError( + 'Conflicting bounds for {}'.format(reaction)) + elif bounds.operation == SBMLFluxBoundEntry.EQUAL: + if (reaction not in limits_lower and + reaction not in limits_upper): + limits_lower[reaction] = bounds.value + limits_upper[reaction] = bounds.value + else: + raise ParseError( + 'Conflicting bounds for {}'.format(reaction)) + + for reaction in model.reactions: + if reaction.id in limits_lower or reaction.id in limits_upper: + lower = limits_lower.get(reaction.id, None) + upper = limits_upper.get(reaction.id, None) + model.limits[reaction.id] = reaction.id, lower, upper + + return model + + +class SBMLWriter(object): + """"""Writer of SBML files."""""" + + def __init__(self, cobra_flux_bounds=False): + self._namespace = SBML_NS_L3_V1_CORE + self._sbml_tag = partial(_tag, namespace=self._namespace) + self._cobra_flux_bounds = False + + def _make_safe_id(self, id): + """"""Returns a modified id that has been made safe for SBML. + + Replaces or deletes the ones that aren't allowed. + """""" + + substitutions = { + '-': '_DASH_', + '/': '_FSLASH_', + '\\': '_BSLASH_', + '(': '_LPAREN_', + ')': '_RPAREN_', + '[': '_LSQBKT_', + ']': '_RSQBKT_', + ',': '_COMMA_', + '.': '_PERIOD_', + ""'"": '_APOS_' + } + + id = id.encode('ascii', 'backslashreplace').decode('ascii') + id = re.sub(r'\(([a-z])\)$', '_\\1', id) + for symbol, escape in iteritems(substitutions): + id = id.replace(symbol, escape) + id = re.sub(r'[^a-zA-Z0-9_]', '', id) + return id + + def _get_flux_bounds(self, r_id, model, flux_limits, equation): + """"""Read reaction's limits to set up strings for limits in the output file. + """""" + if r_id not in flux_limits or flux_limits[r_id][0] is None: + if equation.direction == Direction.Forward: + lower = 0 + else: + lower = -model.default_flux_limit + else: + lower = flux_limits[r_id][0] + + if r_id not in flux_limits or flux_limits[r_id][1] is None: + if equation.direction == Direction.Reverse: + upper = 0 + else: + upper = model.default_flux_limit + else: + upper = flux_limits[r_id][1] + + if lower % 1 == 0: + lower = int(lower) + if upper % 1 == 0: + upper = int(upper) + return text_type(lower), text_type(upper) + + def _make_safe_numerical_id(self, stri): + return stri.replace('-', 'neg').replace('.', '_') + + def _add_gene_associations(self, r_id, r_genes, gene_ids, r_tag): + """"""Adds all the different kinds of genes into a list."""""" + genes = ETree.SubElement( + r_tag, _tag('geneProductAssociation', FBC_V2)) + if isinstance(r_genes, list): + e = Expression(And(*(Variable(i) for i in r_genes))) + else: + e = Expression(r_genes) + gene_stack = [(e.root, genes)] + while len(gene_stack) > 0: + current, parent = gene_stack.pop() + if isinstance(current, Or): + gene_tag = ETree.SubElement(parent, _tag('or', FBC_V2)) + elif isinstance(current, And): + gene_tag = ETree.SubElement(parent, _tag('and', FBC_V2)) + elif isinstance(current, Variable): + gene_tag = ETree.SubElement(parent, _tag( + 'geneProductRef', FBC_V2)) + if current.symbol not in gene_ids: + id = 'g_' + util.create_unique_id( + self._make_safe_id(current.symbol), gene_ids) + gene_ids[id] = current.symbol + gene_tag.set(_tag('geneProduct', FBC_V2), id) + if isinstance(current, (Or, And)): + for item in current: + gene_stack.append((item, gene_tag)) + + def _add_fbc_objective(self, model_tag, obj_id): + """"""Adds the objective(s) to the sbml document."""""" + objective_list = ETree.SubElement(model_tag, _tag( + 'listOfObjectives', FBC_V2)) + objective_list.set(_tag('activeObjective', FBC_V2), 'O_1') + objective_tag = ETree.SubElement( + objective_list, _tag('objective', FBC_V2)) + objective_tag.set(_tag('id', FBC_V2), 'O_1') + objective_tag.set(_tag('type', FBC_V2), 'maximize') + flux_objective_list = ETree.SubElement(objective_tag, _tag( + 'listOfFluxObjectives', FBC_V2)) + flux_objective_tag = ETree.SubElement(flux_objective_list, _tag( + 'fluxObjective', FBC_V2)) + flux_objective_tag.set(_tag('reaction', FBC_V2), 'R_' + obj_id) + flux_objective_tag.set(_tag('coefficient', FBC_V2), '1') + + def _add_gene_list(self, parent_tag, gene_id_dict): + """"""Create list of all gene products as sbml readable elements."""""" + list_all_genes = ETree.SubElement(parent_tag, _tag( + 'listOfGeneProducts', FBC_V2)) + for id, label in sorted(iteritems(gene_id_dict)): + gene_tag = ETree.SubElement( + list_all_genes, _tag('geneProduct', FBC_V2)) + gene_tag.set(_tag('id', FBC_V2), id) + gene_tag.set(_tag('label', FBC_V2), label) + + def _add_properties_notes(self, parent_tag, properties): + for prop, value in sorted(iteritems(properties)): + p_tag = ETree.SubElement(parent_tag, _tag('p', XHTML_NS)) + try: + s = json.dumps(value) + except TypeError: + s = json.dumps(text_type(value)) + p_tag.text = '{}: {}'.format(prop, s) + + def _indent(self, elem, level=0): + i = ""\n"" + level*"" "" + if len(elem): + if not elem.text or not elem.text.strip(): + elem.text = i + "" "" + if not elem.tail or not elem.tail.strip(): + elem.tail = i + for elem in elem: + self._indent(elem, level+1) + if not elem.tail or not elem.tail.strip(): + elem.tail = i + else: + if level and (not elem.tail or not elem.tail.strip()): + elem.tail = i + + def write_model(self, file, model, pretty=False): + """"""Write a given model to file. + + Args: + file: File-like object open for writing. + model: Instance of :class:`NativeModel` to write. + pretty: Whether to format the XML output for readability. + """""" + ETree.register_namespace('mathml', MATHML_NS) + ETree.register_namespace('xhtml', XHTML_NS) + ETree.register_namespace('fbc', FBC_V2) + + # Load compound information + compound_name = {} + compound_properties = {} + for compound in model.compounds: + compound_name[compound.id] = ( + compound.name if compound.name is not None else compound.id) + compound_properties[compound.id] = compound.properties + + model_reactions = set(model.model) + + reaction_properties = {} + biomass_id = None + for r in model.reactions: + if (model_reactions is not None and + r.id not in model_reactions): + continue + + reaction_id = util.create_unique_id( + self._make_safe_id(r.id), reaction_properties) + if r.id == model.biomass_reaction: + biomass_id = reaction_id + + reaction_properties[reaction_id] = r.properties + + # Add exchange reactions to reaction_properties, + # also add flux limit info to flux_limits + flux_limits = {} + for compound, reaction_id, lower, upper in itervalues(model.exchange): + # Create exchange reaction + if reaction_id is None: + reaction_id = create_exchange_id(reaction_properties, compound) + reaction_id = util.create_unique_id( + self._make_safe_id(reaction_id), reaction_properties) + + reaction_properties[reaction_id] = { + 'id': reaction_id, + 'equation': Reaction(Direction.Both, {compound: -1}) + } + + if lower is None: + lower = -model.default_flux_limit + if upper is None: + upper = model.default_flux_limit + flux_limits[reaction_id] = (lower, upper) + + # Create a dummy properties dict for undefined compounds + if compound.name not in compound_properties: + compound_properties[compound.name] = { + 'id': compound.name + } + + root = ETree.Element(self._sbml_tag('sbml')) + root.set(self._sbml_tag('level'), '3') + root.set(self._sbml_tag('version'), '1') + root.set(_tag('required', FBC_V2), 'false') + if model.version_string is not None: + notes_tag = ETree.SubElement(root, self._sbml_tag('notes')) + body_tag = ETree.SubElement(notes_tag, _tag('body', XHTML_NS)) + self._add_properties_notes( + body_tag, {'model version': model.version_string}) + + model_tag = ETree.SubElement(root, self._sbml_tag('model')) + model_tag.set(_tag('strict', FBC_V2), 'true') + if model.name is not None: + model_tag.set(self._sbml_tag('name'), model.name) + + # Build mapping from Compound to species ID + model_compartments = {} + model_species = {} + species_ids = set() + for _, properties in iteritems(reaction_properties): + for compound, _ in properties['equation'].compounds: + if compound in model_species: + continue + + # Create a dummy properties dict for undefined compounds + if compound.name not in compound_properties: + compound_properties[compound.name] = { + 'id': compound.name + } + + compound_id = util.create_unique_id( + self._make_safe_id(compound.name), species_ids) + model_species[compound] = compound_id + species_ids.add(compound_id) + if compound.compartment not in model_compartments: + model_compartments[ + compound.compartment] = 'C_' + util.create_unique_id( + self._make_safe_id(compound.compartment), + model_compartments) + + # Create list of compartments + compartments = ETree.SubElement( + model_tag, self._sbml_tag('listOfCompartments')) + for _, compartment_id in iteritems(model_compartments): + compartment_tag = ETree.SubElement( + compartments, self._sbml_tag('compartment')) + compartment_tag.set(self._sbml_tag('id'), compartment_id) + compartment_tag.set(self._sbml_tag('constant'), 'true') + + # Create list of species + species_list = ETree.SubElement( + model_tag, self._sbml_tag('listOfSpecies')) + for species, species_id in sorted( + iteritems(model_species), key=lambda x: x[1]): + species_tag = ETree.SubElement(species_list, + self._sbml_tag('species')) + species_tag.set(self._sbml_tag('id'), 'M_' + species_id) + species_tag.set( + self._sbml_tag('name'), + text_type(compound_name.get(species.name, species.name))) + species_tag.set( + self._sbml_tag('compartment'), + model_compartments[species.compartment]) + species_tag.set(self._sbml_tag('constant'), 'false') + species_tag.set(self._sbml_tag('boundaryCondition'), 'false') + species_tag.set(self._sbml_tag('hasOnlySubstanceUnits'), 'true') + if 'charge' in compound_properties[species.name]: + species_tag.set(_tag('charge', FBC_V2), text_type( + compound_properties[species.name]['charge'])) + if 'formula' in compound_properties[species.name]: + species_tag.set(_tag( + 'chemicalFormula', FBC_V2), text_type( + compound_properties[species.name]['formula'])) + + notes_tag = ETree.SubElement(species_tag, self._sbml_tag('notes')) + body_tag = ETree.SubElement(notes_tag, _tag('body', XHTML_NS)) + self._add_properties_notes( + body_tag, compound_properties[species.name]) + + params_list = ETree.SubElement( + model_tag, self._sbml_tag('listOfParameters')) + + # Create mapping for reactions containing flux limit definitions + for rxn_id, lower_lim, upper_lim in itervalues(model.limits): + flux_limits[rxn_id] = lower_lim, upper_lim + + params = {} + gene_ids = {} + + if biomass_id is not None: + self._add_fbc_objective(model_tag, biomass_id) + + # Create list of reactions + reactions = ETree.SubElement( + model_tag, self._sbml_tag('listOfReactions')) + for eq_id, properties in sorted(iteritems(reaction_properties)): + reaction_tag = ETree.SubElement(reactions, + self._sbml_tag('reaction')) + equation = properties['equation'] + + reaction_tag.set(self._sbml_tag('id'), 'R_' + eq_id) + if 'name' in properties: + reaction_tag.set(self._sbml_tag('name'), properties['name']) + reaction_tag.set(self._sbml_tag('reversible'), text_type( + equation.direction == Direction.Both).lower()) + reaction_tag.set(self._sbml_tag('fast'), 'false') + lower_str, upper_str = self._get_flux_bounds( + eq_id, model, flux_limits, equation) + + params[upper_str] = 'P_'+self._make_safe_numerical_id(upper_str) + params[lower_str] = 'P_'+self._make_safe_numerical_id(lower_str) + reaction_tag.set( + _tag('upperFluxBound', FBC_V2), params[upper_str]) + reaction_tag.set( + _tag('lowerFluxBound', FBC_V2), params[lower_str]) + + if 'genes' in properties: + self._add_gene_associations( + eq_id, properties['genes'], gene_ids, reaction_tag) + + if any(value < 0 for _, value in equation.compounds): + reactants = ETree.SubElement( + reaction_tag, self._sbml_tag('listOfReactants')) + + if any(value > 0 for _, value in equation.compounds): + products = ETree.SubElement( + reaction_tag, self._sbml_tag('listOfProducts')) + + for compound, value in sorted(equation.compounds): + dest_list = reactants if value < 0 else products + spec_ref = ETree.SubElement( + dest_list, self._sbml_tag('speciesReference')) + spec_ref.set( + self._sbml_tag('species'), 'M_' + model_species[compound]) + spec_ref.set( + self._sbml_tag('constant'), 'true') + spec_ref.set( + self._sbml_tag('stoichiometry'), text_type(abs(value))) + + notes_tag = ETree.SubElement(reaction_tag, self._sbml_tag('notes')) + body_tag = ETree.SubElement(notes_tag, _tag('body', XHTML_NS)) + self._add_properties_notes(body_tag, reaction_properties[eq_id]) + + if self._cobra_flux_bounds is True: + # Create COBRA-compliant parameter list + kl_tag = ETree.SubElement( + reaction_tag, self._sbml_tag('kineticLaw')) + math_tag = ETree.SubElement(kl_tag, self._sbml_tag('math')) + ci_tag = ETree.SubElement(math_tag, _tag('ci', MATHML_NS)) + ci_tag.text = 'FLUX_VALUE' + param_list = ETree.SubElement( + kl_tag, self._sbml_tag('listOfParameters')) + + ETree.SubElement(param_list, self._sbml_tag('parameter'), { + self._sbml_tag('id'): 'LOWER_BOUND', + self._sbml_tag('name'): 'LOWER_BOUND', + self._sbml_tag('value'): lower_str, + self._sbml_tag('constant'): 'true' + }) + ETree.SubElement(param_list, self._sbml_tag('parameter'), { + self._sbml_tag('id'): 'UPPER_BOUND', + self._sbml_tag('name'): 'UPPER_BOUND', + self._sbml_tag('value'): upper_str, + self._sbml_tag('constant'): 'true' + }) + + for val, id in iteritems(params): + param_tag = ETree.SubElement( + params_list, self._sbml_tag('parameter')) + param_tag.set(self._sbml_tag('id'), id) + param_tag.set(self._sbml_tag('value'), val) + param_tag.set(self._sbml_tag('constant'), 'true') + + self._add_gene_list(model_tag, gene_ids) + + tree = ETree.ElementTree(root) + if pretty: + self._indent(root) + + write_options = dict( + encoding='ascii', + default_namespace=self._namespace, + xml_declaration=True + ) + if PY3: + write_options['encoding'] = 'unicode' + + tree.write(file, **write_options) + + +def convert_sbml_model(model): + """"""Convert raw SBML model to extended model. + + Args: + model: :class:`NativeModel` obtained from :class:`SBMLReader`. + """""" + biomass_reactions = set() + for reaction in model.reactions: + # Extract limits + if reaction.id not in model.limits: + lower, upper = parse_flux_bounds(reaction) + if lower is not None or upper is not None: + model.limits[reaction.id] = reaction.id, lower, upper + + # Detect objective + objective = parse_objective_coefficient(reaction) + if objective is not None and objective != 0: + biomass_reactions.add(reaction.id) + + if len(biomass_reactions) == 1: + model.biomass_reaction = next(iter(biomass_reactions)) + + # Convert model to mutable entries + convert_model_entries(model) + + # Detect extracelluar compartment + if model.extracellular_compartment is None: + extracellular = detect_extracellular_compartment(model) + model.extracellular_compartment = extracellular + + # Convert exchange reactions to exchange compounds + convert_exchange_to_compounds(model) + + +def entry_id_from_cobra_encoding(cobra_id): + """"""Convert COBRA-encoded ID string to decoded ID string."""""" + for escape, symbol in iteritems(_COBRA_DECODE_ESCAPES): + cobra_id = cobra_id.replace(escape, symbol) + return cobra_id + + +def create_convert_sbml_id_function( + compartment_prefix='C_', reaction_prefix='R_', + compound_prefix='M_', decode_id=entry_id_from_cobra_encoding): + """"""Create function for converting SBML IDs. + + The returned function will strip prefixes, decode the ID using the provided + function. These prefixes are common on IDs in SBML models because the IDs + live in a global namespace. + """""" + def convert_sbml_id(entry): + if isinstance(entry, BaseCompartmentEntry): + prefix = compartment_prefix + elif isinstance(entry, BaseReactionEntry): + prefix = reaction_prefix + elif isinstance(entry, BaseCompoundEntry): + prefix = compound_prefix + + new_id = entry.id + if decode_id is not None: + new_id = decode_id(new_id) + if prefix is not None and new_id.startswith(prefix): + new_id = new_id[len(prefix):] + + return new_id + + return convert_sbml_id + + +def translate_sbml_compartment(entry, new_id): + """"""Translate SBML compartment entry."""""" + return DictCompartmentEntry(entry, id=new_id) + + +def translate_sbml_reaction(entry, new_id, compartment_map, compound_map): + """"""Translate SBML reaction entry."""""" + new_entry = DictReactionEntry(entry, id=new_id) + + # Convert compound IDs in reaction equation + if new_entry.equation is not None: + compounds = [] + for compound, value in new_entry.equation.compounds: + # Translate compartment to new ID, if available. + compartment = compartment_map.get( + compound.compartment, compound.compartment) + new_compound = compound.translate( + lambda name: compound_map.get(name, name)).in_compartment( + compartment) + compounds.append((new_compound, value)) + + new_entry.equation = Reaction( + new_entry.equation.direction, compounds) + + # Get XHTML notes properties + for key, value in iteritems(parse_xhtml_reaction_notes(entry)): + if key not in new_entry.properties: + new_entry.properties[key] = value + + return new_entry + + +def translate_sbml_compound(entry, new_id, compartment_map): + """"""Translate SBML compound entry."""""" + new_entry = DictCompoundEntry(entry, id=new_id) + + if 'compartment' in new_entry.properties: + old_compartment = new_entry.properties['compartment'] + new_entry.properties['compartment'] = compartment_map.get( + old_compartment, old_compartment) + + # Get XHTML notes properties + for key, value in iteritems(parse_xhtml_species_notes(entry)): + if key not in new_entry.properties: + new_entry.properties[key] = value + + return new_entry + + +def convert_model_entries( + model, convert_id=create_convert_sbml_id_function(), + create_unique_id=None, + translate_compartment=translate_sbml_compartment, + translate_reaction=translate_sbml_reaction, + translate_compound=translate_sbml_compound): + """"""Convert and decode model entries. + + Model entries are converted to new entries using the translate functions + and IDs are converted using the given coversion function. If ID conversion + would create a clash of IDs, the ``create_unique_id`` function is called + with a container of current IDs and the base ID to generate a unique ID + from. The translation functions take an existing entry and the new ID. + + All references within the model are updated to use new IDs: compartment + boundaries, limits, exchange, model, biomass reaction, etc. + + Args: + model: :class:`NativeModel`. + """""" + def find_new_ids(entries): + """"""Create new IDs for entries."""""" + id_map = {} + new_ids = set() + for entry in entries: + new_id = convert_id(entry) + if new_id in new_ids: + if create_unique_id is not None: + new_id = create_unique_id(new_ids, new_id) + else: + raise ValueError( + 'Entity ID {!r} is not unique after conversion'.format( + entry.id)) + + id_map[entry.id] = new_id + new_ids.add(new_id) + + return id_map + + # Find new IDs for all entries + compartment_map = find_new_ids(model.compartments) + compound_map = find_new_ids(model.compounds) + reaction_map = find_new_ids(model.reactions) + + # Create new compartment entries + new_compartments = [] + for compartment in model.compartments: + new_id = compartment_map[compartment.id] + new_compartments.append(translate_compartment(compartment, new_id)) + + # Create new compound entries + new_compounds = [] + for compound in model.compounds: + new_id = compound_map[compound.id] + new_compounds.append( + translate_compound(compound, new_id, compartment_map)) + + # Create new reaction entries + new_reactions = [] + for reaction in model.reactions: + new_id = reaction_map[reaction.id] + new_entry = translate_reaction( + reaction, new_id, compartment_map, compound_map) + new_reactions.append(new_entry) + + # Update entries + model.compartments.clear() + model.compartments.update(new_compartments) + + model.compounds.clear() + model.compounds.update(new_compounds) + + model.reactions.clear() + model.reactions.update(new_reactions) + + # Convert compartment boundaries + new_boundaries = [] + for boundary in model.compartment_boundaries: + c1, c2 = (compartment_map.get(c, c) for c in boundary) + new_boundaries.append(tuple(sorted(c1, c2))) + + model.compartment_boundaries.clear() + model.compartment_boundaries.update(new_boundaries) + + # Convert limits + new_limits = [] + for reaction, lower, upper in itervalues(model.limits): + new_reaction_id = reaction_map.get(reaction, reaction) + new_limits.append((new_reaction_id, lower, upper)) + + model.limits.clear() + model.limits.update((limit[0], limit) for limit in new_limits) + + # Convert exchange + new_exchanges = [] + for compound, reaction, lower, upper in itervalues(model.exchange): + new_compound_id = compound.translated( + lambda name: compound_map.get(name, name)) + new_reaction_id = reaction_map.get(reaction, reaction) + new_exchanges.append((new_compound_id, new_reaction_id, lower, upper)) + + model.exchange.clear() + model.exchange.update((ex[0], ex) for ex in new_exchanges) + + # Convert model + new_model = [] + for reaction in model.model: + new_id = reaction_map.get(reaction, reaction) + new_model.append(new_id) + + model.model.clear() + model.model.update((new_id, None) for new_id in new_model) + + # Convert other properties + if model.biomass_reaction is not None: + old_id = model.biomass_reaction + model.biomass_reaction = reaction_map.get(old_id, old_id) + + if model.extracellular_compartment is not None: + old_id = model.extracellular_compartment + model.extracellular_compartment = compartment_map.get(old_id, old_id) + + if model.default_compartment is not None: + old_id = model.default_compartment + model.default_compartment = compartment_map.get(old_id, old_id) + + +def parse_xhtml_notes(entry): + """"""Yield key, value pairs parsed from the XHTML notes section. + + Each key, value pair must be defined in its own text block, e.g. + ``

key: value

key2: value2

``. The key and value must be + separated by a colon. Whitespace is stripped from both key and value, and + quotes are removed from values if present. The key is normalized by + conversion to lower case and spaces replaced with underscores. + + Args: + entry: :class:`_SBMLEntry`. + """""" + for note in entry.xml_notes.itertext(): + m = re.match(r'^([^:]+):(.+)$', note) + if m: + key, value = m.groups() + key = key.strip().lower().replace(' ', '_') + value = value.strip() + m = re.match(r'^""(.*)""$', value) + if m: + value = m.group(1) + if value != '': + yield key, value + + +def parse_xhtml_species_notes(entry): + """"""Return species properties defined in the XHTML notes. + + Older SBML models often define additional properties in the XHTML notes + section because structured methods for defining properties had not been + developed. This will try to parse the following properties: ``PUBCHEM ID``, + ``CHEBI ID``, ``FORMULA``, ``KEGG ID``, ``CHARGE``. + + Args: + entry: :class:`SBMLSpeciesEntry`. + """""" + properties = {} + if entry.xml_notes is not None: + cobra_notes = dict(parse_xhtml_notes(entry)) + + for key in ('pubchem_id', 'chebi_id'): + if key in cobra_notes: + properties[key] = cobra_notes[key] + + if 'formula' in cobra_notes: + properties['formula'] = cobra_notes['formula'] + + if 'kegg_id' in cobra_notes: + properties['kegg'] = cobra_notes['kegg_id'] + + if 'charge' in cobra_notes: + try: + value = int(cobra_notes['charge']) + except ValueError: + logger.warning( + 'Unable to parse charge for {} as an' + ' integer: {}'.format( + entry.id, cobra_notes['charge'])) + value = cobra_notes['charge'] + properties['charge'] = value + + return properties + + +def parse_xhtml_reaction_notes(entry): + """"""Return reaction properties defined in the XHTML notes. + + Older SBML models often define additional properties in the XHTML notes + section because structured methods for defining properties had not been + developed. This will try to parse the following properties: ``SUBSYSTEM``, + ``GENE ASSOCIATION``, ``EC NUMBER``, ``AUTHORS``, ``CONFIDENCE``. + + Args: + entry: :class:`SBMLReactionEntry`. + """""" + properties = {} + if entry.xml_notes is not None: + cobra_notes = dict(parse_xhtml_notes(entry)) + + if 'subsystem' in cobra_notes: + properties['subsystem'] = cobra_notes['subsystem'] + + if 'gene_association' in cobra_notes: + properties['genes'] = cobra_notes['gene_association'] + + if 'ec_number' in cobra_notes: + properties['ec'] = cobra_notes['ec_number'] + + if 'authors' in cobra_notes: + properties['authors'] = [ + a.strip() for a in cobra_notes['authors'].split(';')] + + if 'confidence' in cobra_notes: + try: + value = int(cobra_notes['confidence']) + except ValueError: + logger.warning( + 'Unable to parse confidence level for {} as an' + ' integer: {}'.format( + entry.id, cobra_notes['confidence'])) + value = cobra_notes['confidence'] + properties['confidence'] = value + + return properties + + +def parse_objective_coefficient(entry): + """"""Return objective value for reaction entry. + + Detect objectives that are specified using the non-standardized + kinetic law parameters which are used by many pre-FBC SBML models. The + objective coefficient is returned for the given reaction, or None if + undefined. + + Args: + entry: :class:`SBMLReactionEntry`. + """""" + for parameter in entry.kinetic_law_reaction_parameters: + pid, name, value, units = parameter + if (pid == 'OBJECTIVE_COEFFICIENT' or + name == 'OBJECTIVE_COEFFICIENT'): + return value + + return None + + +def parse_flux_bounds(entry): + """"""Return flux bounds for reaction entry. + + Detect flux bounds that are specified using the non-standardized + kinetic law parameters which are used by many pre-FBC SBML models. The + flux bounds are returned as a pair of lower, upper bounds. The returned + bound is None if undefined. + + Args: + entry: :class:`SBMLReactionEntry`. + """""" + lower_bound = None + upper_bound = None + for parameter in entry.kinetic_law_reaction_parameters: + pid, name, value, units = parameter + if pid == 'UPPER_BOUND' or name == 'UPPER_BOUND': + upper_bound = value + elif pid == 'LOWER_BOUND' or name == 'LOWER_BOUND': + lower_bound = value + + return lower_bound, upper_bound + + +def detect_extracellular_compartment(model): + """"""Detect the identifier for equations with extracellular compartments. + + Args: + model: :class:`NativeModel`. + """""" + extracellular_key = Counter() + + for reaction in model.reactions: + equation = reaction.equation + if equation is None: + continue + + if len(equation.compounds) == 1: + compound, _ = equation.compounds[0] + compartment = compound.compartment + extracellular_key[compartment] += 1 + if len(extracellular_key) == 0: + return None + else: + best_key, _ = extracellular_key.most_common(1)[0] + + logger.info('{} is extracellular compartment'.format(best_key)) + + return best_key + + +def convert_exchange_to_compounds(model): + """"""Convert exchange reactions in model to exchange compounds. + + Only exchange reactions in the extracellular compartment are converted. + The extracelluar compartment must be defined for the model. + + Args: + model: :class:`NativeModel`. + """""" + # Build set of exchange reactions + exchanges = set() + for reaction in model.reactions: + equation = reaction.properties.get('equation') + if equation is None: + continue + + if len(equation.compounds) != 1: + # Provide warning for exchange reactions with more than + # one compound, they won't be put into the exchange definition + if (len(equation.left) == 0) != (len(equation.right) == 0): + logger.warning('Exchange reaction {} has more than one' + ' compound, it was not converted to' + ' exchange compound'.format(reaction.id)) + continue + + exchanges.add(reaction.id) + + # Convert exchange reactions into exchange compounds + for reaction_id in exchanges: + equation = model.reactions[reaction_id].equation + compound, value = equation.compounds[0] + if compound.compartment != model.extracellular_compartment: + continue + + if compound in model.exchange: + logger.warning( + 'Compound {} is already defined in the exchange' + ' definition'.format(compound)) + continue + + # We multiply the flux bounds by value in order to create equivalent + # exchange reactions with stoichiometric value of one. If the flux + # bounds are not set but the reaction is unidirectional, the implicit + # flux bounds must be used. + lower_flux, upper_flux = None, None + if reaction_id in model.limits: + _, lower, upper = model.limits[reaction_id] + if lower is not None: + lower_flux = lower * abs(value) + if upper is not None: + upper_flux = upper * abs(value) + + if lower_flux is None and equation.direction == Direction.Forward: + lower_flux = 0 + if upper_flux is None and equation.direction == Direction.Reverse: + upper_flux = 0 + + # If the stoichiometric value of the reaction is reversed, the flux + # limits must be flipped. + if value > 0: + lower_flux, upper_flux = ( + -upper_flux if upper_flux is not None else None, + -lower_flux if lower_flux is not None else None) + + model.exchange[compound] = ( + compound, reaction_id, lower_flux, upper_flux) + + model.reactions.discard(reaction_id) + model.limits.pop(reaction_id, None) + + +def merge_equivalent_compounds(model): + """"""Merge equivalent compounds in various compartments. + + Tries to detect and merge compound entries that represent the same + compound in different compartments. The entries are only merged if all + properties are equivalent. Compound entries must have an ID with a suffix + of an underscore followed by the compartment ID. This suffix will be + stripped and compounds with identical IDs are merged if the properties + are identical. + + Args: + model: :class:`NativeModel`. + """""" + def dicts_are_compatible(d1, d2): + return all(key not in d1 or key not in d2 or d1[key] == d2[key] + for key in set(d1) | set(d2)) + + compound_compartment = {} + inelegible = set() + for reaction in model.reactions: + equation = reaction.equation + if equation is None: + continue + + for compound, _ in equation.compounds: + compartment = compound.compartment + if compartment is not None: + compound_compartment[compound.name] = compartment + if not compound.name.endswith('_{}'.format(compartment)): + inelegible.add(compound.name) + + compound_groups = {} + for compound_id, compartment in iteritems(compound_compartment): + if compound_id in inelegible: + continue + + suffix = '_{}'.format(compound_compartment[compound_id]) + if compound_id.endswith(suffix): + group_name = compound_id[:-len(suffix)] + compound_groups.setdefault(group_name, set()).add(compound_id) + + compound_mapping = {} + merged_compounds = {} + for group, compound_set in iteritems(compound_groups): + # Try to merge as many compounds as possible + merged = [] + for compound_id in compound_set: + props = dict(model.compounds[compound_id].properties) + + # Ignore differences in ID and compartment properties + props.pop('id', None) + props.pop('compartment', None) + + for merged_props, merged_set in merged: + if dicts_are_compatible(props, merged_props): + merged_set.add(compound_id) + merged_props.update(props) + break + else: + keys = set(key for key in set(props) | set(merged_props) + if key not in props or + key not in merged_props or + props[key] != merged_props[key]) + logger.info( + 'Unable to merge {} into {}, difference in' + ' keys: {}'.format( + compound_id, ', '.join(merged_set), + ', '.join(keys))) + else: + merged.append((props, {compound_id})) + + if len(merged) == 1: + # Merge into one set with the group name + merged_props, merged_set = merged[0] + + for compound_id in merged_set: + compound_mapping[compound_id] = group + merged_compounds[group] = merged_props + else: + # Since we cannot merge all compounds, create new group names + # based on the group and compartments. + for merged_props, merged_set in merged: + compartments = set(compound_compartment[c] for c in merged_set) + merged_name = '{}_{}'.format( + group, '_'.join(sorted(compartments))) + + for compound_id in merged_set: + compound_mapping[compound_id] = merged_name + merged_compounds[merged_name] = merged_props + + # Translate reaction compounds + for reaction in model.reactions: + equation = reaction.equation + if equation is None: + continue + + reaction.equation = equation.translated_compounds( + lambda c: compound_mapping.get(c, c)) + + # Translate compound entries + new_compounds = [] + for compound in model.compounds: + if compound.id not in compound_mapping: + new_compounds.append(compound) + else: + group = compound_mapping[compound.id] + if group not in merged_compounds: + continue + props = merged_compounds.pop(group) + props['id'] = group + new_compounds.append(DictCompoundEntry( + props, filemark=compound.filemark)) + + model.compounds.clear() + model.compounds.update(new_compounds) + + # Translate exchange + new_exchange = OrderedDict() + for compound, reaction_id, lower, upper in itervalues(model.exchange): + new_compound = compound.translate( + lambda name: compound_mapping.get(name, name)) + new_exchange[new_compound] = new_compound, reaction_id, lower, upper + + model.exchange.clear() + model.exchange.update(new_exchange) +","Python" +"Metabolic","zhanglab/psamm","psamm/datasource/reaction.py",".py","9503","274","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2020 Elysha Sameth + +""""""Reaction parser."""""" +from __future__ import unicode_literals + +import re +from decimal import Decimal +import enum + +from six import raise_from, PY3 + +from psamm.reaction import Reaction, Compound, Direction +from psamm.expression import affine + +if PY3: + unicode = str + + +def convert_to_unicode(str_, encoding='UTF-8'): + if PY3 or bool(re.search(r'\\u', str_)): + try: + return str_.encode('latin-1').decode('unicode-escape') + except: + return str_ + else: + if isinstance(str_, unicode): + return str_ + return str_.decode(encoding) + + +class ParseError(Exception): + """"""Error raised when parsing reaction fails."""""" + + def __init__(self, *args, **kwargs): + self._span = kwargs.pop('span', None) + super(ParseError, self).__init__(*args, **kwargs) + + @property + def indicator(self): + if self._span is None: + return None + pre = ' ' * self._span[0] + ind = '^' * max(1, self._span[1] - self._span[0]) + return pre + ind + + +@enum.unique +class _ReactionToken(enum.Enum): + Space = 0 + Quoted = 1 + Group = 2 + Plus = 3 + Arrow = 4 + Other = 5 + End = 6 + + +class ReactionParser(object): + """"""Parser of reactions equations. + + This parser recognizes: + + * Global compartment specification as a prefix (when ``parse_global`` is + ``True``) + + * Configurable reaction arrow tokens (``arrows``) + + * Compounds quoted by pipe (``|``) (required only if the compound name + includes a space) + + * Compound counts that are affine expressions. + """""" + + def __init__(self, arrows=None, parse_global=False): + if arrows is None: + arrows = ( + ('<=>', Direction.Both), + ('=>', Direction.Forward), + ('<=', Direction.Reverse) + ) + + arrow_p = '|'.join(re.escape(arrow) for arrow, _ in arrows) + self._arrows = dict(arrows) + self._tokens = ( + (r'\s+', _ReactionToken.Space), + (r'\|[^|]+\|', _ReactionToken.Quoted), + (r'\([^)]+\)(?=\Z|\s|\|)', _ReactionToken.Group), + (r'\+(?=\s)', _ReactionToken.Plus), + (arrow_p + r'(?=\Z|\s)', _ReactionToken.Arrow), + (r'\S+', _ReactionToken.Other), + (r'\Z', _ReactionToken.End), + (r'.', None) + ) + + self._scanner = re.compile( + '|'.join('(' + pattern + ')' for pattern, _ in self._tokens), + re.DOTALL | re.UNICODE) + + self._parse_global = parse_global + + def parse(self, s): + """"""Parse reaction string."""""" + global_comp = None + if self._parse_global: + # Split by colon for global compartment information + m = re.match(r'^\s*\[(\w+)\]\s*:\s*(.*)', s) + if m is not None: + global_comp = m.group(1) + s = m.group(2) + expect_operator = False + direction = None + left = [] + right = [] + current_side = left + saved_token = None + + def tokenize(): + for match in re.finditer(self._scanner, s): + for i, group in enumerate(match.groups()): + if group is not None: + token = self._tokens[i][1] + span = match.start(), match.end() + if token is None: + raise ParseError( + 'Invalid token in expression string:' + ' {!r}'.format(group), span=span) + yield self._tokens[i][1], group, span + break + + for token, value, span in tokenize(): + # Handle partially parsed compound. + if saved_token is not None and ( + token in (_ReactionToken.Plus, + _ReactionToken.Arrow, + _ReactionToken.End)): + compound = parse_compound(saved_token, global_comp) + current_side.append((compound, 1)) + expect_operator = True + saved_token = None + + if token == _ReactionToken.Plus: + # Compound separator. Expect compound name or compound count + # next. + if not expect_operator: + raise ParseError('Unexpected token: {!r}'.format(value), + span=span) + expect_operator = False + elif token == _ReactionToken.Arrow: + # Reaction arrow. Expect compound name or compound count next. + if direction is not None: + raise ParseError( + 'More than one equation arrow: {!r}'.format(value), + span=span) + + if not expect_operator and len(left) > 0: + raise ParseError('Unexpected token: {!r}'.format(value), + span=span) + + expect_operator = False + direction = self._arrows[value] + current_side = right + elif token == _ReactionToken.Group: + # Compound count. Expect compound name next. + if expect_operator: + raise ParseError('Expected plus or arrow: {!r}'.format( + value), span=span) + if saved_token is not None: + raise ParseError('Expected compound name: {!r}'.format( + value), span=span) + saved_token = value + elif token == _ReactionToken.Quoted: + # Compound name. Expect operator next. + if expect_operator: + raise ParseError('Expected plus or arrow: {!r}'.format( + value), span=span) + if saved_token is not None: + try: + count = parse_compound_count(saved_token) + except ValueError as e: + raise_from(ParseError( + 'Unable to parse compound count: {!r}'.format( + saved_token), + span=span), e) + else: + count = 1 + compound = parse_compound(value, global_comp) + current_side.append((compound, count)) + expect_operator = True + saved_token = None + elif token == _ReactionToken.Other: + # Could be count or compound name. Store and expect other, + # quoted, operator or end. + if expect_operator: + raise ParseError('Expected plus or arrow: {!r}'.format( + value), span=span) + if saved_token is not None: + try: + count = parse_compound_count(saved_token) + except ValueError as e: + raise_from(ParseError( + 'Unable to parse compound count: {!r}'.format( + saved_token), + span=span), e) + compound = parse_compound(value, global_comp) + current_side.append((compound, count)) + expect_operator = True + saved_token = None + else: + saved_token = value + + if direction is None: + raise ParseError('Missing equation arrow') + return Reaction(direction, left, right) + + +_DEFAULT_PARSER = ReactionParser() + + +def parse_reaction(s): + """"""Parse reaction string using the default parser."""""" + return _DEFAULT_PARSER.parse(s) + + +def parse_compound(s, global_compartment=None): + """"""Parse a compound specification. + + If no compartment is specified in the string, the global compartment + will be used. + """""" + m = re.match(r'^\|(.*)\|$', s) + if m: + s = m.group(1) + + m = re.match(r'^(.+)\[(\S+)\]$', s) + if m: + compound_id = convert_to_unicode(m.group(1)) + compartment = m.group(2) + else: + compound_id = convert_to_unicode(s) + compartment = global_compartment + return Compound(compound_id, compartment=compartment) + + +def parse_compound_count(s): + """"""Parse a compound count (number of compounds)."""""" + m = re.match(r'^\((.*)\)$', s) + if m: + s = convert_to_unicode(m.group(1)) + + for count_type in (int, Decimal, affine.Expression): + try: + return count_type(s) + except: + pass + + raise ValueError('Unable to parse compound count: {}'.format(s)) +","Python" +"Metabolic","zhanglab/psamm","psamm/datasource/kegg.py",".py","10873","367","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2016 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +""""""Module related to loading KEGG database files."""""" + +import re +from types import FunctionType +from collections import Mapping + +from .context import FileMark +from .entry import (CompoundEntry as BaseCompoundEntry, + ReactionEntry as BaseReactionEntry) +from ..reaction import Reaction, Compound, Direction +from ..expression.affine import Expression +from ..util import DictView + +from six import iteritems, add_metaclass + + +class ParseError(Exception): + """"""Exception used to signal errors while parsing"""""" + + +class KEGGEntry(object): + """"""Base class for KEGG entry with raw values from KEGG."""""" + + def __init__(self, properties, filemark=None): + self._properties = DictView(dict(properties)) + self._filemark = filemark + + @property + def properties(self): + return self._properties + + @property + def filemark(self): + return self._filemark + + +class _MappedEntry(object): + """"""Base class for KEGG entry with values mapped to standard keys."""""" + + def __init__(self, mapper, entry): + self._entry = entry + self._properties = mapper(self._entry) + + @property + def id(self): + return self._properties['id'] + + @property + def properties(self): + return self._properties + + @property + def raw_entry(self): + return self._entry + + @property + def filemark(self): + return self._entry.filemark + + +class CompoundEntry(_MappedEntry, BaseCompoundEntry): + """"""KEGG entry with mapped compound properties."""""" + def __init__(self, entry): + super(CompoundEntry, self).__init__(CompoundMapper, entry) + + +class ReactionEntry(_MappedEntry, BaseReactionEntry): + """"""KEGG entry with mapped reaction properties."""""" + def __init__(self, entry): + super(ReactionEntry, self).__init__(ReactionMapper, entry) + + +class _MapperMeta(Mapping.__class__): + """"""Metaclass for mapper that turns methods into cached keys."""""" + def __new__(cls, name, bases, namespace): + property_accessors = {} + new_namespace = {} + for attr_name, attr in iteritems(namespace): + if (isinstance(attr, FunctionType) and + not attr_name.startswith('_')): + property_accessors[attr_name] = attr + else: + new_namespace[attr_name] = attr + + def getitem_props(self, key): + if key in property_accessors: + if key not in self._cache: + self._cache[key] = property_accessors[key]( + self, self._entry.properties) + return self._cache[key] + raise KeyError('key not found: {!r}'.format(key)) + + def iter_props(self): + return iter(property_accessors) + + def len_props(self): + return len(property_accessors) + + new_namespace['__getitem__'] = getitem_props + new_namespace['__iter__'] = iter_props + new_namespace['__len__'] = len_props + + return super(_MapperMeta, cls).__new__( + cls, name, bases, new_namespace) + + def __call__(self, entry, *args, **kwargs): + inst = super(_MapperMeta, self).__call__(*args, **kwargs) + inst._entry = entry + inst._cache = {} + return inst + + +@add_metaclass(_MapperMeta) +class CompoundMapper(Mapping): + """"""Mapper for raw KEGG compound properties to standard properties. + + Public methods are automatically translated into cached properties by the + metaclass. + """""" + def id(self, raw): + return raw['entry'][0].split(None, 1)[0] + + def name(self, raw): + try: + return next(self._iter_names(raw)) + except StopIteration: + return None + + def names(self, raw): + return list(self._iter_names(raw)) + + def reactions(self, raw): + return list(self._iter_reactions(raw)) + + def enzymes(self, raw): + return list(self._iter_enzymes(raw)) + + def formula(self, raw): + if 'formula' in raw: + return raw['formula'][0] + return None + + def exact_mass(self, raw): + if 'exact_mass' in raw: + return float(raw['exact_mass'][0]) + return None + + def mol_weight(self, raw): + if 'mol_weight' in raw: + return float(raw['mol_weight'][0]) + return None + + def pathways(self, raw): + return list(self._iter_pathways(raw)) + + def dblinks(self, raw): + return list(self._iter_dblinks(raw)) + + def comment(self, raw): + if 'comment' in raw: + return '\n'.join(raw['comment']) + return None + + def _iter_names(self, raw): + if 'name' in raw: + for line in raw['name']: + for name in line.rstrip(';').split(';'): + yield name.strip() + + def _iter_reactions(self, raw): + if 'reaction' in raw: + for line in raw['reaction']: + for rxnid in line.split(): + yield rxnid + + def _iter_enzymes(self, raw): + if 'enzyme' in raw: + for line in raw['enzyme']: + for enzyme in line.split(): + yield enzyme + + def _iter_pathways(self, raw): + if 'pathway' in raw: + for line in raw['pathway']: + pathway, name = line.split(None, 1) + yield pathway, name + + def _iter_dblinks(self, raw): + if 'dblinks' in raw: + for line in raw['dblinks']: + database, entry = line.split(':', 1) + yield database.strip(), entry.strip() + + +@add_metaclass(_MapperMeta) +class ReactionMapper(Mapping): + """"""Mapper for raw KEGG reaction properties to standard properties. + + Methods are automatically translated into cached properties by the + metaclass. + """""" + def id(self, raw): + return raw['entry'][0].split(None, 1)[0] + + def name(self, raw): + try: + return next(self._iter_names(raw)) + except StopIteration: + return None + + def names(self, raw): + return list(self._iter_names(raw)) + + def definition(self, raw): + if 'definition' in raw: + return raw['definition'][0] + return None + + def equation(self, raw): + if 'equation' in raw: + return parse_reaction(raw['equation'][0]) + return None + + def enzymes(self, raw): + return list(self._iter_enzymes(raw)) + + def pathways(self, raw): + return list(self._iter_pathways(raw)) + + def comment(self, raw): + if 'comment' in raw: + return '\n'.join(raw['comment']) + return None + + def rpairs(self, raw): + return list(self._iter_rpairs(raw)) + + def _iter_names(self, raw): + if 'name' in raw: + for line in raw['name']: + for name in line.rstrip(';').split(';'): + yield name.strip() + + def _iter_enzymes(self, raw): + if 'enzyme' in raw: + for line in raw['enzyme']: + for enzyme in line.split(): + yield enzyme + + def _iter_pathways(self, raw): + if 'pathway' in raw: + for line in raw['pathway']: + pathway, name = line.split(None, 1) + yield pathway, name + + def _iter_rpairs(self, raw): + if 'rpair' in raw: + for line in raw['rpair']: + pair, compounds, rp_type = line.split(None, 2) + compounds = tuple(compounds.split('_', 1)) + yield pair, compounds, rp_type + + +def parse_kegg_entries(f, context=None): + """"""Iterate over entries in KEGG file."""""" + + section_id = None + entry_line = None + properties = {} + for lineno, line in enumerate(f): + if line.strip() == '///': + # End of entry + mark = FileMark(context, entry_line, 0) + yield KEGGEntry(properties, filemark=mark) + properties = {} + section_id = None + entry_line = None + else: + if entry_line is None: + entry_line = lineno + + # Look for beginning of section + m = re.match(r'([A-Z_]+)\s+(.*)', line.rstrip()) + if m is not None: + section_id = m.group(1).lower() + properties[section_id] = [m.group(2)] + elif section_id is not None: + properties[section_id].append(line.strip()) + else: + raise ParseError( + 'Missing section identifier at line {}'.format(lineno)) + + +def parse_compound_file(f, context=None): + """"""Iterate over the compound entries in the given file."""""" + for entry in parse_kegg_entries(f, context): + yield CompoundEntry(entry) + + +def parse_reaction_file(f, context=None): + """"""Iterate over the reaction entries in the given file."""""" + for entry in parse_kegg_entries(f, context): + yield ReactionEntry(entry) + + +def parse_reaction(s): + """"""Parse a KEGG reaction string"""""" + + def parse_count(s): + m = re.match(r'^\((.+)\)$', s) + if m is not None: + s = m.group(1) + + m = re.match(r'^\d+$', s) + if m is not None: + return int(m.group(0)) + + return Expression(s) + + def parse_compound(s): + m = re.match(r'(.+)\((.+)\)', s) + if m is not None: + return Compound(m.group(1), arguments=[Expression(m.group(2))]) + return Compound(s) + + def parse_compound_list(s): + for cpd in s.split(' + '): + if cpd == '': + continue + + fields = cpd.strip().split(' ') + if len(fields) > 2: + raise ParseError( + 'Malformed compound specification: {}'.format(cpd)) + if len(fields) == 1: + count = 1 + compound = parse_compound(fields[0]) + else: + count = parse_count(fields[0]) + compound = parse_compound(fields[1]) + + yield compound, count + + cpd_left, cpd_right = s.split('<=>') + left = parse_compound_list(cpd_left.strip()) + right = parse_compound_list(cpd_right.strip()) + + return Reaction(Direction.Both, left, right) +","Python" +"Metabolic","zhanglab/psamm","psamm/datasource/native.py",".py","55674","1578","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2020 Elysha Sameth + +""""""Module for reading and writing native formats. + +These formats are either table-based or YAML-based. Table-based formats +are space-separated and empty lines are ignored. Comments starting with +pound (#). YAML-based formats are structured data following the YAML +specification. +"""""" + +from __future__ import absolute_import, unicode_literals + +import os +import logging +import re +import csv +import math +from collections import OrderedDict + +import yaml +from six import string_types, text_type, iteritems, itervalues, PY3 +from decimal import Decimal + +from ..reaction import Reaction, Compound, Direction +from ..expression import boolean +from ..formula import Formula +from ..metabolicmodel import MetabolicModel +from ..database import DictDatabase +from .context import FilePathContext, FileMark +from .entry import (DictCompoundEntry as CompoundEntry, + DictReactionEntry as ReactionEntry, + DictCompartmentEntry as CompartmentEntry) +from .reaction import ReactionParser, convert_to_unicode +from . import modelseed +from .. import util + +# Module-level logging +logger = logging.getLogger(__name__) + +_HAS_YAML_LIBRARY = None + +_REACTION_PARSER = ReactionParser() + + +class ParseError(Exception): + """"""Exception used to signal errors while parsing"""""" + + +def float_constructor(loader, node): + """"""Construct Decimal from YAML float encoding."""""" + s = loader.construct_scalar(node) + if s == '.inf': + return Decimal('Infinity') + elif s == '-.inf': + return -Decimal('Infinity') + elif s == '.nan': + return Decimal('NaN') + return Decimal(s) + + +def yaml_load(stream): + """"""Load YAML file using safe loader."""""" + # Surprisingly, the CSafeLoader does not seem to be used by default. + # Check whether the CSafeLoader is available and provide a log message + # if it is not available. + global _HAS_YAML_LIBRARY + + if _HAS_YAML_LIBRARY is None: + _HAS_YAML_LIBRARY = hasattr(yaml, 'CSafeLoader') + if not _HAS_YAML_LIBRARY: + logger.warning('libyaml was not found! Please install libyaml to' + ' speed up loading the model files.') + + if _HAS_YAML_LIBRARY: + loader = yaml.CSafeLoader(stream) + else: + loader = yaml.SafeLoader(stream) + loader.add_constructor('tag:yaml.org,2002:float', float_constructor) + return loader.get_data() + + +class _OrderedEntrySet(object): + """"""Ordered set of entity entries. + + This is somewhere between a Set and a Mapping but deliberately does not + implement any of those interfaces. Iteration does not provide + (key, value)-items (since the keys are already in the entry values) + but instead provides just values. The usual set operations such as union + and intersection are not provided. + """""" + def __init__(self, mapping={}): + self._dict = OrderedDict(mapping) + + def __contains__(self, key): + return key in self._dict + + def get(self, key, default=None): + try: + return self.__getitem__(key) + except KeyError: + return default + + def __getitem__(self, key): + return self._dict[key] + + def __iter__(self): + return itervalues(self._dict) + + def __len__(self): + return len(self._dict) + + def add_entry(self, entry): + self._dict[entry.id] = entry + + def discard(self, key): + try: + del self._dict[key] + except KeyError: + pass + + def clear(self): + self._dict.clear() + + def update(self, it): + for entry in it: + self.add_entry(entry) + + def __repr__(self): + return str('<_OrderedEntrySet {{{}}}>').format( + ', '.join(repr(x) for x in iter(self))) + + +class ModelReader(object): + """"""Reader of native YAML-based model format. + + The reader can be created from a model YAML file or directly from a + dict, string or File-like object. Use :meth:`reader_from_path` to read the + model from a YAML file or directory and use the constructor to read from + other sources. Any externally referenced file (with ``include``) will be + read on demand by the parse methods. To read the model fully into memory, + use the :meth:`create_model` to create a :class:`NativeModel`. + """""" + + # Model files to try to open if a directory was specified + DEFAULT_MODEL = 'model.yaml', 'model.yml' + + def __init__(self, model_from, context=None): + """"""Create a model from the specified content. + + Model can be a string, open file, or dictionary. + """""" + if isinstance(model_from, string_types): + self._model = yaml_load(model_from) + self._context = context + elif isinstance(model_from, dict): + self._context = context + self._model = model_from + elif hasattr(model_from, 'read') and callable(model_from.read): + self._context = context + self._model = yaml_load(model_from) + else: + raise ValueError(""Model is of an invalid types"") + + @classmethod + def reader_from_path(cls, path): + """"""Create a model from specified path. + + Path can be a directory containing a ``model.yaml`` or ``model.yml`` + file or it can be a path naming the central model file directly. + """""" + context = FilePathContext(path) + try: + with context.open('r') as f: + return ModelReader(f, context) + except IOError: + # Try to open the default file + for filename in cls.DEFAULT_MODEL: + try: + context = FilePathContext( + os.path.join(path, filename)) + with context.open('r') as f: + return ModelReader(f, context) + except: + logger.debug('Failed to load model file', + exc_info=True) + + # No model could be loaded + raise ParseError('No model file could be found ({})'.format( + ', '.join(cls.DEFAULT_MODEL))) + + @property + def name(self): + """"""Name specified by the model."""""" + return self._model.get('name', None) + + @property + def biomass_reaction(self): + """"""Biomass reaction specified by the model."""""" + return self._model.get('biomass', None) + + @property + def extracellular_compartment(self): + """"""Extracellular compartment specified by the model. + + Defaults to 'e'. + """""" + return self._model.get('extracellular', 'e') + + @property + def default_compartment(self): + """"""Default compartment specified by the model. + + The compartment that is implied when not specified. In some contexts + (e.g. for exchange compounds) the extracellular compartment may be + implied instead. Defaults to 'c'. + """""" + return self._model.get('default_compartment', 'c') + + @property + def default_flux_limit(self): + """"""Default flux limit specified by the model. + + When flux limits on reactions are not specified, this value will be + used. Flux limit of [0;x] will be implied for irreversible reactions + and [-x;x] for reversible reactions, where x is this value. + Defaults to 1000."""""" + return self._model.get('default_flux_limit', 1000) + + def parse_compartments(self): + """"""Parse compartment information from model. + + Return tuple of: 1) iterator of + :class:`psamm.datasource.entry.CompartmentEntry`; 2) Set of pairs + defining the compartment boundaries of the model. + """""" + + compartments = OrderedDict() + boundaries = set() + + if 'compartments' in self._model: + boundary_map = {} + for compartment_def in self._model['compartments']: + compartment_id = convert_to_unicode(compartment_def.get('id')) + _check_id(compartment_id, 'Compartment') + if compartment_id in compartments: + raise ParseError('Duplicate compartment ID: {}'.format( + compartment_id)) + props = dict(compartment_def) + adjacent_to = props.pop('adjacent_to', None) + if adjacent_to is not None: + if not isinstance(adjacent_to, list): + adjacent_to = [adjacent_to] + for other in adjacent_to: + boundary_map.setdefault(other, set()).add( + compartment_id) + + mark = FileMark(self._context, None, None) + compartment = CompartmentEntry(props, mark) + compartments[compartment_id] = compartment + + # Check boundaries from boundary_map + for source, dest_set in iteritems(boundary_map): + if source not in compartments: + raise ParseError( + 'Invalid compartment {} referenced' + ' by compartment {}'.format( + source, ', '.join(dest_set))) + for dest in dest_set: + boundaries.add(tuple(sorted((source, dest)))) + + return itervalues(compartments), frozenset(boundaries) + + def parse_reactions(self): + """"""Yield tuples of reaction ID and reactions defined in the model"""""" + + # Parse reactions defined in the main model file + if 'reactions' in self._model: + for reaction in parse_reaction_list( + self._context, self._model['reactions'], + self.default_compartment): + yield reaction + + def has_model_definition(self): + """"""Return True when the list of model reactions is set in the model."""""" + return 'model' in self._model + + def parse_model(self): + """"""Yield reaction IDs of model reactions"""""" + + if self.has_model_definition(): + for reaction_id in parse_model_group_list( + self._context, self._model['model']): + yield reaction_id + + def parse_limits(self): + """"""Yield tuples of reaction ID, lower, and upper bound flux limits"""""" + + if 'limits' in self._model: + if not isinstance(self._model['limits'], list): + raise ParseError('Expected limits to be a list') + + for limit in parse_limits_list( + self._context, self._model['limits']): + yield limit + + def parse_exchange(self): + """"""Yield tuples of exchange compounds. + + Each exchange compound is a tuple of compound, reaction ID, lower and + upper flux limits. + """""" + + if 'media' in self._model: + if 'exchange' in self._model: + raise ParseError('Both ""media"" and ""exchange"" are specified') + logger.warning( + 'The ""media"" key is deprecated! Please use ""exchange"" instead:' + ' https://psamm.readthedocs.io/en/stable/file_format.html') + exchange_list = self._model['media'] + else: + exchange_list = self._model.get('exchange') + + extracellular = self.extracellular_compartment + if exchange_list is not None: + if not isinstance(exchange_list, list): + raise ParseError('Expected ""exchange"" to be a list') + + for exchange_compound in parse_exchange_list( + self._context, exchange_list, extracellular): + compound, reaction_id, lower, upper = exchange_compound + if compound.compartment is None: + compound = compound.in_compartment(extracellular) + yield compound, reaction_id, lower, upper + + parse_medium = parse_exchange + """"""Yield tuples of exchange compounds. + + .. deprecated:: 0.28 + Use :meth:`parse_exchange` instead. + """""" + + def parse_compounds(self): + """"""Yield CompoundEntries for defined compounds"""""" + + if 'compounds' in self._model: + for compound in parse_compound_list( + self._context, self._model['compounds']): + yield compound + + @property + def context(self): + return self._context + + def create_model(self): + """"""Return :class:`NativeModel` fully loaded into memory."""""" + properties = { + 'name': self.name, + 'biomass': self.biomass_reaction, + 'extracellular': self.extracellular_compartment, + 'default_compartment': self.default_compartment, + 'default_flux_limit': self.default_flux_limit + } + + if self.context is not None: + git_version = util.git_try_describe(self.context.basepath) + properties['version_string'] = git_version + + model = NativeModel(properties) + + # Load compartments into model + compartment_iter, boundaries = self.parse_compartments() + for compartment in compartment_iter: + model.compartments.add_entry(compartment) + model.compartment_boundaries.update(boundaries) + + # Load compounds into model + for compound in self.parse_compounds(): + if compound.id in model.compounds: + existing_entry = model.compounds[compound.id] + common_props = set(compound.properties).intersection( + existing_entry.properties).difference({'id'}) + if len(common_props) > 0: + logger.warning( + 'Compound entry {} at {} overrides already defined' + ' properties: {}'.format( + compound.id, compound.filemark, common_props)) + + properties = dict(compound.properties) + properties.update(existing_entry.properties) + compound = CompoundEntry( + properties, filemark=compound.filemark) + model.compounds.add_entry(compound) + + # Load reactions into model + for reaction in self.parse_reactions(): + if reaction.id in model.reactions: + existing_entry = model.reactions[reaction.id] + common_props = set(reaction.properties).intersection( + existing_entry.properties).difference({'id'}) + if len(common_props) > 0: + logger.warning( + 'Reaction entry {} at {} overrides already defined' + ' properties: {}'.format( + reaction.id, reaction.filemark, common_props)) + + properties = dict(reaction.properties) + properties.update(existing_entry.properties) + reaction = ReactionEntry( + properties, filemark=reaction.filemark) + model.reactions.add_entry(reaction) + + for exchange_def in self.parse_exchange(): + model.exchange[exchange_def[0]] = exchange_def + + for limit in self.parse_limits(): + model.limits[limit[0]] = limit + dir = model.reactions.get(limit[0]).properties[ + 'equation'].direction + if str(dir) == 'Direction.Forward' or \ + str(dir) == 'Direction.Right': + v_min = 0 + v_max = model.default_flux_limit + elif str(dir) == 'Direction.Both' or str(dir) == 'Direction.Bidir': + v_min = -model.default_flux_limit + v_max = model.default_flux_limit + else: + logger.warning('Reaction {} has invalid direction: {}'.format( + limit[0], dir)) + if (limit[1] is not None and limit[1] < v_min) or \ + (limit[2] is not None and limit[2] > v_max): + specify_vmin = limit[1] if limit[1] is not None else \ + -model.default_flux_limit + specify_vmax = limit[2] if limit[2] is not None else \ + -model.default_flux_limit + logger.warning( + ""Flux limits for reaction {} override default flux "" + ""limits set by reaction direction (current flux limits: "" + ""[{}, {}]; default limits: [{}, {}])."".format( + limit[0], specify_vmin, specify_vmax, v_min, v_max)) + + if self.has_model_definition(): + for model_reaction in self.parse_model(): + model.model[model_reaction] = None + else: + for reaction in model.reactions: + model.model[reaction.id] = None + + return model + + +class NativeModel(object): + """"""Represents model in the native format."""""" + + def __init__(self, properties={}): + self._properties = dict(properties) + self._compartments = _OrderedEntrySet() + self._compartment_boundaries = set() + self._compounds = _OrderedEntrySet() + self._reactions = _OrderedEntrySet() + self._exchange = OrderedDict() + self._limits = OrderedDict() + self._model = OrderedDict() + + @property + def name(self): + """"""Return model name property."""""" + return self._properties.get('name') + + @name.setter + def name(self, value): + self._properties['name'] = value + + @property + def version_string(self): + """"""Return model version string."""""" + return self._properties.get('version_string') + + @version_string.setter + def version_string(self, value): + self._properties['version_string'] = value + + @property + def biomass_reaction(self): + """"""Return biomass reaction property."""""" + return self._properties.get('biomass') + + @biomass_reaction.setter + def biomass_reaction(self, value): + self._properties['biomass'] = value + + @property + def extracellular_compartment(self): + """"""Return extracellular compartment property."""""" + return self._properties.get('extracellular') + + @extracellular_compartment.setter + def extracellular_compartment(self, value): + self._properties['extracellular'] = value + + @property + def default_compartment(self): + """"""Return default compartment property."""""" + return self._properties.get('default_compartment') + + @default_compartment.setter + def default_compartment(self, value): + self._properties['default_compartment'] = value + + @property + def default_flux_limit(self): + """"""Return default flux limit property."""""" + return self._properties.get('default_flux_limit') + + @default_flux_limit.setter + def default_flux_limit(self, value): + self._properties['default_flux_limit'] = value + + @property + def compartments(self): + """"""Return compartments entry set."""""" + return self._compartments + + @property + def compartment_boundaries(self): + """"""Return set of compartment boundaries."""""" + return self._compartment_boundaries + + @property + def reactions(self): + """"""Return reaction entry set."""""" + return self._reactions + + @property + def compounds(self): + """"""Return compound entry set."""""" + return self._compounds + + @property + def exchange(self): + """"""Return dict of exchange compounds and properties."""""" + return self._exchange + + @property + def limits(self): + """"""Return dict of reaction limits."""""" + return self._limits + + @property + def model(self): + """"""Return dict of model reactions."""""" + return self._model + + def create_metabolic_model(self): + """"""Create a :class:`psamm.metabolicmodel.MetabolicModel`."""""" + + def _translate_compartments(reaction, compartment): + """"""Translate compound with missing compartments. + + These compounds will have the specified compartment in the output. + """""" + left = (((c.in_compartment(compartment), v) + if c.compartment is None else (c, v)) + for c, v in reaction.left) + right = (((c.in_compartment(compartment), v) + if c.compartment is None else (c, v)) + for c, v in reaction.right) + return Reaction(reaction.direction, left, right) + + # Create metabolic model + database = DictDatabase() + for reaction in self.reactions: + if reaction.equation is not None: + equation = _translate_compartments( + reaction.equation, self.default_compartment) + database.set_reaction(reaction.id, equation) + + undefined_compartments = set() + undefined_compounds = set() + extracellular_compounds = set() + extracellular = self.extracellular_compartment + for reaction in database.reactions: + for compound, _ in database.get_reaction_values(reaction): + if compound.name not in self.compounds: + undefined_compounds.add(compound.name) + if compound.compartment == extracellular: + extracellular_compounds.add(compound.name) + if compound.compartment not in self.compartments: + undefined_compartments.add(compound.compartment) + + for compartment in sorted(undefined_compartments): + logger.warning( + 'The compartment {} was not defined in the list' + ' of compartments'.format(compartment)) + + for compound in sorted(undefined_compounds): + logger.warning( + 'The compound {} was not defined in the list' + ' of compounds'.format(compound)) + + exchange_compounds = set() + for exchange_compound in self.exchange: + if exchange_compound.compartment == extracellular: + exchange_compounds.add(exchange_compound.name) + + for compound in sorted(extracellular_compounds - exchange_compounds): + logger.warning( + 'The compound {} was in the extracellular compartment' + ' but not defined in the exchange compounds'.format(compound)) + for compound in sorted(exchange_compounds - extracellular_compounds): + logger.warning( + 'The compound {} was defined in the exchange compounds but' + ' is not in the extracellular compartment'.format(compound)) + + model_definition = None + if len(self.model) > 0: + model_definition = self.model + + for reaction in self.reactions: + if reaction.equation is None: + logger.warning( + 'Reaction {} has no reaction equation'.format(reaction.id)) + del model_definition[reaction.id] + + return MetabolicModel.load_model( + database, model_definition, itervalues(self.exchange), + itervalues(self.limits), v_max=self.default_flux_limit) + + def __repr__(self): + return str('<{} name={!r}>'.format(self.__class__.__name__, self.name)) + + +def _check_id(entity, entity_type): + """"""Check whether the ID is valid. + + First check if the ID is missing, and then check if it is a qualified + string type, finally check if the string is empty. For all checks, it + would raise a ParseError with the corresponding message. + + Args: + entity: a string type object to be checked. + entity_type: a string that shows the type of entities to check, usually + `Compound` or 'Reaction'. + """""" + + if entity is None: + raise ParseError('{} ID missing'.format(entity_type)) + elif not isinstance(entity, string_types): + msg = '{} ID must be a string, id was {}.'.format(entity_type, entity) + if isinstance(entity, bool): + msg += (' You may have accidentally used an ID value that YAML' + ' interprets as a boolean, such as ""yes"", ""no"", ""on"",' + ' ""off"", ""true"" or ""false"". To use this ID, you have to' + ' quote it with single or double quotes') + raise ParseError(msg) + elif len(entity) == 0: + raise ParseError('{} ID must not be empty'.format(entity_type)) + + +def parse_compound(compound_def, context=None): + """"""Parse a structured compound definition as obtained from a YAML file + + Returns a CompoundEntry."""""" + compound_id = convert_to_unicode(compound_def.get('id')) + _check_id(compound_id, 'Compound') + + compound_props = {} + for key, value in compound_def.items(): + if isinstance(value, str): + compound_props[key] = convert_to_unicode(value) + else: + compound_props[key] = value + + mark = FileMark(context, None, None) + return CompoundEntry(compound_props, mark) + + +def parse_compound_list(path, compounds): + """"""Parse a structured list of compounds as obtained from a YAML file + + Yields CompoundEntries. Path can be given as a string or a context. + """""" + context = FilePathContext(path) + + for compound_def in compounds: + compound_dict = dict(compound_def) + if 'include' in compound_dict: + file_format = compound_dict.get('format') + include_context = context.resolve(compound_dict['include']) + for compound in parse_compound_file(include_context, file_format): + yield compound + else: + yield parse_compound(compound_dict, context) + + +def parse_compound_table_file(path, f): + """"""Parse a tab-separated file containing compound IDs and properties + + The compound properties are parsed according to the header which specifies + which property is contained in each column. + """""" + + context = FilePathContext(path) + + for i, row in enumerate(csv.DictReader(f, delimiter=str('\t'))): + if text_type('id') not in row or \ + text_type(convert_to_unicode(row['id'].strip())) == '': + raise ParseError('Expected `id` column in table') + + props = {key: text_type(convert_to_unicode(value)) + for key, value in iteritems(row) + if text_type(convert_to_unicode(value)) != ''} + if 'charge' in props: + props['charge'] = int(props['charge']) + + mark = FileMark(context, i + 2, None) + yield CompoundEntry(props, mark) + + +def parse_compound_yaml_file(path, f): + """"""Parse a file as a YAML-format list of compounds + + Path can be given as a string or a context. + """""" + return parse_compound_list(path, yaml_load(f)) + + +def resolve_format(format, path): + """"""Looks at a file's extension and format (if any) and returns format. + """""" + if format is None: + if (re.match(r'.+\.(yml|yaml)$', path)): + return 'yaml' + elif (re.match(r'.+\.tsv$', path)): + return 'tsv' + else: + return format.lower() + + +def parse_compound_file(path, format): + """"""Open and parse reaction file based on file extension or given format + + Path can be given as a string or a context. + """""" + + context = FilePathContext(path) + + # YAML files do not need to explicitly specify format + format = resolve_format(format, context.filepath) + if format == 'yaml': + logger.debug('Parsing compound file {} as YAML'.format( + context.filepath)) + with context.open('r') as f: + for compound in parse_compound_yaml_file(context, f): + yield compound + elif format == 'modelseed': + logger.debug('Parsing compound file {} as ModelSEED TSV'.format( + context.filepath)) + with context.open('r') as f: + for compound in modelseed.parse_compound_file(f, context): + yield compound + elif format == 'tsv': + logger.debug('Parsing compound file {} as TSV'.format( + context.filepath)) + with context.open('r') as f: + for compound in parse_compound_table_file(context, f): + yield compound + else: + raise ParseError('Unable to detect format of compound file {}'.format( + context.filepath)) + + +def parse_reaction_equation_string(equation, default_compartment): + """"""Parse a string representation of a reaction equation. + + Converts undefined compartments to the default compartment. + """""" + def _translate_compartments(reaction, compartment): + """"""Translate compound with missing compartments. + + These compounds will have the specified compartment in the output. + """""" + left = (((c.in_compartment(compartment), v) + if c.compartment is None else (c, v)) + for c, v in reaction.left) + right = (((c.in_compartment(compartment), v) + if c.compartment is None else (c, v)) + for c, v in reaction.right) + return Reaction(reaction.direction, left, right) + eq = _REACTION_PARSER.parse(equation).normalized() + return _translate_compartments(eq, default_compartment) + + +def parse_reaction_equation(equation_def, default_compartment): + """"""Parse a structured reaction equation as obtained from a YAML file + + Returns a Reaction. + """""" + def parse_compound_list(compound_list, compartment): + """"""Parse a list of reactants or metabolites"""""" + for compound_def in compound_list: + compound_id = convert_to_unicode(compound_def.get('id')) + _check_id(compound_id, 'Compound') + + value = compound_def.get('value') + if value is None: + raise ParseError('Missing value for compound {}'.format( + compound_id)) + + compound_compartment = compound_def.get('compartment') + if compound_compartment is None: + compound_compartment = compartment + + compound = Compound(compound_id, compartment=compound_compartment) + yield compound, value + + if isinstance(equation_def, string_types): + return parse_reaction_equation_string( + equation_def, default_compartment) + else: + compartment = equation_def.get('compartment', default_compartment) + reversible = bool(equation_def.get('reversible', True)) + left = equation_def.get('left', []) + right = equation_def.get('right', []) + if len(left) == 0 and len(right) == 0: + raise ParseError('Reaction values are missing') + + return Reaction(Direction.Both if reversible else Direction.Forward, + parse_compound_list(left, compartment), + parse_compound_list(right, compartment)) + + +def parse_reaction(reaction_def, default_compartment, context=None): + """"""Parse a structured reaction definition as obtained from a YAML file + + Returns a ReactionEntry. + """""" + reaction_id = convert_to_unicode(reaction_def.get('id')) + _check_id(reaction_id, 'Reaction') + + reaction_props = {} + for key, value in reaction_def.items(): + if isinstance(value, str): + reaction_props[key] = convert_to_unicode(value) + else: + reaction_props[key] = value + + if 'genes' in reaction_def.keys(): + if isinstance(reaction_def['genes'], list): + reaction_props['genes'] = [convert_to_unicode(gene) + for gene in reaction_def['genes']] + + # Parse reaction equation + if 'equation' in reaction_def.keys(): + reaction_props['equation'] = parse_reaction_equation( + reaction_def['equation'], default_compartment) + + mark = FileMark(context, None, None) + return ReactionEntry(reaction_props, mark) + + +def parse_reaction_list(path, reactions, default_compartment=None): + """"""Parse a structured list of reactions as obtained from a YAML file + + Yields tuples of reaction ID and reaction object. Path can be given as a + string or a context. + """""" + context = FilePathContext(path) + + for reaction_def in reactions: + reaction_dict = dict(reaction_def) + if 'include' in reaction_dict: + include_context = context.resolve(reaction_dict['include']) + for reaction in parse_reaction_file( + include_context, default_compartment): + yield reaction + else: + yield parse_reaction(reaction_dict, default_compartment, context) + + +def parse_reaction_yaml_file(path, f, default_compartment): + """"""Parse a file as a YAML-format list of reactions + + Path can be given as a string or a context. + """""" + + return parse_reaction_list(path, yaml_load(f), default_compartment) + + +def parse_reaction_table_file(path, f, default_compartment): + """"""Parse a tab-separated file containing reaction IDs and properties + + The reaction properties are parsed according to the header which specifies + which property is contained in each column. + """""" + + context = FilePathContext(path) + + for lineno, row in enumerate(csv.DictReader(f, delimiter=str('\t'))): + if text_type('id') not in row or \ + text_type(convert_to_unicode(row['id'].strip())) == '': + raise ParseError('Expected `id` column in table') + + props = {key: convert_to_unicode(value) + for key, value in iteritems(row) + if convert_to_unicode(value) != ''} + + if 'equation' in props: + props['equation'] = parse_reaction_equation_string( + props['equation'], default_compartment) + + mark = FileMark(context, lineno + 2, 0) + yield ReactionEntry(props, mark) + + +def parse_reaction_file(path, default_compartment=None): + """"""Open and parse reaction file based on file extension + + Path can be given as a string or a context. + """""" + + context = FilePathContext(path) + + format = resolve_format(None, context.filepath) + if format == 'tsv': + logger.debug('Parsing reaction file {} as TSV'.format( + context.filepath)) + with context.open('r') as f: + for reaction in parse_reaction_table_file( + context, f, default_compartment): + yield reaction + elif format == 'yaml': + logger.debug('Parsing reaction file {} as YAML'.format( + context.filepath)) + with context.open('r') as f: + for reaction in parse_reaction_yaml_file( + context, f, default_compartment): + yield reaction + else: + raise ParseError('Unable to detect format of reaction file {}'.format( + context.filepath)) + + +def get_limits(compound_def): + if ('fixed' in compound_def and + ('lower' not in compound_def and 'upper'not in compound_def)): + fixed = compound_def['fixed'] + lower = fixed + upper = fixed + elif ('fixed' in compound_def and + ('lower' in compound_def or 'upper' in compound_def)): + raise ParseError('Cannot use fixed and a lower or upper bound') + else: + lower = compound_def.get('lower', None) + upper = compound_def.get('upper', None) + return lower, upper + + +def parse_exchange(exchange_def, default_compartment): + """"""Parse a structured exchange definition as obtained from a YAML file. + + Returns in iterator of compound, reaction, lower and upper bounds. + """""" + + default_compartment = exchange_def.get('compartment', default_compartment) + + for compound_def in exchange_def.get('compounds', []): + compartment = compound_def.get('compartment', default_compartment) + compound = Compound(convert_to_unicode(compound_def['id']), + compartment=compartment) + reaction = compound_def.get('reaction') + if reaction: + reaction = convert_to_unicode(reaction) + lower, upper = get_limits(compound_def) + yield compound, reaction, lower, upper + + +parse_medium = parse_exchange +""""""Parse a structured exchange definition as obtained from a YAML file. + +.. deprecated:: 0.28 + Use :func:`parse_exchange` instead. +"""""" + + +def parse_exchange_list(path, exchange, default_compartment): + """"""Parse a structured exchange list as obtained from a YAML file. + + Yields tuples of compound, reaction ID, lower and upper flux bounds. Path + can be given as a string or a context. + """""" + + context = FilePathContext(path) + + for exchange_def in exchange: + if 'include' in exchange_def: + include_context = context.resolve(exchange_def['include']) + for exchange_compound in parse_exchange_file( + include_context, default_compartment): + yield exchange_compound + else: + for exchange_compound in parse_exchange( + exchange_def, default_compartment): + yield exchange_compound + + +parse_medium_list = parse_exchange_list +""""""Parse a structured exchange list as obtained from a YAML file. + +.. deprecated:: 0.28 + Use :func:`parse_exchange_list` instead. +"""""" + + +def parse_exchange_yaml_file(path, f, default_compartment): + """"""Parse a file as a YAML-format exchange definition. + + Path can be given as a string or a context. + """""" + + return parse_exchange(yaml_load(f), default_compartment) + + +parse_medium_yaml_file = parse_exchange_yaml_file +""""""Parse a file as a YAML-format exchange definition. + +.. deprecated:: 0.28 + Use :func:`parse_exchange_yaml_file` instead. +"""""" + + +def parse_exchange_table_file(f): + """"""Parse a space-separated file containing exchange compound flux limits. + + The first two columns contain compound IDs and compartment while the + third column contains the lower flux limits. The fourth column is + optional and contains the upper flux limit. + """""" + + for line in f: + line, _, comment = convert_to_unicode(line).partition('#') + line = line.strip() + if line == '': + continue + + # A line can specify lower limit only (useful for + # medium compounds), or both lower and upper limit. + fields = line.split(None) + if len(fields) < 2 or len(fields) > 4: + raise ParseError('Malformed compound limit: {}'.format(fields)) + + # Extend to four values and unpack + fields.extend(['-']*(4-len(fields))) + compound_id, compartment, lower, upper = fields + + compound = Compound(convert_to_unicode(compound_id), compartment) + lower = float(lower) if lower != '-' else None + upper = float(upper) if upper != '-' else None + + yield compound, None, lower, upper + + +parse_medium_table_file = parse_exchange_table_file +""""""Parse a space-separated file containing exchange compound flux limits. + +.. deprecated:: 0.28 + Use :func:`parse_exchange_table_file` instead. +"""""" + + +def parse_exchange_file(path, default_compartment): + """"""Parse a file as a list of exchange compounds with flux limits. + + The file format is detected and the file is parsed accordingly. Path can + be given as a string or a context. + """""" + + context = FilePathContext(path) + + format = resolve_format(None, context.filepath) + if format == 'tsv': + logger.debug('Parsing exchange file {} as TSV'.format( + context.filepath)) + with context.open('r') as f: + for entry in parse_exchange_table_file(f): + yield entry + elif format == 'yaml': + logger.debug('Parsing exchange file {} as YAML'.format( + context.filepath)) + with context.open('r') as f: + for entry in parse_exchange_yaml_file( + context, f, default_compartment): + yield entry + else: + raise ParseError('Unable to detect format of exchange file {}'.format( + context.filepath)) + + +parse_medium_file = parse_exchange_file +""""""Parse a file as a list of exchange compounds with flux limits. + +.. deprecated:: 0.28 + Use :func:`parse_exchange_file` instead. +"""""" + + +def parse_limit(limit_def): + """"""Parse a structured flux limit definition as obtained from a YAML file + + Returns a tuple of reaction, lower and upper bound. + """""" + + lower, upper = get_limits(limit_def) + reaction = convert_to_unicode(limit_def.get('reaction')) + + return reaction, lower, upper + + +def parse_limits_list(path, limits): + """"""Parse a structured list of flux limits as obtained from a YAML file + + Yields tuples of reaction ID, lower and upper flux bounds. Path can be + given as a string or a context. + """""" + + context = FilePathContext(path) + + for limit_def in limits: + if 'include' in limit_def: + include_context = context.resolve(limit_def['include']) + for limit in parse_limits_file(include_context): + yield limit + else: + yield parse_limit(limit_def) + + +def parse_limits_table_file(f): + """"""Parse a space-separated file containing reaction flux limits + + The first column contains reaction IDs while the second column contains + the lower flux limits. The third column is optional and contains the + upper flux limit. + """""" + + for line in f: + line, _, comment = convert_to_unicode(line).partition('#') + line = line.strip() + if line == '': + continue + + # A line can specify lower limit only (useful for + # exchange reactions), or both lower and upper limit. + fields = line.split(None) + if len(fields) < 1 or len(fields) > 3: + raise ParseError('Malformed reaction limit: {}'.format(fields)) + + # Extend to three values and unpack + fields.extend(['-']*(3-len(fields))) + reaction_id, lower, upper = fields + + lower = float(lower) if lower != '-' else None + upper = float(upper) if upper != '-' else None + + yield convert_to_unicode(reaction_id), lower, upper + + +def parse_limits_yaml_file(path, f): + """"""Parse a file as a YAML-format flux limits definition + + Path can be given as a string or a context. + """""" + + return parse_limits_list(path, yaml_load(f)) + + +def parse_limits_file(path): + """"""Parse a file as a list of reaction flux limits + + The file format is detected and the file is parsed accordingly. Path can + be given as a string or a context. + """""" + + context = FilePathContext(path) + + format = resolve_format(None, context.filepath) + if format == 'tsv': + logger.debug('Parsing limits file {} as TSV'.format( + context.filepath)) + with context.open('r') as f: + for limit in parse_limits_table_file(f): + yield limit + elif format == 'yaml': + logger.debug('Parsing limits file {} as YAML'.format( + context.filepath)) + with context.open('r') as f: + for limit in parse_limits_yaml_file(context, f): + yield limit + else: + raise ParseError('Unable to detect format of limits file {}'.format( + context.filepath)) + + +def parse_model_group(path, group): + """"""Parse a structured model group as obtained from a YAML file + + Path can be given as a string or a context. + """""" + + context = FilePathContext(path) + + for reaction_id in group.get('reactions', []): + yield convert_to_unicode(reaction_id) + + # Parse subgroups + for reaction_id in parse_model_group_list( + context, group.get('groups', [])): + yield reaction_id + + +def parse_model_group_list(path, groups): + """"""Parse a structured list of model groups as obtained from a YAML file + + Yields reaction IDs. Path can be given as a string or a context. + """""" + + context = FilePathContext(path) + for model_group in groups: + if 'include' in model_group: + include_context = context.resolve(model_group['include']) + for reaction_id in parse_model_file(include_context): + yield reaction_id + else: + for reaction_id in parse_model_group(context, model_group): + yield reaction_id + + +def parse_model_yaml_file(path, f): + """"""Parse a file as a YAML-format list of model reaction groups + + Path can be given as a string or a context. + """""" + return parse_model_group_list(path, yaml_load(f)) + + +def parse_model_table_file(path, f): + """"""Parse a file as a list of model reactions + + Yields reactions IDs. Path can be given as a string or a context. + """""" + + for line in f: + line, _, comment = convert_to_unicode(line).partition('#') + line = line.strip() + if line == '': + continue + + yield line + + +def parse_model_file(path): + """"""Parse a file as a list of model reactions + + The file format is detected and the file is parsed accordinly. The file is + specified as a file path that will be opened for reading. Path can be given + as a string or a context. + """""" + + context = FilePathContext(path) + + format = resolve_format(None, context.filepath) + if format == 'tsv': + logger.debug('Parsing model file {} as TSV'.format(context.filepath)) + with context.open('r') as f: + for reaction_id in parse_model_table_file(context, f): + yield reaction_id + elif format == 'yaml': + logger.debug('Parsing model file {} as YAML'.format(context.filepath)) + with context.open('r') as f: + for reaction_id in parse_model_yaml_file(context, f): + yield reaction_id + + +# Threshold for converting reactions into dictionary representation. +_MAX_REACTION_LENGTH = 10 + + +# Create wrapper representer for text_type for Py2/3 compatibility. +if PY3: + def _represent_text_type(dumper, data): + return dumper.represent_str(data) +else: + def _represent_text_type(dumper, data): + return dumper.represent_unicode(data) + + +# Define custom dict representers for YAML +# This allows reading/writing Python OrderedDicts in the correct order. +# See: https://stackoverflow.com/questions/5121931/in-python-how-can-you-load-yaml-mappings-as-ordereddicts # noqa +def _dict_representer(dumper, data): + return dumper.represent_dict(iteritems(data)) + + +def _set_representer(dumper, data): + return dumper.represent_list(iter(data)) + + +def _boolean_expression_representer(dumper, data): + return _represent_text_type(dumper, text_type(data)) + + +def _reaction_representer(dumper, data): + """"""Generate a parsable reaction representation to the YAML parser. + + Check the number of compounds in the reaction, if it is larger than 10, + then transform the reaction data into a list of directories with all + attributes in the reaction; otherwise, just return the text_type format + of the reaction data. + """""" + if len(data.compounds) > _MAX_REACTION_LENGTH: + def dict_make(compounds): + for compound, value in compounds: + yield OrderedDict([ + ('id', text_type(compound.name)), + ('compartment', compound.compartment), + ('value', value)]) + + left = list(dict_make(data.left)) + right = list(dict_make(data.right)) + + direction = data.direction == Direction.Both + + reaction = OrderedDict() + reaction['reversible'] = direction + if data.direction == Direction.Reverse: + reaction['left'] = right + reaction['right'] = left + else: + reaction['left'] = left + reaction['right'] = right + + return dumper.represent_data(reaction) + else: + return _represent_text_type(dumper, text_type(data)) + + +def _formula_representer(dumper, data): + return _represent_text_type(dumper, text_type(data)) + + +def _decimal_representer(dumper, data): + # Code from float_representer in PyYAML. + if data % 1 == 0: + return dumper.represent_int(int(data)) + elif math.isnan(data): + value = '.nan' + elif data == float('inf'): + value = '.inf' + elif data == float('-inf'): + value = '-.inf' + else: + value = text_type(data).lower() + if '.' not in value and 'e' in value: + value = value.replace('e', '.0e', 1) + return dumper.represent_scalar('tag:yaml.org,2002:float', value) + + +class ModelWriter(object): + """"""Writer for native (YAML) format."""""" + + def __init__(self): + self._yaml_args = { + 'default_flow_style': False, + 'encoding': 'utf-8', + 'allow_unicode': True, + 'width': 79 + } + + def _dump(self, stream, data): + if hasattr(yaml, 'CSafeDumper'): + dumper = yaml.CSafeDumper(stream, **self._yaml_args) + else: + dumper = yaml.SafeDumper(stream, **self._yaml_args) + + dumper.add_representer(OrderedDict, _dict_representer) + dumper.add_representer(set, _set_representer) + dumper.add_representer(frozenset, _set_representer) + dumper.add_representer( + boolean.Expression, _boolean_expression_representer) + dumper.add_representer(Reaction, _reaction_representer) + dumper.add_representer(Formula, _formula_representer) + dumper.add_representer(Decimal, _decimal_representer) + + dumper.ignore_aliases = lambda *args: True + + try: + dumper.open() + dumper.represent(data) + dumper.close() + finally: + dumper.dispose() + + def convert_compartment_entry(self, compartment, adjacencies): + """"""Convert compartment entry to YAML dict. + + Args: + compartment: :class:`psamm.datasource.entry.CompartmentEntry`. + adjacencies: Sequence of IDs or a single ID of adjacent + compartments (or None). + """""" + d = OrderedDict() + d['id'] = compartment.id + if adjacencies is not None: + d['adjacent_to'] = adjacencies + + order = {key: i for i, key in enumerate(['name'])} + prop_keys = set(compartment.properties) + for prop in sorted(prop_keys, + key=lambda x: (order.get(x, 1000), x)): + if compartment.properties[prop] is not None: + d[prop] = compartment.properties[prop] + + return d + + def convert_compound_entry(self, compound): + """"""Convert compound entry to YAML dict."""""" + d = OrderedDict() + d['id'] = compound.id + + order = { + key: i for i, key in enumerate( + ['name', 'formula', 'formula_neutral', 'charge', 'kegg', + 'cas'])} + prop_keys = ( + set(compound.properties) - {'boundary', 'compartment'}) + for prop in sorted(prop_keys, + key=lambda x: (order.get(x, 1000), x)): + if compound.properties[prop] is not None: + d[prop] = compound.properties[prop] + + return d + + def convert_reaction_entry(self, reaction): + """"""Convert reaction entry to YAML dict."""""" + d = OrderedDict() + d['id'] = reaction.id + + def is_equation_valid(equation): + # If the equation is a Reaction object, it must have non-zero + # number of compounds. + return (equation is not None and ( + not isinstance(equation, Reaction) or + len(equation.compounds) > 0)) + + order = { + key: i for i, key in enumerate( + ['name', 'genes', 'equation', 'subsystem', 'ec'])} + prop_keys = (set(reaction.properties) - + {'lower_flux', 'upper_flux', 'reversible'}) + for prop in sorted(prop_keys, key=lambda x: (order.get(x, 1000), x)): + if reaction.properties[prop] is None: + continue + d[prop] = reaction.properties[prop] + if prop == 'equation' and not is_equation_valid(d[prop]): + del d[prop] + + return d + + def _write_entries(self, stream, entries, converter, properties=None): + """"""Write iterable of entries as YAML object to stream. + + Args: + stream: File-like object. + entries: Iterable of entries. + converter: Conversion function from entry to YAML object. + properties: Set of compartment properties to output (or None to + output all). + """""" + def iter_entries(): + for c in entries: + entry = converter(c) + if entry is None: + continue + if properties is not None: + entry = OrderedDict( + (key, value) for key, value in iteritems(entry) + if key == 'id' or key in properties) + yield entry + + self._dump(stream, list(iter_entries())) + + def write_compartments(self, stream, compartments, adjacencies, + properties=None): + """"""Write iterable of compartments as YAML object to stream. + + Args: + stream: File-like object. + compartments: Iterable of compartment entries. + adjacencies: Dictionary mapping IDs to adjacent compartment IDs. + properties: Set of compartment properties to output (or None to + output all). + """""" + def convert(entry): + return self.convert_compartment_entry( + entry, adjacencies.get(entry.id)) + + self._write_entries(stream, compartments, convert, properties) + + def write_compounds(self, stream, compounds, properties=None): + """"""Write iterable of compounds as YAML object to stream. + + Args: + stream: File-like object. + compounds: Iterable of compound entries. + properties: Set of compound properties to output (or None to output + all). + """""" + self._write_entries( + stream, compounds, self.convert_compound_entry, properties) + + def write_reactions(self, stream, reactions, properties=None): + """"""Write iterable of reactions as YAML object to stream. + + Args: + stream: File-like object. + compounds: Iterable of reaction entries. + properties: Set of reaction properties to output (or None to output + all). + """""" + self._write_entries( + stream, reactions, self.convert_reaction_entry, properties) + + +def reaction_signature(eq, direction=False, stoichiometry=False): + """"""Return unique signature object for :class:`Reaction`. + + Signature objects are hashable, and compare equal only if the reactions + are considered the same according to the specified rules. + + Args: + direction: Include reaction directionality when considering equality. + stoichiometry: Include stoichiometry when considering equality. + """""" + def compounds_sig(compounds): + if stoichiometry: + return tuple(sorted(compounds)) + else: + return tuple(sorted(compound for compound, _ in compounds)) + + left = compounds_sig(eq.left) + right = compounds_sig(eq.right) + + if left < right: + reaction_sig = left, right + direction_sig = eq.direction + else: + reaction_sig = right, left + direction_sig = eq.direction.flipped() + + if direction: + return reaction_sig, direction_sig + return reaction_sig +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_bayesian.py",".py","16450","409","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015 Jon Lund Steffensen +# Copyright 2020 Jing Wang +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest +import tempfile +import os +import shutil +from collections import namedtuple +import pandas as pd + +from psamm import bayesian, bayesian_util as util +from psamm.datasource.native import ( + ModelReader, CompoundEntry, Formula, ReactionEntry) +from psamm.datasource.reaction import parse_reaction + + +class TestBayesianPredictor(unittest.TestCase): + def setUp(self): + self._model_dir = tempfile.mkdtemp() + with open(os.path.join(self._model_dir, 'model1.yaml'), 'w') as f: + f.write('\n'.join([ + '---', + 'reactions:', + ' - id: rxn_1', + ' name: rxn_1', + ' equation: A[e] => B[c]', + ' genes: gene1 and gene2 or gene3', + ' - id: rxn_2', + ' name: rxn_2', + ' equation: B[c] => C[e]', + ' genes: gene5 or gene6', + ' - id: rxn_3', + ' name: rxn_3', + ' equation: A[e] + (6) B[c] <=> (6) C[e] + (6) D[c]', + ' genes: gene7', + 'compounds:', + ' - id: A', + ' name: A', + ' formula: C6H12O6', + ' charge: 1', + ' - id: B', + ' name: B', + ' formula: O2', + ' charge: 1', + ' kegg: C00010', + ' - id: C', + ' name: C', + ' formula: CO2', + ' charge: -1', + ' - id: D', + ' name: D', + ' formula: H2O', + ])) + self._model1 = ModelReader.reader_from_path( + os.path.join(self._model_dir, 'model1.yaml')).create_model() + self._model1 = bayesian.MappingModel(self._model1) + + with open(os.path.join(self._model_dir, 'model2.yaml'), 'w') as f: + f.write('\n'.join([ + '---', + 'reactions:', + ' - id: rxn_1', + ' name: rxn_1', + ' equation: A[e] => B2[c]', + ' genes: gene1 and gene2 or gene3', + ' - id: rnx_2', + ' equation: B2[c] => C[e]', + ' genes: gene5 and gene6', + ' - id: rxn_3', + ' name: rxn_3', + ' equation: A[e] <=> (6) C[e] + (6) D4[c]', + ' - id: rxn_4', + ' equation: E[c] => F[c]', + 'compounds:', + ' - id: A', + ' name: a', + ' formula: C6H11O6', + ' charge: 0', + ' - id: B2', + ' name: -B ()', + ' formula: O2', + ' charge: 1', + ' kegg: C00010', + ' - id: C', + ' name: C', + ' charge: -1', + ' - id: D4', + ' name: D', + ' formula: H2O', + ' charge: -1', + ])) + self._model2 = ModelReader.reader_from_path( + os.path.join(self._model_dir, 'model2.yaml')).create_model() + self._model2 = bayesian.MappingModel(self._model2) + + def tearDown(self): + shutil.rmtree(self._model_dir) + + def test_summary(self): + self._model1.print_summary() + self._model2.print_summary() + + def test_consistency_check(self): + self.assertTrue(self._model1.check_reaction_compounds()) + self.assertFalse(self._model2.check_reaction_compounds()) + + def test_compound_map(self): + p = bayesian.BayesianCompoundPredictor( + self._model1, self._model2, 1, self._model_dir, True, True + ) + self.assertEqual(p.model1, self._model1) + self.assertEqual(p.model2, self._model2) + self.assertEqual(p.map('A', 'A'), 1) + self.assertIsInstance(p, bayesian.BayesianCompoundPredictor) + best_map = p.get_best_map() + self.assertIsInstance(best_map, pd.DataFrame) + self.assertIsInstance(p.get_raw_map(), pd.DataFrame) + self.assertIsInstance(p.get_cpd_pred(), pd.Series) + self.assertLess(best_map.loc[('B', 'B2'), 'p_id'], + best_map.loc[('A', 'A'), 'p_id']) + self.assertIn(('A', 'A'), best_map.index) + self.assertIn(('B', 'B2'), best_map.index) + self.assertIn(('C', 'C'), best_map.index) + self.assertIn(('D', 'D4'), best_map.index) + + def test_reaction_map(self): + cpd_pred = bayesian.BayesianCompoundPredictor( + self._model1, self._model2, 1, self._model_dir, False, False + ).get_cpd_pred() + p = bayesian.BayesianReactionPredictor( + self._model1, self._model2, cpd_pred, + 1, self._model_dir, True, True + ) + self.assertIsInstance(p, bayesian.BayesianReactionPredictor) + best_map = p.get_best_map() + self.assertIsInstance(best_map, pd.DataFrame) + self.assertIsInstance(p.get_raw_map(), pd.DataFrame) + self.assertIn(('rxn_1', 'rxn_1'), best_map.index) + self.assertIn(('rxn_2', 'rnx_2'), best_map.index) + self.assertIn(('rxn_3', 'rxn_3'), best_map.index) + + p = bayesian.BayesianReactionPredictor( + self._model1, self._model2, cpd_pred, + 1, self._model_dir, True, False + ) + self.assertEqual(p.model1, self._model1) + self.assertEqual(p.model2, self._model2) + self.assertAlmostEqual(p.map('rxn_1', 'rxn_1'), 1, 1) + self.assertIsInstance(p, bayesian.BayesianReactionPredictor) + best_map = p.get_best_map() + self.assertIsInstance(best_map, pd.DataFrame) + self.assertIsInstance(p.get_raw_map(), pd.DataFrame) + + def test_compound_id_likelihood(self): + match, unmatch = bayesian.compound_id_likelihood( + CompoundEntry({'id': 'A'}), CompoundEntry({'id': 'A'}), + 1.0 / 500, 1.0 / 1000 + ) + self.assertGreater(match, unmatch) + match, unmatch = bayesian.compound_id_likelihood( + CompoundEntry({'id': 'A'}), CompoundEntry({'id': 'B'}), + 1.0 / 500, 1.0 / 1000 + ) + self.assertLess(match, unmatch) + + def test_compound_name_likelihood(self): + match, unmatch = bayesian.compound_name_likelihood( + CompoundEntry({'id': 'A', 'name': 'Test'}), + CompoundEntry({'id': 'B', 'name': 'te-s(t)'}), + 1.0 / 500, 1.0 / 1000 + ) + self.assertGreater(match, unmatch) + match, unmatch = bayesian.compound_name_likelihood( + CompoundEntry({'id': 'A', 'name': 'Test'}), + CompoundEntry({'id': 'B', 'name': 'Test1'}), + 1.0 / 500, 1.0 / 1000 + ) + self.assertLess(match, unmatch) + + def test_compound_charge_likelihood(self): + match, unmatch = bayesian.compound_charge_likelihood( + CompoundEntry({'id': 'A', 'charge': 1}), + CompoundEntry({'id': 'B', 'charge': 1}), + 1.0 / 500, 0.5, 0.5 + ) + self.assertGreater(match, unmatch) + match, unmatch = bayesian.compound_charge_likelihood( + CompoundEntry({'id': 'A', 'charge': 1}), + CompoundEntry({'id': 'B', 'charge': -1}), + 1.0 / 500, 0.5, 0.5 + ) + self.assertLess(match, unmatch) + match, unmatch = bayesian.compound_charge_likelihood( + CompoundEntry({'id': 'A'}), + CompoundEntry({'id': 'B', 'charge': -1}), + 1.0 / 500, 0.5, 0.5 + ) + self.assertEqual(match, unmatch) + + def test_compound_formula_likelihood(self): + match, unmatch = bayesian.compound_formula_likelihood( + CompoundEntry({'id': 'A', 'formula': Formula.parse('C3H4')}), + CompoundEntry( + {'id': 'B', 'formula': Formula.parse('C3H5'), 'charge': 1}), + 1.0 / 500, 1.0 / 1000, 0.5 + ) + self.assertGreater(match, unmatch) + match, unmatch = bayesian.compound_formula_likelihood( + CompoundEntry({'id': 'A', 'formula': Formula.parse('C3H4')}), + CompoundEntry({'id': 'B', 'formula': Formula.parse('C3H5')}), + 1.0 / 500, 1.0 / 1000, 0.5 + ) + self.assertLess(match, unmatch) + match, unmatch = bayesian.compound_formula_likelihood( + CompoundEntry({'id': 'A', 'formula': Formula.parse('C3H4')}), + CompoundEntry({'id': 'B', 'formula': None}), + 1.0 / 500, 1.0 / 1000, 0.5 + ) + self.assertEqual(match, unmatch) + + def test_compound_kegg_likelihood(self): + CompoundEntry = namedtuple('CompoundEntry', ['id', 'kegg']) + match, unmatch = bayesian.compound_kegg_likelihood( + CompoundEntry(id='A', kegg='C00001'), + CompoundEntry(id='B', kegg='C00001'), + 1.0 / 500, 1.0 / 1000, 0.5 + ) + self.assertGreater(match, unmatch) + match, unmatch = bayesian.compound_kegg_likelihood( + CompoundEntry(id='A', kegg='C00001'), + CompoundEntry(id='B', kegg='C00003'), + 1.0 / 500, 1.0 / 1000, 0.5 + ) + self.assertLess(match, unmatch) + match, unmatch = bayesian.compound_kegg_likelihood( + CompoundEntry(id='A', kegg=None), + CompoundEntry(id='B', kegg='C00001'), + 1.0 / 500, 1.0 / 1000, 0.5 + ) + self.assertEqual(match, unmatch) + + def test_reaction_id_likelihood(self): + match, unmatch = bayesian.reaction_id_likelihood( + ReactionEntry({'id': 'r1'}), + ReactionEntry({'id': 'r1'}), + 1.0 / 500, 1.0 / 500, 499.0 / 500 + ) + self.assertGreater(match, unmatch) + match, unmatch = bayesian.reaction_id_likelihood( + ReactionEntry({'id': 'r1'}), + ReactionEntry({'id': 'r2'}), + 1.0 / 500, 1.0 / 500, 499.0 / 500 + ) + self.assertLess(match, unmatch) + + def test_reaction_name_likelihood(self): + match, unmatch = bayesian.reaction_name_likelihood( + ReactionEntry({'id': 'r1', 'name': 'Test'}), + ReactionEntry({'id': 'r1', 'name': 'te-s(t)'}), + 1.0 / 500, 1.0 / 1000 + ) + self.assertGreater(match, unmatch) + match, unmatch = bayesian.reaction_name_likelihood( + ReactionEntry({'id': 'r1', 'name': 'Test'}), + ReactionEntry({'id': 'r2', 'name': 'Test2'}), + 1.0 / 500, 1.0 / 1000 + ) + self.assertLess(match, unmatch) + + def test_reaction_genes_likelihood(self): + match, unmatch = bayesian.reaction_genes_likelihood( + ReactionEntry({'id': 'r1', 'genes': 'g1 and g2 or g3'}), + ReactionEntry({'id': 'r1', 'genes': 'g2 and g1'}), + 1.0 / 500, 1.0 / 1000, 0.8 + ) + self.assertGreater(match, unmatch) + match, unmatch = bayesian.reaction_genes_likelihood( + ReactionEntry({'id': 'r1', 'genes': 'g1 and g2 or g3'}), + ReactionEntry({'id': 'r1', 'genes': 'g2 and g4'}), + 1.0 / 500, 1.0 / 1000, 0.8 + ) + self.assertLessEqual(match, unmatch) + match, unmatch = bayesian.reaction_genes_likelihood( + ReactionEntry({'id': 'r1', 'genes': 'g1 and g2 or g3'}), + ReactionEntry({'id': 'r1', 'genes': 'g2 and g4'}), + 1.0 / 500, 1.0 / 1000, 0.8, {'g1': 'g4', 'g4': 'g1'} + ) + self.assertGreater(match, unmatch) + match, unmatch = bayesian.reaction_genes_likelihood( + ReactionEntry({'id': 'r1', 'genes': None}), + ReactionEntry({'id': 'r1', 'genes': 'g4 and g5'}), + 1.0 / 500, 1.0 / 1000, 0.8 + ) + self.assertEqual(match, unmatch) + + def test_reaction_equation_likelihood(self): + cpd_map = {'A': set(['A1']), + 'B': set(['B1']), + 'C': set(['C1']), + 'D': set(['D1'])} + cpd_score = {'A': 1, 'B': 1, 'C': 0.9, 'D': 0.9} + eq1 = parse_reaction('A[c] + C[c] + B[c] => D[c]') + eq2 = parse_reaction('A1[c] + C1[c] + B1[c] => D1[c]') + m, un = bayesian.reaction_equation_compound_mapping_likelihood( + ReactionEntry({'id': 'r1', 'equation': eq1}), + ReactionEntry({'id': 'r2', 'equation': eq2}), + cpd_map, cpd_score + ) + self.assertGreater(m, un) + eq2 = parse_reaction('D1[c] + F1[c] <=> A1[c] + C1[c] + B1[c]') + m, un = bayesian.reaction_equation_compound_mapping_likelihood( + ReactionEntry({'id': 'r1', 'equation': eq1}), + ReactionEntry({'id': 'r2', 'equation': eq2}), + cpd_map, cpd_score + ) + self.assertGreater(m, un) + eq2 = parse_reaction('A1[c] => D1[c] + C1[c]') + m, un = bayesian.reaction_equation_compound_mapping_likelihood( + ReactionEntry({'id': 'r1', 'equation': eq1}), + ReactionEntry({'id': 'r2', 'equation': eq2}), + cpd_map, cpd_score + ) + self.assertLess(m, un) + m, un = bayesian.reaction_equation_compound_mapping_likelihood( + ReactionEntry({'id': 'r1', 'equation': eq1}), + ReactionEntry({'id': 'r2', 'equation': None}), + cpd_map, cpd_score + ) + self.assertEqual(m, un) + eq2 = parse_reaction('A1[s] + C1[s] + B1[s] => D1[s]') + m, un = bayesian.reaction_equation_compound_mapping_likelihood( + ReactionEntry({'id': 'r1', 'equation': eq1}), + ReactionEntry({'id': 'r2', 'equation': eq2}), + cpd_map, cpd_score + ) + self.assertLess(m, un) + m, un = bayesian.reaction_equation_compound_mapping_likelihood( + ReactionEntry({'id': 'r1', 'equation': eq1}), + ReactionEntry({'id': 'r2', 'equation': eq2}), + cpd_map, cpd_score, + {'c': 's'} + ) + self.assertGreater(m, un) + + +class Test_bayesian_util(unittest.TestCase): + def test_name_equals(self): + self.assertFalse(util.name_equals('Test', None)) + + def test_name_similar(self): + score = util.name_similar('kit-ten', 'sitt(i)ng') + self.assertEqual(score, 1 - 3.0 / 7) + score = util.name_similar('kitten', None) + self.assertEqual(score, 0.01) + score = util.name_similar('kitten', '') + self.assertEqual(score, 0.01) + + def test_fomula_equals(self): + self.assertFalse(util.formula_equals(None, None, 0, 1)) + + def test_formula_exact(self): + self.assertTrue( + util.formula_exact(Formula.parse('C3H4O5'), + Formula.parse('C3H4O5')) + ) + self.assertFalse( + util.formula_exact(Formula.parse('C2H3O6'), None) + ) + self.assertFalse( + util.formula_exact(Formula.parse('C2H3O6'), + Formula.parse('C5H11')) + ) + + def test_pairwise_distance(self): + for pair, score in util.pairwise_distance(['kitten'], ['sitting'], + util.jaccard): + self.assertTupleEqual( + (pair, score), + (('kitten', 'sitting'), 3.0 / 7) + ) + + def test_gene_equals(self): + g1 = '(A1 and B21) or (A12 and B2)' + g2 = 'A12 and B2' + g3 = 'A1 and B2' + g4 = '(C and D) or (E and F)' + gmap = {'A12': 'D', 'B2': 'C', 'C': 'B2', 'D': 'A12'} + self.assertTrue(util.genes_equals(g1, g2)) + self.assertFalse(util.genes_equals(g1, g3)) + self.assertFalse(util.genes_equals(g1, None)) + self.assertTrue(util.genes_equals(g1, g4, gmap)) +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_massconsistency.py",".py","4685","118","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.metabolicmodel import MetabolicModel +from psamm.database import DictDatabase +from psamm import massconsistency +from psamm.datasource.reaction import parse_reaction +from psamm.reaction import Compound +from psamm.lpsolver import generic + +from six import iteritems + + +class TestMassConsistency(unittest.TestCase): + """"""Test mass consistency using a simple model"""""" + + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_mass_consistent_is_consistent(self): + exchange = {'rxn_1', 'rxn_6'} + self.assertTrue(massconsistency.is_consistent( + self.model, self.solver, exchange, set())) + + def test_mass_inconsistent_is_consistent(self): + exchange = {'rxn_1', 'rxn_6'} + self.database.set_reaction('rxn_7', parse_reaction('|D| => (2) |C|')) + self.model.add_reaction('rxn_7') + self.assertFalse(massconsistency.is_consistent( + self.model, self.solver, exchange, set())) + + def test_mass_consistent_reactions_returns_compounds(self): + exchange = {'rxn_1', 'rxn_6'} + _, compounds = massconsistency.check_reaction_consistency( + self.model, exchange=exchange, solver=self.solver) + for c, value in compounds: + self.assertIn(c, self.model.compounds) + self.assertGreaterEqual(value, 1.0) + + def test_mass_consistent_reactions_returns_reactions(self): + exchange = {'rxn_1', 'rxn_6'} + reactions, _ = massconsistency.check_reaction_consistency( + self.model, exchange=exchange, solver=self.solver) + for r, residual in reactions: + self.assertIn(r, self.model.reactions) + + +class TestMassConsistencyZeroMass(unittest.TestCase): + """"""Test mass consistency using a model with zero-mass compound"""""" + + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction( + '|A| + |B| => |C|')) + self.database.set_reaction('rxn_2', parse_reaction( + '|C| + |Z| => |A| + |B|')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_is_consistent_with_zeromass(self): + consistent = massconsistency.is_consistent( + self.model, solver=self.solver, zeromass={Compound('Z')}) + self.assertTrue(consistent) + + def test_compound_consistency_with_zeromass(self): + compounds = dict(massconsistency.check_compound_consistency( + self.model, solver=self.solver, zeromass={Compound('Z')})) + for c, value in iteritems(compounds): + self.assertGreaterEqual(value, 1) + + def test_reaction_consistency_with_zeromass(self): + reactions, _ = massconsistency.check_reaction_consistency( + self.model, solver=self.solver, zeromass={Compound('Z')}) + reactions = dict(reactions) + + for r, value in iteritems(reactions): + self.assertAlmostEqual(value, 0) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_lpsolver_cplex.py",".py","4857","129","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.lpsolver import lp + +try: + from psamm.lpsolver import cplex +except ImportError: + cplex = None + +requires_solver = unittest.skipIf(cplex is None, 'Cplex solver not available') + + +@requires_solver +class TestCplexProblem(unittest.TestCase): + def setUp(self): + self.solver = cplex.Solver() + + def test_expression_to_string(self): + prob = self.solver.create_problem() + prob.define('x', 'y', lower=0, upper=10) + expr = -3 * prob.var('x') + prob.var('y') + self.assertEqual(str(expr), '-3*x + y') + + def test_expression_of_tuple_to_string(self): + prob = self.solver.create_problem() + prob.define(('x', 1), ('x', 2), lower=0, upper=10) + expr = -prob.var(('x', 1)) + 2 * prob.var(('x', 2)) + self.assertEqual(str(expr), ""-('x', 1) + 2*('x', 2)"") + + def test_objective_reset_on_set_objective(self): + prob = self.solver.create_problem() + prob.define('x', 'y', lower=0, upper=10) + prob.add_linear_constraints(prob.var('x') + prob.var('y') <= 12) + prob.set_objective_sense(lp.ObjectiveSense.Maximize) + + # Solve first time, maximize x + prob.set_objective(2*prob.var('x')) + result = prob.solve() + self.assertAlmostEqual(result.get_value('x'), 10) + + # Solve second time, maximize y + # If the objective is not properly cleared, + # the second solve will still maximize x. + prob.set_objective(prob.var('y')) + result = prob.solve() + self.assertAlmostEqual(result.get_value('y'), 10) + + def test_quadratic_objective(self): + prob = self.solver.create_problem() + prob.define('x', 'y', lower=0, upper=10) + prob.add_linear_constraints(prob.var('x') + prob.var('y') <= 12) + prob.set_objective_sense(lp.ObjectiveSense.Maximize) + + prob.set_objective(-prob.var('x')**2 + 5*prob.var('x')) + result = prob.solve() + self.assertAlmostEqual(result.get_value('x'), 2.5) + + # Solve second time, maximize y + prob.set_objective(prob.var('y')) + result = prob.solve() + self.assertAlmostEqual(result.get_value('y'), 10) + + def test_result_to_bool_conversion_on_optimal(self): + """"""Run a feasible LP problem and check that the result is True"""""" + prob = self.solver.create_problem() + prob.define('x', 'y', lower=0, upper=10) + prob.add_linear_constraints(prob.var('x') + prob.var('y') <= 12) + prob.set_objective_sense(lp.ObjectiveSense.Maximize) + + prob.set_linear_objective(2*prob.var('x')) + result = prob.solve() + self.assertTrue(result) + + def test_result_to_bool_conversion_on_infeasible(self): + """"""Run an infeasible LP problem and check that the result is False"""""" + prob = self.solver.create_problem() + prob.define('x', 'y', 'z', lower=0, upper=10) + prob.add_linear_constraints(2*prob.var('x') == -prob.var('y'), + prob.var('x') + prob.var('z') >= 6, + prob.var('z') <= 3) + prob.set_objective_sense(lp.ObjectiveSense.Maximize) + prob.set_linear_objective(2*prob.var('x')) + result = prob.solve_unchecked() + self.assertFalse(result) + + # Check that the normal solve raises SolverError when non-optimal. + with self.assertRaises(lp.SolverError): + prob.solve() + + def test_constraint_delete(self): + prob = self.solver.create_problem() + prob.define('x', 'y', lower=0, upper=10) + prob.add_linear_constraints(prob.var('x') + prob.var('y') <= 12) + c1, = prob.add_linear_constraints(prob.var('x') <= 5) + + prob.set_objective_sense(lp.ObjectiveSense.Maximize) + prob.set_linear_objective(prob.var('x')) + + result = prob.solve() + self.assertAlmostEqual(result.get_value('x'), 5) + + # Delete constraint + c1.delete() + result = prob.solve() + self.assertAlmostEqual(result.get_value('x'), 10) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_gapfilling.py",".py","5594","163","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2016-2017 Jon Lund Steffensen +# Copyright 2016 Chao liu +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.datasource import native +from psamm.metabolicmodel import MetabolicModel +from psamm.database import DictDatabase +from psamm.datasource.reaction import parse_reaction +from psamm import gapfilling + + +class TestAddReactions(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) A[c]')) + self.database.set_reaction('rxn_2', parse_reaction('A[c] <=> B[c]')) + self.database.set_reaction('rxn_3', parse_reaction('A[c] => D[e]')) + self.database.set_reaction('rxn_4', parse_reaction('A[c] => C[c]')) + self.database.set_reaction('rxn_5', parse_reaction('C[c] => D[e]')) + self.database.set_reaction('rxn_6', parse_reaction('D[e] =>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + def test_add_all_database_reactions(self): + # Should get added + self.database.set_reaction('rxn_7', parse_reaction('D[c] => E[c]')) + # Not added because of compartment + self.database.set_reaction('rxn_8', parse_reaction('D[c] => E[p]')) + added = gapfilling.add_all_database_reactions(self.model, {'c', 'e'}) + self.assertEqual(added, {'rxn_7'}) + self.assertEqual(set(self.model.reactions), { + 'rxn_1', 'rxn_2', 'rxn_3', 'rxn_4', 'rxn_5', 'rxn_6', 'rxn_7' + }) + + def test_add_all_database_reactions_none(self): + added = gapfilling.add_all_database_reactions(self.model, {'c', 'e'}) + self.assertEqual(added, set()) + self.assertEqual(set(self.model.reactions), { + 'rxn_1', 'rxn_2', 'rxn_3', 'rxn_4', 'rxn_5', 'rxn_6'}) + + def test_add_all_transport_reactions(self): + added = gapfilling.add_all_transport_reactions( + self.model, {('e', 'c')}) + for reaction in added: + compartments = tuple(c.compartment for c, _ in + self.model.get_reaction_values(reaction)) + self.assertEqual(len(compartments), 2) + self.assertTrue('e' in compartments) + self.assertTrue(compartments[0] != compartments[1]) + + +class TestCreateExtendedModel(unittest.TestCase): + def setUp(self): + reader = native.ModelReader({ + 'compartments': [ + { + 'id': 'c', + 'adjacent_to': 'e' + }, { + 'id': 'e' + } + ], + 'reactions': [ + { + 'id': 'rxn_1', + 'equation': 'A[e] <=> B[c]' + }, { + 'id': 'rxn_2', + 'equation': 'A[e] => C[c]' + }, { + 'id': 'rxn_3', + 'equation': 'A[e] => D[e]' + }, { + 'id': 'rxn_4', + 'equation': 'C[c] => D[e]' + } + ], + 'compounds': [ + {'id': 'A'}, + {'id': 'B'}, + {'id': 'C'}, + {'id': 'D'} + ], + 'exchange': [{ + 'compartment': 'e', + 'compounds': [ + { + 'id': 'A', + 'reaction': 'rxn_5' + }, + { + 'id': 'D', + 'reaction': 'rxn_6' + } + ] + }], + 'model': [{ + 'reactions': [ + 'rxn_1', + 'rxn_2' + ] + }] + }) + self._model = reader.create_model() + + def test_create_model_extended(self): + expected_reactions = set([ + 'rxn_1', + 'rxn_2', + 'rxn_3', + 'rxn_4', + 'rxn_5', + 'rxn_6', + 'TP_A[c]_A[e]', + 'TP_B[c]_B[e]', + 'TP_C[c]_C[e]', + 'TP_D[c]_D[e]', + 'EX_B[e]', + 'EX_C[e]', + ]) + + expected_weights = { + 'rxn_3': 5.6, + 'rxn_4': 1.0, + 'TP_A[c]_A[e]': 3.0, + 'TP_B[c]_B[e]': 3.0, + 'TP_C[c]_C[e]': 3.0, + 'TP_D[c]_D[e]': 3.0, + 'EX_B[e]': 2.0, + 'EX_C[e]': 2.0 + } + penalties = {'rxn_3': 5.6} + + model_extended, weights = gapfilling.create_extended_model( + self._model, + db_penalty=1.0, + ex_penalty=2.0, + tp_penalty=3.0, + penalties=penalties) + self.assertEqual(set(model_extended.reactions), expected_reactions) + self.assertEqual(weights, expected_weights) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_fastgapfill.py",".py","2085","59","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2016-2017 Jon Lund Steffensen +# Copyright 2016 Chao liu +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.metabolicmodel import MetabolicModel +from psamm.database import DictDatabase +from psamm import fastgapfill +from psamm.lpsolver import generic +from psamm.datasource.reaction import parse_reaction + + +class TestFastGapFill(unittest.TestCase): + def setUp(self): + self._database = DictDatabase() + self._database.set_reaction('rxn_1', parse_reaction('|A| <=>')) + self._database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self._database.set_reaction('rxn_3', parse_reaction('|C| <=> |B|')) + self._database.set_reaction('rxn_4', parse_reaction('|C| <=>')) + self._mm = MetabolicModel.load_model( + self._database, self._database.reactions) + + try: + self._solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_fastgapfill(self): + core = {'rxn_2', 'rxn_3'} + induced = fastgapfill.fastgapfill( + self._mm, + core, + epsilon=0.001, + solver=self._solver) + + self.assertEqual( + set(induced), + {'rxn_1', 'rxn_2', 'rxn_3', 'rxn_4'}) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_util.py",".py","2380","75","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.util import MaybeRelative, FrozenOrderedSet + + +class TestMaybeRelative(unittest.TestCase): + def test_init_from_float(self): + arg = MaybeRelative(24.5) + self.assertFalse(arg.relative) + self.assertIsNone(arg.reference) + self.assertAlmostEqual(float(arg), 24.5) + + def test_init_from_float_string(self): + arg = MaybeRelative('-10') + self.assertFalse(arg.relative) + self.assertIsNone(arg.reference) + self.assertAlmostEqual(float(arg), -10.0) + + def test_init_from_percentage(self): + arg = MaybeRelative('110%') + self.assertTrue(arg.relative) + self.assertIsNone(arg.reference) + with self.assertRaises(ValueError): + float(arg) + + def test_resolve_relative(self): + arg = MaybeRelative('40%') + arg.reference = 200.0 + self.assertAlmostEqual(float(arg), 80.0) + + def test_invalid(self): + with self.assertRaises(ValueError): + arg = MaybeRelative('abc') + + +class TestFrozenOrderedSet(unittest.TestCase): + def test_init_from_empty(self): + s = FrozenOrderedSet() + self.assertEqual(list(s), []) + + def test_init_from_sequence(self): + s = FrozenOrderedSet([5, 2, 4, 0, 9, 13, 5, 3]) + self.assertEqual(list(s), [5, 2, 4, 0, 9, 13, 3]) + + def test_set_length(self): + s = FrozenOrderedSet([1, 2, 3]) + self.assertEqual(len(s), 3) + + def test_set_is_hashable(self): + s = FrozenOrderedSet(['a', 'b', 'c']) + hash(s) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_gimme.py",".py","9207","197","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2020 Keith Dufault-Thompson +# Copyright 2015-2020 Keith Dufault-Thompson + + +import unittest + +from psamm.metabolicmodel import MetabolicModel +from psamm.database import DictDatabase +from psamm.datasource.reaction import parse_reaction +from psamm.expression import boolean +from psamm.lpsolver import generic +from psamm import fluxanalysis +from psamm.commands import gimme +from psamm.util import MaybeRelative + + +class TestAddReactions(unittest.TestCase): + def setUp(self): + self._database = DictDatabase() + self._database.set_reaction('rxn_1', parse_reaction('A[e] => B[e]')) + self._database.set_reaction('rxn_2', parse_reaction('B[e] => C[e]')) + self._database.set_reaction('rxn_3', parse_reaction('B[e] <=> D[e]')) + self._database.set_reaction('rxn_4', parse_reaction('C[e] <=> E[e]')) + self._database.set_reaction('rxn_5', parse_reaction('D[e] => E[e]')) + self._database.set_reaction('rxn_6', parse_reaction('E[e] =>')) + self._database.set_reaction('rxn_7', parse_reaction('F[e] =>')) + self._database.set_reaction('ex_A', parse_reaction('A[e] <=>')) + + self._mm = MetabolicModel.load_model( + self._database, self._database.reactions) + self._assoc = { + 'rxn_1': str('gene_1'), + 'rxn_2': str('gene_2'), + 'rxn_3': str('gene_5'), + 'rxn_4': str('gene_3 or gene_4'), + 'rxn_5': str('gene_5 and gene_6'), + 'rxn_7': str('gene5 and gene4') + } + self._obj_reaction = 'rxn_6' + self.empty_dict = {} + + try: + self._solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + try: + self.solver = generic.Solver(integer=True) + except generic.RequirementsError: + self.skipTest('Needs and integer programming solver') + + def test_reverse_model(self): + test_associations = { + 'rxn_1': str('gene_1'), + 'rxn_2': str('gene_2'), + 'rxn_3_forward': str('gene_5'), + 'rxn_3_reverse': str('gene_5'), + 'rxn_4_forward': str('gene_3 or gene_4'), + 'rxn_4_reverse': str('gene_3 or gene_4'), + 'rxn_5': str('gene_5 and gene_6') + } + mm_irreversible, reversible_gene_assoc, split_rxns, self.empty_dict = \ + self._mm.make_irreversible(self._assoc, + exclude_list=['ex_A', 'rxn_6', 'rxn_7']) + self.assertEqual(split_rxns, set([('rxn_4_forward', 'rxn_4_reverse'), + ('rxn_3_forward', 'rxn_3_reverse')])) + self.assertEqual(reversible_gene_assoc, test_associations) + self.assertEqual(set([i for i in mm_irreversible.reactions]), + {'rxn_1', 'rxn_2', 'rxn_3_forward', 'rxn_3_reverse', + 'rxn_4_forward', 'rxn_4_reverse', 'rxn_5', + 'rxn_6', 'rxn_7', 'ex_A'}) + + def test_revese_model_limits(self): + mm = self._mm.copy() + mm.limits['rxn_3'].lower = 0 + empty_dict = {} + mm_irreversible, reversible_gene_assoc, split_rxns, self.empty_dict = \ + mm.make_irreversible(self._assoc, + exclude_list=['ex_A', 'rxn_6', 'rxn_7']) + self.assertEqual( + mm_irreversible.limits['rxn_3_forward'].bounds, (0, 1000)) + self.assertEqual( + mm_irreversible.limits['rxn_3_reverse'].bounds, (0, 0)) + mm.limits['rxn_3'].lower = -1000 + mm.limits['rxn_3'].upper = 0 + mm_irreversible, reversible_gene_assoc, split_rxns, self.empty_dict = \ + mm.make_irreversible(self._assoc, + exclude_list=['ex_A', 'rxn_6', 'rxn_7']) + self.assertEqual( + mm_irreversible.limits['rxn_3_forward'].bounds, (0, 0)) + self.assertEqual( + mm_irreversible.limits['rxn_3_reverse'].bounds, (0, 1000)) + + def test_all_reverse_model(self): + test_associations = { + 'rxn_1_forward': str('gene_1'), + 'rxn_1_reverse': str('gene_1'), + 'rxn_3_forward': str('gene_5'), + 'rxn_3_reverse': str('gene_5'), + 'rxn_4_forward': str('gene_3 or gene_4'), + 'rxn_4_reverse': str('gene_3 or gene_4'), + } + mm_irreversible, reversible_gene_assoc, split_rxns, self.empty_dict = \ + self._mm.make_irreversible( + self._assoc, + exclude_list=['ex_A', 'rxn_2', 'rxn_5', 'rxn_6', 'rxn_7'], + all_reversible=True) + self.assertEqual(split_rxns, set([('rxn_1_forward', 'rxn_1_reverse'), + ('rxn_4_forward', 'rxn_4_reverse'), + ('rxn_3_forward', 'rxn_3_reverse')])) + self.assertEqual(reversible_gene_assoc, test_associations) + self.assertEqual(set([i for i in mm_irreversible.reactions]), + {'rxn_1_forward', 'rxn_1_reverse', 'rxn_2', + 'rxn_3_forward', 'rxn_3_reverse', + 'rxn_4_forward', 'rxn_4_reverse', 'rxn_5', + 'rxn_6', 'rxn_7', 'ex_A'}) + + def test_parse_transcriptome_file(self): + f = ['gene\texpression', 'gene_1\t15', 'gene_2\t20', + 'gene_3\t15', 'gene_4\t25', 'gene_5\t10', 'gene_6\t25'] + d = gimme.parse_transcriptome_file(f, 20) + self.assertEqual(d, {'gene_1': 5.0, 'gene_3': 5.0, 'gene_5': 10.0}) + + def test_get_rxn_value(self): + mm_irreversible, reversible_gene_assoc, split_rxns, self.empty_dict =\ + self._mm.make_irreversible( + self._assoc, + exclude_list=['ex_A', 'rxn_6']) + f = ['gene\texpression', 'gene_1\t15', 'gene_2\t20', + 'gene_3\t15', 'gene_4\t10', 'gene_5\t10', 'gene_6\t25'] + d = gimme.parse_transcriptome_file(f, 20) + root_single = gimme.get_rxn_value(boolean.Expression( + reversible_gene_assoc['rxn_1'])._root, d) + self.assertEqual(root_single, 5) + + root_and = gimme.get_rxn_value(boolean.Expression( + reversible_gene_assoc['rxn_5'])._root, d) + self.assertEqual(root_and, 10) + + root_or = gimme.get_rxn_value(boolean.Expression( + reversible_gene_assoc['rxn_4_forward'])._root, d) + self.assertEqual(root_or, 5) + + root_none = gimme.get_rxn_value(boolean.Expression( + reversible_gene_assoc['rxn_2'])._root, d) + self.assertEqual(root_none, None) + + def test_gimme_model(self): + f = ['gene\texpression', 'gene_1\t15', 'gene_2\t20', + 'gene_3\t15', 'gene_4\t25', 'gene_5\t10', 'gene_6\t25'] + threshold_dict = gimme.parse_transcriptome_file(f, 20) + mm_irreversible, reversible_gene_assoc, split_rxns, self.empty_dict = \ + self._mm.make_irreversible( + self._assoc, + exclude_list=['ex_A', 'rxn_6']) + p = fluxanalysis.FluxBalanceProblem(mm_irreversible, generic.Solver()) + final_model, used_exchange, below_threshold_ids, incon_score = \ + gimme.solve_gimme_problem( + p, mm_irreversible, 'rxn_6', + reversible_gene_assoc, split_rxns, threshold_dict, + MaybeRelative(20)) + self.assertEqual(incon_score, 100) + self.assertEqual(final_model, set(['rxn_1', 'rxn_2', 'rxn_4'])) + self.assertEqual(below_threshold_ids, set(['rxn_1', 'rxn_3', 'rxn_5'])) + + def test_gimme_model_relative(self): + f = ['gene\texpression', 'gene_1\t15', 'gene_2\t20', + 'gene_3\t15', 'gene_4\t30', 'gene_5\t10', 'gene_6\t25'] + threshold_dict = gimme.parse_transcriptome_file(f, 20) + mm_irreversible, reversible_gene_assoc, split_rxns, self.empty_dict = \ + self._mm.make_irreversible( + self._assoc, + exclude_list=['ex_A', 'rxn_6']) + p = fluxanalysis.FluxBalanceProblem(mm_irreversible, generic.Solver()) + final_model, used_exchange, below_threshold_ids, incon_score = \ + gimme.solve_gimme_problem( + p, mm_irreversible, 'rxn_6', + reversible_gene_assoc, split_rxns, threshold_dict, + MaybeRelative('2%')) + self.assertEqual(incon_score, 100) + self.assertEqual(final_model, set(['rxn_1', 'rxn_2', 'rxn_4'])) + self.assertEqual(below_threshold_ids, set(['rxn_1', 'rxn_3', 'rxn_5'])) +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_vis.py",".py","58449","1254","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2018-2020 Ke Zhang +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2020 Elysha Sameth + +from __future__ import unicode_literals + +import unittest +import os +import tempfile + +from psamm.formula import Formula, Atom +from psamm.commands import vis +from psamm.reaction import Compound, Reaction, Direction +from collections import defaultdict +from psamm.datasource.reaction import parse_reaction, parse_compound +from psamm.datasource import entry +from psamm import graph +from psamm.datasource.native import NativeModel, ReactionEntry, CompoundEntry + + +# 2019-08-30 new test cases for vis +class TestMakeSubset(unittest.TestCase): + def setUp(self): + native_model = NativeModel() + native_model.reactions.add_entry(ReactionEntry({ + 'id': 'rxn1', 'equation': parse_reaction( + 'fum[c] + h2o[c] <=> mal_L[c]')})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'fum', 'formula': parse_compound('C4H2O4', 'c')})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'h2o', 'formula': parse_compound('H2O', 'c')})) + native_model.compounds.add_entry(CompoundEntry( + {'id': 'mal_L', 'formula': parse_compound('C4H4O5', 'c')})) + native_model.reactions.add_entry(ReactionEntry({ + 'id': 'rxn2', 'equation': parse_reaction( + 'q8[c] + succ[c] => fum[c] + q8h2[c]')})) + native_model.compounds.add_entry(CompoundEntry( + {'id': 'q8', 'formula': parse_compound('C49H74O4', 'c')})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'q8h2', 'formula': parse_compound('C49H76O4', 'c')})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'succ', 'formula': parse_compound('C4H4O4', 'c')})) + native_model.reactions.add_entry(ReactionEntry({ + 'id': 'rxn3', 'equation': parse_reaction( + 'h2o[c] <=> h2o[e]')})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'h2o', 'formula': parse_compound('H2O', 'c')})) + self.native = native_model + self.mm = native_model.create_metabolic_model() + self.sub = None + self.exclude = [] + + def test1_no_subset(self): + subset = vis.rxnset_for_vis(self.mm, self.sub, self.exclude) + self.assertEqual(subset, set(['rxn1', 'rxn2', 'rxn3'])) + + def test2_subset_reactions(self): + path = os.path.join(tempfile.mkdtemp(), 'subset') + with open(path, 'w') as f: + f.write('{}\n{}'.format('rxn1', 'rxn2')) + sub_file = open(path, 'r') + subset = vis.rxnset_for_vis(self.mm, sub_file, self.exclude) + sub_file.close() + self.assertEqual(subset, set(['rxn1', 'rxn2'])) + + def test3_subset_one_compound1(self): + path = os.path.join(tempfile.mkdtemp(), 'subset') + with open(path, 'w') as f: + f.write('{}'.format('mal_L[c]')) + sub_file = open(path, 'r') + subset = vis.rxnset_for_vis(self.mm, sub_file, self.exclude) + sub_file.close() + self.assertEqual(subset, set(['rxn1'])) + + def test4_subset_one_compound2(self): + path = os.path.join(tempfile.mkdtemp(), 'subset') + with open(path, 'w') as f: + f.write('{}'.format('fum[c]')) + sub_file = open(path, 'r') + subset = vis.rxnset_for_vis(self.mm, sub_file, self.exclude) + sub_file.close() + self.assertEqual(subset, set(['rxn1', 'rxn2'])) + + def test5_subset_compound3(self): + path = os.path.join(tempfile.mkdtemp(), 'subset') + with open(path, 'w') as f: + f.write('{}'.format('h2o[c]')) + sub_file = open(path, 'r') + subset = vis.rxnset_for_vis(self.mm, sub_file, self.exclude) + sub_file.close() + self.assertEqual(subset, set(['rxn1', 'rxn3'])) + + def test6_mixed_subset(self): + path = os.path.join(tempfile.mkdtemp(), 'subset') + with open(path, 'w') as f: + f.write('{}\n{}'.format('h2o[c]', 'rxn1')) + sub_file = open(path, 'r') + self.assertRaises(ValueError, vis.rxnset_for_vis, + self.mm, sub_file, self.exclude) + + def test7_not_in_model(self): + path = os.path.join(tempfile.mkdtemp(), 'subset') + with open(path, 'w') as f: + f.write('{}'.format('h3o')) + sub_file = open(path, 'r') + self.assertRaises(ValueError, vis.rxnset_for_vis, + self.mm, sub_file, self.exclude) + + def test8_exclude(self): + exclude = ['rxn3'] + subset = vis.rxnset_for_vis(self.mm, self.sub, exclude) + self.assertEqual(subset, set(['rxn1', 'rxn2'])) + + def test9_exclude_mult(self): + exclude = ['rxn1', 'rxn3'] + subset = vis.rxnset_for_vis(self.mm, self.sub, exclude) + self.assertEqual(subset, set(['rxn2'])) + + +class TestAddNodeProps(unittest.TestCase): + def setUp(self): + self.cpd_a = CompoundEntry({ + 'id': 'A', 'name': 'compound A', 'formula': 'XXXX', 'charge': 0}) + self.cpd_b = CompoundEntry({ + 'id': 'B', 'name': 'compound B', 'formula': 'YYYY', 'charge': 0}) + self.cpd_c = CompoundEntry({ + 'id': 'C', 'name': 'compound C', 'formula': 'ZZZZ', 'charge': 0}) + self.cpd_d = CompoundEntry({ + 'id': 'D', 'name': 'compound D', 'formula': 'MMMM', 'charge': 0}) + self.cpd_e = CompoundEntry({ + 'id': 'E', 'name': 'compound E', 'formula': 'NNNN', 'charge': 0}) + + # new rxn used to test: rxn1: A => B; rxn2: A => B; rxn3: C <=> B + D + self.rxn1 = entry.DictReactionEntry({ + 'id': 'rxn1', 'name': 'Reaction 1', 'genes': 'gene1 and gene2', + 'equation': Reaction( + Direction.Forward, {Compound('A', 'c'): -1, + Compound('B', 'c'): 1}), + }) + self.rxn2 = entry.DictReactionEntry({ + 'id': 'rxn2', 'name': 'Reaction 2', 'genes': 'gene3', + 'equation': Reaction(Direction.Forward, { + Compound('A', 'c'): -1, Compound('B', 'c'): 1}) + }) + self.rxn3 = entry.DictReactionEntry({ + 'id': 'rxn3', 'name': 'Reaction 3', + 'equation': Reaction(Direction.Both, { + Compound('C', 'c'): -1, Compound('B', 'c'): 1, + Compound('D', 'c'): 1}) + }) + + self.node_a = graph.Node({ + 'id': 'A[c]', 'entry': [self.cpd_a], + 'type': 'cpd', 'compartment': 'c'}) + self.node_b = graph.Node({ + 'id': 'B[c]', 'entry': [self.cpd_b], + 'type': 'cpd', 'compartment': 'c'}) + self.node_c = graph.Node({ + 'id': 'C[c]', 'entry': [self.cpd_c], + 'type': 'cpd', 'compartment': 'c'}) + self.node_d = graph.Node({ + 'id': 'D[c]', 'entry': [self.cpd_d], + 'type': 'cpd', 'compartment': 'c'}) + self.node_ab = graph.Node({ + 'id': 'rxn1_1, rxn2_1', 'entry': [self.rxn1, self.rxn2], + 'compartment': 'c', 'type': 'rxn'}) + self.node_cb = graph.Node({ + 'id': 'rxn3_1', 'entry': [self.rxn3], 'compartment': 'c', + 'type': 'rxn'}) + + self.edge1 = graph.Edge(self.node_a, self.node_ab, {'dir': 'forward'}) + self.edge2 = graph.Edge(self.node_ab, self.node_b, {'dir': 'forward'}) + self.edge3 = graph.Edge(self.node_c, self.node_cb, {'dir': 'both'}) + self.edge4 = graph.Edge(self.node_cb, self.node_b, {'dir': 'both'}) + self.edge5 = graph.Edge(self.node_cb, self.node_d, {'dir': 'both'}) + + self.g = graph.Graph() + self.node_list = [self.node_a, self.node_b, self.node_c, self.node_d, + self.node_ab, self.node_cb] + for node in self.node_list: + self.g.add_node(node) + self.edge_list = [self.edge1, self.edge2, + self.edge3, self.edge4, self.edge5] + for edge in self.edge_list: + self.g.add_edge(edge) + + self.recolor_dict = {'A': '#f4fc55', 'rxn1': '#ef70de', + 'rxn3': '#64b3f4'} + + def test1_DefaultRecolor(self): + g1 = vis.add_node_props(self.g, {}) + node_a = graph.Node({ + 'id': 'A[c]', 'entry': [self.cpd_a], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + node_b = graph.Node({ + 'id': 'B[c]', 'entry': [self.cpd_b], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + node_c = graph.Node({ + 'id': 'C[c]', 'entry': [self.cpd_c], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + node_d = graph.Node({ + 'id': 'D[c]', 'entry': [self.cpd_d], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + node_ab = graph.Node({ + 'id': 'rxn1_1, rxn2_1', 'entry': [self.rxn1, self.rxn2], + 'compartment': 'c', 'type': 'rxn', 'style': 'filled', + 'shape': 'box', 'fillcolor': '#c9fccd'}) + node_cb = graph.Node({ + 'id': 'rxn3_1', 'entry': [self.rxn3], + 'compartment': 'c', 'type': 'rxn', + 'style': 'filled', 'shape': 'box', + 'fillcolor': '#c9fccd'}) + node_list = [node_a, node_b, node_c, node_d, node_ab, node_cb] + self.assertTrue(all(i in node_list for i in g1.nodes)) + self.assertTrue(all(i in g1.nodes for i in node_list)) + + def test2_Recolor(self): + g2 = vis.add_node_props(self.g, self.recolor_dict) + node_a = graph.Node({ + 'id': 'A[c]', 'entry': [self.cpd_a], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#f4fc55'}) + node_b = graph.Node({ + 'id': 'B[c]', 'entry': [self.cpd_b], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + node_c = graph.Node({ + 'id': 'C[c]', 'entry': [self.cpd_c], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + node_d = graph.Node({ + 'id': 'D[c]', 'entry': [self.cpd_d], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + node_ab = graph.Node({ + 'id': 'rxn1_1, rxn2_1', 'entry': [self.rxn1, self.rxn2], + 'compartment': 'c', 'type': 'rxn', 'style': 'filled', + 'shape': 'box', 'fillcolor': '#c9fccd'}) + node_cb = graph.Node({ + 'id': 'rxn3_1', 'entry': [self.rxn3], + 'compartment': 'c', 'type': 'rxn', + 'style': 'filled', 'shape': 'box', + 'fillcolor': '#64b3f4'}) + node_list = [node_a, node_b, node_c, node_d, node_ab, node_cb] + self.assertTrue(all(i in node_list for i in g2.nodes)) + self.assertTrue(all(i in g2.nodes for i in node_list)) + + def test3_ConflictRecolorDict(self): + recolor_dict = {'A': '#f4fc55', 'rxn1': '#ef70de', 'rxn2': '#64b3f4'} + g3 = vis.add_node_props(self.g, recolor_dict) + node_a = graph.Node({ + 'id': 'A[c]', 'entry': [self.cpd_a], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#f4fc55'}) + node_b = graph.Node({ + 'id': 'B[c]', 'entry': [self.cpd_b], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + node_c = graph.Node({ + 'id': 'C[c]', 'entry': [self.cpd_c], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + node_d = graph.Node({ + 'id': 'D[c]', 'entry': [self.cpd_d], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + node_ab = graph.Node({ + 'id': 'rxn1_1, rxn2_1', 'entry': [self.rxn1, self.rxn2], + 'compartment': 'c', 'type': 'rxn', 'style': 'filled', + 'shape': 'box', 'fillcolor': '#c9fccd'}) + node_cb = graph.Node({ + 'id': 'rxn3_1', 'entry': [self.rxn3], + 'compartment': 'c', 'type': 'rxn', + 'style': 'filled', 'shape': 'box', + 'fillcolor': '#c9fccd'}) + node_list = [node_a, node_b, node_c, node_d, node_ab, node_cb] + self.assertTrue(all(i in node_list for i in g3.nodes)) + self.assertTrue(all(i in g3.nodes for i in node_list)) + + +class TestAddNodeLabel(unittest.TestCase): + def setUp(self): + self.cpd_a = CompoundEntry({ + 'id': 'A', 'name': 'compound A', 'formula': 'XXXX', 'charge': 0}) + self.cpd_b = CompoundEntry({ + 'id': 'B', 'name': 'compound B', 'formula': 'YYYY', 'charge': 0}) + self.cpd_c = CompoundEntry({ + 'id': 'C', 'name': 'compound C', 'formula': 'ZZZZ', 'charge': 0}) + self.cpd_d = CompoundEntry({ + 'id': 'D', 'name': 'compound D', 'formula': 'MMMM', 'charge': 0}) + # self.cpd_e = CompoundEntry({ + # 'id': 'E', 'name': 'compound E', 'formula': 'NNNN', 'charge': 0}) + + # new rxn used to test: rxn1: A => B; rxn2: A => B; rxn3: C <=> B + D + self.rxn1 = entry.DictReactionEntry({ + 'id': 'rxn1', 'name': 'Reaction 1', 'genes': 'gene1 and gene2', + 'equation': Reaction( + Direction.Forward, {Compound('A', 'c'): -1, + Compound('B', 'c'): 1}), + }) + self.rxn2 = entry.DictReactionEntry({ + 'id': 'rxn2', 'name': 'Reaction 2', + 'equation': Reaction(Direction.Forward, { + Compound('A', 'c'): -1, Compound('B', 'c'): 1}) + }) + self.rxn3 = entry.DictReactionEntry({ + 'id': 'rxn3', 'name': 'Reaction 3', 'genes': 'gene3', + 'equation': Reaction(Direction.Both, { + Compound('C', 'c'): -1, Compound('B', 'c'): 1, + Compound('D', 'c'): 1}) + }) + + self.node_a = graph.Node({ + 'id': 'A[c]', 'entry': [self.cpd_a], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + self.node_b = graph.Node({ + 'id': 'B[c]', 'entry': [self.cpd_b], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + self.node_c = graph.Node({ + 'id': 'C[c]', 'entry': [self.cpd_c], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + self.node_d = graph.Node({ + 'id': 'D[c]', 'entry': [self.cpd_d], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf'}) + self.node_ab = graph.Node({ + 'id': 'rxn1_1, rxn2_1', 'entry': [self.rxn1, self.rxn2], + 'compartment': 'c', 'type': 'rxn', 'style': 'filled', + 'shape': 'box', 'fillcolor': '#c9fccd'}) + self.node_cb = graph.Node({ + 'id': 'rxn3_1', 'entry': [self.rxn3], + 'compartment': 'c', 'type': 'rxn', + 'style': 'filled', 'shape': 'box', + 'fillcolor': '#c9fccd'}) + self.edge1 = graph.Edge(self.node_a, self.node_ab, {'dir': 'forward'}) + self.edge2 = graph.Edge(self.node_ab, self.node_b, {'dir': 'forward'}) + self.edge3 = graph.Edge(self.node_c, self.node_cb, {'dir': 'both'}) + self.edge4 = graph.Edge(self.node_cb, self.node_b, {'dir': 'both'}) + self.edge5 = graph.Edge(self.node_cb, self.node_d, {'dir': 'both'}) + + self.g = graph.Graph() + node_list = [self.node_a, self.node_b, + self.node_c, self.node_d, self.node_ab, self.node_cb] + # node_list = [a, b, c, d, ab, cb] + for node in node_list: + self.g.add_node(node) + edge_list = [self.edge1, self.edge2, + self.edge3, self.edge4, self.edge5] + for edge in edge_list: + self.g.add_edge(edge) + + def test1_detail_default(self): + """"""test vis codes when both --cpd-detail and --rxn-detail are None"""""" + g1 = vis.add_node_label(self.g, None, None) + # self.node_a.props['label'] = 'A[c]' + # self.node_b.props['label'] = 'B[c]' + # self.node_c.props['label'] = 'C[c]' + # self.node_d.props['label'] = 'D[c]' + # self.node_ab.props['label'] = 'rxn1\nrxn2' + # self.node_cb.props['label'] = 'rxn3\nReaction 3' + # node_list_1 = [self.node_a, self.node_b, self.node_c, self.node_d, + # self.node_ab, self.node_cb] + + a = graph.Node({ + 'id': 'A[c]', 'entry': [self.cpd_a], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'A[c]'}) + b = graph.Node({ + 'id': 'B[c]', 'entry': [self.cpd_b], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'B[c]'}) + c = graph.Node({ + 'id': 'C[c]', 'entry': [self.cpd_c], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'C[c]'}) + d = graph.Node({ + 'id': 'D[c]', 'entry': [self.cpd_d], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'D[c]'}) + ab = graph.Node({ + 'id': 'rxn1_1, rxn2_1', 'entry': [self.rxn1, self.rxn2], + 'compartment': 'c', 'type': 'rxn', 'style': 'filled', + 'shape': 'box', 'fillcolor': '#c9fccd', 'label': 'rxn1\nrxn2'}) + cb = graph.Node({ + 'id': 'rxn3_1', 'entry': [self.rxn3], + 'compartment': 'c', 'type': 'rxn', + 'style': 'filled', 'shape': 'box', + 'fillcolor': '#c9fccd', 'label': 'rxn3'}) + node_list_1 = [a, b, c, d, ab, cb] + # for i in g1.nodes: + # print('in g1:', i.props) + # if i not in node_list_1: + # print('in g1 but not in node_list:', i) + # for j in node_list_1: + # print('in node list:', j.props) + self.assertTrue(all(i in node_list_1 for i in g1.nodes)) + self.assertTrue(all(i in g1.nodes for i in node_list_1)) + + def test2_detail_id_name(self): + """"""test vis codes when both --cpd-detail + and --rxn-detail are ['id', 'name']"""""" + g2 = vis.add_node_label(self.g, [['id', 'name']], [['id', 'name']]) + # self.node_a.props['label'] = 'A[c]\ncompound A' + # self.node_b.props['label'] = 'B[c]\ncompound B' + # self.node_c.props['label'] = 'C[c]\ncompound C' + # self.node_d.props['label'] = 'D[c]\ncompound D' + # self.node_ab.props['label'] = 'rxn1\nrxn2' + # self.node_cb.props['label'] = 'rxn3\nReaction 3' + # node_list_2 = [self.node_a, self.node_b, self.node_c, self.node_d, + # self.node_ab, self.node_cb] + + a = graph.Node({ + 'id': 'A[c]', 'entry': [self.cpd_a], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'A[c]\ncompound A'}) + b = graph.Node({ + 'id': 'B[c]', 'entry': [self.cpd_b], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'B[c]\ncompound B'}) + c = graph.Node({ + 'id': 'C[c]', 'entry': [self.cpd_c], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'C[c]\ncompound C'}) + d = graph.Node({ + 'id': 'D[c]', 'entry': [self.cpd_d], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'D[c]\ncompound D'}) + ab = graph.Node({ + 'id': 'rxn1_1, rxn2_1', 'entry': [self.rxn1, self.rxn2], + 'compartment': 'c', 'type': 'rxn', 'style': 'filled', + 'shape': 'box', 'fillcolor': '#c9fccd', 'label': 'rxn1\nrxn2'}) + cb = graph.Node({ + 'id': 'rxn3_1', 'entry': [self.rxn3], + 'compartment': 'c', 'type': 'rxn', + 'style': 'filled', 'shape': 'box', + 'fillcolor': '#c9fccd', 'label': 'rxn3\nReaction 3'}) + node_list_2 = [a, b, c, d, ab, cb] + for i in g2.nodes: + if i not in node_list_2: + print('not in node_list :', i, i.props) + self.assertTrue(all(i in node_list_2 for i in g2.nodes)) + self.assertTrue(all(i in g2.nodes for i in node_list_2)) + + def test3_id_formula_genes(self): + """"""test vis codes when --cpd-detail and + --rxn-detail are ['id', 'formula', 'genes']"""""" + g3 = vis.add_node_label(self.g, [['id', 'formula', 'genes']], + [['id', 'formula', 'genes']]) + # self.node_a.props['label'] = 'A[c]\ncompound A' + # self.node_b.props['label'] = 'B[c]\ncompound B' + # self.node_c.props['label'] = 'C[c]\ncompound C' + # self.node_d.props['label'] = 'D[c]\ncompound D' + # self.node_ab.props['label'] = 'rxn1\nrxn2' + # self.node_cb.props['label'] = 'rxn3\nReaction 3' + # node_list_2 = [self.node_a, self.node_b, self.node_c, self.node_d, + # self.node_ab, self.node_cb] + + a = graph.Node({ + 'id': 'A[c]', 'entry': [self.cpd_a], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'A[c]\nXXXX'}) + b = graph.Node({ + 'id': 'B[c]', 'entry': [self.cpd_b], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'B[c]\nYYYY'}) + c = graph.Node({ + 'id': 'C[c]', 'entry': [self.cpd_c], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'C[c]\nZZZZ'}) + d = graph.Node({ + 'id': 'D[c]', 'entry': [self.cpd_d], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'D[c]\nMMMM'}) + ab = graph.Node({ + 'id': 'rxn1_1, rxn2_1', 'entry': [self.rxn1, self.rxn2], + 'compartment': 'c', 'type': 'rxn', 'style': 'filled', + 'shape': 'box', 'fillcolor': '#c9fccd', 'label': 'rxn1\nrxn2'}) + cb = graph.Node({ + 'id': 'rxn3_1', 'entry': [self.rxn3], + 'compartment': 'c', 'type': 'rxn', + 'style': 'filled', 'shape': 'box', + 'fillcolor': '#c9fccd', 'label': 'rxn3\ngene3'}) + node_list_3 = [a, b, c, d, ab, cb] + self.assertTrue(all(i in node_list_3 for i in g3.nodes)) + self.assertTrue(all(i in g3.nodes for i in node_list_3)) + + def test4_noID(self): + """"""test vis codes when 'id' is not in --cpd-detail and --rxn-detail"""""" + g4 = vis.add_node_label(self.g, [['name', 'genes']], + [['name', 'formula', 'genes']]) + # self.node_a.props['label'] = 'A[c]\ncompound A' + # self.node_b.props['label'] = 'B[c]\ncompound B' + # self.node_c.props['label'] = 'C[c]\ncompound C' + # self.node_d.props['label'] = 'D[c]\ncompound D' + # self.node_ab.props['label'] = 'rxn1\nrxn2' + # self.node_cb.props['label'] = 'rxn3\nReaction 3' + # node_list_2 = [self.node_a, self.node_b, self.node_c, self.node_d, + # self.node_ab, self.node_cb] + + a = graph.Node({ + 'id': 'A[c]', 'entry': [self.cpd_a], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'compound A'}) + b = graph.Node({ + 'id': 'B[c]', 'entry': [self.cpd_b], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'compound B'}) + c = graph.Node({ + 'id': 'C[c]', 'entry': [self.cpd_c], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'compound C'}) + d = graph.Node({ + 'id': 'D[c]', 'entry': [self.cpd_d], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'compound D'}) + ab = graph.Node({ + 'id': 'rxn1_1, rxn2_1', 'entry': [self.rxn1, self.rxn2], + 'compartment': 'c', 'type': 'rxn', 'style': 'filled', + 'shape': 'box', 'fillcolor': '#c9fccd', 'label': 'rxn1\nrxn2'}) + cb = graph.Node({ + 'id': 'rxn3_1', 'entry': [self.rxn3], + 'compartment': 'c', 'type': 'rxn', + 'style': 'filled', 'shape': 'box', + 'fillcolor': '#c9fccd', 'label': 'Reaction 3\ngene3'}) + node_list_4 = [a, b, c, d, ab, cb] + self.assertTrue(all(i in node_list_4 for i in g4.nodes)) + self.assertTrue(all(i in g4.nodes for i in node_list_4)) + + def test5_(self): + """"""test vis codes when obly --cpd-detail is given """""" + g5 = vis.add_node_label(self.g, [['name', 'genes']], None) + # self.node_a.props['label'] = 'A[c]\ncompound A' + # self.node_b.props['label'] = 'B[c]\ncompound B' + # self.node_c.props['label'] = 'C[c]\ncompound C' + # self.node_d.props['label'] = 'D[c]\ncompound D' + # self.node_ab.props['label'] = 'rxn1\nrxn2' + # self.node_cb.props['label'] = 'rxn3\nReaction 3' + # node_list_2 = [self.node_a, self.node_b, self.node_c, self.node_d, + # self.node_ab, self.node_cb] + + a = graph.Node({ + 'id': 'A[c]', 'entry': [self.cpd_a], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'compound A'}) + b = graph.Node({ + 'id': 'B[c]', 'entry': [self.cpd_b], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'compound B'}) + c = graph.Node({ + 'id': 'C[c]', 'entry': [self.cpd_c], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'compound C'}) + d = graph.Node({ + 'id': 'D[c]', 'entry': [self.cpd_d], + 'type': 'cpd', 'compartment': 'c', + 'style': 'filled', 'shape': 'ellipse', + 'fillcolor': '#ffd8bf', 'label': 'compound D'}) + ab = graph.Node({ + 'id': 'rxn1_1, rxn2_1', 'entry': [self.rxn1, self.rxn2], + 'compartment': 'c', 'type': 'rxn', 'style': 'filled', + 'shape': 'box', 'fillcolor': '#c9fccd', 'label': 'rxn1\nrxn2'}) + cb = graph.Node({ + 'id': 'rxn3_1', 'entry': [self.rxn3], + 'compartment': 'c', 'type': 'rxn', + 'style': 'filled', 'shape': 'box', + 'fillcolor': '#c9fccd', 'label': 'rxn3'}) + node_list_5 = [a, b, c, d, ab, cb] + self.assertTrue(all(i in node_list_5 for i in g5.nodes)) + self.assertTrue(all(i in g5.nodes for i in node_list_5)) + + +class TestAddBiomassRnxs(unittest.TestCase): + def setUp(self): + cpd_a = CompoundEntry({ + 'id': 'A', 'name': 'compound A', 'formula': 'XXXX', 'charge': 0}) + cpd_b = CompoundEntry({ + 'id': 'B', 'name': 'compound B', 'formula': 'YYYY', 'charge': 0}) + cpd_c = CompoundEntry({ + 'id': 'C', 'name': 'compound C', 'formula': 'ZZZZ', 'charge': 0}) + cpd_d = CompoundEntry({ + 'id': 'D', 'name': 'compound D', 'formula': 'MMMM', 'charge': 0}) + rxn1 = entry.DictReactionEntry({ + 'id': 'rxn1', 'name': 'Reaction 1', 'genes': 'gene1 and gene2', + 'equation': Reaction( + Direction.Both, {Compound('A', 'c'): -1, + Compound('C', 'c'): 1}), + }) + + self.node_a = graph.Node({ + 'id': 'A[c]', 'shape': 'ellipse', 'style': 'filled', 'type': + 'cpd', 'entry': [cpd_a], 'compartment': 'c', + 'fillcolor': '#ffd8bf'}) + self.node_b = graph.Node({ + 'id': 'B[c]', 'shape': 'ellipse', 'style': 'filled', 'type': + 'cpd', 'entry': [cpd_b], 'compartment': 'c', + 'fillcolor': '#ffd8bf'}) + self.node_c = graph.Node({ + 'id': 'C[c]', 'shape': 'ellipse', 'style': 'filled', 'type': + 'cpd', 'entry': [cpd_c], 'compartment': 'c', + 'fillcolor': '#ffd8bf'}) + self.node_d = graph.Node({ + 'id': 'D[c]', 'shape': 'ellipse', 'style': 'filled', 'type': + 'cpd', 'entry': [cpd_d], 'compartment': 'c', + 'fillcolor': '#ffd8bf'}) + self.node_rxn1 = graph.Node({ + 'id': 'rxn1_1', 'shape': 'box', 'style': 'filled', 'type': 'rxn', + 'entry': [rxn1], 'compartment': 'c', 'fillcolor': '#c9fccd'}) + self.edge_A_rxn = graph.Edge(self.node_a, self.node_rxn1, + {'dir': 'both'}) + self.edge_C_rxn = graph.Edge(self.node_rxn1, self.node_c, + {'dir': 'both'}) + self.g = graph.Graph() + for node in [self.node_a, self.node_b, + self.node_c, self.node_d, self.node_rxn1]: + self.g.add_node(node) + self.g.add_edge(self.edge_A_rxn) + self.g.add_edge(self.edge_C_rxn) + + self.biorxn = ReactionEntry({ + 'id': 'test_bio', 'name': 'biomass_equatin', 'equation': + parse_reaction('A[c] + B[c] => D[c]')}) + + def test1_addBiorxn_default(self): + g1 = vis.add_biomass_rxns(self.g, self.biorxn) + bio_a = graph.Node({ + 'id': 'test_bio_1', 'entry': [self.biorxn], 'shape': 'box', + 'style': 'filled', 'label': 'test_bio', 'type': 'bio_rxn', + 'fillcolor': '#b3fcb8', 'compartment': 'c'}) + bio_b = graph.Node({ + 'id': 'test_bio_2', 'entry': [self.biorxn], 'shape': 'box', + 'style': 'filled', 'label': 'test_bio', 'type': 'bio_rxn', + 'fillcolor': '#b3fcb8', 'compartment': 'c'}) + bio_d = graph.Node({ + 'id': 'test_bio_3', 'entry': [self.biorxn], 'shape': 'box', + 'style': 'filled', 'label': 'test_bio', 'type': 'bio_rxn', + 'fillcolor': '#b3fcb8', 'compartment': 'c'}) + edge_bio_a = graph.Edge(self.node_a, bio_a, {'dir': 'forward'}) + edge_bio_b = graph.Edge(self.node_b, bio_b, {'dir': 'forward'}) + edge_bio_d = graph.Edge(bio_d, self.node_d, {'dir': 'forward'}) + + self.assertTrue(all(i in [self.node_a, self.node_b, + self.node_c, self.node_d, + self.node_rxn1, bio_a, bio_b, bio_d] + for i in g1.nodes)) + self.assertTrue(all(i in g1.nodes for i in [ + self.node_a, self.node_b, self.node_c, self.node_d, self.node_rxn1, + bio_a, bio_b, bio_d])) + + self.assertTrue(all(i in [self.edge_A_rxn, self.edge_C_rxn, edge_bio_a, + edge_bio_b, edge_bio_d] for i in g1.edges)) + self.assertTrue(all(i in g1.edges for i in [ + self.edge_A_rxn, self.edge_C_rxn, + edge_bio_a, edge_bio_b, edge_bio_d])) + + def test2_TwoCpdsRight(self): + biorxn = ReactionEntry({ + 'id': 'test_bio', 'name': 'biomass_equatin', + 'equation': parse_reaction('A[c] + B[c] => C[c] + D[c]')}) + g2 = vis.add_biomass_rxns(self.g, biorxn) + bio_a = graph.Node({ + 'id': 'test_bio_1', 'entry': [biorxn], 'shape': 'box', + 'style': 'filled', 'label': 'test_bio', 'type': 'bio_rxn', + 'fillcolor': '#b3fcb8', 'compartment': 'c'}) + bio_b = graph.Node({ + 'id': 'test_bio_2', 'entry': [biorxn], 'shape': 'box', + 'style': 'filled', 'label': 'test_bio', 'type': 'bio_rxn', + 'fillcolor': '#b3fcb8', 'compartment': 'c'}) + bio_c = graph.Node({ + 'id': 'test_bio_3', 'entry': [biorxn], 'shape': 'box', + 'style': 'filled', 'label': 'test_bio', 'type': 'bio_rxn', + 'fillcolor': '#b3fcb8', 'compartment': 'c'}) + bio_d = graph.Node({ + 'id': 'test_bio_4', 'entry': [biorxn], 'shape': 'box', + 'style': 'filled', 'label': 'test_bio', 'type': 'bio_rxn', + 'fillcolor': '#b3fcb8', 'compartment': 'c'}) + edge_bio_a = graph.Edge(self.node_a, bio_a, {'dir': 'forward'}) + edge_bio_b = graph.Edge(self.node_b, bio_b, {'dir': 'forward'}) + edge_bio_c = graph.Edge(bio_c, self.node_c, {'dir': 'forward'}) + edge_bio_d = graph.Edge(bio_d, self.node_d, {'dir': 'forward'}) + + final_nodes = [self.node_a, self.node_b, self.node_c, self.node_d, + self.node_rxn1, bio_a, bio_b, bio_c, bio_d] + final_edges = [self.edge_A_rxn, self.edge_C_rxn, edge_bio_a, + edge_bio_b, edge_bio_c, edge_bio_d] + self.assertTrue(all(i in final_nodes for i in g2.nodes)) + self.assertTrue(all(i in g2.nodes for i in final_nodes)) + self.assertTrue(all(i in final_edges for i in g2.edges)) + self.assertTrue(all(i in g2.edges for i in final_edges)) + + def test3_EmptyRight(self): + biorxn = ReactionEntry({ + 'id': 'test_bio', 'name': 'biomass_equatin', + 'equation': parse_reaction('A[c] + B[c] => ')}) + g3 = vis.add_biomass_rxns(self.g, biorxn) + bio_a = graph.Node({ + 'id': 'test_bio_1', 'entry': [biorxn], 'shape': 'box', + 'style': 'filled', 'label': 'test_bio', 'type': 'bio_rxn', + 'fillcolor': '#b3fcb8', 'compartment': 'c'}) + bio_b = graph.Node({ + 'id': 'test_bio_2', 'entry': [biorxn], 'shape': 'box', + 'style': 'filled', 'label': 'test_bio', 'type': 'bio_rxn', + 'fillcolor': '#b3fcb8', 'compartment': 'c'}) + edge_bio_a = graph.Edge(self.node_a, bio_a, {'dir': 'forward'}) + edge_bio_b = graph.Edge(self.node_b, bio_b, {'dir': 'forward'}) + final_nodes = [self.node_a, self.node_b, self.node_c, self.node_d, + self.node_rxn1, bio_a, bio_b] + final_edges = [self.edge_A_rxn, self.edge_C_rxn, + edge_bio_a, edge_bio_b] + self.assertTrue(all(i in final_nodes for i in g3.nodes)) + self.assertTrue(all(i in g3.nodes for i in final_nodes)) + self.assertTrue(all(i in final_edges for i in g3.edges)) + self.assertTrue(all(i in g3.edges for i in final_edges)) + + +class TestAddExchange(unittest.TestCase): + def setUp(self): + native_model = NativeModel() + native_model.reactions.add_entry(ReactionEntry({ + 'id': 'rxn1', 'equation': parse_reaction( + 'fum[c] + h2o[c] <=> mal_L[c]')})) + self.cpd_a = CompoundEntry({ + 'id': 'A', 'name': 'compound A', 'formula': 'CO2', 'charge': 0}) + cpd_c = CompoundEntry({ + 'id': 'C', 'name': 'compound C', 'formula': 'MNO', 'charge': 0}) + rxn1 = entry.DictReactionEntry({ + 'id': 'rxn1', 'name': 'Reaction 1', 'equation': Reaction( + Direction.Forward, {Compound('A', 'c'): -1, + Compound('C', 'c'): 1}) + }) + rxn2 = entry.DictReactionEntry({ + 'id': 'rxn2', 'name': 'Reaction 2', 'equation': Reaction( + Direction.Forward, {Compound('A', 'e'): -1, + Compound('A', 'c'): 1}), + }) + rxn3 = entry.DictReactionEntry({ + 'id': 'rxn3', 'name': 'Reaction 3', 'equation': Reaction( + Direction.Forward, {Compound('C', 'c'): 1, + Compound('C', 'e'): 1}), + }) + + node_a = graph.Node({ + 'id': 'A[c]', 'entry': [self.cpd_a], + 'compartment': 'c', 'type': 'cpd', + 'style': 'filled', 'shape': 'ellipse', 'fillcolor': '#ffd8bf', + 'label': 'A[c]'}) + node_c = graph.Node({ + 'id': 'C[c]', 'entry': [cpd_c], 'compartment': 'c', 'type': 'cpd', + 'style': 'filled', 'shape': 'ellipse', 'fillcolor': '#ffd8bf', + 'label': 'C[c]'}) + self.node_a_extracell = graph.Node({ + 'id': 'A[e]', 'entry': [self.cpd_a], + 'compartment': 'e', 'type': 'cpd', + 'style': 'filled', 'shape': 'ellipse', 'fillcolor': '#ffd8bf', + 'label': 'A[e]'}) + self.node_c_extracell = graph.Node({ + 'id': 'C[e]', 'entry': [cpd_c], 'compartment': 'e', 'type': 'cpd', + 'style': 'filled', 'shape': 'ellipse', 'fillcolor': '#ffd8bf', + 'label': 'C[e]'}) + node_ac = graph.Node({ + 'id': 'rxn1_1', 'shape': 'box', 'style': 'filled', 'type': 'rxn', + 'entry': [rxn1], 'compartment': 'c', + 'fillcolor': '#c9fccd', 'label': 'rxn1'}) + self.node_aa = graph.Node({ + 'id': 'rxn2_1', 'shape': 'box', 'style': 'filled', 'type': 'rxn', + 'entry': [rxn2], 'compartment': 'c', 'fillcolor': '#90f998', + 'label': 'rxn2'}) + node_cc = graph.Node({ + 'id': 'rxn3_1', 'shape': 'box', 'style': 'filled', 'type': 'rxn', + 'entry': [rxn3], 'compartment': 'e', 'fillcolor': '#90f998', + 'label': 'rxn3'}) + edge_a_r1 = graph.Edge(node_a, node_ac, {'dir': 'both'}) + edge_r1_c = graph.Edge(node_ac, node_c, {'dir': 'both'}) + self.edge_a_r2 = graph.Edge(self.node_a_extracell, + self.node_aa, {'dir': 'forward'}) + self.edge_r2_a = graph.Edge(self.node_aa, node_a, {'dir': 'forward'}) + edge_c_r3 = graph.Edge(self.node_c_extracell, node_cc, {'dir': 'back'}) + edge_r3_c = graph.Edge(node_cc, node_c, {'dir': 'back'}) + + self.g = graph.Graph() + self.edge_list = [edge_a_r1, edge_r1_c, self.edge_a_r2, self.edge_r2_a, + edge_c_r3, edge_r3_c] + self.node_list = [node_a, node_c, self.node_a_extracell, + self.node_c_extracell, node_ac, + self.node_aa, node_cc] + for node in self.node_list: + self.g.add_node(node) + for edge in self.edge_list: + self.g.add_edge(edge) + self.EX_A = Reaction(Direction.Both, {Compound('A', 'e'): -5}) + self.EX_C = Reaction(Direction.Both, {Compound('C', 'e'): 5}) + + def test1_addExrRxn_cpdA(self): + g1 = vis.add_exchange_rxns(self.g, 'test_EX_A', self.EX_A, + {'test_EX_A': ('solid', 1)}) + node_ex = graph.Node({ + 'id': 'test_EX_A', 'entry': [self.EX_A], 'shape': 'box', + 'style': 'filled', 'label': 'test_EX_A', 'type': 'Ex_rxn', + 'fillcolor': '#90f998', 'compartment': 'e'}) + edge_ex = graph.Edge(self.node_a_extracell, node_ex, + {'dir': 'both', 'style': 'solid', + 'penwidth': 1}) + self.node_list.append(node_ex) + self.edge_list.append(edge_ex) + + self.assertTrue(all(i in self.node_list for i in g1.nodes)) + self.assertTrue(all(i in g1.nodes for i in self.node_list)) + + self.assertTrue(all(i in self.edge_list for i in g1.edges)) + self.assertTrue(all(i in g1.edges for i in self.edge_list)) + + def test2_addExrRxn_right(self): + g2 = vis.add_exchange_rxns(self.g, 'test_EX_C', self.EX_C, + {'test_EX_C': ('solid', 1)}) + node_ex = graph.Node({ + 'id': 'test_EX_C', 'entry': [self.EX_C], 'shape': 'box', + 'style': 'filled', 'label': 'test_EX_C', 'type': 'Ex_rxn', + 'fillcolor': '#90f998', 'compartment': 'e'}) + edge_ex = graph.Edge(node_ex, self.node_c_extracell, + {'dir': 'both', 'style': 'solid', + 'penwidth': 1}) + self.node_list.append(node_ex) + self.edge_list.append(edge_ex) + + self.assertTrue(all(i in self.node_list for i in g2.nodes)) + self.assertTrue(all(i in g2.nodes for i in self.node_list)) + + self.assertTrue(all(i in self.edge_list for i in g2.edges)) + self.assertTrue(all(i in g2.edges for i in self.edge_list)) + + def test3_addExrCpd(self): + cpd_formula = {'A': Formula({Atom('O'): 2, Atom('C'): 1})} + mm_a = Compound('A', 'e') + new_node_a_extra = graph.Node({'id': 'A[e]', 'entry': [self.cpd_a], + 'compartment': 'e', 'type': 'cpd'}) + g_missA = graph.Graph() + node_list_missA = [n for n in self.node_list if n not in [ + self.node_aa, self.node_a_extracell]] + edge_list_missA = [e for e in self.edge_list if e not in [ + self.edge_a_r2, self.edge_r2_a]] + for node in node_list_missA: + g_missA.add_node(node) + for edge in edge_list_missA: + g_missA.add_edge(edge) + g3 = vis.add_ex_cpd(g_missA, mm_a, self.cpd_a, cpd_formula, 'C') + node_list_missA.append(new_node_a_extra) + + # for i in g3.nodes: + # print(i, i.props) + # print('fen ge') + # for i in node_list_missA: + # print(i, i.props) + + self.assertTrue(all(i in node_list_missA for i in g3.nodes)) + self.assertTrue(all(i in g3.nodes for i in node_list_missA)) + + self.assertTrue(all(i in edge_list_missA for i in g3.edges)) + self.assertTrue(all(i in g3.edges for i in edge_list_missA)) + + def test4_addExrCpd_noEle(self): + cpd_formula = {'A': Formula({Atom('O'): 2, Atom('C'): 1})} + mm_a = Compound('A', 'e') + + g_missA = graph.Graph() + node_list_missA = [n for n in self.node_list if n not in [ + self.node_aa, self.node_a_extracell]] + edge_list_missA = [e for e in self.edge_list if e not in [ + self.edge_a_r2, self.edge_r2_a]] + for node in node_list_missA: + g_missA.add_node(node) + for edge in edge_list_missA: + g_missA.add_edge(edge) + g4 = vis.add_ex_cpd(g_missA, mm_a, self.cpd_a, cpd_formula, 'N') + + self.assertTrue(all(i in node_list_missA for i in g4.nodes)) + self.assertTrue(all(i in g4.nodes for i in node_list_missA)) + + self.assertTrue(all(i in edge_list_missA for i in g4.edges)) + self.assertTrue(all(i in g4.edges for i in edge_list_missA)) + + def test5_addExrCpd_noFormula(self): + cpd_formula = {} + mm_a = Compound('A', 'e') + + g_missA = graph.Graph() + node_list_missA = [n for n in self.node_list if n not in [ + self.node_aa, self.node_a_extracell]] + edge_list_missA = [e for e in self.edge_list if e not in [ + self.edge_a_r2, self.edge_r2_a]] + for node in node_list_missA: + g_missA.add_node(node) + for edge in edge_list_missA: + g_missA.add_edge(edge) + g5 = vis.add_ex_cpd(g_missA, mm_a, self.cpd_a, cpd_formula, 'C') + + self.assertTrue(all(i in node_list_missA for i in g5.nodes)) + self.assertTrue(all(i in g5.nodes for i in node_list_missA)) + + self.assertTrue(all(i in edge_list_missA for i in g5.edges)) + self.assertTrue(all(i in g5.edges for i in edge_list_missA)) + + def test6_addExrCpd_EleNone(self): + cpd_formula = {'A': Formula({Atom('O'): 2, Atom('C'): 1})} + mm_a = Compound('A', 'e') + new_node_a_extra = graph.Node({'id': 'A[e]', 'entry': [self.cpd_a], + 'compartment': 'e', 'type': 'cpd'}) + g_missA = graph.Graph() + node_list_missA = [n for n in self.node_list if n not in [ + self.node_aa, self.node_a_extracell]] + edge_list_missA = [e for e in self.edge_list if e not in [ + self.edge_a_r2, self.edge_r2_a]] + for node in node_list_missA: + g_missA.add_node(node) + for edge in edge_list_missA: + g_missA.add_edge(edge) + g6 = vis.add_ex_cpd(g_missA, mm_a, self.cpd_a, cpd_formula, None) + node_list_missA.append(new_node_a_extra) + + self.assertTrue(all(i in node_list_missA for i in g6.nodes)) + self.assertTrue(all(i in g6.nodes for i in node_list_missA)) + + self.assertTrue(all(i in edge_list_missA for i in g6.edges)) + self.assertTrue(all(i in g6.edges for i in edge_list_missA)) + + +class TestMakeCptTree(unittest.TestCase): + def test1_if_e_inthemodel(self): + boundaries = [('c', 'e'), ('c', 'p'), ('e', 'p')] + extra = 'e' + c1, e1 = vis.make_cpt_tree(boundaries, extra) + c1_res = defaultdict(set) + c1_res['c'].add('e') + c1_res['c'].add('p') + c1_res['p'].add('e') + c1_res['p'].add('c') + c1_res['e'].add('c') + c1_res['e'].add('p') + e1_res = 'e' + self.assertEqual(c1, c1_res) + self.assertEqual(e1, e1_res) + + def test2_if_e_not_inthemodel(self): + boundaries = [('c', 'mi')] + extra = 'e' + c2, e2 = vis.make_cpt_tree(boundaries, extra) + c2_res = defaultdict(set) + c2_res['c'].add('mi') + c2_res['mi'].add('c') + e2_res = 'mi' + self.assertEqual(c2, c2_res) + self.assertEqual(e2, e2_res) + + def test3_if_e_not_inthemodel_cpmi(self): + boundaries = [('c', 'p'), ('c', 'mi')] + extra = 'e' + c3, e3 = vis.make_cpt_tree(boundaries, extra) + c3_res = defaultdict(set) + c3_res['c'].add('p') + c3_res['c'].add('mi') + c3_res['mi'].add('c') + c3_res['p'].add('c') + e3_res = 'p' + self.assertEqual(c3, c3_res) + self.assertEqual(e3, e3_res) + + +class TestGetCptBoundaries(unittest.TestCase): + def setUp(self): + native_model = NativeModel() + native_model.reactions.add_entry(ReactionEntry({ + 'id': 'rxn1', 'equation': parse_reaction('A[c] => A[e]')})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'A[c]', 'formula': parse_compound('formula_A', 'c')})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'A[e]', 'formula': parse_compound('formula_A', 'e')})) + native_model.reactions.add_entry(ReactionEntry({ + 'id': 'rxn2', 'equation': parse_reaction('B[e] <=> B[p]')})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'B[e]', 'formula': parse_compound('formula_B', 'e')})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'B[p]', 'formula': parse_compound('formula_B', 'p')})) + self.native = native_model + + def test1_default_setting(self): + e1_bound, e1_extra = vis.get_cpt_boundaries(self.native) + e1_bound_res = set() + e1_bound_res.add(('c', 'e')) + e1_bound_res.add(('e', 'p')) + e1_extra_res = 'e' + self.assertTrue(all(i in e1_bound for i in e1_bound_res)) + self.assertEqual(e1_extra, e1_extra_res) + + def test2_with_extra_defined(self): + self.native._properties['extracellular'] = 'p' + e2_bound, e2_extra = vis.get_cpt_boundaries(self.native) + e2_bound_res = set() + e2_bound_res.add(('c', 'e')) + e2_bound_res.add(('e', 'p')) + e2_extra_res = 'p' + self.assertTrue(all(i in e2_bound for i in e2_bound_res)) + self.assertEqual(e2_extra, e2_extra_res) + + def test3_e_notinmodel(self): + native_model = NativeModel() + native_model.reactions.add_entry(ReactionEntry({ + 'id': 'rxn1', 'equation': parse_reaction('A[c] => A[mi]')})) + e3_bound, e3_extra = vis.get_cpt_boundaries(native_model) + e3_bound_res = set() + e3_bound_res.add(('c', 'mi')) + e3_extra_res = 'e' + self.assertEqual(e3_bound, e3_bound_res) + self.assertEqual(e3_extra, e3_extra_res) + + def test4_cpt_boundaries_defined_in_model(self): + self.native.compartment_boundaries.add(('c', 'e')) + self.native.compartment_boundaries.add(('e', 'p')) + self.native.compartment_boundaries.add(('c', 'mi')) + e4_bound, e4_extra = vis.get_cpt_boundaries(self.native) + e4_bound_res = set() + e4_bound_res.add(('c', 'e')) + e4_bound_res.add(('e', 'p')) + e4_bound_res.add(('c', 'mi')) + e4_extra_res = 'e' + self.assertTrue(all(i in e4_bound for i in e4_bound_res)) + self.assertEqual(e4_extra, e4_extra_res) + + +class TestFlux(unittest.TestCase): + def setUp(self): + native_model = NativeModel() + native_model.reactions.add_entry(ReactionEntry({ + 'id': 'rxn1', 'equation': parse_reaction( + 'fum[c] + h2o[c] <=> mal_L[c]')})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'fum', 'formula': 'C4H2O4'})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'h2o', 'formula': 'H2O'})) + native_model.compounds.add_entry(CompoundEntry( + {'id': 'mal_L', 'formula': 'C4H4O5'})) + native_model.reactions.add_entry(ReactionEntry({ + 'id': 'rxn2', 'equation': parse_reaction( + 'q8[c] + succ[c] => fum[c] + q8h2[c]')})) + native_model.compounds.add_entry(CompoundEntry( + {'id': 'q8', 'formula': 'C49H74O4'})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'q8h2', 'formula': 'C49H76O4'})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'succ', 'formula': 'C4H4O4'})) + native_model.reactions.add_entry(ReactionEntry({ + 'id': 'rxn3', 'equation': parse_reaction( + 'h2o[c] <=> h2o[e]')})) + native_model.compounds.add_entry(CompoundEntry({ + 'id': 'h2o', 'formula': 'H2O'})) + self.native = native_model + self.mm = native_model.create_metabolic_model() + + def test1_neg_flux_fba(self): + reaction_dict = {'rxn1': (-20, 1)} + full_pairs_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + reaction_dict=reaction_dict, + analysis='fba') + self.assertEqual(Direction.Reverse, + full_pairs_dict[self.native.reactions['rxn1']][1]) + self.assertEqual('solid', style_flux_dict['rxn1'][0]) + self.assertEqual(5, style_flux_dict['rxn1'][1]) + + def test2_pos_flux_fba(self): + reaction_dict = {'rxn1': (10, 1)} + full_pairs_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + reaction_dict=reaction_dict, + analysis='fba') + self.assertEqual(Direction.Forward, + full_pairs_dict[self.native.reactions['rxn1']][1]) + self.assertEqual('solid', style_flux_dict['rxn1'][0]) + self.assertEqual(5, style_flux_dict['rxn1'][1]) + + def test3_0_flux_fba(self): + reaction_dict = {'rxn1': (0, 1)} + full_pairs_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + reaction_dict=reaction_dict, + analysis='fba') + self.assertEqual(Direction.Both, + full_pairs_dict[self.native.reactions['rxn1']][1]) + self.assertEqual('dotted', style_flux_dict['rxn1'][0]) + self.assertEqual(1, style_flux_dict['rxn1'][1]) + + def test4_neg_flux_fva(self): + reaction_dict = {'rxn1': (-10, 1)} + full_pairs_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + reaction_dict=reaction_dict, + analysis='fva') + self.assertEqual(Direction.Both, + full_pairs_dict[self.native.reactions['rxn1']][1]) + self.assertEqual('dotted', style_flux_dict['rxn2'][0]) + self.assertEqual(5, style_flux_dict['rxn1'][1]) + + def test5_pos_flux_neg_fva(self): + reaction_dict = {'rxn1': (-10, -10)} + full_pairs_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + reaction_dict=reaction_dict, + analysis='fva') + self.assertEqual(Direction.Reverse, + full_pairs_dict[self.native.reactions['rxn1']][1]) + self.assertEqual('solid', style_flux_dict['rxn1'][0]) + self.assertEqual(5, style_flux_dict['rxn1'][1]) + + def test6_pos_flux_pos_fva(self): + reaction_dict = {'rxn1': (10, 10)} + full_pairs_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + reaction_dict=reaction_dict, + analysis='fva') + self.assertEqual(Direction.Forward, + full_pairs_dict[self.native.reactions['rxn1']][1]) + self.assertEqual('solid', style_flux_dict['rxn1'][0]) + self.assertEqual(5, style_flux_dict['rxn1'][1]) + + def test7_lower_0_flux_fva(self): + reaction_dict = {'rxn1': (0, 10)} + full_pairs_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + reaction_dict=reaction_dict, + analysis='fva') + self.assertEqual(Direction.Forward, + full_pairs_dict[self.native.reactions['rxn1']][1]) + self.assertEqual('solid', style_flux_dict['rxn1'][0]) + self.assertEqual(1, style_flux_dict['rxn1'][1]) + + def test8_upper_0_flux_fva(self): + reaction_dict = {'rxn1': (-10, 0)} + full_pairs_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + reaction_dict=reaction_dict, + analysis='fva') + self.assertEqual(Direction.Reverse, + full_pairs_dict[self.native.reactions['rxn1']][1]) + self.assertEqual('solid', style_flux_dict['rxn1'][0]) + self.assertEqual(1, style_flux_dict['rxn1'][1]) + + def test9_both_0_flux_fva(self): + reaction_dict = {'rxn1': (0, 0)} + full_pairs_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + reaction_dict=reaction_dict, + analysis='fva') + self.assertEqual(Direction.Both, + full_pairs_dict[self.native.reactions['rxn1']][1]) + self.assertEqual('dotted', style_flux_dict['rxn1'][0]) + self.assertEqual(1, style_flux_dict['rxn1'][1]) + + def test10_mult_rxn_fba(self): + reaction_dict = {'rxn1': (2, 1), 'rxn2': (-4, 1), 'rxn3': (6, 1)} + full_pairs_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + reaction_dict=reaction_dict, + analysis='fba') + self.assertEqual(Direction.Forward, + full_pairs_dict[self.native.reactions['rxn1']][1]) + self.assertEqual(Direction.Reverse, + full_pairs_dict[self.native.reactions['rxn2']][1]) + self.assertEqual(Direction.Forward, + full_pairs_dict[self.native.reactions['rxn3']][1]) + self.assertEqual('solid', style_flux_dict['rxn1'][0]) + self.assertEqual('solid', style_flux_dict['rxn2'][0]) + self.assertEqual('solid', style_flux_dict['rxn3'][0]) + self.assertEqual(2.5, style_flux_dict['rxn1'][1]) + self.assertEqual(5, style_flux_dict['rxn2'][1]) + self.assertEqual(7.5, style_flux_dict['rxn3'][1]) + + def test11_mult_rxn_fva(self): + reaction_dict = {'rxn1': (0, 2), 'rxn2': (-4, 1), 'rxn3': (-1, -1)} + full_pairs_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + reaction_dict=reaction_dict, + analysis='fva') + self.assertEqual(Direction.Forward, + full_pairs_dict[self.native.reactions['rxn1']][1]) + self.assertEqual(Direction.Both, + full_pairs_dict[self.native.reactions['rxn2']][1]) + self.assertEqual(Direction.Reverse, + full_pairs_dict[self.native.reactions['rxn3']][1]) + self.assertEqual('solid', style_flux_dict['rxn1'][0]) + self.assertEqual('solid', style_flux_dict['rxn2'][0]) + self.assertEqual('solid', style_flux_dict['rxn3'][0]) + self.assertEqual(1, style_flux_dict['rxn1'][1]) + self.assertEqual(8, style_flux_dict['rxn2'][1]) + self.assertEqual(2, style_flux_dict['rxn3'][1]) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_datasource_kegg.py",".py","5274","145","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.datasource import kegg +from psamm.reaction import Reaction, Compound, Direction +from psamm.expression.affine import Expression + +from six import StringIO + + +class TestKEGGEntryParser(unittest.TestCase): + def setUp(self): + self.f = StringIO('\n'.join([ + 'ENTRY ID001', + 'NAME Test entry', + 'PROPERTY This is a multi-line', + ' property!', + '///', + 'ENTRY ID002', + 'NAME Another entry', + 'PROPERTY Single line property', + 'REFS ref1: abcdef', + ' ref2: defghi', + '///' + ])) + + def test_parse_entries(self): + entries = list(kegg.parse_kegg_entries(self.f)) + self.assertEqual(len(entries), 2) + + self.assertEqual(entries[0].properties, { + 'entry': ['ID001'], + 'name': ['Test entry'], + 'property': ['This is a multi-line', 'property!'] + }) + + self.assertEqual(entries[1].properties, { + 'entry': ['ID002'], + 'name': ['Another entry'], + 'property': ['Single line property'], + 'refs': [ + 'ref1: abcdef', + 'ref2: defghi' + ] + }) + + +class TestKEGGCompoundEntry(unittest.TestCase): + def test_minimal_compound_entry(self): + c = kegg.CompoundEntry(kegg.KEGGEntry({ + 'entry': ['C00001 Compound'] + })) + + self.assertEqual(c.id, 'C00001') + self.assertIsNone(c.properties['name']) + self.assertIsNone(c.filemark) + + def test_complete_compound_entry(self): + c = kegg.CompoundEntry(kegg.KEGGEntry({ + 'entry': ['C00001 Compound'], + 'name': ['H2O;', 'Water'], + 'reaction': ['R00001 R00002', 'R00003'], + 'enzyme': ['1.2.3.4 2.3.4.5', '7.6.50.4 2.1.-,-'], + 'formula': ['H2O'], + 'exact_mass': ['18.01'], + 'mol_weight': ['18.01'], + 'pathway': [ + 'map00001 First pathway', + 'map00002 Second pathway' + ], + 'dblinks': [ + 'CAS: 12345', + 'ChEBI: B2345' + ], + 'comment': ['This information is purely for testing!'] + })) + + self.assertEqual(c.id, 'C00001') + self.assertEqual(c.properties['name'], 'H2O') + self.assertEqual(c.properties['names'], ['H2O', 'Water']) + self.assertEqual( + c.properties['reactions'], ['R00001', 'R00002', 'R00003']) + self.assertEqual(c.properties['enzymes'], [ + '1.2.3.4', '2.3.4.5', '7.6.50.4', '2.1.-,-']) + self.assertEqual(c.properties['formula'], 'H2O') + self.assertAlmostEqual(c.properties['exact_mass'], 18.01) + self.assertAlmostEqual(c.properties['mol_weight'], 18.01) + self.assertEqual(c.properties['pathways'], [ + ('map00001', 'First pathway'), + ('map00002', 'Second pathway') + ]) + self.assertEqual(c.properties['dblinks'], [ + ('CAS', '12345'), ('ChEBI', 'B2345') + ]) + self.assertEqual( + c.properties['comment'], 'This information is purely for testing!') + + +class TestKEGGReactionParser(unittest.TestCase): + def test_kegg_parse(self): + r = kegg.parse_reaction('C00013 + C00001 <=> 2 C00009') + self.assertEqual( + r, Reaction(Direction.Both, + [(Compound('C00013'), 1), (Compound('C00001'), 1)], + [(Compound('C00009'), 2)])) + + def test_kegg_parse_with_count_expression(self): + r = kegg.parse_reaction('2n C00404 + n C00001 <=> (n+1) C02174') + self.assertEqual( + r, Reaction(Direction.Both, + [(Compound('C00404'), Expression('2n')), + (Compound('C00001'), Expression('n'))], + [(Compound('C02174'), Expression('n+1'))])) + + def test_kegg_parse_with_compound_argument(self): + r = kegg.parse_reaction('C00039(n) <=> C00013 + C00039(n+1)') + self.assertEqual( + r, Reaction(Direction.Both, + [(Compound('C00039', arguments=[Expression('n')]), 1)], + [(Compound('C00013'), 1), + (Compound('C00039', + arguments=[Expression('n+1')]), 1)])) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_gapfill.py",".py","3942","101","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.database import DictDatabase +from psamm.metabolicmodel import MetabolicModel +from psamm.datasource.reaction import parse_reaction +from psamm.lpsolver import generic +from psamm.gapfill import gapfind, gapfill, GapFillError +from psamm.reaction import Compound + + +class TestGapfind(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_4', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_5', parse_reaction('|D| <=> |E|')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver(integer=True) + except generic.RequirementsError: + self.skipTest('Unable to find an MILP solver for tests') + + def test_gapfind(self): + self.model.remove_reaction('rxn_4') + compounds = set(gapfind(self.model, self.solver, epsilon=0.1)) + self.assertEqual(compounds, {Compound('D'), Compound('E')}) + + def test_gapfill_add_reaction(self): + core = set(self.model.reactions) - {'rxn_4'} + blocked = {Compound('D'), Compound('E')} + + add, rev = gapfill( + self.model, core, blocked, {}, self.solver, epsilon=0.1) + self.assertEqual(set(rev), set()) + self.assertEqual(set(add), {'rxn_4'}) + + def test_gapfill_exclude_addition(self): + core = set(self.model.reactions) - {'rxn_4'} + blocked = {Compound('D'), Compound('E')} + exclude = {'rxn_4'} + + with self.assertRaises(GapFillError): + gapfill(self.model, core, blocked, exclude, self.solver, + epsilon=0.1) + + def test_gapfill_reverse_reaction(self): + self.model.database.set_reaction('rxn_4', parse_reaction('|D| => |C|')) + core = set(self.model.reactions) + blocked = {Compound('D'), Compound('E')} + + add, rev = gapfill( + self.model, core, blocked, {}, self.solver, epsilon=0.1, + allow_bounds_expansion=True) + self.assertEqual(set(rev), {'rxn_4'}) + self.assertEqual(set(add), set()) + + def test_gapfill_reverse_reaction_not_allowed(self): + self.model.database.set_reaction('rxn_4', parse_reaction('|D| => |C|')) + core = set(self.model.reactions) + blocked = {Compound('D'), Compound('E')} + + with self.assertRaises(GapFillError): + add, rev = gapfill( + self.model, core, blocked, {}, self.solver, epsilon=0.1) + + def test_gapfill_exclude_reversal(self): + self.model.database.set_reaction('rxn_4', parse_reaction('D => C')) + core = set(self.model.reactions) + blocked = {Compound('D'), Compound('E')} + exclude = {'rxn_4'} + + with self.assertRaises(GapFillError): + gapfill(self.model, core, blocked, exclude, self.solver, + epsilon=0.1) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_datasource_reaction.py",".py","7408","180","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest +from decimal import Decimal + +from six import text_type + +from psamm.reaction import Reaction, Compound, Direction +from psamm.datasource import reaction + + +class TestDefaultReactionParser(unittest.TestCase): + def test_reaction_parse(self): + r = reaction.parse_reaction( + '|H2O| + |PPi| => (2) |Phosphate| + (2) |H+|') + self.assertEqual(r, Reaction( + Direction.Forward, [(Compound('H2O'), 1), (Compound('PPi'), 1)], + [(Compound('Phosphate'), 2), (Compound('H+'), 2)])) + + def test_reaction_parse_space(self): + r = reaction.parse_reaction( + '(2) |Some compound[c]| <=> ' + 'abc[c] + |Some other compound| + (3) def') + self.assertEqual(r, Reaction( + Direction.Both, [(Compound('Some compound', 'c'), 2)], + [(Compound('abc', 'c'), 1), + (Compound('Some other compound'), 1), (Compound('def'), 3)])) + + def test_reaction_parse_with_decimal(self): + r = reaction.parse_reaction('|H2| + (0.5) |O2| => |H2O|') + self.assertEqual(r, Reaction( + Direction.Forward, + [(Compound('H2'), 1), (Compound('O2'), Decimal('0.5'))], + [(Compound('H2O'), 1)])) + + def test_reaction_parse_with_compartment(self): + r = reaction.parse_reaction('(2) |H2| + |O2| => (2) |H2O[e]|') + self.assertEqual(r, Reaction( + Direction.Forward, [(Compound('H2'), 2), (Compound('O2'), 1)], + [(Compound('H2O', compartment='e'), 2)])) + + def test_reaction_parse_with_multichar_compartment(self): + r = reaction.parse_reaction( + '(2) |H2[C_c]| + |O2[C_c]| => (2) |H2O[C_e]|') + self.assertEqual(r, Reaction( + Direction.Forward, + [(Compound('H2', compartment='C_c'), 2), + (Compound('O2', compartment='C_c'), 1)], + [(Compound('H2O', compartment='C_e'), 2)])) + + def test_reaction_parse_raw_compound_id(self): + r = reaction.parse_reaction('(2) cpd00001 => cpd00002') + self.assertEqual(r, Reaction( + Direction.Forward, [(Compound('cpd00001'), 2)], + [(Compound('cpd00002'), 1)])) + + def test_reaction_parse_raw_compound_id_with_typo(self): + r = reaction.parse_reaction('(2) cpd00001 => cdp00002') + self.assertEqual(r, Reaction( + Direction.Forward, [(Compound('cpd00001'), 2)], + [(Compound('cdp00002'), 1)])) + + def test_reaction_parse_raw_compound_id_in_compartment(self): + r = reaction.parse_reaction('(2) cpd00001 => cpd00002[e]') + self.assertEqual(r, Reaction( + Direction.Forward, [(Compound('cpd00001'), 2)], + [(Compound('cpd00002', 'e'), 1)])) + + def test_reaction_parse_bidirectional(self): + r = reaction.parse_reaction('(1) |cpd1| <=> (2) cpd2 + |cpd3|') + self.assertEqual(r, Reaction( + Direction.Both, [(Compound('cpd1'), 1)], + [(Compound('cpd2'), 2), (Compound('cpd3'), 1)])) + + def test_reaction_str(self): + r = Reaction(Direction.Reverse, [(Compound('H2O'), 2)], + [(Compound('H2'), 2), (Compound('O2'), 1)]) + self.assertEqual(text_type(r), '(2) H2O <= (2) H2 + O2') + + +class TestSudenSimple(unittest.TestCase): + def setUp(self): + arrows = ( + ('<=>', Direction.Both), + ('-->', Direction.Forward) + ) + self.parser = reaction.ReactionParser(arrows=arrows) + + def test_sudensimple_parse(self): + r = self.parser.parse('1 H2O + 1 PPi <=> 2 Phosphate + 2 proton') + self.assertEqual(r, Reaction( + Direction.Both, [(Compound('H2O'), 1), (Compound('PPi'), 1)], + [(Compound('Phosphate'), 2), (Compound('proton'), 2)])) + + def test_sudensimple_parse_with_implicit_count(self): + r = self.parser.parse('H2O + PPi <=> 2 Phosphate + 2 proton') + self.assertEqual(r, Reaction( + Direction.Both, [(Compound('H2O'), 1), (Compound('PPi'), 1)], + [(Compound('Phosphate'), 2), (Compound('proton'), 2)])) + + def test_sudensimple_parse_with_decimal(self): + r = self.parser.parse('1 H2 + 0.5 O2 <=> 1 H2O') + self.assertEqual(r, Reaction( + Direction.Both, [(Compound('H2'), 1), + (Compound('O2'), Decimal('0.5'))], + [(Compound('H2O'), 1)])) + + +class TestMetNet(unittest.TestCase): + def setUp(self): + arrows = ( + ('<==>', Direction.Both), + ('-->', Direction.Forward) + ) + self.parser = reaction.ReactionParser(arrows=arrows, parse_global=True) + + def test_metnet_parse_with_global_compartment(self): + r = self.parser.parse('[c] : akg + ala-L <==> glu-L + pyr') + self.assertEqual(r, Reaction( + Direction.Both, + [(Compound('akg', 'c'), 1), (Compound('ala-L', 'c'), 1)], + [(Compound('glu-L', 'c'), 1), (Compound('pyr', 'c'), 1)])) + + def test_metnet_parse_with_local_compartment(self): + r = self.parser.parse( + '(2) ficytcc553[c] + so3[c] + h2o[c] -->' + ' (2) focytcc553[c] + so4[c] + (2) h[e]') + self.assertEqual(r, Reaction( + Direction.Forward, + [(Compound('ficytcc553', 'c'), 2), (Compound('so3', 'c'), 1), + (Compound('h2o', 'c'), 1)], + [(Compound('focytcc553', 'c'), 2), (Compound('so4', 'c'), 1), + (Compound('h', 'e'), 2)])) + + def test_metnet_parse_global_with_colon_in_name(self): + r = self.parser.parse( + '[c] : fdxr-4:2 + h + nadp <==> fdxo-4:2 + nadph') + self.assertEqual(r, Reaction( + Direction.Both, + [(Compound('fdxr-4:2', 'c'), 1), (Compound('h', 'c'), 1), + (Compound('nadp', 'c'), 1)], + [(Compound('fdxo-4:2', 'c'), 1), (Compound('nadph', 'c'), 1)])) + + def test_metnet_parse_local_with_colon_in_name(self): + r = self.parser.parse( + 'fdxr-4:2[c] + h[c] + nadp[c] <==> fdxo-4:2[c] + nadph[c]') + self.assertEqual(r, Reaction( + Direction.Both, + [(Compound('fdxr-4:2', 'c'), 1), (Compound('h', 'c'), 1), + (Compound('nadp', 'c'), 1)], + [(Compound('fdxo-4:2', 'c'), 1), (Compound('nadph', 'c'), 1)])) + + def test_metnet_parse_with_numeric_id(self): + r = self.parser.parse('[c] : 3pg + atp <==> 13dpg + adp') + self.assertEqual(r, Reaction( + Direction.Both, + [(Compound('3pg', 'c'), 1), (Compound('atp', 'c'), 1)], + [(Compound('13dpg', 'c'), 1), (Compound('adp', 'c'), 1)])) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_model-generation.py",".py","28850","589","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2021 Christopher Powers +# Copyright 2022 Jason Vailionis + +import unittest +import sys +import os +from psamm import mapmaker +from psamm import generate_model +from psamm import generate_biomass +from pkg_resources import resource_filename +from psamm.datasource.native import NativeModel, ModelReader +from psamm.datasource.reaction import Reaction, Compound, Direction +from collections import defaultdict +import re +import yaml +import pandas as pd +import numpy as np +from io import StringIO + + +if sys.version_info.minor < 6: + raise unittest.SkipTest(""not compatible with py3.5"") + +class TestGenerateTransporters(unittest.TestCase): + + def test_parse_orthology(self): + test_egg = ""gene1\ta\tb\tc\td\te\tf\tg\th\ti\t2.3.3.1\tK01647\tk"" + test_egg += ""\tl\tR00351\tm\tn\t2.A.49.5.2\tp\tq\n"" + outfile = open(""testin.tsv"", ""w"") + outfile.write(test_egg) + outfile.close() + asso = generate_model.parse_orthology(""testin.tsv"", ""tcdb"", None) + self.assertTrue(len(asso) == 1) + self.assertTrue(asso[""2.A.49.5.2""] == [""gene1""]) + + def test_transporters(self): + asso = {""R00351"": [""gene1""], ""R00375"": [""gene2""]} + generate_model.create_model_api(""."", asso, False, False, ""c"") + substrate = resource_filename(""psamm"", + ""external-data/tcdb_substrates.tsv"") + family = resource_filename(""psamm"", + ""external-data/tcdb_families.tsv"") + + # read in the model and build a dictionary of Chebi IDs + mr = ModelReader.reader_from_path(""."""""") + nm = mr.create_model() + mm = nm.create_metabolic_model() + chebi_dict = defaultdict(lambda: []) + for cpd in nm.compounds: + if ""ChEBI"" in cpd.__dict__[""_properties""]: + chebi = re.split("" "", cpd.__dict__[""_properties""][""ChEBI""]) + for i in chebi: + chebi_dict[""CHEBI:{}"".format(i)].append(cpd.id) + # Read in the reaction substrates + tp_sub_dict = defaultdict(lambda: []) + with open(substrate, ""r"") as infile: + for line in infile: + line = line.rstrip() + listall = re.split(""\t"", line) + substrates = re.split(r""\|"", listall[1]) + sub_out = [] + for i in substrates: + sub_out.append(re.split("";"", i)[0]) + tp_sub_dict[listall[0]] = sub_out + + # read in the reaction families + tp_fam_dict = defaultdict(lambda: """") + with open(family, ""r"", encoding=""utf8"") as infile: + for line in infile: + line = line.rstrip() + listall = re.split(""\t"", line) + tp_fam_dict[listall[0]] = listall[1] + tp_asso = {""2.A.11.1.6"": [""gene2""], ""1.A.8.9.20"": [""gene3""]} + generate_model.gen_transporters(""."", tp_asso, tp_sub_dict, + tp_fam_dict, chebi_dict, ""c"", ""e"") + rxn = open(""transporters.yaml"", ""r"").read() + self.assertIn(""TP_2.A.11.1.6"", rxn) + self.assertIn(""[c] <=> [e]"", rxn) + self.assertIn(""CHEBI:34982"", rxn) + self.assertIn(""CHEBI:3308"", rxn) + self.assertIn(""CHEBI:50744"", rxn) + self.assertIn(""C00001_diff"", rxn) + self.assertIn(""[c] <=> [e]"", rxn) + self.assertIn(""The Major Intrinsic Protein (MIP) Family"", rxn) + self.assertIn(""CHEBI:15377"", rxn) + self.assertIn(""C00001[c] <=> C00001[e]"", rxn) + # check different compartments + generate_model.gen_transporters(""."", tp_asso, tp_sub_dict, + tp_fam_dict, chebi_dict, ""d"", ""f"") + rxn = open(""transporters.yaml"", ""r"").read() + self.assertIn(""C00001[d] <=> C00001[f]"", rxn) + self.assertIn(""[d] <=> [f]"", rxn) + os.remove(""log.tsv"") + os.remove(""reactions.yaml"") + os.remove(""reactions_generic.yaml"") + os.remove(""model.yaml"") + os.remove(""compounds.yaml"") + os.remove(""compounds_generic.yaml"") + os.remove(""gene-association.tsv"") + os.remove(""gene-association_generic.tsv"") + os.remove(""model_def.tsv"") + os.remove(""transporters.yaml"") + os.remove(""transporter_log.tsv"") + + +class TestGenerateDatabase(unittest.TestCase): + """""" + Test cases largely designed to test download of information + from KEGG through biopython and generate a reaction database + properly. Note that if these start to fail, one of the avenues + to check for errors is the composition of the ec, ko, reaction, or + compound representation in KEGG. + """""" + + + def test_overall(self): + # Check ability to create expected output files + asso = {""R00351"": [""gene1""], ""R00375"": [""gene2""]} + generate_model.create_model_api(""."", asso, False, False, ""c"") + self.assertTrue(os.path.exists(""log.tsv"")) + self.assertTrue(os.path.exists(""reactions.yaml"")) + self.assertTrue(os.path.exists(""compounds.yaml"")) + self.assertTrue(os.path.exists(""model.yaml"")) + self.assertTrue(os.path.exists(""gene-association.tsv"")) + self.assertTrue(os.path.exists(""gene-association_generic.tsv"")) + self.assertTrue(os.path.exists(""reactions_generic.yaml"")) + self.assertTrue(os.path.exists(""compounds_generic.yaml"")) + # Check contents of the created files + mr = ModelReader.reader_from_path(""."") + nm = mr.create_model() + mm = nm.create_metabolic_model() + self.assertIn(""R00351"", set(mm.reactions)) + self.assertNotIn(""R00375"", set(mm.reactions)) + self.assertIn(Compound(""C00010"", ""c""), set(mm.compounds)) + self.assertNotIn(Compound(""C00039"", ""c""), set(mm.compounds)) + self.assertIn(""2.3.3.1"", nm.reactions[""R00351""]. + __dict__[""_properties""][""enzymes""]) + self.assertIn(""Glyoxylate and dicarboxylate metabolism"", + nm.reactions[""R00351""]. + __dict__[""_properties""][""pathways""]) + self.assertIn(""K01647"", nm.reactions[""R00351""]. + __dict__[""_properties""][""orthology""]) + self.assertEqual(""C6H5O7"", nm.compounds[""C00158""]. + __dict__[""_properties""][""formula""]) + self.assertEqual(""16947"", nm.compounds[""C00158""]. + __dict__[""_properties""][""ChEBI""]) + self.assertEqual(-3, nm.compounds[""C00158""]. + __dict__[""_properties""][""charge""]) + # Check for relevant entries in the generic and other files + cpd = open(""compounds_generic.yaml"", ""r"").read() + self.assertIn(""C00039"", cpd) + rxn = open(""reactions_generic.yaml"", ""r"").read() + self.assertIn(""R00375"", rxn) + ga = open(""gene-association.tsv"", ""r"").read() + self.assertIn(""R00351"", ga) + ga = open(""gene-association_generic.tsv"", ""r"").read() + self.assertIn(""R00375"", ga) + os.remove(""log.tsv"") + os.remove(""reactions.yaml"") + os.remove(""reactions_generic.yaml"") + os.remove(""model.yaml"") + os.remove(""compounds.yaml"") + os.remove(""compounds_generic.yaml"") + os.remove(""gene-association.tsv"") + os.remove(""gene-association_generic.tsv"") + os.remove(""model_def.tsv"") + + def test_Rhea(self): + # Test that the rhea flag properly captures charge of atp + rhea_db = generate_model.RheaDb(resource_filename(""psamm"", + ""external-data/"" + ""chebi_pH7_3_"" + ""mapping.tsv"")) + cpd = [""C00002""] + cpd_out = generate_model._download_kegg_entries(""."", cpd, None, + generate_model. + CompoundEntry, + context=None) + cpd_out = list(cpd_out) + nonRhea = list(generate_model.model_compounds(cpd_out)) + self.assertTrue(nonRhea[0][""charge""] == 0) + cpd_out = generate_model._download_kegg_entries(""."", cpd, rhea_db, + generate_model. + CompoundEntry, + context=None) + cpd_out = list(cpd_out) + Rhea = list(generate_model.model_compounds(cpd_out)) + self.assertTrue(Rhea[0][""charge""] == -4) + os.remove(""log.tsv"") + + def test_EC_download(self): + # Test when EC has one reaction + rxn_mapping = {""2.3.3.1"": [""Gene1""]} + ec = generate_model.parse_rxns_from_EC(rxn_mapping, ""."", False) + self.assertTrue(len(ec) == 1) + self.assertTrue(len(ec[""R00351""]) == 1) + self.assertTrue(""R00351"" in ec) + self.assertTrue(ec[""R00351""] == [""Gene1""]) + # Test when EC has multiple reactions + rxn_mapping = {""4.2.1.3"": [""Gene1""]} + ec = generate_model.parse_rxns_from_EC(rxn_mapping, ""."", False) + self.assertTrue(len(ec) == 3) + self.assertTrue(""R01324"" in ec) + self.assertTrue(""R01325"" in ec) + self.assertTrue(""R01900"" in ec) + self.assertTrue(ec[""R01324""] == [""Gene1""]) + self.assertTrue(ec[""R01325""] == [""Gene1""]) + self.assertTrue(ec[""R01900""] == [""Gene1""]) + # Test for multiple genes + rxn_mapping = {""2.3.3.1"": [""Gene1"", ""Gene2""]} + ec = generate_model.parse_rxns_from_EC(rxn_mapping, ""."", False) + self.assertTrue(len(ec) == 1) + self.assertTrue(len(ec[""R00351""]) == 2) + self.assertTrue(""R00351"" in ec) + self.assertTrue(ec[""R00351""] == [""Gene1"", ""Gene2""]) + os.remove(""log.tsv"") + + def test_KO_download(self): + # Test when EC has one reaction + rxn_mapping = {""K01647"": [""Gene1""]} + ko = generate_model.parse_rxns_from_KO(rxn_mapping, ""."", False) + self.assertTrue(len(ko) == 1) + self.assertTrue(len(ko[""R00351""]) == 1) + self.assertTrue(""R00351"" in ko) + self.assertTrue(ko[""R00351""] == [""Gene1""]) + # Test when EC has multiple reactions + rxn_mapping = {""K01681"": [""Gene1""]} + ko = generate_model.parse_rxns_from_KO(rxn_mapping, ""."", False) + self.assertTrue(len(ko) == 3) + self.assertTrue(""R01324"" in ko) + self.assertTrue(""R01325"" in ko) + self.assertTrue(""R01900"" in ko) + self.assertTrue(ko[""R01324""] == [""Gene1""]) + self.assertTrue(ko[""R01325""] == [""Gene1""]) + self.assertTrue(ko[""R01900""] == [""Gene1""]) + # Test for multiple genes + rxn_mapping = {""K01647"": [""Gene1"", ""Gene2""]} + ko = generate_model.parse_rxns_from_KO(rxn_mapping, ""."", False) + self.assertTrue(len(ko) == 1) + self.assertTrue(len(ko[""R00351""]) == 2) + self.assertTrue(""R00351"" in ko) + self.assertTrue(ko[""R00351""] == [""Gene1"", ""Gene2""]) + os.remove(""log.tsv"") + + def test_model_compounds(self): + # Tests that compounds are properly sorted into generic compounds + # with the proper attributes. + cpd = [""C02987"", ""C00001""] + cpd_out = generate_model._download_kegg_entries(""."", cpd, None, + generate_model. + CompoundEntry, + context=None) + cpd_out = list(cpd_out) + generic = generate_model.check_generic_compounds(cpd_out) + generic_out = generate_model._download_kegg_entries(""."", generic, None, + generate_model. + CompoundEntry, + context=None) + generic_out = generate_model.model_generic_compounds(list(generic_out)) + generic_out = list(generic_out) + self.assertTrue(len(cpd_out) == 2) + self.assertTrue(len(generic_out) == 1) + self.assertTrue(""C02987"" == cpd_out[0].id) + self.assertTrue(""C00001"" == cpd_out[1].id) + self.assertTrue(""C02987"" == generic_out[0][""id""]) + self.assertTrue(""L-Glutamyl-tRNA(Glu)"" == generic_out[0][""name""]) + self.assertTrue(""C20H28N6O13PR(C5H8O6PR)n"" == + generic_out[0][""formula""]) + self.assertTrue(""29157"" == generic_out[0][""ChEBI""]) + cpd_out = list(generate_model.model_compounds(cpd_out)) + self.assertTrue(len(cpd_out) == 1) + self.assertTrue(""C00001"" == cpd_out[0][""id""]) + self.assertTrue(""H2O"" == cpd_out[0][""name""]) + self.assertTrue(""H2O"" == cpd_out[0][""formula""]) + self.assertTrue(""15377"" == cpd_out[0][""ChEBI""]) + + def test_generic_compoundID(self): + # Test that the download of compounds works + cpd = [""C02987"", ""C00001""] + cpd_out = generate_model._download_kegg_entries(""."", cpd, None, + generate_model. + CompoundEntry, + context=None) + cpd_out = generate_model.check_generic_compounds(list(cpd_out)) + cpd_out = list(cpd_out) + self.assertTrue(len(cpd_out) == 1) + self.assertTrue(""C02987"" in cpd_out) + self.assertTrue(""C00001"" not in cpd_out) + os.remove(""log.tsv"") + + def test_Compound_Download(self): + # Test that the download of compounds works + cpd = [""C00001""] + cpd_out = generate_model._download_kegg_entries(""."", cpd, None, + generate_model. + CompoundEntry, + context=None) + cpd_out = list(cpd_out) + self.assertTrue(len(cpd_out) == 1) + os.remove(""log.tsv"") + + def test_rxn_clean(self): + # Test teh function that reformats stoichiometry + rxn = [""R04347""] + rxn_out = generate_model._download_kegg_entries(""."", rxn, None, + generate_model. + ReactionEntry, + context=None) + rxn_out, gen= generate_model.clean_reaction_equations(list(rxn_out)) + self.assertTrue(""R04347"" in gen) + + def test_Compound_Contents(self): + # Test that the downloaded compound contains the relevant information + cpd = [""C00001""] + cpd_out = generate_model._download_kegg_entries(""."", cpd, None, + generate_model. + CompoundEntry, + context=None) + cpd_out = list(cpd_out) + self.assertTrue(len(cpd_out) == 1) + self.assertEqual(list(cpd_out)[0].id, ""C00001"") + self.assertEqual(list(cpd_out)[0].name, ""H2O"") + self.assertEqual(list(cpd_out)[0].formula, ""H2O"") + self.assertEqual(list(cpd_out)[0].mol_weight, 18.0153) + self.assertEqual(list(cpd_out)[0].chebi, ""15377"") + self.assertEqual(list(cpd_out)[0].charge, 0) + os.remove(""log.tsv"") + + def test_Reaction_Download(self): + # Test that the download of reactions works + rxn = [""R00351""] + rxn_out = generate_model._download_kegg_entries(""."", rxn, None, + generate_model. + ReactionEntry, + context=None) + self.assertTrue(len(list(rxn_out)) == 1) + os.remove(""log.tsv"") + + def test_Reaction_Contents(self): + # Test that the downloaded reaction contains the relevant information + rxn = [""R00351""] + rxn_out = generate_model._download_kegg_entries(""."", rxn, None, + generate_model. + ReactionEntry, + context=None) + rxn_out = list(rxn_out) + self.assertEqual(rxn_out[0].id, ""R00351"") + self.assertEqual(rxn_out[0].name, ""acetyl-CoA:oxaloacetate "" + ""C-acetyltransferase (thioester-hydrolysing)"") + self.assertEqual(rxn_out[0].definition, ""Citrate + CoA <=> Acetyl-CoA"" + "" + H2O + Oxaloacetate"") + self.assertEqual(rxn_out[0].equation, ""C00158 + C00010 <=> C00024 "" + ""+ C00001 + C00036"") + self.assertEqual(list(rxn_out[0].enzymes), + [""2.3.3.1"", ""2.3.3.3"", ""2.3.3.16""]) + self.assertIsNone(rxn_out[0].tcdb_family) + self.assertIsNone(rxn_out[0].substrates) + self.assertIsNone(rxn_out[0].genes) + self.assertTrue(len(list(rxn_out[0].pathways)) == 8) + self.assertEqual(list(rxn_out[0].pathways)[0], + (""rn00020"", ""Citrate cycle (TCA cycle)"")) + os.remove(""log.tsv"") + + def test_Model_Reactions(self): + # Tests the conversion of the reactions object to a dictionary format + rxn = [""R00351""] + rxn_out = [] + for entry in generate_model._download_kegg_entries(""."", rxn, None, + generate_model. + ReactionEntry, + context=None): + rxn_out.append(entry) + rxn_model = generate_model.model_reactions(rxn_out) + rxn_model = list(rxn_model) + self.assertEqual(rxn_out[0].id, rxn_model[0][""id""]) + self.assertEqual(rxn_out[0].name, rxn_model[0][""name""]) + self.assertEqual(rxn_out[0].definition, rxn_model[0] + [""KEGG_definition""]) + self.assertEqual(rxn_out[0].equation, rxn_model[0][""equation""]) + self.assertEqual(list(rxn_out[0].enzymes), rxn_model[0][""enzymes""]) + path = [] + for i in list(rxn_out[0].pathways): + path.append(i[1]) + self.assertEqual(len(list(rxn_out[0].pathways)), len(rxn_model[0] + [""pathways""])) + self.assertEqual(path, rxn_model[0][""pathways""]) + os.remove(""log.tsv"") + + def test_parseOrtho(self): + # Test the ability to parse the defaul eggnog output + test_egg = ""gene1\ta\tb\tc\td\te\tf\tg\th\ti\t2.3.3.1\t"" + test_egg += ""K01647\tk\tl\tR00351\tm\tn\to\tp\tq\n"" + outfile = open(""testin.tsv"", ""w"") + outfile.write(test_egg) + outfile.close() + asso = generate_model.parse_orthology(""testin.tsv"", ""R"", None) + self.assertTrue(len(asso) == 1) + self.assertTrue(asso[""R00351""] == [""gene1""]) + asso = generate_model.parse_orthology(""testin.tsv"", ""KO"", None) + self.assertTrue(len(asso) == 1) + self.assertTrue(asso[""K01647""] == [""gene1""]) + asso = generate_model.parse_orthology(""testin.tsv"", ""EC"", None) + self.assertTrue(len(asso) == 1) + self.assertTrue(asso[""2.3.3.1""] == [""gene1""]) + asso = generate_model.parse_orthology(""testin.tsv"", ""R"", 2) + self.assertTrue(len(asso) == 1) + self.assertTrue(asso[""a""] == [""gene1""]) + os.remove(""testin.tsv"") + + +class TestGenerateBiomass(unittest.TestCase): + + def test_cpd_database_load(self): + df = generate_biomass.load_compound_data() + self.assertTrue(df.shape == (79, 7)) + config = generate_biomass.make_template(df) + self.assertTrue(config.shape == (79, 3)) + config.custom_id = list(range(79)) # config w/ custom ids from 0 to 78 + config.to_csv(""config_file.csv"", index=False) + modified_df = generate_biomass.apply_config(df, ""config_file.csv"") + self.assertTrue(modified_df.shape == (79, 8)) + self.assertTrue(modified_df.loc[""biomass"", ""id""] == 0) + self.assertTrue(modified_df.loc[""C02554"", ""id""] == 78) + os.remove(""config_file.csv"") + + def test_model_parsing(self): + # THIS will include the way to build a fake model + # Then, test the load_model, check_missing_cpds, fix_cell_compartment, + # and update_model_yaml methods + yaml_args = {""default_flow_style"": False, + ""sort_keys"": False, + ""encoding"": ""utf-8"", + ""allow_unicode"": True, + ""width"": float(""inf"")} + test_model_dict = {""default_compartment"": None, ""biomass"": None, + ""compounds"": [{""include"": ""compounds.yaml""}], + ""reactions"": [{""include"": ""reactions.yaml""}], + ""model"": [{""include"": ""model_def.tsv""}]} + tmp_model_path = ""tmp_model.yaml"" + df = generate_biomass.load_compound_data() + with open(tmp_model_path, ""w"") as f: + yaml.dump(test_model_dict, f, **yaml_args) + model_dict = generate_biomass.load_model(tmp_model_path) + self.assertTrue(test_model_dict == model_dict) + # FAKE compounds.yaml which contains one of the 79 biomass compounds + # Testing if generate_biomass.yaml has the other 78 compounds + with open(""compounds.yaml"", ""w"") as f: + f.write(""- id: C02554"") + generate_biomass.check_missing_cpds( + tmp_model_path, df, None, yaml_args) + # Read in the biomass_compounds.yaml and make sure theres 78 cpds + # matching the first 78 in the df + with open(""biomass_compounds.yaml"", ""r"") as f: + matches = re.findall(""- id:.*\n"", f.read()) + cpds = [x.rstrip(""\n"").replace(""- id: "", """") for x in matches] + self.assertTrue(len(cpds) == 78) + self.assertTrue(list(df.id)[:-1] == cpds) + # Check fix_cell_compartment() + model_dict[""default_compartment""] = None + self.assertTrue( + generate_biomass.fix_cell_compartment(model_dict) == ""c"") + model_dict[""default_compartment""] = ""x"" + self.assertTrue( + generate_biomass.fix_cell_compartment(model_dict) == ""x"") + del model_dict[""default_compartment""] + self.assertTrue( + generate_biomass.fix_cell_compartment(model_dict) == ""c"") + # Check update_model_yaml() + test_model_dict[""compounds""].append( + {""include"": ""./biomass_compounds.yaml""}) + test_model_dict[""reactions""].append( + {""include"": ""./biomass_reactions.yaml""}) + test_model_dict[""biomass""] = ""biomass_name"" + test_model_dict[""default_compartment""] = ""c"" + generate_biomass.update_model_yaml( + tmp_model_path, model_dict, ""c"", ""biomass_name"", yaml_args) + updated_model_dict = generate_biomass.load_model(tmp_model_path) + self.assertTrue(test_model_dict == updated_model_dict) + os.remove(""biomass_compounds.yaml"") + os.remove(tmp_model_path) + os.remove(""compounds.yaml"") + + def test_calc_stoichiometry(self): + df = pd.DataFrame({""mol_weight"": [1, 2, 3, 3]}) + out = generate_biomass.calc_stoichiometry_df(df, [2, 2, 3, 3]) + self.assertTrue(out.shape == (4, 5)) + self.assertTrue(list(out.columns) == [""mol_weight"", ""counts"", + ""composition"", ""mass"", + ""stoichiometry""]) + np.testing.assert_almost_equal(out.stoichiometry, + [0.0833333, 0.0833333, 0.125, 0.125]) + + def test_dna_entry(self): + from Bio import SeqIO + with StringIO("">seq1\nAAGGGT\n>seq2\nAGCT"") as seqfile: + genome = {seq.name: seq.upper() + for seq in SeqIO.parse(seqfile, ""fasta"")} + df = generate_biomass.load_compound_data() + dna_output = generate_biomass.count_DNA(genome, df, ""c"") + print(dna_output) + proper_output = {""id"": ""dna_met"", ""name"": ""DNA"", + ""equation"": ""(0.613065) C00131[c] + (0.40871) "" + ""C00459[c] + (0.81742) C00286[c] + (0.204355) "" + ""C00458[c] + (4.0871) C00002[c] + (4.0871) C00001[c] "" + ""=> dna[c] + (4.0871) C00008[c] + (4.0871) C00009[c] "" + ""+ (2.04355) C00013[c]"", ""pathways"": [""Biomass""]} + self.assertTrue(dna_output == proper_output) + + def test_rna_entry(self): + from Bio import SeqIO + df = generate_biomass.load_compound_data() + with StringIO("">seq1\nAAGGGT\n>seq2\nAGCT"") as fna: + genome = {seq.name: seq.upper() + for seq in SeqIO.parse(fna, ""fasta"")} + with open(""temp.gff"", ""w"") as gff: + gff.write(""seq1\tProtein Homology\tCDS\t2\t6\t.\t+\t0\ttest\n"" + + ""seq2\tProtein Homology\tCDS\t2\t4\t.\t-\t0\ttest"") + rna_output = generate_biomass.count_RNA(genome, ""temp.gff"", df, ""c"") + proper_output = {""id"": ""rna_met"", ""name"": ""RNA"", + ""equation"": ""(4.248569) C00002[c] + (0.326813) "" + ""C00075[c] + (1.307252) C00044[c] + (3.921756) "" + ""C00001[c] => rna[c] + (3.921756) C00008[c] + "" + ""(3.921756) C00009[c] + (1.960878) C00013[c]"", + ""pathways"": [""Biomass""]} + self.assertTrue(rna_output == proper_output) + os.remove(""temp.gff"") + + def test_prot_entry(self): + from Bio import SeqIO + df = generate_biomass.load_compound_data() + with StringIO("">seq1\nLEW\n>seq2\nMIG"") as faa: + proteome = {seq.name: seq.upper() + for seq in SeqIO.parse(faa, ""fasta"")} + prot_output = generate_biomass.count_Prot(proteome, df, ""c"") + proper_output = {""id"": ""pro_met"", ""name"": ""Protein"", + ""equation"": ""(1.194786) C02987[c] + (1.194786) "" + ""C02412[c] + (1.194786) C03127[c] + (1.194786) "" + ""C02047[c] + (1.194786) C02430[c] + (1.194786) "" + ""C03512[c] + (14.337431) C00044[c] + (14.337431) "" + ""C00001[c] => (1.194786) C01641[c] + (1.194786) "" + ""C01642[c] + (1.194786) C01644[c] + (1.194786) "" + ""C01645[c] + (1.194786) C01647[c] + (1.194786) "" + ""C01652[c] + protein[c] + (14.337431) C00035[c] + "" + ""(14.337431) C00009[c]"", ""pathways"": [""Biomass""]} + self.assertTrue(prot_output == proper_output) + + def test_bio_entry(self): + df = generate_biomass.load_compound_data() + bio_output = generate_biomass.return_biomass_rxn(df, ""biomass"", ""c"") + proper_output = {""id"": ""biomass"", ""name"": ""Biomass"", + ""equation"": ""dna[c] + rna[c] + protein[c] => "" + ""biomass[c]"", ""pathways"": [""Biomass""]} + self.assertTrue(bio_output == proper_output) + + def test_sink_entry(self): + df = generate_biomass.load_compound_data() + sink_output = generate_biomass.return_bio_sink_rxn(df, ""c"") + proper_output = {""id"": ""sink_biomass"", ""name"": ""Biomass accumulation"", + ""equation"": ""biomass[c] =>"", ""pathways"": [""Biomass""]} + self.assertTrue(sink_output == proper_output) + + def test_tRNA_entries(self): + df = generate_biomass.load_compound_data() + trna_output = generate_biomass.return_trna_rxns(df, ""c"") + self.assertTrue(len(trna_output) == 20) + proper_output_lastaa = {""id"": ""R03665"", + ""name"": ""L-Valine:tRNAVal ligase "" + ""(AMP-forming)"", + ""equation"": ""C00002[c] + C00183[c] + C01653[c]"" + "" <=> C00020[c] + C00013[c] + C02554[c]"", + ""enzyme"": ""['6.1.1.9']"", + ""pathways"": [""Biomass""]} + self.assertTrue(trna_output[19] == proper_output_lastaa) +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_manual_curation.py",".py","6783","171","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015 Jon Lund Steffensen +# Copyright 2020 Jing Wang + +import unittest +import tempfile +import shutil +import os + +from psamm import manual_curation as curation +from psamm.datasource.native import ModelReader +from psamm.datasource.reaction import Compound + + +class TestCurator(unittest.TestCase): + def setUp(self): + self._model_dir = tempfile.mkdtemp() + with open(os.path.join(self._model_dir, 'compound.tsv'), 'w') as f: + f.write('id1\tid2\tp\n') + f.write('%s\t%s\t%f\n' % ('A', 'A1', 1.0)) + f.write('%s\t%s\t%f\n' % ('B', 'B1', 1.0)) + f.write('%s\t%s\t%f\n' % ('C', 'C1', 0.03)) + f.write('%s\t%s\t%f\n' % ('D', 'D1', 0.00005)) + with open(os.path.join(self._model_dir, 'reaction.tsv'), 'w') as f: + f.write('id1\tid2\tp\n') + f.write('%s\t%s\t%f\n' % ('rxn1', 'rxn1', 1.0)) + f.write('%s\t%s\t%f\n' % ('rxn2', 'rxn2', 1.0)) + f.write('%s\t%s\t%f\n' % ('rxn3', 'rxn3', 0.03)) + f.write('%s\t%s\t%f\n' % ('rxn4', 'rxn4', 0.00005)) + self.curator = curation.Curator( + os.path.join(self._model_dir, 'compound.tsv'), + os.path.join(self._model_dir, 'reaction.tsv'), + os.path.join(self._model_dir, 'curated_compound.tsv'), + os.path.join(self._model_dir, 'curated_reaction.tsv') + ) + + def tearDown(self): + shutil.rmtree(self._model_dir) + + def test_add_mapping(self): + self.curator.add_mapping(('A', 'A1'), 'c', True) + self.curator.add_mapping(('D', 'D1'), 'c', False) + self.curator.add_mapping(('rxn1', 'rxn1'), 'r', True) + self.curator.add_mapping(('rxn4', 'rxn4'), 'r', False) + self.curator.save() + + def test_compound_checked(self): + self.assertFalse(self.curator.compound_checked(('B', 'B1'))) + self.curator.add_mapping(('B', 'B1'), 'c', True) + self.assertFalse(self.curator.compound_checked(('C', 'C1'))) + self.curator.save() + curator = self.curator = curation.Curator( + self.curator.compound_map_file, + self.curator.reaction_map_file, + self.curator.curated_compound_map_file, + self.curator.curated_reaction_map_file + ) + self.assertTrue(curator.compound_checked(('B', 'B1'))) + self.assertTrue(curator.compound_checked('B')) + + def test_compound_ignored(self): + self.assertFalse(self.curator.compound_ignored('C')) + self.curator.add_ignore('C', 'c') + self.assertTrue(self.curator.compound_ignored('C')) + self.curator.save() + curator = self.curator = curation.Curator( + self.curator.compound_map_file, + self.curator.reaction_map_file, + self.curator.curated_compound_map_file, + self.curator.curated_reaction_map_file + ) + self.assertTrue(curator.compound_ignored('C')) + + def test_reaction_checked(self): + self.assertFalse(self.curator.reaction_checked(('rxn2', 'rxn2'))) + self.curator.add_mapping(('rxn2', 'rxn2'), 'r', False) + self.assertFalse(self.curator.reaction_checked(('rxn3', 'rxn3'))) + self.curator.save() + curator = self.curator = curation.Curator( + self.curator.compound_map_file, + self.curator.reaction_map_file, + self.curator.curated_compound_map_file, + self.curator.curated_reaction_map_file + ) + self.assertTrue(curator.reaction_checked(('rxn2', 'rxn2'))) + + def test_reaction_ignored(self): + self.assertFalse(self.curator.reaction_ignored('rxn3')) + self.curator.add_ignore('rxn3', 'r') + self.assertTrue(self.curator.reaction_ignored('rxn3')) + self.curator.save() + curator = self.curator = curation.Curator( + self.curator.compound_map_file, + self.curator.reaction_map_file, + self.curator.curated_compound_map_file, + self.curator.curated_reaction_map_file + ) + self.assertTrue(curator.reaction_ignored('rxn3')) + + +class TestSearch(unittest.TestCase): + def setUp(self): + self._model_dir = tempfile.mkdtemp() + with open(os.path.join(self._model_dir, 'model.yaml'), 'w') as f: + f.write('\n'.join([ + '---', + 'reactions:', + ' - id: rxn_1', + ' name: rxn_1', + ' equation: A[e] => B[c]', + ' genes: gene1 and gene2 or gene3', + ' - id: rxn_2', + ' name: rxn_2', + ' equation: B[c] => C[e]', + ' genes: gene5 or gene6', + ' - id: rxn_3', + ' name: rxn_3', + ' equation: A[e] + (6) B[c] <=> (6) C[e] + (6) D[c]', + ' genes: gene7', + 'compounds:', + ' - id: A', + ' name: compound_A', + ' formula: C6H12O6', + ' charge: 1', + ' - id: B', + ' name: compound_B', + ' formula: O2', + ' charge: 1', + ' kegg: C00010', + ' - id: C', + ' name: compound_C', + ' formula: CO2', + ' charge: -1', + ' - id: D', + ' name: compound_D', + ' formula: H2O', + ])) + self._model = ModelReader.reader_from_path( + os.path.join(self._model_dir, 'model.yaml')).create_model() + + def tearDown(self): + shutil.rmtree(self._model_dir) + + def test_search_compound(self): + curation.search_compound(self._model, ['C', 'Z']) + + def test_search_reaction(self): + cpds = curation.search_reaction(self._model, ['rxn_1', 'test']) + self.assertListEqual( + next(cpds), + [Compound('A', 'e'), Compound('B', 'c')]) + + def test_filter_search_term(self): + self.assertEqual(curation.filter_search_term('Test-(tes)_t'), + 'testtest') +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_findprimarypairs.py",".py","5465","139","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020 Elysha Sameth + + +import unittest + +from psamm import findprimarypairs +from psamm.formula import Formula, Atom, Radical +from psamm.reaction import Compound +from psamm.datasource.reaction import parse_reaction +from itertools import permutations + + +class TestFindPrimaryPairs(unittest.TestCase): + def test_default_weight(self): + self.assertEqual(findprimarypairs.element_weight(Atom.C), 1) + self.assertEqual(findprimarypairs.element_weight(Atom.H), 0) + self.assertEqual(findprimarypairs.element_weight(Atom.N), 0.82) + self.assertEqual(findprimarypairs.element_weight(Radical('R')), 0.82) + + def test_predict_compound_pairs(self): + """"""Test prediction of HEX1 reaction."""""" + reaction = parse_reaction( + 'atp[c] + glc-D[c] => adp[c] + g6p[c] + h[c]') + formulas = { + 'atp': Formula.parse('C10H12N5O13P3'), + 'adp': Formula.parse('C10H12N5O10P2'), + 'glc-D': Formula.parse('C6H12O6'), + 'g6p': Formula.parse('C6H11O9P'), + 'h': Formula.parse('H') + } + transfer, balance, ambiguous_pairs = \ + findprimarypairs.predict_compound_pairs( + reaction, formulas) + + self.assertEqual(balance, {}) + self.assertEqual(transfer, { + ((Compound('atp', 'c'), 1), (Compound('adp', 'c'), 1)): + Formula.parse('C10H12N5O10P2'), + ((Compound('glc-D', 'c'), 1), (Compound('g6p', 'c'), 1)): + Formula.parse('C6H11O6'), + ((Compound('atp', 'c'), 1), (Compound('g6p', 'c'), 1)): + Formula.parse('O3P'), + ((Compound('glc-D', 'c'), 1), (Compound('h', 'c'), 1)): + Formula.parse('H') + }) + self.assertEqual(ambiguous_pairs, set()) + + def test_predict_compound_pairs_ambig(self): + """"""Test prediction of (non-sense) ambiguous reaction."""""" + reaction = parse_reaction( + 'a[c] + b[c] => c[c] + d[c]') + formulas = { + 'a': Formula.parse('C10H10'), + 'b': Formula.parse('C10H10'), + 'c': Formula.parse('C10H10'), + 'd': Formula.parse('C10H10') + } + transfer, balance, ambiguous_pairs = \ + findprimarypairs.predict_compound_pairs( + reaction, formulas) + + all_perm = set(set(permutations(list(ambiguous_pairs)[0]))) + ambig = list(ambiguous_pairs)[0] + + self.assertEqual(balance, {}) + self.assertEqual(transfer, { + ((Compound('b', 'c'), 1), (Compound('d', 'c'), 1)): + Formula.parse('C10H10'), + ((Compound('a', 'c'), 1), (Compound('c', 'c'), 1)): + Formula.parse('C10H10') + }) + self.assertEqual(ambig, ambig if ambig in all_perm else set()) + + def test_predict_compound_pairs_unbalanced(self): + """"""Test prediction of (non-sense) unbalanced reaction."""""" + reaction = parse_reaction( + 'a[c] <=> b[c] + c[c]') + formulas = { + 'a': Formula.parse('C10H12'), + 'b': Formula.parse('C9H11'), + 'c': Formula.parse('CO2') + } + transfer, balance, ambiguous_pairs = \ + findprimarypairs.predict_compound_pairs( + reaction, formulas) + + self.assertEqual(balance, { + (Compound('a', 'c'), 1): Formula.parse('H'), + (Compound('c', 'c'), 1): Formula.parse('O2'), + }) + self.assertEqual(transfer, { + ((Compound('a', 'c'), 1), (Compound('b', 'c'), 1)): + Formula.parse('C9H11'), + ((Compound('a', 'c'), 1), (Compound('c', 'c'), 1)): + Formula.parse('C'), + }) + self.assertEqual(ambiguous_pairs, set()) + + def test_predict_compound_pairs_multiple(self): + """"""Test prediction of reaction with multiple instances."""""" + reaction = parse_reaction( + 'a[c] <=> (2) b[c] + c[c]') + formulas = { + 'a': Formula.parse('C10H13O6'), + 'b': Formula.parse('C5H6O3'), + 'c': Formula.parse('H'), + } + transfer, balance, ambiguous_pairs = \ + findprimarypairs.predict_compound_pairs( + reaction, formulas) + + self.assertEqual(balance, {}) + self.assertEqual(transfer, { + ((Compound('a', 'c'), 1), (Compound('b', 'c'), 1)): + Formula.parse('C5H6O3'), + ((Compound('a', 'c'), 1), (Compound('b', 'c'), 2)): + Formula.parse('C5H6O3'), + ((Compound('a', 'c'), 1), (Compound('c', 'c'), 1)): + Formula.parse('H') + }) + self.assertEqual(ambiguous_pairs, set()) +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_fluxcoupling.py",".py","5545","128","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.metabolicmodel import MetabolicModel +from psamm.database import DictDatabase +from psamm import fluxcoupling +from psamm.datasource.reaction import parse_reaction +from psamm.lpsolver import generic + + +class TestFluxCouplingBurgardModel(unittest.TestCase): + """"""Test case based on the simple model in [Burgard04]_."""""" + + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('|A| => |B|')) + self.database.set_reaction('rxn_2', parse_reaction('|B| => |G|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |G|')) + self.database.set_reaction('rxn_4', parse_reaction('|B| => |H|')) + self.database.set_reaction('rxn_5', parse_reaction('|B| => |C| + |F|')) + self.database.set_reaction('rxn_6', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_7', parse_reaction('|E| <=> |D|')) + self.database.set_reaction('rxn_9', parse_reaction('|I| => |J|')) + self.database.set_reaction('rxn_10', parse_reaction('|J| => |K|')) + self.database.set_reaction('rxn_A', parse_reaction('=> |A|')) + self.database.set_reaction('rxn_G', parse_reaction('|G| =>')) + self.database.set_reaction('rxn_E', parse_reaction('|E| =>')) + self.database.set_reaction( + 'rxn_bio', parse_reaction('|D| + (2.5) |F| =>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_flux_coupling(self): + if self.solver.properties['name'] == 'qsoptex': + self.skipTest('Flux coupling with QSopt_ex is very slow') + + fcp = fluxcoupling.FluxCouplingProblem(self.model, {}, self.solver) + reactions = sorted(self.model.reactions) + couplings = {} + for r1 in reactions: + for r2 in reactions: + couplings[r1, r2] = fcp.solve(r1, r2) + + inconsistent = {'rxn_4', 'rxn_9', 'rxn_10'} + coupled_set = {'rxn_5', 'rxn_6', 'rxn_7', 'rxn_bio', 'rxn_E'} + + for i, r1 in enumerate(reactions): + for r2 in reactions[i:]: + if r1 == r2: + # A reaction is always fully coupled to itself + # unless it is inconsistent. + lower, upper = couplings[r1, r2] + if r1 in inconsistent: + self.assertEqual((lower, upper), (None, None)) + else: + print('{}, {}: {}, {}'.format(r1, r2, lower, upper)) + self.assertAlmostEqual(lower, upper) + elif r1 in inconsistent or r2 in inconsistent: + # Couplings with inconsistent reactions are always + # fully coupled at 0.0 or uncoupled. + coupling = couplings[r1, r2] + self.assertIn(coupling, ((0.0, 0.0), (None, None))) + elif r1 in coupled_set and r2 in coupled_set: + lower, upper = couplings[r1, r2] + self.assertAlmostEqual(lower, upper) + else: + # At least one of the values must be 0 or None if the + # reactions are not in the coupled set. + coupling = couplings[r1, r2] + self.assertTrue(any(v in (0.0, None) for v in coupling)) + + # Couplings with rxn_7 are negative + for r in coupled_set: + if r != 'rxn_7': + self.assertLess(couplings['rxn_7', r][0], 0.0) + + +class TestFluxCouplingClass(unittest.TestCase): + def test_uncoupled(self): + cc = fluxcoupling.classify_coupling((None, None)) + self.assertEqual(cc, fluxcoupling.CouplingClass.Uncoupled) + + def test_directional_reverse(self): + cc = fluxcoupling.classify_coupling((None, 1000)) + self.assertEqual(cc, fluxcoupling.CouplingClass.DirectionalReverse) + + cc = fluxcoupling.classify_coupling((-1000, None)) + self.assertEqual(cc, fluxcoupling.CouplingClass.DirectionalReverse) + + def test_inconsistent(self): + cc = fluxcoupling.classify_coupling((0.0, 0.0)) + self.assertEqual(cc, fluxcoupling.CouplingClass.Inconsistent) + + def test_directional_forward(self): + cc = fluxcoupling.classify_coupling((-1000, 100.0)) + self.assertEqual(cc, fluxcoupling.CouplingClass.DirectionalForward) + + def test_full(self): + cc = fluxcoupling.classify_coupling((-1000, -1000.0)) + self.assertEqual(cc, fluxcoupling.CouplingClass.Full) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_randomsparse.py",".py","8565","225","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2016 Chao Liu + +import os +import unittest +import tempfile +import shutil + +from psamm.datasource.native import ModelReader +from psamm.metabolicmodel import MetabolicModel +from psamm.database import DictDatabase +from psamm.datasource.reaction import parse_reaction +from psamm.expression import boolean +from psamm.lpsolver import generic +from psamm import fluxanalysis, randomsparse + + +class TestGetGeneAssociation(unittest.TestCase): + def setUp(self): + self._model_dir = tempfile.mkdtemp() + with open(os.path.join(self._model_dir, 'model.yaml'), 'w') as f: + f.write('\n'.join([ + '---', + 'reactions:', + ' - id: rxn_1', + ' equation: A[e] <=> B[c]', + ' genes: gene_1 and gene_2', + ' - id: rxn_2', + ' equation: A[e] => C[c]', + ' genes: gene_3', + ' - id: rxn_3', + ' equation: A[e] => D[e]', + ' - id: rxn_4', + ' equation: C[c] => D[e]', + ' genes: [gene_4, gene_5, gene_6]', + 'compounds:', + ' - id: A', + ' - id: B', + ' - id: C', + ' - id: D', + 'exchange:', + ' - compartment: e', + ' compounds:', + ' - id: A', + ' reaction: rxn_5', + ' - id: D', + ' reaction: rxn_6', + 'model:', + ' - reactions:', + ' - rxn_3', + ' - rxn_4', + ])) + self._model = ModelReader.reader_from_path( + self._model_dir).create_model() + + def tearDown(self): + shutil.rmtree(self._model_dir) + + def test_get_gene_association(self): + expected_association = { + 'rxn_1': boolean.Expression('gene_1 and gene_2'), + 'rxn_2': boolean.Expression('gene_3'), + 'rxn_4': boolean.Expression('gene_4 and gene_6 and gene_5') + } + + self.assertEqual( + dict(randomsparse.get_gene_associations(self._model)), + expected_association) + + +class TestGetExchangeReactions(unittest.TestCase): + def setUp(self): + self._database = DictDatabase() + self._database.set_reaction('rxn_1', parse_reaction('|A| <=>')) + self._database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self._database.set_reaction('rxn_3', parse_reaction('|C| <=> |B|')) + self._database.set_reaction('rxn_4', parse_reaction('|C| <=>')) + self._mm = MetabolicModel.load_model( + self._database, self._database.reactions) + + def test_get_exchange_reactions(self): + expected_reactions = {'rxn_1', 'rxn_4'} + self.assertEqual( + set(randomsparse.get_exchange_reactions(self._mm)), + expected_reactions) + + +class TestReactionDeletionStrategy(unittest.TestCase): + def setUp(self): + self._database = DictDatabase() + self._database.set_reaction('rxn_1', parse_reaction('|A| <=>')) + self._database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self._database.set_reaction('rxn_3', parse_reaction('|C| <=> |B|')) + self._database.set_reaction('rxn_4', parse_reaction('|C| <=>')) + self._mm = MetabolicModel.load_model( + self._database, self._database.reactions) + + self._strategy = randomsparse.ReactionDeletionStrategy(self._mm) + + def test_method_get_all(self): + expected_total = {'rxn_1', 'rxn_2', 'rxn_3', 'rxn_4'} + self.assertEqual(set(self._strategy.entities), expected_total) + + def test_method_tests(self): + expected_reactions = { + 'rxn_1': {'rxn_1'}, + 'rxn_2': {'rxn_2'}, + 'rxn_3': {'rxn_3'}, + 'rxn_4': {'rxn_4'} + } + self.assertEqual(dict(self._strategy.iter_tests()), expected_reactions) + + +class TestGeneDeletionStrategy(unittest.TestCase): + def setUp(self): + self._database = DictDatabase() + self._database.set_reaction('rxn_1', parse_reaction('|A| <=>')) + self._database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self._database.set_reaction('rxn_3', parse_reaction('|C| <=> |B|')) + self._database.set_reaction('rxn_4', parse_reaction('|C| <=>')) + self._mm = MetabolicModel.load_model( + self._database, self._database.reactions) + self._assoc = {'rxn_2': boolean.Expression('gene_1 or gene_2')} + + self._strategy = randomsparse.GeneDeletionStrategy( + self._mm, self._assoc) + + def test_method_get_all(self): + expected_total = {'gene_1', 'gene_2'} + self.assertEqual(set(self._strategy.entities), expected_total) + + def test_method_tests_and_delete(self): + expected_genes = {'gene_1', 'gene_2'} + expected_reaction_set = {'rxn_2'} + test_dict = {} + + for i, (gene, deleted_reac) in enumerate(self._strategy.iter_tests()): + self._strategy.delete(gene, deleted_reac) + if i == 0: + self.assertEqual(deleted_reac, set()) + else: + self.assertEqual(deleted_reac, {'rxn_2'}) + test_dict[gene] = deleted_reac + + self.assertTrue(all(x in test_dict for x in expected_genes)) + self.assertTrue(expected_reaction_set in test_dict.values()) + + +class TestRandomSparse(unittest.TestCase): + def setUp(self): + self._database = DictDatabase() + self._database.set_reaction('rxn_1', parse_reaction('A[e] => B[e]')) + self._database.set_reaction('rxn_2', parse_reaction('B[e] => C[e]')) + self._database.set_reaction('rxn_3', parse_reaction('B[e] => D[e]')) + self._database.set_reaction('rxn_4', parse_reaction('C[e] => E[e]')) + self._database.set_reaction('rxn_5', parse_reaction('D[e] => E[e]')) + self._database.set_reaction('rxn_6', parse_reaction('E[e] =>')) + self._database.set_reaction('ex_A', parse_reaction('A[e] <=>')) + + self._mm = MetabolicModel.load_model( + self._database, self._database.reactions) + self._assoc = { + 'rxn_1': boolean.Expression('gene_1'), + 'rxn_2': boolean.Expression('gene_2 or gene_3'), + 'rxn_5': boolean.Expression('gene_3 and gene_4') + } + self._obj_reaction = 'rxn_6' + + try: + self._solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + self._prob = fluxanalysis.FluxBalanceProblem(self._mm, self._solver) + + def test_random_sparse_reaction_strategy(self): + expected = [ + ({'rxn_1', 'rxn_6', 'ex_A', 'rxn_2', 'rxn_4'}, {'rxn_3', 'rxn_5'}), + ({'rxn_1', 'rxn_6', 'ex_A', 'rxn_3', 'rxn_5'}, {'rxn_2', 'rxn_4'}) + ] + + strategy = randomsparse.ReactionDeletionStrategy(self._mm) + essential, deleted = randomsparse.random_sparse( + strategy, + self._prob, + self._obj_reaction, + flux_threshold=100) + + self.assertTrue((essential, deleted) in expected) + + def test_random_sparse_gene_strategy(self): + expected = [ + ({'gene_1', 'gene_2'}, {'gene_3', 'gene_4'}), + ({'gene_1', 'gene_3'}, {'gene_2', 'gene_4'}) + ] + strategy = randomsparse.GeneDeletionStrategy( + self._mm, self._assoc) + essential, deleted = randomsparse.random_sparse( + strategy, + self._prob, + self._obj_reaction, + flux_threshold=100) + + self.assertTrue((essential, deleted) in expected) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_expression_affine.py",".py","12982","345","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.expression.affine import Expression, Variable + + +class TestVariable(unittest.TestCase): + def test_variable_init(self): + v = Variable('x') + + def test_variable_init_long_symbol(self): + v = Variable('xyz') + + def test_variable_init_number_symbol(self): + v = Variable('x2') + + def test_variable_init_underscore_symbol(self): + v = Variable('x_y') + + def test_variable_init_invalid_number(self): + with self.assertRaises(ValueError): + v = Variable('45x') + + def test_variable_symbol(self): + self.assertEqual(Variable('x').symbol, 'x') + + def test_variable_simplify_returns_self(self): + self.assertEqual(Variable('y').simplify(), Variable('y')) + + def test_variable_substitute(self): + self.assertEqual(Variable('x').substitute( + lambda v: {'x': 567}.get(v.symbol, v)), 567) + + def test_variable_substitute_unknown(self): + self.assertEqual(Variable('x').substitute( + lambda v: v), Variable('x')) + + def test_variable_substitute_multiple(self): + self.assertEqual(Variable('x').substitute( + lambda v: {'y': 123, 'x': 56}.get(v.symbol, v)), 56) + + def test_variable_add_number(self): + self.assertEqual(Variable('x') + 1, Expression('x + 1')) + + def test_variable_radd_number(self): + self.assertEqual(1 + Variable('x'), Expression('x + 1')) + + def test_variable_sub_number(self): + self.assertEqual(Variable('x') - 4, Expression('x - 4')) + + def test_variable_rsub_number(self): + self.assertEqual(4 - Variable('x'), Expression('4 - x')) + + def test_variable_mul_zero(self): + self.assertEqual(Variable('x') * 0, 0) + + def test_variable_mul_one(self): + self.assertEqual(Variable('x') * 1, Variable('x')) + + def test_variable_mul_number(self): + self.assertEqual(Variable('x') * 2, Expression('2x')) + + def test_variable_rmul_number(self): + self.assertEqual(3 * Variable('x'), Expression('3x')) + + def test_variable_div_number(self): + self.assertEqual(Variable('x')/1, Variable('x')) + + def test_variable_neg(self): + self.assertEqual(-Variable('x'), Expression('-x')) + + def test_variables_equals_true(self): + self.assertEqual(Variable('x'), Variable('x')) + + def test_variables_not_equals(self): + self.assertNotEqual(Variable('x'), Variable('y')) + + def test_variable_not_equals_number(self): + self.assertNotEqual(Variable('x'), 5) + + def test_variables_ordered_by_symbol(self): + var_list = sorted([Variable('b'), Variable('cd'), + Variable('a'), Variable('cc')]) + self.assertEqual(var_list, [Variable('a'), Variable('b'), + Variable('cc'), Variable('cd')]) + + def test_variable_hash(self): + self.assertEqual(hash(Variable('xyz')), hash(Variable('xyz'))) + + +class TestExpression(unittest.TestCase): + def test_expression_init_empty(self): + e = Expression() + + def test_expression_init_with_variables(self): + e = Expression({Variable('a'): 1, Variable('b'): 2}) + + def test_expression_init_with_offset(self): + e = Expression({}, 5) + + def test_expression_init_with_variables_and_offset(self): + e = Expression({Variable('a'): 4}, -5) + + def test_expression_init_with_zero_variables(self): + e = Expression({Variable('a'): 3, Variable('b'): 0}) + self.assertEqual(e, Expression({Variable('a'): 3})) + + def test_expression_init_with_non_variables(self): + with self.assertRaises(ValueError): + e = Expression({'a': 3}) + + def test_expression_simplify_to_number(self): + result = Expression({}, 5).simplify() + self.assertEqual(result, 5) + self.assertIsInstance(result, int) + + def test_expression_simplify_to_variable(self): + result = Expression({Variable('x'): 1}).simplify() + self.assertEqual(result, Variable('x')) + self.assertIsInstance(result, Variable) + + def test_expression_simplify_to_expression(self): + result = Expression({Variable('x'): 2}).simplify() + self.assertEqual(result, Expression('2x')) + self.assertIsInstance(result, Expression) + + def test_expression_simplify_to_expression_with_offset(self): + result = Expression({Variable('x'): 1}, 2).simplify() + self.assertEqual(result, Expression('x + 2')) + self.assertIsInstance(result, Expression) + + def test_expression_substitute_existing(self): + e = Expression({Variable('x'): 2}, 1) + self.assertEqual(e.substitute(lambda v: {'x': 2}.get(v.symbol, v)), 5) + + def test_expression_substitute_unknown_to_variable(self): + e = Expression({Variable('x'): 1}) + self.assertEqual(e.substitute(lambda v: v), Variable('x')) + + def test_expression_substitute_unknown_to_expression(self): + e = Expression({Variable('x'): 2}, 1) + self.assertEqual(e.substitute(lambda v: v), Expression('2x + 1')) + + def test_expression_substitute_with_variable(self): + e = Expression({Variable('x'): 1, Variable('y'): 2}) + self.assertEqual(e.substitute( + lambda v: {'y': Variable('x')}.get(v.symbol, v)), Expression('3x')) + + def test_expression_substitute_with_expression(self): + e = Expression({Variable('x'): 3, Variable('y'): -2}) + es = e.substitute( + lambda v: {'x': Expression('y + 2z')}.get(v.symbol, v)) + self.assertEqual(es, Expression('y + 6z')) + + def test_expression_substitute_with_expression_is_atomic(self): + e = Expression({Variable('x'): 1, Variable('y'): 1}) + es = e.substitute( + lambda v: {'x': Expression('x + y'), + 'y': Expression('x + y')}.get(v.symbol, v)) + self.assertEqual(es, Expression('2x + 2y')) + + def test_expression_variables(self): + e = Expression({Variable('x'): 1, Variable('y'): 2}) + self.assertEqual(sorted(e.variables()), [Variable('x'), Variable('y')]) + + def test_expression_add_number(self): + e = Expression({Variable('x'): 1}) + self.assertEqual(e + 1, Expression('x + 1')) + + def test_expression_add_other_variable(self): + e = Expression({Variable('x'): 1}) + self.assertEqual(e + Variable('y'), Expression('x + y')) + + def test_expression_add_same_variable(self): + e = Expression({Variable('x'): 1}) + self.assertEqual(e + Variable('x'), Expression('2x')) + + def test_expression_add_expression(self): + e1 = Expression({Variable('x'): 1}) + e2 = Expression({Variable('y'): 2}) + self.assertEqual(e1 + e2, Expression('x + 2y')) + + def test_expression_add_sums_to_zero(self): + e1 = Expression({Variable('x'): 2, Variable('y'): 1}) + e2 = Expression({Variable('x'): -2, Variable('z'): 3}) + self.assertEqual(e1 + e2, Expression('y + 3z')) + + def test_expression_sub_number(self): + e = Expression({Variable('x'): 1}) + self.assertEqual(e - 1, Expression('x - 1')) + + def text_expression_rsub_number(self): + e = Expression({Variable('x'): 2}) + self.assertEqual(4 - e, Expression('4 - 2x')) + + def test_expression_sub_other_variable(self): + e = Expression({Variable('x'): 1}) + self.assertEqual(e - Variable('y'), Expression('x - y')) + + def test_expression_sub_same_variable(self): + e = Expression({Variable('x'): 1}) + self.assertEqual(e - Variable('x'), 0) + + def test_expression_sub_expression(self): + e1 = Expression({Variable('x'): 1}) + e2 = Expression({Variable('y'): 2}) + self.assertEqual(e1 - e2, Expression('x - 2y')) + + def test_expression_mul_zero(self): + e = Expression({Variable('x'): 3, Variable('y'): -2}, 4) + self.assertEqual(e * 0, 0) + + def test_expression_mul_one(self): + e = Expression({Variable('x'): 3, Variable('y'): -2}, 4) + self.assertEqual(e * 1, e) + + def test_expression_mul_number(self): + e = Expression({Variable('x'): 3, Variable('y'): -2}, 4) + self.assertEqual(e * 4, Expression('12x - 8y + 16')) + + def test_expression_div_number(self): + e = Expression({Variable('x'): 8, Variable('y'): -2}, 4) + self.assertEqual(e/2, Expression('4x - y + 2')) + + def test_expression_neg(self): + e = Expression({Variable('x'): 3, Variable('y'): -2}, 4) + self.assertEqual(-e, Expression('-3x + 2y - 4')) + + def test_expression_equals_expression(self): + e1 = Expression({Variable('x'): 2, Variable('y'): 5}) + e2 = Expression({Variable('y'): 5, Variable('x'): 2}) + self.assertEqual(e1, e2) + + def test_expression_not_equals_same_variables(self): + e1 = Expression({Variable('x'): 2, Variable('y'): 5}) + e2 = Expression({Variable('y'): 2, Variable('x'): -5}) + self.assertNotEqual(e1, e2) + + def test_expression_not_equals_diffrent_variables(self): + e1 = Expression({Variable('x'): 2, Variable('y'): 5}) + e2 = Expression({Variable('y'): 2, Variable('x'): -5, + Variable('z'): 1}) + self.assertNotEqual(e1, e2) + + def test_expression_not_equals_with_offset(self): + e1 = Expression({Variable('x'): 2, Variable('y'): 5}, 4) + e2 = Expression({Variable('y'): 5, Variable('x'): 2}) + self.assertNotEqual(e1, e2) + + def test_expression_equals_variable(self): + e = Expression({Variable('x'): 1}) + self.assertEqual(e, Variable('x')) + + def test_expression_with_coefficient_not_equals_variable(self): + e = Expression({Variable('x'): 2}) + self.assertNotEqual(e, Variable('x')) + + def test_expression_with_offset_not_equals_variable(self): + e = Expression({Variable('x'): 1}, 4) + self.assertNotEqual(e, Variable('x')) + + def test_expression_with_multiple_not_equals_variable(self): + e = Expression({Variable('x'): 1, Variable('y'): 1}) + self.assertNotEqual(e, Variable('x')) + + def test_expression_with_no_variables_equals_number(self): + self.assertEqual(Expression({}, 3), 3) + + def test_expression_with_no_variables_not_equals_number(self): + self.assertNotEqual(Expression({}, -3), 3) + + def test_expression_with_variables_not_equals_number(self): + self.assertNotEqual(Expression({Variable('x'): 1}, 3), 3) + + def test_expression_parse(self): + e = Expression('2x + 3') + self.assertEqual(e, Expression({Variable('x'): 2}, 3)) + + def test_expression_parse_number(self): + e = Expression('1') + self.assertEqual(e, Expression({}, 1)) + self.assertEqual(e, 1) + + def test_expression_parse_zero_offset(self): + e = Expression('x + 4y + 0') + self.assertEqual(e, Expression({Variable('x'): 1, Variable('y'): 4})) + + def test_expression_parse_multiple_occurences(self): + e = Expression('x + 4y + 2x') + self.assertEqual(e, Expression({Variable('x'): 3, Variable('y'): 4})) + + def test_expression_parse_negative_coefficient(self): + e = Expression('-x + 4y - 3z') + self.assertEqual(e, Expression( + {Variable('x'): -1, Variable('y'): 4, Variable('z'): -3})) + + def test_expression_parse_zero_coefficient(self): + e = Expression('2x + 0y + 4') + self.assertEqual(e, Expression({Variable('x'): 2}, 4)) + + def test_expression_parse_long_variable_symbols(self): + e = Expression('-2x1 + 5pi - 3x2') + self.assertEqual(e, Expression( + {Variable('x1'): -2, Variable('pi'): 5, Variable('x2'): -3})) + + def test_expression_parse_no_space(self): + e = Expression('x+3f+6h+10') + self.assertEqual(e, Expression( + {Variable('x'): 1, Variable('f'): 3, Variable('h'): 6}, 10)) + + def test_expression_parse_large_coefficient(self): + e = Expression('x + 4200y') + self.assertEqual(e, Expression( + {Variable('x'): 1, Variable('y'): 4200})) + + def test_expression_to_str(self): + e = Expression({ + Variable('x1'): -2, + Variable('pi'): 5, + Variable('x2'): -3 + }) + self.assertEqual(str(e), '5pi - 2x1 - 3x2') + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/__init__.py",".py","0","0","","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_reaction.py",".py","16965","441","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from six import text_type + +from psamm.reaction import Reaction, Compound, Direction + + +class TestCompound(unittest.TestCase): + def test_compound_init_no_arguments(self): + with self.assertRaises(TypeError): + c = Compound() + + def test_compound_init_with_name(self): + c = Compound('Phosphate') + + def test_compound_init_with_compartment(self): + c = Compound('Phosphate', compartment='e') + + def test_compound_init_with_argument(self): + c = Compound('Menaquinone', arguments=[8]) + + def test_compound_init_with_compartment_and_argument(self): + c = Compound('Menaquinone', compartment='e', arguments=[8]) + + def test_compound_name(self): + c = Compound('Phosphate') + self.assertEqual(c.name, 'Phosphate') + + def test_compound_compartment(self): + c = Compound('Phosphate', compartment='e') + self.assertEqual(c.compartment, 'e') + + def test_compound_compartment_none(self): + c = Compound('Phosphate') + self.assertIsNone(c.compartment) + + def test_compound_arguments(self): + c = Compound('Menaquinone', arguments=[8]) + self.assertEqual(list(c.arguments), [8]) + + def test_compound_arguments_none(self): + c = Compound('Phosphate') + self.assertEqual(list(c.arguments), []) + + def test_compound_translate_name(self): + c = Compound('Pb') + self.assertEqual(c.translate(lambda x: x.lower()), Compound('pb')) + self.assertIsNot(c.translate(lambda x: x.lower()), c) + + def test_compound_in_compartment_when_unassigned(self): + c = Compound('H+') + self.assertEqual(c.in_compartment('e'), Compound('H+', 'e')) + self.assertIsNot(c.in_compartment('e'), c) + + def test_compound_in_compartment_when_assigned(self): + c = Compound('H+', 'c') + self.assertEqual(c.in_compartment('p'), Compound('H+', 'p')) + self.assertIsNot(c.in_compartment('p'), c) + + def test_compound_equals_other_with_same_name(self): + c = Compound('Phosphate') + self.assertEqual(c, Compound('Phosphate')) + + def test_compound_not_equals_other_with_name(self): + c = Compound('H+') + self.assertNotEqual(c, Compound('Phosphate')) + + def test_compound_equals_other_with_compartment(self): + c = Compound('Phosphate', 'e') + self.assertEqual(c, Compound('Phosphate', 'e')) + + def test_compound_not_equals_other_with_compartment(self): + c = Compound('Phosphate', 'e') + self.assertNotEqual(c, Compound('Phosphate', None)) + + def test_compound_equals_other_with_arguments(self): + c = Compound('Polyphosphate', arguments=[5]) + self.assertEqual(c, Compound('Polyphosphate', arguments=[5])) + + def test_compound_not_equals_other_with_arguments(self): + c = Compound('Polyphosphate', arguments=[4]) + self.assertNotEqual(c, Compound('Polyphosphate', arguments=[5])) + + def test_compounds_sorted(self): + l = sorted([Compound('A', arguments=[10]), + Compound('A'), Compound('B'), + Compound('A', arguments=[4]), Compound('A', 'e')]) + self.assertEqual(l, [Compound('A'), Compound('A', arguments=[4]), + Compound('A', arguments=[10]), + Compound('A', 'e'), Compound('B')]) + + def test_compound_str_basic(self): + self.assertEqual(text_type(Compound('Phosphate')), 'Phosphate') + + def test_compound_str_with_compartment(self): + self.assertEqual(text_type(Compound('Phosphate', 'e')), 'Phosphate[e]') + + def test_compound_str_with_argument(self): + self.assertEqual(text_type( + Compound('Polyphosphate', arguments=[3])), 'Polyphosphate(3)') + + def test_compound_str_with_compartment_and_argument(self): + self.assertEqual(text_type( + Compound('Polyphosphate', 'p', [3])), 'Polyphosphate(3)[p]') + + +class TestReaction(unittest.TestCase): + def test_reaction_init_empty_bidir(self): + r = Reaction(Direction.Both, [], []) + + def test_reaction_init_empty_left(self): + r = Reaction(Direction.Reverse, [], []) + + def test_reaction_init_empty_right(self): + r = Reaction(Direction.Forward, [], []) + + def test_reaction_init_from_two_iterables(self): + left = [(Compound('A'), 2), (Compound('B'), 3)] + right = [(Compound('C'), 1)] + r = Reaction(Direction.Forward, iter(left), iter(right)) + self.assertEqual(list(r.left), left) + self.assertEqual(list(r.right), right) + + def test_reaction_init_from_two_iterables_with_negative_lhs(self): + left = [(Compound('A'), 2), (Compound('B'), -3)] + right = [(Compound('C'), 1)] + with self.assertRaises(ValueError): + r = Reaction(Direction.Forward, iter(left), iter(right)) + + def test_reaction_init_from_two_iterables_with_negative_rhs(self): + left = [(Compound('A'), 2), (Compound('B'), 3)] + right = [(Compound('C'), -1)] + with self.assertRaises(ValueError): + r = Reaction(Direction.Forward, iter(left), iter(right)) + + def test_reaction_init_from_two_iterables_with_zero_lhs(self): + left = [(Compound('A'), 2), (Compound('B'), 0)] + right = [(Compound('C'), 1)] + r = Reaction(Direction.Forward, iter(left), iter(right)) + self.assertEqual(dict(r.compounds), { + Compound('A'): -2, + Compound('C'): 1 + }) + + def test_reaction_init_from_two_iterables_with_zero_rhs(self): + left = [(Compound('A'), 2), (Compound('B'), 3)] + right = [(Compound('C'), 0)] + r = Reaction(Direction.Forward, iter(left), iter(right)) + self.assertEqual(dict(r.compounds), { + Compound('A'): -2, + Compound('B'): -3 + }) + + def test_reaction_init_from_two_iterables_with_non_numbers(self): + left = [(Compound('A'), 'x')] + right = [(Compound('B'), 'y')] + r = Reaction(Direction.Forward, left, right) + + def test_reaction_init_from_one_iterable(self): + compounds = [(Compound('A'), -2), (Compound('B'), -3), + (Compound('C'), 1)] + r = Reaction(Direction.Forward, iter(compounds)) + self.assertEqual(list(r.compounds), compounds) + + def test_reaction_init_from_one_iterable_with_zero(self): + compounds = [ + (Compound('A'), -2), + (Compound('B'), 0), + (Compound('C'), 1) + ] + r = Reaction(Direction.Forward, iter(compounds)) + self.assertEqual(dict(r.compounds), { + Compound('A'): -2, + Compound('C'): 1 + }) + + def test_reaction_init_from_one_iterable_with_non_numbers(self): + compounds = [ + (Compound('A'), 'x'), + (Compound('B'), 3) + ] + with self.assertRaises(TypeError): + r = Reaction(Direction.Forward, iter(compounds)) + + def test_reaction_init_from_dict(self): + compounds = { + Compound('A'): -2, + Compound('B'): -3, + Compound('C'): 1 + } + r = Reaction(Direction.Forward, compounds) + self.assertEqual(dict(r.compounds), compounds) + + def test_reaction_init_from_reaction(self): + compounds = {Compound('A'): -1, Compound('B'): 1} + r = Reaction(Direction.Forward, compounds) + r2 = Reaction(r) + self.assertEqual(dict(r2.compounds), compounds) + self.assertEqual(r2.direction, Direction.Forward) + + def test_reaction_init_empty_invalid_direction(self): + with self.assertRaises(TypeError): + r = Reaction(None, [], []) + + def test_reaction_init_left_empty(self): + r = Reaction(Direction.Forward, [], [(Compound('A'), 1)]) + + def test_reaction_init_right_empty(self): + r = Reaction(Direction.Forward, [(Compound('A'), 1)], []) + + def test_reaction_init_none_empty(self): + r = Reaction(Direction.Both, + [(Compound('A'), 1)], [(Compound('B'), 1)]) + + def test_reaction_init_from_nothing(self): + with self.assertRaises(TypeError): + r = Reaction() + + def test_reaction_init_from_invalid_type(self): + with self.assertRaises(TypeError): + r = Reaction('abc') + + def test_reaction_init_too_many_variables(self): + with self.assertRaises(TypeError): + r = Reaction(Direction.Both, [(Compound('A'), 1)], + [(Compound('B'), 1)], [(Compound('C'), 1)]) + + def test_reaction_direction_property(self): + r = Reaction(Direction.Both, + [(Compound('A'), 1)], [(Compound('B'), 1)]) + self.assertEqual(r.direction, Direction.Both) + + def test_reaction_left_property(self): + r = Reaction(Direction.Both, + [(Compound('A'), 1)], [(Compound('B'), 1)]) + self.assertEqual(list(r.left), [(Compound('A'), 1)]) + + def test_reaction_right_property(self): + r = Reaction(Direction.Both, + [(Compound('A'), 1)], [(Compound('B'), 1)]) + self.assertEqual(list(r.right), [(Compound('B'), 1)]) + + def test_reaction_compounds_property(self): + r = Reaction(Direction.Both, + [(Compound('A'), 1)], [(Compound('B'), 1)]) + self.assertEqual(list(r.compounds), + [(Compound('A'), -1), (Compound('B'), 1)]) + + def test_reaction_normalized_of_bidir(self): + r = Reaction( + Direction.Both, [(Compound('Au'), 1)], + [(Compound('Pb'), 1)]).normalized() + self.assertEqual( + r, Reaction(Direction.Both, [(Compound('Au'), 1)], + [(Compound('Pb'), 1)])) + + def test_reaction_normalized_of_right(self): + r = Reaction( + Direction.Forward, [(Compound('Au'), 1)], + [(Compound('Pb'), 1)]).normalized() + self.assertEqual( + r, Reaction(Direction.Forward, [(Compound('Au'), 1)], + [(Compound('Pb'), 1)])) + + def test_reaction_normalized_of_left(self): + r = Reaction( + Direction.Reverse, [(Compound('Au'), 1)], + [(Compound('Pb'), 1)]).normalized() + self.assertEqual( + r, Reaction(Direction.Forward, [(Compound('Pb'), 1)], + [(Compound('Au'), 1)])) + + def test_reaction_translated_compounds(self): + r = Reaction(Direction.Forward, [(Compound('Pb'), 1)], + [(Compound('Au'), 1)]) + rt = r.translated_compounds(lambda name: name.lower()) + self.assertEqual( + rt, Reaction(Direction.Forward, [(Compound('pb'), 1)], + [(Compound('au'), 1)])) + + def test_reaction_format_simple(self): + r = Reaction( + Direction.Forward, [(Compound('Pb'), 1)], [(Compound('Au'), 1)]) + self.assertEqual(text_type(r), 'Pb => Au') + + def test_reaction_format_with_space(self): + r = Reaction( + Direction.Forward, [(Compound('A thing'), 1)], + [(Compound('Another thing'), 2), (Compound('B'), 1)]) + self.assertEqual(text_type(r), '|A thing| => (2) |Another thing| + B') + + def test_reaction_format_with_empty_right_side(self): + r = Reaction(Direction.Forward, [(Compound('A'), 1)], []) + self.assertEqual(text_type(r), 'A =>') + + def test_reaction_format_with_empty_left_side(self): + r = Reaction(Direction.Forward, [], [(Compound('A'), 1)]) + self.assertEqual(text_type(r), '=> A') + + def test_reaction_format_with_arguments(self): + pp1 = Compound('Polyphosphate', arguments=[4]) + pp2 = Compound('Polyphosphate', arguments=[5]) + r = Reaction(Direction.Forward, [(Compound('ATP'), 1), (pp1, 1)], + [(Compound('ADP'), 1), (pp2, 1)]) + self.assertEqual( + text_type(r), 'ATP + Polyphosphate(4) => ADP + Polyphosphate(5)') + + def test_reaction_equals_other(self): + r = Reaction(Direction.Forward, [(Compound('Pb'), 1)], + [(Compound('Au'), 1)]) + self.assertEqual( + r, Reaction(Direction.Forward, [(Compound('Pb'), 1)], + [(Compound('Au'), 1)])) + + def test_reaction_not_equals_other_with_different_compounds(self): + r = Reaction(Direction.Forward, [(Compound('Au'), 1)], + [(Compound('Pb'), 1)]) + self.assertNotEqual( + r, Reaction(Direction.Forward, [(Compound('Pb'), 1)], + [(Compound('Au'), 1)])) + + def test_reaction_not_equals_other_with_different_direction(self): + r = Reaction(Direction.Forward, [(Compound('Au'), 1)], + [(Compound('Pb'), 1)]) + self.assertNotEqual( + r, Reaction(Direction.Reverse, [(Compound('Pb'), 1)], + [(Compound('Au'), 1)])) + + def test_reaction_plus_reaction_forward(self): + r = Reaction(Direction.Forward, {Compound('A'): -1, Compound('B'): 1}) + s = Reaction(Direction.Forward, {Compound('B'): -1, Compound('C'): 1}) + t = r + s + self.assertEqual(t.direction, Direction.Forward) + self.assertEqual(dict(t.compounds), { + Compound('A'): -1, + Compound('C'): 1}) + + def test_reaction_plus_reaction_reverse(self): + r = Reaction(Direction.Reverse, {Compound('A'): -1, Compound('B'): 1}) + s = Reaction(Direction.Reverse, {Compound('B'): -1, Compound('C'): 1}) + t = r + s + self.assertEqual(t.direction, Direction.Reverse) + + def test_reaction_plus_reaction_both(self): + r = Reaction(Direction.Both, {Compound('A'): -1, Compound('B'): 1}) + s = Reaction(Direction.Both, {Compound('B'): -1, Compound('C'): 1}) + t = r + s + self.assertEqual(t.direction, Direction.Both) + + def test_reaction_plus_reaction_mixed(self): + r = Reaction(Direction.Forward, {Compound('A'): -1, Compound('B'): 1}) + s = Reaction(Direction.Both, {Compound('B'): -1, Compound('C'): 1}) + t = r + s + self.assertEqual(t.direction, Direction.Forward) + + def test_reaction_plus_reaction_incompatible(self): + r = Reaction(Direction.Forward, {Compound('A'): -1, Compound('B'): 1}) + s = Reaction(Direction.Reverse, {Compound('B'): -1, Compound('C'): 1}) + with self.assertRaises(ValueError): + t = r + s + + def test_reaction_minus_reaction(self): + r = Reaction(Direction.Forward, {Compound('A'): -1, Compound('B'): 1}) + s = Reaction(Direction.Reverse, {Compound('C'): -1, Compound('B'): 1}) + t = r - s + self.assertEqual(t.direction, Direction.Forward) + self.assertEqual(dict(t.compounds), { + Compound('A'): -1, + Compound('C'): 1}) + + def test_reaction_negate(self): + r = Reaction(Direction.Forward, {Compound('A'): -1, Compound('B'): 1}) + s = -r + self.assertEqual(s.direction, Direction.Reverse) + self.assertEqual(dict(s.compounds), { + Compound('B'): -1, + Compound('A'): 1}) + + def test_reaction_multiply(self): + r = Reaction(Direction.Forward, {Compound('A'): -1, Compound('B'): 3}) + s = 2 * r + self.assertEqual(s.direction, Direction.Forward) + self.assertEqual(dict(s.compounds), { + Compound('A'): -2, + Compound('B'): 6}) + + +class TestDirection(unittest.TestCase): + def test_forward_direction(self): + d = Direction.Forward + self.assertTrue(d.forward) + self.assertFalse(d.reverse) + + def test_right_direction(self): + d = Direction.Right + self.assertTrue(d.forward) + self.assertFalse(d.reverse) + + def test_reverse_direction(self): + d = Direction.Reverse + self.assertTrue(d.reverse) + self.assertFalse(d.forward) + + def test_left_direction(self): + d = Direction.Left + self.assertTrue(d.reverse) + self.assertFalse(d.forward) + + def test_both_directions(self): + d = Direction.Both + self.assertTrue(d.forward) + self.assertTrue(d.reverse) + + def test_bidir_direction(self): + d = Direction.Bidir + self.assertTrue(d.forward) + self.assertTrue(d.reverse) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_robustness.py",".py","7383","190","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2020 Elysha Sameth + +from __future__ import unicode_literals + +import unittest + +from psamm import fluxanalysis +from psamm.lpsolver import generic +from psamm.datasource import native +from psamm.database import DictDatabase +from psamm.metabolicmodel import MetabolicModel +from psamm.datasource.reaction import parse_reaction +from psamm.commands.robustness import RobustnessTaskHandler, \ + RobustnessTaskHandlerFva + +from six import itervalues + + +class TestRobustnessTaskHandler(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + self._problem = fluxanalysis.FluxBalanceProblem( + self.model, self.solver) + self._reactions = list(self.model.reactions) + + def test1_loop_removal_none(self): + fluxes = RobustnessTaskHandler.handle_task(RobustnessTaskHandler( + self.model, self.solver, 'none', self._reactions), + ['rxn_6', 1000], 'rxn_6') + + self.assertAlmostEqual(fluxes['rxn_1'], 500) + self.assertAlmostEqual(fluxes['rxn_2'], 0) + self.assertAlmostEqual(fluxes['rxn_6'], 1000) + + def test2_loop_removal_l1min(self): + fluxes = RobustnessTaskHandler.handle_task(RobustnessTaskHandler( + self.model, self.solver, 'l1min', self._reactions), + ['rxn_6', 1000], 'rxn_6') + + self.assertAlmostEqual(fluxes['rxn_1'], 500) + self.assertAlmostEqual(fluxes['rxn_2'], 0) + self.assertAlmostEqual(fluxes['rxn_3'], 1000) + self.assertAlmostEqual(fluxes['rxn_4'], 0) + self.assertAlmostEqual(fluxes['rxn_5'], 0) + self.assertAlmostEqual(fluxes['rxn_6'], 1000) + + def test3_loop_removal_tfba(self): + try: + self.solver = generic.Solver(integer=True) + except generic.RequirementsError: + self.skipTest('Unable to find an MIQP solver for tests') + + fluxes = RobustnessTaskHandler.handle_task(RobustnessTaskHandler( + self.model, self.solver, 'tfba', self._reactions), + ['rxn_3', 100], 'rxn_1') + + self.assertAlmostEqual(fluxes['rxn_1'], 500) + self.assertAlmostEqual(fluxes['rxn_2'], 0) + self.assertAlmostEqual(fluxes['rxn_3'], 100) + self.assertAlmostEqual(fluxes['rxn_4'], 900) + self.assertAlmostEqual(fluxes['rxn_5'], 900) + self.assertAlmostEqual(fluxes['rxn_6'], 1000) + + def test4_no_reactions(self): + self._reactions2 = None + fluxes = RobustnessTaskHandler.handle_task(RobustnessTaskHandler( + self.model, self.solver, 'none', self._reactions2), + ['rxn_6', 10], 'rxn_6') + self.assertEqual(fluxes, 10) + + +class TestRobustnessTaskHandlerFva(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + self.database.set_reaction('rxn_7', parse_reaction('|E| => |F|')) + self.database.set_reaction('rxn_8', parse_reaction('|F| => |E|')) + + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + self.model.limits['rxn_5'].upper = 100 + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + self._problem = fluxanalysis.FluxBalanceProblem( + self.model, self.solver) + self._reactions = list(self.model.reactions) + + def test1_loop_removal_none(self): + fluxes = RobustnessTaskHandlerFva.handle_task(RobustnessTaskHandlerFva( + self.model, self.solver, 'none', self._reactions), + ['rxn_6', 200], 'rxn_6') + + for bounds in itervalues(fluxes): + self.assertEqual(len(bounds), 2) + + self.assertAlmostEqual(fluxes['rxn_1'][0], 100) + + self.assertAlmostEqual(fluxes['rxn_2'][0], 0) + self.assertAlmostEqual(fluxes['rxn_2'][1], 0) + + self.assertAlmostEqual(fluxes['rxn_5'][0], 0) + self.assertAlmostEqual(fluxes['rxn_5'][1], 100) + + self.assertAlmostEqual(fluxes['rxn_6'][0], 200) + + self.assertGreater(fluxes['rxn_7'][1], 0) + self.assertGreater(fluxes['rxn_8'][1], 0) + + def test2_loop_removal_tfba(self): + try: + self.solver = generic.Solver(integer=True) + except generic.RequirementsError: + self.skipTest('Unable to find an MIQP solver for tests') + + fluxes = RobustnessTaskHandlerFva.handle_task(RobustnessTaskHandlerFva( + self.model, self.solver, 'tfba', self._reactions), + ['rxn_6', 200], 'rxn_3') + + for bounds in itervalues(fluxes): + self.assertEqual(len(bounds), 2) + + self.assertAlmostEqual(fluxes['rxn_1'][0], 100) + + self.assertAlmostEqual(fluxes['rxn_2'][0], 0) + self.assertAlmostEqual(fluxes['rxn_2'][1], 0) + + self.assertAlmostEqual(fluxes['rxn_3'][0], 200) + + self.assertAlmostEqual(fluxes['rxn_5'][0], 0) + self.assertAlmostEqual(fluxes['rxn_5'][1], 0) + + self.assertAlmostEqual(fluxes['rxn_6'][0], 200) + + self.assertAlmostEqual(fluxes['rxn_7'][1], 0) + self.assertAlmostEqual(fluxes['rxn_8'][1], 0) + + def test3_no_reactions(self): + self._reactions2 = None + fluxes = RobustnessTaskHandlerFva.handle_task(RobustnessTaskHandlerFva( + self.model, self.solver, 'none', self._reactions2), + ['rxn_6', 200], 'rxn_6') + + for bounds in itervalues(fluxes): + self.assertEqual(len(bounds), 2) + + self.assertAlmostEqual(fluxes['rxn_6'][0], 200) + self.assertAlmostEqual(fluxes['rxn_6'][1], 200) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_expression_boolean.py",".py","12191","336","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.expression.boolean import (Expression, And, Or, Variable, + ParseError, SubstitutionError) + + +class TestVariable(unittest.TestCase): + def test_variable_init(self): + v = Variable('x') + + def test_variable_init_long_symbol(self): + v = Variable('xyz') + + def test_variable_init_number_symbol(self): + v = Variable('x2') + + def test_variable_init_underscore_symbol(self): + v = Variable('x_y') + + def test_variable_init_from_unicode(self): + symbol = u'\u00c6\u00d8\u00c5' + v = Variable(symbol) + self.assertEqual(v.symbol, symbol) + + def test_variable_init_with_dot_symbol(self): + v = Variable('x12345.6') + + def test_variable_init_with_number(self): + v = Variable('123') + + def test_variable_symbol(self): + self.assertEqual(Variable('x').symbol, 'x') + + def test_variables_equals_true(self): + self.assertEqual(Variable('x'), Variable('x')) + + def test_variables_not_equals(self): + self.assertNotEqual(Variable('x'), Variable('y')) + + def test_variable_not_equals_bool(self): + self.assertNotEqual(Variable('x'), True) + + def test_variable_hash(self): + self.assertEqual(hash(Variable('xyz')), hash(Variable('xyz'))) + + +class TestTerm(unittest.TestCase): + def test_length_of_and(self): + term = And(Variable('b1'), Variable('b2')) + self.assertEqual(len(term), 2) + + def test_length_of_or(self): + term = Or(Variable('b1'), And(Variable('b2'), Variable('b3'))) + self.assertEqual(len(term), 2) + + +class TestExpression(unittest.TestCase): + def test_expression_substitute_existing(self): + e = Expression('b1') + e1 = e.substitute(lambda v: {'b1': True}.get(v.symbol, v)) + self.assertTrue(e1.has_value()) + self.assertTrue(e1.value) + + def test_expression_substitute_existing_false(self): + e = Expression('b1') + e1 = e.substitute(lambda v: {'b1': False}.get(v.symbol, v)) + self.assertTrue(e1.has_value()) + self.assertFalse(e1.value) + + def test_expression_substitute_unknown_to_variable(self): + e = Expression('b1') + e1 = e.substitute(lambda v: v) + self.assertEqual(e1, Expression(Variable('b1'))) + + def test_expression_substitute_unknown_to_expression(self): + e = Expression('b1 and b2') + e1 = e.substitute(lambda v: v) + self.assertEqual(e1, Expression('b1 and b2')) + + def test_expression_substitute_invalid(self): + e = Expression('b1 and b2') + with self.assertRaises(SubstitutionError): + e.substitute(lambda v: {'b1': 17}.get(v.symbol, v)) + + def test_expression_substitute_with_short_circuit_and(self): + e = Expression('a and (b or c) and d') + e1 = e.substitute(lambda v: {'a': False}.get(v.symbol, v)) + self.assertTrue(e1.has_value()) + self.assertFalse(e1.value) + + def test_expression_substitute_with_short_circuit_or(self): + e = Expression('(a and b) or c or d') + e1 = e.substitute(lambda v: {'c': True}.get(v.symbol, v)) + self.assertTrue(e1.has_value()) + self.assertTrue(e1.value) + + def test_expression_substitute_remove_terms_from_and(self): + e = Expression('a and b') + e1 = e.substitute(lambda v: {'a': True}.get(v.symbol, v)) + self.assertEqual(e1, Expression(Variable('b'))) + + def test_expression_substitute_remove_terms_from_or(self): + e = Expression('a or b') + e1 = e.substitute(lambda v: {'a': False}.get(v.symbol, v)) + self.assertEqual(e1, Expression(Variable('b'))) + + def test_expression_substitute_evaluate_all_and_terms_to_true(self): + e = Expression('a and b') + e1 = e.substitute(lambda v: True) + self.assertEqual(e1, Expression(True)) + + def test_expression_substitute_evaluate_all_or_terms_to_false(self): + e = Expression('a or b') + e1 = e.substitute(lambda v: False) + self.assertEqual(e1, Expression(False)) + + def test_expression_iter_variables(self): + e = Expression( + Or( + And(Variable('b1'), Variable('b2')), + And(Variable('b3'), Variable('b4')))) + self.assertEqual(list(e.variables), [ + Variable('b1'), Variable('b2'), Variable('b3'), Variable('b4') + ]) + + def test_expression_root(self): + e = Expression(Or(Variable('b1'), Variable('b2'))) + root = e.root + self.assertIsInstance(e.root, Or) + + def test_expression_root_boolean(self): + e = Expression(False) + self.assertEqual(e.root, False) + + def test_expression_to_string(self): + e = Expression('(a and b) or (c and d)') + self.assertEqual(str(e), '(a and b) or (c and d)') + + def test_expression_with_variable_to_string(self): + e = Expression(Variable('a')) + self.assertEqual(str(e), 'a') + + def test_expression_with_bool_to_string(self): + e = Expression(False) + self.assertEqual(str(e), 'False') + + def test_expression_parse_and(self): + e = Expression('b1 and b2') + self.assertEqual(e, Expression( + And(Variable('b1'), Variable('b2')))) + + def test_expression_parse_or(self): + e = Expression('b1 or b2') + self.assertEqual(e, Expression( + Or(Variable('b1'), Variable('b2')))) + + def test_expression_parse_multiple_with_duplicates(self): + e = Expression('b1 and b2 and b1 and b4') + self.assertEqual(e, Expression( + And(Variable('b1'), Variable('b2'), Variable('b4')))) + + def test_expression_parse_multiple_and(self): + e = Expression('b1 and b2 and b3 and b4') + self.assertEqual(e, Expression( + And( + Variable('b1'), Variable('b2'), Variable('b3'), + Variable('b4')))) + + def test_expression_parse_multiple_or(self): + e = Expression('b1 or b2 or b3 or b4') + self.assertEqual(e, Expression( + Or( + Variable('b1'), Variable('b2'), Variable('b3'), + Variable('b4')))) + + def test_expression_parse_multiple_parenthesis_and(self): + e = Expression('b1 and (b2 and b3) and b4') + self.assertEqual(e, Expression( + And( + Variable('b1'), Variable('b2'), Variable('b3'), + Variable('b4')))) + + def test_expression_parse_multiple_parenthesis_or(self): + e = Expression('b1 or (b2 or b3) or b4') + self.assertEqual(e, Expression( + Or( + Variable('b1'), Variable('b2'), Variable('b3'), + Variable('b4')))) + + def test_expression_parse_parentheses_mixed_1(self): + e = Expression('(b1 and b2) or (b3 and b4)') + self.assertEqual(e, Expression( + Or( + And(Variable('b1'), Variable('b2')), + And(Variable('b3'), Variable('b4'))))) + + def test_expression_parse_parentheses_mixed_2(self): + e = Expression('(b1 or b2) and (b3 or b4)') + self.assertEqual(e, Expression( + And( + Or(Variable('b1'), Variable('b2')), + Or(Variable('b3'), Variable('b4'))))) + + def test_expression_parse_uppercase_operators(self): + e = Expression('(b1 AND b2) OR b3') + self.assertEqual(e, Expression( + Or( + Variable('b3'), + And(Variable('b1'), Variable('b2'))))) + + def test_expression_parse_parenthesis_with_space_right(self): + e = Expression('(b1 and b2 )') + self.assertEqual(e, Expression( + And(Variable('b1'), Variable('b2')))) + + def test_expression_parse_parenthesis_with_space_left(self): + e = Expression('( b1 and b2)') + self.assertEqual(e, Expression( + And(Variable('b1'), Variable('b2')))) + + def test_expression_parse_parentheses_right_nested(self): + e = Expression('(b1 or (b2 and (b3 or (b4 and (b5)))))') + self.assertEqual(e, Expression( + Or( + Variable('b1'), + And( + Variable('b2'), + Or( + Variable('b3'), + And(Variable('b4'), Variable('b5'))))))) + + def test_expression_parse_parentheses_left_nested(self): + e = Expression('(((b1 or b2) and b3) or b4) and (b5)') + self.assertEqual(e, Expression( + And( + Variable('b5'), + Or( + Variable('b4'), + And( + Variable('b3'), + Or(Variable('b1'), Variable('b2'))))))) + + def test_expression_parse_implicit_mixed_1(self): + e = Expression('b1 and b2 or b3 and b4') + self.assertEqual(e, Expression( + Or( + And(Variable('b1'), Variable('b2')), + And(Variable('b3'), Variable('b4'))))) + + def test_expression_parse_implicit_mixed_2(self): + e = Expression('b1 or b2 and b3 or b4') + self.assertEqual(e, Expression( + Or( + Variable('b1'), + And(Variable('b2'), Variable('b3')), + Variable('b4')))) + + def test_expression_parse_longer_names(self): + e = Expression('b12345 and bxyz and testtesttest') + self.assertEqual(e, Expression( + And( + Variable('b12345'), Variable('bxyz'), + Variable('testtesttest')))) + + def test_expression_parse_with_missing_variable(self): + with self.assertRaises(ParseError): + e = Expression('b1 and and b3') + + def test_expression_parse_with_missing_end_parenthesis(self): + with self.assertRaises(ParseError): + e = Expression('b1 and (b2 or b3') + + def test_expression_parse_name_starting_with_or(self): + e = Expression('b1 and order') + self.assertEqual(e, Expression( + And(Variable('b1'), Variable('order')))) + + def test_expression_parse_name_starting_with_and(self): + e = Expression('b1 or anderson') + self.assertEqual(e, Expression( + Or(Variable('b1'), Variable('anderson')))) + + def test_expression_parse_with_extra_space(self): + e = Expression('b1 and b2 and b3') + self.assertEqual(e, Expression( + And(Variable('b1'), Variable('b2'), Variable('b3')))) + + def test_expression_parse_with_square_mixed_groups(self): + e = Expression('[(a or b) or (c or d)] or [e or (f and g and h)]') + self.assertEqual(e, Expression( + Or( + Variable('a'), Variable('b'), Variable('c'), Variable('d'), + Variable('e'), + And(Variable('f'), Variable('g'), Variable('h'))))) + + def test_expression_parse_with_square_groups_unmatched(self): + with self.assertRaises(ParseError): + e = Expression('[(a or b) or (c or d])') + + +class TestParseError(unittest.TestCase): + def test_parse_error_without_indicator(self): + e = ParseError('Random error') + self.assertIsNone(e.indicator) + + def test_parse_error_with_indicator(self): + e = ParseError('Random error', span=(3, 5)) + self.assertEqual(e.indicator, ' ^^') + + def test_parse_error_with_zero_width_indicator(self): + e = ParseError('Random error', span=(4, 4)) + self.assertEqual(e.indicator, ' ^') + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_graph.py",".py","66406","1337","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2020 Elysha Sameth + + +from __future__ import unicode_literals + +from psamm import graph +import os +import tempfile +import unittest +from collections import defaultdict +from psamm.datasource.reaction import parse_reaction, parse_compound, \ + Direction, Compound +from psamm.datasource.native import NativeModel, ReactionEntry, CompoundEntry +from psamm.formula import Formula, Atom, ParseError + + +class TestGraph(unittest.TestCase): + def setUp(self): + self.fum = CompoundEntry({ + 'id': 'fum_c', 'formula': 'C4H2O4'}) + self.rxn1 = ReactionEntry({ + 'id': 'rxn1', 'equation': parse_reaction( + 'fum_c[c] + h2o_c[c] <=> mal_L_c[c]')}) + self.rxn2 = ReactionEntry({ + 'id': 'rxn2', 'equation': parse_reaction( + 'fum_c[c] + h2o_c[c] <=> mal_L_c[c]')}) + self.g = graph.Graph() + self.node1 = graph.Node({'id': 'A'}) + self.node2 = graph.Node({'id': 'B', 'color': 'blue'}) + self.node3 = graph.Node({'id': 'C', 'color': 'red'}) + self.node4 = graph.Node({'id': 'D', + 'original_id': ['A', 'B'], 'type': 'rxn'}) + self.node5 = graph.Node({'id': 'E', + 'original_id': 'cpd_E', 'type': 'cpd'}) + self.node6 = graph.Node({'id': 'Ex_e', + 'type': 'Ex_rxn'}) + self.node7 = graph.Node({'id': 'Ex_e', + 'type': 'cpd', 'entry': [self.fum]}) + self.node8 = graph.Node({'id': 'rxn1', + 'type': 'cpd', 'entry': [self.rxn1]}) + self.node9 = graph.Node({'id': 'rxn1_rxn2', + 'type': 'cpd', 'entry': + [self.rxn1, self.rxn2]}) + self.edge1_2 = graph.Edge(self.node1, self.node2) + self.edge2_3 = graph.Edge(self.node2, self.node3, + props={'id': '2_3'}) + + def test_add_node(self): + self.g.add_node(self.node1) + self.assertTrue(self.node1 in self.g.nodes) + + def test_node_id_dict(self): + self.g.add_node(self.node1) + self.assertEqual(self.node1, self.g._nodes_id[self.node1.props['id']]) + + def test_add_multiple_nodes(self): + self.g.add_node(self.node1) + self.g.add_node(self.node2) + self.assertTrue(all(i in self.g.nodes + for i in [self.node1, self.node2])) + + def test_original_id_EX(self): + self.g.add_node(self.node6) + nd = defaultdict(list) + nd['Ex_e'].append(self.node6) + self.assertTrue(self.g._nodes_original_id == nd) + + def test_original_id_cpd(self): + self.g.add_node(self.node7) + nd = defaultdict(list) + nd[self.fum.id].append(self.node7) + self.assertTrue(self.g._nodes_original_id == nd) + + def test_original_id_rxn(self): + self.g.add_node(self.node8) + nd = defaultdict(list) + nd[self.rxn1.id].append(self.node8) + self.assertTrue(self.g._nodes_original_id == nd) + + def test_original_id_rxn(self): + self.g.add_node(self.node9) + nd = defaultdict(list) + nd['rxn1,rxn2'].append(self.node9) + self.assertEqual(self.g._nodes_original_id, nd) + + def test_node_count(self): + self.g.add_node(self.node1) + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.assertEqual(self.g.node_count, 3) + + def test_add_edge(self): + self.g.add_node(self.node1) + self.g.add_node(self.node2) + self.g.add_edge(self.edge1_2) + self.assertTrue(self.edge1_2 in self.g.edges) + + def test_add_edge_with_props(self): + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + self.assertTrue(self.edge2_3 in self.g.edges) + + def test_add_multiple_edges(self): + self.g.add_node(self.node1) + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge1_2) + self.g.add_edge(self.edge2_3) + self.assertTrue(all(i in self.g.edges + for i in [self.edge1_2, self.edge2_3])) + + def test_edge_count(self): + self.g.add_node(self.node1) + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge1_2) + self.g.add_edge(self.edge2_3) + self.assertTrue(self.g.edge_count, 2) + + def test_add_edge_missing_node(self): + self.g.add_node(self.node1) + with self.assertRaises(ValueError): + self.g.add_edge(self.edge1_2) + + def test_edges_for(self): + self.g.add_node(self.node1) + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge1_2) + self.g.add_edge(self.edge2_3) + edges_for_list = [] + for i in self.g.edges_for(self.node1): + edges_for_list.append(i) + self.assertTrue(edges_for_list == [(self.node2, + set([self.edge1_2]))]) + self.assertEqual('A', 'A') + + def test_get_node(self): + self.g.add_node(self.node1) + test_node = self.g.get_node('A') + self.assertEqual(test_node, self.node1) + + def test_nodes_id_dict(self): + self.g.add_node(self.node1) + self.g.add_node(self.node2) + self.assertEqual(self.g.nodes_id_dict, {'A': self.node1, + 'B': self.node2}) + + def test_default_edge_props(self): + self.g._default_edge_props['style'] = 'dashed' + d = {'style': 'dashed'} + self.assertEqual(d, self.g.default_edge_props) + + def test_default_node_props(self): + self.g._default_node_props['shape'] = 'box' + d = {'shape': 'box'} + self.assertEqual(d, self.g.default_node_props) + + def test_write_nodes_table(self): + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_node') + with open(path, mode='w') as f: + self.g.write_nodes_tables(f) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(read_file, ['id\tcolor\tlabel\n', + 'B\tblue\tB\n', 'C\tred\tC\n']) + + def test_write_nodes_table_with_original_id(self): + self.g.add_node(self.node2) + self.node3.props['original_id'] = 'A_1' + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_node') + with open(path, mode='w') as f: + self.g.write_nodes_tables(f) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(read_file, ['id\tcolor\tlabel\n', + 'B\tblue\tB\n', 'C\tred\tC\n']) + + def test_write_edges_tables(self): + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_edge') + with open(path, mode='w') as f: + self.g.write_edges_tables(f) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(read_file, ['source\ttarget\tid\n', 'B\tC\t2_3\n']) + + def test_write_graphviz(self): + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_edge') + with open(path, mode='w') as f: + self.g.write_graphviz(f, 2, 2) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(['digraph {\n', 'size = ""2, 2""; ratio = fill;\n', + ' ""B""[color=""blue"",id=""B""]\n', + ' ""C""[color=""red"",id=""C""]\n', + ' ""B"" -> ""C""[id=""2_3""]\n', '}\n'], read_file) + + def test_write_graphviz_graph_props(self): + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + self.g.props['fontsize'] = 12 + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_edge') + with open(path, mode='w') as f: + self.g.write_graphviz(f, 2, 2) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(['digraph {\n', 'size = ""2, 2""; ratio = fill;\n', + ' fontsize=""12"";\n', ' ""B""[color=""blue"",id=""B""]\n', + ' ""C""[color=""red"",id=""C""]\n', + ' ""B"" -> ""C""[id=""2_3""]\n', '}\n'], read_file) + + def test_write_graphviz_default_node_props(self): + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + self.g._default_node_props['fontname'] = 'Arial' + self.g._default_node_props['fontsize'] = 12 + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_edge') + with open(path, mode='w') as f: + self.g.write_graphviz(f, 2, 2) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(['digraph {\n', 'size = ""2, 2""; ratio = fill;\n', + ' node[fontname=""Arial"",fontsize=""12""];\n', + ' ""B""[color=""blue"",id=""B""]\n', + ' ""C""[color=""red"",id=""C""]\n', + ' ""B"" -> ""C""[id=""2_3""]\n', '}\n'], read_file) + + def test_write_graphvizdefault_edge_props(self): + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + self.g._default_edge_props['style'] = 'dashed' + self.g._default_edge_props['width'] = 12 + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_edge') + with open(path, mode='w') as f: + self.g.write_graphviz(f, 2, 2) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(['digraph {\n', 'size = ""2, 2""; ratio = fill;\n', + ' edge[style=""dashed"",width=""12""];\n', + ' ""B""[color=""blue"",id=""B""]\n', + ' ""C""[color=""red"",id=""C""]\n', + ' ""B"" -> ""C""[id=""2_3""]\n', '}\n'], read_file) + + def test_write_graphviz_default_size(self): + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + self.g._default_node_props['fontname'] = 'Arial' + self.g._default_node_props['fontsize'] = 12 + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_edge') + with open(path, mode='w') as f: + self.g.write_graphviz(f, None, None) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(read_file, + ['digraph {\n', + ' node[fontname=""Arial"",fontsize=""12""];\n', + ' ""B""[color=""blue"",id=""B""]\n', + ' ""C""[color=""red"",id=""C""]\n', + ' ""B"" -> ""C""[id=""2_3""]\n', '}\n']) + + def test_write_graphviz_compartmentalize(self): + self.node2.props['compartment'] = 'c' + self.node3.props['compartment'] = 'e' + self.edge2_3.props['compartment'] = 'e' + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_edge') + with open(path, mode='w') as f: + self.g.write_graphviz_compartmentalized( + f, {'e': {'c'}, 'c': set()}, 'e', 2, 2) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(read_file, + ['digraph {\n', + 'size=""2,2""; ratio = fill;\n', + ' subgraph cluster_e {\n', + ' style=solid;\n', ' color=black;\n', + ' penwidth=4;\n', ' fontsize=35;\n', + ' label = ""Compartment: e""\n', + ' ""C""[color=""red"",compartment=""e"",id=""C""]\n', + ' subgraph cluster_c {\n', ' style=dashed;\n', + ' color=black;\n', ' penwidth=4;\n', + ' fontsize=35;\n', ' label = ""Compartment: c""\n', + ' ""B""[color=""blue"",compartment=""c"",id=""B""]\n', + '}} ""B"" -> ""C""[compartment=""e"",id=""2_3""]\n', '}\n']) + + def test_write_graphviz_compartmentalize_default_size(self): + self.node2.props['compartment'] = 'c' + self.node3.props['compartment'] = 'e' + self.edge2_3.props['compartment'] = 'e' + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_edge') + with open(path, mode='w') as f: + self.g.write_graphviz_compartmentalized( + f, {'e': {'c'}, 'c': set()}, 'e', None, None) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(read_file, + ['digraph {\n', ' subgraph cluster_e {\n', + ' style=solid;\n', ' color=black;\n', + ' penwidth=4;\n', ' fontsize=35;\n', + ' label = ""Compartment: e""\n', + ' ""C""[color=""red"",compartment=""e"",id=""C""]\n', + ' subgraph cluster_c {\n', ' style=dashed;\n', + ' color=black;\n', ' penwidth=4;\n', + ' fontsize=35;\n', + ' label = ""Compartment: c""\n', + ' ""B""[color=""blue"",compartment=""c"",id=""B""]\n', + '}} ""B"" -> ""C""[compartment=""e"",id=""2_3""]\n', '}\n']) + + def test_write_graphviz_compartmentalize_default_node_props(self): + self.node2.props['compartment'] = 'c' + self.node3.props['compartment'] = 'e' + self.edge2_3.props['compartment'] = 'e' + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + self.g._default_node_props['fontname'] = 'Arial' + self.g._default_node_props['fontsize'] = 12 + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_edge') + with open(path, mode='w') as f: + self.g.write_graphviz_compartmentalized( + f, {'e': {'c'}, 'c': set()}, 'e', None, None) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(read_file, + ['digraph {\n', + ' node[fontname=""Arial"",fontsize=""12""];\n', + ' subgraph cluster_e {\n', ' style=solid;\n', + ' color=black;\n', ' penwidth=4;\n', + ' fontsize=35;\n', ' label = ""Compartment: e""\n', + ' ""C""[color=""red"",compartment=""e"",id=""C""]\n', + ' subgraph cluster_c {\n', ' style=dashed;\n', + ' color=black;\n', ' penwidth=4;\n', + ' fontsize=35;\n', ' label = ""Compartment: c""\n', + ' ""B""[color=""blue"",compartment=""c"",id=""B""]\n', + '}} ""B"" -> ""C""[compartment=""e"",id=""2_3""]\n', '}\n']) + + def test_write_graphviz_compartmentalize_default_edge_props(self): + self.node2.props['compartment'] = 'c' + self.node3.props['compartment'] = 'e' + self.edge2_3.props['compartment'] = 'e' + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + self.g._default_edge_props['style'] = 'dashed' + self.g._default_edge_props['width'] = 12 + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_edge') + with open(path, mode='w') as f: + self.g.write_graphviz_compartmentalized( + f, {'e': {'c'}, 'c': set()}, 'e', None, None) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(read_file, + ['digraph {\n', + ' edge[style=""dashed"",width=""12""];\n', + ' subgraph cluster_e {\n', ' style=solid;\n', + ' color=black;\n', ' penwidth=4;\n', + ' fontsize=35;\n', ' label = ""Compartment: e""\n', + ' ""C""[color=""red"",compartment=""e"",id=""C""]\n', + ' subgraph cluster_c {\n', ' style=dashed;\n', + ' color=black;\n', ' penwidth=4;\n', + ' fontsize=35;\n', ' label = ""Compartment: c""\n', + ' ""B""[color=""blue"",compartment=""c"",id=""B""]\n', + '}} ""B"" -> ""C""[compartment=""e"",id=""2_3""]\n', '}\n']) + + def test_write_graphviz_compartmentalize_default_graph_props(self): + self.node2.props['compartment'] = 'c' + self.node3.props['compartment'] = 'e' + self.edge2_3.props['compartment'] = 'e' + self.g.add_node(self.node2) + self.g.add_node(self.node3) + self.g.add_edge(self.edge2_3) + self.g.props['fontsize'] = 12 + path = os.path.join(tempfile.mkdtemp(), 'tmp_cyto_edge') + with open(path, mode='w') as f: + self.g.write_graphviz_compartmentalized( + f, {'e': {'c'}, 'c': set()}, 'e', None, None) + read_file = [] + f = open(path, 'r') + for i in f.readlines(): + read_file.append(i) + f.close() + self.assertEqual(read_file, + ['digraph {\n', ' fontsize=""12"";\n', + ' subgraph cluster_e {\n', + ' style=solid;\n', ' color=black;\n', + ' penwidth=4;\n', ' fontsize=35;\n', + ' label = ""Compartment: e""\n', + ' ""C""[color=""red"",compartment=""e"",id=""C""]\n', + ' subgraph cluster_c {\n', ' style=dashed;\n', + ' color=black;\n', ' penwidth=4;\n', + ' fontsize=35;\n', + ' label = ""Compartment: c""\n', + ' ""B""[color=""blue"",compartment=""c"",id=""B""]\n', + '}} ""B"" -> ""C""[compartment=""e"",id=""2_3""]\n', '}\n']) + + +class TestNodes(unittest.TestCase): + def setUp(self): + self.g = graph.Graph() + self.node1 = graph.Node({'id': 'A'}) + self.node2 = graph.Node({'id': 'B'}) + self.node3 = graph.Node({'id': 'C'}) + self.edge1_2 = graph.Edge(self.node1, self.node2) + + def test_eq_nodes(self): + self.g.add_node(self.node1) + self.assertEqual(self.node1 == self.g.get_node('A'), + self.node1.props == self.g.get_node('A').props) + + def test_neq_nodes(self): + self.assertTrue(self.node1 != self.node2) + + def test_neq_node_edge(self): + self.assertFalse(self.node1 == self.edge1_2) + + def test_node_repr(self): + rep = self.node1.__repr__() + self.assertEqual(rep, '') + + +class TestOther(unittest.TestCase): + def setUp(self): + native_model = NativeModel() + self.rxn1 = ReactionEntry({ + 'id': 'rxn1', 'equation': parse_reaction( + 'fum_c[c] + h2o_c[c] <=> mal_L_c[c]')}) + native_model.reactions.add_entry(self.rxn1) + + self.fum = CompoundEntry({ + 'id': 'fum_c', 'formula': 'C4H2O4'}) + native_model.compounds.add_entry(self.fum) + + self.h2o = CompoundEntry({ + 'id': 'h2o_c', 'formula': 'H2O'}) + native_model.compounds.add_entry(self.h2o) + + self.mal = CompoundEntry( + {'id': 'mal_L_c', 'formula': 'C4H4O5'}) + native_model.compounds.add_entry(self.mal) + + self.rxn2 = ReactionEntry({ + 'id': 'rxn2', 'equation': parse_reaction( + 'q8_c[c] + succ_c[c] => fum_c[c] + q8h2_c[c]')}) + native_model.reactions.add_entry(self.rxn2) + + self.q8 = CompoundEntry( + {'id': 'q8_c', 'formula': 'C49H74O4'}) + native_model.compounds.add_entry(self.q8) + + self.q8h2 = CompoundEntry({ + 'id': 'q8h2_c', 'formula': 'C49H76O4'}) + native_model.compounds.add_entry(self.q8h2) + + self.succ = CompoundEntry({ + 'id': 'succ_c', 'formula': 'C4H4O4'}) + native_model.compounds.add_entry(self.succ) + + self.native = native_model + self.mm = native_model.create_metabolic_model() + + def test_compound_dict(self): + cpd_dict = graph.get_compound_dict(self.native) + test_dict = {'fum_c': Formula({Atom('O'): 4, + Atom('C'): 4, Atom('H'): 2}), + 'h2o_c': Formula({Atom('O'): 1, + Atom('H'): 2}), + 'mal_L_c': Formula({Atom('O'): 5, + Atom('C'): 4, Atom('H'): 4}), + 'q8_c': Formula({Atom('O'): 4, + Atom('C'): 49, Atom('H'): 74}), + 'q8h2_c': Formula({Atom('O'): 4, + Atom('C'): 49, Atom('H'): 76}), + 'succ_c': Formula({Atom('O'): 4, + Atom('C'): 4, Atom('H'): 4})} + self.assertEqual(test_dict, cpd_dict) + + def test_network_dict(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + subset=None, method='fpp', + element=None, excluded_reactions=[]) + + test_dict = {self.rxn1: ([(Compound(u'fum_c', u'c'), + Compound(u'mal_L_c', u'c')), + (Compound(u'h2o_c', u'c'), + Compound(u'mal_L_c', u'c'))], + Direction.Both), + self.rxn2: ([(Compound(u'q8_c', u'c'), + Compound(u'q8h2_c', u'c')), + (Compound(u'succ_c', u'c'), + Compound(u'fum_c', u'c')), + (Compound(u'succ_c', u'c'), + Compound(u'q8h2_c', u'c'))], + Direction.Right)} + self.assertEqual(net_dict, test_dict) + + def test_network_dict_nofpp(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native, self.mm, + subset=None, method='no-fpp', + element=None, excluded_reactions=[]) + test_dict = {self.rxn1: ([(Compound(u'fum_c', u'c'), + Compound(u'mal_L_c', u'c')), + (Compound(u'h2o_c', u'c'), + Compound(u'mal_L_c', u'c'))], + Direction.Both), + self.rxn2: ([(Compound(u'q8_c', u'c'), + Compound(u'fum_c', u'c')), + (Compound(u'q8_c', u'c'), + Compound(u'q8h2_c', u'c')), + (Compound(u'succ_c', u'c'), + Compound(u'fum_c', u'c')), + (Compound(u'succ_c', u'c'), + Compound(u'q8h2_c', u'c')), + ], + Direction.Right)} + self.assertEqual(net_dict, test_dict) + + def test_reaction_dir_for(self): + self.assertTrue(graph.dir_value(Direction.Forward) == 'forward') + + def test_reaction_dir_rev(self): + self.assertTrue(graph.dir_value(Direction.Reverse) == 'back') + + def test_reaction_dir_both(self): + self.assertTrue(graph.dir_value(Direction.Both) == 'both') + + +class TestMakeNetworks(unittest.TestCase): + def setUp(self): + self.native_model = NativeModel() + self.atp = CompoundEntry({ + 'id': 'atp', 'formula': 'C10H16N5O13P3'}) + self.adp = CompoundEntry({ + 'id': 'adp', 'formula': 'C10H15N5O10P2'}) + self.glc = CompoundEntry({ + 'id': 'glc', 'formula': 'C6H12O6'}) + self.g6p = CompoundEntry({ + 'id': 'g6p', 'formula': 'C6H13O9P'}) + self.f6p = CompoundEntry({ + 'id': 'f6p', 'formula': 'C6H13O9P'}) + self.rxn1 = ReactionEntry({ + 'id': 'rxn1', 'equation': parse_reaction( + 'atp + glc => adp + g6p')}) + self.rxn2 = ReactionEntry({ + 'id': 'rxn2', 'equation': parse_reaction( + 'g6p <=> f6p')}) + self.native_model.compounds.add_entry(self.atp) + self.native_model.compounds.add_entry(self.adp) + self.native_model.compounds.add_entry(self.g6p) + self.native_model.compounds.add_entry(self.glc) + self.native_model.compounds.add_entry(self.f6p) + self.native_model.reactions.add_entry(self.rxn1) + self.native_model.reactions.add_entry(self.rxn2) + self.mm = self.native_model.create_metabolic_model() + self.node_atp = graph.Node({'id': 'atp', 'entry': Compound('atp')}) + self.node_adp = graph.Node({'id': 'adp', 'entry': Compound('adp')}) + self.node_g6p = graph.Node({'id': 'g6p', 'entry': Compound('g6p')}) + self.node_glc = graph.Node({'id': 'glc', 'entry': Compound('glc')}) + self.node_f6p = graph.Node({'id': 'f6p', 'entry': Compound('f6p')}) + self.edge_1 = graph.Edge(self.node_glc, self.node_g6p, + props={'id': 'g6p_glc_forward', + 'dir': 'forward'}) + self.edge_2 = graph.Edge(self.node_g6p, self.node_f6p, + props={'id': 'f6p_g6p_both', + 'dir': 'both'}) + self.edge_3 = graph.Edge(self.node_atp, self.node_adp, + props={'id': 'adp_atp_forward', + 'dir': 'forward'}) + self.edge_4 = graph.Edge(self.node_atp, self.node_adp, + props={'id': 'adp_atp_forward', + 'dir': 'forward'}) + self.edge_5 = graph.Edge(self.node_atp, self.node_g6p, + props={'id': 'atp_g6p_forward', + 'dir': 'forward'}) + self.edge_6 = graph.Edge(self.node_glc, self.node_adp, + props={'id': 'adp_glc_forward', + 'dir': 'forward'}) + + self.model_compound_entries = {} + for cpd in self.native_model.compounds: + self.model_compound_entries[cpd.id] = cpd + self.node_atp_bip = graph.Node( + {'id': 'atp', 'entry': [self.model_compound_entries['atp']], + 'compartment': None, 'type': 'cpd'}) + self.node_adp_bip = graph.Node( + {'id': 'adp', 'entry': [self.model_compound_entries['adp']], + 'compartment': None, 'type': 'cpd'}) + self.node_g6p_bip = graph.Node( + {'id': 'g6p', 'entry': [self.model_compound_entries['g6p']], + 'compartment': None, 'type': 'cpd'}) + self.node_glc_bip = graph.Node( + {'id': 'glc', 'entry': [self.model_compound_entries['glc']], + 'compartment': None, 'type': 'cpd'}) + self.node_f6p_bip = graph.Node( + {'id': 'f6p', 'entry': [self.model_compound_entries['f6p']], + 'compartment': None, 'type': 'cpd'}) + self.node_rxn1_1 = graph.Node({'id': 'rxn1_1', 'entry': [self.rxn1], + 'compartment': None, 'type': 'rxn'}) + self.node_rxn1_2 = graph.Node({'id': 'rxn1_2', 'entry': [self.rxn1], + 'compartment': None, 'type': 'rxn'}) + self.node_rxn2_1 = graph.Node({'id': 'rxn2_1', 'entry': [self.rxn2], + 'compartment': None, 'type': 'rxn'}) + self.edge_bip_1 = graph.Edge(self.node_atp_bip, self.node_rxn1_1, + props={'dir': 'forward', + 'style': 'solid', 'penwidth': 1}) + self.edge_bip_2 = graph.Edge(self.node_rxn1_1, self.node_adp_bip, + props={'dir': 'forward', + 'style': 'solid', 'penwidth': 1}) + self.edge_bip_3 = graph.Edge(self.node_atp_bip, self.node_rxn1_1, + props={'dir': 'forward', + 'style': 'solid', 'penwidth': 1}) + self.edge_bip_4 = graph.Edge(self.node_rxn1_1, self.node_g6p_bip, + props={'dir': 'forward', + 'style': 'solid', 'penwidth': 1}) + self.edge_bip_5 = graph.Edge(self.node_glc_bip, self.node_rxn1_2, + props={'dir': 'forward', + 'style': 'solid', 'penwidth': 1}) + self.edge_bip_6 = graph.Edge(self.node_rxn1_2, self.node_g6p_bip, + props={'dir': 'forward', + 'style': 'solid', 'penwidth': 1}) + self.edge_bip_7 = graph.Edge(self.node_g6p_bip, self.node_rxn2_1, + props={'dir': 'both', + 'style': 'solid', 'penwidth': 1}) + self.edge_bip_8 = graph.Edge(self.node_rxn2_1, self.node_f6p_bip, + props={'dir': 'both', + 'style': 'solid', 'penwidth': 1}) + self.node_list = [ + self.node_atp_bip, self.node_adp_bip, self.node_g6p_bip, + self.node_glc_bip, self.node_f6p_bip, + self.node_rxn1_1, self.node_rxn1_2, self.node_rxn2_1] + self.edge_list = [ + self.edge_bip_1, self.edge_bip_2, self.edge_bip_3, + self.edge_bip_4, self.edge_bip_5, self.edge_bip_6, + self.edge_bip_7, self.edge_bip_8] + + self.model_compound_entries = {} + for cpd in self.native_model.compounds: + self.model_compound_entries[cpd.id] = cpd + + def test_compound_graph(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + compound_graph = graph.make_compound_graph(net_dict) + self.assertTrue(all(i in compound_graph.nodes + for i in [self.node_atp, self.node_adp, + self.node_g6p, self.node_glc, + self.node_f6p])) + self.assertTrue( + all(i in compound_graph.edges + for i in [self.edge_1, self.edge_2, + self.edge_3, self.edge_4, self.edge_5])) + self.assertTrue(self.edge_6 not in compound_graph.edges) + + def test_compound_graph_filter(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='fpp', + element='C', excluded_reactions=[], + reaction_dict={}, analysis=None) + compound_graph = graph.make_compound_graph(net_dict) + self.assertTrue(all(i in compound_graph.nodes + for i in [self.node_atp, self.node_adp, + self.node_g6p, self.node_glc, + self.node_f6p])) + self.assertTrue(all(i in compound_graph.edges + for i in [self.edge_1, self.edge_2, + self.edge_3, self.edge_4])) + self.assertTrue(self.edge_5 not in compound_graph.edges) + self.assertTrue(self.edge_6 not in compound_graph.edges) + + def test_compound_graph_subset(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=['rxn1'], method='fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + compound_graph = graph.make_compound_graph(net_dict) + self.assertTrue( + all(i in compound_graph.nodes + for i in [self.node_atp, self.node_adp, + self.node_g6p, self.node_glc])) + self.assertTrue(self.node_f6p not in compound_graph.nodes) + self.assertTrue(all(i in compound_graph.edges + for i in [self.edge_1, self.edge_3, + self.edge_4, self.edge_5])) + self.assertTrue(self.edge_2 not in compound_graph.edges) + self.assertTrue(self.edge_6 not in compound_graph.edges) + + def test_compound_graph_exclude(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='fpp', + element=None, excluded_reactions=['rxn2'], + reaction_dict={}, analysis=None) + compound_graph = graph.make_compound_graph(net_dict) + self.assertTrue( + all(i in compound_graph.nodes + for i in [self.node_atp, self.node_adp, + self.node_g6p, self.node_glc])) + self.assertTrue(self.node_f6p not in compound_graph.nodes) + self.assertTrue(all(i in compound_graph.edges + for i in [self.edge_1, self.edge_3, + self.edge_4, self.edge_5])) + self.assertTrue(self.edge_2 not in compound_graph.edges) + self.assertTrue(self.edge_6 not in compound_graph.edges) + + def test_compound_graph_nofpp(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='no-fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + compound_graph = graph.make_compound_graph(net_dict) + self.assertTrue(all(i in compound_graph.nodes for i in + [self.node_f6p, self.node_g6p, self.node_glc, + self.node_adp, self.node_atp])) + self.assertTrue(all(i in compound_graph.edges for i in + [self.edge_1, self.edge_2, self.edge_3, + self.edge_4, self.edge_5, self.edge_6])) + + def test_make_cpair_dict_combine_0(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 0, style_flux_dict) + test_dict = defaultdict(lambda: defaultdict(list)) + test_dict[(Compound('atp'), Compound('adp'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('atp'), Compound('g6p'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('glc'), Compound('g6p'))]['forward'] = ['rxn1_2'] + test_dict[(Compound('g6p'), Compound('f6p'))]['both'] = ['rxn2_1'] + + test_new_id = {u'rxn2_1': self.rxn2, + u'rxn1_2': self.rxn1, u'rxn1_1': self.rxn1} + + self.assertEqual(cpairs, test_dict) + self.assertEqual(new_id, test_new_id) + + def test_make_cpair_dict_combine_1(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 1, style_flux_dict) + test_dict = defaultdict(lambda: defaultdict(list)) + test_dict[(Compound('glc'), Compound('g6p'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('atp'), Compound('g6p'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('atp'), Compound('adp'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('g6p'), Compound('f6p'))]['both'] = ['rxn2_1'] + + test_new_id = {u'rxn2_1': self.rxn2, u'rxn1_1': self.rxn1} + + self.assertEqual(cpairs, test_dict) + self.assertEqual(new_id, test_new_id) + + def test_make_cpair_dict_combine_2(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 2, style_flux_dict) + test_dict = defaultdict(lambda: defaultdict(list)) + test_dict[(Compound('glc'), Compound('g6p'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('atp'), Compound('g6p'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('atp'), Compound('adp'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('g6p'), Compound('f6p'))]['both'] = ['rxn2_1'] + + test_new_id = {u'rxn2_1': self.rxn2, u'rxn1_1': self.rxn1} + + self.assertEqual(cpairs, test_dict) + self.assertEqual(new_id, test_new_id) + + def test_make_cpair_dict_nofpp(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='no-fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'no-fpp', 0, style_flux_dict) + test_dict = defaultdict(lambda: defaultdict(list)) + test_dict[(Compound('glc'), Compound('g6p'))]['forward'] = ['rxn1'] + test_dict[(Compound('glc'), Compound('adp'))]['forward'] = ['rxn1'] + test_dict[(Compound('atp'), Compound('g6p'))]['forward'] = ['rxn1'] + test_dict[(Compound('atp'), Compound('adp'))]['forward'] = ['rxn1'] + test_dict[(Compound('g6p'), Compound('f6p'))]['both'] = ['rxn2'] + + test_new_id = {u'rxn2': self.rxn2, u'rxn1': self.rxn1} + + self.assertEqual(cpairs, test_dict) + self.assertEqual(new_id, test_new_id) + + def test_cpair_dict_duplicate_cpair_both(self): + rxn3 = ReactionEntry({ + 'id': 'rxn3', 'equation': parse_reaction( + 'f6p <=> g6p')}) + nm = self.native_model + nm.reactions.add_entry(rxn3) + mm = self.native_model.create_metabolic_model() + + net_dict, style_flux_dict = \ + graph.make_network_dict(nm, mm, subset=None, + method='fpp', element=None, + excluded_reactions=[], reaction_dict={}, + analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 0, style_flux_dict) + test_dict = defaultdict(lambda: defaultdict(list)) + test_dict[(Compound('atp'), Compound('adp'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('atp'), Compound('g6p'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('glc'), Compound('g6p'))]['forward'] = ['rxn1_2'] + test_dict[(Compound('f6p'), + Compound('g6p'))]['both'] = ['rxn2_1', 'rxn3_1'] + + test_new_id = {u'rxn2_1': self.rxn2, u'rxn1_2': self.rxn1, + u'rxn1_1': self.rxn1, 'rxn3_1': rxn3} + self.assertEqual(cpairs, test_dict) + self.assertEqual(new_id, test_new_id) + + def test_cpair_dict_duplicate_cpair_rev(self): + rxn3 = ReactionEntry({ + 'id': 'rxn3', 'equation': parse_reaction( + 'g6p => f6p')}) + nm = self.native_model + nm.reactions.add_entry(rxn3) + mm = self.native_model.create_metabolic_model() + + net_dict, style_flux_dict = \ + graph.make_network_dict(nm, mm, subset=None, method='fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 0, style_flux_dict) + test_dict = defaultdict(lambda: defaultdict(list)) + test_dict[(Compound('atp'), Compound('adp'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('atp'), Compound('g6p'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('glc'), Compound('g6p'))]['forward'] = ['rxn1_2'] + test_dict[(Compound('g6p'), Compound('f6p'))]['both'] = ['rxn2_1'] + test_dict[(Compound('g6p'), Compound('f6p'))]['forward'] = ['rxn3_1'] + + test_new_id = {u'rxn1_1': self.rxn1, u'rxn1_2': self.rxn1, + u'rxn2_1': self.rxn2, 'rxn3_1': rxn3} + + self.assertEqual(cpairs, test_dict) + self.assertEqual(new_id, test_new_id) + + def test_cpair_dict_duplicate_for(self): + rxn3 = ReactionEntry({ + 'id': 'rxn3', 'equation': parse_reaction( + 'f6p => g6p')}) + nm = self.native_model + nm.reactions.add_entry(rxn3) + mm = self.native_model.create_metabolic_model() + + net_dict, style_flux_dict = \ + graph.make_network_dict(nm, mm, subset=None, method='fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 0, style_flux_dict) + test_dict = defaultdict(lambda: defaultdict(list)) + test_dict[(Compound('atp'), Compound('adp'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('atp'), Compound('g6p'))]['forward'] = ['rxn1_1'] + test_dict[(Compound('glc'), Compound('g6p'))]['forward'] = ['rxn1_2'] + test_dict[(Compound('f6p'), Compound('g6p'))]['both'] = ['rxn2_1'] + test_dict[(Compound('f6p'), Compound('g6p'))]['forward'] = ['rxn3_1'] + + test_new_id = {u'rxn2_1': self.rxn2, u'rxn1_2': self.rxn1, + u'rxn1_1': self.rxn1, 'rxn3_1': rxn3} + + self.assertEqual(cpairs, test_dict) + self.assertEqual(new_id, test_new_id) + + def test_node_original_id_dict(self): + g = graph.Graph() + g.add_node(self.node_atp) + d = defaultdict(list) + d['atp'].append(self.node_atp) + self.assertEqual(g.nodes_original_id_dict, d) + + def test_bipartite_graph(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 0, style_flux_dict) + bipartite_graph = \ + graph.make_bipartite_graph_object(cpairs, new_id, 'fpp', 0, + self.model_compound_entries, + new_style_flux_dict) + self.assertTrue(all(i in bipartite_graph.nodes + for i in self.node_list)) + self.assertTrue(all(i in self.node_list + for i in bipartite_graph.nodes)) + self.assertTrue(all(i in bipartite_graph.edges + for i in self.edge_list)) + self.assertTrue(all(i in self.edge_list + for i in bipartite_graph.edges)) + + def test_bipartite_graph_filter(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='fpp', + element='C', excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 0, style_flux_dict) + bipartite_graph = \ + graph.make_bipartite_graph_object(cpairs, new_id, 'fpp', 0, + self.model_compound_entries, + new_style_flux_dict) + edge_list = [self.edge_bip_1, self.edge_bip_2, self.edge_bip_5, + self.edge_bip_6, self.edge_bip_7, self.edge_bip_8] + self.assertTrue(all(i in bipartite_graph.nodes + for i in self.node_list)) + self.assertTrue(all(i in bipartite_graph.edges for i in edge_list)) + self.assertTrue(all(i in self.node_list + for i in bipartite_graph.nodes)) + self.assertTrue(all(i in edge_list for i in bipartite_graph.edges)) + + def test_bipartite_graph_filter2(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='fpp', + element='P', excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 0, style_flux_dict) + bipartite_graph = \ + graph.make_bipartite_graph_object(cpairs, new_id, 'fpp', 0, + self.model_compound_entries, + new_style_flux_dict) + node_list = [i for i in self.node_list + if i not in [self.node_glc_bip, self.node_rxn1_2]] + edge_list = [self.edge_bip_1, self.edge_bip_2, self.edge_bip_3, + self.edge_bip_4, self.edge_bip_7, self.edge_bip_8] + self.assertTrue(all(i in bipartite_graph.nodes for i in node_list)) + self.assertTrue(all(i in bipartite_graph.edges for i in edge_list)) + self.assertTrue(all(i in node_list for i in bipartite_graph.nodes)) + self.assertTrue(all(i in edge_list for i in bipartite_graph.edges)) + + def test_bipartite_graph_filter3(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 0, style_flux_dict) + bipartite_graph = \ + graph.make_bipartite_graph_object(cpairs, new_id, 'fpp', 0, + self.model_compound_entries, + new_style_flux_dict) + edge_list = [self.edge_bip_1, self.edge_bip_2, self.edge_bip_3, + self.edge_bip_4, self.edge_bip_5, self.edge_bip_6, + self.edge_bip_7, self.edge_bip_8] + self.assertTrue(all(i in bipartite_graph.nodes + for i in self.node_list)) + self.assertTrue(all(i in bipartite_graph.edges for i in edge_list)) + self.assertTrue(all(i in self.node_list + for i in bipartite_graph.nodes)) + self.assertTrue(all(i in edge_list for i in bipartite_graph.edges)) + + def test_bipartite_graph_subset(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=['rxn1'], method='fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 0, style_flux_dict) + bipartite_graph = \ + graph.make_bipartite_graph_object(cpairs, new_id, 'fpp', 0, + self.model_compound_entries, + new_style_flux_dict) + node_list = [i for i in self.node_list + if i not in [self.node_f6p_bip, self.node_rxn2_1]] + edge_list = [self.edge_bip_1, self.edge_bip_2, self.edge_bip_3, + self.edge_bip_4, self.edge_bip_5, self.edge_bip_6] + self.assertTrue(all(i in bipartite_graph.nodes for i in node_list)) + self.assertTrue(all(i in bipartite_graph.edges for i in edge_list)) + self.assertTrue(all(i in node_list for i in bipartite_graph.nodes)) + self.assertTrue(all(i in edge_list for i in bipartite_graph.edges)) + + def test_bipartite_graph_subset2(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=['rxn2'], method='fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 0, style_flux_dict) + bipartite_graph = \ + graph.make_bipartite_graph_object(cpairs, new_id, 'fpp', 0, + self.model_compound_entries, + new_style_flux_dict) + node_list = [self.node_g6p_bip, self.node_f6p_bip, self.node_rxn2_1] + edge_list = [self.edge_bip_7, self.edge_bip_8] + self.assertTrue(all(i in bipartite_graph.nodes for i in node_list)) + self.assertTrue(all(i in bipartite_graph.edges for i in edge_list)) + self.assertTrue(all(i in node_list for i in bipartite_graph.nodes)) + self.assertTrue(all(i in edge_list for i in bipartite_graph.edges)) + + def test_bipartite_graph_exclude(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='fpp', + element=None, excluded_reactions=['rxn2'], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 0, style_flux_dict) + bipartite_graph = \ + graph.make_bipartite_graph_object(cpairs, new_id, 'fpp', 0, + self.model_compound_entries, + new_style_flux_dict) + node_list = [i for i in self.node_list + if i not in [self.node_f6p_bip, self.node_rxn2_1]] + edge_list = [self.edge_bip_1, self.edge_bip_2, self.edge_bip_3, + self.edge_bip_4, self.edge_bip_5, self.edge_bip_6] + self.assertTrue(all(i in bipartite_graph.nodes for i in node_list)) + self.assertTrue(all(i in bipartite_graph.edges for i in edge_list)) + self.assertTrue(all(i in node_list for i in bipartite_graph.nodes)) + self.assertTrue(all(i in edge_list for i in bipartite_graph.edges)) + + def test_bipartite_graph_nofpp(self): + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='no-fpp', + element=None, excluded_reactions=[], + reaction_dict={}, analysis=None) + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'no-fpp', 0, style_flux_dict) + bipartite_graph = \ + graph.make_bipartite_graph_object(cpairs, new_id, 'no-fpp', 0, + self.model_compound_entries, + new_style_flux_dict) + node_rxn1 = graph.Node({'id': 'rxn1', 'entry': [self.rxn1], + 'compartment': None, 'type': 'rxn'}) + node_rxn2 = graph.Node({'id': 'rxn2', 'entry': [self.rxn2], + 'compartment': None, 'type': 'rxn'}) + edge_bip_1 = graph.Edge(self.node_atp_bip, node_rxn1, + props={'dir': 'forward', + 'style': 'solid', 'penwidth': 1}) + edge_bip_2 = graph.Edge(self.node_glc_bip, node_rxn1, + props={'dir': 'forward', + 'style': 'solid', 'penwidth': 1}) + edge_bip_3 = graph.Edge(node_rxn1, self.node_adp_bip, + props={'dir': 'forward', + 'style': 'solid', 'penwidth': 1}) + edge_bip_4 = graph.Edge(node_rxn1, self.node_g6p_bip, + props={'dir': 'forward', + 'style': 'solid', 'penwidth': 1}) + edge_bip_5 = graph.Edge(self.node_g6p_bip, node_rxn2, + props={'dir': 'both', + 'style': 'solid', 'penwidth': 1}) + edge_bip_6 = graph.Edge(node_rxn2, self.node_f6p_bip, + props={'dir': 'both', + 'style': 'solid', 'penwidth': 1}) + node_list = [self.node_atp_bip, self.node_adp_bip, self.node_g6p_bip, + self.node_glc_bip, self.node_f6p_bip, + node_rxn1, node_rxn2] + edge_list = [edge_bip_1, edge_bip_2, edge_bip_3, + edge_bip_4, edge_bip_5, edge_bip_6] + self.assertTrue(all(i in bipartite_graph.nodes for i in node_list)) + self.assertTrue(all(i in bipartite_graph.edges for i in edge_list)) + self.assertTrue(all(i in node_list for i in bipartite_graph.nodes)) + self.assertTrue(all(i in edge_list for i in bipartite_graph.edges)) + + def test_bipartite_graph_fba(self): + reaction_dict = {'rxn1': (0, 1), 'rxn2': (2, 1)} + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='no-fpp', + element=None, excluded_reactions=[], + reaction_dict=reaction_dict, + analysis='fba') + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'no-fpp', 0, style_flux_dict) + bipartite_graph = \ + graph.make_bipartite_graph_object(cpairs, new_id, 'no-fpp', 0, + self.model_compound_entries, + new_style_flux_dict, 'fba') + node_rxn1 = graph.Node({'id': 'rxn1', 'entry': [self.rxn1], + 'compartment': None, 'type': 'rxn'}) + node_rxn2 = graph.Node({'id': 'rxn2', 'entry': [self.rxn2], + 'compartment': None, 'type': 'rxn'}) + edge_bip_1 = graph.Edge(self.node_atp_bip, node_rxn1, + props={'dir': 'forward', + 'style': 'dotted', 'penwidth': 1}) + edge_bip_2 = graph.Edge(self.node_glc_bip, node_rxn1, + props={'dir': 'forward', + 'style': 'dotted', 'penwidth': 1}) + edge_bip_3 = graph.Edge(node_rxn1, self.node_adp_bip, + props={'dir': 'forward', + 'style': 'dotted', 'penwidth': 1}) + edge_bip_4 = graph.Edge(node_rxn1, self.node_g6p_bip, + props={'dir': 'forward', + 'style': 'dotted', 'penwidth': 1}) + edge_bip_5 = graph.Edge(self.node_g6p_bip, node_rxn2, + props={'dir': 'forward', + 'style': 'solid', 'penwidth': 5}) + edge_bip_6 = graph.Edge(node_rxn2, self.node_f6p_bip, + props={'dir': 'forward', + 'style': 'solid', 'penwidth': 5}) + node_list = [self.node_atp_bip, self.node_adp_bip, + self.node_g6p_bip, self.node_glc_bip, + self.node_f6p_bip, node_rxn1, node_rxn2] + edge_list = [edge_bip_1, edge_bip_2, edge_bip_3, + edge_bip_4, edge_bip_5, edge_bip_6] + self.assertTrue(all(i in bipartite_graph.nodes for i in node_list)) + self.assertTrue(all(i in bipartite_graph.edges for i in edge_list)) + self.assertTrue(all(i in node_list for i in bipartite_graph.nodes)) + self.assertTrue(all(i in edge_list for i in bipartite_graph.edges)) + + def test_bipartite_graph_fva(self): + reaction_dict = {'rxn1': (0, 0), 'rxn2': (-1, 1)} + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='no-fpp', + element='C', excluded_reactions=[], + reaction_dict=reaction_dict, + analysis='fva') + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'no-fpp', 0, style_flux_dict) + bipartite_graph = \ + graph.make_bipartite_graph_object(cpairs, new_id, 'no-fpp', 0, + self.model_compound_entries, + new_style_flux_dict, 'fva') + node_rxn1 = graph.Node({'id': 'rxn1', 'entry': [self.rxn1], + 'compartment': None, 'type': 'rxn'}) + node_rxn2 = graph.Node({'id': 'rxn2', 'entry': [self.rxn2], + 'compartment': None, 'type': 'rxn'}) + edge_bip_1 = graph.Edge(self.node_atp_bip, node_rxn1, + props={'dir': 'forward', + 'style': 'dotted', 'penwidth': 1}) + edge_bip_2 = graph.Edge(self.node_glc_bip, node_rxn1, + props={'dir': 'forward', + 'style': 'dotted', 'penwidth': 1}) + edge_bip_3 = graph.Edge(node_rxn1, self.node_adp_bip, + props={'dir': 'forward', + 'style': 'dotted', 'penwidth': 1}) + edge_bip_4 = graph.Edge(node_rxn1, self.node_g6p_bip, + props={'dir': 'forward', + 'style': 'dotted', 'penwidth': 1}) + edge_bip_5 = graph.Edge(self.node_g6p_bip, node_rxn2, + props={'dir': 'both', + 'style': 'solid', 'penwidth': 5}) + edge_bip_6 = graph.Edge(node_rxn2, self.node_f6p_bip, + props={'dir': 'both', + 'style': 'solid', 'penwidth': 5}) + node_list = [self.node_atp_bip, self.node_adp_bip, + self.node_g6p_bip, self.node_glc_bip, self.node_f6p_bip, + node_rxn1, node_rxn2] + edge_list = [edge_bip_1, edge_bip_2, edge_bip_3, + edge_bip_4, edge_bip_5, edge_bip_6] + self.assertTrue(all(i in bipartite_graph.nodes for i in node_list)) + self.assertTrue(all(i in bipartite_graph.edges for i in edge_list)) + self.assertTrue(all(i in node_list for i in bipartite_graph.nodes)) + self.assertTrue(all(i in edge_list for i in bipartite_graph.edges)) + + def test_bipartite_graph_combine_2(self): + reaction_dict = {'rxn1': (0, 0), 'rxn2': (-1, 1)} + net_dict, style_flux_dict = \ + graph.make_network_dict(self.native_model, self.mm, + subset=None, method='fpp', + element=None, excluded_reactions=[], + reaction_dict=reaction_dict, + analysis='fva') + cpairs, new_id, new_style_flux_dict = graph.make_cpair_dict( + net_dict, 'fpp', 2, style_flux_dict) + bipartite_graph = \ + graph.make_bipartite_graph_object(cpairs, new_id, 'fpp', 2, + self.model_compound_entries, + new_style_flux_dict, 'fva') + node_rxn1_1 = graph.Node({'id': 'rxn1_1', 'entry': [self.rxn1], + 'compartment': None, 'type': 'rxn'}) + node_rxn2_1 = graph.Node({'id': 'rxn2_1', 'entry': [self.rxn2], + 'compartment': None, 'type': 'rxn'}) + edge_bip_1 = graph.Edge(self.node_atp_bip, node_rxn1_1, + props={'dir': 'forward', + 'style': 'dotted', 'penwidth': 1}) + edge_bip_2 = graph.Edge(node_rxn1_1, self.node_adp_bip, + props={'dir': 'forward', + 'style': 'dotted', 'penwidth': 1}) + edge_bip_3 = graph.Edge(node_rxn1_1, self.node_g6p_bip, + props={'dir': 'forward', + 'style': 'dotted', 'penwidth': 1}) + edge_bip_4 = graph.Edge(self.node_g6p_bip, node_rxn2_1, + props={'dir': 'both', + 'style': 'solid', 'penwidth': 5}) + edge_bip_5 = graph.Edge(node_rxn2_1, self.node_f6p_bip, + props={'dir': 'both', + 'style': 'solid', 'penwidth': 5}) + edge_bip_6 = graph.Edge(self.node_glc_bip, node_rxn1_1, + props={'dir': 'forward', + 'style': 'dotted', 'penwidth': 1}) + node_list = [self.node_atp_bip, self.node_adp_bip, + self.node_g6p_bip, self.node_glc_bip, self.node_f6p_bip, + node_rxn1_1, node_rxn2_1] + edge_list = [edge_bip_1, edge_bip_2, edge_bip_3, + edge_bip_4, edge_bip_5, edge_bip_6] + self.assertTrue(all(i in bipartite_graph.nodes for i in node_list)) + self.assertTrue(all(i in bipartite_graph.edges for i in edge_list)) + self.assertTrue(all(i in node_list for i in bipartite_graph.nodes)) + self.assertTrue(all(i in edge_list for i in bipartite_graph.edges)) + + +class TestEdges(unittest.TestCase): + def setUp(self): + self.g = graph.Graph() + self.node1 = graph.Node({'id': 'A'}) + self.node2 = graph.Node({'id': 'B'}) + self.node3 = graph.Node({'id': 'C'}) + self.node4 = graph.Node({'id': 'A'}) + self.edge1_2 = graph.Edge(self.node1, self.node2) + self.edge2_3 = graph.Edge(self.node2, self.node3) + self.edge12_21 = graph.Edge(self.node1, self.node2) + + def test_eq_edges(self): + self.assertTrue(self.edge1_2 == self.edge12_21) + + def test_neq_edges(self): + self.assertTrue(self.edge1_2 != self.edge2_3) + + def test_neq_edge_node(self): + self.assertFalse(self.edge1_2 == self.node1) + + +class TestCompExit(unittest.TestCase): + def setUp(self): + native_model = NativeModel() + self.rxn1 = ReactionEntry({ + 'id': 'rxn1', 'equation': parse_reaction( + 'fum_c[c] + h2o_c[c] <=> mal_L_c[c]')}) + native_model.reactions.add_entry(self.rxn1) + self.native = native_model + self.mm = native_model.create_metabolic_model() + + def test_sys_exit(self): + with self.assertRaises(SystemExit): + graph.make_network_dict(self.native, self.mm) + + def test_with_element(self): + with self.assertRaises(SystemExit): + graph.make_network_dict(self.native, self.mm, + method='no-fpp', element='C') + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_importer.py",".py","21899","549","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import os +import tempfile +import shutil +import json +import unittest +from decimal import Decimal + +import numpy as np +from scipy.io import savemat, loadmat +from scipy.sparse.csc import csc_matrix + +from six import BytesIO + +from psamm import importer +from psamm.importer import ModelLoadError +from psamm.datasource.native import NativeModel +from psamm.datasource.entry import (DictCompoundEntry as CompoundEntry, + DictReactionEntry as ReactionEntry, + DictCompartmentEntry as CompartmentEntry) +from psamm.datasource.reaction import parse_reaction +from psamm.reaction import Reaction, Compound +from psamm.formula import Formula +from psamm.expression import boolean + +from psamm.importers.sbml import StrictImporter as SBMLStrictImporter +from psamm.importers.sbml import NonstrictImporter as SBMLNonstrictImporter +from psamm.importers.cobrajson import Importer as CobraJSONImporter +from psamm.importers.matlab import Importer as MatlabImporter + + +class TestImporterBaseClass(unittest.TestCase): + def setUp(self): + self.importer = importer.Importer() + + def test_try_parse_formula(self): + result = self.importer._try_parse_formula('cpd_1', ' ') + self.assertIsNone(result) + + # Should not return parsed result! + result = self.importer._try_parse_formula('cpd_1', 'CO2') + self.assertEqual(result, 'CO2') + + result = self.importer._try_parse_formula('cpd_1', 'XYZ...\u03c0') + self.assertEqual(result, 'XYZ...\u03c0') + + def test_try_parse_reaction(self): + result = self.importer._try_parse_reaction('rxn_1', 'A => (3) B') + self.assertIsInstance(result, Reaction) + + with self.assertRaises(importer.ParseError): + self.importer._try_parse_reaction('rxn_1', '+ + ==> \u03c0 5') + + def test_try_parse_gene_association(self): + result = self.importer._try_parse_gene_association( + 'rxn_1', 'g1 and (g2 or g3)') + self.assertIsInstance(result, boolean.Expression) + + result = self.importer._try_parse_gene_association('rxn_1', ' ') + self.assertIsNone(result) + + result = self.importer._try_parse_gene_association('rxn_1', '123 and') + self.assertEqual(result, '123 and') + + +class TestImporterCheckAndWriteModel(unittest.TestCase): + def setUp(self): + self.dest = tempfile.mkdtemp() + + self.model = NativeModel({ + 'id': 'test_mode', + 'name': 'Test model', + }) + + # Compounds + self.model.compounds.add_entry(CompoundEntry({ + 'id': 'cpd_1', + 'formula': Formula.parse('CO2') + })) + self.model.compounds.add_entry(CompoundEntry({ + 'id': 'cpd_2', + })) + self.model.compounds.add_entry(CompoundEntry({ + 'id': 'cpd_3', + })) + + # Compartments + self.model.compartments.add_entry(CompartmentEntry({ + 'id': 'c' + })) + self.model.compartments.add_entry(CompartmentEntry({ + 'id': 'e' + })) + + # Reactions + self.model.reactions.add_entry(ReactionEntry({ + 'id': 'rxn_1', + 'equation': parse_reaction('(2) cpd_1[c] <=> cpd_2[e] + cpd_3[c]'), + 'genes': boolean.Expression('g_1 and (g_2 or g_3)'), + 'subsystem': 'Some subsystem' + })) + self.model.reactions.add_entry(ReactionEntry({ + 'id': 'rxn_2', + 'equation': parse_reaction( + '(0.234) cpd_1[c] + (1.34) cpd_2[c] => cpd_3[c]'), + 'subsystem': 'Biomass' + })) + + self.model.biomass_reaction = 'rxn_2' + self.model.limits['rxn_1'] = 'rxn_1', Decimal(-42), Decimal(1000) + self.model.exchange[Compound('cpd_2', 'e')] = ( + Compound('cpd_2', 'e'), 'EX_cpd_2', -10, 0) + + def tearDown(self): + shutil.rmtree(self.dest) + + def test_get_default_compartment(self): + importer.get_default_compartment(self.model) + + def test_detect_best_flux_limit(self): + flux_limit = importer.detect_best_flux_limit(self.model) + self.assertEqual(flux_limit, 1000) + + def test_infer_compartment_entries(self): + self.model.compartments.clear() + importer.infer_compartment_entries(self.model) + + self.assertEqual(len(self.model.compartments), 2) + self.assertEqual({c.id for c in self.model.compartments}, {'c', 'e'}) + + def test_get_output_limit(self): + self.assertIsNone(importer._get_output_limit(1000, 1000)) + self.assertEqual(importer._get_output_limit(-5, 0), -5) + + def test_generate_limit_items(self): + item = dict(importer._generate_limit_items(None, None)) + self.assertEqual(item, {}) + + item = dict(importer._generate_limit_items(None, 400)) + self.assertEqual(item, {'upper': 400}) + + item = dict(importer._generate_limit_items(-56, None)) + self.assertEqual(item, {'lower': -56}) + + item = dict(importer._generate_limit_items(-224, 0)) + self.assertEqual(item, {'lower': -224, 'upper': 0}) + + item = dict(importer._generate_limit_items(-5, -5)) + self.assertEqual(item, {'fixed': -5}) + + def test_count_genes(self): + self.assertEqual(importer.count_genes(self.model), 3) + + def test_write_yaml_model(self): + importer.write_yaml_model(self.model, self.dest) + + +class TestSBMLImporter(unittest.TestCase): + def setUp(self): + self.dest = tempfile.mkdtemp() + with open(os.path.join(self.dest, 'model.sbml'), 'wb') as f: + f.write(''' + + + + +

This is model information intended to be seen by humans.

+ +
+ + + + + + + + +

This is compound information intended to be seen by humans.

+ +
+
+ + + + +
+ + + + + + + + + + + + + + + + + +

This is reaction information intended to be seen by humans.

+ +
+ + + + + +
  • + + + + + + + + + + + + + + + + + + + + + + + + + '''.encode('utf-8')) + + def tearDown(self): + shutil.rmtree(self.dest) + + def test_create_strict_importer(self): + importer = SBMLStrictImporter() + importer.help() + importer.import_model(os.path.join(self.dest, 'model.sbml')) + + def test_strict_importer_main(self): + output_dir = os.path.join(self.dest, 'output') + os.mkdir(output_dir) + importer.main(importer_class=SBMLStrictImporter, args=[ + '--source', os.path.join(self.dest, 'model.sbml'), + '--dest', output_dir + ]) + + def test_create_nonstrict_importer(self): + importer = SBMLNonstrictImporter() + importer.help() + importer.import_model(os.path.join(self.dest, 'model.sbml')) + + def test_nonstrict_importer_main(self): + output_dir = os.path.join(self.dest, 'output') + os.mkdir(output_dir) + importer.main(importer_class=SBMLNonstrictImporter, args=[ + '--source', os.path.join(self.dest, 'model.sbml'), + '--dest', output_dir + ]) + + +class TestCobraJSONImporter(unittest.TestCase): + def setUp(self): + self.dest = tempfile.mkdtemp() + with open(os.path.join(self.dest, 'model.json'), 'w') as f: + json.dump({ + 'id': 'test_model', + 'compartments': { + 'c': 'Cytosol', + 'e': 'Extracellular', + }, + 'metabolites': [ + { + 'id': 'cpd_1', + 'name': 'Compound 1', + 'formula': 'CO2', + 'compartment': 'c' + }, + { + 'id': 'cpd_2', + 'name': 'Compound 2', + 'charge': -2, + 'compartment': 'e' + }, + { + 'id': 'cpd_3', + 'compartment': 'c' + } + ], + 'reactions': [ + { + 'id': 'rxn_1', + 'metabolites': { + 'cpd_1': -1, + 'cpd_2': 2, + 'cpd_3': 1, + }, + 'lower_bound': -20, + 'upper_bound': 100, + 'gene_reaction_rule': 'gene_1 and (gene_2 or gene_3)' + } + ] + }, f) + + def tearDown(self): + shutil.rmtree(self.dest) + + def test_create_importer(self): + importer = CobraJSONImporter() + importer.help() + importer.import_model(os.path.join(self.dest, 'model.json')) + + def test_cobra_json_main(self): + output_dir = os.path.join(self.dest, 'output') + os.mkdir(output_dir) + importer.main(importer_class=CobraJSONImporter, args=[ + '--source', os.path.join(self.dest, 'model.json'), + '--dest', output_dir + ]) + + def test_cobra_json_main_bigg(self): + def mock_urlopen(url): + return open(os.path.join(self.dest, 'model.json'), 'rb') + + output_dir = os.path.join(self.dest, 'output') + os.mkdir(output_dir) + importer.main_bigg( + args=['mock_model', '--dest', output_dir], urlopen=mock_urlopen) + + +class TestBiGGImportMain(unittest.TestCase): + def test_list_models(self): + def mock_urlopen(url): + return BytesIO(b''' +{""results_count"": 4, + ""results"": [ + {""organism"": ""Escherichia coli str. K-12 substr. MG1655"", + ""metabolite_count"": 72, + ""bigg_id"": ""e_coli_core"", + ""gene_count"": 137, + ""reaction_count"": 95}, + {""organism"": ""Homo sapiens"", + ""metabolite_count"": 342, + ""bigg_id"": ""iAB_RBC_283"", + ""gene_count"": 346, + ""reaction_count"": 469}, + {""organism"": ""Escherichia coli str. K-12 substr. MG1655"", + ""metabolite_count"": 1668, + ""bigg_id"": ""iAF1260"", + ""gene_count"": 1261, + ""reaction_count"": 2382}]}''') + + importer.main_bigg(['list'], urlopen=mock_urlopen) + + +class TestMatlabImporter(unittest.TestCase): + def setUp(self): + self.dest = tempfile.mkdtemp() + dt = np.dtype([ + ('comps', 'O'), + ('compNames', 'O'), + ('rxns', 'O'), + ('rxnNames', 'O'), + ('rxnGeneMat', 'O'), + ('ub', 'O'), + ('lb', 'O'), + ('S', 'O'), + ('grRules', 'O'), + ('subSystems', 'O'), + ('mets', 'O'), + ('metFormulas', 'O'), + ('metNames', 'O'), + ('metCharges', 'O'), + ('metNotes', 'O'), + ('c', 'O'), + ]) + model1 = np.ndarray((1, 1), dtype=dt) + # compartments + model1['comps'][0, 0] = np.ndarray((3, 1), dtype='O') + model1['comps'][0, 0][0][0] = np.array(['c']) + model1['comps'][0, 0][1][0] = np.array(['e']) + model1['comps'][0, 0][2][0] = np.array(['b']) + model1['compNames'][0, 0] = np.ndarray((3, 1), dtype='O') + model1['compNames'][0, 0][0][0] = np.array(['Cell']) + model1['compNames'][0, 0][1][0] = np.array(['Extracellular']) + model1['compNames'][0, 0][2][0] = np.array(['Boundary']) + # reactions + model1['rxns'][0, 0] = np.ndarray((3, 1), dtype='O') + model1['rxns'][0, 0][0][0] = np.array(['rxn1']) + model1['rxns'][0, 0][1][0] = np.array(['rxn2']) + model1['rxns'][0, 0][2][0] = np.array(['rxn3']) + model1['rxnNames'][0, 0] = np.ndarray((3, 1), dtype='O') + model1['rxnNames'][0, 0][0][0] = np.array(['rxn1']) + model1['rxnNames'][0, 0][1][0] = np.array([]) + model1['rxnNames'][0, 0][2][0] = np.array(['rxn3']) + model1['rxnGeneMat'][0, 0] = np.ndarray((3, 1), dtype='O') + model1['rxnGeneMat'][0, 0][0][0] = np.array([]) + model1['rxnGeneMat'][0, 0][1][0] = np.array([0]) + model1['rxnGeneMat'][0, 0][2][0] = np.array([0]) + model1['ub'][0, 0] = np.ndarray((3, 1), dtype='O') + model1['ub'][0, 0][0][0] = np.array([1000]) + model1['ub'][0, 0][1][0] = np.array([0]) + model1['ub'][0, 0][2][0] = np.array([1000]) + model1['lb'][0, 0] = np.ndarray((3, 1), dtype='O') + model1['lb'][0, 0][0][0] = np.array([0]) + model1['lb'][0, 0][1][0] = np.array([-1000]) + model1['lb'][0, 0][2][0] = np.array([-1000]) + # equation matrix + data = np.array([-1, -2, 1, -1, 2, -1, 1]) + row = np.array([0, 1, 2, 2, 3, 3, 4]) + col = np.array([0, 0, 0, 1, 1, 2, 2]) + model1['S'][0, 0] = csc_matrix((data, (row, col)), shape=(5, 3)) + # genes + model1['grRules'][0, 0] = np.ndarray((3, 1), dtype='O') + model1['grRules'][0, 0][0][0] = np.array(['g1 and g2']) + model1['grRules'][0, 0][1][0] = np.array(['g3 or g4']) + model1['grRules'][0, 0][2][0] = np.array([]) + # subsystems + model1['subSystems'][0, 0] = np.ndarray((3, 1), dtype='O') + model1['subSystems'][0, 0][0][0] = np.array(['system1']) + model1['subSystems'][0, 0][1][0] = np.ndarray((1, 1), 'O') + model1['subSystems'][0, 0][1][0][0][0] = np.array(['system2']) + model1['subSystems'][0, 0][2][0] = np.array(['system3']) + # compounds + model1['mets'][0, 0] = np.ndarray((5, 1), dtype='O') + model1['mets'][0, 0][0][0] = np.array(['A[e]']) + model1['mets'][0, 0][1][0] = np.array(['B_c']) + model1['mets'][0, 0][2][0] = np.array(['C(c)']) + model1['mets'][0, 0][3][0] = np.array(['D[c]']) + model1['mets'][0, 0][4][0] = np.array(['E001e']) + model1['metFormulas'][0, 0] = np.ndarray((5, 1), dtype='O') + model1['metFormulas'][0, 0][0][0] = np.array(['H2O']) + model1['metFormulas'][0, 0][1][0] = np.array(['C5H10O2']) + model1['metFormulas'][0, 0][2][0] = np.array(['H2SPO4']) + model1['metFormulas'][0, 0][3][0] = np.array(['CH4N2']) + model1['metFormulas'][0, 0][4][0] = np.array(['CO2']) + model1['metNames'][0, 0] = np.ndarray((5, 1), dtype='O') + model1['metNames'][0, 0][0][0] = np.array(['A']) + model1['metNames'][0, 0][1][0] = np.array(['B']) + model1['metNames'][0, 0][2][0] = np.array(['C']) + model1['metNames'][0, 0][3][0] = np.array(['D']) + model1['metNames'][0, 0][4][0] = np.array(['E']) + model1['metCharges'][0, 0] = np.ndarray((5, 1), dtype='O') + model1['metCharges'][0, 0][0][0] = 1 + model1['metCharges'][0, 0][1][0] = 2 + model1['metCharges'][0, 0][2][0] = -1.0 + model1['metCharges'][0, 0][3][0] = 0 + model1['metCharges'][0, 0][4][0] = 0 + model1['metNotes'][0, 0] = np.ndarray((5, 1), dtype='O') + model1['metNotes'][0, 0][0][0] = np.array(['A']) + model1['metNotes'][0, 0][1][0] = np.array(['B']) + model1['metNotes'][0, 0][2][0] = np.array([]) + model1['metNotes'][0, 0][3][0] = np.array(['D']) + model1['metNotes'][0, 0][4][0] = np.array(['E']) + # biomass reaction + model1['c'][0, 0] = np.ndarray((3, 1), dtype='O') + model1['c'][0, 0][0][0] = 0 + model1['c'][0, 0][1][0] = 0 + model1['c'][0, 0][2][0] = 1 + + os.mkdir(os.path.join(self.dest, 'models')) + savemat(os.path.join(self.dest, 'model1.mat'), {'model1': model1}) + savemat(os.path.join(self.dest, 'models', 'model1.mat'), + {'model1': model1}) + model2 = model1.copy() + model2['c'][0, 0][1][0] = 1 + savemat(os.path.join(self.dest, 'models', 'model2.mat'), + {'model1': model1, 'model2': model2}) + + def tearDown(self): + shutil.rmtree(self.dest) + + def test_create_importer(self): + importer = MatlabImporter() + importer.help() + importer.import_model(os.path.join(self.dest, 'model1.mat')) + importer.import_model(self.dest) + importer.import_model(os.path.join(self.dest, 'models', 'model2.mat'), + 'model2') + with self.assertRaises(ModelLoadError): + importer.import_model(os.path.join(self.dest, 'models')) + with self.assertRaises(ModelLoadError): + importer.import_model(os.path.join( + self.dest, 'models', 'model2.mat')) + + def test_matlab_importer_main(self): + output_dir = os.path.join(self.dest, 'output') + os.mkdir(output_dir) + importer.main(importer_class=MatlabImporter, + args=[ + '--source', os.path.join(self.dest, 'model1.mat'), + '--dest', output_dir, + ]) +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_moma.py",".py","5244","131","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.metabolicmodel import MetabolicModel +from psamm.database import DictDatabase +from psamm import moma +from psamm.datasource.reaction import parse_reaction +from psamm.lpsolver import generic + + +class TestLinearMOMA(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_moma_fba(self): + p = moma.MOMAProblem(self.model, self.solver) + fluxes = p.get_fba_flux('rxn_6') + self.assertAlmostEqual(fluxes['rxn_1'], 500) + self.assertAlmostEqual(fluxes['rxn_2'], 0) + self.assertAlmostEqual(fluxes['rxn_6'], 1000) + + def test_moma_minimal_fba(self): + p = moma.MOMAProblem(self.model, self.solver) + fluxes = p.get_minimal_fba_flux('rxn_6') + self.assertAlmostEqual(fluxes['rxn_1'], 500) + self.assertAlmostEqual(fluxes['rxn_2'], 0) + self.assertAlmostEqual(fluxes['rxn_3'], 1000) + self.assertAlmostEqual(fluxes['rxn_6'], 1000) + + def test_linear_moma(self): + p = moma.MOMAProblem(self.model, self.solver) + with p.constraints(p.get_flux_var('rxn_3') == 0): + p.lin_moma({ + 'rxn_3': 1000, + 'rxn_4': 0, + 'rxn_5': 0, + }) + + # The closest solution when these are constrained is for + # rxn_6 to take on a flux of zero. + self.assertAlmostEqual(p.get_flux('rxn_6'), 0) + + def test_linear_moma2(self): + p = moma.MOMAProblem(self.model, self.solver) + with p.constraints(p.get_flux_var('rxn_3') == 0): + p.lin_moma2('rxn_6', 1000) + + self.assertAlmostEqual(p.get_flux('rxn_1'), 500) + self.assertAlmostEqual(p.get_flux('rxn_2'), 0) + self.assertAlmostEqual(p.get_flux('rxn_3'), 0) + self.assertAlmostEqual(p.get_flux('rxn_4'), 1000) + self.assertAlmostEqual(p.get_flux('rxn_5'), 1000) + self.assertAlmostEqual(p.get_flux('rxn_6'), 1000) + + +class TestQuadraticMOMA(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver(quadratic=True) + except generic.RequirementsError: + self.skipTest('Unable to find an MIQP solver for tests') + + def test_quadratic_moma(self): + p = moma.MOMAProblem(self.model, self.solver) + with p.constraints(p.get_flux_var('rxn_3') == 0): + p.moma({ + 'rxn_3': 1000, + 'rxn_4': 0, + 'rxn_5': 0, + }) + + # The closest solution when these are constrained is for + # rxn_6 to take on a flux of zero. + self.assertAlmostEqual(p.get_flux('rxn_6'), 0) + + def test_quadratic_moma2(self): + p = moma.MOMAProblem(self.model, self.solver) + with p.constraints(p.get_flux_var('rxn_3') == 0): + p.moma2('rxn_6', 1000) + + self.assertAlmostEqual(p.get_flux('rxn_1'), 500) + self.assertAlmostEqual(p.get_flux('rxn_2'), 0) + self.assertAlmostEqual(p.get_flux('rxn_3'), 0) + self.assertAlmostEqual(p.get_flux('rxn_4'), 1000) + self.assertAlmostEqual(p.get_flux('rxn_5'), 1000) + self.assertAlmostEqual(p.get_flux('rxn_6'), 1000) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_datasource_entry.py",".py","4152","121","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.datasource import entry + + +class TestDictEntries(unittest.TestCase): + def test_create_compound_dict_entry(self): + props = { + 'id': 'test_compound', + 'name': 'Test compound', + 'formula': 'H2O', + 'charge': 1, + 'custom': 'ABC' + } + e = entry.DictCompoundEntry(props) + self.assertIsInstance(e, entry.CompoundEntry) + self.assertEqual(e.id, 'test_compound') + self.assertEqual(e.name, 'Test compound') + self.assertEqual(e.formula, 'H2O') + self.assertEqual(e.charge, 1) + self.assertEqual(e.properties.get('custom'), 'ABC') + + def test_create_compound_dict_entry_copy(self): + props = { + 'id': 'test_compound', + 'name': 'Test compound' + } + e = entry.DictCompoundEntry(props) + e2 = entry.DictCompoundEntry(e) + self.assertIsInstance(e2, entry.CompoundEntry) + self.assertEqual(e2.id, 'test_compound') + self.assertEqual(e2.name, 'Test compound') + + def test_create_compound_dict_entry_without_id(self): + props = { + 'name': 'Compound 1', + 'formula': 'CO2' + } + with self.assertRaises(ValueError): + e = entry.DictCompoundEntry(props) + + def test_create_compound_dict_entry_with_id_override(self): + props = { + 'id': 'old_id', + 'name': 'Compound 1', + 'formula': 'CO2' + } + e = entry.DictCompoundEntry(props, id='new_id') + self.assertEqual(e.id, 'new_id') + self.assertEqual(e.properties['id'], 'new_id') + + def test_use_compound_dict_entry_setters(self): + e = entry.DictCompoundEntry({}, id='new_id') + e.formula = 'CO2' + e.name = 'Compound 1' + e.charge = 5 + self.assertEqual(e.formula, 'CO2') + self.assertEqual(e.properties['formula'], 'CO2') + self.assertEqual(e.name, 'Compound 1') + self.assertEqual(e.charge, 5) + + def test_create_reaction_entry(self): + props = { + 'id': 'reaction_1', + 'name': 'Reaction 1' + } + e = entry.DictReactionEntry(props) + self.assertIsInstance(e, entry.ReactionEntry) + self.assertEqual(e.id, 'reaction_1') + self.assertEqual(e.name, 'Reaction 1') + + def test_create_reaction_entry_from_compound_entry(self): + e = entry.DictCompoundEntry({ + 'id': 'compound_1', + 'name': 'Compound 1' + }) + with self.assertRaises(ValueError): + e2 = entry.DictReactionEntry(e) + + def test_use_reaction_dict_entry_setters(self): + e = entry.DictReactionEntry({}, id='reaction_1') + e.name = 'Reaction 1' + e.equation = 'A => B' + e.genes = 'gene_1 and gene_2' + self.assertEqual(e.name, 'Reaction 1') + self.assertEqual(e.equation, 'A => B') + self.assertEqual(e.genes, 'gene_1 and gene_2') + self.assertEqual(e.properties['genes'], 'gene_1 and gene_2') + + def test_create_compartment_entry(self): + props = { + 'id': 'c', + 'name': 'Cytosol' + } + e = entry.DictCompartmentEntry(props) + self.assertIsInstance(e, entry.CompartmentEntry) + self.assertEqual(e.id, 'c') + self.assertEqual(e.name, 'Cytosol') + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_datasource_native.py",".py","29678","880","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import os +import shutil +import tempfile +import unittest +import math +from decimal import Decimal +from collections import OrderedDict + +from psamm.datasource import native, context, entry +from psamm.reaction import Reaction, Compound, Direction +from psamm.formula import Formula + +from six import StringIO +import yaml + + +class MockEntry(object): + """"""Entry object for testing OrderedEntrySet."""""" + def __init__(self, id): + self._id = id + + @property + def id(self): + return self._id + + +class TestOrderedEntrySet(unittest.TestCase): + def test_init_from_dict(self): + entries = { + 'test_1': MockEntry('test_1'), + 'test_2': MockEntry('test_2') + } + entry_set = native._OrderedEntrySet(entries) + self.assertEqual(entry_set['test_1'], entries['test_1']) + self.assertEqual(entry_set['test_2'], entries['test_2']) + self.assertEqual(len(entry_set), len(entries)) + + def test_add_and_contains(self): + entry_set = native._OrderedEntrySet() + entry_set.add_entry(MockEntry('def')) + entry_set.add_entry(MockEntry('abc')) + entry_set.add_entry(MockEntry('ghi')) + + self.assertIn('def', entry_set) + self.assertIn('ghi', entry_set) + self.assertNotIn('klm', entry_set) + self.assertEqual(len(entry_set), 3) + + # Check that it is ordered + self.assertEqual( + [entry.id for entry in entry_set], ['def', 'abc', 'ghi']) + + def test_get(self): + entries = { + 'test_1': MockEntry('test_1'), + 'test_2': MockEntry('test_2') + } + entry_set = native._OrderedEntrySet(entries) + self.assertEqual(entry_set.get('test_1'), entries['test_1']) + self.assertIsNone(entry_set.get('test_3')) + self.assertEqual(entry_set.get('test_3', 5), 5) + + def test_discard(self): + entries = { + 'test_1': MockEntry('test_1'), + 'test_2': MockEntry('test_2') + } + entry_set = native._OrderedEntrySet(entries) + entry_set.discard('test_1') + self.assertNotIn('test_1', entry_set) + + def test_update(self): + entries = { + 'test_1': MockEntry('test_1'), + 'test_2': MockEntry('test_2') + } + entry_set = native._OrderedEntrySet(entries) + entry_set.update([ + MockEntry('test_2'), + MockEntry('test_3') + ]) + + self.assertEqual(len(entry_set), 3) + self.assertEqual(entry_set['test_1'], entries['test_1']) + self.assertNotEqual(entry_set['test_2'], entries['test_2']) + + def test_clear(self): + entries = { + 'test_1': MockEntry('test_1'), + 'test_2': MockEntry('test_2') + } + entry_set = native._OrderedEntrySet(entries) + entry_set.clear() + + self.assertEqual(len(entry_set), 0) + self.assertNotIn('test_1', entry_set) + + +class TestYAMLDataSource(unittest.TestCase): + def test_parse_compartments(self): + model_dict = { + 'compartments': [ + { + 'id': 'e', + 'name': 'Extracellular' + }, + { + 'id': 'p', + 'name': 'Periplasm', + 'adjacent_to': ['e', 'c'] + }, + { + 'id': 'c', + 'name': 'Cytosol', + 'adjacent_to': 'p' + }, + { + 'id': 'internal', + 'name': 'Internal compartment', + 'adjacent_to': 'c' + } + ] + } + reader = native.ModelReader(model_dict) + compartment_iter, boundaries = reader.parse_compartments() + compartments = list(compartment_iter) + + self.assertEqual(len(compartments), 4) + self.assertEqual(compartments[0].id, 'e') + self.assertEqual(compartments[0].name, 'Extracellular') + self.assertEqual(compartments[1].id, 'p') + self.assertEqual(compartments[1].name, 'Periplasm') + self.assertEqual(compartments[2].id, 'c') + self.assertEqual(compartments[2].name, 'Cytosol') + self.assertEqual(compartments[3].id, 'internal') + self.assertEqual(compartments[3].name, 'Internal compartment') + + normalized_boundaries = set( + tuple(sorted((c1, c2))) for c1, c2 in boundaries) + self.assertSetEqual(normalized_boundaries, { + ('c', 'internal'), + ('c', 'p'), + ('e', 'p') + }) + + def test_parse_reaction(self): + reaction = native.parse_reaction({ + 'id': 'reaction_123', + 'equation': 'A + 2 B => C[e]' + }, default_compartment='p') + + self.assertEqual(reaction.id, 'reaction_123') + self.assertEqual(reaction.equation, Reaction( + Direction.Forward, + [(Compound('A', 'p'), 1), (Compound('B', 'p'), 2)], + [(Compound('C', 'e'), 1)])) + + def test_parse_reaction_list(self): + reactions = list(native.parse_reaction_list('./test.yaml', [ + { + 'id': 'rxn1', + 'equation': { + 'reversible': True, + 'left': [ + {'id': 'A', 'value': 1}, + {'id': 'B', 'value': 2}], + 'right': [ + {'id': 'C', 'value': 1} + ] + } + } + ])) + + self.assertEqual(len(reactions), 1) + + reaction = Reaction(Direction.Both, + [(Compound('A'), 1), (Compound('B'), 2)], + [(Compound('C'), 1)]) + self.assertEqual(reactions[0].equation, reaction) + + def test_parse_reaction_list_missing_value(self): + with self.assertRaises(native.ParseError): + reaction = list(native.parse_reaction_list('./test.yaml', [ + { + 'id': 'rxn1', + 'equation': { + 'left': [ + {'id': 'A'} + ] + } + } + ])) + + def test_parse_exchange_table(self): + table = ''' +ac e +glcD e -10 +co2 e - 50 +''' + + exchange = list( + native.parse_exchange_table_file(StringIO(table.strip()))) + self.assertEqual(len(exchange), 3) + self.assertEqual(exchange[0], (Compound('ac', 'e'), None, None, None)) + self.assertEqual(exchange[1], (Compound('glcD', 'e'), None, -10, None)) + self.assertEqual(exchange[2], (Compound('co2', 'e'), None, None, 50)) + + def test_parse_exchange(self): + exchange = list(native.parse_exchange({ + 'compartment': 'e', + 'compounds': [ + {'id': 'ac'}, + {'id': 'glcD', 'lower': -10}, + {'id': 'co2', 'upper': 50}, + {'id': 'compound_x', 'compartment': 'c'}, + {'id': 'compound_y', 'reaction': 'EX_cpdy'} + ] + }, 'e')) + + self.assertEqual(len(exchange), 5) + self.assertEqual(exchange[0], (Compound(('ac'), ('e')), + None, None, None)) + self.assertEqual(exchange[1], (Compound('glcD', 'e'), None, -10, None)) + self.assertEqual(exchange[2], (Compound('co2', 'e'), None, None, 50)) + self.assertEqual( + exchange[3], (Compound('compound_x', 'c'), None, None, None)) + self.assertEqual( + exchange[4], (Compound('compound_y', 'e'), 'EX_cpdy', None, None)) + + def test_parse_normal_float(self): + v = native.yaml_load('-23.456') + self.assertEqual(v, Decimal('-23.456')) + self.assertIsInstance(v, Decimal) + + def test_parse_special_float(self): + self.assertEqual(native.yaml_load('.inf'), Decimal('Infinity')) + self.assertEqual(native.yaml_load('-.inf'), -Decimal('Infinity')) + self.assertTrue(math.isnan(native.yaml_load('.nan'))) + + +class TestYAMLFileSystemData(unittest.TestCase): + """"""Test loading files from file system."""""" + + def setUp(self): + self._model_dir = tempfile.mkdtemp() + + def tearDown(self): + shutil.rmtree(self._model_dir) + + def write_model_file(self, filename, contents): + path = os.path.join(self._model_dir, filename) + with open(path, 'w') as f: + f.write(contents) + return path + + def test_long_string_model(self): + long_string = '''--- + name: Test model + biomass: rxn_1 + reactions: + - id: rxn_1 + equation: '|A_\u2206[e]| => |B[c]|' + genes: + - gene_1 + - gene_2 + - id: rxn_2_\u03c0 + equation: '|B[c]| => |C[e]|' + genes: 'gene_3 or (gene_4 and gene_5)' + compounds: + - id: A_\u2206 + - id: B + - id: C + exchange: + - compartment: e + compounds: + - id: A_\u2206 + - id: C + limits: + - reaction: rxn_2_\u03c0 + upper: 100 + ''' + m = native.ModelReader(long_string) + self.assertEqual(m.name, 'Test model') + self.assertEqual(m.biomass_reaction, 'rxn_1') + self.assertEqual(m.extracellular_compartment, 'e') + reactions = list(m.parse_reactions()) + self.assertEqual(reactions[0].id, 'rxn_1') + + def test_long_string_model_include(self): + longString = '''--- + name: Test model + biomass: rxn_1 + reactions: + - include: exchange.yaml + ''' + m = native.ModelReader(longString) + with self.assertRaises(context.ContextError): + list(m.parse_reactions()) + + def test_dict_model(self): + dict_model = { + 'name': 'Test model', + 'biomass': 'rxn_1', + 'reactions': [ + {'id': 'rxn_1', + 'equation': '|A_\u2206[e]| => |B[c]|', + 'genes': [ + 'gene_1', + 'gene_2'] + }, + {'id': 'rxn_2_\u03c0', + 'equation': '|B[c]| => |C[e]|', + 'genes': 'gene_3 or (gene_4 and gene_5)' + }], + 'compounds': [ + {'id': 'A_\u2206'}, + {'id': 'B'}, + {'id': 'C'}], + 'exchange': [ + {'compartment': 'e', + 'compounds': [ + {'id': 'A_\u2206'}, + {'id': 'C'}] + }], + 'limits': [ + {'reaction': 'rxn_2_\u03c0', + 'upper': 100 + }] + } + + dmodel = native.ModelReader(dict_model) + self.assertEqual(dmodel.name, 'Test model') + self.assertEqual(dmodel.biomass_reaction, 'rxn_1') + self.assertEqual(dmodel.extracellular_compartment, 'e') + + def test_parse_model_file(self): + path = self.write_model_file('model.yaml', '\n'.join([ + 'name: Test model', + 'biomass: biomass_reaction_id', + 'extracellular: Extra', + 'default_flux_limit: 500' + ])) + + model = native.ModelReader.reader_from_path(path) + + self.assertEqual(model.name, 'Test model') + self.assertEqual(model.biomass_reaction, 'biomass_reaction_id') + self.assertEqual(model.extracellular_compartment, 'Extra') + self.assertEqual(model.default_flux_limit, 500) + + def test_bad_path(self): + with self.assertRaises(native.ParseError): + native.ModelReader.reader_from_path('/nope/nreal/path') + + def test_invalid_model_type(self): + with self.assertRaises(ValueError): + native.ModelReader(42.2) + + def test_parse_model_file_with_exchange(self): + path = self.write_model_file('model.yaml', '\n'.join([ + 'extracellular: Ex', + 'exchange:', + ' - compounds:', + ' - id: A', + ' - id: B', + ' compartment: c' + ])) + + model = native.ModelReader.reader_from_path(path) + + exchange = list(model.parse_exchange()) + self.assertEqual(exchange[0][0], Compound('A', 'Ex')) + self.assertEqual(exchange[1][0], Compound('B', 'c')) + + def test_parse_model_file_with_media(self): + """"""Test parsing model with the deprecated media key."""""" + path = self.write_model_file('model.yaml', '\n'.join([ + 'extracellular: Ex', + 'media:', + ' - compounds:', + ' - id: A', + ' - id: B', + ' compartment: c' + ])) + + model = native.ModelReader.reader_from_path(path) + + exchange = list(model.parse_exchange()) + self.assertEqual(exchange[0][0], Compound('A', 'Ex')) + self.assertEqual(exchange[1][0], Compound('B', 'c')) + + def test_parse_model_file_with_media_and_exchange(self): + """"""Test that parsing model with both media and exchange fails."""""" + path = self.write_model_file('model.yaml', '\n'.join([ + 'extracellular: Ex', + 'media:', + ' - compounds:', + ' - id: A', + ' - id: B', + ' compartment: c', + 'exchange:', + ' - compounds:', + ' - id: C', + ' - id: D' + ])) + + model = native.ModelReader.reader_from_path(path) + + with self.assertRaises(native.ParseError): + medium = list(model.parse_exchange()) + + def test_parse_compound_tsv_file(self): + path = self.write_model_file('compounds.tsv', '\n'.join([ + 'id\tname\tformula\tcharge\tkegg\tcas', + 'h2o\tWater\tH2O\t0\tC00001\t7732-18-5' + ])) + + compounds = list(native.parse_compound_file(path, 'tsv')) + self.assertEqual(len(compounds), 1) + + self.assertEqual(compounds[0].id, 'h2o') + self.assertEqual(compounds[0].name, 'Water') + self.assertEqual(compounds[0].properties['name'], 'Water') + self.assertEqual(compounds[0].formula, 'H2O') + self.assertEqual(compounds[0].charge, 0) + self.assertEqual(compounds[0].properties['kegg'], 'C00001') + self.assertEqual(compounds[0].properties['cas'], '7732-18-5') + + def test_parse_compound_yaml_file(self): + path = self.write_model_file('compounds.yaml', '\n'.join([ + '- id: h2o', + ' name: Water', + ' formula: H2O', + ' user_annotation: ABC' + ])) + + compounds = list(native.parse_compound_file(path, 'yaml')) + self.assertEqual(len(compounds), 1) + + self.assertEqual(compounds[0].id, 'h2o') + self.assertEqual(compounds[0].name, 'Water') + self.assertEqual(compounds[0].formula, 'H2O') + self.assertEqual(compounds[0].properties['user_annotation'], 'ABC') + + def test_parse_reaction_table_file(self): + path = self.write_model_file('reactions.tsv', '\n'.join([ + 'id\tname\tequation', + 'rxn_1\tReaction 1\t|A| => (2) |B|', + 'rxn_2\tSecond reaction\t<=> |C|' + ])) + + reactions = list(native.parse_reaction_file(path)) + self.assertEqual(len(reactions), 2) + + self.assertEqual(reactions[0].id, 'rxn_1') + self.assertEqual(reactions[0].name, 'Reaction 1') + self.assertEqual(reactions[0].properties['name'], 'Reaction 1') + self.assertEqual(reactions[0].equation, Reaction( + Direction.Forward, [(Compound('A'), 1)], [(Compound('B'), 2)])) + self.assertEqual(reactions[0].properties.get('ec'), None) + self.assertEqual(reactions[0].genes, None) + self.assertEqual(reactions[0].filemark.filecontext.filepath, path) + self.assertEqual(reactions[0].filemark.line, 2) + + self.assertEqual(reactions[1].id, 'rxn_2') + self.assertEqual(reactions[1].name, 'Second reaction') + self.assertEqual(reactions[1].equation, Reaction( + Direction.Both, [], [(Compound('C'), 1)])) + self.assertEqual(reactions[1].filemark.filecontext.filepath, path) + self.assertEqual(reactions[1].filemark.line, 3) + + def test_parse_reaction_yaml_file(self): + path = self.write_model_file('reaction.yaml', '\n'.join([ + '- id: rxn_1', + ' equation: ""|A| => |B|""', + '- id: rxn_2', + ' equation:', + ' reversible: no', + ' left:', + ' - id: B', + ' value: 1', + ' right:', + ' - id: A', + ' value: 1' + ])) + + reactions = list(native.parse_reaction_file(path)) + self.assertEqual(len(reactions), 2) + + self.assertEqual(reactions[0].id, 'rxn_1') + self.assertEqual(reactions[1].id, 'rxn_2') + + def test_parse_exchange_table_file(self): + path = self.write_model_file('exchange.tsv', '\n'.join([ + '', + '# comment', + 'cpd_A\tc', + 'cpd_B\te\t-1000', + 'cpd_C\te\t-\t20 # line comment', + 'cpd_D\te\t-100\t-10' + ])) + + exchange = list(native.parse_exchange_file(path, 'e')) + self.assertEqual(exchange, [ + (Compound('cpd_A', 'c'), None, None, None), + (Compound('cpd_B', 'e'), None, -1000, None), + (Compound('cpd_C', 'e'), None, None, 20), + (Compound('cpd_D', 'e'), None, -100, -10) + ]) + + def test_get_limits_invalid_fixed(self): + d = { + 'fixed': 10, + 'upper': 20 + } + with self.assertRaises(native.ParseError): + native.get_limits(d) + + def test_parse_exchange_yaml_file(self): + path = self.write_model_file('exchange.yaml', '\n'.join([ + 'compartment: e', + 'compounds:', + ' - id: cpd_A', + ' reaction: EX_A', + ' lower: -40', + ' - id: cpd_B', + ' upper: 100', + ' - id: cpd_C', + ' lower: -100.0', + ' upper: 500.0', + ' - id: cpd_D', + ' compartment: c', + ' - id: cpd_E', + ' fixed: 100.0', + ])) + + exchange = list(native.parse_exchange_file(path, 'e')) + self.assertEqual(exchange, [ + (Compound('cpd_A', 'e'), 'EX_A', -40, None), + (Compound('cpd_B', 'e'), None, None, 100), + (Compound('cpd_C', 'e'), None, -100, 500), + (Compound('cpd_D', 'c'), None, None, None), + (Compound('cpd_E', 'e'), None, 100, 100) + ]) + + def test_parse_exchange_yaml_list(self): + self.write_model_file('exchange.yaml', '\n'.join([ + 'compartment: e', + 'compounds:', + ' - id: cpd_A', + ' lower: -42' + ])) + + path = os.path.join(self._model_dir, 'fake.yaml') + exchange = list(native.parse_exchange_list(path, [ + {'include': 'exchange.yaml'}, + { + 'compartment': 'e', + 'compounds': [ + {'id': 'cpd_B', 'upper': 767} + ] + } + ], 'e')) + + self.assertEqual(exchange, [ + (Compound('cpd_A', 'e'), None, -42, None), + (Compound('cpd_B', 'e'), None, None, 767) + ]) + + def test_parse_limits_table_file(self): + path = self.write_model_file('limits_1.tsv', '\n'.join([ + '# comment', + '', + 'rxn_1', + 'rxn_2\t-100', + 'rxn_3\t-\t3e-1', + 'rxn_4\t-1000\t-100 # line comment' + ])) + + limits = list(native.parse_limits_file(path)) + self.assertEqual(limits[0], ('rxn_1', None, None)) + self.assertEqual(limits[1], ('rxn_2', -100, None)) + self.assertEqual(limits[2][0], 'rxn_3') + self.assertEqual(limits[2][1], None) + self.assertAlmostEqual(limits[2][2], 3e-1) + self.assertEqual(limits[3], ('rxn_4', -1000, -100)) + + def test_parse_limits_table_file_too_many_fields(self): + path = self.write_model_file('limits.tsv', '\n'.join([ + 'rxn_1\t-\t100\ttext'])) + with self.assertRaises(native.ParseError): + list(native.parse_limits_file(path)) + + def test_parse_limits_yaml_file(self): + path = self.write_model_file('limits_1.yaml', '\n'.join([ + '- include: limits_2.yml', + '- reaction: rxn_3', + ' lower: -1000', + '- reaction: rxn_4', + ' fixed: 10' + ])) + + self.write_model_file('limits_2.yml', '\n'.join([ + '- reaction: rxn_1', + ' lower: -1', + ' upper: 25.5', + '- reaction: rxn_2' + ])) + + limits = list(native.parse_limits_file(path)) + self.assertEqual(limits, [ + ('rxn_1', -1, 25.5), + ('rxn_2', None, None), + ('rxn_3', -1000, None), + ('rxn_4', 10, 10) + ]) + + def test_parse_model_table_file(self): + path = self.write_model_file('model_1.tsv', '\n'.join([ + '# comment', + 'rxn_1', + 'rxn_2', + 'rxn_3', + 'rxn_4 # line comment'])) + + reactions = list(native.parse_model_file(path)) + self.assertEqual(reactions, ['rxn_1', 'rxn_2', 'rxn_3', 'rxn_4']) + + def test_parse_model_yaml_file(self): + path = self.write_model_file('model_1.yaml', '''--- + - include: model_2.yaml + - reactions: + - rxn_3 + - rxn_4''') + + self.write_model_file('model_2.yaml', '''--- + - groups: + - name: First group + reactions: [rxn_1] + - name: Second group + reactions: [rxn_2]''') + + reactions = list(native.parse_model_file(path)) + self.assertEqual(reactions, ['rxn_1', 'rxn_2', 'rxn_3', 'rxn_4']) + + +class TestCheckId(unittest.TestCase): + def test_check_id_none(self): + with self.assertRaises(native.ParseError): + native._check_id(None, 'Compound') + + def test_check_id_not_string(self): + with self.assertRaises(native.ParseError): + native._check_id(False, 'Compound') + + def test_check_id_empty_string(self): + with self.assertRaises(native.ParseError): + native._check_id('', 'Reaction') + + def test_check_id_success(self): + native._check_id(u'\u222b', 'Compound') + + +class TestNativeModel(unittest.TestCase): + def test_properties(self): + model = native.NativeModel() + model.name = 'Test model' + model.version_string = '1.0' + model.biomass_reaction = 'rxn_1' + model.extracellular_compartment = 'e' + model.default_compartment = 'c' + model.default_flux_limit = 1000 + self.assertEqual(model.name, 'Test model') + self.assertEqual(model.version_string, '1.0') + self.assertEqual(model.biomass_reaction, 'rxn_1') + self.assertEqual(model.extracellular_compartment, 'e') + self.assertEqual(model.default_compartment, 'c') + self.assertEqual(model.default_flux_limit, 1000) + + +class TestNativeModelWriter(unittest.TestCase): + def setUp(self): + self.writer = native.ModelWriter() + + def test_convert_compartment_entry(self): + compartment = entry.DictCompartmentEntry({ + 'id': 'cytosol', + 'name': 'Cytosol', + 'custom': 456 + }) + d = self.writer.convert_compartment_entry(compartment, 'periplasm') + self.assertIsInstance(d, OrderedDict) + self.assertEqual(d['id'], 'cytosol') + self.assertEqual(d['name'], 'Cytosol') + self.assertEqual(d['custom'], 456) + self.assertEqual(d['adjacent_to'], 'periplasm') + + def test_convert_compound_entry(self): + compound = entry.DictCompoundEntry({ + 'id': 'c1', + 'name': 'Compound 1', + 'charge': 2, + 'formula': None, + 'custom': 'ABC' + }) + d = self.writer.convert_compound_entry(compound) + self.assertIsInstance(d, OrderedDict) + self.assertEqual(d['id'], 'c1') + self.assertEqual(d['name'], 'Compound 1') + self.assertEqual(d['charge'], 2) + self.assertEqual(d['custom'], 'ABC') + self.assertNotIn('formula', d) + + def test_convert_reaction_entry(self): + equation = Reaction( + Direction.Both, {Compound('c1', 'c'): -1, Compound('c2', 'c'): 1}) + reaction = entry.DictReactionEntry({ + 'id': 'rxn01234', + 'name': 'Test reaction', + 'equation': equation, + 'custom_property': -34, + 'another_custom_property': None + }) + d = self.writer.convert_reaction_entry(reaction) + self.assertIsInstance(d, OrderedDict) + self.assertEqual(d['id'], 'rxn01234') + self.assertEqual(d['name'], 'Test reaction') + self.assertEqual(d['equation'], equation) + self.assertEqual(d['custom_property'], -34) + self.assertNotIn('another_custom_property', d) + + def test_write_compartments(self): + stream = StringIO() + compartments = [ + entry.DictCompartmentEntry({ + 'id': 'cytosol', + 'name': 'Cytosol', + 'custom': 456 + }), + entry.DictCompartmentEntry({ + 'id': 'periplasm', + 'name': 'Periplasm', + 'test': 'abc' + }) + ] + adjacencies = { + 'cytosol': 'periplasm', + 'periplasm': ['cytosol', 'e'] + } + self.writer.write_compartments(stream, compartments, adjacencies) + + self.assertEqual(yaml.safe_load(stream.getvalue()), [ + { + 'id': 'cytosol', + 'adjacent_to': 'periplasm', + 'name': 'Cytosol', + 'custom': 456 + }, + { + 'id': 'periplasm', + 'adjacent_to': ['cytosol', 'e'], + 'name': 'Periplasm', + 'test': 'abc' + } + ]) + + def test_write_compounds(self): + stream = StringIO() + compounds = [ + entry.DictCompoundEntry({ + 'id': 'c1', + 'name': 'Compound 1', + 'charge': 2, + 'custom': 34.5 + }), + entry.DictCompoundEntry({ + 'id': 'c2', + 'name': 'Compound 2', + 'formula': Formula.parse('H2O') + }) + ] + self.writer.write_compounds(stream, compounds) + + self.assertEqual(yaml.safe_load(stream.getvalue()), [ + { + 'id': 'c1', + 'name': 'Compound 1', + 'charge': 2, + 'custom': 34.5 + }, + { + 'id': 'c2', + 'name': 'Compound 2', + 'formula': 'H2O' + } + ]) + + def test_write_compounds_with_properties(self): + stream = StringIO() + compounds = [ + entry.DictCompoundEntry({ + 'id': 'c1', + 'name': 'Compound 1', + 'charge': 2 + }), + entry.DictCompoundEntry({ + 'id': 'c2', + 'name': 'Compound 2', + 'formula': 'H2O' + }) + ] + self.writer.write_compounds(stream, compounds, properties={'name'}) + + self.assertEqual(yaml.safe_load(stream.getvalue()), [ + { + 'id': 'c1', + 'name': 'Compound 1' + }, + { + 'id': 'c2', + 'name': 'Compound 2' + } + ]) + + def test_write_reactions(self): + stream = StringIO() + reactions = [ + entry.DictReactionEntry({ + 'id': 'r1', + 'name': 'Reaction 1', + 'equation': Reaction(Direction.Both, {}) + }), + entry.DictReactionEntry({ + 'id': 'r2', + 'name': 'Reaction 2', + 'equation': Reaction(Direction.Forward, { + Compound('c1', 'c'): -1, + Compound('c2', 'c'): 2 + }) + }) + ] + self.writer.write_reactions(stream, reactions) + + # The reaction equation for r1 is invalid (no compounds) and is + # therefore skipped. + self.assertEqual(yaml.safe_load(stream.getvalue()), [ + { + 'id': 'r1', + 'name': 'Reaction 1' + }, + { + 'id': 'r2', + 'name': 'Reaction 2', + 'equation': 'c1[c] => (2) c2[c]' + } + ]) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_database.py",".py","7332","180","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.database import DictDatabase, ChainedDatabase +from psamm.reaction import Compound, Reaction, Direction +from psamm.datasource.reaction import parse_reaction + + +class TestMetabolicDatabase(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> 2 A')) + self.database.set_reaction('rxn_2', parse_reaction('A <=> B')) + self.database.set_reaction('rxn_3', parse_reaction('A => D[e]')) + self.database.set_reaction('rxn_4', parse_reaction('A + 2 B => C')) + self.database.set_reaction('rxn_5', parse_reaction('C => 3 D[e]')) + self.database.set_reaction('rxn_6', parse_reaction('D[e] =>')) + + def test_reactions(self): + self.assertEqual( + set(self.database.reactions), + {'rxn_1', 'rxn_2', 'rxn_3', 'rxn_4', 'rxn_5', 'rxn_6'}) + + def test_compounds(self): + self.assertEqual( + set(self.database.compounds), + {Compound('A'), Compound('B'), Compound('C'), Compound('D', 'e')}) + + def test_compartments(self): + self.assertEqual(set(self.database.compartments), {None, 'e'}) + + def test_has_reaction_existing(self): + self.assertTrue(self.database.has_reaction('rxn_3')) + + def test_has_reaction_not_existing(self): + self.assertFalse(self.database.has_reaction('rxn_7')) + + def test_is_reversible_is_true(self): + self.assertTrue(self.database.is_reversible('rxn_2')) + + def test_is_reversible_is_false(self): + self.assertFalse(self.database.is_reversible('rxn_5')) + + def test_get_reaction_values(self): + self.assertEqual( + list(self.database.get_reaction_values('rxn_4')), + [(Compound('A'), -1), (Compound('B'), -2), (Compound('C'), 1)]) + + def test_get_compound_reactions(self): + self.assertEqual( + set(self.database.get_compound_reactions(Compound('A'))), + {'rxn_1', 'rxn_2', 'rxn_3', 'rxn_4'}) + + def test_reversible(self): + self.assertEqual(set(self.database.reversible), {'rxn_2'}) + + def test_get_reaction(self): + reaction = parse_reaction('A + (2) B => C') + self.assertEqual(self.database.get_reaction('rxn_4'), reaction) + + def test_set_reaction_with_zero_coefficient(self): + reaction = Reaction( + Direction.Both, [(Compound('A'), 1), (Compound('B'), 0)], + [(Compound('C'), 1)]) + self.database.set_reaction('rxn_new', reaction) + self.assertNotIn( + 'rxn_new', self.database.get_compound_reactions(Compound('B'))) + + def test_matrix_get_item(self): + self.assertEqual(self.database.matrix[Compound('A'), 'rxn_1'], 2) + self.assertEqual(self.database.matrix[Compound('A'), 'rxn_2'], -1) + self.assertEqual(self.database.matrix[Compound('B'), 'rxn_2'], 1) + self.assertEqual(self.database.matrix[Compound('A'), 'rxn_4'], -1) + self.assertEqual(self.database.matrix[Compound('B'), 'rxn_4'], -2) + self.assertEqual(self.database.matrix[Compound('C'), 'rxn_4'], 1) + self.assertEqual(self.database.matrix[Compound('C'), 'rxn_5'], -1) + self.assertEqual(self.database.matrix[Compound('D', 'e'), 'rxn_5'], 3) + + def test_matrix_get_item_invalid_key(self): + with self.assertRaises(KeyError): + a = self.database.matrix[Compound('A'), 'rxn_5'] + with self.assertRaises(KeyError): + b = self.database.matrix['rxn_1'] + + def test_matrix_set_item_is_invalid(self): + with self.assertRaises(TypeError): + self.database.matrix[Compound('A'), 'rxn_1'] = 4 + + def test_matrix_iter(self): + matrix_keys = { + (Compound('A'), 'rxn_1'), + (Compound('A'), 'rxn_2'), + (Compound('B'), 'rxn_2'), + (Compound('A'), 'rxn_3'), + (Compound('D', 'e'), 'rxn_3'), + (Compound('A'), 'rxn_4'), + (Compound('B'), 'rxn_4'), + (Compound('C'), 'rxn_4'), + (Compound('C'), 'rxn_5'), + (Compound('D', 'e'), 'rxn_5'), + (Compound('D', 'e'), 'rxn_6') + } + self.assertEqual(set(iter(self.database.matrix)), matrix_keys) + + def test_matrix_len(self): + self.assertEqual(len(self.database.matrix), 11) + + +class TestChainedDatabase(unittest.TestCase): + def setUp(self): + database1 = DictDatabase() + database1.set_reaction('rxn_1', parse_reaction('|A| => |B|')) + database1.set_reaction('rxn_2', parse_reaction('|B| => |C| + |D|')) + database1.set_reaction('rxn_3', parse_reaction('|D| <=> |E|')) + database1.set_reaction('rxn_4', parse_reaction('|F| => |G|')) + + database2 = DictDatabase() + database2.set_reaction('rxn_2', parse_reaction('|B| => |C|')) + database2.set_reaction('rxn_3', parse_reaction('|C| => |D|')) + database2.set_reaction('rxn_4', parse_reaction('|F| <=> |G|')) + database2.set_reaction('rxn_5', parse_reaction('|G| + |I| <=> |H|')) + + self.database = ChainedDatabase(database2, database1) + + def test_has_reaction_in_lower_database(self): + self.assertTrue(self.database.has_reaction('rxn_1')) + + def test_has_reaction_in_upper_new(self): + self.assertTrue(self.database.has_reaction('rxn_5')) + + def test_has_reaction_in_upper_shadowing(self): + self.assertTrue(self.database.has_reaction('rxn_3')) + + def test_is_reversible_in_lower_database(self): + self.assertFalse(self.database.is_reversible('rxn_1')) + + def test_is_reversible_in_upper_new(self): + self.assertTrue(self.database.is_reversible('rxn_5')) + + def test_is_reversible_in_upper_shadowing(self): + self.assertFalse(self.database.is_reversible('rxn_3')) + + def test_get_compound_reactions_in_upper(self): + reactions = set(self.database.get_compound_reactions(Compound('H'))) + self.assertEqual(reactions, {'rxn_5'}) + + def test_get_compound_reactions_in_lower(self): + reactions = set(self.database.get_compound_reactions(Compound('A'))) + self.assertEqual(reactions, {'rxn_1'}) + + def test_get_compound_reactions_in_both(self): + reactions = set(self.database.get_compound_reactions(Compound('B'))) + self.assertEqual(reactions, {'rxn_1', 'rxn_2'}) + + def test_get_compound_reactions_in_both_and_shadowed(self): + reactions = set(self.database.get_compound_reactions(Compound('D'))) + self.assertEqual(reactions, {'rxn_3'}) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_fluxanalysis.py",".py","17740","402","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.metabolicmodel import MetabolicModel +from psamm.database import DictDatabase +from psamm import fluxanalysis +from psamm.datasource.reaction import parse_reaction +from psamm.lpsolver import generic + +from six import itervalues + + +class TestFluxBalance(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_flux_balance_rxn_1(self): + fluxes = dict(fluxanalysis.flux_balance( + self.model, 'rxn_1', tfba=False, solver=self.solver)) + self.assertAlmostEqual(fluxes['rxn_1'], 500) + self.assertAlmostEqual(fluxes['rxn_2'], 0) + self.assertAlmostEqual(fluxes['rxn_6'], 1000) + + def test_flux_balance_rxn_2(self): + fluxes = dict(fluxanalysis.flux_balance( + self.model, 'rxn_2', tfba=False, solver=self.solver)) + self.assertAlmostEqual(fluxes['rxn_2'], 0) + + def test_flux_balance_rxn_3(self): + fluxes = dict(fluxanalysis.flux_balance( + self.model, 'rxn_3', tfba=False, solver=self.solver)) + self.assertAlmostEqual(fluxes['rxn_1'], 500) + self.assertAlmostEqual(fluxes['rxn_2'], 0) + self.assertAlmostEqual(fluxes['rxn_3'], 1000) + self.assertAlmostEqual(fluxes['rxn_6'], 1000) + + def test_flux_balance_rxn_6(self): + fluxes = dict(fluxanalysis.flux_balance( + self.model, 'rxn_6', tfba=False, solver=self.solver)) + self.assertAlmostEqual(fluxes['rxn_1'], 500) + self.assertAlmostEqual(fluxes['rxn_2'], 0) + self.assertAlmostEqual(fluxes['rxn_6'], 1000) + + def test_flux_balance_object_maximize(self): + p = fluxanalysis.FluxBalanceProblem(self.model, self.solver) + p.maximize('rxn_6') + self.assertAlmostEqual(p.get_flux('rxn_1'), 500) + self.assertAlmostEqual(p.get_flux('rxn_2'), 0) + self.assertAlmostEqual(p.get_flux('rxn_6'), 1000) + + def test_flux_balance_object_minimize_l1(self): + p = fluxanalysis.FluxBalanceProblem(self.model, self.solver) + p.prob.add_linear_constraints(p.get_flux_var('rxn_6') == 1000) + p.minimize_l1() + self.assertAlmostEqual(p.get_flux('rxn_1'), 500) + self.assertAlmostEqual(p.get_flux('rxn_2'), 0) + self.assertAlmostEqual(p.get_flux('rxn_3'), 1000) + self.assertAlmostEqual(p.get_flux('rxn_4'), 0) + self.assertAlmostEqual(p.get_flux('rxn_5'), 0) + self.assertAlmostEqual(p.get_flux('rxn_6'), 1000) + + def test_flux_balance_object_minimize_l1_function(self): + fluxes = dict(fluxanalysis.flux_minimization( + self.model, {'rxn_6': 1000}, self.solver)) + self.assertAlmostEqual(fluxes['rxn_1'], 500) + self.assertAlmostEqual(fluxes['rxn_2'], 0) + self.assertAlmostEqual(fluxes['rxn_3'], 1000) + self.assertAlmostEqual(fluxes['rxn_4'], 0) + self.assertAlmostEqual(fluxes['rxn_5'], 0) + self.assertAlmostEqual(fluxes['rxn_6'], 1000) + + def test_flux_balance_object_max_min_l1(self): + p = fluxanalysis.FluxBalanceProblem(self.model, self.solver) + p.max_min_l1('rxn_6') + self.assertAlmostEqual(p.get_flux('rxn_1'), 500) + self.assertAlmostEqual(p.get_flux('rxn_2'), 0) + self.assertAlmostEqual(p.get_flux('rxn_3'), 1000) + self.assertAlmostEqual(p.get_flux('rxn_4'), 0) + self.assertAlmostEqual(p.get_flux('rxn_5'), 0) + self.assertAlmostEqual(p.get_flux('rxn_6'), 1000) + + # The temporary constraint on the reaction rxn_6 should go away. If + # not, the next maximize will raise a FluxBalanceError. + p.prob.add_linear_constraints(p.get_flux_var('rxn_1') == 10) + p.maximize('rxn_6') + self.assertAlmostEqual(p.get_flux('rxn_6'), 20) + + def test_flux_balance_object_max_min_l1_multiple(self): + p = fluxanalysis.FluxBalanceProblem(self.model, self.solver) + p.max_min_l1({'rxn_3': 1, 'rxn_4': 1, 'rxn_5': 1}) + self.assertAlmostEqual(p.get_flux('rxn_1'), 500) + self.assertAlmostEqual(p.get_flux('rxn_2'), 0) + self.assertAlmostEqual(p.get_flux('rxn_3'), 0) + self.assertAlmostEqual(p.get_flux('rxn_4'), 1000) + self.assertAlmostEqual(p.get_flux('rxn_5'), 1000) + self.assertAlmostEqual(p.get_flux('rxn_6'), 1000) + + def test_flux_balance_infeasible(self): + self.model.limits['rxn_6'].lower = 500 + self.model.limits['rxn_1'].upper = 10 + p = fluxanalysis.FluxBalanceProblem(self.model, self.solver) + + try: + p.maximize('rxn_6') + except fluxanalysis.FluxBalanceError as e: + self.assertFalse(e.result.unbounded) + else: + self.fail('FluxBalanceError was not raised!') + + def test_flux_balance_unbounded(self): + unbounded = float('-inf'), float('inf') + self.model.limits['rxn_1'].bounds = unbounded + self.model.limits['rxn_3'].bounds = unbounded + self.model.limits['rxn_6'].bounds = unbounded + p = fluxanalysis.FluxBalanceProblem(self.model, self.solver) + + if self.solver.properties['name'] == 'qsoptex': + # QSopt_ex returns status code 100 for this example. It seems that + # it is unable to determine whether the problem is unbounded. + self.skipTest('Skipping because of known issue with QSopt_ex') + + try: + p.maximize('rxn_6') + except fluxanalysis.FluxBalanceError as e: + self.assertTrue(e.result.unbounded) + else: + self.fail('FluxBalanceError was not raised!') + + +class TestFluxBalanceThermodynamic(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('ex_A', parse_reaction('|A| <=>')) + self.database.set_reaction('ex_D', parse_reaction('|D| <=>')) + self.database.set_reaction('rxn_1', parse_reaction('|A| => |B|')) + self.database.set_reaction('rxn_2', parse_reaction('|B| <=> |C|')) + self.database.set_reaction('rxn_3', parse_reaction('|C| <=> |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|D| <=> |E|')) + self.database.set_reaction('rxn_5', parse_reaction('|E| => |B|')) + + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + self.model.limits['ex_A'].lower = -10 # Low uptake + self.model.limits['ex_D'].lower = 0 # No uptake + + try: + self.solver = generic.Solver(integer=True) + except generic.RequirementsError: + self.skipTest('Unable to find an MILP solver for tests') + + def test_flux_balance_tfba_exchange_d(self): + fluxes = dict(fluxanalysis.flux_balance( + self.model, 'ex_D', tfba=True, solver=self.solver)) + self.assertAlmostEqual(fluxes['ex_A'], -10) + self.assertAlmostEqual(fluxes['ex_D'], 10) + self.assertAlmostEqual(fluxes['rxn_2'], 10) + self.assertAlmostEqual(fluxes['rxn_4'], 0) + self.assertAlmostEqual(fluxes['rxn_5'], 0) + + +class TestFluxVariability(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + self.database.set_reaction('rxn_7', parse_reaction('|E| => |F|')) + self.database.set_reaction('rxn_8', parse_reaction('|F| => |E|')) + + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + self.model.limits['rxn_5'].upper = 100 + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_flux_variability(self): + if self.solver.properties['name'] == 'qsoptex': + self.skipTest('Skipping because of known issue with QSopt_ex (' + 'cannot assign value to integrality tolerance when ' + 'QSopt_ex is the sole LP solver)') + + fluxes = dict(fluxanalysis.flux_variability( + self.model, self.model.reactions, {'rxn_6': 200}, + tfba=False, solver=self.solver)) + + for bounds in itervalues(fluxes): + self.assertEqual(len(bounds), 2) + + self.assertAlmostEqual(fluxes['rxn_1'][0], 100) + + self.assertAlmostEqual(fluxes['rxn_2'][0], 0) + self.assertAlmostEqual(fluxes['rxn_2'][1], 0) + + self.assertAlmostEqual(fluxes['rxn_5'][0], 0) + self.assertAlmostEqual(fluxes['rxn_5'][1], 100) + + self.assertAlmostEqual(fluxes['rxn_6'][0], 200) + + self.assertGreater(fluxes['rxn_7'][1], 0) + self.assertGreater(fluxes['rxn_8'][1], 0) + + def test_flux_variability_unbounded(self): + self.model.limits['rxn_7'].upper = float('inf') + self.model.limits['rxn_8'].upper = float('inf') + + if self.solver.properties['name'] == 'qsoptex': + # QSopt_ex returns status code 100 for this example. It seems that + # it is unable to determine whether the problem is unbounded. + self.skipTest('Skipping because of known issue with QSopt_ex') + + fluxes = dict(fluxanalysis.flux_variability( + self.model, self.model.reactions, {'rxn_6': 200}, + tfba=False, solver=self.solver)) + + for bounds in itervalues(fluxes): + self.assertEqual(len(bounds), 2) + + self.assertAlmostEqual(fluxes['rxn_6'][0], 200) + + self.assertAlmostEqual(fluxes['rxn_7'][0], 0) + self.assertEqual(fluxes['rxn_7'][1], float('inf')) + + self.assertAlmostEqual(fluxes['rxn_8'][0], 0) + self.assertEqual(fluxes['rxn_8'][1], float('inf')) + + +class TestFluxVariabilityThermodynamic(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + self.database.set_reaction('rxn_7', parse_reaction('|E| => |F|')) + self.database.set_reaction('rxn_8', parse_reaction('|F| => |E|')) + + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + self.model.limits['rxn_5'].upper = 100 + + try: + self.solver = generic.Solver(integer=True) + except generic.RequirementsError: + self.skipTest('Unable to find an MILP solver for tests') + + def test_flux_variability_thermodynamic(self): + if self.solver.properties['name'] == 'glpk': + self.skipTest('Skipping because of known issue with GLPK') + fluxes = dict(fluxanalysis.flux_variability( + self.model, self.model.reactions, {'rxn_6': 200}, + tfba=True, solver=self.solver)) + + self.assertAlmostEqual(fluxes['rxn_1'][0], 100) + + self.assertAlmostEqual(fluxes['rxn_2'][0], 0) + self.assertAlmostEqual(fluxes['rxn_2'][1], 0) + + self.assertAlmostEqual(fluxes['rxn_5'][0], 0) + self.assertAlmostEqual(fluxes['rxn_5'][1], 100) + + self.assertAlmostEqual(fluxes['rxn_6'][0], 200) + + self.assertAlmostEqual(fluxes['rxn_7'][1], 0) + self.assertAlmostEqual(fluxes['rxn_8'][1], 0) + + +class TestFluxConsistency(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + self.database.set_reaction('rxn_7', parse_reaction('|E| => |F|')) + self.database.set_reaction('rxn_8', parse_reaction('|F| => |E|')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_check_on_consistent(self): + self.model.remove_reaction('rxn_2') + core = self.model.reactions + inconsistent = set(fluxanalysis.consistency_check( + self.model, core, epsilon=0.001, tfba=False, solver=self.solver)) + self.assertEqual(inconsistent, set()) + + def test_check_on_inconsistent(self): + core = set(self.model.reactions) + inconsistent = set(fluxanalysis.consistency_check( + self.model, core, epsilon=0.001, tfba=False, solver=self.solver)) + self.assertEqual(inconsistent, {'rxn_2'}) + + +class TestFluxConsistencyThermodynamic(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + self.database.set_reaction('rxn_7', parse_reaction('|E| => |F|')) + self.database.set_reaction('rxn_8', parse_reaction('|F| => |E|')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver(integer=True) + except generic.RequirementsError: + self.skipTest('Unable to find an MILP solver for tests') + + def test_check_on_inconsistent_with_thermodynamic_constraints(self): + self.model.remove_reaction('rxn_2') + core = self.model.reactions + inconsistent = set(fluxanalysis.consistency_check( + self.model, core, epsilon=0.001, tfba=True, solver=self.solver)) + self.assertEqual(inconsistent, {'rxn_7', 'rxn_8'}) + + +class TestFluxRandomization(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + self.database.set_reaction('rxn_7', parse_reaction('|E| => |F|')) + self.database.set_reaction('rxn_8', parse_reaction('|F| => |E|')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_flux_randomization(self): + fluxes = dict(fluxanalysis.flux_randomization( + self.model, {'rxn_6': 1000}, False, self.solver)) + self.assertAlmostEqual(fluxes['rxn_1'], 500) + self.assertAlmostEqual(fluxes['rxn_2'], 0) + self.assertAlmostEqual(fluxes['rxn_3'] + fluxes['rxn_4'], 1000) + self.assertAlmostEqual(fluxes['rxn_6'], 1000) + + # Cycle + self.assertGreaterEqual(fluxes['rxn_7'], 0) + self.assertGreaterEqual(fluxes['rxn_8'], 0) + self.assertLessEqual(fluxes['rxn_7'], 1000) + self.assertLessEqual(fluxes['rxn_8'], 1000) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_lpsolver_generic.py",".py","3829","101","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import os +import unittest +from decimal import Decimal +from fractions import Fraction + +from psamm.lpsolver import generic, lp + + +class TestSolverProblem(unittest.TestCase): + """"""Test the current solver chosen by generic. + + To test all solvers, run this test multiple times with the PSAMM_SOLVER + environment variable set to the solver to test. + """""" + def setUp(self): + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_set_decimal_variable_bounds(self): + """"""Test that Decimal can be used for variable bounds."""""" + prob = self.solver.create_problem() + prob.define('x', lower=Decimal('3.5'), upper=Decimal('500.3')) + + def test_set_decimal_objective(self): + """"""Test that Decimal can be used in objective."""""" + prob = self.solver.create_problem() + prob.define('x', lower=3, upper=100) + prob.set_objective(Decimal('3.4') * prob.var('x')) + + def test_set_fraction_objective(self): + """"""Test that Fraction can be used in objective."""""" + prob = self.solver.create_problem() + prob.define('x', lower=-5, upper=5) + prob.set_objective(Fraction(1, 2) * prob.var('x')) + + def test_set_decimal_constraint(self): + """"""Test that Decimal can be used in constraints."""""" + prob = self.solver.create_problem() + prob.define('x', lower=0, upper=5) + prob.add_linear_constraints( + Decimal('5.6') * prob.var('x') >= Decimal('8.9')) + + def test_result_evaluate_decimal_expression(self): + """"""Test that Decimal in expression can be used to evaluate result."""""" + prob = self.solver.create_problem() + prob.define('x', lower=0, upper=Fraction(5, 2)) + prob.add_linear_constraints(prob.var('x') >= 2) + prob.set_objective(prob.var('x')) + result = prob.solve(lp.ObjectiveSense.Maximize) + value = result.get_value(Decimal('3.4') * prob.var('x')) + self.assertAlmostEqual(value, Fraction(17, 2)) + + def test_redefine_variable(self): + """"""Test that redefining a variable fails."""""" + prob = self.solver.create_problem() + prob.define('x', lower=3, upper=100) + with self.assertRaises(ValueError): + prob.define('x', lower=3, upper=100) + + def test_has_variable(self): + """"""Test whether has_variable() works."""""" + prob = self.solver.create_problem() + self.assertFalse(prob.has_variable('x')) + prob.define('x', lower=-400) + self.assertTrue(prob.has_variable('x')) + + +class TestListSolversCommand(unittest.TestCase): + def test_list_lpsolvers(self): + # This test case is for travis and will not pass on a local computer + if os.environ.get('PSAMM_SOLVER') in ('nosolver', None): + with self.assertRaises(SystemExit): + generic.list_solvers([]) + else: + generic.list_solvers([]) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_command.py",".py","35643","904","# -*- coding: utf-8 -*- +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson +# Copyright 2020-2020 Elysha Sameth + +from __future__ import unicode_literals + +import sys +import os +import argparse +import shutil +import tempfile +from contextlib import contextmanager +import unittest + +from six import StringIO, BytesIO, text_type + +from psamm.command import (main, Command, MetabolicMixin, SolverCommandMixin, + CommandError) +from psamm.lpsolver import generic +from psamm.datasource import native, sbml + +from psamm.commands.chargecheck import ChargeBalanceCommand +from psamm.commands.duplicatescheck import DuplicatesCheck +from psamm.commands.excelexport import ExcelExportCommand +from psamm.commands.fastgapfill import FastGapFillCommand +from psamm.commands.fba import FluxBalanceCommand +from psamm.commands.fluxcheck import FluxConsistencyCommand +from psamm.commands.fluxcoupling import FluxCouplingCommand +from psamm.commands.formulacheck import FormulaBalanceCommand +from psamm.commands.fva import FluxVariabilityCommand +from psamm.commands.gapcheck import GapCheckCommand +from psamm.commands.gapfill import GapFillCommand +from psamm.commands.genedelete import GeneDeletionCommand +from psamm.commands.masscheck import MassConsistencyCommand +from psamm.commands.primarypairs import PrimaryPairsCommand +from psamm.commands.randomsparse import RandomSparseNetworkCommand +from psamm.commands.robustness import RobustnessCommand +from psamm.commands.sbmlexport import SBMLExport +from psamm.commands.search import SearchCommand +from psamm.commands.tableexport import ExportTableCommand +from psamm.commands.vis import VisualizationCommand + + +@contextmanager +def redirected_stdout(target=None): + stdout = sys.stdout + if target is None: + target = StringIO() + try: + sys.stdout = target + yield target + finally: + sys.stdout = stdout + + +class MockCommand(Command): + """"""Test command. + + This is a command for testing basic commands. + """""" + init_parser_called = False + run_called = False + has_native_model = False + + @classmethod + def init_parser(cls, parser): + cls.init_parser_called = True + parser.add_argument('--test-argument', action='store_true') + super(MockCommand, cls).init_parser(parser) + + def __init__(self, *args, **kwargs): + super(MockCommand, self).__init__(*args, **kwargs) + + def run(self): + self.__class__.run_called = True + self.__class__.has_native_model = hasattr(self, '_model') + + +class MockMetabolicCommand(MetabolicMixin, Command): + """"""Test metabolic model command."""""" + has_metabolic_model = False + + def run(self): + self.__class__.has_metabolic_model = hasattr(self, '_mm') + + +class MockSolverCommand(SolverCommandMixin, Command): + """"""Test solver command. + + This is a command for testing solver commands. + """""" + def run(self): + solver = self._get_solver() + print(solver) + + +class BaseCommandTest(object): + """"""Generic methods used for different test cases. + + This does not inherit from TestCase as it should not be run as a test + case. Use as a mixin from actual TestCase subclasses. Implement the + method get_default_model() to have the run_command() methods use a + default model. + """""" + def assertTableOutputEqual(self, output, table): + self.assertEqual( + output, '\n'.join('\t'.join(row) for row in table) + '\n') + + def is_solver_available(self, **kwargs): + try: + generic.Solver(**kwargs) + except generic.RequirementsError: + return False + + return True + + def skip_test_if_no_solver(self, **kwargs): + if not self.is_solver_available(**kwargs): + self.skipTest('No solver available') + + def run_command(self, command_class, args=[], target=None, model=None): + parser = argparse.ArgumentParser() + command_class.init_parser(parser) + parsed_args = parser.parse_args(args) + + if model is None: + model = self.get_default_model() + + command = command_class(model, parsed_args) + + with redirected_stdout(target=target) as f: + command.run() + + return f + + def run_solver_command( + self, command_class, args=[], requirements={}, **kwargs): + with redirected_stdout() as f: + if self.is_solver_available(**requirements): + self.run_command(command_class, args, **kwargs) + else: + with self.assertRaises(generic.RequirementsError): + self.run_command(command_class, args, **kwargs) + + return f + + +class TestCommandMain(unittest.TestCase, BaseCommandTest): + def setUp(self): + reader = native.ModelReader({ + 'name': 'Test model', + 'biomass': 'rxn_1', + 'compartments': [ + { + 'id': 'e', + 'name': 'Extracellular', + 'adjacent_to': ['c'] + }, + { + 'id': 'c', + 'name': 'Cytosol', + 'adjacent_to': 'e' + } + ], + 'reactions': [ + { + 'id': 'rxn_1', + 'name': 'Reaction 1', + 'equation': '|A_\u2206[e]| => |B[c]|', + 'genes': ['gene_1', 'gene_2'] + }, { + 'id': 'rxn_2_\u03c0', + 'name': 'Reaction 2', + 'equation': 'atp[c] + (2) |B[c]| <=> adp[c] + |C[e]|', + 'genes': 'gene_3 or (gene_4 and gene_5)' + }, { + 'id': 'rxn_3', + 'equation': 'D[c] => E[c]' + } + ], + 'compounds': [ + { + 'id': 'A_\u2206', + 'name': 'Compound A', + 'charge': 0 + }, + { + 'id': 'B', + 'name': 'Compound B', + 'formula': 'H2O', + 'charge': -1 + }, + { + 'id': 'C', + 'charge': -1, + 'formula': 'O2' + }, + { + 'id': 'atp', + 'name': '\u2192 ATP ', + 'charge': -4, + 'formula': 'C10H12N5O13P3' + }, + { + 'id': 'adp', + 'name': ' ADP', + 'charge': -3, + 'formula': 'C10H12N5O10P2' + } + ], + 'exchange': [ + { + 'compartment': 'e', + 'compounds': [ + {'id': 'A_\u2206'}, + {'id': 'C'} + ] + } + ], + 'limits': [ + { + 'reaction': 'rxn_2_\u03c0', + 'upper': 100 + } + ] + }) + self._model = reader.create_model() + + reader = native.ModelReader({ + 'biomass': 'rxn_1', + 'reactions': [ + { + 'id': 'rxn_1', + 'equation': 'A[c] => B[c]' + } + ], + 'limits': [ + { + 'reaction': 'rxn_1', + 'fixed': 10 + } + ] + }) + self._infeasible_model = reader.create_model() + + def get_default_model(self): + return self._model + + def test_invoke_version(self): + with redirected_stdout(): + with self.assertRaises(SystemExit) as context: + main(args=['--version']) + self.assertEqual(context.exception.code, 0) + + def test_run_chargecheck(self): + self.run_command(ChargeBalanceCommand) + + def test_run_duplicatescheck(self): + self.run_command(DuplicatesCheck) + + def test_run_duplicatescheck_compare_stoichiometry(self): + self.run_command(DuplicatesCheck, ['--compare-stoichiometry']) + + def test_run_duplicatescheck_compare_direction(self): + self.run_command(DuplicatesCheck, ['--compare-direction']) + + def test_run_excelexport(self): + dest = tempfile.mkdtemp() + try: + dest_path = os.path.join(dest, 'model.xlsx') + self.run_command(ExcelExportCommand, [dest_path]) + self.assertTrue(os.path.isfile(dest_path)) + finally: + shutil.rmtree(dest) + + def test_run_fastgapfill(self): + # Skip test if solver is GLPK because of issue #61. + try: + solver = generic.Solver() + if solver.properties['name'] == 'glpk': + self.skipTest('Test has known issue with GLPK') + except generic.RequirementsError: + pass + + self.run_solver_command(FastGapFillCommand) + + def test_run_fba(self): + self.run_solver_command(FluxBalanceCommand) + + def test_run_fba_with_infeasible(self): + self.skip_test_if_no_solver() + with self.assertRaises(SystemExit): + self.run_solver_command( + FluxBalanceCommand, model=self._infeasible_model) + + def test_run_fba_show_all_reactions(self): + self.run_solver_command(FluxBalanceCommand, ['--all-reactions']) + + def test_run_fba_with_tfba(self): + self.run_solver_command( + FluxBalanceCommand, ['--loop-removal', 'tfba'], {'integer': True}) + + def test_run_fba_with_tfba_infeasible(self): + self.skip_test_if_no_solver(integer=True) + with self.assertRaises(SystemExit): + self.run_solver_command( + FluxBalanceCommand, ['--loop-removal=tfba'], {'integer': True}, + model=self._infeasible_model) + + def test_run_fba_with_l1min(self): + self.run_solver_command( + FluxBalanceCommand, ['--loop-removal', 'l1min']) + + def test_run_fba_with_l1min_infeasible(self): + self.skip_test_if_no_solver() + with self.assertRaises(SystemExit): + self.run_solver_command( + FluxBalanceCommand, ['--loop-removal=l1min'], + model=self._infeasible_model) + + def test_run_fluxcheck(self): + self.run_solver_command(FluxConsistencyCommand) + + def test_run_fluxcheck_with_infeasible(self): + self.skip_test_if_no_solver() + try: + solver = generic.Solver() + if solver.properties['name'] == 'glpk' or \ + solver.properties['name'] == 'qsoptex': + self.skipTest('Test has known issue with github actions. ' + 'Known to work locally') + except generic.RequirementsError: + pass + with self.assertRaises(SystemExit): + self.run_solver_command( + FluxConsistencyCommand, model=self._infeasible_model) + + def test_run_fluxcheck_with_unrestricted(self): + self.run_solver_command(FluxConsistencyCommand, ['--unrestricted']) + + def test_run_fluxcheck_with_fastcore(self): + self.run_solver_command(FluxConsistencyCommand, ['--fastcore']) + + def test_run_fluxcheck_with_fastcore_infeasible(self): + self.skip_test_if_no_solver() + with self.assertRaises(SystemExit): + self.run_solver_command( + FluxConsistencyCommand, ['--fastcore'], + model=self._infeasible_model) + + def test_run_fluxcheck_with_tfba(self): + self.run_solver_command( + FluxConsistencyCommand, ['--loop-removal=tfba'], {'integer': True}) + + def test_run_fluxcheck_with_reduce_lp(self): + self.run_solver_command(FluxConsistencyCommand, ['--reduce-lp']) + + def test_run_fluxcheck_with_reduce_lp_infeasible(self): + self.skip_test_if_no_solver() + with self.assertRaises(SystemExit): + self.run_solver_command( + FluxConsistencyCommand, ['--reduce-lp'], + model=self._infeasible_model) + + def test_run_fluxcheck_with_both_tfba_and_fastcore(self): + self.skip_test_if_no_solver() + with self.assertRaises(CommandError): + self.run_solver_command( + FluxConsistencyCommand, ['--loop-removal=tfba', '--fastcore'], + {'integer': True}) + + def test_run_fluxcoupling(self): + self.run_solver_command(FluxCouplingCommand) + + def test_run_fluxcoupling_with_infeasible(self): + self.skip_test_if_no_solver() + with self.assertRaises(SystemExit): + self.run_solver_command( + FluxCouplingCommand, model=self._infeasible_model) + + def test_run_formulacheck(self): + self.run_command(FormulaBalanceCommand) + + def test_run_fva(self): + self.run_solver_command(FluxVariabilityCommand) + + def test_run_fva_with_infeasible(self): + self.skip_test_if_no_solver() + with self.assertRaises(SystemExit): + self.run_solver_command( + FluxVariabilityCommand, model=self._infeasible_model) + + def test_run_fva_with_tfba(self): + self.run_solver_command( + FluxVariabilityCommand, ['--loop-removal=tfba'], {'integer': True}) + + def test_run_gapcheck_prodcheck(self): + self.run_solver_command( + GapCheckCommand, ['--method=prodcheck']) + + def test_run_gapcheck_prodcheck_without_implicit_sinks(self): + self.run_solver_command( + GapCheckCommand, ['--method=prodcheck', '--no-implicit-sinks']) + + def test_run_gapcheck_prodcheck_without_extracellular(self): + self.run_solver_command( + GapCheckCommand, ['--method=prodcheck', '--exclude-extracellular']) + + def test_run_gapcheck_prodcheck_with_unrestricted_exchange(self): + self.run_solver_command( + GapCheckCommand, ['--method=prodcheck', '--unrestricted-exchange']) + + def test_run_gapcheck_sinkcheck(self): + self.run_solver_command( + GapCheckCommand, ['--method=sinkcheck']) + + def test_run_gapcheck_sinkcheck_without_implicit_sinks(self): + self.run_solver_command( + GapCheckCommand, ['--method=sinkcheck', '--no-implicit-sinks']) + + def test_run_gapcheck_gapfind(self): + self.run_solver_command( + GapCheckCommand, ['--method=gapfind'], {'integer': True}) + + def test_run_gapcheck_gapfind_without_implicit_sinks(self): + self.run_solver_command( + GapCheckCommand, ['--method=gapfind', '--no-implicit-sinks'], + {'integer': True}) + + def test_run_gapfill(self): + self.run_solver_command( + GapFillCommand, requirements={'integer': True}) + + def test_run_gapfill_with_blocked(self): + self.run_solver_command( + GapFillCommand, ['--compound', 'D[c]'], {'integer': True}) + + def test_run_genedelete(self): + self.run_solver_command(GeneDeletionCommand, ['--gene', 'gene_1']) + + def test_run_genedelete_with_fba(self): + self.run_solver_command( + GeneDeletionCommand, ['--gene=gene_1', '--method=fba']) + + def test_run_genedelete_with_lin_moma(self): + self.run_solver_command( + GeneDeletionCommand, ['--gene=gene_1', '--method=lin_moma']) + + def test_run_genedelete_with_lin_moma2(self): + self.run_solver_command( + GeneDeletionCommand, ['--gene=gene_1', '--method=lin_moma2']) + + def test_run_genedelete_with_moma(self): + self.run_solver_command( + GeneDeletionCommand, ['--gene=gene_1', '--method=moma'], + {'quadratic': True}) + + def test_run_genedelete_with_moma2(self): + self.run_solver_command( + GeneDeletionCommand, ['--gene=gene_1', '--method=moma2'], + {'quadratic': True}) + + def test_run_genedelete_with_infeasible(self): + self.skip_test_if_no_solver() + with self.assertRaises(SystemExit): + self.run_solver_command( + GeneDeletionCommand, ['--gene=gene_1'], + model=self._infeasible_model) + + def test_run_masscheck_compounds(self): + self.run_solver_command(MassConsistencyCommand, ['--type', 'compound']) + + def test_run_masscheck_reactions(self): + self.run_solver_command(MassConsistencyCommand, ['--type', 'reaction']) + + def test_run_masscheck_reaction_with_checked(self): + self.run_solver_command( + MassConsistencyCommand, ['--type=reaction', '--checked=rxn_3']) + + def test_run_primarypairs_with_fpp(self): + self.run_command(PrimaryPairsCommand, ['--method', 'fpp']) + + def test_run_primarypairs_with_fpp_and_report_element(self): + self.run_command( + PrimaryPairsCommand, ['--method', 'fpp', '--report-element', 'C']) + + def test_run_primarypairs_with_fpp_and_report_all_transfers(self): + self.run_command( + PrimaryPairsCommand, ['--method', 'fpp', '--report-all-transfers']) + + def test_run_primarypairs_with_fpp_and_weight(self): + self.run_command( + PrimaryPairsCommand, [ + '--method', 'fpp', '--weights', 'C=1,H=0,R=0.5,*=0.4']) + + def test_run_primarypairs_with_mapmaker(self): + self.run_solver_command( + PrimaryPairsCommand, ['--method', 'mapmaker'], {'integer': True}) + + def test_run_randomsparse_reactions(self): + self.run_solver_command( + RandomSparseNetworkCommand, ['--type=reactions', '50%']) + + def test_run_randomsparse_genes(self): + self.run_solver_command( + RandomSparseNetworkCommand, ['--type=genes', '50%']) + + def test_run_randomsparse_exchange(self): + self.run_solver_command( + RandomSparseNetworkCommand, ['--type=exchange', '50%']) + + def test_run_randomsparse_reactions_with_infeasible(self): + self.skip_test_if_no_solver() + with self.assertRaises(SystemExit): + self.run_solver_command( + RandomSparseNetworkCommand, ['--type=reactions', '50%'], + model=self._infeasible_model) + + def test_run_robustness(self): + self.run_solver_command(RobustnessCommand, ['rxn_2_\u03c0']) + + def test_run_robustness_all_reactions(self): + self.run_solver_command( + RobustnessCommand, ['--all-reaction-fluxes', 'rxn_2_\u03c0']) + + def test_run_robustness_with_tfba(self): + self.run_solver_command( + RobustnessCommand, ['--loop-removal=tfba', 'rxn_2_\u03c0'], + {'integer': True}) + + def test_run_robustness_with_l1min(self): + self.run_solver_command( + RobustnessCommand, ['--loop-removal=l1min', 'rxn_2_\u03c0']) + + def test_run_robustness_with_fva(self): + self.run_solver_command( + RobustnessCommand, ['--fva', 'rxn_2_\u03c0'] + ) + + def test_run_robustness_with_invalid_objective(self): + with self.assertRaises(SystemExit): + self.run_solver_command( + RobustnessCommand, ['--objective=rxn_4', 'rxn_2_\u03c0'], + model=self._model) + + def test_run_robustness_with_neg_steps(self): + with self.assertRaises(CommandError): + self.run_solver_command( + RobustnessCommand, ['--steps=0', 'rxn_2_\u03c0']) + + def test_run_robustness_with_loop_removal_fva(self): + self.skip_test_if_no_solver() + with self.assertRaises(SystemExit): + self.run_solver_command( + RobustnessCommand, ['--loop-removal=tfba', '--fva', + 'rxn_2_\u03c0']) + + def test_run_robustness_min_greater(self): + self.skip_test_if_no_solver() + with self.assertRaises(CommandError): + self.run_solver_command( + RobustnessCommand, ['--minimum=50', '--maximum=20', + 'rxn_2_\u03c0']) + + def test_run_robustness_with_infeasible(self): + with self.assertRaises(SystemExit): + self.run_solver_command( + RobustnessCommand, ['rxn_2_\u03c0'], + model=self._infeasible_model) + + def test_run_sbmlexport(self): + dest = tempfile.mkdtemp() + try: + dest_path = os.path.join(dest, 'model.xml') + self.run_command(SBMLExport, [dest_path]) + self.assertTrue(os.path.isfile(dest_path)) + finally: + shutil.rmtree(dest) + + def test_run_search_compound(self): + self.run_command(SearchCommand, ['compound', '--id', 'A_\u2206']) + + def test_run_search_compound_name(self): + self.run_command(SearchCommand, ['compound', '--name', 'Compound A']) + + def test_run_search_reaction(self): + self.run_command(SearchCommand, ['reaction', '--id', 'rxn_1']) + + def test_run_search_reaction_by_compound(self): + self.run_command(SearchCommand, ['reaction', '--compound=A']) + + def test_run_tableexport_reactions(self): + f = self.run_command(ExportTableCommand, ['reactions']) + + self.assertTableOutputEqual(f.getvalue(), [ + ['id', 'equation', 'genes', 'name', 'in_model'], + ['rxn_1', 'A_\u2206[e] => B[c]', '[""gene_1"", ""gene_2""]', + 'Reaction 1', 'true'], + ['rxn_2_\u03c0', 'atp[c] + (2) B[c] <=> adp[c] + C[e]', + 'gene_3 or (gene_4 and gene_5)', 'Reaction 2', 'true'], + ['rxn_3', 'D[c] => E[c]', '', '', 'true'], + ]) + + def test_run_tableexport_trans_reactions(self): + f = self.run_command(ExportTableCommand, ['translated-reactions']) + print(f.getvalue()) + + self.assertTableOutputEqual(f.getvalue(), [ + ['id', 'equation', 'genes', 'name', 'in_model', + 'translated_equation'], + ['rxn_1', 'A_\u2206[e] => B[c]', '[""gene_1"", ""gene_2""]', + 'Reaction 1', 'true', '|Compound A[e]| => |Compound B[c]|'], + ['rxn_2_\u03c0', 'atp[c] + (2) B[c] <=> adp[c] + C[e]', + 'gene_3 or (gene_4 and gene_5)', 'Reaction 2', 'true', + '|\u2192 ATP [c]| + (2) |Compound B[c]| <=> ' + '| ADP[c]| + C[e]'], + ['rxn_3', 'D[c] => E[c]', '', '', 'true', 'D[c] => E[c]'], + ]) + + def test_run_tableexport_compounds(self): + f = self.run_command(ExportTableCommand, ['compounds']) + self.assertTableOutputEqual(f.getvalue(), [ + ['id', 'name', 'charge', 'formula', 'in_model'], + ['A_\u2206', 'Compound A', '0', '', 'true'], + ['B', 'Compound B', '-1', 'H2O', 'true'], + ['C', '', '-1', 'O2', 'true'], + ['atp', '\u2192 ATP ', '-4', 'C10H12N5O13P3', 'true'], + ['adp', ' ADP', '-3', 'C10H12N5O10P2', 'true'] + ]) + + def test_run_tableexport_exchange(self): + f = self.run_command(ExportTableCommand, ['exchange']) + + self.assertTableOutputEqual(f.getvalue(), [ + ['Compound ID', 'Reaction ID', 'Lower Limit', 'Upper Limit'], + ['A_\u2206[e]', '', '-1000', '1000'], + ['C[e]', '', '-1000', '1000'] + ]) + + def test_run_tableexport_limits(self): + f = self.run_command(ExportTableCommand, ['limits']) + + self.assertTableOutputEqual(f.getvalue(), [ + ['Reaction ID', 'Lower Limits', 'Upper Limits'], + ['rxn_2_\u03c0', '', '100'] + ]) + + def test_run_tableexport_metadata(self): + f = self.run_command(ExportTableCommand, ['metadata']) + + self.assertTableOutputEqual(f.getvalue(), [ + ['Model Name', 'Test model'], + ['Biomass Reaction', 'rxn_1'], + ['Default Flux Limits', '1000'] + ]) + + def test_run_vis(self): + dest = tempfile.mkdtemp() + dest_path = os.path.join(dest, 'reactions') + dest_path_dot = os.path.join(dest, 'reactions.dot') + dest_path_nodes = os.path.join(dest, 'reactions.nodes.tsv') + dest_path_edges = os.path.join(dest, 'reactions.edges.tsv') + self.run_command(VisualizationCommand, ['--output', dest_path]) + self.assertTrue(os.path.isfile(dest_path_dot)) + self.assertTrue(os.path.isfile(dest_path_nodes)) + self.assertTrue(os.path.isfile(dest_path_edges)) + + def test_run_vis_element_all(self): + dest = tempfile.mkdtemp() + dest_path = os.path.join(dest, 'reactions') + dest_path_dot = os.path.join(dest, 'reactions.dot') + dest_path_nodes = os.path.join(dest, 'reactions.nodes.tsv') + dest_path_edges = os.path.join(dest, 'reactions.edges.tsv') + self.run_command(VisualizationCommand, ['--output', dest_path, + ""--element"", ""all""]) + self.assertTrue(os.path.isfile(dest_path_dot)) + self.assertTrue(os.path.isfile(dest_path_nodes)) + self.assertTrue(os.path.isfile(dest_path_edges)) + + def test_run_vis_hide_edges(self): + path = os.path.join(tempfile.mkdtemp(), 'hide_edges.csv') + with open(path, 'w') as f: + f.write('{}\t{}'.format('D[c]', 'E[c]')) + + dest = tempfile.mkdtemp() + dest_path = os.path.join(dest, 'reactions') + dest_path_dot = os.path.join(dest, 'reactions.dot') + dest_path_nodes = os.path.join(dest, 'reactions.nodes.tsv') + dest_path_edges = os.path.join(dest, 'reactions.edges.tsv') + self.run_command(VisualizationCommand, ['--output', dest_path, + ""--hide-edges"", path]) + self.assertTrue(os.path.isfile(dest_path_dot)) + self.assertTrue(os.path.isfile(dest_path_nodes)) + self.assertTrue(os.path.isfile(dest_path_edges)) + + def test_run_vis_recolor(self): + path = os.path.join(tempfile.mkdtemp(), 'color.csv') + with open(path, 'w') as f: + f.write('{}\t{}'.format('B', '#f4fc55')) + dest = tempfile.mkdtemp() + dest_path = os.path.join(dest, 'reactions') + dest_path_dot = os.path.join(dest, 'reactions.dot') + dest_path_nodes = os.path.join(dest, 'reactions.nodes.tsv') + dest_path_edges = os.path.join(dest, 'reactions.edges.tsv') + self.run_command(VisualizationCommand, ['--output', dest_path, + ""--color"", path]) + self.assertTrue(os.path.isfile(dest_path_dot)) + self.assertTrue(os.path.isfile(dest_path_nodes)) + self.assertTrue(os.path.isfile(dest_path_edges)) + + def test_run_vis_output(self): + dest = tempfile.mkdtemp() + dest_path = os.path.join(dest, 'test') + dest_path_dot = os.path.join(dest, 'test.dot') + dest_path_nodes = os.path.join(dest, 'test.nodes.tsv') + dest_path_edges = os.path.join(dest, 'test.edges.tsv') + self.run_command(VisualizationCommand, ['--output', dest_path]) + self.assertTrue(os.path.isfile(dest_path_dot)) + self.assertTrue(os.path.isfile(dest_path_nodes)) + self.assertTrue(os.path.isfile(dest_path_edges)) + + def test_run_vis_compartment(self): + dest = tempfile.mkdtemp() + dest_path = os.path.join(dest, 'reactions') + dest_path_dot = os.path.join(dest, 'reactions.dot') + dest_path_nodes = os.path.join(dest, 'reactions.nodes.tsv') + dest_path_edges = os.path.join(dest, 'reactions.edges.tsv') + self.run_command(VisualizationCommand, ['--output', dest_path, + '--compartment']) + self.assertTrue(os.path.isfile(dest_path_dot)) + self.assertTrue(os.path.isfile(dest_path_nodes)) + self.assertTrue(os.path.isfile(dest_path_edges)) + + def test_run_vis_fba(self): + path = os.path.join(tempfile.mkdtemp(), 'fba.tsv') + with open(path, 'w') as f: + f.write('{}\t{}'.format('rxn_1', -0.000001)) + dest = tempfile.mkdtemp() + dest_path = os.path.join(dest, 'reactions') + dest_path_dot = os.path.join(dest, 'reactions.dot') + dest_path_nodes = os.path.join(dest, 'reactions.nodes.tsv') + dest_path_edges = os.path.join(dest, 'reactions.edges.tsv') + self.run_command(VisualizationCommand, ['--output', dest_path, + '--fba', path]) + self.assertTrue(os.path.isfile(dest_path_dot)) + self.assertTrue(os.path.isfile(dest_path_nodes)) + self.assertTrue(os.path.isfile(dest_path_edges)) + + def test_run_vis_fba_invalid_flux(self): + path = os.path.join(tempfile.mkdtemp(), 'fba.tsv') + with open(path, 'w') as f: + f.write('{}\t{}'.format('rxn_1', 'a')) + dest = tempfile.mkdtemp() + dest_path = os.path.join(dest, 'reactions') + dest_path_dot = os.path.join(dest, 'reactions.dot') + dest_path_nodes = os.path.join(dest, 'reactions.nodes.tsv') + dest_path_edges = os.path.join(dest, 'reactions.edges.tsv') + self.run_command(VisualizationCommand, ['--output', dest_path, + '--fba', path]) + self.assertTrue(os.path.isfile(dest_path_dot)) + self.assertTrue(os.path.isfile(dest_path_nodes)) + self.assertTrue(os.path.isfile(dest_path_edges)) + + def test_run_vis_fva(self): + path = os.path.join(tempfile.mkdtemp(), 'fva.tsv') + with open(path, 'w') as f: + f.write('{}\t{}\t{}'.format('rxn_1', -0.000001, 0.000001)) + dest = tempfile.mkdtemp() + dest_path = os.path.join(dest, 'reactions') + dest_path_dot = os.path.join(dest, 'reactions.dot') + dest_path_nodes = os.path.join(dest, 'reactions.nodes.tsv') + dest_path_edges = os.path.join(dest, 'reactions.edges.tsv') + self.run_command(VisualizationCommand, ['--output', dest_path, + '--fva', path]) + self.assertTrue(os.path.isfile(dest_path_dot)) + self.assertTrue(os.path.isfile(dest_path_nodes)) + self.assertTrue(os.path.isfile(dest_path_edges)) + + def test_run_vis_fva_invalid_flux(self): + path = os.path.join(tempfile.mkdtemp(), 'fva.tsv') + with open(path, 'w') as f: + f.write('{}\t{}\t{}'.format('rxn_1', 'a', -0.000001)) + dest = tempfile.mkdtemp() + dest_path = os.path.join(dest, 'reactions') + dest_path_dot = os.path.join(dest, 'reactions.dot') + dest_path_nodes = os.path.join(dest, 'reactions.nodes.tsv') + dest_path_edges = os.path.join(dest, 'reactions.edges.tsv') + self.run_command(VisualizationCommand, ['--output', dest_path, + '--fva', path]) + self.assertTrue(os.path.isfile(dest_path_dot)) + self.assertTrue(os.path.isfile(dest_path_nodes)) + self.assertTrue(os.path.isfile(dest_path_edges)) + + def test_command_main(self): + self.run_command(MockCommand) + self.assertTrue(MockCommand.run_called) + self.assertTrue(MockCommand.init_parser_called) + self.assertTrue(MockCommand.has_native_model) + + def test_solver_command_main(self): + with self.assertRaises(generic.RequirementsError): + self.run_command( + MockSolverCommand, ['--solver', 'name=not-an-actual-solver']) + + def test_metabolic_command_main(self): + self.run_command(MockMetabolicCommand) + self.assertTrue(MockMetabolicCommand.has_metabolic_model) + + def test_command_fail(self): + mock_command = MockCommand(self._model, None) + with self.assertRaises(SystemExit): + mock_command.fail('Run time error') + + def test_command_argument_error(self): + mock_command = MockCommand(self._model, None) + with self.assertRaises(CommandError): + mock_command.argument_error(msg='Argument error') + + +class TestSBMLCommandMain(unittest.TestCase, BaseCommandTest): + def setUp(self): + doc = BytesIO(''' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +'''.encode('utf-8')) + + reader = sbml.SBMLReader(doc) + self._model = reader.create_model() + + def get_default_model(self): + return self._model + + def test_run_fba(self): + self.run_solver_command(FluxBalanceCommand) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_metabolicmodel.py",".py","14865","330","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.metabolicmodel import MetabolicModel, FlipableModelView +from psamm.database import DictDatabase +from psamm.reaction import Reaction, Compound, Direction +from psamm.datasource.reaction import parse_reaction + + +class TestLoadMetabolicModel(unittest.TestCase): + def test_load_model_without_reactions(self): + database = DictDatabase() + database.set_reaction('rxn_1', parse_reaction('|A| => |B|')) + database.set_reaction('rxn_2', parse_reaction('|B| => |C|')) + database.set_reaction('rxn_3', parse_reaction('|C| => |D|')) + model = MetabolicModel.load_model(database) + + self.assertEqual(set(model.reactions), {'rxn_1', 'rxn_2', 'rxn_3'}) + + def test_load_model_with_reaction_subset(self): + database = DictDatabase() + database.set_reaction('rxn_1', parse_reaction('|A| => |B|')) + database.set_reaction('rxn_2', parse_reaction('|B| => |C|')) + database.set_reaction('rxn_3', parse_reaction('|C| => |D|')) + model = MetabolicModel.load_model(database, {'rxn_1'}) + + self.assertEqual(set(model.reactions), {'rxn_1'}) + + +class TestMetabolicModel(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) A[c]')) + self.database.set_reaction('rxn_2', parse_reaction('A[c] <=> B[c]')) + self.database.set_reaction('rxn_3', parse_reaction('A[c] => D[e]')) + self.database.set_reaction('rxn_4', parse_reaction('A[c] => C[c]')) + self.database.set_reaction('rxn_5', parse_reaction('C[c] => D[e]')) + self.database.set_reaction('rxn_6', parse_reaction('D[e] =>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + def test_database_property(self): + self.assertIs(self.model.database, self.database) + + def test_reaction_set(self): + self.assertEqual(set(self.model.reactions), + {'rxn_1', 'rxn_2', 'rxn_3', 'rxn_4', + 'rxn_5', 'rxn_6'}) + + def test_compound_set(self): + self.assertEqual(set(self.model.compounds), + {Compound('A', 'c'), Compound('B', 'c'), + Compound('C', 'c'), Compound('D', 'e')}) + + def test_compartments(self): + self.assertEqual(set(self.model.compartments), {'c', 'e'}) + + def test_add_reaction_new(self): + self.database.set_reaction('rxn_7', parse_reaction('D[e] => E[e]')) + self.model.add_reaction('rxn_7') + self.assertIn('rxn_7', set(self.model.reactions)) + self.assertIn(Compound('E', 'e'), set(self.model.compounds)) + + def test_add_reaction_existing(self): + self.model.add_reaction('rxn_1') + self.assertEqual( + set(self.model.reactions), + {'rxn_1', 'rxn_2', 'rxn_3', 'rxn_4', 'rxn_5', 'rxn_6'}) + self.assertEqual(set(self.model.compounds), { + Compound('A', 'c'), Compound('B', 'c'), Compound('C', 'c'), + Compound('D', 'e')}) + + def test_add_reaction_invalid(self): + with self.assertRaises(Exception): + self.model.add_reaction('rxn_7') + + def test_remove_reaction_existing(self): + self.model.remove_reaction('rxn_2') + self.assertEqual( + set(self.model.reactions), + {'rxn_1', 'rxn_3', 'rxn_4', 'rxn_5', 'rxn_6'}) + self.assertEqual(set(self.model.compounds), { + Compound('A', 'c'), Compound('C', 'c'), Compound('D', 'e')}) + + def test_is_reversible_on_reversible(self): + self.assertTrue(self.model.is_reversible('rxn_2')) + + def test_is_reversible_on_irreversible(self): + self.assertFalse(self.model.is_reversible('rxn_1')) + self.assertFalse(self.model.is_reversible('rxn_3')) + + def test_is_exchange_on_exchange(self): + self.assertTrue(self.model.is_exchange('rxn_1')) + self.assertTrue(self.model.is_exchange('rxn_6')) + + def test_is_exchange_on_internal(self): + self.assertFalse(self.model.is_exchange('rxn_2')) + self.assertFalse(self.model.is_exchange('rxn_5')) + + def test_is_exchange_on_empty(self): + self.database.set_reaction('rxn_7', Reaction(Direction.Both, [], [])) + self.model.add_reaction('rxn_7') + self.assertFalse(self.model.is_exchange('rxn_7')) + + def test_limits_get_item(self): + self.assertEqual(self.model.limits['rxn_1'].bounds, (0, 1000)) + self.assertEqual(self.model.limits['rxn_2'].bounds, (-1000, 1000)) + self.assertEqual(self.model.limits['rxn_3'].bounds, (0, 1000)) + + def test_limits_get_item_invalid_key(self): + with self.assertRaises(KeyError): + a = self.model.limits['rxn_7'] + + def test_limits_set_item_is_invalid(self): + with self.assertRaises(TypeError): + self.model.limits['rxn_1'] = None + + def test_limits_set_upper_flux_bounds(self): + self.model.limits['rxn_1'].upper = 500 + self.assertEqual(self.model.limits['rxn_1'].bounds, (0, 500)) + + def test_limits_set_upper_flux_bounds_to_invalid(self): + with self.assertRaises(ValueError): + self.model.limits['rxn_1'].upper = -20 + + def test_limits_delete_upper_flux_bounds(self): + self.model.limits['rxn_1'].upper = 500 + del self.model.limits['rxn_1'].upper + self.assertEqual(self.model.limits['rxn_1'].bounds, (0, 1000)) + + def test_limits_delete_upper_not_set(self): + del self.model.limits['rxn_1'].upper + self.assertEqual(self.model.limits['rxn_1'].bounds, (0, 1000)) + + def test_limits_set_lower_flux_bounds(self): + self.model.limits['rxn_1'].lower = 500 + self.assertEqual(self.model.limits['rxn_1'].bounds, (500, 1000)) + + def test_limits_set_lower_flux_bounds_to_invalid(self): + with self.assertRaises(ValueError): + self.model.limits['rxn_1'].lower = 1001 + + def test_limits_delete_lower_flux_bounds(self): + self.model.limits['rxn_1'].lower = 500 + del self.model.limits['rxn_1'].lower + self.assertEqual(self.model.limits['rxn_1'].bounds, (0, 1000)) + + def test_limits_delete_lower_not_set(self): + del self.model.limits['rxn_1'].lower + self.assertEqual(self.model.limits['rxn_1'].bounds, (0, 1000)) + + def test_limits_set_both_flux_bounds(self): + self.model.limits['rxn_2'].bounds = 1001, 1002 + self.assertEqual(self.model.limits['rxn_2'].lower, 1001) + self.assertEqual(self.model.limits['rxn_2'].upper, 1002) + self.assertEqual(self.model.limits['rxn_2'].bounds, (1001, 1002)) + + def test_limits_set_both_flux_bounds_to_invalid(self): + with self.assertRaises(ValueError): + self.model.limits['rxn_2'].bounds = 10, -1000 + + def test_limits_delete_both_flux_bounds(self): + self.model.limits['rxn_2'].bounds = -10, 800 + del self.model.limits['rxn_2'].bounds + self.assertEqual(self.model.limits['rxn_2'].bounds, (-1000, 1000)) + + def test_limits_set_both_flux_bounds_delete_lower(self): + self.model.limits['rxn_2'].bounds = -10, 800 + del self.model.limits['rxn_2'].lower + self.assertEqual(self.model.limits['rxn_2'].bounds, (-1000, 800)) + + def test_limits_set_both_flux_bounds_delete_upper(self): + self.model.limits['rxn_2'].bounds = -10, 800 + del self.model.limits['rxn_2'].upper + self.assertEqual(self.model.limits['rxn_2'].bounds, (-10, 1000)) + + def test_limits_iter(self): + self.assertEqual(set(iter(self.model.limits)), { + 'rxn_1', 'rxn_2', 'rxn_3', 'rxn_4', 'rxn_5', 'rxn_6'}) + + def test_limits_len(self): + self.assertEqual(len(self.model.limits), 6) + + +class TestMetabolicModelFlipableView(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + + model = MetabolicModel.load_model( + self.database, self.database.reactions) + self.model = FlipableModelView(model) + + def test_flipable_model_view_matrix_get_item_after_flip(self): + self.model.flip({'rxn_4'}) + self.assertEqual(self.model.matrix[Compound('A'), 'rxn_1'], 2) + self.assertEqual(self.model.matrix[Compound('A'), 'rxn_2'], -1) + self.assertEqual(self.model.matrix[Compound('A'), 'rxn_4'], 1) + self.assertEqual(self.model.matrix[Compound('C'), 'rxn_4'], -1) + + def test_flipable_model_view_matrix_get_item_after_double_flip(self): + self.model.flip({'rxn_4', 'rxn_5'}) + self.model.flip({'rxn_1', 'rxn_4', 'rxn_2'}) + self.assertEqual(self.model.matrix[Compound('A'), 'rxn_1'], -2) + self.assertEqual(self.model.matrix[Compound('A'), 'rxn_2'], 1) + self.assertEqual(self.model.matrix[Compound('B'), 'rxn_2'], -1) + self.assertEqual(self.model.matrix[Compound('A'), 'rxn_4'], -1) + self.assertEqual(self.model.matrix[Compound('C'), 'rxn_4'], 1) + self.assertEqual(self.model.matrix[Compound('C'), 'rxn_5'], 1) + self.assertEqual(self.model.matrix[Compound('D'), 'rxn_5'], -1) + + def test_flipable_model_view_limits_get_item_after_flip(self): + self.model.flip({'rxn_1', 'rxn_2'}) + self.assertEqual(self.model.limits['rxn_1'].bounds, (-1000, 0)) + self.assertEqual(self.model.limits['rxn_2'].bounds, (-1000, 1000)) + self.assertEqual(self.model.limits['rxn_3'].bounds, (0, 1000)) + + def test_flipable_model_view_limits_set_item_after_flip(self): + self.model.flip({'rxn_1'}) + self.model.limits['rxn_1'].bounds = -20, 500 + self.assertEqual(self.model.limits['rxn_1'].bounds, (-20, 500)) + + self.model.flip({'rxn_1'}) + self.assertEqual(self.model.limits['rxn_1'].bounds, (-500, 20)) + + +class TestMetabolicModelMakeIreversible(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| => |D|')) + + self.model = MetabolicModel.load_model(self.database, + self.database.reactions) + + def test_make_irreversible(self): + mm_irrev, reversible_gene_dict, split_reversible, new_lump_rxn_dict = \ + self.model.make_irreversible() + rxn_list = [i for i in mm_irrev.reactions] + self.assertTrue( + str(mm_irrev.get_reaction('rxn_1_forward')) == 'A => B') + self.assertTrue( + str(mm_irrev.get_reaction('rxn_1_reverse')) == 'B => A') + self.assertTrue(mm_irrev.has_reaction('rxn_1_forward')) + self.assertTrue(mm_irrev.has_reaction('rxn_1_reverse')) + self.assertFalse(mm_irrev.has_reaction('rxn_1')) + + def test_make_irreversible_exclude(self): + mm_irrev, reversible_gene_dict, split_reversible, new_lump_rxn_dict = \ + self.model.make_irreversible(exclude_list=['rxn_1']) + rxn_list = [i for i in mm_irrev.reactions] + self.assertFalse(mm_irrev.has_reaction('rxn_1_forward')) + self.assertFalse(mm_irrev.has_reaction('rxn_1_reverse')) + + def test_make_irreversible_genes(self): + mm_irrev, reversible_gene_dict, split_reversible, new_lump_rxn_dict = \ + self.model.make_irreversible(gene_dict={'rxn_1': 'gene_1'}) + rxn_list = [i for i in mm_irrev.reactions] + self.assertTrue(reversible_gene_dict.get('rxn_1_forward') == 'gene_1') + self.assertTrue(reversible_gene_dict.get('rxn_1_reverse') == 'gene_1') + + def test_make_irreversible_allrev(self): + mm_irrev, reversible_gene_dict, split_reversible, new_lump_rxn_dict = \ + self.model.make_irreversible(all_reversible=True) + rxn_list = [i for i in mm_irrev.reactions] + self.assertTrue( + str(mm_irrev.get_reaction('rxn_1_forward')) == 'A => B') + self.assertTrue( + str(mm_irrev.get_reaction('rxn_1_reverse')) == 'B => A') + self.assertTrue(mm_irrev.has_reaction('rxn_1_forward')) + self.assertTrue(mm_irrev.has_reaction('rxn_1_reverse')) + self.assertTrue( + str(mm_irrev.get_reaction('rxn_2_forward')) == 'A => D') + self.assertTrue( + str(mm_irrev.get_reaction('rxn_2_reverse')) == 'D => A') + self.assertTrue(mm_irrev.has_reaction('rxn_2_forward')) + self.assertTrue(mm_irrev.has_reaction('rxn_2_reverse')) + + def test_make_irreversible_allrev(self): + mm_irrev, reversible_gene_dict, split_reversible, new_lump_rxn_dict = \ + self.model.make_irreversible(all_reversible=True) + rxn_list = [i for i in mm_irrev.reactions] + self.assertTrue( + str(mm_irrev.get_reaction('rxn_1_forward')) == 'A => B') + self.assertTrue( + str(mm_irrev.get_reaction('rxn_1_reverse')) == 'B => A') + self.assertTrue(mm_irrev.has_reaction('rxn_1_forward')) + self.assertTrue(mm_irrev.has_reaction('rxn_1_reverse')) + self.assertTrue( + str(mm_irrev.get_reaction('rxn_2_forward')) == 'A => D') + self.assertTrue( + str(mm_irrev.get_reaction('rxn_2_reverse')) == 'D => A') + self.assertTrue(mm_irrev.has_reaction('rxn_2_forward')) + self.assertTrue(mm_irrev.has_reaction('rxn_2_reverse')) + + def test_make_irreversible_allrev(self): + mm_irrev, reversible_gene_dict, split_reversible, new_lump_rxn_dict = \ + self.model.make_irreversible( + lumped_rxns={'rxn_1': [('rxn_2', 1)]}, + exclude_list=['rxn_1', 'rxn_2']) + rxn_list = [i for i in mm_irrev.reactions] + self.assertTrue(new_lump_rxn_dict == {'rxn_1': ['rxn_2']}) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_translate_id.py",".py","8895","233","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015 Jon Lund Steffensen +# Copyright 2020 Jing Wang + +import unittest +import tempfile +import shutil +import os + +from psamm import translate_id as tr_id +from psamm.datasource.native import ModelReader, NativeModel +from psamm.datasource.reaction import parse_reaction + + +class TestTranslateId(unittest.TestCase): + def setUp(self): + self._model_dir = tempfile.mkdtemp() + with open(os.path.join(self._model_dir, 'model.yaml'), 'w') as f: + f.write('\n'.join([ + '---', + 'biomass: rxn_1', + 'compartments:', + ' - id: c', + ' adjacent_to: e', + ' - id: e', + 'reactions:', + ' - id: rxn_1', + ' name: rxn_1', + ' equation: A[e] => B[c]', + ' genes: gene1 and gene2 or gene3', + ' - id: rxn_2', + ' name: rxn_2', + ' equation: B[c] => C[e]', + ' genes: gene5 or gene6', + ' - id: rxn_3', + ' name: rxn_3', + ' equation: A[e] + (6) B[c] <=> (6) C[e] + (6) D[c]', + ' genes: gene7', + 'compounds:', + ' - id: A', + ' name: compound_A', + ' formula: C6H12O6', + ' charge: 1', + ' - id: B', + ' name: compound_B', + ' formula: O2', + ' charge: 1', + ' kegg: C00010', + ' - id: C', + ' name: compound_C', + ' formula: CO2', + ' charge: -1', + ' - id: D', + ' name: compound_D', + ' formula: H2O', + 'exchange:', + ' - compartment: e', + ' - compounds:', + ' - id: A', + ' upper: 100', + ' - id: C', + 'limits:', + ' - reaction: rxn_1', + ' lower: -50', + ' - reaction: rxn_2', + ' upper: 100', + ])) + self._model = ModelReader.reader_from_path( + os.path.join(self._model_dir, 'model.yaml')).create_model() + + with open(os.path.join(self._model_dir, 'newmodel.yaml'), 'w') as f: + f.write('\n'.join([ + '---', + 'biomass: rxn_1a', + 'extracellular: s', + 'compartments:', + ' - id: c', + ' adjacent_to: s', + ' - id: s', + 'reactions:', + ' - id: rxn_1a', + ' name: rxn_1', + ' equation: A1[s] => B2[c]', + ' genes: gene1 and gene2 or gene3', + ' - id: rxn_2b', + ' name: rxn_2', + ' equation: B2[c] => A1[s]', + ' genes: gene5 or gene6', + ' - id: rxn_3c', + ' name: rxn_3', + ' equation: A1[s] + (6) B2[c] <=> (6) A1[s] + (6) D4[c]', + ' genes: gene7', + 'compounds:', + ' - id: A1', + ' name: compound_A', + ' formula: C6H12O6', + ' charge: 1', + ' - id: B2', + ' name: compound_B', + ' formula: O2', + ' charge: 1', + ' kegg: C00010', + ' - id: C3', + ' name: compound_C', + ' formula: CO2', + ' charge: -1', + ' - id: D4', + ' name: compound_D', + ' formula: H2O', + 'exchange:', + ' - compartment: s', + ' - compounds:', + ' - id: A1', + ' upper: 100', + ' reaction: EX_A1(s)', + 'limits:', + ' - reaction: rxn_1a', + ' lower: -50', + ])) + self._newmodel = ModelReader.reader_from_path( + os.path.join(self._model_dir, 'newmodel.yaml')).create_model() + + with open(os.path.join(self._model_dir, 'compount_map.tsv'), 'w') as f: + f.write('\n'.join([ + 'id1\tid2\tp', + 'A\tA1\t1.0', + 'B\tB2\t0.9', + 'C\tA1\t0.001', + 'D\tD4\t0.32', + 'F\t\t', + ])) + + with open(os.path.join(self._model_dir, 'reaction_map.tsv'), 'w') as f: + f.write('\n'.join([ + 'id1\tid2\tp', + 'rxn_1\trxn_1a\t1.0', + 'rxn_2\trxn_1a\t0.9', + 'rxn_4\t\t', + 'rxn_3\trxn_3c\t0.32', + ])) + + with open( + os.path.join(self._model_dir, 'compartment_map.tsv'), + 'w') as f: + f.write('\n'.join([ + 'e\ts', + ])) + + self._compound_map = tr_id.read_mapping( + os.path.join(self._model_dir, 'compount_map.tsv')) + self._reaction_map = tr_id.read_mapping( + os.path.join(self._model_dir, 'reaction_map.tsv')) + self._compartment_map = tr_id.read_mapping( + os.path.join(self._model_dir, 'compartment_map.tsv')) + self._translated = tr_id.TranslatedModel( + self._model, self._compound_map, + self._reaction_map, self._compartment_map) + + def tearDown(self): + shutil.rmtree(self._model_dir) + + def test_instance(self): + self.assertIsInstance(self._translated, NativeModel) + self.assertIsInstance(self._translated, tr_id.TranslatedModel) + + def test_translate_compound(self): + for cpd in ['A', 'B', 'C', 'D', 'C3']: + self.assertNotIn(cpd, self._translated.compounds) + for cpd in ['A1', 'B2', 'D4']: + self.assertIn(cpd, self._translated.compounds) + + def test_translate_compartment(self): + self.assertIn('c', self._translated.compartments) + self.assertIn('s', self._translated.compartments) + self.assertNotIn('e', self._translated.compartments) + self.assertSetEqual( + self._translated._compartment_boundaries, set({('c', 's')})) + self.assertEqual(self._translated.extracellular_compartment, 's') + + def test_translate_reaction(self): + for rxn in ['rxn_1', 'rxn_2', 'rxn_3', 'rxn_2b']: + self.assertNotIn(rxn, self._translated.reactions) + for rxn in ['rxn_1a', 'rxn_3c']: + self.assertIn(rxn, self._translated.reactions) + self.assertEqual(self._translated.reactions[rxn].equation, + self._newmodel.reactions[rxn].equation) + + def test_translate_exchange(self): + self.assertDictEqual(self._translated.exchange, + self._newmodel.exchange) + + def test_translate_limits(self): + self.assertDictEqual(self._translated.limits, + self._newmodel.limits) + + def test_write_model(self): + self._translated.write_model( + os.path.join(self._model_dir, 'translated')) + + def test_no_compartment_change(self): + model = ModelReader.reader_from_path( + os.path.join(self._model_dir, 'model.yaml')).create_model() + translated = tr_id.TranslatedModel( + model, + self._translated.cpd_mapping_id, + self._translated.rxn_mapping_id) + self.assertEqual(translated.reactions['rxn_1a'].equation, + parse_reaction('A1[e] => B2[c]')) + self.assertEqual(translated.reactions['rxn_3c'].equation, + parse_reaction( + 'A1[e] + (6) B2[c] <=> (6) A1[e] + (6) D4[c]')) + self.assertIn('c', translated.compartments) + self.assertNotIn('s', translated.compartments) + self.assertIn('e', translated.compartments) + self.assertSetEqual( + translated._compartment_boundaries, set({('c', 'e')})) + self.assertEqual(translated.extracellular_compartment, 'e') +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_balancecheck.py",".py","4944","129","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2017 Jon Lund Steffensen +# Copyright 2016 Chao liu +# Copyright 2015-2020 Keith Dufault-Thompson + +import os +import unittest +import tempfile +import shutil +import math + +from psamm.formula import Formula +from psamm.datasource.native import ModelReader +from psamm import balancecheck +from psamm.datasource.reaction import parse_reaction + + +class TestBalanceCheckWithModel(unittest.TestCase): + def setUp(self): + self._model_dir = tempfile.mkdtemp() + with open(os.path.join(self._model_dir, 'model.yaml'), 'w') as f: + f.write('\n'.join([ + '---', + 'reactions:', + ' - id: rxn_1', + ' equation: A[e] => B[c]', + ' - id: rxn_2', + ' equation: B[c] => C[e]', + ' - id: rxn_3', + ' equation: A[e] + (6) B[c] <=> (6) C[e] + (6) D[c]', + 'compounds:', + ' - id: A', + ' formula: C6H12O6', + ' charge: 1', + ' - id: B', + ' formula: O2', + ' charge: 1', + ' - id: C', + ' formula: CO2', + ' charge: -1', + ' - id: D', + ' formula: H2O', + ])) + self._model = ModelReader.reader_from_path( + self._model_dir).create_model() + + def tearDown(self): + shutil.rmtree(self._model_dir) + + def test_charge_balance(self): + d = {reaction.id: value for reaction, value in + balancecheck.charge_balance(self._model)} + self.assertEqual(d['rxn_1'], 0) + self.assertEqual(d['rxn_2'], -2) + self.assertTrue(math.isnan(d['rxn_3'])) + + def test_formula_balance(self): + d = {reaction.id: value for reaction, value in + balancecheck.formula_balance(self._model)} + self.assertEqual(d['rxn_1'][0], Formula.parse('C6H12O6')) + self.assertEqual(d['rxn_1'][1], Formula.parse('O2')) + + self.assertEqual(d['rxn_2'][0], Formula.parse('O2')) + self.assertEqual(d['rxn_2'][1], Formula.parse('CO2')) + + self.assertEqual(d['rxn_3'][0], Formula.parse('C6H12O18')) + self.assertEqual(d['rxn_3'][1], Formula.parse('C6H12O18')) + + +class TestBalanceCheckWithReaction(unittest.TestCase): + def test_reaction_charge_zero_sum(self): + reaction = parse_reaction('A[e] + (6) B[c] <=> (6) C[e] + (6) D[c]') + compound_charge = {'A': 6, 'B': -1, 'C': 1, 'D': -1} + charge_sum = balancecheck.reaction_charge(reaction, compound_charge) + self.assertEqual(charge_sum, 0) + + def test_reaction_charge_non_zero_sum(self): + reaction = parse_reaction('A[e] + (6) B[c] <=> (6) C[e] + (6) D[c]') + compound_charge = {'A': 1, 'B': -1, 'C': 1, 'D': -1} + charge_sum = balancecheck.reaction_charge(reaction, compound_charge) + self.assertEqual(charge_sum, 5) + + def test_reaction_charge_nan_sum(self): + reaction = parse_reaction('A[e] + (6) B[c] <=> (6) C[e] + (6) D[c]') + compound_charge = {'A': 1, 'B': -1, 'C': 1} + charge_sum = balancecheck.reaction_charge(reaction, compound_charge) + self.assertTrue(math.isnan(charge_sum)) + + def test_reaction_formula_normal_return(self): + reaction = parse_reaction('A[e] + (6) B[c] <=> (6) C[e] + (6) D[c]') + compound_formula = { + 'A': Formula.parse('C6H12O6'), + 'B': Formula.parse('O2'), + 'C': Formula.parse('CO2'), + 'D': Formula.parse('H2O') + } + left_form, right_form = balancecheck.reaction_formula( + reaction, compound_formula) + self.assertEqual(left_form, Formula.parse('C6H12O18')) + self.assertEqual(right_form, Formula.parse('C6H12O18')) + + def test_reaction_formula_none_return(self): + reaction = parse_reaction('A[e] + (6) B[c] <=> (6) C[e] + (6) D[c]') + compound_formula = { + 'A': Formula.parse('C6H12O6'), + 'B': Formula.parse('O2'), + 'C': Formula.parse('CO2'), + } + result = balancecheck.reaction_formula(reaction, compound_formula) + self.assertIsNone(result) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_lpsolver_lp.py",".py","13156","391","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2015-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import math +import unittest + +from psamm.lpsolver import lp + +# Beware: Expressions cannot be tested for equality using normal +# assertEqual because the equality operator is overloaded! + + +class DummyRangedPropertyContainer(object): + def __init__(self): + self._property_rw = 5 + + @lp.ranged_property(min=-5, max=10) + def property_ro(self): + return 2.0 + + @lp.ranged_property(min=-50, max=17) + def property_rw(self): + return self._property_rw + + @property_rw.setter + def property_rw(self, value): + self._property_rw = value + + @property_rw.deleter + def property_rw(self): + self._property_rw = 0 + + +class TestRangedProperty(unittest.TestCase): + def setUp(self): + self.c = DummyRangedPropertyContainer() + + def test_read_property_ro(self): + self.assertEqual(self.c.property_ro.value, 2.0) + + def test_write_property_ro(self): + with self.assertRaises(AttributeError): + self.c.property_ro.value = 3.0 + + def test_write_property_base(self): + with self.assertRaises(AttributeError): + self.c.property_ro = 3.0 + + def test_delete_property_base(self): + with self.assertRaises(AttributeError): + del self.c.property_ro + + def test_delete_property_ro(self): + with self.assertRaises(AttributeError): + del self.c.property_ro.value + + def test_read_property_ro_bounds(self): + self.assertEqual(self.c.property_ro.min, -5) + self.assertEqual(self.c.property_ro.max, 10) + + def test_write_property_ro_bounds(self): + with self.assertRaises(AttributeError): + self.c.property_ro.min = -50 + with self.assertRaises(AttributeError): + self.c.property_ro.max = 100 + + def test_read_property_rw(self): + self.assertEqual(self.c.property_rw.value, 5) + + def test_write_property_rw(self): + self.c.property_rw.value = 10 + self.assertEqual(self.c.property_rw.value, 10) + + def test_delete_property_rw(self): + del self.c.property_rw.value + self.assertEqual(self.c.property_rw.value, 0) + + +class TestExpression(unittest.TestCase): + def test_create_expression(self): + e = lp.Expression() + self.assertEqual(e.offset, 0) + self.assertEqual(dict(e.values()), {}) + + def test_create_expression_with_offset(self): + e = lp.Expression(offset=42) + self.assertEqual(e.offset, 42) + self.assertEqual(dict(e.values()), {}) + + def test_create_expression_with_variables(self): + e = lp.Expression(variables={'x1': -5, 'x2': 100}) + self.assertEqual(e.offset, 0) + self.assertEqual(dict(e.values()), {'x1': -5, 'x2': 100}) + + def test_expression_variables(self): + e = lp.Expression(variables={'x1': -1, 'x2': 1}, offset=100) + self.assertEqual(set(e.variables()), {'x1', 'x2'}) + + def test_add_expression_and_number(self): + e = lp.Expression({'x1': -5}, 100) + e1 = e + 45 + self.assertEqual(e1.offset, 145) + self.assertEqual(dict(e1.values()), {'x1': -5}) + + def test_add_expression_and_expression(self): + e1 = lp.Expression({'x1': -5, 'x2': 42}, -1000) + e2 = lp.Expression({'x2': -42, 'x3': -50}, 2) + e3 = e1 + e2 + self.assertEqual(e3.offset, -998) + self.assertEqual(dict(e3.values()), {'x1': -5, 'x2': 0, 'x3': -50}) + + def test_add_expression_and_infinity(self): + e = lp.Expression({'x1': -5}, 100) + e1 = e + float('inf') + self.assertEqual(e1.offset, float('inf')) + + e2 = e - float('inf') + self.assertEqual(e2.offset, -float('inf')) + + def test_add_expression_and_infinity_expression(self): + e = lp.Expression({'x1': -5}, float('inf')) + e1 = e + lp.Expression({'x2': 4}, 100) + self.assertEqual(e1.offset, float('inf')) + + def test_add_expression_and_number_in_place(self): + e = lp.Expression({'x1': -5}, 100) + e += 45 + self.assertEqual(e.offset, 145) + self.assertEqual(dict(e.values()), {'x1': -5}) + + def test_add_expression_and_expression_in_place(self): + e1 = lp.Expression({'x1': -5, 'x2': 42}, -1000) + e2 = lp.Expression({'x2': -42, 'x3': -50}, 2) + e1 += e2 + + self.assertEqual(e1.offset, -998) + self.assertEqual(dict(e1.values()), {'x1': -5, 'x2': 0, 'x3': -50}) + + self.assertEqual(e2.offset, 2) + self.assertEqual(dict(e2.values()), {'x2': -42, 'x3': -50}) + + def test_add_expression_and_infinity_in_place(self): + e = lp.Expression({'x1': -5}, 100) + e += float('inf') + self.assertEqual(e.offset, float('inf')) + + def test_subtract_expressions_in_place(self): + e = lp.Expression({'x1': 40}, 22) + e -= lp.Expression({'x1': 5, 'x2': -20}, -2) + self.assertEqual(e.offset, 24) + self.assertEqual(dict(e.values()), {'x1': 35, 'x2': 20}) + + def test_multiply_expression_and_number(self): + e = lp.Expression({'x1': -5}, 100) + e1 = 2 * e + self.assertEqual(e1.offset, 200) + self.assertEqual(dict(e1.values()), {'x1': -10}) + + def test_multiply_expression_and_infinity(self): + e = lp.Expression({'x1': -5}) + e1 = float('-inf') * e + self.assertTrue(math.isnan(e1.offset)) + + def test_multiply_expression_and_number_in_place(self): + e = lp.Expression({'x1': -5}, 100) + e *= 2 + self.assertEqual(e.offset, 200) + self.assertEqual(dict(e.values()), {'x1': -10}) + + def test_multiply_expression_and_infinity_in_place(self): + e = lp.Expression({'x1': -5}) + e *= float('inf') + self.assertTrue(math.isnan(e.offset)) + + def test_multiply_expression_and_simple_expression(self): + e1 = lp.Expression({'x1': -5, 'x2': 3}, offset=10) + e2 = lp.Expression({'x1': 1}) + e = e1 * e2 + self.assertEqual(e.offset, 0) + self.assertEqual(dict(e.values()), { + lp.Product(['x1', 'x1']): -5, + lp.Product(['x1', 'x2']): 3, + 'x1': 10 + }) + + def test_multiply_expression_and_expression(self): + e1 = lp.Expression({'x1': 1, 'x2': 2, 'x3': 3}, offset=4) + e2 = lp.Expression({'x2': 4, 'x4': 5}, offset=-5) + e = e1 * e2 + self.assertEqual(e.offset, -20) + self.assertEqual(dict(e.values()), { + lp.Product(['x1', 'x2']): 4, + lp.Product(['x2', 'x2']): 8, + lp.Product(['x2', 'x3']): 12, + lp.Product(['x1', 'x4']): 5, + lp.Product(['x2', 'x4']): 10, + lp.Product(['x3', 'x4']): 15, + 'x1': -5, + 'x2': 6, + 'x3': -15, + 'x4': 20 + }) + + def test_multiply_expression_and_expression_in_place(self): + e = lp.Expression({'x1': -5, 'x2': 3}, offset=10) + e *= lp.Expression({'x1': 1}) + self.assertEqual(e.offset, 0) + self.assertEqual(dict(e.values()), { + lp.Product(['x1', 'x1']): -5, + lp.Product(['x1', 'x2']): 3, + 'x1': 10 + }) + + def test_expression_pow_negative(self): + e = lp.Expression({'x1': -5, 'x2': 3}, offset=10) + with self.assertRaises(ValueError): + e1 = e**-2 + + def test_expression_pow_neagtive_in_place(self): + e = lp.Expression({'x1': -5, 'x2': 3}, offset=10) + with self.assertRaises(ValueError): + e **= -2 + + def test_expression_pow_zero(self): + e = lp.Expression({'x1': -5, 'x2': 3}, offset=10) + e1 = e**0 + self.assertEqual(e1.offset, 1) + self.assertEqual(dict(e1.values()), {}) + + def test_expression_pow_zero_in_place(self): + e = lp.Expression({'x1': -5, 'x2': 3}, offset=10) + e **= 0 + self.assertEqual(e.offset, 1) + self.assertEqual(dict(e.values()), {}) + + def test_expression_pow_one(self): + e = lp.Expression({'x1': -5, 'x2': 3}, offset=10) + e1 = e**1 + self.assertEqual(e1.offset, e.offset) + self.assertEqual(dict(e1.values()), dict(e.values())) + + def test_expression_pow_one_in_place(self): + e = lp.Expression({'x1': -5, 'x2': 3}, offset=10) + e **= 1 + self.assertEqual(e.offset, 10) + self.assertEqual(dict(e.values()), {'x1': -5, 'x2': 3}) + + def test_expression_pow_two(self): + e = lp.Expression({'x1': -5, 'x2': 3}, offset=10) + e1 = e**2 + e2 = e*e + self.assertEqual(e1.offset, e2.offset) + self.assertEqual(dict(e1.values()), dict(e2.values())) + + def test_expression_pow_two_in_place(self): + e = lp.Expression({'x1': -5, 'x2': 3}, offset=10) + e **= 2 + self.assertEqual(e.offset, 100) + self.assertEqual(dict(e.values()), { + lp.Product(['x1', 'x1']): 25, + lp.Product(['x1', 'x2']): -30, + lp.Product(['x2', 'x2']): 9, + 'x1': -100, + 'x2': 60 + }) + + def test_negate_expression(self): + e = lp.Expression({'x1': 52}, -32) + e1 = -e + self.assertEqual(e1.offset, 32) + self.assertEqual(dict(e1.values()), {'x1': -52}) + + def test_expression_to_string(self): + e = lp.Expression({'x1': -4, 'x2': 100, 'x3': 1}, 42) + self.assertEqual(str(e), '-4*x1 + 100*x2 + x3 + 42') + + def test_expression_with_product_to_string(self): + e = lp.Expression({'x1': -4, lp.Product(['x1', 'x2']): 2}, 12) + self.assertEqual(str(e), '-4*x1 + 2*x1*x2 + 12') + + def test_expression_with_tuple_vars_to_string(self): + e = lp.Expression({('v', 1): 1}, -1) + self.assertEqual(str(e), ""('v', 1) - 1"") + + def test_expression_contains(self): + e = lp.Expression({'x1': 10, 'x2': -5}) + self.assertIn('x1', e) + self.assertNotIn('x3', e) + + def test_expression_contains_product(self): + e = lp.Expression({lp.Product(['x1', 'x1']): -1}) + self.assertIn(lp.Product(['x1', 'x1']), e) + self.assertNotIn('x1', e) + + +class TestRelation(unittest.TestCase): + def assertExpressionEqual(self, e1, e2): + """"""Assert that expressions are equal."""""" + self.assertEqual(e1.offset, e2.offset) + self.assertEqual(dict(e1.values()), dict(e2.values())) + + def test_create_relation(self): + e = lp.Expression({'x1': 4}) + r = lp.Relation(lp.RelationSense.Greater, e) + self.assertExpressionEqual(r.expression, e) + self.assertEqual(r.sense, lp.RelationSense.Greater) + + def test_relation_with_offset_to_string(self): + e = lp.Expression({'x1': 4}, -20) + r = lp.Relation(lp.RelationSense.Less, e) + self.assertEqual(str(r), '4*x1 <= 20') + + def test_relation_without_offset_to_string(self): + e = lp.Expression({'x1': 1}) + r = lp.Relation(lp.RelationSense.Equals, e) + self.assertEqual(str(r), 'x1 == 0') + + def test_chained_relation(self): + e = lp.Expression({'x1': 1}) + with self.assertRaises(ValueError): + self.assertFalse(4 <= e <= 10) + + +class MockResult(lp.Result): + def __init__(self, values): + self._values = dict(values) + + @property + def success(self): + return True + + @property + def status(self): + return 'Success' + + @property + def unbounded(self): + return False + + def _has_variable(self, var): + return var in self._values + + def _get_value(self, var): + return self._values[var] + + +class TestResult(unittest.TestCase): + def test_result_to_bool(self): + result = MockResult({'x': 3}) + self.assertTrue(bool(result)) + + def test_result_get_simple_value(self): + result = MockResult({'x': 3, 'y': 4}) + self.assertEqual(result.get_value('x'), 3) + self.assertEqual(result.get_value('y'), 4) + + def test_result_get_invalid_value(self): + result = MockResult({'x': 3}) + with self.assertRaises(ValueError): + y = result.get_value('y') + + def test_result_get_expression_value(self): + result = MockResult({'x': 3, 'y': 4}) + expr = lp.Expression({'x': 2, 'y': -6}, offset=3) + self.assertEqual(result.get_value(expr), -15) + + def test_result_get_expression_product_value(self): + result = MockResult({'x1': 2, 'x2': 3, 'x3': 4}) + expr = lp.Expression({lp.Product(['x1', 'x2']): 3, 'x3': -1}, offset=4) + self.assertEqual(result.get_value(expr), 18) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_tmfa.py",".py","31769","590","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen + +import unittest + +from psamm.metabolicmodel import MetabolicModel +from psamm.database import DictDatabase +from psamm.datasource.reaction import parse_reaction +from psamm.commands import tmfa +from psamm.lpsolver import generic +from decimal import Decimal +from psamm.lpsolver import lp + + +try: + test_solver = generic.Solver() + requires_solver = unittest.skipIf(test_solver._properties['name'] not in [ + 'cplex', 'gurobi'], 'Unable to find an LP solver for tests ' + '(TMFA requires Cplex or Gurobi as LP solver') +except generic.RequirementsError: + requires_solver = unittest.skip('Unable to find an LP solver for tests') + + +@requires_solver +class TestTMFA(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) A[c]')) + self.database.set_reaction('rxn_2', parse_reaction('A[c] <=> B[c]')) + self.database.set_reaction('rxn_3', parse_reaction('A[c] => D[e]')) + self.database.set_reaction('rxn_4', parse_reaction('A[c] => C[c]')) + self.database.set_reaction('rxn_5', parse_reaction('C[c] => D[e]')) + self.database.set_reaction('rxn_6', parse_reaction('D[e] =>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + self.mm_irreversible, _, self.split_reversible, \ + reversible_lump_to_rxn_dict = self.model.make_irreversible( + gene_dict={}, + lumped_rxns={}, + exclude_list=[], + all_reversible=False) + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + try: + self.solver = generic.Solver(integrality_tolerance=True) + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_mm_irrev(self): + mm_irreversible, _, split_reversible, new_lump_rxn_dict = \ + self.model.make_irreversible({}, [], {}, False) + self.assertTrue('rxn_2_forward' in [i for i in + mm_irreversible.reactions]) + self.assertTrue('rxn_2_reverse' in [i for i in + mm_irreversible.reactions]) + + def test_mm_irrev_exclude(self): + mm_irreversible, _, split_reversible, new_lump_rxn_dict = \ + self.model.make_irreversible({}, ['rxn_2'], {}, False) + self.assertTrue('rxn_2_forward' not in [i for i in + mm_irreversible.reactions]) + self.assertTrue('rxn_2_reverse' not in [i for i in + mm_irreversible.reactions]) + + def test_make_tmfa_problem_fluxvar(self): + prob, v, zi, dgri, xij, cp_list = tmfa.make_tmfa_problem( + self.mm_irreversible, self.solver) + self.assertTrue(v.has_variable('rxn_1')) + self.assertTrue(v.has_variable('rxn_2_forward')) + self.assertFalse(v.has_variable('rxn_2')) + + def test_make_tmfa_problem_dgrvar(self): + prob, v, zi, dgri, xij, cp_list = tmfa.make_tmfa_problem( + self.mm_irreversible, self.solver) + self.assertTrue(dgri.has_variable('rxn_1')) + self.assertTrue(dgri.has_variable('rxn_2_forward')) + self.assertFalse(dgri.has_variable('rxn_2')) + + def test_make_tmfa_problem_zivar(self): + prob, v, zi, dgri, xij, cp_list = tmfa.make_tmfa_problem( + self.mm_irreversible, self.solver) + self.assertTrue(zi.has_variable('rxn_1')) + self.assertTrue(zi.has_variable('rxn_2_forward')) + self.assertFalse(zi.has_variable('rxn_2')) + + def test_make_tmfa_problem_xijvar(self): + prob, v, zi, dgri, xij, cp_list = tmfa.make_tmfa_problem( + self.mm_irreversible, self.solver) + self.assertTrue(xij.has_variable('A[c]')) + self.assertTrue(xij.has_variable('B[c]')) + self.assertFalse(xij.has_variable('A[e]')) + self.assertFalse(xij.has_variable('D[c]')) + self.assertTrue(xij.has_variable('D[e]')) + self.assertFalse(xij.has_variable('rxn1')) + + def test_make_tmfa_problem_cplist(self): + prob, v, zi, dgri, xij, cp_list = tmfa.make_tmfa_problem( + self.mm_irreversible, self.solver) + self.assertEqual(set(cp_list), set(['A[c]', 'B[c]', 'C[c]', 'D[e]'])) + + def test_parsedgr(self): + f = ['rxn_1\t1\t2', 'rxn_2\t-4\t0.5'] + dgr_dict = tmfa.parse_dgr_file(f, self.mm_irreversible) + self.assertEqual(dgr_dict, {'rxn_1': (Decimal(1), Decimal(2)), + 'rxn_2_forward': (Decimal(-4), + Decimal(0.5)), + 'rxn_2_reverse': (Decimal(4), + Decimal(0.5))}) + + def test_parsedgrinvalid(self): + f = ['rxn_1\t1\t2', 'rxn_2\tNA\tNA'] + dgr_dict = tmfa.parse_dgr_file(f, self.mm_irreversible) + self.assertEqual(dgr_dict, {'rxn_1': (Decimal(1), Decimal(2))}) + + +@requires_solver +class TestSolving(unittest.TestCase): + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('EX_A', parse_reaction('<=> A[e]')) + self.database.set_reaction('EX_C', parse_reaction('<=> C[e]')) + self.database.set_reaction('EX_h2o', parse_reaction('<=> h2o[e]')) + self.database.set_reaction('EX_h', parse_reaction('<=> h[e]')) + self.database.set_reaction('rxn1', parse_reaction( + 'C[e] + h[e] <=> C[c] + h[c]')) + self.database.set_reaction('rxn2', parse_reaction( + 'A[e] + h[e] <=> A[c] + h[c]')) + self.database.set_reaction('rxn3', parse_reaction( + 'A[c] => B[c] + C[c]')) + self.database.set_reaction('rxn4', parse_reaction('B[c] => D[c]')) + self.database.set_reaction('rxn5', parse_reaction('D[c] => F[c]')) + self.database.set_reaction('rxn6', parse_reaction('B[c] => E[c]')) + self.database.set_reaction('rxn7', parse_reaction('E[c] => F[c]')) + self.database.set_reaction('rxn8', parse_reaction('h2o[e] <=> h2o[c]')) + self.database.set_reaction('bio', parse_reaction('F[c] =>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + try: + self.solver = generic.Solver(integrality_tolerance=True) + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + self.dgr_dict = {'rxn1_forward': (0, 2), 'rxn1_reverse': (0, 2), + 'rxn2_forward': (0, 2), 'rxn2_reverse': (0, 2), + 'rxn8_forward': (0, 2), 'rxn8_reverse': (0, 2), + 'rxn3': (-5, 2), 'rxn4': (-5, 2), + 'rxn5': (-5, 2), 'rxn6': (300, 2), 'rxn7': (300, 2)} + self.trans_param = {'rxn1_forward': (Decimal(1), Decimal(1)), + 'rxn1_reverse': (-Decimal(1), -Decimal(1)), + 'rxn2_forward': (Decimal(1), Decimal(1)), + 'rxn2_reverse': (-Decimal(1), -Decimal(1)), + 'rxn8_forward': (Decimal(0), Decimal(0)), + 'rxn8_reverse': (-Decimal(0), -Decimal(0))} + self.mm_irreversible, _, self.split_reversible, \ + self.reversible_lump_to_rxn_dict = \ + self.model.make_irreversible({}, + ['EX_A', 'EX_C', 'EX_h', + 'EX_h2o', 'bio'], {}, False) + + self.empty_prob, self.empty_v, self.empty_zi, self.empty_dgri, \ + self.empty_xij, self.empty_cp_list = tmfa.make_tmfa_problem( + self.mm_irreversible, self.solver) + self.prob, self.v, self.zi, self.dgri, self.xij, \ + self.cp_list = tmfa.make_tmfa_problem( + self.mm_irreversible, self.solver) + + self.prob, self.cpd_xij_dict = tmfa.add_conc_constraints( + self.xij, self.prob, {}, self.cp_list, ['h2o[c]', 'h2o[e]'], + 'h[c]', 'h[e]', '') + self.prob, self.excluded_compounds = \ + tmfa.add_reaction_constraints(self.prob, self.v, + self.zi, self.dgri, self.xij, + self.mm_irreversible, [], + ['EX_A', 'EX_C', 'EX_h', + 'EX_h2o', 'bio'], + ['EX_A', 'EX_C', 'EX_H', + 'EX_h2o', 'bio'], self.dgr_dict, + {}, self.split_reversible, + self.trans_param, + [i for i in + self.mm_irreversible.reactions], + None, ['h2o', 'h2o[e]'], 'h[c]', + 'h[e]', '', [(float(4), float(11)), + (float(4), float(11))], + 275, err_est=False, hamilton=False) + + self.ham_prob, self.ham_v, self.ham_zi, self.ham_dgri, \ + self.ham_xij, self.ham_cp_list = \ + tmfa.make_tmfa_problem(self.mm_irreversible, self.solver) + self.ham_prob, self.ham_cpd_xij_dict = tmfa.add_conc_constraints( + self.ham_xij, self.ham_prob, {}, self.cp_list, + ['h2o[c]', 'h2o[e]'], 'h[c]', 'h[e]', '') + self.ham_prob, self.ham_excluded_compounds = \ + tmfa.add_reaction_constraints(self.ham_prob, self.ham_v, + self.ham_zi, self.ham_dgri, + self.ham_xij, self.mm_irreversible, + [], ['EX_A', 'EX_C', 'EX_h', + 'EX_h2o', 'bio'], + ['EX_A', 'EX_C', 'EX_H', + 'EX_h2o', 'bio'], self.dgr_dict, + {}, self.split_reversible, + self.trans_param, + [i for i in + self.mm_irreversible.reactions], + None, ['h2o', 'h2o[e]'], 'h[c]', + 'h[e]', '', [(float(4), float(11)), + (float(4), float(11))], + 275, err_est=False, hamilton=True) + + self.err_prob, self.err_v, self.err_zi, self.err_dgri, self.err_xij, \ + self.err_cp_list = tmfa.make_tmfa_problem( + self.mm_irreversible, self.solver) + self.err_prob, self.err_cpd_xij_dict = \ + tmfa.add_conc_constraints(self.err_xij, self.err_prob, {}, + self.cp_list, ['h2o[c]', 'h2o[e]'], + 'h[c]', 'h[e]', '') + self.err_prob, self.err_excluded_compounds = \ + tmfa.add_reaction_constraints(self.err_prob, self.err_v, + self.err_zi, self.err_dgri, + self.err_xij, self.mm_irreversible, + [], ['EX_A', 'EX_C', 'EX_h', + 'EX_h2o', 'bio'], + ['EX_A', 'EX_C', 'EX_H', + 'EX_h2o', 'bio'], self.dgr_dict, + {}, self.split_reversible, + self.trans_param, + [i for i in + self.mm_irreversible.reactions], + None, ['h2o', 'h2o[e]'], 'h[c]', + 'h[e]', '', [(float(4), float(11)), + (float(4), float(11))], + 275, err_est=True, hamilton=False) + + def test_addconc_constraints_default(self): + prob, cpd_xij_dict = tmfa.add_conc_constraints(self.empty_xij, + self.empty_prob, {}, + self.empty_cp_list, + ['h2o[c]', 'h2o[e]'], + 'h[c]', 'h[e]', '') + prob, excluded_compounds = \ + tmfa.add_reaction_constraints(prob, self.empty_v, + self.empty_zi, self.empty_dgri, + self.empty_xij, + self.mm_irreversible, [], + ['EX_A', 'EX_C', 'EX_h', + 'EX_h2o', 'bio'], + ['EX_A', 'EX_C', 'EX_H', + 'EX_h2o', 'bio'], self.dgr_dict, + {}, self.split_reversible, + self.trans_param, + [i for i in + self.mm_irreversible.reactions], + None, ['h2o', 'h2o[e]'], 'h[c]', + 'h[e]', '', [(float(4), float(11)), + (float(4), float(11))], + 275, err_est=False, hamilton=False) + + cpd_range_dict = {} + for cpd in ['A[c]', 'B[c]', 'C[c]']: + cpd_range_dict[cpd] = \ + (tmfa.get_var_bound(prob, self.empty_xij[cpd], + lp.ObjectiveSense.Minimize), + tmfa.get_var_bound(prob, self.empty_xij[cpd], + lp.ObjectiveSense.Maximize)) + + self.assertAlmostEqual(cpd_range_dict['A[c]'][0], + (-11.512925026140119, + -3.912023005428146)[0], places=6) + self.assertAlmostEqual(cpd_range_dict['A[c]'][1], + (-11.512925026140119, + -3.912023005428146)[1], places=6) + self.assertAlmostEqual(cpd_range_dict['B[c]'][0], + (-11.512925026140119, + -3.912023005428146)[0], places=6) + self.assertAlmostEqual(cpd_range_dict['B[c]'][1], + (-11.512925026140119, + -3.912023005428146)[1], places=6) + self.assertAlmostEqual(cpd_range_dict['C[c]'][0], + (-11.512925026140119, + -3.912023005428146)[0], places=6) + self.assertAlmostEqual(cpd_range_dict['C[c]'][1], + (-11.512925026140119, + -3.912023005428146)[1], places=6) + + def test_addconc_constraints_nondefault(self): + prob, cpd_xij_dict = \ + tmfa.add_conc_constraints(self.empty_xij, + self.empty_prob, + {'A[c]': (0.005, 0.005), + 'B[c]': (0.0005, 0.005)}, + self.empty_cp_list, ['h2o[c]', 'h2o[e]'], + 'h[c]', 'h[e]', '') + prob, excluded_compounds = \ + tmfa.add_reaction_constraints(prob, + self.empty_v, self.empty_zi, + self.empty_dgri, self.empty_xij, + self.mm_irreversible, [], + ['EX_A', 'EX_C', 'EX_h', + 'EX_h2o', 'bio'], + ['EX_A', 'EX_C', 'EX_H', + 'EX_h2o', 'bio'], + self.dgr_dict, {}, + self.split_reversible, + self.trans_param, + [i for i in + self.mm_irreversible.reactions], + None, ['h2o', 'h2o[e]'], 'h[c]', + 'h[e]', '', [(float(4), float(11)), + (float(4), float(11))], + 275, err_est=False, hamilton=False) + + cpd_range_dict = {} + for cpd in ['A[c]', 'B[c]', 'C[c]']: + cpd_range_dict[cpd] = \ + (tmfa.get_var_bound(prob, self.empty_xij[cpd], + lp.ObjectiveSense.Minimize), + tmfa.get_var_bound(prob, self.empty_xij[cpd], + lp.ObjectiveSense.Maximize)) + + self.assertAlmostEqual(cpd_range_dict['A[c]'][0], + (-5.298317366548036, + -5.298317366548036)[0], places=6) + self.assertAlmostEqual(cpd_range_dict['A[c]'][1], + (-5.298317366548036, + -5.298317366548036)[1], places=6) + self.assertAlmostEqual(cpd_range_dict['B[c]'][0], + (-7.600902459542082, + -5.298317366548036)[0], places=6) + self.assertAlmostEqual(cpd_range_dict['B[c]'][1], + (-7.600902459542082, + -5.298317366548036)[1], places=6) + self.assertAlmostEqual(cpd_range_dict['C[c]'][0], + (-11.512925026140119, + -3.912023005428146)[0], places=6) + self.assertAlmostEqual(cpd_range_dict['C[c]'][1], + (-11.512925026140119, + -3.912023005428146)[1], places=6) + + def test_solvebiomass(self): + x = tmfa.get_var_bound(self.prob, self.v('bio'), + lp.ObjectiveSense.Maximize) + self.assertEqual(x, 1000) + + def test_rxnfluxes(self): + flux_dict = {} + x = tmfa.get_var_bound(self.prob, self.v('bio'), + lp.ObjectiveSense.Maximize) + self.prob.add_linear_constraints(self.v('bio') == x) + for i in [i for i in self.mm_irreversible.reactions]: + x = tmfa.get_var_bound(self.prob, self.v(i), + lp.ObjectiveSense.Maximize) + flux_dict[i] = x + self.assertTrue(flux_dict['bio'] == 1000) + self.assertTrue(flux_dict['rxn7'] == 0) + self.assertTrue(flux_dict['rxn1_forward'] == 0) + self.assertTrue(flux_dict['rxn4'] == 1000) + + def test_dgrrange(self): + dgr_dict = {} + x = tmfa.get_var_bound(self.prob, self.v('bio'), + lp.ObjectiveSense.Maximize) + self.prob.add_linear_constraints(self.v('bio') == x) + for reaction in ['rxn1_forward', 'rxn4', 'rxn6']: + dgr_dict[reaction] = \ + (tmfa.get_var_bound(self.prob, self.dgri(reaction), + lp.ObjectiveSense.Minimize), + tmfa.get_var_bound(self.prob, self.dgri(reaction), + lp.ObjectiveSense.Maximize)) + + self.assertAlmostEqual(dgr_dict['rxn1_forward'][0], + (9.999999974752427e-07, + 69.28332553115047)[0], places=6) + self.assertAlmostEqual(dgr_dict['rxn1_forward'][1], + (9.999999974752427e-07, + 69.28332553115047)[1], places=6) + self.assertAlmostEqual(dgr_dict['rxn4'][0], + (-39.64166326557521, + -9.999999903698154e-07)[0], places=6) + self.assertAlmostEqual(dgr_dict['rxn4'][1], + (-39.64166326557521, + -9.999999903698154e-07)[1], places=6) + self.assertAlmostEqual(dgr_dict['rxn6'][0], + (265.3583367344248, + 334.6416632655752)[0], places=6) + self.assertAlmostEqual(dgr_dict['rxn6'][1], + (265.3583367344248, + 334.6416632655752)[1], places=6) + + def test_cpd_range(self): + cpd_dict = {} + x = tmfa.get_var_bound(self.prob, self.v('bio'), + lp.ObjectiveSense.Maximize) + self.prob.add_linear_constraints(self.v('bio') == x) + for cpd in ['A[c]', 'A[e]', 'D[c]', 'E[c]']: + cpd_dict[cpd] = \ + (tmfa.get_var_bound(self.prob, self.xij(cpd), + lp.ObjectiveSense.Minimize), + tmfa.get_var_bound(self.prob, self.xij(cpd), + lp.ObjectiveSense.Maximize)) + self.assertAlmostEqual(cpd_dict['A[c]'][1], + (-11.512925464970229, + -3.912023005428146)[1], places=6) + self.assertAlmostEqual(cpd_dict['A[e]'][1], + (-11.512925464970229, + -3.912023005428146)[1], places=6) + self.assertAlmostEqual(cpd_dict['D[c]'][1], + (-11.512925464970229, + -3.912023005428146)[1], places=6) + + def test_constrainedconc(self): + cpd_dict = {} + self.prob.add_linear_constraints(self.xij('A[c]') == -10) + self.prob.add_linear_constraints(self.xij('B[c]') == -6) + x = tmfa.get_var_bound(self.prob, self.v('bio'), + lp.ObjectiveSense.Maximize) + self.prob.add_linear_constraints(self.v('bio') == x) + for cpd in ['A[c]', 'A[e]', 'D[c]', 'E[c]', 'B[c]']: + cpd_dict[cpd] = \ + (tmfa.get_var_bound(self.prob, self.xij(cpd), + lp.ObjectiveSense.Minimize), + tmfa.get_var_bound(self.prob, self.xij(cpd), + lp.ObjectiveSense.Maximize)) + dgr_dict = {} + x = tmfa.get_var_bound(self.prob, self.v('bio'), + lp.ObjectiveSense.Maximize) + self.prob.add_linear_constraints(self.v('bio') == x) + for reaction in ['rxn1_forward', 'rxn4', 'rxn6']: + dgr_dict[reaction] = \ + (tmfa.get_var_bound(self.prob, self.dgri(reaction), + lp.ObjectiveSense.Minimize), + tmfa.get_var_bound(self.prob, self.dgri(reaction), + lp.ObjectiveSense.Maximize)) + self.assertAlmostEqual(cpd_dict['D[c]'][1], + (-11.51292546497023, + -4.90292494313994)[1], places=6) + self.assertAlmostEqual(cpd_dict['A[c]'][1], + (-10.0, -10.0)[1], places=6) + self.assertAlmostEqual(cpd_dict['B[c]'][1], + (-6.0, -6.0)[1], places=6) + self.assertAlmostEqual(cpd_dict['E[c]'][1], + (-11.512925245555174, + -3.912023005428146)[1], places=6) + self.assertAlmostEqual(dgr_dict['rxn4'][1], + (-30.125556943039474, + -9.999999974752427e-07)[1], places=6) + + def test_reversibledgri(self): + dgr_dict = {} + x = tmfa.get_var_bound(self.prob, self.v('bio'), + lp.ObjectiveSense.Maximize) + self.prob.add_linear_constraints(self.v('bio') == x) + for reaction in ['rxn1_forward', 'rxn1_reverse', + 'rxn2_forward', 'rxn2_reverse']: + dgr_dict[reaction] = \ + (tmfa.get_var_bound(self.prob, self.dgri(reaction), + lp.ObjectiveSense.Minimize), + tmfa.get_var_bound(self.prob, self.dgri(reaction), + lp.ObjectiveSense.Maximize)) + + self.assertAlmostEqual(dgr_dict['rxn1_forward'][1], + (dgr_dict['rxn1_reverse'][0], + dgr_dict['rxn1_reverse'][1])[1], places=6) + self.assertAlmostEqual(dgr_dict['rxn2_forward'][1], + (dgr_dict['rxn2_reverse'][0], + dgr_dict['rxn2_reverse'][1])[1], places=6) + self.assertAlmostEqual(dgr_dict['rxn1_forward'][1], + (dgr_dict['rxn1_reverse'][0], + dgr_dict['rxn1_reverse'][1])[1], places=6) + self.assertAlmostEqual(dgr_dict['rxn2_forward'][1], + (dgr_dict['rxn2_reverse'][0], + dgr_dict['rxn2_reverse'][1])[1], places=6) + + def test_reversibleflux(self): + flux_dict = {} + x = tmfa.get_var_bound(self.prob, self.v('bio'), + lp.ObjectiveSense.Maximize) + self.prob.add_linear_constraints(self.v('bio') == x) + for reaction in ['rxn1_forward', 'rxn1_reverse', + 'rxn2_forward', 'rxn2_reverse']: + flux_dict[reaction] = \ + (tmfa.get_var_bound(self.prob, self.v(reaction), + lp.ObjectiveSense.Minimize), + tmfa.get_var_bound(self.prob, self.v(reaction), + lp.ObjectiveSense.Maximize)) + self.assertTrue(flux_dict['rxn1_forward'] == (0, 0)) + self.assertTrue(flux_dict['rxn1_reverse'] == (1000, 1000)) + self.assertTrue(flux_dict['rxn2_forward'] == (1000, 1000)) + self.assertTrue(flux_dict['rxn2_reverse'] == (0, 0)) + + def test_ham_flux(self): + flux_dict = {} + x = tmfa.get_var_bound(self.ham_prob, self.ham_v('bio'), + lp.ObjectiveSense.Maximize) + self.ham_prob.add_linear_constraints(self.ham_v('bio') == x) + for reaction in ['rxn1_forward', 'rxn2_forward', 'rxn2_reverse']: + flux_dict[reaction] = \ + (tmfa.get_var_bound(self.ham_prob, self.ham_v(reaction), + lp.ObjectiveSense.Minimize), + tmfa.get_var_bound(self.ham_prob, self.ham_v(reaction), + lp.ObjectiveSense.Maximize)) + self.assertTrue(flux_dict['rxn1_forward'] == (0, 0)) + self.assertTrue(flux_dict['rxn2_forward'] == (1000, 1000)) + self.assertTrue(flux_dict['rxn2_reverse'] == (0, 0)) + dgr_dict = {} + for reaction in ['rxn1_forward', 'rxn4', 'rxn6']: + dgr_dict[reaction] = \ + (tmfa.get_var_bound(self.ham_prob, self.ham_dgri(reaction), + lp.ObjectiveSense.Minimize), + tmfa.get_var_bound(self.ham_prob, self.ham_dgri(reaction), + lp.ObjectiveSense.Maximize)) + self.assertAlmostEqual(dgr_dict['rxn1_forward'][0], + (9.999999974752427e-07, + 69.28332553115047)[0], places=6) + self.assertAlmostEqual(dgr_dict['rxn1_forward'][1], + (9.999999974752427e-07, + 69.28332553115047)[1], places=6) + self.assertAlmostEqual(dgr_dict['rxn4'][0], + (-39.64166326557521, + -9.999999903698154e-07)[0], places=6) + self.assertAlmostEqual(dgr_dict['rxn4'][1], + (-39.64166326557521, + -9.999999903698154e-07)[1], places=6) + self.assertAlmostEqual(dgr_dict['rxn6'][0], + (265.3583377344248, 299.999999)[0], places=6) + self.assertAlmostEqual(dgr_dict['rxn6'][1], + (265.3583377344248, 299.999999)[1], places=6) + + def test_err_flux(self): + flux_dict = {} + x = tmfa.get_var_bound(self.err_prob, self.err_v('bio'), + lp.ObjectiveSense.Maximize) + self.err_prob.add_linear_constraints(self.err_v('bio') == x) + for reaction in ['rxn1_forward', 'rxn2_forward', 'rxn2_reverse']: + flux_dict[reaction] = \ + (tmfa.get_var_bound(self.err_prob, self.err_v(reaction), + lp.ObjectiveSense.Minimize), + tmfa.get_var_bound(self.err_prob, self.err_v(reaction), + lp.ObjectiveSense.Maximize)) + self.assertTrue(flux_dict['rxn1_forward'] == (0, 0)) + self.assertTrue(flux_dict['rxn2_forward'] == (1000, 1000)) + self.assertTrue(flux_dict['rxn2_reverse'] == (0, 0)) + dgr_dict = {} + for reaction in ['rxn1_forward', 'rxn4', 'rxn6']: + dgr_dict[reaction] = \ + (tmfa.get_var_bound(self.err_prob, self.err_dgri(reaction), + lp.ObjectiveSense.Minimize), + tmfa.get_var_bound(self.err_prob, self.err_dgri(reaction), + lp.ObjectiveSense.Maximize)) + self.assertAlmostEqual(dgr_dict['rxn1_forward'][0], + (-7.999998999999999, 77.28332553115047)[0], + places=6) + self.assertAlmostEqual(dgr_dict['rxn1_forward'][1], + (9.999999974752427e-07, 77.28332553115047)[1], + places=6) + self.assertAlmostEqual(dgr_dict['rxn4'][0], + (-43.64166326557521, -9.999999903698154e-07)[0], + places=6) + self.assertAlmostEqual(dgr_dict['rxn4'][1], + (-43.64166326557521, -9.999999903698154e-07)[1], + places=6) + self.assertAlmostEqual(dgr_dict['rxn6'][0], + (261.3583367344248, 338.6416632655752)[0], + places=6) + self.assertAlmostEqual(dgr_dict['rxn6'][1], + (261.3583367344248, 338.6416632655752)[1], + places=6) +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_formula.py",".py","11696","338","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.formula import Formula, FormulaElement, Atom, Radical, ParseError + + +class TestFormulaElement(unittest.TestCase): + def test_add_formula_elements(self): + e1 = FormulaElement() + e2 = FormulaElement() + self.assertEqual(e1 + e2, Formula({e1: 1, e2: 1})) + + def test_add_formula_element_to_self(self): + e1 = FormulaElement() + self.assertEqual(e1 + e1, Formula({e1: 2})) + + def test_add_formula_element_and_number(self): + with self.assertRaises(TypeError): + f = FormulaElement() + 42 + + def test_merge_formula_elements(self): + e1 = FormulaElement() + e2 = FormulaElement() + self.assertEqual(e1 | e2, Formula({e1: 1, e2: 1})) + + def test_merge_formula_element_to_self(self): + e1 = FormulaElement() + self.assertEqual(e1 | e1, Formula({e1: 2})) + + def test_substitute_into_formula_element(self): + e1 = FormulaElement() + self.assertEqual( + e1.substitute(lambda v: {'x': 42}.get(v.symbol, v)), e1) + + +class TestAtom(unittest.TestCase): + def test_atom_symbol(self): + a = Atom('H') + self.assertEqual(a.symbol, 'H') + + def test_atom_symbol_wide(self): + a = Atom('Zn') + self.assertEqual(a.symbol, 'Zn') + + def test_atom_symbol_non_standard(self): + a = Atom('X') + self.assertEqual(a.symbol, 'X') + + def test_atom_singleton_property(self): + a = Atom.C + self.assertEqual(a.symbol, 'C') + + def test_atom_to_string(self): + a = Atom('C') + self.assertEqual(str(a), 'C') + + def test_atom_repr(self): + a = Atom('Si') + self.assertEqual(repr(a), ""Atom('Si')"") + + def test_atom_equals(self): + a1 = Atom('H') + self.assertEqual(a1, Atom.H) + self.assertNotEqual(a1, Atom.Zn) + + def test_atom_ordered(self): + a1 = Atom('H') + a2 = Atom('C') + a3 = Atom('Zn') + self.assertGreater(a1, a2) + self.assertLess(a1, a3) + + +class TestFormula(unittest.TestCase): + def test_formula_merge_same_formulas_with_same_atoms(self): + f = Formula({Atom.H: 2, Atom.O: 1}) | Formula({Atom.N: 1, Atom.O: 2}) + self.assertEqual(f, Formula({Atom.H: 2, Atom.N: 1, Atom.O: 3})) + + def test_formula_merge_formulas_that_cancel_out(self): + f = Formula({Atom.H: 3}) | Formula({Atom.H: -3}) + self.assertEqual(f, Formula()) + + def test_formula_multiply_number(self): + f = Formula({Atom.H: 2, Atom.O: 1}) * 4 + self.assertEqual(f, Formula({Atom.H: 8, Atom.O: 4})) + + def test_formula_multiply_one(self): + f = Formula({Atom.H: 2, Atom.O: 1}) * 1 + self.assertEqual(f, f) + + def test_formula_multiply_zero(self): + f = Formula({Atom.H: 2, Atom.O: 1}) * 0 + self.assertEqual(f, Formula()) + + def test_formula_right_multiply_number(self): + f = 2 * Formula({Atom.H: 2, Atom.O: 1}) + self.assertEqual(f, Formula({Atom.H: 4, Atom.O: 2})) + + def test_formula_repeat(self): + f = Formula({Atom.H: 2, Atom.O: 1}).repeat(4) + self.assertEqual(f, Formula({Formula({Atom.H: 2, Atom.O: 1}): 4})) + + def test_formula_intersection(self): + f1 = Formula({Atom.H: 4, Atom.N: 1}) + f2 = Formula({Atom.H: 2, Atom.O: 1}) + f = f1 & f2 + self.assertEqual(f, Formula({Atom.H: 2})) + + def test_formula_intersection_with_atom(self): + f = Formula({Atom.H: 4, Atom.N: 1}) & Atom.H + self.assertEqual(f, Formula({Atom.H: 1})) + + def test_formula_subtraction(self): + f1 = Formula({Atom.H: 4, Atom.N: 1}) + f2 = Formula({Atom.H: 2, Atom.O: 1}) + f = f1 - f2 + self.assertEqual(f, Formula({Atom.H: 2, Atom.N: 1})) + + def test_formula_subtraction_with_atom(self): + f = Formula({Atom.H: 4, Atom.N: 1}) - Atom.H + self.assertEqual(f, Formula({Atom.H: 3, Atom.N: 1})) + + def test_formula_equals_other_formula(self): + f = Formula({Atom.H: 2, Atom.O: 1}) + self.assertEqual(f, Formula({Atom.O: 1, Atom.H: 2})) + + def test_formula_not_equals_other_with_distinct_elements(self): + f = Formula({Atom.Au: 1}) + self.assertNotEqual(f, Formula({Atom.Ag: 1})) + + def test_formula_not_equals_other_with_different_number(self): + f = Formula({Atom.Au: 1}) + self.assertNotEqual(f, Formula({Atom.Au: 2})) + + def test_formula_iter(self): + f = Formula({Atom.H: 12, Atom.C: 6, Atom.O: 6}) + self.assertEqual(set(iter(f)), {Atom.H, Atom.C, Atom.O}) + + def test_formula_items(self): + f = Formula({Atom.H: 12, Atom.C: 6, Atom.O: 6}) + self.assertEqual(dict(f.items()), { + Atom.C: 6, + Atom.H: 12, + Atom.O: 6 + }) + + def test_formula_contains(self): + f = Formula({Atom.H: 12, Atom.C: 6, Atom.O: 6}) + self.assertIn(Atom.C, f) + self.assertNotIn(Atom.Ag, f) + + def test_formula_get(self): + f = Formula({Atom.H: 12, Atom.C: 6, Atom.O: 6}) + self.assertEqual(f.get(Atom.H), 12) + self.assertEqual(f.get(Atom.Au), None) + self.assertEqual(f.get(Atom.Hg, 4), 4) + + def test_formula_getitem(self): + f = Formula({Atom.H: 12, Atom.C: 6, Atom.O: 6}) + self.assertEqual(f[Atom.H], 12) + + def test_formula_getitem_not_found(self): + f = Formula({Atom.H: 12, Atom.C: 6, Atom.O: 6}) + with self.assertRaises(KeyError): + f[Atom.Au] + + def test_formula_length(self): + f = Formula({Atom.H: 12, Atom.C: 6, Atom.O: 6}) + self.assertEqual(len(f), 3) + + def test_formula_to_string(self): + f = Formula({Atom.H: 12, Atom.C: 6, Atom.O: 6}) + self.assertEqual(str(f), 'C6H12O6') + + def test_formula_to_string_with_group(self): + f = Formula({ + Atom.C: 1, + Atom.H: 3, + Formula({Atom.C: 1, Atom.H: 2}): 14, + Formula({ + Atom.C: 1, Atom.O: 1, + Formula({Atom.H: 1, Atom.O: 1}): 1 + }): 1 + }) + # Ideally: self.assertEqual(str(f), 'CH3(CH2)14COOH') + # The two subgroups are unordered so we cannot assert a specfic string + # at this point. + + def test_formula_flattened(self): + f = Formula({ + Atom.C: 1, + Atom.H: 3, + Formula({Atom.C: 1, Atom.H: 2}): 14, + Formula({ + Atom.C: 1, Atom.O: 1, + Formula({Atom.H: 1, Atom.O: 1}): 1 + }): 1 + }) + self.assertEqual(f.flattened(), Formula({ + Atom.C: 16, + Atom.H: 32, + Atom.O: 2 + })) + + def test_formula_substitute_non_positive(self): + f = Formula.parse('CH3(CH2)nCOOH') + + with self.assertRaises(ValueError): + f.substitute(lambda v: {'n': -5}.get(v.symbol, v)) + + with self.assertRaises(ValueError): + f.substitute(lambda v: {'n': 0}.get(v.symbol, v)) + + def test_formula_is_not_variable(self): + f = Formula.parse('C6H12O6') + self.assertFalse(f.is_variable()) + + def test_formula_is_variable(self): + f = Formula.parse('C2H4NO2R(C2H2NOR)n') + self.assertTrue(f.is_variable()) + + def test_formula_balance_missing_on_one_side(self): + f1, f2 = Formula.balance(Formula.parse('H2O'), Formula.parse('OH')) + self.assertEqual(f1, Formula()) + self.assertEqual(f2, Formula({Atom.H: 1})) + + def test_formula_balance_missing_on_both_sides(self): + f1, f2 = Formula.balance( + Formula.parse('C3H6OH'), Formula.parse('CH6O2')) + self.assertEqual(f1, Formula({Atom.O: 1})) + self.assertEqual(f2, Formula({Atom.C: 2, Atom.H: 1})) + + def test_formula_balance_subgroups_cancel_out(self): + f1, f2 = Formula.balance( + Formula.parse('H2(CH2)n'), Formula.parse('CH3O(CH2)n')) + self.assertEqual(f1, Formula({Atom.C: 1, Atom.H: 1, Atom.O: 1})) + self.assertEqual(f2, Formula()) + + +class TestFormulaParser(unittest.TestCase): + def test_formula_parse_with_final_digit(self): + f = Formula.parse('H2O2') + self.assertEqual(f, Formula({Atom.H: 2, Atom.O: 2})) + + def test_formula_parse_with_implicit_final_digit(self): + f = Formula.parse('H2O') + self.assertEqual(f, Formula({Atom.H: 2, Atom.O: 1})) + + def test_formula_parse_with_implicit_digit(self): + f = Formula.parse('C2H5NO2') + self.assertEqual(f, Formula( + {Atom.C: 2, Atom.H: 5, Atom.N: 1, Atom.O: 2})) + + def test_formula_parse_with_wide_element(self): + f = Formula.parse('ZnO') + self.assertEqual(f, Formula({Atom.Zn: 1, Atom.O: 1})) + + def test_formula_parse_with_wide_count(self): + f = Formula.parse('C6H10O2') + self.assertEqual(f, Formula({Atom.C: 6, Atom.H: 10, Atom.O: 2})) + + def test_formula_parse_with_implicitly_counted_subgroup(self): + f = Formula.parse('C2H6O2(CH)') + self.assertEqual(f, Formula({ + Atom.C: 2, Atom.H: 6, Atom.O: 2, + Formula({Atom.C: 1, Atom.H: 1}): 1})) + + def test_formula_parse_with_counted_subgroup(self): + f = Formula.parse('C2H6O2(CH)2') + self.assertEqual(f, Formula({ + Atom.C: 2, Atom.H: 6, Atom.O: 2, + Formula({Atom.C: 1, Atom.H: 1}): 2})) + + def test_formula_parse_with_two_identical_counted_subgroups(self): + f = Formula.parse('C2H6O2(CH)2(CH)2') + self.assertEqual(f, Formula({ + Atom.C: 2, Atom.H: 6, Atom.O: 2, + Formula({Atom.C: 1, Atom.H: 1}): 4})) + + def test_formula_parse_with_two_distinct_counted_subgroups(self): + f = Formula.parse('C2H6O2(CH)2(CH2)2') + self.assertEqual(f, Formula({ + Atom.C: 2, Atom.H: 6, Atom.O: 2, + Formula({Atom.C: 1, Atom.H: 1}): 2, + Formula({Atom.C: 1, Atom.H: 2}): 2})) + + def test_formula_parse_with_wide_counted_subgroup(self): + f = Formula.parse('C2(CH)10NO2') + self.assertEqual(f, Formula({ + Atom.C: 2, Atom.N: 1, Atom.O: 2, + Formula({Atom.C: 1, Atom.H: 1}): 10})) + + def test_formula_parse_with_radical(self): + f = Formula.parse('C2H4NO2R') + self.assertEqual(f, Formula({ + Atom.C: 2, Atom.H: 4, Atom.N: 1, Atom.O: 2, Radical('R'): 1})) + + def test_formula_parse_with_numbered_radical(self): + f = Formula.parse('C2H4NO2(R1)') + self.assertEqual(f, Formula({ + Atom.C: 2, Atom.H: 4, Atom.N: 1, Atom.O: 2, Radical('R1'): 1})) + + def test_formula_parse_error(self): + with self.assertRaises(ParseError): + Formula.parse('H2O. ABC') + + +class TestFormulaParseError(unittest.TestCase): + def test_create_with_span(self): + e = ParseError('This is an error', span=(4, 7)) + self.assertEqual(e.indicator, ' ^^^') + + def test_create_without_span(self): + e = ParseError('This is an error') + self.assertIsNone(e.indicator) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_datasource_sbml.py",".py","47812","1166","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +from __future__ import unicode_literals + +import unittest + +from psamm.datasource import sbml, native, entry +from psamm.datasource.reaction import parse_reaction +from psamm.reaction import Reaction, Compound, Direction + +from decimal import Decimal +from fractions import Fraction +from six import BytesIO, itervalues + + +class TestSBMLDatabaseL1V2(unittest.TestCase): + """"""Test parsing of a simple level 1 version 2 SBML file"""""" + + def setUp(self): + self.doc = BytesIO(''' + + + + + + + + + + + + + + + + + + + + + + + + + Glucose 6-phosphatase + + + + + + + + + + + + + +'''.encode('utf-8')) + + def test_model_name(self): + reader = sbml.SBMLReader(self.doc) + self.assertEqual(reader.name, 'Test model') + + def test_compartment_exists(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + compartments = {entry.id: entry for entry in reader.compartments} + self.assertEqual(len(compartments), 2) + self.assertEqual(compartments['cell'].id, 'cell') + self.assertEqual(compartments['cell'].name, 'cell') + self.assertEqual(compartments['boundary'].id, 'boundary') + self.assertEqual(compartments['boundary'].name, 'boundary') + + def test_compartment_exists_with_ignore_boundary(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=True) + compartments = {entry.id: entry for entry in reader.compartments} + self.assertEqual(len(compartments), 1) + self.assertEqual(compartments['cell'].id, 'cell') + self.assertEqual(compartments['cell'].name, 'cell') + + def test_compounds_exist(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + species = {entry.id: entry for entry in reader.species} + self.assertEqual(len(species), 5) + + self.assertEqual(species['Glucose'].id, 'Glucose') + self.assertEqual(species['Glucose'].name, 'Glucose') + self.assertEqual(species['Glucose'].compartment, 'cell') + self.assertFalse(species['Glucose'].boundary) + self.assertEqual(species['Glucose'].charge, 0) + + self.assertEqual(species['Glucose_6_P'].id, 'Glucose_6_P') + self.assertEqual(species['Glucose_6_P'].name, 'Glucose_6_P') + self.assertEqual(species['Glucose_6_P'].compartment, 'cell') + self.assertFalse(species['Glucose_6_P'].boundary) + self.assertEqual(species['Glucose_6_P'].charge, -2) + + self.assertEqual(species['H2O'].id, 'H2O') + self.assertEqual(species['H2O'].name, 'H2O') + self.assertEqual(species['H2O'].compartment, 'cell') + self.assertFalse(species['H2O'].boundary) + self.assertEqual(species['H2O'].charge, 0) + + self.assertFalse(species['Phosphate'].boundary) + self.assertTrue(species['Biomass'].boundary) + + def test_g6pase_reaction_exists(self): + reader = sbml.SBMLReader(self.doc) + reaction = reader.get_reaction('G6Pase') + self.assertTrue(reaction.reversible) + + # Compare equation of reaction + actual_equation = Reaction(Direction.Both, + [(Compound('Glucose', 'cell'), 2), + (Compound('Phosphate', 'cell'), 2)], + [(Compound('H2O', 'cell'), 2), + (Compound('Glucose_6_P', 'cell'), 2)]) + self.assertEqual(reaction.equation, actual_equation) + + def test_biomass_reaction_exists(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + reaction = reader.get_reaction('Biomass') + self.assertFalse(reaction.reversible) + + # Compare equation of reaction + actual_equation = Reaction(Direction.Forward, [ + (Compound('Glucose_6_P', 'cell'), Fraction(56, 100)), + (Compound('Glucose', 'cell'), Fraction(88, 100)) + ], [ + (Compound('Biomass', 'boundary'), 1) + ]) + self.assertEqual(reaction.equation, actual_equation) + + def test_reaction_xml_notes(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + reaction = reader.get_reaction('G6Pase') + notes = reaction.xml_notes + + notes_tags = list(notes) + self.assertEqual(len(notes_tags), 1) + self.assertEqual(notes_tags[0].tag, '{http://www.w3.org/1999/xhtml}p') + self.assertEqual(notes_tags[0].text, 'Glucose 6-phosphatase') + + def test_objective_not_present(self): + reader = sbml.SBMLReader(self.doc) + objectives = list(reader.objectives) + self.assertEqual(len(objectives), 0) + self.assertIsNone(reader.get_active_objective()) + + def test_flux_bounds_not_present(self): + reader = sbml.SBMLReader(self.doc) + flux_bounds = list(reader.flux_bounds) + self.assertEqual(len(flux_bounds), 0) + + def test_create_and_convert_model(self): + reader = sbml.SBMLReader(self.doc) + model = reader.create_model() + sbml.convert_sbml_model(model) + + self.assertEqual( + {entry.id for entry in model.compounds}, + {'Glucose', 'Glucose_6_P', 'H2O', 'Phosphate'}) + self.assertEqual( + {entry.id for entry in model.reactions}, + {'G6Pase', 'Biomass'}) + self.assertEqual( + {entry.id for entry in model.compartments}, + {'cell'}) + + self.assertEqual(set(model.model), {'Biomass', 'G6Pase'}) + + +class TestSBMLDatabaseL2V5(unittest.TestCase): + """"""Test parsing of a simple level 2 version 5 SBML file"""""" + + def setUp(self): + self.doc = BytesIO(''' + + + + + + + + + + +

    FORMULA: C6H12O6

    +

    Charge: ""0""

    +

    Additional notes..

    +

    KEGG ID: C00031

    +

    Custom: 123

    + +
    +
    + + + + +
    + + + + + + + + + + + + +

    Authors: Jane Doe ; John Doe

    +

    CONFIDENCE: 3

    +

    EC NUMBER: 3.1.3.9

    +

    gene association : b0822

    +

    SUBSYSTEM: ""Glycolysis / Gluconeogenesis""

    +

    Additional notes...

    + +
    +
    + + + + + + + + + + + + + + + + + +
    +
    +
    '''.encode('utf-8')) + + def test_model_name(self): + reader = sbml.SBMLReader(self.doc) + self.assertEqual(reader.id, 'test_model') + self.assertEqual(reader.name, 'Test model') + + def test_compartment_exists(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + compartments = {entry.id: entry for entry in reader.compartments} + self.assertEqual(len(compartments), 2) + self.assertEqual(compartments['C_c'].id, 'C_c') + self.assertEqual(compartments['C_c'].name, 'cell') + self.assertEqual(compartments['C_b'].id, 'C_b') + self.assertEqual(compartments['C_b'].name, 'boundary') + + def test_compartment_exists_with_ignore_boundary(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=True) + compartments = {entry.id: entry for entry in reader.compartments} + self.assertEqual(len(compartments), 1) + self.assertEqual(compartments['C_c'].id, 'C_c') + self.assertEqual(compartments['C_c'].name, 'cell') + + def test_compounds_exist(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + species = {entry.id: entry for entry in reader.species} + self.assertEqual(len(species), 5) + + gluc_species = species['M_Glucose_LPAREN_c_RPAREN_'] + self.assertEqual(gluc_species.id, 'M_Glucose_LPAREN_c_RPAREN_') + self.assertEqual(gluc_species.name, 'Glucose') + self.assertEqual(gluc_species.compartment, 'C_c') + self.assertFalse(gluc_species.boundary) + self.assertEqual(gluc_species.charge, 0) + + g6p_species = species['M_Glucose_6_DASH_P_LPAREN_c_RPAREN_'] + self.assertEqual(g6p_species.id, 'M_Glucose_6_DASH_P_LPAREN_c_RPAREN_') + self.assertEqual(g6p_species.name, 'Glucose-6-P') + self.assertEqual(g6p_species.compartment, 'C_c') + self.assertFalse(g6p_species.boundary) + self.assertEqual(g6p_species.charge, -2) + + h2o_species = species['M_H2O_LPAREN_c_RPAREN_'] + self.assertEqual(h2o_species.id, 'M_H2O_LPAREN_c_RPAREN_') + self.assertEqual(h2o_species.name, 'H2O') + self.assertEqual(h2o_species.compartment, 'C_c') + self.assertFalse(h2o_species.boundary) + self.assertEqual(h2o_species.charge, 0) + + self.assertFalse(species['M_Phosphate_LPAREN_c_RPAREN_'].boundary) + self.assertTrue(species['M_Biomass'].boundary) + + def test_glucose_parse_notes(self): + reader = sbml.SBMLReader(self.doc) + species = reader.get_species('M_Glucose_LPAREN_c_RPAREN_') + notes_dict = sbml.parse_xhtml_species_notes(species) + self.assertEqual(notes_dict, { + 'formula': 'C6H12O6', + 'kegg': 'C00031', + 'charge': 0 + }) + + def test_g6pase_reaction_exists(self): + reader = sbml.SBMLReader(self.doc) + reaction = reader.get_reaction('R_G6Pase') + self.assertTrue(reaction.reversible) + + # Compare equation of reaction + actual_equation = Reaction(Direction.Both, [ + (Compound('M_Glucose_LPAREN_c_RPAREN_', 'C_c'), 2), + (Compound('M_Phosphate_LPAREN_c_RPAREN_', 'C_c'), 2) + ], [ + (Compound('M_H2O_LPAREN_c_RPAREN_', 'C_c'), 2), + (Compound('M_Glucose_6_DASH_P_LPAREN_c_RPAREN_', 'C_c'), 2) + ]) + self.assertEqual(reaction.equation, actual_equation) + + def test_g6pase_parse_notes(self): + reader = sbml.SBMLReader(self.doc) + reaction = reader.get_reaction('R_G6Pase') + notes = sbml.parse_xhtml_reaction_notes(reaction) + self.assertEqual(notes, { + 'subsystem': 'Glycolysis / Gluconeogenesis', + 'genes': 'b0822', + 'ec': '3.1.3.9', + 'confidence': 3, + 'authors': ['Jane Doe', 'John Doe'] + }) + + def test_parse_reaction_cobra_flux_bounds(self): + reader = sbml.SBMLReader(self.doc) + reaction = reader.get_reaction('R_G6Pase') + lower, upper = sbml.parse_flux_bounds(reaction) + self.assertIsNone(lower) + self.assertIsNone(upper) + + reaction = reader.get_reaction('R_Biomass') + lower, upper = sbml.parse_flux_bounds(reaction) + self.assertEqual(lower, 0) + self.assertEqual(upper, 1000) + + def test_parse_reaction_cobra_objective(self): + reader = sbml.SBMLReader(self.doc) + reaction = reader.get_reaction('R_G6Pase') + coeff = sbml.parse_objective_coefficient(reaction) + self.assertIsNone(coeff) + + reaction = reader.get_reaction('R_Biomass') + coeff = sbml.parse_objective_coefficient(reaction) + self.assertEqual(coeff, 1) + + def test_biomass_reaction_exists(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + reaction = reader.get_reaction('R_Biomass') + self.assertFalse(reaction.reversible) + + # Compare equation of reaction + actual_equation = Reaction(Direction.Forward, [ + (Compound('M_Glucose_6_DASH_P_LPAREN_c_RPAREN_', 'C_c'), + Decimal('0.56')), + (Compound('M_Glucose_LPAREN_c_RPAREN_', 'C_c'), Decimal('0.88')) + ], [ + (Compound('M_Biomass', 'C_b'), 1) + ]) + self.assertEqual(reaction.equation, actual_equation) + + def test_objective_not_present(self): + reader = sbml.SBMLReader(self.doc) + objectives = list(reader.objectives) + self.assertEqual(len(objectives), 0) + self.assertIsNone(reader.get_active_objective()) + + def test_flux_bounds_not_present(self): + reader = sbml.SBMLReader(self.doc) + flux_bounds = list(reader.flux_bounds) + self.assertEqual(len(flux_bounds), 0) + + def test_create_and_convert_model(self): + reader = sbml.SBMLReader(self.doc) + model = reader.create_model() + sbml.convert_sbml_model(model) + + self.assertEqual( + {entry.id for entry in model.compounds}, + {'Glucose(c)', 'Glucose_6-P(c)', 'H2O(c)', 'Phosphate(c)'}) + self.assertEqual( + {entry.id for entry in model.reactions}, + {'G6Pase', 'Biomass'}) + self.assertEqual( + {entry.id for entry in model.compartments}, + {'c'}) + + self.assertEqual(model.limits['Biomass'], ('Biomass', 0, 1000)) + self.assertEqual(model.biomass_reaction, 'Biomass') + self.assertEqual(set(model.model), {'Biomass', 'G6Pase'}) + + +class TestSBMLDatabaseL3V1(unittest.TestCase): + """"""Test parsing of a simple level 3 version 1 SBML file"""""" + + def setUp(self): + self.doc = BytesIO(''' + + + + + + + + + + + + + + + + + + + + + + + + + Glucose 6-phosphatase + + + + + + + + + + + + + +'''.encode('utf-8')) + + def test_model_name(self): + reader = sbml.SBMLReader(self.doc) + self.assertEqual(reader.id, 'test_model') + self.assertEqual(reader.name, 'Test model') + + def test_compartment_exists(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + compartments = {entry.id: entry for entry in reader.compartments} + self.assertEqual(len(compartments), 2) + self.assertEqual(compartments['C_c'].id, 'C_c') + self.assertEqual(compartments['C_c'].name, 'cell') + self.assertEqual(compartments['C_b'].id, 'C_b') + self.assertEqual(compartments['C_b'].name, 'boundary') + + def test_compartment_exists_with_ignore_boundary(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=True) + compartments = {entry.id: entry for entry in reader.compartments} + self.assertEqual(len(compartments), 1) + self.assertEqual(compartments['C_c'].id, 'C_c') + self.assertEqual(compartments['C_c'].name, 'cell') + + def test_compounds_exist(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + species = {entry.id: entry for entry in reader.species} + self.assertEqual(len(species), 5) + + gluc_species = species['M_Glucose_LPAREN_c_RPAREN_'] + self.assertEqual(gluc_species.id, 'M_Glucose_LPAREN_c_RPAREN_') + self.assertEqual(gluc_species.name, 'Glucose') + self.assertEqual(gluc_species.compartment, 'C_c') + self.assertFalse(gluc_species.boundary) + + g6p_species = species['M_Glucose_6_DASH_P_LPAREN_c_RPAREN_'] + self.assertEqual(g6p_species.id, 'M_Glucose_6_DASH_P_LPAREN_c_RPAREN_') + self.assertEqual(g6p_species.name, 'Glucose-6-P') + self.assertEqual(g6p_species.compartment, 'C_c') + self.assertFalse(g6p_species.boundary) + + h2o_species = species['M_H2O_LPAREN_c_RPAREN_'] + self.assertEqual(h2o_species.id, 'M_H2O_LPAREN_c_RPAREN_') + self.assertEqual(h2o_species.name, 'H2O') + self.assertEqual(h2o_species.compartment, 'C_c') + self.assertFalse(h2o_species.boundary) + + self.assertFalse(species['M_Phosphate_LPAREN_c_RPAREN_'].boundary) + self.assertTrue(species['M_Biomass'].boundary) + + def test_g6pase_reaction_exists(self): + reader = sbml.SBMLReader(self.doc) + reaction = reader.get_reaction('R_G6Pase') + self.assertTrue(reaction.reversible) + + # Compare equation of reaction + actual_equation = Reaction(Direction.Both, [ + (Compound('M_Glucose_LPAREN_c_RPAREN_', 'C_c'), 2), + (Compound('M_Phosphate_LPAREN_c_RPAREN_', 'C_c'), 2) + ], [ + (Compound('M_H2O_LPAREN_c_RPAREN_', 'C_c'), 2), + (Compound('M_Glucose_6_DASH_P_LPAREN_c_RPAREN_', 'C_c'), 2) + ]) + self.assertEqual(reaction.equation, actual_equation) + + def test_biomass_reaction_exists(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + reaction = reader.get_reaction('R_Biomass') + self.assertFalse(reaction.reversible) + + # Compare equation of reaction + actual_equation = Reaction(Direction.Forward, [ + (Compound('M_Glucose_6_DASH_P_LPAREN_c_RPAREN_', 'C_c'), + Decimal('0.56')), + (Compound('M_Glucose_LPAREN_c_RPAREN_', 'C_c'), Decimal('0.88')) + ], [ + (Compound('M_Biomass', 'C_b'), 1) + ]) + self.assertEqual(reaction.equation, actual_equation) + + def test_reaction_xml_notes(self): + reader = sbml.SBMLReader(self.doc) + reaction = reader.get_reaction('R_G6Pase') + notes = reaction.xml_notes + + notes_tags = list(notes) + self.assertEqual(len(notes_tags), 1) + self.assertEqual(notes_tags[0].tag, '{http://www.w3.org/1999/xhtml}p') + self.assertEqual(notes_tags[0].text, 'Glucose 6-phosphatase') + + def test_objective_not_present(self): + reader = sbml.SBMLReader(self.doc) + objectives = list(reader.objectives) + self.assertEqual(len(objectives), 0) + self.assertIsNone(reader.get_active_objective()) + + def test_flux_bounds_not_present(self): + reader = sbml.SBMLReader(self.doc) + flux_bounds = list(reader.flux_bounds) + self.assertEqual(len(flux_bounds), 0) + + def test_create_and_convert_model(self): + reader = sbml.SBMLReader(self.doc) + model = reader.create_model() + sbml.convert_sbml_model(model) + + self.assertEqual( + {entry.id for entry in model.compounds}, + {'Glucose(c)', 'Glucose_6-P(c)', 'H2O(c)', 'Phosphate(c)'}) + self.assertEqual( + {entry.id for entry in model.reactions}, + {'G6Pase', 'Biomass'}) + self.assertEqual( + {entry.id for entry in model.compartments}, + {'c'}) + + self.assertEqual(set(model.model), {'Biomass', 'G6Pase'}) + + +class TestSBMLDatabaseL3V1WithFBCV1(unittest.TestCase): + """"""Test parsing of a level 3 version 1 SBML file with FBC version 1"""""" + + def setUp(self): + self.doc = BytesIO(''' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +'''.encode('utf-8')) + + def test_model_name(self): + reader = sbml.SBMLReader(self.doc) + self.assertEqual(reader.id, 'test_model') + self.assertEqual(reader.name, 'Test model') + + def test_compartment_exists(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + compartments = {entry.id: entry for entry in reader.compartments} + self.assertEqual(len(compartments), 2) + self.assertEqual(compartments['C_c'].id, 'C_c') + self.assertEqual(compartments['C_c'].name, 'cell') + self.assertEqual(compartments['C_b'].id, 'C_b') + self.assertEqual(compartments['C_b'].name, 'boundary') + + def test_compounds_exist(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + species = {entry.id: entry for entry in reader.species} + self.assertEqual(len(species), 5) + + gluc_species = species['M_Glucose_LPAREN_c_RPAREN_'] + self.assertEqual(gluc_species.id, 'M_Glucose_LPAREN_c_RPAREN_') + self.assertEqual(gluc_species.name, 'Glucose') + self.assertEqual(gluc_species.compartment, 'C_c') + self.assertFalse(gluc_species.boundary) + self.assertEqual(gluc_species.formula, 'C6H12O6') + self.assertEqual(gluc_species.charge, 0) + + g6p_species = species['M_Glucose_6_DASH_P_LPAREN_c_RPAREN_'] + self.assertEqual(g6p_species.id, 'M_Glucose_6_DASH_P_LPAREN_c_RPAREN_') + self.assertEqual(g6p_species.name, 'Glucose-6-P') + self.assertEqual(g6p_species.compartment, 'C_c') + self.assertFalse(g6p_species.boundary) + self.assertEqual(g6p_species.formula, 'C6H11O9P') + self.assertEqual(g6p_species.charge, -2) + + h2o_species = species['M_H2O_LPAREN_c_RPAREN_'] + self.assertEqual(h2o_species.id, 'M_H2O_LPAREN_c_RPAREN_') + self.assertEqual(h2o_species.name, 'H2O') + self.assertEqual(h2o_species.compartment, 'C_c') + self.assertFalse(h2o_species.boundary) + self.assertEqual(h2o_species.formula, 'H2O') + self.assertEqual(h2o_species.charge, 0) + + self.assertFalse(species['M_Phosphate_LPAREN_c_RPAREN_'].boundary) + self.assertTrue(species['M_Biomass'].boundary) + + self.assertIsNone(species['M_Biomass'].formula) + self.assertIsNone(species['M_Biomass'].charge) + + def test_g6pase_reaction_exists(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + reaction = reader.get_reaction('R_G6Pase') + self.assertTrue(reaction.reversible) + + # Compare equation of reaction + actual_equation = Reaction(Direction.Both, [ + (Compound('M_Glucose_LPAREN_c_RPAREN_', 'C_c'), 2), + (Compound('M_Phosphate_LPAREN_c_RPAREN_', 'C_c'), 2) + ], [ + (Compound('M_H2O_LPAREN_c_RPAREN_', 'C_c'), 2), + (Compound('M_Glucose_6_DASH_P_LPAREN_c_RPAREN_', 'C_c'), 2) + ]) + self.assertEqual(reaction.equation, actual_equation) + + self.assertEqual(reaction.properties['lower_flux'], -10) + self.assertEqual(reaction.properties['upper_flux'], 1000) + + def test_biomass_reaction_exists(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + reaction = reader.get_reaction('R_Biomass') + self.assertFalse(reaction.reversible) + + # Compare equation of reaction + actual_equation = Reaction(Direction.Forward, [ + (Compound('M_Glucose_6_DASH_P_LPAREN_c_RPAREN_', 'C_c'), + Decimal('0.56')), + (Compound('M_Glucose_LPAREN_c_RPAREN_', 'C_c'), Decimal('0.88')) + ], [ + (Compound('M_Biomass', 'C_b'), 1) + ]) + self.assertEqual(reaction.equation, actual_equation) + + self.assertEqual(reaction.properties['lower_flux'], 0) + self.assertEqual(reaction.properties['upper_flux'], 1000) + + def test_objective_exists(self): + reader = sbml.SBMLReader(self.doc) + objectives = {entry.id: entry for entry in reader.objectives} + self.assertEqual(len(objectives), 1) + + objective = objectives['obj1'] + self.assertEqual(objective.name, 'Objective 1') + self.assertEqual(objective.type, 'maximize') + self.assertEqual(dict(objective.reactions), {'R_Biomass': 1}) + + def test_active_objective(self): + reader = sbml.SBMLReader(self.doc) + objectives = {entry.id: entry for entry in reader.objectives} + self.assertEqual(reader.get_active_objective(), objectives['obj1']) + + def test_flux_bounds_exists(self): + reader = sbml.SBMLReader(self.doc) + flux_bounds = list(reader.flux_bounds) + self.assertEqual(len(flux_bounds), 4) + + biomass_bounds = set( + (b.operation, b.value) for b in flux_bounds + if b.reaction == 'R_Biomass') + self.assertEqual(biomass_bounds, { + ('greaterEqual', 0), + ('lessEqual', 1000)}) + + g6pase_bounds = set( + (b.operation, b.value) for b in flux_bounds + if b.reaction == 'R_G6Pase') + self.assertEqual(g6pase_bounds, { + ('greaterEqual', -10), + ('lessEqual', 1000)}) + + def test_create_and_convert_model(self): + reader = sbml.SBMLReader(self.doc) + model = reader.create_model() + sbml.convert_sbml_model(model) + + self.assertEqual( + {entry.id for entry in model.compounds}, + {'Glucose(c)', 'Glucose_6-P(c)', 'H2O(c)', 'Phosphate(c)'}) + self.assertEqual( + {entry.id for entry in model.reactions}, + {'G6Pase', 'Biomass'}) + self.assertEqual( + {entry.id for entry in model.compartments}, + {'c'}) + + self.assertEqual(model.limits['Biomass'], ('Biomass', 0, 1000)) + self.assertEqual(model.limits['G6Pase'], ('G6Pase', -10, 1000)) + self.assertEqual(set(model.model), {'Biomass', 'G6Pase'}) + self.assertEqual(model.biomass_reaction, 'Biomass') + + +class TestSBMLDatabaseL3V1WithFBCV2(unittest.TestCase): + """"""Test parsing of a level 3 version 1 SBML file with FBC version 2"""""" + + def setUp(self): + self.doc = BytesIO(''' + + + + +

    This is model information intended to be seen by humans.

    + +
    + + + + + + + + +

    This is compound information intended to be seen by humans.

    + +
    +
    + + + + +
    + + + + + + + + + + + + + + + + + +

    This is reaction information intended to be seen by humans.

    + +
    + + + + + +
  • + + + + + + + + + + + + + + + + + + + + + + + + +'''.encode('utf-8')) + + def test_model_name(self): + reader = sbml.SBMLReader(self.doc) + self.assertEqual(reader.id, 'test_model') + self.assertEqual(reader.name, 'Test model') + + def test_compartment_exists(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + compartments = {entry.id: entry for entry in reader.compartments} + self.assertEqual(len(compartments), 2) + self.assertEqual(compartments['C_c'].id, 'C_c') + self.assertEqual(compartments['C_c'].name, 'cell') + self.assertEqual(compartments['C_b'].id, 'C_b') + self.assertEqual(compartments['C_b'].name, 'boundary') + + def test_compounds_exist(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + species = {entry.id: entry for entry in reader.species} + self.assertEqual(len(species), 5) + + gluc_species = species['M_Glucose_LPAREN_c_RPAREN_'] + self.assertEqual(gluc_species.id, 'M_Glucose_LPAREN_c_RPAREN_') + self.assertEqual(gluc_species.name, 'Glucose') + self.assertEqual(gluc_species.compartment, 'C_c') + self.assertFalse(gluc_species.boundary) + self.assertEqual(gluc_species.formula, 'C6H12O6') + self.assertEqual(gluc_species.charge, 0) + self.assertIsNotNone(gluc_species.xml_notes) + + g6p_species = species['M_Glucose_6_DASH_P_LPAREN_c_RPAREN_'] + self.assertEqual(g6p_species.id, 'M_Glucose_6_DASH_P_LPAREN_c_RPAREN_') + self.assertEqual(g6p_species.name, 'Glucose-6-P') + self.assertEqual(g6p_species.compartment, 'C_c') + self.assertFalse(g6p_species.boundary) + self.assertEqual(g6p_species.formula, 'C6H11O9P') + self.assertEqual(g6p_species.charge, -2) + self.assertIsNone(g6p_species.xml_notes) + + h2o_species = species['M_H2O_LPAREN_c_RPAREN_'] + self.assertEqual(h2o_species.id, 'M_H2O_LPAREN_c_RPAREN_') + self.assertEqual(h2o_species.name, 'H2O') + self.assertEqual(h2o_species.compartment, 'C_c') + self.assertFalse(h2o_species.boundary) + self.assertEqual(h2o_species.formula, 'H2O') + self.assertEqual(h2o_species.charge, 0) + + self.assertFalse(species['M_Phosphate_LPAREN_c_RPAREN_'].boundary) + self.assertTrue(species['M_Biomass'].boundary) + + self.assertIsNone(species['M_Biomass'].formula) + self.assertIsNone(species['M_Biomass'].charge) + + def test_g6pase_reaction_exists(self): + reader = sbml.SBMLReader(self.doc) + reaction = reader.get_reaction('R_G6Pase') + self.assertTrue(reaction.reversible) + + # Compare equation of reaction + actual_equation = Reaction(Direction.Both, [ + (Compound('M_Glucose_LPAREN_c_RPAREN_', 'C_c'), 2), + (Compound('M_Phosphate_LPAREN_c_RPAREN_', 'C_c'), 2) + ], [ + (Compound('M_H2O_LPAREN_c_RPAREN_', 'C_c'), 2), + (Compound('M_Glucose_6_DASH_P_LPAREN_c_RPAREN_', 'C_c'), 2) + ]) + self.assertEqual(reaction.equation, actual_equation) + + self.assertEqual(reaction.properties['lower_flux'], -10) + self.assertEqual(reaction.properties['upper_flux'], 1000) + + self.assertIsNotNone(reaction.xml_notes) + self.assertIsNotNone(reaction.xml_annotation) + + def test_biomass_reaction_exists(self): + reader = sbml.SBMLReader(self.doc, ignore_boundary=False) + reaction = reader.get_reaction('R_Biomass') + self.assertFalse(reaction.reversible) + + # Compare equation of reaction + actual_equation = Reaction(Direction.Forward, [ + (Compound('M_Glucose_6_DASH_P_LPAREN_c_RPAREN_', 'C_c'), + Decimal('0.56')), + (Compound('M_Glucose_LPAREN_c_RPAREN_', 'C_c'), Decimal('0.88')) + ], [ + (Compound('M_Biomass', 'C_b'), 1) + ]) + self.assertEqual(reaction.equation, actual_equation) + + self.assertEqual(reaction.properties['lower_flux'], 0) + self.assertEqual(reaction.properties['upper_flux'], 1000) + + self.assertIsNone(reaction.xml_notes) + self.assertIsNone(reaction.xml_annotation) + + def test_objective_exists(self): + reader = sbml.SBMLReader(self.doc) + objectives = {entry.id: entry for entry in reader.objectives} + self.assertEqual(len(objectives), 1) + + objective = objectives['obj1'] + self.assertEqual(objective.name, 'Objective 1') + self.assertEqual(objective.type, 'maximize') + self.assertEqual(dict(objective.reactions), {'R_Biomass': 1}) + + def test_active_objective(self): + reader = sbml.SBMLReader(self.doc) + objectives = {entry.id: entry for entry in reader.objectives} + self.assertEqual(reader.get_active_objective(), + objectives['obj1']) + + def test_flux_bounds_not_present(self): + reader = sbml.SBMLReader(self.doc) + flux_bounds = list(reader.flux_bounds) + self.assertEqual(len(flux_bounds), 0) + + def test_create_and_convert_model(self): + reader = sbml.SBMLReader(self.doc) + model = reader.create_model() + sbml.convert_sbml_model(model) + + self.assertEqual( + {entry.id for entry in model.compounds}, + {'Glucose(c)', 'Glucose_6-P(c)', 'H2O(c)', 'Phosphate(c)'}) + self.assertEqual( + {entry.id for entry in model.reactions}, + {'G6Pase', 'Biomass'}) + self.assertEqual( + {entry.id for entry in model.compartments}, + {'c'}) + + self.assertEqual(model.limits['Biomass'], ('Biomass', 0, 1000)) + self.assertEqual(model.limits['G6Pase'], ('G6Pase', -10, 1000)) + self.assertEqual(set(model.model), {'Biomass', 'G6Pase'}) + self.assertEqual(model.biomass_reaction, 'Biomass') + + +class TestModelExtracellularCompartment(unittest.TestCase): + def setUp(self): + self.model = native.NativeModel() + self.model.reactions.update([ + entry.DictReactionEntry({ + 'id': 'EX_g6p', + 'equation': parse_reaction('g6p[e] <=>') + }), + entry.DictReactionEntry({ + 'id': 'EX_glc-D', + 'equation': parse_reaction('glc-D[e] <=>') + }), + entry.DictReactionEntry({ + 'id': 'SINK_glc-D', + 'equation': parse_reaction('glc-D[c] <=>') + }), + entry.DictReactionEntry({ + 'id': 'rxn_1', + 'equation': parse_reaction('g6p[c] <=> glc-D[c]') + }), + entry.DictReactionEntry({ + 'id': 'TP_glc-D', + 'equation': parse_reaction('glc-D[c] <=> glc-D[e]') + }) + ]) + + def test_detect_model(self): + """"""Test that the extracellular compartment is detected. + + Since the 'e' compartment occurs more often in exchange reactions, + this compartment should be detected. + """""" + extracellular = sbml.detect_extracellular_compartment(self.model) + self.assertEqual(extracellular, 'e') + + def test_convert_model(self): + self.model.extracellular_compartment = 'e' + sbml.convert_exchange_to_compounds(self.model) + + self.assertEqual( + {entry.id for entry in self.model.reactions}, + {'rxn_1', 'TP_glc-D', 'SINK_glc-D'}) + self.assertEqual( + set(itervalues(self.model.exchange)), + { + (Compound('g6p', 'e'), 'EX_g6p', None, None), + (Compound('glc-D', 'e'), 'EX_glc-D', None, None) + }) + + +class TestMergeEquivalentCompounds(unittest.TestCase): + def test_merge(self): + model = native.NativeModel() + model.compounds.update([ + entry.DictCompoundEntry({ + 'id': 'g6p_c', + 'name': 'G6P' + }), + entry.DictCompoundEntry({ + 'id': 'g6p_e', + 'name': 'G6P' + }) + ]) + model.reactions.update([ + entry.DictReactionEntry({ + 'id': 'TP_g6p', + 'equation': parse_reaction('g6p_c[c] <=> g6p_e[e]') + }) + ]) + exchange_compound = Compound('g6p_e', 'e') + model.exchange[exchange_compound] = ( + exchange_compound, 'EX_g6p_e', -10, 0) + + sbml.merge_equivalent_compounds(model) + + self.assertEqual({entry.id for entry in model.compounds}, {'g6p'}) + self.assertEqual( + model.reactions['TP_g6p'].equation, + parse_reaction('g6p[c] <=> g6p[e]')) + + new_exchange_compound = Compound('g6p', 'e') + self.assertEqual( + model.exchange[new_exchange_compound], + (new_exchange_compound, 'EX_g6p_e', -10, 0)) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_psammotate.py",".py","8359","195","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2020 Keith Dufault-Thompson + +import unittest +import tempfile +import shutil +import os + +from psamm.commands import psammotate +from psamm.datasource.native import ModelReader + + +class TestPsammotate(unittest.TestCase): + def setUp(self): + self._model_dir = tempfile.mkdtemp() + with open(os.path.join(self._model_dir, 'model.yaml'), 'w') as f: + f.write('\n'.join([ + '---', + 'reactions:', + ' - id: rxn_1', + ' equation: A[e] => B[c]', + ' genes: gene_1', + ' - id: rxn_2', + ' equation: B[c] => C[c]', + ' genes: gene_2 and gene_3', + ' - id: rxn_3', + ' equation: C[c] <=> D[c]', + ' genes: gene_3 and gene_4', + ' - id: rxn_4', + ' equation: D[c] => E[e]', + ' genes: gene_3 or gene_4', + ' - id: rxn_5', + ' equation: C[c] => D[e]', + ' genes: (gene_3 or gene_4) and (gene_1 or gene_5)', + ' - id: rxn_6', + ' equation: D[c] => A[e]', + ' genes: Biomass', + ' - id: rxn_7', + ' equation: E[e] => A[e]', + ' - id: rxn_8', + ' equation: E[e] =>' + ])) + self._model = ModelReader.reader_from_path( + self._model_dir).create_model() + self.rxn_entry_dict = {} + for rx in self._model.reactions: + self.rxn_entry_dict[rx.id] = rx + + with open(os.path.join(self._model_dir, 'app.tsv'), 'w') as f: + f.write('\n'.join([ + 'gene_1\tgene_a', + 'gene_2\tgene_b', + 'gene_3\tgene_c', + 'gene_4\t-', + 'gene_5\tgene_e, gene_f', + '-\tgene_g' + ])) + + def tearDown(self): + shutil.rmtree(self._model_dir) + + def test_app_reader(self): + translation_dict = psammotate.app_reader( + open(os.path.join(self._model_dir, 'app.tsv')), 1, 0) + self.assertTrue('-' not in translation_dict) + self.assertTrue(translation_dict['gene_1'] == ['gene_a']) + self.assertTrue(translation_dict['gene_2'] == ['gene_b']) + self.assertTrue(translation_dict['gene_3'] == ['gene_c']) + self.assertTrue(translation_dict['gene_4'] == ['-']) + self.assertTrue(translation_dict['gene_5'] == ['gene_e', 'gene_f']) + + def test_model_loader_ignorena(self): + translation_dict = psammotate.app_reader( + open(os.path.join(self._model_dir, 'app.tsv')), 1, 0) + translated_genes = psammotate.model_loader( + self._model, True, translation_dict) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_1']], + ['gene_1', 'gene_a', True]) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_2']], + ['gene_2 and gene_3', 'gene_b and gene_c', True]) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_3']], + ['gene_3 and gene_4', 'gene_c and -', False]) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_4']], + ['gene_3 or gene_4', 'gene_c or -', True]) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_5']], + ['(gene_3 or gene_4) and (gene_1 or gene_5)', + '(gene_c or -) and (gene_a or (gene_e or gene_f))', + True]) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_7']], + [None, None, False]) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_8']], + [None, None, False]) + + def test_model_loader(self): + translation_dict = psammotate.app_reader( + open(os.path.join(self._model_dir, 'app.tsv')), 1, 0) + translated_genes = psammotate.model_loader( + self._model, False, translation_dict) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_1']], + ['gene_1', 'gene_a', True]) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_2']], + ['gene_2 and gene_3', 'gene_b and gene_c', True]) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_3']], + ['gene_3 and gene_4', 'gene_c and -', False]) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_4']], + ['gene_3 or gene_4', 'gene_c or -', True]) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_5']], + ['(gene_3 or gene_4) and (gene_1 or gene_5)', + '(gene_c or -) and (gene_a or (gene_e or gene_f))', + True]) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_7']], + [None, None, True]) + self.assertEqual(translated_genes[self.rxn_entry_dict['rxn_8']], + [None, None, True]) + + def test_get_gene_list_and(self): + genes = 'gene_a and gene_b' + self.assertEqual(psammotate.get_gene_list(genes), + frozenset(['gene_a', 'gene_b'])) + + def test_get_gene_list_or(self): + genes = 'gene_a or gene_b' + self.assertEqual(psammotate.get_gene_list(genes), + frozenset(['gene_a', 'gene_b'])) + + def test_get_gene_list_nested_or(self): + genes = 'gene_a or (gene_b or gene_c)' + self.assertEqual(psammotate.get_gene_list(genes), + frozenset(['gene_a', 'gene_b', 'gene_c'])) + + def test_get_gene_list_nested_and(self): + genes = 'gene_a or (gene_b and gene_c)' + self.assertEqual(psammotate.get_gene_list(genes), + frozenset(['gene_a', 'gene_b', 'gene_c'])) + + def test_get_gene_list_nested_and_or(self): + genes = '(gene_a or gene_d) or (gene_b and gene_c)' + self.assertEqual(psammotate.get_gene_list(genes), + frozenset(['gene_a', 'gene_b', 'gene_c', 'gene_d'])) + + def test_get_gene_list_multiple_nests(self): + genes = '(gene_a or (gene_b and gene_c)) or gene_d' + self.assertEqual(psammotate.get_gene_list(genes), + frozenset(['gene_a', 'gene_b', 'gene_c', 'gene_d'])) + + def test_remove_gaps_single(self): + genes = 'gene_a' + self.assertEqual(psammotate.remove_gap(genes), 'gene_a') + + def test_remove_gaps_or(self): + genes = 'gene_a or gene_b' + self.assertEqual(psammotate.remove_gap(genes), 'gene_a or gene_b') + + def test_remove_gaps_and(self): + genes = 'gene_a and gene_b' + self.assertEqual(psammotate.remove_gap(genes), 'gene_a and gene_b') + + def test_remove_gaps_and_missing(self): + genes = 'gene_a and -' + self.assertEqual(psammotate.remove_gap(genes), 'gene_a and -') + + def test_remove_gaps_or_missing(self): + genes = 'gene_a or -' + self.assertEqual(psammotate.remove_gap(genes), 'gene_a') + + def test_remove_gaps_or_missing_nested(self): + genes = 'gene_a or (- or -)' + self.assertEqual(psammotate.remove_gap(genes), 'gene_a') + + def test_remove_gaps_and_missing_nested(self): + genes = 'gene_a and (- or -)' + self.assertEqual(psammotate.remove_gap(genes), 'gene_a and -') + + def test_remove_gaps_double_nested(self): + genes = 'gene_a or (- or (- or gene_b))' + self.assertEqual(psammotate.remove_gap(genes), 'gene_a or ((gene_b))') + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_fastcore.py",".py","10040","242","#!/usr/bin/env python +# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2014-2015 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm.metabolicmodel import MetabolicModel +from psamm.database import DictDatabase +from psamm import fastcore +from psamm.datasource.reaction import parse_reaction +from psamm.lpsolver import generic + + +class TestFastcoreSimpleVlassisModel(unittest.TestCase): + """"""Test fastcore using the simple model in [Vlassis14]_."""""" + + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> (2) |A|')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|A| => |D|')) + self.database.set_reaction('rxn_4', parse_reaction('|A| => |C|')) + self.database.set_reaction('rxn_5', parse_reaction('|C| => |D|')) + self.database.set_reaction('rxn_6', parse_reaction('|D| =>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_lp10(self): + p = fastcore.FastcoreProblem(self.model, self.solver, epsilon=0.001) + scaling = 1000 + p.lp10({'rxn_6'}, {'rxn_1', 'rxn_3', 'rxn_4', 'rxn_5'}) + supp = set(reaction_id for reaction_id in self.model.reactions + if abs(p.get_flux(reaction_id)) >= 0.999 * 0.001 / scaling) + self.assertEqual(supp, {'rxn_1', 'rxn_3', 'rxn_6'}) + + def test_lp10_weighted(self): + p = fastcore.FastcoreProblem(self.model, self.solver, epsilon=0.001) + scaling = 1000 + weights = {'rxn_3': 1} + p.lp10({'rxn_6'}, {'rxn_1', 'rxn_3', 'rxn_4', 'rxn_5'}, + weights=weights) + supp = set(reaction_id for reaction_id in self.model.reactions + if abs(p.get_flux(reaction_id)) >= 0.999 * 0.001 / scaling) + self.assertEqual(supp, {'rxn_1', 'rxn_3', 'rxn_6'}) + + weights = {'rxn_3': 3} + p.lp10({'rxn_6'}, {'rxn_1', 'rxn_3', 'rxn_4', 'rxn_5'}, + weights=weights) + supp = set(reaction_id for reaction_id in self.model.reactions + if abs(p.get_flux(reaction_id)) >= 0.999 * 0.001 / scaling) + self.assertEqual(supp, {'rxn_1', 'rxn_4', 'rxn_5', 'rxn_6'}) + + def test_lp7(self): + p = fastcore.FastcoreProblem(self.model, self.solver, epsilon=0.001) + p.lp7(set(self.model.reactions)) + supp = set(reaction_id for reaction_id in self.model.reactions + if p.get_flux(reaction_id) >= 0.001*0.999) + self.assertEqual(supp, {'rxn_1', 'rxn_3', 'rxn_4', 'rxn_5', 'rxn_6'}) + + p.lp7({'rxn_5'}) + supp = set(reaction_id for reaction_id in self.model.reactions + if p.get_flux(reaction_id) >= 0.001*0.999) + # Test that the support contains at least the given reactions + self.assertLessEqual({'rxn_4', 'rxn_5', 'rxn_6'}, supp) + + def test_find_sparse_mode_singleton(self): + p = fastcore.FastcoreProblem(self.model, self.solver, epsilon=0.001) + core = {'rxn_1'} + mode = set(p.find_sparse_mode( + core, set(self.model.reactions) - core, scaling=1e3)) + self.assertEqual(mode, {'rxn_1', 'rxn_3', 'rxn_6'}) + + core = {'rxn_2'} + mode = set(p.find_sparse_mode( + core, set(self.model.reactions) - core, scaling=1e3)) + self.assertEqual(mode, set()) + + core = {'rxn_3'} + mode = set(p.find_sparse_mode( + core, set(self.model.reactions) - core, scaling=1e3)) + self.assertEqual(mode, {'rxn_1', 'rxn_3', 'rxn_6'}) + + core = {'rxn_4'} + mode = set(p.find_sparse_mode( + core, set(self.model.reactions) - core, scaling=1e3)) + self.assertEqual(mode, {'rxn_1', 'rxn_4', 'rxn_5', 'rxn_6'}) + + core = {'rxn_5'} + mode = set(p.find_sparse_mode( + core, set(self.model.reactions) - core, scaling=1e3)) + self.assertEqual(mode, {'rxn_1', 'rxn_4', 'rxn_5', 'rxn_6'}) + + core = {'rxn_6'} + mode = set(p.find_sparse_mode( + core, set(self.model.reactions) - core, scaling=1e3)) + self.assertEqual(mode, {'rxn_1', 'rxn_3', 'rxn_6'}) + + def test_find_sparse_mode_weighted(self): + p = fastcore.FastcoreProblem(self.model, self.solver, epsilon=0.001) + core = {'rxn_1'} + weights = {'rxn_3': 1} + mode = set(p.find_sparse_mode( + core, set(self.model.reactions) - core, + scaling=1e3, weights=weights)) + self.assertEqual(mode, {'rxn_1', 'rxn_3', 'rxn_6'}) + + weights = {'rxn_3': 3} + mode = set(p.find_sparse_mode( + core, set(self.model.reactions) - core, + scaling=1e3, weights=weights)) + self.assertEqual(mode, {'rxn_1', 'rxn_4', 'rxn_5', 'rxn_6'}) + + def test_fastcc_inconsistent(self): + self.assertEqual( + set(fastcore.fastcc(self.model, 0.001, solver=self.solver)), + {'rxn_2'}) + + def test_fastcc_is_consistent_on_inconsistent(self): + self.assertFalse(fastcore.fastcc_is_consistent( + self.model, 0.001, solver=self.solver)) + + def test_fastcc_is_consistent_on_consistent(self): + self.model.remove_reaction('rxn_2') + self.assertTrue(fastcore.fastcc_is_consistent( + self.model, 0.001, solver=self.solver)) + + def test_fastcc_consistent_subset(self): + self.assertEqual(fastcore.fastcc_consistent_subset( + self.model, 0.001, solver=self.solver), + set(['rxn_1', 'rxn_3', 'rxn_4', 'rxn_5', 'rxn_6'])) + + def test_fastcore_global_inconsistent(self): + self.database.set_reaction('rxn_7', parse_reaction('|E| <=>')) + self.model.add_reaction('rxn_7') + with self.assertRaises(fastcore.FastcoreError): + fastcore.fastcore(self.model, {'rxn_7'}, 0.001, + solver=self.solver) + + +class TestFastcoreTinyBiomassModel(unittest.TestCase): + """"""Test fastcore using a model with tiny values in biomass reaction + + This model is consistent mathematically since there is a flux solution + within the flux bounds. However, the numerical nature of the fastcore + algorithm requires an epsilon-parameter indicating the minimum flux that + is considered non-zero. For this reason, some models with reactions where + tiny stoichiometric values appear can be seen as inconsistent by + fastcore. + + In this particular model, rxn_2 can take a maximum flux of 1000. At the + same time rxn_1 will have to take a flux of 1e-3. This is the maximum + possible flux for rxn_1 so running fastcore with an epsilon larger than + 1e-3 will indicate that the model is not consistent. + """""" + + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('=> |A|')) + self.database.set_reaction('rxn_2', + parse_reaction('(0.000001) |A| =>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + # Skip these tests with GLPK because of issue #61. + if self.solver.properties['name'] == 'glpk': + self.skipTest('Test has known issue with GLPK') + + def test_fastcc_is_consistent(self): + self.assertTrue(fastcore.fastcc_is_consistent( + self.model, 0.0001, solver=self.solver)) + + def test_fastcc_is_consistent_high_epsilon(self): + self.assertFalse(fastcore.fastcc_is_consistent( + self.model, 0.1, solver=self.solver)) + + def test_fastcore_induced_model(self): + core = {'rxn_2'} + self.assertEqual( + set(fastcore.fastcore( + self.model, core, 0.0001, scaling=1e7, solver=self.solver)), + {'rxn_1', 'rxn_2'}) + + def test_fastcore_induced_model_high_epsilon(self): + core = {'rxn_2'} + self.assertEqual( + set(fastcore.fastcore( + self.model, core, 0.1, scaling=1e7, solver=self.solver)), + {'rxn_1', 'rxn_2'}) + + +class TestFlippingModel(unittest.TestCase): + """"""Test fastcore on a model that has to flip"""""" + + def setUp(self): + self.database = DictDatabase() + self.database.set_reaction('rxn_1', parse_reaction('|A| <=>')) + self.database.set_reaction('rxn_2', parse_reaction('|A| <=> |B|')) + self.database.set_reaction('rxn_3', parse_reaction('|C| <=> |B|')) + self.database.set_reaction('rxn_4', parse_reaction('|C| <=>')) + self.model = MetabolicModel.load_model( + self.database, self.database.reactions) + + try: + self.solver = generic.Solver() + except generic.RequirementsError: + self.skipTest('Unable to find an LP solver for tests') + + def test_fastcore_induced_model(self): + core = {'rxn_2', 'rxn_3'} + self.assertEqual(set( + fastcore.fastcore(self.model, core, 0.001, solver=self.solver)), + {'rxn_1', 'rxn_2', 'rxn_3', 'rxn_4'}) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","psamm/tests/test_mapmaker.py",".py","5500","150","# This file is part of PSAMM. +# +# PSAMM is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PSAMM is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with PSAMM. If not, see . +# +# Copyright 2017 Jon Lund Steffensen +# Copyright 2015-2020 Keith Dufault-Thompson + +import unittest + +from psamm import mapmaker +from psamm.lpsolver import generic +from psamm.formula import Formula, Atom, Radical +from psamm.reaction import Compound +from psamm.datasource.reaction import parse_reaction + + +class TestMapMakerWeigths(unittest.TestCase): + def test_default_weight(self): + self.assertEqual(mapmaker.default_weight(Atom.C), 1) + self.assertEqual(mapmaker.default_weight(Atom.N), 0.4) + self.assertEqual(mapmaker.default_weight(Atom.O), 0.4) + self.assertEqual(mapmaker.default_weight(Atom.P), 0.4) + self.assertEqual(mapmaker.default_weight(Atom.S), 1) + self.assertEqual(mapmaker.default_weight(Radical('R')), 40.0) + + def test_weighted_formula(self): + weighted = mapmaker._weighted_formula( + Formula.parse('C1H2N3S4R'), mapmaker.default_weight) + self.assertEqual(set(weighted), { + (Atom.C, 1, 1), + # H is discarded + (Atom.N, 3, 0.4), + (Atom.S, 4, 1), + (Radical('R'), 1, 40.0) + }) + + +class TestMapMaker(unittest.TestCase): + def setUp(self): + try: + self.solver = generic.Solver(integer=True) + except generic.RequirementsError: + self.skipTest('Unable to find an MILP solver for tests') + + def test_predict_compound_pairs(self): + """"""Test prediction of HEX1 reaction."""""" + reaction = parse_reaction( + 'atp[c] + glc-D[c] => adp[c] + g6p[c] + h[c]') + formulas = { + 'atp': Formula.parse('C10H12N5O13P3'), + 'adp': Formula.parse('C10H12N5O10P2'), + 'glc-D': Formula.parse('C6H12O6'), + 'g6p': Formula.parse('C6H11O9P'), + 'h': Formula.parse('H') + } + + solutions = list( + mapmaker.predict_compound_pairs(reaction, formulas, self.solver)) + + self.assertEqual(len(solutions), 1) + self.assertEqual(solutions[0], { + (Compound('atp', 'c'), Compound('adp', 'c')): + Formula.parse('C10N5O10P2'), + (Compound('glc-D', 'c'), Compound('g6p', 'c')): + Formula.parse('C6O6'), + (Compound('atp', 'c'), Compound('g6p', 'c')): + Formula.parse('O3P'), + }) + + def test_predict_compound_pairs_unbalanced(self): + """"""Test prediction of (non-sense) unbalanced reaction."""""" + reaction = parse_reaction( + 'a[c] <=> b[c] + c[c]') + formulas = { + 'a': Formula.parse('C10H12'), + 'b': Formula.parse('C9H11'), + 'c': Formula.parse('CO2'), + } + + with self.assertRaises(mapmaker.UnbalancedReactionError): + list(mapmaker.predict_compound_pairs( + reaction, formulas, self.solver)) + + def test_predict_compound_pairs_multiple(self): + """"""Test prediction of reaction with multiple instances."""""" + reaction = parse_reaction( + 'a[c] <=> (2) b[c] + c[c]') + formulas = { + 'a': Formula.parse('C10H13O6'), + 'b': Formula.parse('C5H6O3'), + 'c': Formula.parse('H'), + } + solutions = list( + mapmaker.predict_compound_pairs(reaction, formulas, self.solver)) + + self.assertEqual(len(solutions), 1) + self.assertEqual(solutions[0], { + (Compound('a', 'c'), Compound('b', 'c')): Formula.parse('C10O6'), + }) + + def test_predict_with_multiple_solutions(self): + """"""Test prediction where multiple solutions exist (TALA)."""""" + reaction = parse_reaction( + 'r5p[c] + xu5p-D[c] <=> g3p[c] + s7p[c]') + formulas = { + 'r5p': Formula.parse('C5H9O8P'), + 'xu5p-D': Formula.parse('C5H9O8P'), + 'g3p': Formula.parse('C3H5O6P'), + 's7p': Formula.parse('C7H13O10P'), + } + + solutions = list( + mapmaker.predict_compound_pairs(reaction, formulas, self.solver)) + self.assertEqual(len(solutions), 2) + + # Solution A + self.assertIn({ + (Compound('r5p', 'c'), Compound('s7p', 'c')): + Formula.parse('C5O8P'), + (Compound('xu5p-D', 'c'), Compound('g3p', 'c')): + Formula.parse('C3O6P'), + (Compound('xu5p-D', 'c'), Compound('s7p', 'c')): + Formula.parse('C2O2'), + }, solutions) + + # Solution B + self.assertIn({ + (Compound('xu5p-D', 'c'), Compound('s7p', 'c')): + Formula.parse('C5O8P'), + (Compound('r5p', 'c'), Compound('g3p', 'c')): + Formula.parse('C3O6P'), + (Compound('r5p', 'c'), Compound('s7p', 'c')): + Formula.parse('C2O2'), + }, solutions) + + +if __name__ == '__main__': + unittest.main() +","Python" +"Metabolic","zhanglab/psamm","docs/conf.py",".py","9792","311","# -*- coding: utf-8 -*- +# +# PSAMM documentation build configuration file, created by +# sphinx-quickstart on Fri Mar 27 15:57:14 2015. +# +# 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. + +import sys +import os +import shlex +import mock + +import psamm + +# 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. +sys.path.insert(0, os.path.abspath('..')) + +# Add local extensions to path. +sys.path.insert(0, os.path.abspath('extensions')) + +# Mock optional modules to allow autodoc to run even in the absense of these +# modules. +MOCK_MODULES = ['cplex', 'gurobipy', 'qsoptex', 'swiglpk'] +for module in MOCK_MODULES: + sys.modules[module] = mock.Mock() + +# -- 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.doctest', + 'sphinx.ext.coverage', + 'sphinx.ext.intersphinx', + 'sphinx.ext.napoleon', + 'sphinx.ext.mathjax', + 'doilinks' +] + +# 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 encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'PSAMM' +copyright = u'2015-2021, PSAMM developers' +author = u'PSAMM developers' + +# 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 = psamm.__version__ +# The full version, including alpha/beta/rc tags. +release = version + +# 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 = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as ""system message"" paragraphs in the built documents. +#keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + +intersphinx_mapping = { + 'python': ('https://docs.python.org/3', None) +} + +autodoc_member_order = 'bysource' + + +# -- 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 = 'sphinx_rtd_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 themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# "" v documentation"". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# 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'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +#html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, ""Created using Sphinx"" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, ""(C) Copyright ..."" is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. "".xhtml""). +#html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +#html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +#html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +#html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = 'psammdoc' + +# -- 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, 'psamm.tex', u'PSAMM Documentation', + u'PSAMM developers', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For ""manual"" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- 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, 'PSAMM', u'PSAMM Documentation', + [author], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- 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, 'PSAMM', u'PSAMM Documentation', + author, 'PSAMM', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the ""Top"" node's menu. +#texinfo_no_detailmenu = False +","Python" +"Metabolic","zhanglab/psamm","docs/extensions/doilinks.py",".py","1242","40","# -*- coding: utf-8 -*- +"""""" + doilinks + ~~~~~~~~~~~~~~~~~~~ + Extension to add links to DOIs. With this extension you can use e.g. + :doi:`10.1016/S0022-2836(05)80360-2` in your documents. This will + create a link to a DOI resolver + (``https://doi.org/10.1016/S0022-2836(05)80360-2``). + The link caption will be the raw DOI. + You can also give an explicit caption, e.g. + :doi:`Basic local alignment search tool <10.1016/S0022-2836(05)80360-2>`. + + :copyright: Copyright 2015 Jon Lund Steffensen. Based on extlinks by + the Sphinx team. + :license: BSD. +"""""" + +from docutils import nodes, utils + +from sphinx.util.nodes import split_explicit_title + + +def doi_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): + text = utils.unescape(text) + has_explicit_title, title, part = split_explicit_title(text) + full_url = 'https://doi.org/' + part + if not has_explicit_title: + title = 'doi:' + part + pnode = nodes.reference(title, title, internal=False, refuri=full_url) + return [pnode], [] + + +def setup_link_role(app): + app.add_role('doi', doi_role) + + +def setup(app): + app.connect('builder-inited', setup_link_role) + return {'version': '0.1', 'parallel_read_safe': True} +","Python" +"Metabolic","Yu-sysbio/Tutorials-of-metabolic-modeling","startme.m",".m","377","7","%% startme +% 加载COBRA工具包,这样才能正常使用该工具包,即调用该工具包的所有函数 + +cd ../cobratoolbox; % 进入COBRA文件夹(如果路径不对需要手动修改至相应路径) +initCobraToolbox; % 初始化COBRA +cd ../Tutorials-of-metabolic-modeling/; % 从COBRA文件夹回到本教程的文件夹 +","MATLAB" +"Metabolic","Yu-sysbio/Tutorials-of-metabolic-modeling","Model applications/Flux estimation/flux_estimation.m",".m","6787","126","%% flux estimation +% 预计用时:大约 1 min +% 比较凝结芽孢杆菌(Bacillus coagulans)在不同pH条件下的胞内代谢流量差异。 +% 背景介绍:同一株凝结芽孢杆菌分别在pH为6和pH为5.5的条件���进行恒化培养,稀释速率为0.2 /h + +% 注:为简化教程,模型以及模拟方法与原始文献中略有差异,因此结果也有所差别。 + +% Author: Yu Chen (yuchen.scholar@gmail.com) + +%% 读取模型 +load('iBag597.mat'); % 得到的模型文件为model +% "".mat""文件可直接使用MATLAB自带的function读取。 + +%% 设置模型 +% 因为要比较两个条件,所以需要构建两个模型,分别是pH6和pH5.5的模型。 +% 这两个模型由于都是针对同一菌株,所以在结构上没有差别。差别在于测量到的交换流量,因此需要用到条件特异性的数据来约束模型。 + +% 实验数据可以自行写入到Excel等类型的文件中,再导入到MATLAB。 +[~, ~, data_bc] = xlsread('data_bc_chemostat.xlsx'); % 导入已经在Excel中提前备好的实验数据 +exchange_rxns = data_bc(2:end,1); % 读取需要修改流量的反应ID +lb_ph6 = cell2mat(data_bc(2:end,ismember(data_bc(1,:),'LB_ph6'))); % 读取pH6条件下对应反应的流量的下限 +ub_ph6 = cell2mat(data_bc(2:end,ismember(data_bc(1,:),'UB_ph6'))); % 读取pH6条件下对应反应的流量的上限 +lb_ph55 = cell2mat(data_bc(2:end,ismember(data_bc(1,:),'LB_ph55'))); % 读取pH5.5条件下对应反应的流量的下限 +ub_ph55 = cell2mat(data_bc(2:end,ismember(data_bc(1,:),'UB_ph55'))); % 读取pH5.5条件下对应反应的流量的上限 + +% pH6的模型,命名为model_ph6 +model_ph6 = model; % 将出发模型赋值给新的模型model_high +model_ph6 = changeRxnBounds(model_ph6,exchange_rxns,lb_ph6,'l'); % 批量设置模型中对应反应的实验测得的流量 +model_ph6 = changeRxnBounds(model_ph6,exchange_rxns,ub_ph6,'u'); + +% pH5.5的模型,命名为model_ph55 +model_ph55 = model; % 将出发模型赋值给新的模型model_high +model_ph55 = changeRxnBounds(model_ph55,exchange_rxns,lb_ph55,'l'); % 批量设置模型中对应反应的实验测得的流量 +model_ph55 = changeRxnBounds(model_ph55,exchange_rxns,ub_ph55,'u'); + +%% FBA计算代谢流量 +% FBA需要认为确定一个目标函数,这里定为最大化非生长偶联的ATP消耗(NGAM),也可以理解为最大化ATP生成。 +model_ph6 = changeObjective(model_ph6,'NGAM'); +model_ph55 = changeObjective(model_ph55,'NGAM'); +% 求解 +sol_ph6 = optimizeCbModel(model_ph6,'max','one'); +sol_ph55 = optimizeCbModel(model_ph55,'max','one'); +% optimizeCbModel用来求解模型,其中""max""代表对模型中的目标函数进行最大化 +% 通常而言传统FBA只能从众多解中可能毫无根据地选择一组解 +% 而使用pFBA可以在所有解中选择总流量最小的一组解,其根据是细胞会尽可能减少酶的使用以达到给定的状态,因而更具生物学意义 +% optimizeCbModel中的""one""即代表在所有解中选择总流量最小的,是非常常用的一种方式 +fba_ph6 = sol_ph6.x; +fba_ph55 = sol_ph55.x; + +%% FVA计算每个反应的最大和最小值 +% FVA能给出在满足当前约束时每个反应的最大值和最小值 +% 以下两种方法都能计算FVA,可选任一进行计算 +% 1. fastFVA +[minFlux_ph6, maxFlux_ph6, ~] = fastFVA(model_ph6); +[minFlux_ph55, maxFlux_ph55, ~] = fastFVA(model_ph55); +% 2. fluxVariability +% [minFlux_ph6, maxFlux_ph6, ~] = fluxVariability(model_ph6); +% [minFlux_ph55, maxFlux_ph55, ~] = fluxVariability(model_ph55); + +%% Sampling获得10000组流量 +% Sampling即是在满足当前约束下,穷举所有可能的流量结果。取样次数越多,越能看出每个反应的速率可能性分布 + +% 将FBA计算得到的目标函数的最值作为约束添加到模型中 +modelSampling_ph6 = changeRxnBounds(model_ph6,'NGAM',sol_ph6.f*0.99,'b'); +modelSampling_ph55 = changeRxnBounds(model_ph55,'NGAM',sol_ph55.f*0.99,'b'); +% 有时需要将计算得到的最值稍微调小,比如乘以0.99,使得模型有解 + +% 设置Sampling的相关参数 +options.nStepsPerPoint = 200; +options.nPointsReturned = 10000; + +% Sampling计算10000组流量 +[~,samples_ph6] = sampleCbModel(modelSampling_ph6, [], [], options); +[~,samples_ph55] = sampleCbModel(modelSampling_ph55, [], [], options); + +%% 可视化 +% 选取两个反应的FBA,FVA和Sampling结果进行比较 + +% 定位所关注的三个反应在模型中的位置 +xpk_idx = ismember(model.rxns,'R0032'); % phosphoketolase +fba_idx = ismember(model.rxns,'R0008'); % fructose‐bisphosphate aldolase + +clr_6 = [5,113,176]/255; % 给pH6的结果特定颜色 +clr_55 = [202,0,32]/255; % 给pH5.5的结果特定颜色 + +figure(); +subplot(2,2,1); +hold on; +errorbar(1,fba_ph55(xpk_idx),abs(fba_ph55(xpk_idx)-minFlux_ph55(xpk_idx)),abs(fba_ph55(xpk_idx)-maxFlux_ph55(xpk_idx)),'o','Color',clr_55,'linestyle','none','MarkerSize',10,'LineWidth',1,'CapSize',20); +errorbar(2,fba_ph6(xpk_idx),abs(fba_ph6(xpk_idx)-minFlux_ph6(xpk_idx)),abs(fba_ph6(xpk_idx)-maxFlux_ph6(xpk_idx)),'o','Color',clr_6,'linestyle','none','MarkerSize',10,'LineWidth',1,'CapSize',20); +title('phosphoketolase'); +xlim([0 3]);ylim([0 12]);ylabel('Flux (mmol/gCDW/h)');xticks([1 2]);xticklabels({'pH5.5','pH6'}); + +subplot(2,2,2); +hold on; +errorbar(1,fba_ph55(fba_idx),abs(fba_ph55(fba_idx)-minFlux_ph55(fba_idx)),abs(fba_ph55(fba_idx)-maxFlux_ph55(fba_idx)),'o','Color',clr_55,'linestyle','none','MarkerSize',10,'LineWidth',1,'CapSize',20); +errorbar(2,fba_ph6(fba_idx),abs(fba_ph6(fba_idx)-minFlux_ph6(fba_idx)),abs(fba_ph6(fba_idx)-maxFlux_ph6(fba_idx)),'o','Color',clr_6,'linestyle','none','MarkerSize',10,'LineWidth',1,'CapSize',20); +title('fructose‐bisphosphate aldolase'); +xlim([0 3]);ylim([0 12]);ylabel('Flux (mmol/gCDW/h)');xticks([1 2]);xticklabels({'pH5.5','pH6'}); + +subplot(2,2,3); +hold on; +[y1, x1] = hist(samples_ph55(xpk_idx, :), 100); +[y2, x2] = hist(samples_ph6(xpk_idx, :), 100); +plot(x1, y1, 'Color', clr_55); +plot(x2, y2, 'Color', clr_6); +f1 = fill([x1,fliplr(x1)],[y1,zeros(1,length(x1))],clr_55); +set(f1,'edgealpha',0,'facealpha',0.3); +f2 = fill([x2,fliplr(x2)],[y2,zeros(1,length(x2))],clr_6); +set(f2,'edgealpha',0,'facealpha',0.3); +title('phosphoketolase'); +xlim([0 12]);xlabel('Flux (mmol/gCDW/h)');ylabel('Number of Samples'); + +subplot(2,2,4); +hold on; +[y1, x1] = hist(samples_ph55(fba_idx, :), 100); +[y2, x2] = hist(samples_ph6(fba_idx, :), 100); +plot(x1, y1, 'Color', clr_55); +plot(x2, y2, 'Color', clr_6); +f1 = fill([x1,fliplr(x1)],[y1,zeros(1,length(x1))],clr_55); +set(f1,'edgealpha',0,'facealpha',0.3); +f2 = fill([x2,fliplr(x2)],[y2,zeros(1,length(x2))],clr_6); +set(f2,'edgealpha',0,'facealpha',0.3); +title('fructose‐bisphosphate aldolase'); +xlim([0 12]);xlabel('Flux (mmol/gCDW/h)');ylabel('Number of Samples'); +","MATLAB" +"Metabolic","Yu-sysbio/Tutorials-of-metabolic-modeling","Model applications/Cell factory design/knockout_prediction.m",".m","5259","105","%% knockout prediction +% 预计用时:< 1 min +% 利用OptKnock算法预测提高酿酒酵母生产2,3-丁二醇(2,3-butanediol)的反应敲除靶点 +% OptKnock是预测需要敲除的反应而非基因,因此在实验中需要把反应对应的所有isozyme都敲除 + +% 注:为简化教程,模型以及模拟方法与原始文献中略有差异,因此结果也有所差别。 + +% 更多案例见COBRA教程(https://opencobra.github.io/cobratoolbox/stable/tutorials/tutorialOptKnock.html) + +% Author: Yu Chen (yuchen.scholar@gmail.com) + +%% 读取并设置模型 +model = readCbModel('iMM904.xml'); % 读取酵母模型(不是最新版模型) + +% 找到模型中生长的反应和产品的交换反应 +biomass = 'biomass_SC5_notrace'; % 模型中生长的反应ID +product = 'EX_btd_RR_e_'; % 模型中2,3-丁二醇的交换反应的ID + +% 确定目标函数 +model = changeObjective(model,biomass,1); % 设置目标函数为最大化生长 + +% 在模型中添加合理的约束 +model = changeRxnBounds(model,'EX_glc_e_',-10,'l'); % 设置葡萄糖吸收速率最多不超过10 mmol/gCDW/h +model = changeRxnBounds(model,'EX_o2_e_',-2,'l'); % 设置氧气吸收速率最多不超过2 mmol/gCDW/h +model = changeRxnBounds(model,'ATPM',1,'b'); % 设置非生长偶联的ATP消耗为1 mmol/gCDW/h +% 此外还需要确保其它必需的营养物质可自由摄取,iMM904默认是可以的,若使用其它生物的模型需要自行确认 + +%% 模拟用野生型酿酒酵母生产2,3-丁二醇 +solWT = optimizeCbModel(model,'max'); % 求解模型,并将求解结果命名为solWT +productFluxWT = solWT.x(strcmp(model.rxns,product)); % 在得到的解中找到产品生成速率 +% "".x""代表求得的代谢流量,需要用反应的ID定位到所关注的反应 +growthRateWT = solWT.f; % 在得到的解中找到生长速率 +% "".f""代表目标函数的值,而模型的目标函数设置的恰好是生长 + +fprintf('The production rate of 2,3-butanediol before optimization is %.3f mmol/gCDW/h \n', productFluxWT); +fprintf('The growth rate before optimization is %.3f /h \n', growthRateWT); +% 上面两行代码是将结果显示在命令窗口 + +%% 设置OptKnock算法所需要的参数 + +% 最多给出多少组改造策略 +threshold = 5; % 最多给出5组改造策略 + +% 给定每组策略中同时敲除多少个反应 +numDelRxns = 3; % 同时敲除3个反应(可从1开始依次增加,这里仅以3为例) + +% 给定需要对哪些反应进行敲除预测 +selectedRxnList = {'ALCD2ir';'ALCD2irm';'ALCD2x';'ASPTA';'CYTK1';'GLUDyi';'GTPCI';'MDH';'NADK';'NDPK3';'PDHm';'TMDPP'}; +% 通常需要对模型中所有的酶催化反应进行搜索,可用下面这一行代码,但搜索的反应越多所需要的时间越长,因此本教程只搜索如上若干反应作为例子。 +% selectedRxnList = model.rxns(~ismember(model.rules,'')); + +options = struct('targetRxn', product, 'numDel', numDelRxns); +constrOpt = struct('rxnList', {{biomass}},'values', 0.5*solWT.f, 'sense', 'G'); %规定生长至少要达到野生型的50% + +% 以下即是利用OptKnock算法寻找需要敲除的反应 +previousSolutions = cell(10, 1); +contPreviousSolutions = 1; +nIter = 1; +while nIter < threshold + fprintf('...Performing optKnock analysis...\n') + if isempty(previousSolutions{1}) + optKnockSol = OptKnock(model, selectedRxnList, options, constrOpt); + else + optKnockSol = OptKnock(model, selectedRxnList, options, constrOpt, previousSolutions, 1); + end + productFluxM1 = optKnockSol.fluxes(strcmp(model.rxns, product)); + growthRateM1 = optKnockSol.fluxes(strcmp(model.rxns, biomass)); + setM1 = optKnockSol.rxnList; + if ~isempty(setM1) + previousSolutions{contPreviousSolutions} = setM1; + contPreviousSolutions = contPreviousSolutions + 1; + fprintf('optKnock found a optKnock set of large %d composed by ', length(setM1)); + for j = 1:length(setM1) + if j == 1 + fprintf('%s', setM1{j}); + elseif j == length(setM1) + fprintf(' and %s', setM1{j}); + else + fprintf(', %s', setM1{j}); + end + end + fprintf('\n'); + fprintf('The production of 2,3-butanediol after optimization is %.3f mmol/gCDW/h \n', productFluxM1); + fprintf('The growth rate after optimization is %.3f /h \n', growthRateM1); + fprintf('...Performing coupling analysis...\n'); + [type, maxGrowth, maxProd, minProd] = analyzeOptKnock(model, setM1, product); + fprintf('The solution is of type: %s\n', type); + fprintf('The maximun growth rate given the optKnock set is %.3f /h \n', maxGrowth); + fprintf(['The maximun and minimun production of 2,3-butanediol given the optKnock set is ' ... + '%.3f and %.3f mmol/gCDW/h, respectively \n\n'], minProd, maxProd); + if strcmp(type, 'growth coupled') + singleProductionEnvelope(model, setM1, product, biomass, 'savePlot', 0, 'showPlot', 1); + end + else + if nIter == 1 + fprintf('optKnock was not able to found an optKnock set\n'); + else + fprintf('optKnock was not able to found additional optKnock sets\n'); + end + break; + end + nIter = nIter + 1; +end + +","MATLAB"