Пример #1
0
    def test_simple_activator(self):
        model = wc_lang.Model()

        init_volume = wc_lang.core.InitVolume(
            distribution=wc_ontology['WC:normal_distribution'],
            mean=0.5,
            std=0)
        c = wc_lang.Compartment(id='c', init_volume=init_volume)
        c.init_density = wc_lang.Parameter(id='density_' + c.id, value=1.)

        volume = wc_lang.Function(id='volume_' + c.id)
        volume.expression, error = wc_lang.FunctionExpression.deserialize(
            f'{c.id} / {c.init_density.id}', {
                wc_lang.Compartment: {
                    c.id: c
                },
                wc_lang.Parameter: {
                    c.init_density.id: c.init_density
                },
            })
        assert error is None, str(error)

        tf_species_type = wc_lang.SpeciesType(id='Activator')
        tf_species = wc_lang.Species(species_type=tf_species_type,
                                     compartment=c)
        tf_species.id = tf_species.gen_id()
        wc_lang.DistributionInitConcentration(species=tf_species, mean=0.5)

        F_act, species, parameters, functions = utils.simple_activator(
            model, 'transcription_rna1', tf_species)

        self.assertEqual(
            F_act,
            '((1 + Activator[c] / (Ka_transcription_rna1_Activator * Avogadro * volume_c) * f_transcription_rna1_Activator) / '
            '(1 + Activator[c] / (Ka_transcription_rna1_Activator * Avogadro * volume_c)))'
        )
        self.assertEqual(species, {'Activator[c]': tf_species})
        self.assertEqual(functions, {'volume_c': volume})
        self.assertEqual(set(model.parameters), set(parameters.values()))
        self.assertEqual(
            sorted(list(parameters.keys())),
            sorted([
                'Avogadro', 'f_transcription_rna1_Activator',
                'Ka_transcription_rna1_Activator'
            ]))
        self.assertEqual(
            model.parameters.get_one(
                id='Ka_transcription_rna1_Activator').type, None)
        self.assertEqual(
            model.parameters.get_one(
                id='Ka_transcription_rna1_Activator').units,
            unit_registry.parse_units('M'))
Пример #2
0
    def run(self):
        """ Generate a :obj:`wc_lang` model from a :obj:`wc_kb` knowledge base

        Returns:
            :obj:`wc_lang.Model`: model
        """
        model = wc_lang.Model()
        model.id = self.options.get('id')
        model.name = self.options.get('name')
        model.version = self.options.get('version')

        component_options = self.options.get('component', {})
        for component_generator in self.component_generators:
            options = component_options.get(component_generator.__name__, {})
            component_generator(self.knowledge_base, model,
                                options=options).run()

        return model
Пример #3
0
    def setUp(self):
        # make model
        self.model = wc_lang.Model(id='model')
        comp = self.model.compartments.create(id='comp')
        self.species = []
        self.num_species = 20
        for i in range(1, self.num_species+1):
            spec_type = self.model.species_types.create(id=self.sp_id(i),
                                                        type=onto['WC:metabolite']) # metabolite
            species = wc_lang.Species(
                species_type=spec_type,
                compartment=comp)
            species.id = species.gen_id()
            self.species.append(species)
        self.dfba_submodel = self.model.submodels.create(
            id='metabolism',
            framework=onto['WC:dynamic_flux_balance_analysis'])

        self.id_idx = 0
        self.model_analysis = wc_analysis.model.fba.FbaModelAnalysis(self.model)
Пример #4
0
    def setUp(self):

        # Create KB content
        self.tmp_dirname = tempfile.mkdtemp()
        self.sequence_path = os.path.join(self.tmp_dirname, 'test_seq.fasta')
        with open(self.sequence_path, 'w') as f:
            f.write('>chr1\nGCGTGCGATGAT\n'
                    '>chrM\nNGCGTGCGATGAT\n'
                    '>chrX\nATGtgaGCGtgatga\n')

        self.kb = wc_kb.KnowledgeBase()
        cell = self.kb.cell = wc_kb.Cell()

        chr1 = wc_kb.core.DnaSpeciesType(cell=cell,
                                         id='chr1',
                                         sequence_path=self.sequence_path)
        gene1 = wc_kb.eukaryote.GeneLocus(cell=cell,
                                          id='gene1',
                                          polymer=chr1,
                                          start=1,
                                          end=12)
        chrM = wc_kb.core.DnaSpeciesType(cell=cell,
                                         id='chrM',
                                         sequence_path=self.sequence_path)
        geneM = wc_kb.eukaryote.GeneLocus(cell=cell,
                                          id='geneM',
                                          polymer=chrM,
                                          start=2,
                                          end=13)
        chrX = wc_kb.core.DnaSpeciesType(cell=cell,
                                         id='chrX',
                                         sequence_path=self.sequence_path)
        geneX1 = wc_kb.eukaryote.GeneLocus(cell=cell,
                                           id='geneX1',
                                           polymer=chrX,
                                           start=1,
                                           end=15)
        geneX2 = wc_kb.eukaryote.GeneLocus(cell=cell,
                                           id='geneX2',
                                           polymer=chrX,
                                           start=1,
                                           end=15)

        locus1 = wc_kb.eukaryote.GenericLocus(start=1, end=6)
        transcript1 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            gene=gene1,
                                                            exons=[locus1])
        prot1 = wc_kb.eukaryote.ProteinSpeciesType(cell=cell,
                                                   id='prot1',
                                                   name='protein1',
                                                   transcript=transcript1,
                                                   coding_regions=[locus1])
        prot1_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=prot1,
            value='40000.0',
            value_type=wc_ontology['WC:float'])

        locus2 = wc_kb.eukaryote.GenericLocus(start=4, end=9)
        transcript2 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            gene=gene1,
                                                            exons=[locus2])
        prot2 = wc_kb.eukaryote.ProteinSpeciesType(cell=cell,
                                                   id='prot2',
                                                   name='protein2',
                                                   transcript=transcript2,
                                                   coding_regions=[locus2])
        prot2_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=prot2,
            value='40000.0',
            value_type=wc_ontology['WC:float'])

        locus3 = wc_kb.eukaryote.GenericLocus(start=7, end=12)
        transcript3 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            gene=gene1,
                                                            exons=[locus3])
        prot3 = wc_kb.eukaryote.ProteinSpeciesType(cell=cell,
                                                   id='prot3',
                                                   name='protein3',
                                                   transcript=transcript3,
                                                   coding_regions=[locus3])
        prot3_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=prot3,
            value='25000.0',
            value_type=wc_ontology['WC:float'])

        locusM = wc_kb.eukaryote.GenericLocus(start=8, end=13)
        transcriptM = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            gene=geneM,
                                                            exons=[locusM])
        protM = wc_kb.eukaryote.ProteinSpeciesType(cell=cell,
                                                   id='protM',
                                                   name='proteinM',
                                                   transcript=transcriptM,
                                                   coding_regions=[locusM])
        protM_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=protM,
            value='25000.0',
            value_type=wc_ontology['WC:float'])

        locusX1 = wc_kb.eukaryote.GenericLocus(start=1, end=15)
        transcriptX1 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                             gene=geneX1,
                                                             exons=[locusX1])
        protX1 = wc_kb.eukaryote.ProteinSpeciesType(cell=cell,
                                                    id='protX1',
                                                    name='proteinX1',
                                                    transcript=transcriptX1,
                                                    coding_regions=[locusX1])
        protX1_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=protX1,
            value='25000.0',
            value_type=wc_ontology['WC:float'])

        locusX2 = wc_kb.eukaryote.GenericLocus(start=1, end=15)
        transcriptX2 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                             gene=geneX2,
                                                             exons=[locusX2])
        protX2 = wc_kb.eukaryote.ProteinSpeciesType(cell=cell,
                                                    id='protX2',
                                                    name='proteinX2',
                                                    transcript=transcriptX2,
                                                    coding_regions=[locusX2])
        protX2_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=protX2,
            value='25000.0',
            value_type=wc_ontology['WC:float'])

        # Create initial model content
        self.model = model = wc_lang.Model()

        model.parameters.create(
            id='Avogadro',
            value=scipy.constants.Avogadro,
            units=unit_registry.parse_units('molecule mol^-1'))

        compartments = {
            'n': ('nucleus', 5E-14),
            'c': ('cytoplasm', 1E-13),
            'm': ('mitochondria', 2.5E-14),
            'l': ('lysosome', 1.5E-14),
            'c_m': ('membrane', 5E-15)
        }
        for k, v in compartments.items():
            init_volume = wc_lang.core.InitVolume(
                distribution=wc_ontology['WC:normal_distribution'],
                mean=v[1],
                std=0)
            c = model.compartments.create(id=k,
                                          name=v[0],
                                          init_volume=init_volume)
            c.init_density = model.parameters.create(
                id='density_' + k,
                value=1000,
                units=unit_registry.parse_units('g l^-1'))
            volume = model.functions.create(
                id='volume_' + k, units=unit_registry.parse_units('l'))
            volume.expression, error = wc_lang.FunctionExpression.deserialize(
                f'{c.id} / {c.init_density.id}', {
                    wc_lang.Compartment: {
                        c.id: c
                    },
                    wc_lang.Parameter: {
                        c.init_density.id: c.init_density
                    },
                })
            assert error is None, str(error)

        proteins = {
            'prot1': ['n', 'c'],
            'prot2': ['c', 'l'],
            'prot3': ['l'],
            'protM': ['m', 'c_m'],
            'protX1': ['l'],
            'protX2': ['l']
        }
        for k, v in proteins.items():
            kb_protein = cell.species_types.get_one(id=k)
            model_species_type = model.species_types.create(
                id=kb_protein.id,
                name=kb_protein.name,
                type=wc_ontology['WC:protein'])
            for comp in v:
                model_compartment = model.compartments.get_one(id=comp)
                model_species = model.species.create(
                    species_type=model_species_type,
                    compartment=model_compartment)
                model_species.id = model_species.gen_id()
                conc_model = model.distribution_init_concentrations.create(
                    species=model_species,
                    mean=10,
                    units=unit_registry.parse_units('molecule'))
                conc_model.id = conc_model.gen_id()
        model.distribution_init_concentrations.get_one(
            id='dist-init-conc-protM[m]').mean = 0.

        complexes = {
            'comp_1': ('26S proteasome', ['n', 'c']),
            'comp_2': ('lonp1', ['m']),
            'comp_3': ('clpp', ['m']),
            'comp_4': ('cathepsin B', ['l']),
            'comp_5': ('cathepsin D', ['l'])
        }
        for k, v in complexes.items():
            model_species_type = model.species_types.create(
                id=k, name=v[0], type=wc_ontology['WC:pseudo_species'])
            for comp in v[1]:
                model_compartment = model.compartments.get_one(id=comp)
                model_species = model.species.create(
                    species_type=model_species_type,
                    compartment=model_compartment)
                model_species.id = model_species.gen_id()
                conc_model = model.distribution_init_concentrations.create(
                    species=model_species,
                    mean=2,
                    units=unit_registry.parse_units('molecule'))
                conc_model.id = conc_model.gen_id()

        metabolic_participants = [
            'Ala', 'Cys', 'Asp', 'Glu', 'Met', 'Selcys', 'h2o'
        ]
        metabolic_compartments = ['l', 'm']
        for i in metabolic_participants:
            for c in metabolic_compartments:
                model_species_type = model.species_types.get_or_create(
                    id=i, type=wc_ontology['WC:metabolite'])
                model_compartment = model.compartments.get_one(id=c)
                model_species = model.species.get_or_create(
                    species_type=model_species_type,
                    compartment=model_compartment)
                model_species.id = model_species.gen_id()
Пример #5
0
def main(examples_dir=os.path.join(os.path.dirname(__file__), 'examples')):

    ################################################################
    # This code is used by literalinclude commands in wc_lang_tutorial.rst
    # It contains many separate examples, each prefixed by a comment that delineates the
    # start of the example and is used by a start-after option in a literalinclude.
    # The line before each of these comments is:
    # Don't change the next comment - it's used by a literalinclude
    # Changes to these comments should be synchronized with changes to wc_lang_tutorial.rst
    ################################################################

    # save the results of example commands so this function can be unit-tested
    results = []

    ################################################
    # Reading and writing models to/from files
    ################################################

    model_filename = os.path.join(examples_dir, 'example_model.xlsx')
    # Don't change the next comment - it's used by a literalinclude
    # This example illustrates how to read a model from an Excel file
    # 'model_filename' is the name of an Excel file storing a model
    model = wc_lang.io.Reader().run(model_filename)[wc_lang.Model][0]

    results.append("read model: '{}'".format(model.name))

    if not os.path.isdir(examples_dir):
        os.makedirs(examples_dir)
    # Don't change the next comment - it's used by a literalinclude
    # This example illustrates how to write a model to a set of .tsv files
    # 'examples_dir' is a directory
    model_filename_pattern = os.path.join(examples_dir, 'example_model-*.tsv')
    wc_lang.io.Writer().run(model_filename_pattern, model, data_repo_metadata=False)

    results.append("write a model to a set of .tsv files: '{}'".format(model_filename_pattern))

    # Don't change the next comment - it's used by a literalinclude
    # This example illustrates how to read a model from a set of .tsv files
    model_from_tsv = wc_lang.io.Reader().run(model_filename_pattern)[wc_lang.Model][0]

    results.append("read a model from a set of .tsv files: '{}'".format(model_from_tsv.name))

    ################################################
    # Accessing model properties
    ################################################

    # Don't change the next comment - it's used by a literalinclude
    # ``wc_lang`` models have many attributes
    model.id                # the model's unique identifier
    model.name              # its human readable name
    model.version           # its version number
    model.taxon             # the taxon of the organism being modeled
    model.submodels         # a list of the model's submodels
    model.compartments      # "  "   "  the model's compartments
    model.species_types     # "  "   "  its species types
    model.parameters        # "  "   "  its parameters
    model.references        # "  "   "  publication sources for the model instance
    model.identifiers       # "  "   "  identifiers in external namespaces for the model instance

    results.append("referenced model attributes")

    # Don't change the next comment - it's used by a literalinclude
    # ``wc_lang`` also provides many convenience methods
    model.get_compartments()
    model.get_species_types()
    model.get_submodels()
    model.get_species()
    model.get_distribution_init_concentrations()
    model.get_reactions()
    model.get_dfba_obj_reactions()
    model.get_rate_laws()
    model.get_parameters()
    model.get_references()

    results.append("referenced model convenience methods")

    # Don't change the next comment - it's used by a literalinclude
    # ``get_reactions()`` returns a list of all of the reactions in a model's submodels
    reaction_identification = []
    for reaction in model.get_reactions():
        reaction_identification.append('submodel name: {}, reaction id: {}'.format(
            reaction.submodel.name, reaction.id))

    results.append("get_reactions entry 0: '{}'".format(reaction_identification[0]))

    #################################################
    # Building models and editing model properties
    #################################################

    # Don't change the next comment - it's used by a literalinclude
    # The following illustrates how to program a trivial model
    # create a model with one submodel and one compartment
    prog_model = wc_lang.Model(id='programmatic_model', name='Programmatic model')

    submodel = wc_lang.Submodel(id='submodel_1', model=prog_model)

    cytosol = wc_lang.Compartment(id='c', name='Cytosol')

    # create 5 species types
    atp = wc_lang.SpeciesType(id='atp', name='ATP', model=prog_model)
    adp = wc_lang.SpeciesType(id='adp', name='ADP', model=prog_model)
    pi = wc_lang.SpeciesType(id='pi', name='Pi', model=prog_model)
    h2o = wc_lang.SpeciesType(id='h2o', name='H2O', model=prog_model)
    h = wc_lang.SpeciesType(id='h', name='H+', model=prog_model)

    # create an 'ATP hydrolysis' reaction that uses these species types
    atp_hydrolysis = wc_lang.Reaction(id='atp_hydrolysis', name='ATP hydrolysis')

    # add two reactants, which have negative stoichiometric coefficients
    atp_hydrolysis.participants.create(
        species=wc_lang.Species(id='atp[c]', species_type=atp, compartment=cytosol), coefficient=-1)
    atp_hydrolysis.participants.create(
        species=wc_lang.Species(id='h2o[c]', species_type=h2o, compartment=cytosol), coefficient=-1)

    # add three products, with positive stoichiometric coefficients
    atp_hydrolysis.participants.create(
        species=wc_lang.Species(id='adp[c]', species_type=adp, compartment=cytosol), coefficient=1)
    atp_hydrolysis.participants.create(
        species=wc_lang.Species(id='pi[c]', species_type=pi, compartment=cytosol), coefficient=1)
    atp_hydrolysis.participants.create(
        species=wc_lang.Species(id='h[c]', species_type=h, compartment=cytosol), coefficient=1)
    # The previous illustrates how to program a trivial model
    # Don't change the previous comment - it's used by a literalinclude

    results.append("created model: '{}'".format(prog_model.name))

    # Don't change the next comment - it's used by a literalinclude
    # so that this assertion holds
    assert(atp in prog_model.get_species_types())

    # Don't change the next comment - it's used by a literalinclude
    # these assertions hold
    # 5 participants were added to the reaction
    assert(len(atp_hydrolysis.participants) == 5)
    first_reaction_participant = atp_hydrolysis.participants[0]
    assert(first_reaction_participant.reactions[0] is atp_hydrolysis)

    # Don't change the next comment - it's used by a literalinclude
    # The attribues that can be initialized when a ``wc_lang.BaseModel`` class is instantiated
    wc_lang.Model.Meta.attributes.keys()
    wc_lang.Submodel.Meta.attributes.keys()
    wc_lang.SpeciesType.Meta.attributes.keys()
    wc_lang.Compartment.Meta.attributes.keys()

    # Don't change the next comment - it's used by a literalinclude
    # The following illustrates how to edit a model programmatically
    atp_hydrolysis.comments = 'example comments'
    atp_hydrolysis.reversible = False

    #################################################
    # Viewing Models and their attributes
    #################################################

    # pprint example
    atp_hydrolysis.participants[0].pprint(max_depth=1)

    #################################################
    # Finding model components
    #################################################

    #################################################
    # Completing and validating models
    #################################################

    # Don't change the next comment - it's used by a literalinclude
    # This example illustrates how to validate ``prog_model``
    prog_model.validate()

    rv = prog_model.validate()
    results.append("validate model: '{}'".format(rv))

    # TODO: make this work: print(atp_hydrolysis.participants[0].reaction)
    # TODO: make this work: print('len(atp_hydrolysis.participants)', len(atp_hydrolysis.participants))

    #################################################
    # Comparing and differencing models
    #################################################

    # Don't change the next comment - it's used by a literalinclude
    # compare the semantic equality of ``model`` and ``model_from_tsv``
    assert(model.is_equal(model_from_tsv) == True)

    # Don't change the next comment - it's used by a literalinclude
    # produces a textual description of the differences between two models
    assert(model.difference(model_from_tsv) == '')

    #################################################
    # Normalizing models into a reproducible order
    #################################################

    # Don't change the next comment - it's used by a literalinclude
    # The following code excerpt will normalize ``model`` into a reproducible order
    model.normalize()

    rv = model.normalize()
    results.append("normalize model: '{}'".format(rv))

    return results
Пример #6
0
    def gen_model(self):
        """ Generate this model:

        * One compartment, comp
        * Two submodels, submodel_synthesis and submodel_degradation
        * Two species types
        * Two species

            * One whose copy number increases at a constant rate, st_constant[comp]
            * One whose copy number changes dynamically, st_dynamic[comp]

        * Four reactions which produce and consume the dynamically changing species

            * In submodel_synthesis

                * rxn_synthesis_constant: -> st_constant[comp]; k_syn_constant
                * rxn_synthesis_dynamic: -> st_dynamic[comp]; k_syn_dynamic

            * In submodel_degradation

                * rxn_degradation_constant: st_constant[comp] -> ; k_deg_constant * st_constant[comp]
                * rxn_degradation_dynamic: st_dynamic[comp] -> ; k_deg_dynamic * st_dynamic[comp]

        * Default values

            * k_syn_constant = 0
            * k_deg_constant = 0
        """
        model = wc_lang.Model(id='model',
                              version='0.0.1',
                              wc_lang_version='0.0.1')

        # species, compartment and initial concentrations
        st_constant = model.species_types.create(
            id='st_constant',
            structure=wc_lang.ChemicalStructure(charge=0.,
                                                molecular_weight=1.))
        st_dynamic = model.species_types.create(
            id='st_dynamic',
            structure=wc_lang.ChemicalStructure(charge=0.,
                                                molecular_weight=0.))
        comp = model.compartments.create(
            id='comp', init_volume=wc_lang.InitVolume(std=0.))
        spec_constant = model.species.create(species_type=st_constant,
                                             compartment=comp)
        spec_dynamic = model.species.create(species_type=st_dynamic,
                                            compartment=comp)
        spec_constant.id = spec_constant.gen_id()
        spec_dynamic.id = spec_dynamic.gen_id()
        conc_constant = model.distribution_init_concentrations.create(
            species=spec_constant,
            std=0.,
            units=unit_registry.parse_units('molecule'))
        conc_dynamic = model.distribution_init_concentrations.create(
            species=spec_dynamic,
            std=0.,
            units=unit_registry.parse_units('molecule'))
        conc_constant.id = conc_constant.gen_id()
        conc_dynamic.id = conc_dynamic.gen_id()

        # density and volume
        density = comp.init_density = model.parameters.create(
            id='density', value=1., units=unit_registry.parse_units('g l^-1'))
        volume = model.functions.create(id='volume',
                                        units=unit_registry.parse_units('l'))
        volume.expression, error = wc_lang.FunctionExpression.deserialize(
            f'{comp.id} / {density.id}', {
                wc_lang.Compartment: {
                    comp.id: comp
                },
                wc_lang.Parameter: {
                    density.id: density
                }
            })
        assert error is None, str(error)

        # submodels
        submdl_syn = model.submodels.create(
            id='submodel_synthesis',
            framework=onto['WC:stochastic_simulation_algorithm'])
        submdl_deg = model.submodels.create(
            id='submodel_degradation',
            framework=onto['WC:stochastic_simulation_algorithm'])

        # reactions
        rxn_syn_constant = model.reactions.create(id='rxn_synthesis_constant',
                                                  submodel=submdl_syn)
        rxn_syn_constant.participants.create(species=spec_constant,
                                             coefficient=1)
        rl_syn_constant = model.rate_laws.create(reaction=rxn_syn_constant)
        rl_syn_constant.id = rl_syn_constant.gen_id()
        k_syn_constant = model.parameters.create(
            id='k_syn_constant',
            value=0.,
            units=unit_registry.parse_units('s^-1'))
        rl_syn_constant.expression, error = wc_lang.RateLawExpression.deserialize(
            k_syn_constant.id, {
                wc_lang.Parameter: {
                    k_syn_constant.id: k_syn_constant,
                },
            })
        assert error is None, str(error)

        rxn_deg_constant = model.reactions.create(
            id='rxn_degradation_constant', submodel=submdl_deg)
        rxn_deg_constant.participants.create(species=spec_constant,
                                             coefficient=-1)
        rl_deg_constant = model.rate_laws.create(reaction=rxn_deg_constant)
        rl_deg_constant.id = rl_deg_constant.gen_id()
        k_deg_constant = model.parameters.create(
            id='k_deg_constant',
            value=0.,
            units=unit_registry.parse_units('s^-1 molecule^-1'))
        rl_deg_constant.expression, error = \
            wc_lang.RateLawExpression.deserialize(f'{k_deg_constant.id} * {spec_constant.id}', {
            wc_lang.Parameter: {
                k_deg_constant.id: k_deg_constant,
            },
            wc_lang.Species: {
                spec_constant.id: spec_constant,
            }
        })
        assert error is None, str(error)

        rxn_syn_dynamic = model.reactions.create(id='rxn_synthesis_dynamic',
                                                 submodel=submdl_syn)
        rxn_syn_dynamic.participants.create(species=spec_dynamic,
                                            coefficient=1)
        rl_syn_dynamic = model.rate_laws.create(reaction=rxn_syn_dynamic)
        rl_syn_dynamic.id = rl_syn_dynamic.gen_id()
        k_syn_dynamic = model.parameters.create(
            id='k_syn_dynamic', units=unit_registry.parse_units('s^-1'))
        rl_syn_dynamic.expression, error = wc_lang.RateLawExpression.deserialize(
            k_syn_dynamic.id, {
                wc_lang.Parameter: {
                    k_syn_dynamic.id: k_syn_dynamic,
                },
            })
        assert error is None, str(error)

        rxn_deg_dynamic = model.reactions.create(id='rxn_degradation_dynamic',
                                                 submodel=submdl_deg)
        rxn_deg_dynamic.participants.create(species=spec_dynamic,
                                            coefficient=-1)
        rl_deg_dynamic = model.rate_laws.create(reaction=rxn_deg_dynamic)
        rl_deg_dynamic.id = rl_deg_dynamic.gen_id()
        k_deg_dynamic = model.parameters.create(
            id='k_deg_dynamic',
            units=unit_registry.parse_units('s^-1 molecule^-1'))
        rl_deg_dynamic.expression, error = \
            wc_lang.RateLawExpression.deserialize(f'{k_deg_dynamic.id} * {spec_dynamic.id}', {
                wc_lang.Parameter: {
                    k_deg_dynamic.id: k_deg_dynamic,
                },
                wc_lang.Species: {
                    spec_dynamic.id: spec_dynamic,
                }
            })
        assert error is None, str(error)

        # other parameter
        model.parameters.create(
            id='Avogadro',
            value=NA,
            units=unit_registry.parse_units('molecule mol^-1'))

        return model
Пример #7
0
    def setUp(self):

        # Create KB content
        self.tmp_dirname = tempfile.mkdtemp()
        self.sequence_path = os.path.join(self.tmp_dirname, 'test_seq.fasta')
        with open(self.sequence_path, 'w') as f:
            f.write('>chr1\nTTTATGACTCTAGTTTAT\n'
                    '>chrM\nTTTatgaCTCTAGTTTAT\n')

        self.kb = wc_kb.KnowledgeBase()
        cell = self.kb.cell = wc_kb.Cell()

        nucleus = cell.compartments.create(id='n')
        mito = cell.compartments.create(id='m')
        cytoplasm = cell.compartments.create(id='c')

        chr1 = wc_kb.core.DnaSpeciesType(cell=cell,
                                         id='chr1',
                                         sequence_path=self.sequence_path)
        gene1 = wc_kb.eukaryote.GeneLocus(cell=cell,
                                          id='gene1',
                                          polymer=chr1,
                                          start=1,
                                          end=18)
        exon1 = wc_kb.eukaryote.GenericLocus(start=4, end=18)
        transcript1 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            id='trans1',
                                                            name='transcript1',
                                                            gene=gene1,
                                                            exons=[exon1])
        transcript1_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=transcript1,
            value='36000.0',
            value_type=wc_ontology['WC:float'])
        transcript1_spec = wc_kb.core.Species(species_type=transcript1,
                                              compartment=cytoplasm)
        transcript1_conc = wc_kb.core.Concentration(cell=cell,
                                                    species=transcript1_spec,
                                                    value=10.)

        chrM = wc_kb.core.DnaSpeciesType(cell=cell,
                                         id='chrM',
                                         sequence_path=self.sequence_path)
        gene2 = wc_kb.eukaryote.GeneLocus(cell=cell,
                                          id='gene2',
                                          polymer=chrM,
                                          start=1,
                                          end=18)
        exon2 = wc_kb.eukaryote.GenericLocus(start=1, end=10)
        transcript2 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            id='trans2',
                                                            name='transcript2',
                                                            gene=gene2,
                                                            exons=[exon2])
        transcript2_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=transcript2,
            value='15000.0',
            value_type=wc_ontology['WC:float'])
        transcript2_spec = wc_kb.core.Species(species_type=transcript2,
                                              compartment=mito)
        transcript2_conc = wc_kb.core.Concentration(cell=cell,
                                                    species=transcript2_spec,
                                                    value=10.)

        transcript3 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            id='trans3',
                                                            name='transcript3',
                                                            gene=gene2,
                                                            exons=[exon2])
        transcript3_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=transcript3,
            value='36000.0',
            value_type=wc_ontology['WC:float'])
        transcript3_spec = wc_kb.core.Species(species_type=transcript3,
                                              compartment=mito)
        transcript3_conc = wc_kb.core.Concentration(cell=cell,
                                                    species=transcript3_spec,
                                                    value=10.)

        transcript4 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            id='trans4',
                                                            name='transcript4',
                                                            gene=gene2,
                                                            exons=[exon2])
        transcript4_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=transcript4,
            value='36000.0',
            value_type=wc_ontology['WC:float'])
        transcript4_spec = wc_kb.core.Species(species_type=transcript4,
                                              compartment=mito)
        transcript4_conc = wc_kb.core.Concentration(cell=cell,
                                                    species=transcript4_spec,
                                                    value=0.)

        transcript5 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            id='trans5',
                                                            name='transcript5',
                                                            gene=gene2)
        transcript5_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=transcript5,
            value='36000.0',
            value_type=wc_ontology['WC:float'])
        transcript5_spec = wc_kb.core.Species(species_type=transcript5,
                                              compartment=mito)
        transcript5_conc = wc_kb.core.Concentration(cell=cell,
                                                    species=transcript5_spec,
                                                    value=0.)

        # Create initial model content
        self.model = model = wc_lang.Model()

        model.parameters.create(
            id='Avogadro',
            value=scipy.constants.Avogadro,
            units=unit_registry.parse_units('molecule mol^-1'))

        compartments = {
            'n': ('nucleus', 5E-14),
            'm': ('mitochondria', 2.5E-14),
            'c': ('cytoplasm', 9E-14)
        }
        for k, v in compartments.items():
            init_volume = wc_lang.core.InitVolume(
                distribution=wc_ontology['WC:normal_distribution'],
                mean=v[1],
                std=0)
            c = model.compartments.create(id=k,
                                          name=v[0],
                                          init_volume=init_volume)
            c.init_density = model.parameters.create(
                id='density_' + k,
                value=1000,
                units=unit_registry.parse_units('g l^-1'))
            volume = model.functions.create(
                id='volume_' + k, units=unit_registry.parse_units('l'))
            volume.expression, error = wc_lang.FunctionExpression.deserialize(
                f'{c.id} / {c.init_density.id}', {
                    wc_lang.Compartment: {
                        c.id: c
                    },
                    wc_lang.Parameter: {
                        c.init_density.id: c.init_density
                    },
                })
            assert error is None, str(error)

        for i in cell.species_types.get(
                __type=wc_kb.eukaryote.TranscriptSpeciesType):
            model_species_type = model.species_types.create(id=i.id,
                                                            name=i.name)
            model_compartment = model.compartments.get_one(
                id='m' if 'M' in i.gene.polymer.id else 'c')
            model_species = model.species.get_or_create(
                species_type=model_species_type, compartment=model_compartment)
            model_species.id = model_species.gen_id()
            conc_model = model.distribution_init_concentrations.create(
                species=model_species,
                mean=10.,
                units=unit_registry.parse_units('molecule'))
            conc_model.id = conc_model.gen_id()
        model.distribution_init_concentrations.get_one(
            id='dist-init-conc-trans4[m]').mean = 0.
        ribo_site_species_type = model.species_types.create(
            id='trans2_ribosome_binding_site')
        mitochondria = model.compartments.get_one(id='m')
        ribo_site_species = model.species.create(
            species_type=ribo_site_species_type, compartment=mitochondria)
        ribo_site_species.id = ribo_site_species.gen_id()
        conc_ribo_site_species = model.distribution_init_concentrations.create(
            species=ribo_site_species,
            mean=20,
            units=unit_registry.parse_units('molecule'))
        conc_ribo_site_species.id = conc_ribo_site_species.gen_id()

        complexes = {
            'complex1': ('Exosome', ['c', 'n']),
            'complex2': ('Exosome variant', ['c', 'n']),
            'complex3': ('Mitochondrial Exosome', ['m']),
            'complex4': ('Mitochondrial Exosome variant', ['m'])
        }
        for k, v in complexes.items():
            model_species_type = model.species_types.get_or_create(id=k,
                                                                   name=v[0])
            for comp in v[1]:
                model_compartment = model.compartments.get_one(id=comp)
                model_species = model.species.get_or_create(
                    species_type=model_species_type,
                    compartment=model_compartment)
                model_species.id = model_species.gen_id()
                conc_model = model.distribution_init_concentrations.create(
                    species=model_species,
                    mean=100.,
                    units=unit_registry.parse_units('molecule'))
                conc_model.id = conc_model.gen_id()

        metabolic_participants = ['amp', 'cmp', 'gmp', 'ump', 'h2o', 'h']
        for i in metabolic_participants:
            model_species_type = model.species_types.create(id=i)
            for c in ['n', 'm', 'c']:
                model_compartment = model.compartments.get_one(id=c)
                model_species = model.species.get_or_create(
                    species_type=model_species_type,
                    compartment=model_compartment)
                model_species.id = model_species.gen_id()
                conc_model = model.distribution_init_concentrations.create(
                    species=model_species,
                    mean=1500.,
                    units=unit_registry.parse_units('molecule'))
                conc_model.id = conc_model.gen_id()
    def setUp(self):

        # Create KB content
        self.tmp_dirname = tempfile.mkdtemp()
        self.sequence_path = os.path.join(self.tmp_dirname, 'test_seq.fasta')
        with open(self.sequence_path, 'w') as f:
            f.write('>chr1\nGCGTGCGATGATtgatga\n')

        self.kb = wc_kb.KnowledgeBase()
        cell = self.kb.cell = wc_kb.Cell()

        nucleus = cell.compartments.create(id='n')
        mito = cell.compartments.create(id='m')
        lysosome = cell.compartments.create(id='l')
        membrane = cell.compartments.create(id='c_m')

        chr1 = wc_kb.core.DnaSpeciesType(cell=cell, id='chr1', sequence_path=self.sequence_path)
        gene1 = wc_kb.eukaryote.GeneLocus(cell=cell, id='gene1', polymer=chr1, start=1, end=18)
        
        locus1 = wc_kb.eukaryote.GenericLocus(start=1, end=6)
        transcript1 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell, gene=gene1, exons=[locus1])
        prot1 = wc_kb.eukaryote.ProteinSpeciesType(cell=cell, id='prot1', name='protein1', transcript=transcript1, coding_regions=[locus1])
        prot1_half_life = wc_kb.core.SpeciesTypeProperty(property='half-life', species_type=prot1, 
            value='40000.0', value_type=wc_ontology['WC:float'])
        prot1_spec = wc_kb.core.Species(species_type=prot1, compartment=nucleus)
        
        locus2 = wc_kb.eukaryote.GenericLocus(start=4, end=9)
        transcript2 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell, gene=gene1, exons=[locus2])
        prot2 = wc_kb.eukaryote.ProteinSpeciesType(cell=cell, id='prot2', name='protein2', transcript=transcript2, coding_regions=[locus2])
        prot2_half_life = wc_kb.core.SpeciesTypeProperty(property='half-life', species_type=prot2, 
            value='20000.0', value_type=wc_ontology['WC:float'])
        prot2_spec = wc_kb.core.Species(species_type=prot2, compartment=nucleus)
        
        locus3 = wc_kb.eukaryote.GenericLocus(start=7, end=12)
        transcript3 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell, gene=gene1, exons=[locus3])
        prot3 = wc_kb.eukaryote.ProteinSpeciesType(cell=cell, id='prot3', name='protein3', transcript=transcript3, coding_regions=[locus3])
        prot3_half_life = wc_kb.core.SpeciesTypeProperty(property='half-life', species_type=prot3, 
            value='25000.0', value_type=wc_ontology['WC:float'])
        prot3_spec1 = wc_kb.core.Species(species_type=prot3, compartment=nucleus)
        prot3_spec2 = wc_kb.core.Species(species_type=prot3, compartment=mito)
        prot3_spec3 = wc_kb.core.Species(species_type=prot3, compartment=membrane)

        locus4 = wc_kb.eukaryote.GenericLocus(start=10, end=18)
        transcript4 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell, gene=gene1, exons=[locus4])
        prot4 = wc_kb.eukaryote.ProteinSpeciesType(cell=cell, id='prot4', name='protein4', transcript=transcript4, coding_regions=[locus4])
        prot4_half_life = wc_kb.core.SpeciesTypeProperty(property='half-life', species_type=prot4, 
            value='40000.0', value_type=wc_ontology['WC:float'])
        prot4_spec = wc_kb.core.Species(species_type=prot4, compartment=nucleus)

        met1 = wc_kb.core.MetaboliteSpeciesType(cell=cell, id='met1', name='metabolite1')
        for i in cell.compartments:
            met1_species = wc_kb.core.Species(species_type=met1, compartment=i)
        
        complex1 = wc_kb.core.ComplexSpeciesType(cell=cell, id='complex_1', subunits=[
            wc_kb.core.SpeciesTypeCoefficient(species_type=prot1, coefficient=1),
            wc_kb.core.SpeciesTypeCoefficient(species_type=prot2, coefficient=2),
            wc_kb.core.SpeciesTypeCoefficient(species_type=prot3, coefficient=0),
            ])

        complex2 = wc_kb.core.ComplexSpeciesType(cell=cell, id='complex_2', subunits=[
            wc_kb.core.SpeciesTypeCoefficient(species_type=prot3, coefficient=2),
            wc_kb.core.SpeciesTypeCoefficient(species_type=met1, coefficient=2),
            ])

        complex3 = wc_kb.core.ComplexSpeciesType(cell=cell, id='complex_3', subunits=[
            wc_kb.core.SpeciesTypeCoefficient(species_type=prot4, coefficient=2),
            ])                

        # Create initial model content
        self.model = model = wc_lang.Model()
        
        model.parameters.create(id='Avogadro', value = scipy.constants.Avogadro,
                                units = unit_registry.parse_units('molecule mol^-1'))

        compartments = {'n': ('nucleus', 5E-14), 'm': ('mitochondria', 2.5E-14), 'l': ('lysosome', 2.5E-14), 'c_m': ('membrane', 5E-15)}
        for k, v in compartments.items():
            init_volume = wc_lang.core.InitVolume(distribution=wc_ontology['WC:normal_distribution'], 
                    mean=v[1], std=0)
            c = model.compartments.create(id=k, name=v[0], init_volume=init_volume)
            c.init_density = model.parameters.create(id='density_' + k, value=1000, 
                units=unit_registry.parse_units('g l^-1'))
            volume = model.functions.create(id='volume_' + k, units=unit_registry.parse_units('l'))
            volume.expression, error = wc_lang.FunctionExpression.deserialize(f'{c.id} / {c.init_density.id}', {
                wc_lang.Compartment: {c.id: c},
                wc_lang.Parameter: {c.init_density.id: c.init_density},
                })
            assert error is None, str(error)

        for i in cell.species_types.get(__type=wc_kb.eukaryote.ProteinSpeciesType):
            model_species_type = model.species_types.get_or_create(id=i.id, name=i.name, type=wc_ontology['WC:protein'])
            model_compartment = model.compartments.get_one(id='n')
            model_species = model.species.get_or_create(species_type=model_species_type, compartment=model_compartment)
            model_species.id = model_species.gen_id()
            conc_model = model.distribution_init_concentrations.get_or_create(species=model_species, 
                mean=10, units=unit_registry.parse_units('molecule'))
            conc_model.id = conc_model.gen_id()

        model_species_type = model.species_types.get_or_create(id='prot3', name='protein3', type=wc_ontology['WC:protein'])
        model_mito = model.compartments.get_one(id='m')
        model_species = model.species.get_or_create(species_type=model_species_type, compartment=model_mito)
        model_species.id = model_species.gen_id()
        conc_model = model.distribution_init_concentrations.create(species=model_species, 
            mean=20, units=unit_registry.parse_units('molecule'))
        conc_model.id = conc_model.gen_id()        
        
        model_membrane = model.compartments.get_one(id='c_m')
        model_species = model.species.get_or_create(species_type=model_species_type, compartment=model_membrane)
        model_species.id = model_species.gen_id()
        conc_model = model.distribution_init_concentrations.create(species=model_species, 
            mean=20, units=unit_registry.parse_units('molecule'))
        conc_model.id = conc_model.gen_id()

        model_species_type = model.species_types.get_or_create(id='met1', name='metabolite1', type=wc_ontology['WC:metabolite'])
        for compartment in model.compartments:
            model_species = model.species.get_or_create(species_type=model_species_type, compartment=compartment)
            model_species.id = model_species.gen_id()

        for compl in [complex1, complex2, complex3]:
            model_species_type = model.species_types.create(id=compl.id, type=wc_ontology['WC:pseudo_species'])
            subunit_compartments = [[s.compartment.id for s in sub.species_type.species]
                for sub in compl.subunits]
            if len(subunit_compartments) == 1:
                shared_compartments = set(subunit_compartments[0])
            else:    
                shared_compartments = set([])
                for i in range(len(subunit_compartments)):
                    shared_compartments = (set(subunit_compartments[i])
                        if i==0 else shared_compartments).intersection(
                        set(subunit_compartments[i+1]) if i<(len(subunit_compartments)-1) else shared_compartments)            
            compartment_ids = set(list(shared_compartments))
            for compartment_id in compartment_ids:
                model_compartment = model.compartments.get_one(id=compartment_id)
                model_species = model.species.get_or_create(species_type=model_species_type, compartment=model_compartment)
                model_species.id = model_species.gen_id()

        metabolic_participants = ['Ala', 'Cys', 'Asp', 'Glu', 'Selcys', 'h2o']
        metabolic_compartments = ['l', 'm']
        for i in metabolic_participants:
            for c in metabolic_compartments:
                model_species_type = model.species_types.get_or_create(id=i, type=wc_ontology['WC:metabolite'])            
                model_compartment = model.compartments.get_one(id=c)
                model_species = model.species.get_or_create(species_type=model_species_type, compartment=model_compartment)
                model_species.id = model_species.gen_id()
Пример #9
0
    def test_gen_mass_action_rate_law(self):
        model = wc_lang.Model()
        c = wc_lang.Compartment(id='c',
                                init_volume=wc_lang.InitVolume(mean=0.5))
        c.init_density = wc_lang.Parameter(id='density_' + c.id, value=1.)
        kinetic_parameter = wc_lang.Parameter(id='this_parameter', value=1.)
        volume = wc_lang.Function(id='volume_' + c.id)
        volume.expression, error = wc_lang.FunctionExpression.deserialize(
            f'{c.id} / {c.init_density.id}', {
                wc_lang.Compartment: {
                    c.id: c
                },
                wc_lang.Parameter: {
                    c.init_density.id: c.init_density
                },
            })
        assert error is None, str(error)

        species_types = {}
        species = {}
        for i in range(1, 7):
            Id = 's' + str(i)
            species_types[Id] = wc_lang.SpeciesType(id=Id)
            species[Id + '_c'] = wc_lang.Species(
                species_type=species_types[Id], compartment=c)
            wc_lang.DistributionInitConcentration(species=species[Id + '_c'],
                                                  mean=0.5)
        Id = 'e'
        species_types[Id] = wc_lang.SpeciesType(id=Id)
        species[Id + '_c'] = wc_lang.Species(species_type=species_types[Id],
                                             compartment=c)
        wc_lang.DistributionInitConcentration(species=species[Id + '_c'],
                                              mean=0.5)

        # ob_exp1, error = wc_lang.ObservableExpression.deserialize('s4[c] + s5[c]', {
        #     wc_lang.Species:{species['s4_c'].gen_id(): species['s4_c'],
        #                     species['s5_c'].gen_id(): species['s5_c']}})
        # assert error is None, str(error)
        # modifier1 = wc_lang.Observable(id='e1', expression=ob_exp1)

        # ob_exp2, error = wc_lang.ObservableExpression.deserialize('2 * s6[c]', {
        #     wc_lang.Species:{species['s6_c'].gen_id(): species['s6_c']}})
        # assert error is None, str(error)
        # modifier2 = wc_lang.Observable(id='e2', expression=ob_exp2)

        participant1 = wc_lang.SpeciesCoefficient(species=species['s1_c'],
                                                  coefficient=-1)
        participant2 = wc_lang.SpeciesCoefficient(species=species['s2_c'],
                                                  coefficient=-1)
        participant3 = wc_lang.SpeciesCoefficient(species=species['s3_c'],
                                                  coefficient=1)
        participant4 = wc_lang.SpeciesCoefficient(species=species['s4_c'],
                                                  coefficient=1)
        enzyme_lhs = wc_lang.SpeciesCoefficient(species=species['e_c'],
                                                coefficient=-1)
        enzyme_rhs = wc_lang.SpeciesCoefficient(species=species['e_c'],
                                                coefficient=1)

        reaction = wc_lang.Reaction(
            id='Assosication',
            participants=[participant1, participant2, participant3])
        rate_law, parameters = utils.gen_mass_action_rate_law(
            model, reaction, kinetic_parameter)
        self.assertTrue(
            rate_law.expression == 'this_parameter * s1[c] * s2[c]'
            or rate_law.expression == 'this_parameter * s2[c] * s1[c]')
        self.assertEqual(set([i.gen_id() for i in rate_law.species]),
                         set(['s1[c]', 's2[c]']))
        # self.assertEqual(set(rate_law.observables), set([modifier1, modifier2]))
        self.assertEqual(set(rate_law.parameters), set(parameters))
        # self.assertEqual(rate_law.parameters.get_one(id='k_r1').type, wc_ontology['WC:k_cat'])
        self.assertEqual(
            rate_law.parameters.get_one(id='this_parameter').units,
            unit_registry.parse_units('s^-1 * molecule^-1'))
        # self.assertEqual(rate_law.parameters.get_one(id='K_m_r1_s2').type, wc_ontology['WC:K_m'])
        # self.assertEqual(rate_law.parameters.get_one(id='K_m_r1_s2').units, unit_registry.parse_units('M'))

        reaction = wc_lang.Reaction(
            id='Dissociation',
            participants=[participant1, participant3, participant4])
        rate_law, parameters = utils.gen_mass_action_rate_law(
            model, reaction, kinetic_parameter)
        self.assertEqual(rate_law.expression, 'this_parameter * s1[c]')
        self.assertEqual(set([i.gen_id() for i in rate_law.species]),
                         set(['s1[c]']))
        self.assertEqual(
            rate_law.parameters.get_one(id='this_parameter').units,
            unit_registry.parse_units('s^-1'))

        reaction = wc_lang.Reaction(id='Degradation1',
                                    participants=[participant1])
        rate_law, parameters = utils.gen_mass_action_rate_law(
            model, reaction, kinetic_parameter)
        self.assertEqual(rate_law.expression, 'this_parameter * s1[c]')
        self.assertEqual(set([i.gen_id() for i in rate_law.species]),
                         set(['s1[c]']))
        self.assertEqual(
            rate_law.parameters.get_one(id='this_parameter').units,
            unit_registry.parse_units('s^-1'))

        reaction = wc_lang.Reaction(
            id='Degradation2',
            participants=[participant1, enzyme_lhs, enzyme_rhs])
        rate_law, parameters = utils.gen_mass_action_rate_law(
            model, reaction, kinetic_parameter)
        self.assertTrue(
            rate_law.expression, 'this_parameter * s1[c] * e[c]'
            or 'this_parameter * e[c] * s1[c]')
        self.assertEqual(set([i.gen_id() for i in rate_law.species]),
                         set(['s1[c]', 'e[c]']))
        self.assertEqual(
            rate_law.parameters.get_one(id='this_parameter').units,
            unit_registry.parse_units('s^-1 * molecule^-1'))

        reaction = wc_lang.Reaction(id='Synthesis1',
                                    participants=[participant3])
        rate_law, parameters = utils.gen_mass_action_rate_law(
            model, reaction, kinetic_parameter)
        self.assertEqual(rate_law.expression, 'this_parameter')
        self.assertEqual(set([i.gen_id() for i in rate_law.species]), set([]))
        self.assertEqual(
            rate_law.parameters.get_one(id='this_parameter').units,
            unit_registry.parse_units('s^-1 * molecule'))

        reaction = wc_lang.Reaction(
            id='Synthesis2',
            participants=[enzyme_lhs, enzyme_rhs, participant3])
        rate_law, parameters = utils.gen_mass_action_rate_law(
            model, reaction, kinetic_parameter)
        self.assertEqual(rate_law.expression, 'this_parameter * e[c]')
        self.assertEqual(set([i.gen_id() for i in rate_law.species]),
                         set(['e[c]']))
        self.assertEqual(
            rate_law.parameters.get_one(id='this_parameter').units,
            unit_registry.parse_units('s^-1'))

        reaction = wc_lang.Reaction(
            id='Conversion',
            participants=[participant1, enzyme_lhs, enzyme_rhs, participant3]
        )  # Ask Yin Hoon why I can add as many copies of participant2 as I want.
        rate_law, parameters = utils.gen_mass_action_rate_law(
            model, reaction, kinetic_parameter)
        self.assertTrue(
            rate_law.expression == 'this_parameter * s1[c] * e[c]'
            or rate_law.expression == 'this_parameter * e[c] * s1[c]')
        self.assertEqual(set([i.gen_id() for i in rate_law.species]),
                         set(['s1[c]', 'e[c]']))
        self.assertEqual(
            rate_law.parameters.get_one(id='this_parameter').units,
            unit_registry.parse_units('s^-1 * molecule^-1'))
Пример #10
0
    def test_gen_response_functions(self):
        model = wc_lang.Model()
        beta = 2

        init_volume = wc_lang.core.InitVolume(
            distribution=wc_ontology['WC:normal_distribution'],
            mean=0.5,
            std=0)
        c = wc_lang.Compartment(id='c',
                                name='cytosol',
                                init_volume=init_volume)
        c.init_density = wc_lang.Parameter(id='density_' + c.id, value=1.)

        volume = wc_lang.Function(id='volume_' + c.id)
        volume.expression, error = wc_lang.FunctionExpression.deserialize(
            f'{c.id} / {c.init_density.id}', {
                wc_lang.Compartment: {
                    c.id: c
                },
                wc_lang.Parameter: {
                    c.init_density.id: c.init_density
                },
            })
        assert error is None, str(error)

        reaction = wc_lang.Reaction()

        species_types = {}
        species = {}
        for i in range(1, 5):
            Id = 's' + str(i)
            species_types[Id] = wc_lang.SpeciesType(
                model=model, id=Id, name='species_type_{}'.format(i))
            model_species = wc_lang.Species(model=model,
                                            species_type=species_types[Id],
                                            compartment=c)
            model_species.id = model_species.gen_id()
            species[Id + '_c'] = model_species
            wc_lang.DistributionInitConcentration(species=species[Id + '_c'],
                                                  mean=0.5)

        factors = [['s1', 'species_type_2'], ['s3'], ['species_type_4']]
        factor_exp, all_species, all_parameters, all_volumes, all_observables = utils.gen_response_functions(
            model, beta, 'reaction_id', 'reaction_class', c, factors)

        self.assertEqual(factor_exp, [
            '(reaction_class_factors_c_1 / (reaction_class_factors_c_1 + K_m_reaction_class_reaction_class_factors_c_1 * Avogadro * volume_c))',
            '(s3[c] / (s3[c] + K_m_reaction_id_s3 * Avogadro * volume_c))',
            '(s4[c] / (s4[c] + K_m_reaction_id_s4 * Avogadro * volume_c))'
        ])
        self.assertEqual(
            all_species, {
                's1[c]': species['s1_c'],
                's2[c]': species['s2_c'],
                's3[c]': species['s3_c'],
                's4[c]': species['s4_c']
            })
        self.assertEqual(len(all_parameters), 4)
        self.assertEqual(all_parameters['Avogadro'].value,
                         scipy.constants.Avogadro)
        self.assertEqual(all_parameters['Avogadro'].units,
                         unit_registry.parse_units('molecule mol^-1'))
        self.assertEqual(
            all_parameters['K_m_reaction_class_reaction_class_factors_c_1'].
            value, beta * 1. / scipy.constants.Avogadro / c.init_volume.mean)
        self.assertEqual(
            all_parameters['K_m_reaction_class_reaction_class_factors_c_1'].
            comments,
            'The value was assumed to be 2 times the value of reaction_class_factors_c_1'
        )
        self.assertEqual(
            all_parameters['K_m_reaction_id_s3'].value,
            beta * 0.5 / scipy.constants.Avogadro / c.init_volume.mean)
        self.assertEqual(all_parameters['K_m_reaction_id_s4'].type,
                         wc_ontology['WC:K_m'])
        self.assertEqual(all_parameters['K_m_reaction_id_s4'].units,
                         unit_registry.parse_units('M'))
        self.assertEqual(
            all_parameters['K_m_reaction_id_s4'].comments,
            'The value was assumed to be 2 times the concentration of s4 in cytosol'
        )
        self.assertEqual(all_volumes, {'volume_c': volume})
        self.assertEqual(len(all_observables), 1)
        self.assertEqual(len(model.observables), 1)
        self.assertEqual(all_observables['reaction_class_factors_c_1'].name,
                         'factor for reaction_class in cytosol')
        self.assertEqual(all_observables['reaction_class_factors_c_1'].units,
                         unit_registry.parse_units('molecule'))
        self.assertEqual(
            all_observables['reaction_class_factors_c_1'].expression.
            expression, 's1[c] + s2[c]')

        for i in range(5, 9):
            Id = 's' + str(i)
            species_types[Id] = wc_lang.SpeciesType(
                model=model, id=Id, name='species_type_{}'.format(i))
            model_species = wc_lang.Species(model=model,
                                            species_type=species_types[Id],
                                            compartment=c)
            model_species.id = model_species.gen_id()
            species[Id + '_c'] = model_species
            wc_lang.DistributionInitConcentration(species=species[Id + '_c'],
                                                  mean=0.)

        factors = [['s5', 'species_type_6'], ['s7'], ['species_type_8']]
        factor_exp, all_species, all_parameters, all_volumes, all_observables = utils.gen_response_functions(
            model, beta, 'reaction_id', 'reaction_class', c, factors)

        self.assertEqual(len(model.observables), 2)
        self.assertEqual(
            all_parameters['K_m_reaction_class_reaction_class_factors_c_2'].
            value, 1e-05)
        self.assertEqual(
            all_parameters['K_m_reaction_class_reaction_class_factors_c_2'].
            comments,
            'The value was assigned to 1e-05 because the value of reaction_class_factors_c_2 was zero'
        )
        self.assertEqual(all_parameters['K_m_reaction_id_s7'].value, 1e-05)
        self.assertEqual(
            all_parameters['K_m_reaction_id_s8'].comments,
            'The value was assigned to 1e-05 because the concentration of s8 in cytosol was zero'
        )

        factors = [['s5', 'species_type_6']]
        factor_exp, all_species, all_parameters, all_volumes, all_observables = utils.gen_response_functions(
            model, beta, 'reaction_id2', 'reaction_class2', c, factors)

        self.assertEqual(len(model.observables), 2)
        self.assertEqual(
            all_parameters['K_m_reaction_class2_reaction_class_factors_c_2'].
            value, 1e-05)
Пример #11
0
    def test_gen_michaelis_menten_like_propensity_function(self):
        model = wc_lang.Model()

        init_volume = wc_lang.core.InitVolume(
            distribution=wc_ontology['WC:normal_distribution'],
            mean=0.5,
            std=0)
        c = wc_lang.Compartment(id='c', init_volume=init_volume)
        c.init_density = wc_lang.Parameter(id='density_' + c.id, value=1.)

        volume = wc_lang.Function(id='volume_' + c.id)
        volume.expression, error = wc_lang.FunctionExpression.deserialize(
            f'{c.id} / {c.init_density.id}', {
                wc_lang.Compartment: {
                    c.id: c
                },
                wc_lang.Parameter: {
                    c.init_density.id: c.init_density
                },
            })
        assert error is None, str(error)

        species_types = {}
        species = {}
        for i in range(1, 7):
            Id = 's' + str(i)
            species_types[Id] = wc_lang.SpeciesType(id=Id)
            model_species = wc_lang.Species(species_type=species_types[Id],
                                            compartment=c)
            model_species.id = model_species.gen_id()
            species[Id + '_c'] = model_species
            wc_lang.DistributionInitConcentration(species=species[Id + '_c'],
                                                  mean=0.5)

        participant1 = wc_lang.SpeciesCoefficient(species=species['s1_c'],
                                                  coefficient=-1)
        participant2 = wc_lang.SpeciesCoefficient(species=species['s2_c'],
                                                  coefficient=-1)
        participant3 = wc_lang.SpeciesCoefficient(species=species['s3_c'],
                                                  coefficient=-1)
        participant4 = wc_lang.SpeciesCoefficient(species=species['s4_c'],
                                                  coefficient=-1)
        participant5 = wc_lang.SpeciesCoefficient(species=species['s5_c'],
                                                  coefficient=1)
        participant6 = wc_lang.SpeciesCoefficient(species=species['s6_c'],
                                                  coefficient=1)

        reaction = wc_lang.Reaction(id='r1',
                                    participants=[
                                        participant1, participant2,
                                        participant3, participant4,
                                        participant5, participant6
                                    ])

        with self.assertRaises(ValueError):
            rate_law1, parameters = utils.gen_michaelis_menten_like_propensity_function(
                model, reaction)

        rate_law2, parameters = utils.gen_michaelis_menten_like_propensity_function(
            model, reaction, substrates_as_modifiers=[species['s3_c']])
        self.assertEqual(
            rate_law2.expression, 'k_cat_r1 * s3[c] * '
            '(s1[c] / (s1[c] + K_m_r1_s1 * Avogadro * volume_c)) * '
            '(s2[c] / (s2[c] + K_m_r1_s2 * Avogadro * volume_c)) * '
            '(s4[c] / (s4[c] + K_m_r1_s4 * Avogadro * volume_c))')
        self.assertEqual(set([i.gen_id() for i in rate_law2.species]),
                         set(['s1[c]', 's2[c]', 's3[c]', 's4[c]']))
        self.assertEqual(set(rate_law2.parameters), set(parameters))
        self.assertEqual(
            rate_law2.parameters.get_one(id='k_cat_r1').type,
            wc_ontology['WC:k_cat'])
        self.assertEqual(
            rate_law2.parameters.get_one(id='k_cat_r1').units,
            unit_registry.parse_units('s^-1 molecule^-1'))
        self.assertEqual(
            rate_law2.parameters.get_one(id='K_m_r1_s2').type,
            wc_ontology['WC:K_m'])
        self.assertEqual(
            rate_law2.parameters.get_one(id='K_m_r1_s2').units,
            unit_registry.parse_units('M'))

        rate_law3, parameters = utils.gen_michaelis_menten_like_propensity_function(
            model,
            reaction,
            substrates_as_modifiers=[species['s3_c']],
            exclude_substrates=[species['s1_c']])
        self.assertEqual(
            rate_law3.expression, 'k_cat_r1 * s3[c] * '
            '(s2[c] / (s2[c] + K_m_r1_s2 * Avogadro * volume_c)) * '
            '(s4[c] / (s4[c] + K_m_r1_s4 * Avogadro * volume_c))')
        self.assertEqual(set([i.gen_id() for i in rate_law3.species]),
                         set(['s2[c]', 's3[c]', 's4[c]']))
        self.assertEqual(set(rate_law3.parameters), set(parameters))
Пример #12
0
    def test_test_metabolite_production(self):

        model = wc_lang.Model()
        submodel = wc_lang.Submodel(model=model, id='metabolism')
        compartment = model.compartments.create(id='c')

        for i in ['o2', 'h2o', 'atp']:
            st = model.species_types.create(id=i)
            species = model.species.create(species_type=st,
                                           compartment=compartment)
            species.id = species.gen_id()

        R1 = model.reactions.create(submodel=submodel, id='Ex_o2')
        R1.participants.add(
            model.species.get_one(
                id='o2[c]').species_coefficients.get_or_create(
                    coefficient=1.0))

        R2 = model.reactions.create(submodel=submodel, id='Ex_h2o')
        R2.participants.add(
            model.species.get_one(
                id='h2o[c]').species_coefficients.get_or_create(
                    coefficient=1.0))

        R3 = model.reactions.create(submodel=submodel, id='Ex_atp')
        R3.participants.add(
            model.species.get_one(
                id='atp[c]').species_coefficients.get_or_create(
                    coefficient=-1.0))

        biomass_reaction = model.reactions.create(submodel=submodel,
                                                  id='biomass_reaction')
        biomass_reaction.participants.add(
            model.species.get_one(
                id='o2[c]').species_coefficients.get_or_create(
                    coefficient=-1.0))
        biomass_reaction.participants.add(
            model.species.get_one(
                id='h2o[c]').species_coefficients.get_or_create(
                    coefficient=-1.0))
        biomass_reaction.participants.add(
            model.species.get_one(
                id='atp[c]').species_coefficients.get_or_create(
                    coefficient=1.0))

        submodel.dfba_obj = wc_lang.DfbaObjective(model=model)
        submodel.dfba_obj.id = submodel.dfba_obj.gen_id()
        obj_expression = biomass_reaction.id
        dfba_obj_expression, error = wc_lang.DfbaObjectiveExpression.deserialize(
            obj_expression,
            {wc_lang.Reaction: {
                biomass_reaction.id: biomass_reaction
            }})
        assert error is None, str(error)
        submodel.dfba_obj.expression = dfba_obj_expression

        reaction_bounds = {i.id: (0., 1000.) for i in model.reactions}

        unproducibles, unrecyclables = utils.test_metabolite_production(
            submodel, reaction_bounds, pseudo_reactions=['biomass_reaction'])

        self.assertEqual(unproducibles, [])
        self.assertEqual(unrecyclables, [])

        unproducibles, unrecyclables = utils.test_metabolite_production(
            submodel, reaction_bounds)

        self.assertEqual(unproducibles, [])
        self.assertEqual(unrecyclables, [])

        mock1 = model.species.create(id='mock1')
        mock2 = model.species.create(id='mock2')
        biomass_reaction.participants.add(
            mock1.species_coefficients.get_or_create(coefficient=1.0))
        biomass_reaction.participants.add(
            mock2.species_coefficients.get_or_create(coefficient=-1.0))

        unproducibles, unrecyclables = utils.test_metabolite_production(
            submodel, reaction_bounds)

        self.assertEqual(unproducibles, ['mock2'])
        self.assertEqual(unrecyclables, ['mock1'])

        unproducibles, unrecyclables = utils.test_metabolite_production(
            submodel,
            reaction_bounds,
            pseudo_reactions=['biomass_reaction'],
            test_producibles=['mock1'],
            test_recyclables=['mock2'])

        self.assertEqual(unproducibles, ['mock1'])
        self.assertEqual(unrecyclables, ['mock2'])

        unproducibles, unrecyclables = utils.test_metabolite_production(
            submodel,
            reaction_bounds,
            test_producibles=['mock1'],
            test_recyclables=['mock2'])

        self.assertEqual(unproducibles, [])
        self.assertEqual(unrecyclables, [])

        R4 = model.reactions.create(submodel=submodel, id='Ex_mock1')
        R4.participants.add(
            mock1.species_coefficients.get_or_create(coefficient=-1.0))

        R5 = model.reactions.create(submodel=submodel, id='Ex_mock2')
        R5.participants.add(
            mock2.species_coefficients.get_or_create(coefficient=1.0))

        reaction_bounds = {i.id: (0., 1000.) for i in model.reactions}

        unproducibles, unrecyclables = utils.test_metabolite_production(
            submodel, reaction_bounds)

        self.assertEqual(unproducibles, [])
        self.assertEqual(unrecyclables, [])
Пример #13
0
    def test_gen_michaelis_menten_like_rate_law(self):
        model = wc_lang.Model()

        init_volume = wc_lang.core.InitVolume(
            distribution=wc_ontology['WC:normal_distribution'],
            mean=0.5,
            std=0)
        c = wc_lang.Compartment(id='c', init_volume=init_volume)
        c.init_density = wc_lang.Parameter(id='density_' + c.id, value=1.)

        volume = wc_lang.Function(id='volume_' + c.id)
        volume.expression, error = wc_lang.FunctionExpression.deserialize(
            f'{c.id} / {c.init_density.id}', {
                wc_lang.Compartment: {
                    c.id: c
                },
                wc_lang.Parameter: {
                    c.init_density.id: c.init_density
                },
            })
        assert error is None, str(error)

        species_types = {}
        species = {}
        for i in range(1, 7):
            Id = 's' + str(i)
            species_types[Id] = wc_lang.SpeciesType(id=Id)
            species[Id + '_c'] = wc_lang.Species(
                species_type=species_types[Id], compartment=c)
            wc_lang.DistributionInitConcentration(species=species[Id + '_c'],
                                                  mean=0.5)

        ob_exp1, error = wc_lang.ObservableExpression.deserialize(
            's4[c] + s5[c]', {
                wc_lang.Species: {
                    species['s4_c'].gen_id(): species['s4_c'],
                    species['s5_c'].gen_id(): species['s5_c']
                }
            })
        assert error is None, str(error)
        modifier1 = wc_lang.Observable(id='e1', expression=ob_exp1)

        ob_exp2, error = wc_lang.ObservableExpression.deserialize(
            '2 * s6[c]',
            {wc_lang.Species: {
                species['s6_c'].gen_id(): species['s6_c']
            }})
        assert error is None, str(error)
        modifier2 = wc_lang.Observable(id='e2', expression=ob_exp2)

        participant1 = wc_lang.SpeciesCoefficient(species=species['s1_c'],
                                                  coefficient=-1)
        participant2 = wc_lang.SpeciesCoefficient(species=species['s2_c'],
                                                  coefficient=-1)
        participant3 = wc_lang.SpeciesCoefficient(species=species['s3_c'],
                                                  coefficient=1)
        participant4 = wc_lang.SpeciesCoefficient(species=species['s4_c'],
                                                  coefficient=-1)
        participant5 = wc_lang.SpeciesCoefficient(species=species['s4_c'],
                                                  coefficient=1)
        participant6 = wc_lang.SpeciesCoefficient(species=species['s6_c'],
                                                  coefficient=-1)
        participant7 = wc_lang.SpeciesCoefficient(species=species['s6_c'],
                                                  coefficient=-1)
        participant8 = wc_lang.SpeciesCoefficient(species=species['s6_c'],
                                                  coefficient=1)
        reaction = wc_lang.Reaction(id='r1',
                                    participants=[
                                        participant1, participant2,
                                        participant3, participant4,
                                        participant5, participant6,
                                        participant7, participant8
                                    ])

        rate_law, parameters = utils.gen_michaelis_menten_like_rate_law(
            model,
            reaction,
            modifiers=[modifier1, modifier2],
            modifier_reactants=[species['s6_c']])

        self.assertEqual(
            rate_law.expression, 'k_cat_r1 * e1 * e2 * '
            '(s1[c] / (s1[c] + K_m_r1_s1 * Avogadro * volume_c)) * '
            '(s2[c] / (s2[c] + K_m_r1_s2 * Avogadro * volume_c)) * '
            '(s6[c] / (s6[c] + K_m_r1_s6 * Avogadro * volume_c))')
        self.assertEqual(set([i.gen_id() for i in rate_law.species]),
                         set(['s1[c]', 's2[c]', 's6[c]']))
        self.assertEqual(set(rate_law.observables), set([modifier1,
                                                         modifier2]))
        self.assertEqual(set(rate_law.parameters), set(parameters))
        self.assertEqual(
            rate_law.parameters.get_one(id='k_cat_r1').type,
            wc_ontology['WC:k_cat'])
        self.assertEqual(
            rate_law.parameters.get_one(id='k_cat_r1').units,
            unit_registry.parse_units('s^-1 molecule^-2'))
        self.assertEqual(
            rate_law.parameters.get_one(id='K_m_r1_s2').type,
            wc_ontology['WC:K_m'])
        self.assertEqual(
            rate_law.parameters.get_one(id='K_m_r1_s2').units,
            unit_registry.parse_units('M'))

        reaction = wc_lang.Reaction(id='r1',
                                    participants=[
                                        participant1, participant2,
                                        participant4, participant8
                                    ])
        rate_law, parameters = utils.gen_michaelis_menten_like_rate_law(
            model, reaction)
        self.assertEqual(
            rate_law.expression, 'k_cat_r1 * '
            '(s1[c] / (s1[c] + K_m_r1_s1 * Avogadro * volume_c)) * '
            '(s2[c] / (s2[c] + K_m_r1_s2 * Avogadro * volume_c)) * '
            '(s4[c] / (s4[c] + K_m_r1_s4 * Avogadro * volume_c))')

        reaction = wc_lang.Reaction(id='r1', participants=[participant3])
        rate_law, parameters = utils.gen_michaelis_menten_like_rate_law(
            model, reaction)
        self.assertEqual(rate_law.expression, 'k_cat_r1')

        reaction = wc_lang.Reaction(id='r1',
                                    participants=[participant3, participant6])
        rate_law, parameters = utils.gen_michaelis_menten_like_rate_law(
            model, reaction, modifiers=[modifier1, species['s6_c']])
        self.assertEqual(rate_law.expression, 'k_cat_r1 * e1 * s6[c]')

        reaction = wc_lang.Reaction(id='r1',
                                    participants=[
                                        participant1, participant2,
                                        participant4, participant8
                                    ])
        rate_law, parameters = utils.gen_michaelis_menten_like_rate_law(
            model, reaction, exclude_substrates=[species['s1_c']])
        self.assertEqual(
            rate_law.expression, 'k_cat_r1 * '
            '(s2[c] / (s2[c] + K_m_r1_s2 * Avogadro * volume_c)) * '
            '(s4[c] / (s4[c] + K_m_r1_s4 * Avogadro * volume_c))')

        with self.assertRaises(TypeError) as ctx:
            rate_law, parameters = utils.gen_michaelis_menten_like_rate_law(
                model, reaction, modifiers=['s6_c'])
        self.assertEqual(
            'The modifiers contain element(s) that is not an observable or a species',
            str(ctx.exception))
    def setUp(self):

        # Create KB content
        self.tmp_dirname = tempfile.mkdtemp()
        self.sequence_path = os.path.join(self.tmp_dirname, 'test_seq.fasta')
        with open(self.sequence_path, 'w') as f:
            f.write('>chr1\nATGCATGACTCTAGTTTAT\n'
                    '>chrM\nTTTatgaCTCTAGTTTACNNN\n')

        self.kb = wc_kb.KnowledgeBase()
        cell = self.kb.cell = wc_kb.Cell()

        nucleus = cell.compartments.create(id='n')
        mito = cell.compartments.create(id='m')
        cytoplasm = cell.compartments.create(id='c')

        chr1 = wc_kb.core.DnaSpeciesType(cell=cell,
                                         id='chr1',
                                         sequence_path=self.sequence_path)
        gene1 = wc_kb.eukaryote.GeneLocus(cell=cell,
                                          id='gene1',
                                          polymer=chr1,
                                          start=1,
                                          end=19)
        exon1 = wc_kb.eukaryote.GenericLocus(start=5, end=19)
        transcript1 = wc_kb.eukaryote.TranscriptSpeciesType(
            cell=cell,
            id='trans1',
            name='transcript1',
            gene=gene1,
            exons=[exon1],
            type=wc_kb.eukaryote.TranscriptType.mRna)
        transcript1_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=transcript1,
            value='36000.0',
            value_type=wc_ontology['WC:float'])
        transcript1_spec = wc_kb.core.Species(species_type=transcript1,
                                              compartment=cytoplasm)
        transcript1_conc = wc_kb.core.Concentration(cell=cell,
                                                    species=transcript1_spec,
                                                    value=10.)

        chrM = wc_kb.core.DnaSpeciesType(cell=cell,
                                         id='chrM',
                                         sequence_path=self.sequence_path)
        gene2 = wc_kb.eukaryote.GeneLocus(cell=cell,
                                          id='gene2',
                                          polymer=chrM,
                                          start=1,
                                          end=19)
        exon2 = wc_kb.eukaryote.GenericLocus(start=1, end=10)
        transcript2 = wc_kb.eukaryote.TranscriptSpeciesType(
            cell=cell,
            id='trans2',
            name='transcript2',
            gene=gene2,
            exons=[exon2],
            type=wc_kb.eukaryote.TranscriptType.mRna)
        transcript2_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=transcript2,
            value='15000.0',
            value_type=wc_ontology['WC:float'])
        transcript2_spec = wc_kb.core.Species(species_type=transcript2,
                                              compartment=mito)
        transcript2_conc = wc_kb.core.Concentration(cell=cell,
                                                    species=transcript2_spec,
                                                    value=10.)

        gene3 = wc_kb.eukaryote.GeneLocus(cell=cell,
                                          id='gene3',
                                          polymer=chr1,
                                          start=1,
                                          end=19)
        exon3 = wc_kb.eukaryote.GenericLocus(start=1, end=15)
        transcript3 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            id='trans3',
                                                            name='transcript3',
                                                            gene=gene3,
                                                            exons=[exon3])
        transcript3_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=transcript3,
            value='36000.0',
            value_type=wc_ontology['WC:float'])
        transcript3_spec = wc_kb.core.Species(species_type=transcript3,
                                              compartment=cytoplasm)
        transcript3_conc = wc_kb.core.Concentration(cell=cell,
                                                    species=transcript3_spec,
                                                    value=10.)

        gene4 = wc_kb.eukaryote.GeneLocus(cell=cell,
                                          id='gene4',
                                          polymer=chr1,
                                          start=1,
                                          end=3)
        exon4 = wc_kb.eukaryote.GenericLocus(start=1, end=3)
        transcript4 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            id='trans4',
                                                            name='transcript4',
                                                            gene=gene4,
                                                            exons=[exon4])
        transcript4_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=transcript4,
            value='36000.0',
            value_type=wc_ontology['WC:float'])
        transcript4_spec = wc_kb.core.Species(species_type=transcript4,
                                              compartment=cytoplasm)
        transcript4_conc = wc_kb.core.Concentration(cell=cell,
                                                    species=transcript4_spec,
                                                    value=10.)

        gene5 = wc_kb.eukaryote.GeneLocus(cell=cell,
                                          id='gene5',
                                          polymer=chr1,
                                          start=1,
                                          end=3)
        exon5 = wc_kb.eukaryote.GenericLocus(start=1, end=3)
        transcript5 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            id='trans5',
                                                            name='transcript5',
                                                            gene=gene5,
                                                            exons=[exon5])
        transcript5_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=transcript5,
            value='36000.0',
            value_type=wc_ontology['WC:float'])
        transcript5_spec = wc_kb.core.Species(species_type=transcript5,
                                              compartment=cytoplasm)
        transcript5_conc = wc_kb.core.Concentration(cell=cell,
                                                    species=transcript5_spec,
                                                    value=0.)

        gene6 = wc_kb.eukaryote.GeneLocus(cell=cell,
                                          id='gene6',
                                          polymer=chr1,
                                          start=1,
                                          end=3)
        exon6 = wc_kb.eukaryote.GenericLocus(start=1, end=3)
        transcript6 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            id='trans6',
                                                            name='transcript6',
                                                            gene=gene6,
                                                            exons=[exon6])
        transcript6_half_life = wc_kb.core.SpeciesTypeProperty(
            property='half-life',
            species_type=transcript6,
            value='36000.0',
            value_type=wc_ontology['WC:float'])
        transcript6_spec = wc_kb.core.Species(species_type=transcript6,
                                              compartment=cytoplasm)
        transcript6_conc = wc_kb.core.Concentration(cell=cell,
                                                    species=transcript6_spec,
                                                    value=0.)

        transcript7 = wc_kb.eukaryote.TranscriptSpeciesType(
            cell=cell,
            id='trans7',
            name='transcript7',
            gene=gene6,
            type=wc_kb.eukaryote.TranscriptType.mRna)
        transcript7_spec = wc_kb.core.Species(species_type=transcript7,
                                              compartment=cytoplasm)
        transcript7_conc = wc_kb.core.Concentration(cell=cell,
                                                    species=transcript7_spec,
                                                    value=10.)

        transcript8 = wc_kb.eukaryote.TranscriptSpeciesType(cell=cell,
                                                            id='trans8',
                                                            name='transcript8',
                                                            gene=gene6)

        activator = wc_kb.eukaryote.ProteinSpeciesType(cell=cell,
                                                       id='activator')
        repressor = wc_kb.eukaryote.ProteinSpeciesType(cell=cell,
                                                       id='repressor')
        gene2_reg1 = gene2.regulatory_modules.create(
            transcription_factor_regulation=[
                wc_kb.eukaryote.TranscriptionFactorRegulation(
                    transcription_factor=activator,
                    direction=wc_kb.eukaryote.RegulatoryDirection.activation)
            ])
        gene2_reg2 = gene2.regulatory_modules.create(
            transcription_factor_regulation=[
                wc_kb.eukaryote.TranscriptionFactorRegulation(
                    transcription_factor=repressor,
                    direction=wc_kb.eukaryote.RegulatoryDirection.repression)
            ])

        activator2 = wc_kb.eukaryote.ProteinSpeciesType(cell=cell,
                                                        id='activator2')
        repressor2 = wc_kb.eukaryote.ProteinSpeciesType(cell=cell,
                                                        id='repressor2')
        gene6_reg1 = gene6.regulatory_modules.create(
            transcription_factor_regulation=[
                wc_kb.eukaryote.TranscriptionFactorRegulation(
                    transcription_factor=activator2,
                    direction=wc_kb.eukaryote.RegulatoryDirection.activation)
            ])
        gene6_reg2 = gene6.regulatory_modules.create(
            transcription_factor_regulation=[
                wc_kb.eukaryote.TranscriptionFactorRegulation(
                    transcription_factor=repressor2,
                    direction=wc_kb.eukaryote.RegulatoryDirection.repression)
            ])

        # Create initial model content
        self.model = model = wc_lang.Model()

        model.parameters.create(id='mean_doubling_time',
                                value=20 * 3600,
                                units=unit_registry.parse_units('s'))
        model.parameters.create(
            id='Avogadro',
            value=scipy.constants.Avogadro,
            units=unit_registry.parse_units('molecule mol^-1'))

        compartments = {
            'n': ('nucleus', 5E-14),
            'm': ('mitochondria', 2.5E-14),
            'c': ('cytoplasm', 1E-13)
        }
        for k, v in compartments.items():
            init_volume = wc_lang.core.InitVolume(
                distribution=wc_ontology['WC:normal_distribution'],
                mean=v[1],
                std=0)
            c = model.compartments.create(id=k,
                                          name=v[0],
                                          init_volume=init_volume)
            c.init_density = model.parameters.create(
                id='density_' + k,
                value=1000,
                units=unit_registry.parse_units('g l^-1'))
            volume = model.functions.create(
                id='volume_' + k, units=unit_registry.parse_units('l'))
            volume.expression, error = wc_lang.FunctionExpression.deserialize(
                f'{c.id} / {c.init_density.id}', {
                    wc_lang.Compartment: {
                        c.id: c
                    },
                    wc_lang.Parameter: {
                        c.init_density.id: c.init_density
                    },
                })
            assert error is None, str(error)

        for i in cell.species_types.get(
                __type=wc_kb.eukaryote.TranscriptSpeciesType):
            model_species_type = model.species_types.create(id=i.id)
            model_compartment = model.compartments.get_one(
                id='m' if 'M' in i.gene.polymer.id else 'c')
            model_species = model.species.get_or_create(
                species_type=model_species_type, compartment=model_compartment)
            model_species.id = model_species.gen_id()
            conc_model = model.distribution_init_concentrations.create(
                species=model_species,
                mean=10,
                units=unit_registry.parse_units('molecule'))
            conc_model.id = conc_model.gen_id()
        model.distribution_init_concentrations.get_one(
            id='dist-init-conc-trans5[c]').mean = 0.

        complexes = {
            'complex1': ('RNA Polymerase I', 'n'),
            'complex2': ('RNA Polymerase II', 'n'),
            'complex3': ('RNA Polymerase mitochondria', 'm'),
            'complex4': ('RNA Polymerase III', 'n')
        }
        for k, v in complexes.items():
            model_species_type = model.species_types.create(
                id=k,
                name=v[0],
                structure=wc_lang.ChemicalStructure(
                    empirical_formula=EmpiricalFormula('H'),
                    molecular_weight=1.018,
                    charge=1))
            model_compartment = model.compartments.get_one(id=v[1])
            model_species = model.species.get_or_create(
                species_type=model_species_type, compartment=model_compartment)
            model_species.id = model_species.gen_id()
            conc_model = model.distribution_init_concentrations.create(
                species=model_species,
                mean=2500 if k == 'complex2' else 100,
                units=unit_registry.parse_units('molecule'))
            conc_model.id = conc_model.gen_id()

        metabolic_participants = [
            'atp', 'ctp', 'gtp', 'utp', 'ppi', 'amp', 'cmp', 'gmp', 'ump',
            'h2o', 'h', 'adp', 'pi'
        ]
        for i in metabolic_participants:
            model_species_type = model.species_types.create(id=i,
                                                            name=i.upper())
            for c in ['n', 'm']:
                model_compartment = model.compartments.get_one(id=c)
                model_species = model.species.get_or_create(
                    species_type=model_species_type,
                    compartment=model_compartment)
                model_species.id = model_species.gen_id()
                conc_model = model.distribution_init_concentrations.create(
                    species=model_species,
                    mean=1500,
                    units=unit_registry.parse_units('molecule'))
                conc_model.id = conc_model.gen_id()

        for i in ['activator', 'repressor']:
            model_species_type = model.species_types.create(id=i,
                                                            name=i.upper())
            model_compartment = model.compartments.get_one(id='m')
            model_species = model.species.get_or_create(
                species_type=model_species_type, compartment=model_compartment)
            model_species.id = model_species.gen_id()
            conc_model = model.distribution_init_concentrations.create(
                species=model_species,
                mean=3,
                units=unit_registry.parse_units('molecule'))
            conc_model.id = conc_model.gen_id()

        for i in ['activator2', 'repressor2']:
            model_species_type = model.species_types.create(id=i,
                                                            name=i.upper())
            model_compartment = model.compartments.get_one(id='n')
            model_species = model.species.get_or_create(
                species_type=model_species_type, compartment=model_compartment)
            model_species.id = model_species.gen_id()
            conc_model = model.distribution_init_concentrations.create(
                species=model_species,
                mean=0,
                units=unit_registry.parse_units('molecule'))
            conc_model.id = conc_model.gen_id()

        factors = [
            'pol1_init_factor1', 'pol1_el_factor1', 'pol2_init_factor1',
            'pol2_el_factor1', 'pol2_neg_factor1', 'pol3_init_factor1',
            'pol3_el_factor1', 'polm_init_factor1', 'polm_el_factor1'
        ]
        for i in factors:
            model_species_type = model.species_types.create(id=i,
                                                            name=i.upper())
            model_compartment = model.compartments.get_one(
                id='m' if 'polm' in i else 'n')
            model_species = model.species.get_or_create(
                species_type=model_species_type, compartment=model_compartment)
            model_species.id = model_species.gen_id()
            conc_model = model.distribution_init_concentrations.create(
                species=model_species,
                mean=2,
                units=unit_registry.parse_units('molecule'))
            conc_model.id = conc_model.gen_id()
Пример #15
0
    def test_sample_copy_num_from_concentration(self):
        model = wc_lang.Model()

        submodel = model.submodels.create(
            id='submodel',
            framework=onto['WC:stochastic_simulation_algorithm'])

        compartment_c = model.compartments.create(
            id='c', init_volume=wc_lang.InitVolume(mean=1.))

        structure = wc_lang.ChemicalStructure(molecular_weight=10.)

        species_types = {}
        cus_species_types = {}
        for cu in wc_lang.DistributionInitConcentration.units.choices:
            id = str(cu).replace(' ', '_')
            species_types[id] = model.species_types.create(id=id,
                                                           structure=structure)
            cus_species_types[id] = cu

        for other in ['no_units', 'no_concentration', 'no_std']:
            species_types[other] = model.species_types.create(
                id=other, structure=structure)

        species = {}
        for key, species_type in species_types.items():
            species[key] = wc_lang.Species(species_type=species_type,
                                           compartment=compartment_c)
            species[key].id = species[key].gen_id()

        conc_value = 2_000.
        std_value = 0.
        for key, sp in species.items():
            if key in cus_species_types:
                wc_lang.DistributionInitConcentration(
                    species=sp,
                    mean=conc_value,
                    std=std_value,
                    units=cus_species_types[key])
            elif key == 'no_units':
                wc_lang.DistributionInitConcentration(species=sp,
                                                      mean=conc_value,
                                                      std=std_value)
            elif key == 'no_std':
                wc_lang.DistributionInitConcentration(
                    species=sp,
                    mean=conc_value,
                    std=float('NaN'),
                    units=cus_species_types['molecule'])
            elif key == 'no_concentration':
                continue

        conc_to_molecules = ModelUtilities.sample_copy_num_from_concentration
        random_state = numpy.random.RandomState()
        copy_number = conc_to_molecules(
            species['molecule'],
            species['molecule'].compartment.init_volume.mean, random_state)
        self.assertEqual(copy_number, conc_value)
        copy_number = conc_to_molecules(
            species['molar'], species['molar'].compartment.init_volume.mean,
            random_state)
        self.assertEqual(copy_number, conc_value * Avogadro)
        copy_number = conc_to_molecules(
            species['no_units'],
            species['no_units'].compartment.init_volume.mean, random_state)
        self.assertEqual(copy_number, conc_value * Avogadro)
        copy_number = conc_to_molecules(
            species['millimolar'],
            species['millimolar'].compartment.init_volume.mean, random_state)
        self.assertEqual(copy_number, 10**-3 * conc_value * Avogadro)
        copy_number = conc_to_molecules(
            species['micromolar'],
            species['micromolar'].compartment.init_volume.mean, random_state)
        self.assertEqual(copy_number, 10**-6 * conc_value * Avogadro)
        copy_number = conc_to_molecules(
            species['nanomolar'],
            species['nanomolar'].compartment.init_volume.mean, random_state)
        self.assertEqual(copy_number, 10**-9 * conc_value * Avogadro)
        copy_number = conc_to_molecules(
            species['picomolar'],
            species['picomolar'].compartment.init_volume.mean, random_state)
        self.assertEqual(copy_number, 10**-12 * conc_value * Avogadro)
        copy_number = conc_to_molecules(
            species['femtomolar'],
            species['femtomolar'].compartment.init_volume.mean, random_state)
        self.assertAlmostEqual(copy_number,
                               10**-15 * conc_value * Avogadro,
                               delta=1)
        copy_number = conc_to_molecules(
            species['attomolar'],
            species['attomolar'].compartment.init_volume.mean, random_state)
        self.assertAlmostEqual(copy_number,
                               10**-18 * conc_value * Avogadro,
                               delta=1)
        copy_number = conc_to_molecules(
            species['no_concentration'],
            species['no_concentration'].compartment.init_volume.mean,
            random_state)
        self.assertEqual(copy_number, 0)
        conc = species['no_std'].distribution_init_concentration
        copy_number = conc_to_molecules(
            species['no_std'], species['no_std'].compartment.init_volume.mean,
            random_state)
        self.assertNotEqual(copy_number, conc_value)

        with self.assertRaises(KeyError):
            conc_to_molecules(
                species['mol dm^-2'],
                species['no_concentration'].compartment.init_volume.mean,
                random_state)

        species_tmp = wc_lang.Species(species_type=species_type,
                                      compartment=compartment_c)
        species_tmp.id = species_tmp.gen_id()
        wc_lang.DistributionInitConcentration(
            species=species_tmp,
            mean=conc_value,
            std=std_value,
            units='not type(unit_registry.Unit)')
        with self.assertRaisesRegex(ValueError, 'Unsupported unit type'):
            conc_to_molecules(species_tmp,
                              species_tmp.compartment.init_volume.mean,
                              random_state)

        species_tmp2 = wc_lang.Species(species_type=species_type,
                                       compartment=compartment_c)
        species_tmp2.id = species_tmp2.gen_id()
        wc_lang.DistributionInitConcentration(
            species=species_tmp2,
            mean=conc_value,
            std=std_value,
            units=wc_lang.InitVolume.units.choices[0])
        with self.assertRaisesRegex(ValueError, 'Unsupported unit'):
            conc_to_molecules(species_tmp2,
                              species_tmp2.compartment.init_volume.mean,
                              random_state)