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'))
def test_unbounded_paths(self): num_rxn = 8 # irrreversible reactions # unbounded network self.create_reaction_network(self.dfba_submodel, 'ring', **{'num_rxn': num_rxn, 'reversible': False, 'flux_max': float('inf')}) path_len = 2*num_rxn-1 g = self.model_analysis.get_digraph(self.dfba_submodel) paths = self.model_analysis.unbounded_paths(g, self.species[0], [self.species[num_rxn-1]]) self.assertEqual(len(paths), 1) self.assertEqual(len(paths[0]), path_len) # bounded network self.create_reaction_network(self.dfba_submodel, 'ring', **{'num_rxn': num_rxn, 'reversible': False}) g = self.model_analysis.get_digraph(self.dfba_submodel) paths = self.model_analysis.unbounded_paths(g, self.species[0], [self.species[num_rxn-1]], min_non_finite_ub=self.default_flux_max+1) self.assertEqual(len(paths), 0) # reversible reactions, paths on both sides of ring # unbounded network self.create_reaction_network(self.dfba_submodel, 'ring', **{'num_rxn': num_rxn, 'reversible': True, 'flux_max': float('inf')}) g = self.model_analysis.get_digraph(self.dfba_submodel) paths = self.model_analysis.unbounded_paths(g, self.species[0], [self.species[num_rxn//2]]) self.assertEqual(len(paths), 2) for p in paths: self.assertEqual(len(p), num_rxn+1) # bounded network self.create_reaction_network(self.dfba_submodel, 'ring', **{'num_rxn': num_rxn, 'reversible': True}) g = self.model_analysis.get_digraph(self.dfba_submodel) paths = self.model_analysis.unbounded_paths(g, self.species[0], [self.species[num_rxn//2]], min_non_finite_ub=self.default_flux_max+1) self.assertEqual(len(paths), 0) # test exceptions with self.assertRaisesRegex(ValueError, "'ex_species' should be a wc_lang.Species instance, but "): self.model_analysis.unbounded_paths(None, 'species', None) with self.assertRaisesRegex(ValueError, "elements of 'obj_fn_species' should be wc_lang.Species instances, but "): self.model_analysis.unbounded_paths(None, wc_lang.Species(), ['species'])
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)
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
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'))
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)
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))
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 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)