Exemplo n.º 1
0
 def spark_work(model_with_parameters):
     import tellurium as te
     if(antimony == "antimony"):
         model_roadrunner = te.loada(model_with_parameters[0])
     else:
         model_roadrunner = te.loadSBMLModel(model_with_parameters[0])
     parameter_scan_initilisation = te.ParameterScan(model_roadrunner,**model_with_parameters[1])
     simulator = getattr(parameter_scan_initilisation, function_name)
     return(simulator())
Exemplo n.º 2
0
def sbml_dom_path():
    import os
    test_path = os.path.dirname(__file__)
    model_path = os.path.join(os.path.dirname(test_path), 'examples', 'sbml_example', 'double_enzymatic_sbml.xml')
    r = te.loadSBMLModel(model_path)
    model = SbmlModel(r)
    sim = SbmlSimulation()
    r.selections = ['time', '__s0', '__s1', '__s2', '__s3', '__s4', '__s5', 'r0', 'r1', 'r2', 'r3']
    r.simulate(0, 100, 100)
    sim.add_simulation(r)
    dom = ds.SbmlDomPath(model, sim)
    return dom
Exemplo n.º 3
0
    def test_roadrunner(self):
        # load test model as SBML
        sbml = te.getTestModel('feedback.xml')
        rr = te.loadSBMLModel(sbml)
        # simulate
        s = rr.simulate(0, 100.0, 200)
        rr.plot(s)

        self.assertIsNotNone(rr)
        self.assertIsNotNone(s)
        self.assertEqual(s.shape[0], 200)
        self.assertEqual(s["time"][0], 0)
        self.assertAlmostEqual(s["time"][-1], 100.0)
Exemplo n.º 4
0
    def __init__(self,
                 sbml,
                 settings_kwargs={},
                 species_kwargs={},
                 conditions_kwargs={}):
        self.model = te.loadSBMLModel(sbml)
        self._config = ChainMap()
        self.settings_kwargs = settings_kwargs
        self.species_kwargs = species_kwargs
        self.conditions_kwargs = conditions_kwargs

        self.config = self._create_config()
        super().__init__(self.config)
Exemplo n.º 5
0
    def test_roadrunner(self):
        # load test model as SBML
        sbml = te.getTestModel('feedback.xml')
        rr = te.loadSBMLModel(sbml)
        # simulate
        s = rr.simulate(0, 100.0, 200)
        rr.plot(s)

        self.assertIsNotNone(rr)
        self.assertIsNotNone(s)
        self.assertEqual(s.shape[0], 200)
        self.assertEqual(s["time"][0], 0)
        self.assertAlmostEqual(s["time"][-1], 100.0)
Exemplo n.º 6
0
    def test_roadrunner(self):
        # load test model as SBML
        from tellurium.tests.testdata import FEEDBACK_SBML
        # sbml = te.getTestModel('feedback.xml')
        rr = te.loadSBMLModel(FEEDBACK_SBML)
        # simulate
        s = rr.simulate(0, 100.0, 200)
        rr.plot(s)

        self.assertIsNotNone(rr)
        self.assertIsNotNone(s)
        self.assertEqual(s.shape[0], 200)
        self.assertEqual(s["time"][0], 0)
        self.assertAlmostEqual(s["time"][-1], 100.0)
 def stochastic_work(model_object):
     import tellurium as te
     if model_type == "antimony":
         model_roadrunner = te.loada(model_object.model)
     else:
         model_roadrunner = te.loadSBMLModel(model_object.model)
     model_roadrunner.integrator = model_object.integrator
     model_roadrunner.setSeed(random.randint(1000, 9999))
     model_roadrunner.variable_step_size = model_object.variable_step_size
     model_roadrunner.reset()
     simulated_data = model_roadrunner.simulate(model_object.from_time,
                                                model_object.to_time,
                                                model_object.step_points)
     return ([simulated_data.colnames, np.array(simulated_data)])
Exemplo n.º 8
0
    def test_roadrunner(self):
        # load test model as SBML
        from tellurium.tests.testdata import FEEDBACK_SBML
        # sbml = te.getTestModel('feedback.xml')
        rr = te.loadSBMLModel(FEEDBACK_SBML)
        # simulate
        s = rr.simulate(0, 100.0, 200)
        rr.plot(s)

        self.assertIsNotNone(rr)
        self.assertIsNotNone(s)
        self.assertEqual(s.shape[0], 200)
        self.assertEqual(s["time"][0], 0)
        self.assertAlmostEqual(s["time"][-1], 100.0)
Exemplo n.º 9
0
 def getSBMLFromAntimony(self, input_string):
     """
 This method runs in a different process from the caller
 and so can import tellurium.
 """
     import tellurium as te
     # Convert input to string.
     inputs = self.__class__._convert(input_string)
     # Try different ways to load the model
     try:
         rr = te.loada(inputs)
     except:
         rr = te.loadSBMLModel(inputs)
     sbml = rr.getSBML()
     sys.stdout.writelines(sbml)
Exemplo n.º 10
0
 def stochastic_work(model_object):
     import tellurium as te
     if model_type == "antimony":
         model_roadrunner = te.loada(model_object.model)
     else:
         model_roadrunner = te.loadSBMLModel(model_object.model)
     model_roadrunner.integrator = model_object.integrator
     # seed the randint method with the current time
     random.seed()
     # it is now safe to use random.randint
     model_roadrunner.setSeed(random.randint(1000, 99999))
     model_roadrunner.integrator.variable_step_size = model_object.variable_step_size
     model_roadrunner.reset()
     simulated_data = model_roadrunner.simulate(model_object.from_time, model_object.to_time, model_object.step_points)
     return([simulated_data.colnames,np.array(simulated_data)])
Exemplo n.º 11
0
    def __init__(self, sbml, config):
        self.sbml = sbml
        self.config = config
        self.model = te.loadSBMLModel(sbml)

        self.nspecies = len(self.config['species'])
        self.n_iterations = self.config['settings']['n_iterations']
        self.start = self.config['settings']['integration_options'][
            'start_time']
        self.end = self.config['settings']['integration_options']['end_time']
        self.intervals = self.config['settings']['integration_options'][
            'intervals']

        self.ics = np.zeros(self.n_iterations * self.nspecies).reshape(
            self.n_iterations, self.nspecies)
        width = self.nspecies + 1 + 1  # +1 for time +1 for iteration id
        self.results = np.zeros(width * self.intervals * self.n_iterations) \
            .reshape(self.intervals * self.n_iterations, width)

        self.current_iter = 0
        self.sampler = MonteCarloSampler(self.sbml, self.config)
Exemplo n.º 12
0
    """
    return ['ki', 'kr', 'k_T1R', 'k_T2R',
            'kdeg_T1R', 'kdeg_T2R', 'kdeg_LRC', 'kdeg_TGF_beta', 'klid', 'ka_LRC', 'kdiss_LRC', 'kimp_Smad2',
            'kexp_Smad2', 'kimp_Smad4', 'kexp_Smad4', 'kpho_Smad2', 'kon_Smads', 'koff_Smads', 'kimp_Smads',
            'kdepho_Smad2', 'kon_ns', 'KD_ns']


# assign, and now freeParameters is callable bound to ExtendedRoadrunner types
ExtendedRoadRunner.freeParameters = freeParameters

#####################################################################################3
#   model and data generation
#

# globally scoped model
r = te.loadSBMLModel(r"D:\SRES\csres\test\zi2011.xml")

print(r.getGlobalParameterIds())


def get_data(**params) -> Tuple[np.ndarray, np.ndarray, List[str]]:
    r.reset()
    for k, v in params.items():
        setattr(r, k, v)

    try:
        # Simulate "experimental" data
        m = r.simulate(0, 20, 21)
    except Exception:
        return None
    x_data = m["time"]  # only time
Exemplo n.º 13
0
import tellurium as te
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = '/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sedx/_te_ClockSedML'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, 'Clock_BIOMD21.xml'))
# Model <model2>
model2 = te.loadSBMLModel(os.path.join(workingDir, 'Clock_BIOMD21.xml'))
# /sbml:sbml/sbml:model/sbml:listOfParameters/sbml:parameter[@id='V_dT']/@value 4.8
model2['V_dT'] = 4.8
# /sbml:sbml/sbml:model/sbml:listOfParameters/sbml:parameter[@id='V_mT']/@value 0.28
model2['V_mT'] = 0.28

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
model1.setIntegrator('cvode')
model1.timeCourseSelections = ['[Mt]', 'time']
Exemplo n.º 14
0
import tellurium as te
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = '/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, '../models/lorenz.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
model1.setIntegrator('cvode')
model1.timeCourseSelections = ['[Z]', '[X]', '[Y]', 'time']
task1[0] = model1.simulate(start=0.0, end=200.0, steps=1000)

# --------------------------------------------------------
# DataGenerators
# --------------------------------------------------------
# DataGenerator <time1>
Exemplo n.º 15
0
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r"/home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/_te_case_03"

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <mod1>
mod1 = te.loadSBMLModel(os.path.join(workingDir, "case_03.xml"))
# Model <mod2>
mod2 = te.loadSBMLModel(os.path.join(workingDir, "case_03.xml"))
__var__S1 = mod2["init([S1])"]
mod2["init([S2])"] = __var__S1 + 4

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
mod1.setIntegrator("cvode")
mod1.timeCourseSelections = ["[S1]", "[S2]", "time"]
task1[0] = mod1.simulate(start=0.0, end=10.0, steps=100)
Exemplo n.º 16
0
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/_te_case_01'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model0>
model0 = te.loadSBMLModel(os.path.join(workingDir, 'case_01.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task0>
# Task: <task0>
task0 = [None]
model0.setIntegrator('cvode')
model0.timeCourseSelections = ['[S1]', 'time']
task0[0] = model0.simulate(start=0.0, end=10.0, steps=100)

# --------------------------------------------------------
# DataGenerators
# --------------------------------------------------------
# DataGenerator <plot_0_0_0>
Exemplo n.º 17
0
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <Application0>
Application0 = te.loadSBMLModel(os.path.join(workingDir, '../models/asedmlComplex.xml'))
# Model <Application0_0>
Application0_0 = te.loadSBMLModel(os.path.join(workingDir, '../models/asedmlComplex.xml'))
# /sbml:sbml/sbml:model/sbml:listOfSpecies/sbml:species[@id='s0'] 25.0
Application0_0['init([s0])'] = 25.0

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task_0_0>
# not part of any DataGenerator: task_0_0

# Task <repeatedTask_0_0>

repeatedTask_0_0 = []
__range__range_0_0_s1_init_uM = np.linspace(start=5.0, stop=15.0, num=4)
Exemplo n.º 18
0
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = '/home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/_te_oneStep'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, 'oneStep.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task0>
# not part of any DataGenerator: task0

# Task <task1>

task1 = []
__range__x = np.linspace(start=0.0, stop=10.0, num=101)
for __k__x, __value__x in enumerate(__range__x):
    if __k__x == 0:
        model1.reset()
    # Task: <task0>
     elif i[3] == 0:
         m.addReaction(["S" + str(i[0]), "S" + str(i[1])], 
                       ["S" + str(i[2])], "k" + str(count) + "*S" + 
                       str(i[0]) + "*S" + str(i[1]))
     elif i[1] == 0:
         m.addReaction(["S" + str(i[0])], ["S" + str(i[1]), 
                       "S" + str(i[2])], "k" + str(count) + "*S" + 
                       str(i[0]))
     else:
         m.addReaction(["S" + str(i[0]), "S" + str(i[1])], ["S" + str(i[2]),
                       "S" + str(i[3])], "k" + str(count) + "*S" + 
                       str(i[0]) + "*S" + str(i[1]))
         
 
 te.saveToFile('ProteinModel.xml', str(m))
 r = te.loadSBMLModel('ProteinModel.xml')
 
 try:
     if forbidZeros:
         r.simulate()
         for i in r.getSteadyStateValues():
             if i < 1e-5:
                 raise ValueError
     r.simulate(end=1000)
     steady = r.steadyState()
     if steady < 10e-6:            
         print "Success!"
         print ("Number of tries = " + str(zcount))
         zcount = 0 
         for i in data:
             zcount += 1
Exemplo n.º 20
0
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <Application0>
Application0 = te.loadSBMLModel(
    os.path.join(workingDir, '../models/asedmlComplex.xml'))
# Model <Application0_0>
Application0_0 = te.loadSBMLModel(
    os.path.join(workingDir, '../models/asedmlComplex.xml'))
# /sbml:sbml/sbml:model/sbml:listOfSpecies/sbml:species[@id='s0'] 25.0
Application0_0['init([s0])'] = 25.0

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task_0_0>
# not part of any DataGenerator: task_0_0

# Task <repeatedTask_0_0>

repeatedTask_0_0 = []
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/results/_te_repeatedStochastic'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, 'repeatedStochastic.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# not part of any DataGenerator: task1

# Task <task2>
# not part of any DataGenerator: task2

# Task <repeat1>

repeat1 = []
__range__x = np.linspace(start=0.0, stop=10.0, num=11)
for __k__x, __value__x in enumerate(__range__x):
import tellurium as te
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = '/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, '../models/oscli.xml'))
# Model <model2>
model2 = te.loadSBMLModel(os.path.join(workingDir, '../models/oscli.xml'))
__var__J3_k2 = model2['J3_k2']
model2['J3_k2'] = __var__J3_k2 / 2
__var__S2 = model2['[S2]']
model2['init([S2])'] = __var__S2 / 2
__var__S1 = model2['[S1]']
model2['init([S1])'] = __var__S1 / 2

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
Exemplo n.º 23
0
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <Application0>
Application0 = te.loadSBMLModel(os.path.join(workingDir, '../models/app2sim.xml'))
# Model <Application0_0>
Application0_0 = te.loadSBMLModel(os.path.join(workingDir, '../models/app2sim.xml'))
# /sbml:sbml/sbml:model/sbml:listOfSpecies/sbml:species[@id='s1'] 10.0
Application0_0['init([s1])'] = 10.0

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task_0_0>
# Task: <task_0_0>
task_0_0 = [None]
Application0.setIntegrator('cvode')
Application0.timeCourseSelections = ['[s0]', '[s1]', 'time']
task_0_0[0] = Application0.simulate(start=0.0, end=20.0, steps=1000)
Exemplo n.º 24
0
    M_df = pd.DataFrame([[round(x, 4) for x in line] for line in M],
                        columns=species_names)
    with open(filepath, "w") as outfile:
        outfile.write(M_df.to_csv(sep="\t"))


def write_eigenvalues_to_file(model, filepath, species_names):
    M_df = pd.DataFrame([model.getFullEigenValues()], columns=species_names)
    with open(filepath, "w") as outfile:
        outfile.write(M_df.to_csv(sep="\t"))


# We start with the smallest subsystem: Amino Sugar and Nucleotide Sugar Metabolism
asansm_libsbml_doc = libsbml.readSBML(asansm_sbml)
asansm_libsbml = asansm_libsbml_doc.getModel()
asansm_model = te.loadSBMLModel(asansm_sbml)
S_asansm = asansm_model.getFullStoichiometryMatrix()
S_asansm.colnames = get_reaction_names(asansm_libsbml.getListOfReactions(),
                                       S_asansm.colnames)
S_asansm.rownames = get_metabolite_names(asansm_libsbml.getListOfSpecies(),
                                         S_asansm.rownames)
asansm_right_nullspace = Matrix(S_asansm).nullspace()
asansm_left_nullspace = Matrix(S_asansm.T).nullspace()
asansm_rank = Matrix(S_asansm).rank()

# Next subsystem: Pyrimidine Metabolism
# This one is a little special because Matrix().nullspace computes an empty right nullspace here, but there is one!
# So we do it the pedestrian way...
pm_libsbml_doc = libsbml.readSBML(pm_sbml)
pm_libsbml = pm_libsbml_doc.getModel()
pm_model = te.loadSBMLModel(pm_sbml)
Exemplo n.º 25
0
 def test_loadSBMLModel_file(self):
     r = te.loadSBMLModel(self.sbml_file)
     self.assertIsNotNone(r)
Exemplo n.º 26
0
 def test_loadSBMLModel_file(self):
     r = te.loadSBMLModel(self.sbml_file)
     self.assertIsNotNone(r)
Exemplo n.º 27
0
import tellurium as te
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = '/home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/_te_case_04'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <mod1>
mod1 = te.loadSBMLModel(os.path.join(workingDir, 'case_04.xml'))
# Model <mod2>
mod2 = te.loadSBMLModel(os.path.join(workingDir, 'case_04.xml'))
__var__S1 = mod2['S1']
mod2['S2'] = __var__S1 + 4
# Model <mod3>
mod3 = te.loadSBMLModel(os.path.join(workingDir, 'case_04.xml'))
__var__S1 = mod3['S1']
mod3['S2'] = __var__S1 + 4
# /sbml:sbml/sbml:model/listOfSpecies/species[@id='S1']/@initialConcentration 20
mod3['init([S1])'] = 20

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
Exemplo n.º 28
0
import tellurium as te
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = '/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, '../models/oscli.xml'))
# Model <model2>
model2 = te.loadSBMLModel(os.path.join(workingDir, '../models/oscli.xml'))
__var__J3_k2 = model2['J3_k2']
model2['J3_k2'] = __var__J3_k2 / 2
__var__S2 = model2['[S2]']
model2['init([S2])'] = __var__S2 / 2
__var__S1 = model2['[S1]']
model2['init([S1])'] = __var__S1 / 2

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
Exemplo n.º 29
0
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/results/_te_case_10'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <mod1>
mod1 = te.loadSBMLModel(os.path.join(workingDir, 'case_10.xml'))
# Model <mod2>
mod2 = te.loadSBMLModel(os.path.join(workingDir, 'case_10.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# not part of any DataGenerator: task1

# Task <task2>
# not part of any DataGenerator: task2

# Task <repeat1>

repeat1 = []
Exemplo n.º 30
0
import tellurium as te
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = '/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, '../models/BorisEJB.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
model1.setIntegrator('cvode')
model1.timeCourseSelections = [
    '[MKKK]', '[MKKK_P]', '[MAPK]', '[MAPK_PP]', '[MKK_P]', '[MAPK_P]', 'time',
    '[MKK]'
]
task1[0] = model1.simulate(start=0.0, end=4000.0, steps=1000)

# --------------------------------------------------------
Exemplo n.º 31
0
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/results/_te_repeatedStochastic'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, 'repeatedStochastic.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# not part of any DataGenerator: task1

# Task <task2>
# not part of any DataGenerator: task2

# Task <repeat1>

repeat1 = []
__range__x = np.linspace(start=0.0, stop=10.0, num=11)
for __k__x, __value__x in enumerate(__range__x):
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <repressor_activator_oscillations>
repressor_activator_oscillations = te.loadSBMLModel(
    os.path.join(workingDir,
                 '../models/BioModel1_repressor_activator_oscillations.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task_0_0>
# not part of any DataGenerator: task_0_0

# Task <repeatedTask_0_0>

repeatedTask_0_0 = []
__range__range_0_0_common_delta_A = np.linspace(start=0.2, stop=1.0, num=4)
for __k__range_0_0_common_delta_A, __value__range_0_0_common_delta_A in enumerate(
        __range__range_0_0_common_delta_A):
    repressor_activator_oscillations.reset()
Exemplo n.º 33
0
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = '/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
import tellurium.temiriam as temiriam

__model1_sbml = temiriam.getSBMLFromBiomodelsURN(
    'urn:miriam:biomodels.db:BIOMD0000000021')
model1 = te.loadSBMLModel(__model1_sbml)

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
model1.setIntegrator('cvode')
model1.timeCourseSelections = [
    '[P0]', '[T1]', '[T0]', '[CC]', '[P2]', '[T2]', '[P1]', '[Cn]', '[Mp]',
    'time', '[Mt]'
]
task1[0] = model1.simulate(start=0.0, end=100.0, steps=1000)

# --------------------------------------------------------
Exemplo n.º 34
0
import tellurium as te
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = '/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sedx/_te_BIOMD0000000012'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel('http://www.ebi.ac.uk/biomodels/models-main/publ/BIOMD0000000012/BIOMD0000000012.xml')
# Model <model2>
model2 = te.loadSBMLModel('http://www.ebi.ac.uk/biomodels/models-main/publ/BIOMD0000000012/BIOMD0000000012.xml')
# /sbml:sbml/sbml:model/sbml:listOfParameters/sbml:parameter[@id="ps_a"]/@value 0.013
model2['ps_a'] = 0.013
# /sbml:sbml/sbml:model/sbml:listOfParameters/sbml:parameter[@id="ps_0"]/@value 1.3e-5
model2['ps_0'] = 1.3e-5

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
model1.setIntegrator('cvode')
model1.timeCourseSelections = ['[Z]', '[X]', '[Y]', 'time']
Exemplo n.º 35
0
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = '/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sedx/_te_BIOMD0000000139'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
import tellurium.temiriam as temiriam
__model1_sbml = temiriam.getSBMLFromBiomodelsURN('urn:miriam:biomodels.db:BIOMD0000000139')
model1 = te.loadSBMLModel(__model1_sbml)

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
model1.setIntegrator('cvode')
model1.timeCourseSelections = ['Total_NFkBn', 'time']
task1[0] = model1.simulate(start=0.0, end=2500.0, steps=1000)

# --------------------------------------------------------
# DataGenerators
# --------------------------------------------------------
# DataGenerator <time>
                    s.join([k2, sp2]) + "+" + s.join([k3, sp1, sp2]) + ")")
            elif i[6] == 8:
                m.addReaction([], [sp3], "(1+" + s.join([k1, sp1, sp2]) +  
                    ")/(1+" + s.join([k1, sp1]) + "+" + s.join([k2, sp2]) + "+"
                    + s.join([k3, sp1, sp2]) + ")")                     
            elif i[6] == 9:
                m.addReaction([], [sp3], "(" + s.join([k1, sp1]) + ")/(1+" +
                    s.join([k1, sp1]) + "+" + s.join([k2, sp2]) + "+" +
                    s.join([k3, sp1, sp2]) + ")")
                    
    decayData = [] # Holds protein decay information
    re.proteindecay()        
                
    te.saveToFile('GeneticModel.xml', str(m))

    r = te.loadSBMLModel('GeneticModel.xml')
    try:
        if forbidZeros:
            r.simulate()
            for i in r.getSteadyStateValues():
                if i < 1e-5:
                    raise ValueError
        steady = r.steadyState() # Determine if final concentrations steady out
        if steady < 10e-6: # If they do, then it's a successful model           
            print "Success!"
            print ("Number of tries = " + str(zcount))
            zcount = 0 
            for i in data:
                zcount += 1
            print ("Number of reactions = " + str(zcount))
            if printReactions:
        if i[1] == 0 and i[3] == 0:
            m.addReaction([sp1], [sp2], "k" + str(count) + "*" + sp1)
        elif i[3] == 0:
            m.addReaction([sp1, sp2], [sp3], "k" + str(count) + "*" + sp1 
                            + "*" + sp2)
        elif i[1] == 0:
            m.addReaction([sp1], [sp2, sp3], "k" + str(count) + "*" + sp1)
                          
        else:
            m.addReaction([sp1, sp2], [sp3, sp4], "k" + str(count) + "*" + sp1 
                            + "*" + sp2)
                          
                
    te.saveToFile('Model.xml', str(m))

    r = te.loadSBMLModel('Model.xml')
    try:
        if forbidZeros:
            r.simulate()
            for i in r.getSteadyStateValues():
                if i < 1e-5:
                    raise ValueError
        if limitBoundarySpecies:
            if speciesType.count(1) > maxBoundarySpecies:
                raise ValueError
        steady = r.steadyState() #Determine if concentrations converge
        if steady < 10e-6: # If they do, it's a successful model
            print "Success!"
            print ("Number of tries = " + str(zcount))
            zcount = 0 
            for i in data:
Exemplo n.º 38
0
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <Application0>
Application0 = te.loadSBMLModel(
    os.path.join(workingDir, '../models/app2sim.xml'))
# Model <Application0_0>
Application0_0 = te.loadSBMLModel(
    os.path.join(workingDir, '../models/app2sim.xml'))
# /sbml:sbml/sbml:model/sbml:listOfSpecies/sbml:species[@id='s1'] 10.0
Application0_0['init([s1])'] = 10.0

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task_0_0>
# Task: <task_0_0>
task_0_0 = [None]
Application0.setIntegrator('cvode')
Application0.timeCourseSelections = ['[s0]', '[s1]', 'time']
task_0_0[0] = Application0.simulate(start=0.0, end=20.0, steps=1000)
Exemplo n.º 39
0
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/results/_te_case_02'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model0>
model0 = te.loadSBMLModel(os.path.join(workingDir, 'case_02.xml'))
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, 'case_02.xml'))
# /sbml:sbml/sbml:model/sbml:listOfSpecies/sbml:species[@id='S1']/@initialConcentration 5
model1['init([S1])'] = 5

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task0>
# not part of any DataGenerator: task0

# Task <task1>

task1 = []
__range__uniform_linear_for_k1 = np.linspace(start=0.0, stop=5.0, num=6)
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r"/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml"

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <repressor_activator_oscillations>
repressor_activator_oscillations = te.loadSBMLModel(
    os.path.join(workingDir, "../models/BioModel1_repressor_activator_oscillations.xml")
)

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task_0_0>
# not part of any DataGenerator: task_0_0

# Task <repeatedTask_0_0>

repeatedTask_0_0 = []
__range__range_0_0_common_delta_A = np.linspace(start=0.2, stop=1.0, num=4)
for __k__range_0_0_common_delta_A, __value__range_0_0_common_delta_A in enumerate(__range__range_0_0_common_delta_A):
    repressor_activator_oscillations.reset()
    # Task: <task_0_0>
def write_left_nullspace_to_file(M, filepath, species_names):  # pass rownames of corresponding S as species_names
    M_df = pd.DataFrame([[round(x, 4) for x in line] for line in M], columns=species_names)
    with open(filepath, "w") as outfile:
        outfile.write(M_df.to_csv(sep="\t"))


def write_eigenvalues_to_file(model, filepath, species_names):
    M_df = pd.DataFrame([model.getFullEigenValues()], columns=species_names)
    with open(filepath, "w") as outfile:
        outfile.write(M_df.to_csv(sep="\t"))


# We start with the smallest subsystem: Amino Sugar and Nucleotide Sugar Metabolism
asansm_libsbml_doc = libsbml.readSBML(asansm_sbml)
asansm_libsbml = asansm_libsbml_doc.getModel()
asansm_model = te.loadSBMLModel(asansm_sbml)
S_asansm = asansm_model.getFullStoichiometryMatrix()
S_asansm.colnames = get_reaction_names(asansm_libsbml.getListOfReactions(), S_asansm.colnames)
S_asansm.rownames = get_metabolite_names(asansm_libsbml.getListOfSpecies(), S_asansm.rownames)
asansm_right_nullspace = Matrix(S_asansm).nullspace()
asansm_left_nullspace = Matrix(S_asansm.T).nullspace()
asansm_rank = Matrix(S_asansm).rank()

# Next subsystem: Pyrimidine Metabolism
# This one is a little special because Matrix().nullspace computes an empty right nullspace here, but there is one!
# So we do it the pedestrian way...
pm_libsbml_doc = libsbml.readSBML(pm_sbml)
pm_libsbml = pm_libsbml_doc.getModel()
pm_model = te.loadSBMLModel(pm_sbml)
S_pm = pm_model.getFullStoichiometryMatrix()
S_pm.colnames = get_reaction_names(pm_libsbml.getListOfReactions(), S_pm.colnames)
Exemplo n.º 42
0
    class Parameters:
        # Input data ==========================================================
        
        INPUT = None
        READ_SETTINGS = None
        
        
        # Test models =========================================================
        
        # 'FFL', 'Linear', 'Nested', 'Branched'
        modelType = 'Linear_m'
        
        
        # General settings ====================================================
        
        # Number of generations
        n_gen = 100
        # Size of output ensemble
        ens_size = 100
        # Number of models passed on the next generation without mutation
        pass_size = int(ens_size/10)
        # Number of models to mutate
        mut_size = int(ens_size/2)
        # Maximum iteration allowed for random generation
        maxIter_gen = 20
        # Maximum iteration allowed for mutation
        maxIter_mut = 20
        # Set conserved moiety
        conservedMoiety = False
        
        
        # Optimizer settings ==================================================
        
        # Maximum iteration allowed for optimizer
        optiMaxIter = 100
        optiTol = 1.
        optiPolish = False
        # Weight for control coefficients when calculating the distance
        w1 = 16
        # Weight for steady-state and flux when calculating the distance
        w2 = 1.0
        FLUX = False
        
        
        # Random settings =====================================================
        
        # random seed
        r_seed = 123123
        # Flag for adding Gaussian noise to steady-state and control coefficiant values
        NOISE = False
        # Standard deviation of Gaussian noise
        ABS_NOISE_STD = 0.01
        # Standard deviation of Gaussian noise
        REL_NOISE_STD = 0.1
        
        
        # Plotting settings ===================================================
        
        # Flag for plots
        PLOT = True
        # Flag for saving plots
        SAVE_PLOT = True
        
        
        # Data settings =======================================================
        
        # Flag for collecting models
        EXPORT_ALL_MODELS = True
        # Flag for saving collected models
        EXPORT_OUTPUT = True
        # Flag for saving current settings
        EXPORT_SETTINGS = False
        # Path to save the output
        EXPORT_PATH = './USE/output_Linear_m_update'
        
        # Flag to run algorithm
        RUN = True
        

#%%    
        if conservedMoiety:
            roadrunner.Config.setValue(roadrunner.Config.LOADSBMLOPTIONS_CONSERVED_MOIETIES, True)

        roadrunner.Config.setValue(roadrunner.Config.STEADYSTATE_APPROX, True)
        roadrunner.Config.setValue(roadrunner.Config.STEADYSTATE_APPROX_MAX_STEPS, 100)
        roadrunner.Config.setValue(roadrunner.Config.STEADYSTATE_APPROX_TIME, 1000000)
#        roadrunner.Config.setValue(roadrunner.Config.STEADYSTATE_APPROX_TOL, 1e-3)

        
        # Using one of the test models
        realModel = ioutils.testModels(modelType)
        
        if os.path.exists(realModel):
            realRR = te.loadSBMLModel(realModel)
        else:
            realRR = te.loada(realModel)
        
        realNumBoundary = realRR.getNumBoundarySpecies()
        realNumFloating = realRR.getNumFloatingSpecies()
        realFloatingIds = np.sort(realRR.getFloatingSpeciesIds())
        realFloatingIdsInd = list(map(int, [s.strip('S') for s in realRR.getFloatingSpeciesIds()]))
        realFloatingIdsInd.sort()
        realBoundaryIds = np.sort(realRR.getBoundarySpeciesIds())
        realBoundaryIdsInd = list(map(int,[s.strip('S') for s in realRR.getBoundarySpeciesIds()]))
        realBoundaryIdsInd.sort()
        realBoundaryVal = realRR.getBoundarySpeciesConcentrations()
        realGlobalParameterIds = realRR.getGlobalParameterIds()
        
        realRR.steadyState()
        realSteadyState = realRR.getFloatingSpeciesConcentrations()
        realSteadyStateRatio = np.divide(realSteadyState, np.min(realSteadyState))
        realFlux = realRR.getReactionRates()
        realRR.reset()
        realRR.steadyState()
        realFluxCC = realRR.getScaledFluxControlCoefficientMatrix()
        realConcCC = realRR.getScaledConcentrationControlCoefficientMatrix()
        
        realFluxCC[np.abs(realFluxCC) < 1e-12] = 0
        realConcCC[np.abs(realConcCC) < 1e-12] = 0
        
        # Ordering
        realFluxCCrow = realFluxCC.rownames
        realFluxCCcol = realFluxCC.colnames
        realFluxCC = realFluxCC[np.argsort(realFluxCCrow)]
        realFluxCC = realFluxCC[:,np.argsort(realFluxCCcol)]
        
        realConcCCrow = realConcCC.rownames
        realConcCCcol = realConcCC.colnames
        realConcCC = realConcCC[np.argsort(realConcCCrow)]
        realConcCC = realConcCC[:,np.argsort(realConcCCcol)]
        
        realFlux = realFlux[np.argsort(realRR.getReactionIds())]
        
        ns = realNumBoundary + realNumFloating # Number of species
        nr = realRR.getNumReactions() # Number of reactions
        
        realReactionList = ng.generateReactionListFromAntimony(realModel)
        knownReactionList = ng.generateKnownReactionListFromAntimony(realModel)
        
        n_range = range(1, n_gen)
        ens_range = range(ens_size)
        mut_range = range(mut_size)
        r_range = range(nr)
Exemplo n.º 43
0
 def test_loadSBMLModel_str(self):
     r = te.loadSBMLModel(self.sbml_str)
     self.assertIsNotNone(r)
Exemplo n.º 44
0
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <Application0>
Application0 = te.loadSBMLModel(
    os.path.join(workingDir, '../models/asedml3repeat.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task_0_0>
# not part of any DataGenerator: task_0_0

# Task <repeatedTask_0_0>

repeatedTask_0_0 = []
__range__range_0_0_s1_init_uM = np.linspace(start=10.0, stop=30.0, num=4)
for __k__range_0_0_s1_init_uM, __value__range_0_0_s1_init_uM in enumerate(
        __range__range_0_0_s1_init_uM):
    Application0.reset()
    # Task: <task_0_0>
Exemplo n.º 45
0
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/results/_te_case_12'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <mod1>
mod1 = te.loadSBMLModel(os.path.join(workingDir, 'case_12.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# not part of any DataGenerator: task1

# Task <task2>
# not part of any DataGenerator: task2

# Task <repeat1>

repeat1 = []
__range__uniform_linear_for_S1 = np.linspace(start=0.0, stop=10.0, num=5)
for __k__uniform_linear_for_S1, __value__uniform_linear_for_S1 in enumerate(
Exemplo n.º 46
0
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/results/_te_lorenz'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, 'lorenz.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
model1.setIntegrator('cvode')
model1.timeCourseSelections = ['x', 'z']
task1[0] = model1.simulate(start=0.0, end=15.0, steps=2000)

# --------------------------------------------------------
# DataGenerators
# --------------------------------------------------------
# DataGenerator <plot_0_0_0>
Exemplo n.º 47
0
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <Application0>
Application0 = te.loadSBMLModel(os.path.join(workingDir, '../models/asedml3repeat.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task_0_0>
# not part of any DataGenerator: task_0_0

# Task <repeatedTask_0_0>

repeatedTask_0_0 = []
__range__range_0_0_s1_init_uM = np.linspace(start=10.0, stop=30.0, num=4)
for __k__range_0_0_s1_init_uM, __value__range_0_0_s1_init_uM in enumerate(__range__range_0_0_s1_init_uM):
    Application0.reset()
    # Task: <task_0_0>
    task_0_0 = [None]
Exemplo n.º 48
0
from __future__ import print_function, division

import libsbml
import tellurium as te
import lxml.etree as ET
from io import StringIO
import tempfile


r = te.loada('''
    J0: S1 -> S2; k1*S1;
    S1=10.0; S2=0.0; k1=1.0;
''')

# create SBML file
f = tempfile.NamedTemporaryFile('w', suffix=".xml")
r.exportToSBML(f.name)

# create C14N canonical XML
et = ET.parse(f.name)
output = StringIO.StringIO()
et.write_c14n(output)
c14n_xml = output.getvalue()
# TODO: in addition sort all elements of the listOfs

# read with libsbml
doc = libsbml.readSBMLFromString(c14n_xml)

# read with roadrunner
te.loadSBMLModel(c14n_xml)
Exemplo n.º 49
0
import tellurium as te
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = '/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sedx/_te_BorisEJB-test'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, 'model1.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
model1.setIntegrator('cvode')
model1.timeCourseSelections = [
    '[MKKK]', '[MKKK_P]', '[MAPK]', '[MAPK_PP]', '[MKK_P]', '[MAPK_P]', 'time',
    '[MKK]'
]
task1[0] = model1.simulate(start=0.0, end=4000.0, steps=1000)

# --------------------------------------------------------
Exemplo n.º 50
0
import tellurium as te
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = '/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, '../models/BorisEJB.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
model1.setIntegrator('cvode')
model1.conservedMoietyAnalysis = True
model1.steadyStateSelections = ['[MKKK]', '[MKKK_P]', '[MAPK]', '[MAPK_PP]', '[MKK_P]', '[MAPK_P]', 'time', '[MKK]']
model1.simulate()
task1[0] = model1.steadyState()
model1.conservedMoietyAnalysis = False

# --------------------------------------------------------
Exemplo n.º 51
0
def evolveBifurcation(model,
                      bifurType='oscillator',
                      parameterList=None,
                      paramRanges=None,
                      maxGenerations=100,
                      numMembers=50,
                      mutationConst=0.5,
                      recombinationConst=0.5,
                      thresholdType='fitness',
                      threshold=5.0,
                      localMin=False,
                      displayOpt=False):
    """
    Author: Veronica Porubsky

    evolveBifurcation(model, bifurType = 'oscillator', parameterList = None, paramRanges = None, maxGenerations = 100, numMembers = 50, mutationConst = 0.5, recombinationConst = 0.5, thresholdType = 'fitness', threshold = 5.0, localMin = False, displayOpt = False)
    ======================
    
    The module will evolve global parameters, floating species initial 
    concentrations, and boundary species of the loaded antimony or sbml model
    to optimize for eigenvalues characteristic of Hopf or turning point 
    bifurcations.
    
    Inputs:
        
    model : executable model string, SBML (.xml) or Antimony (.ant) model 
        string file evolveBifurcation takes models in the form of Antimony or 
        SBML strings which have either an existing instance or which are saved 
        independently as files with the extension .ant or .xml and entered as 
        type str
             
    bifurType : str
        The bifurcation type that the user wishes to optimize for - either for 
        Hopf bifurcations to evolve parameters which produce an oscillatory
        output or for a turning point bifurcation which will attempt to evolve 
        parameters that may generate bistability. Should select either:
            - 'oscillator'
            - 'turningPoint'

    parameterList : list
        parameterList specifies the parameters to be optimized. If the model 
        contains parameters named k1, k3_deg, and k5, which the user wishes to
        optimize, these should be entered as follows: 
        parameterList = ['k1', 'k3_deg', 'k5']. The default value is 
        parameterList = None, in which the algorithm automatically optimizes
        all global parameters and all floating and boundary species initial
        conditions.
        
    paramRanges : list of tuples
        paramRanges imposes a minimum and maximum on the range of values 
        that the parameters being optimized can be assigned. Should be entered 
        as follows: paramRanges = [(lower bound, upper bound)]. The lower and 
        upper bound should both of type float. If the user wishes to assign
        unique parameter ranges for each parameter being optimized, they must
        ensure that the length of the paramRanges list is the same as the length
        of the parameterList. For example, if the user wishes to independently
        specify three parameter ranges for parameterList = ['k1', 'k3_deg', 'k5'], 
        they must enter paramRanges = [(0.1, 10.0), (0.5, 1.0), (5.0, 10.0)].
        
    maxGenerations : int
        maxGenerations sets the determines the maximum number of generations 
        the differential evolution algorithm will complete.
    
    numMembers : int
        Specifies the number of members included in the population for 
        differential evolution. Increasing the number of members may slow
        convergence but improve the quality of the solution.
    
    mutationConst : float
        The mutationConst parameter specifies the scaling factor during 
        
    recombinationConst : float
        The recombinationConst is used to determine whether or not 
        a parameter value in the mutant trial vector will undergo mutation or 
        whether it will accept the value of the original member.
    
    thresholdType : str
        The thresholdType determines whether the specified threshold should be
        checked with respect to the best fitness value of the differential
        evolution algorithm or to the smallest eigenvalue real component 
        magnitude. Should select either:
            - 'fitness'
            - 'eigenvalue'
    
    threshold : float
        The threshold is used to fully define stopping criteria for
        the differential evolution algorithm.
    
    localMin : bool
        Setting this argument to True will allow the optimization algorithm to 
        perform a final local minimization using the 
        Broyden-Fletcher-Goldfarb-Shanno algorithm, maintaining the bounded 
        parameter ranges used during global minimization with differential 
        evolution.
    
    displayOpt : bool
        Use diplayOpt = True to display the progress of optimization. Will 
        print to the console the optimized objective function evaluation at the 
        current generation of differential evolution or iteration of BFGS-B. 
    
    Returns:
        
    bifurcationModel : executable model/ RoadRunner object
        The resulting model with all differential evolution-optimized 
        parameters to produce the specified bifurcation type. This can be 
        accessed from the first element of the evolveBifurcation return, and 
        can be used directly for simulation in tellurium. 
        
    fitness : float
        Returns the minimized objective function evaluation, which is the 
        fitness value for the returned model.
    
    :Example:
        
    >>> import tellurium
    >>> from bifurcationEvolution import evolveBifurcation
    >>> r, funEval = evolveBifurcation('oscillatoryModel.xml', 'oscillator') # assign model with evolved parameters to roadrunner object 'r'
    >>> r.simulate() # simulate the updated model which is now available as a roadrunner object 
    """
    try:
        if type(model) == str:
            if model.endswith('.xml'):
                try:
                    bifurcationModel = te.loadSBMLModel(model)
                    bmSBMLPP = bifurcationModel.getParamPromotedSBML(
                        bifurcationModel)
                    bifurcationModel = te.loadSBMLModel(bmSBMLPP)
                except:
                    print(
                        'Could not promote local parameters to global parameters. Continuing optimization without parameter promotion.'
                    )
                    bifurcationModel = te.loadSBMLModel(model)
            elif model.endswith('.ant'):
                try:
                    bifurcationModel = te.loada(model)
                    bmSBML = bifurcationModel.getCurrentSBML()
                    bmSBMLPP = bifurcationModel.getParamPromotedSBML(bmSBML)
                    bifurcationModel = te.loadSBMLModel(bmSBMLPP)
                except:
                    print(
                        'Could not promote local parameters to global parameters. Continuing optimization without parameter promotion.'
                    )
                    bifurcationModel = te.loada(model)
        elif isinstance(model, RoadRunner):
            try:
                bifurcationModel = model
                bmSBML = bifurcationModel.getCurrentSBML()
                bmSBMLPP = bifurcationModel.getParamPromotedSBML(bmSBML)
                bifurcationModel = te.loadSBMLModel(bmSBMLPP)
            except:
                print(
                    'Could not promote local parameters to global parameters. Continuing optimization without parameter promotion.'
                )
                bifurcationModel = model
        else:
            raise RuntimeError(
                'Input not supported: pass an exisiting roadrunner.RoadRunner instance, Antimony (.ant) file, or an SBML (.xml) file.'
            )
    except Exception as e:
        print(e)
    if not bifurType in ['oscillator', 'turningPoint']:
        raise RuntimeError(
            "bifurType must be either 'oscillator' or 'turningPoint'.")
    bifurcationModel.reset()
    bifurcationModel.conservedMoietyAnalysis = True
    parameterList, paramValues = generateParameterList(bifurcationModel,
                                                       parameterList)
    if paramRanges:
        if len(paramRanges) == 1:
            paramRanges = paramRanges * len(parameterList)
    else:
        paramRanges = generateParameterRanges(paramValues)
    toBifurcationObjFunc = (bifurcationModel, bifurType, parameterList)
    try:
        bifurcationOptParams, fitness = differentialEvolution(
            bifurcationObjFunc,
            parameterRanges=paramRanges,
            maxGenerations=maxGenerations,
            displayDEProgress=displayOpt,
            populationSize=numMembers,
            crossoverProbability=recombinationConst,
            mutationConstant=mutationConst,
            thresholdType=thresholdType,
            threshold=threshold,
            bfgsMin=localMin,
            differentialEvArguments=toBifurcationObjFunc)
    except Exception as e:
        print(e)
    bifurcationModel = setModelParams(bifurcationModel, parameterList,
                                      bifurcationOptParams)
    return bifurcationModel, fitness
Exemplo n.º 52
0
import tellurium as te
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = '/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sed-ml'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, '../models/curien.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
model1.setIntegrator('cvode')
model1.timeCourseSelections = ['[Phser]', 'time']
task1[0] = model1.simulate(start=0.0, end=500.0, steps=500)

# --------------------------------------------------------
# DataGenerators
# --------------------------------------------------------
# DataGenerator <time>
Exemplo n.º 53
0
import tellurium as te
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path

workingDir = "/home/mkoenig/git/tellurium/tellurium/tests/testdata/sedml/sedx/_te_BM12"

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model1>
model1 = te.loadSBMLModel(os.path.join(workingDir, "model1.xml"))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task1>
# Task: <task1>
task1 = [None]
model1.setIntegrator("cvode")
model1.timeCourseSelections = ["[Z]", "[X]", "[Y]", "time"]
task1[0] = model1.simulate(start=0.0, end=100.0, steps=1000)

# --------------------------------------------------------
# DataGenerators
# --------------------------------------------------------
# DataGenerator <time>
Exemplo n.º 54
0
 def test_loadSBMLModel_str(self):
     r = te.loadSBMLModel(self.sbml_str)
     self.assertIsNotNone(r)
Exemplo n.º 55
0
from tellurium.sedml.mathml import *
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
import libsedml
import pandas
import os.path
Config.LOADSBMLOPTIONS_RECOMPILE = True

workingDir = r'/home/mkoenig/git/tellurium/examples/tellurium-files/phrasedml/results/_te_parameterScan2D'

# --------------------------------------------------------
# Models
# --------------------------------------------------------
# Model <model_3>
model_3 = te.loadSBMLModel(os.path.join(workingDir, 'parameterScan2D.xml'))

# --------------------------------------------------------
# Tasks
# --------------------------------------------------------
# Task <task_1>
# not part of any DataGenerator: task_1

# Task <repeatedtask_1>
# not part of any DataGenerator: repeatedtask_1

# Task <repeatedtask_2>

repeatedtask_2 = []
__range__uniform_linear_for_J4_KK5 = np.linspace(start=1.0, stop=40.0, num=11)
for __k__uniform_linear_for_J4_KK5, __value__uniform_linear_for_J4_KK5 in enumerate(__range__uniform_linear_for_J4_KK5):
Exemplo n.º 56
0
# coding: utf-8

# Back to the main [Index](../index.ipynb)

# ### Model loading from BioModels
# Models can be easily retrieved from BioModels via their identifier.

# In[1]:

#!!! DO NOT CHANGE !!! THIS FILE WAS CREATED AUTOMATICALLY FROM NOTEBOOKS !!! CHANGES WILL BE OVERWRITTEN !!! CHANGE CORRESPONDING NOTEBOOK FILE !!!
from __future__ import print_function
import tellurium as te

# Load model from biomodels.
r = te.loadSBMLModel("http://www.ebi.ac.uk/biomodels-main/download?mid=BIOMD0000000010")
result = r.simulate(0, 3000, 5000)
r.plot(result);


# In[2]: