def create_protein_decay(parameter_values=None):
    # Instantiate Model
    model = gillespy2.Model(name="Protein Decay")

    # Define Variables (GillesPy2.Species)
    protein = gillespy2.Species(name='protein', initial_value=50)

    # Add Variables to Model
    model.add_species(protein)

    # Define Parameters
    decayrate = gillespy2.Parameter(name='decayrate', expression=0.05)

    # Add Parameters to Model
    model.add_parameter(decayrate)

    # Define Reactions
    reaction = gillespy2.Reaction(
        name="decay", rate='decayrate', reactants={'protein': 1}, products={}
    )

    # Add Reactions to Model
    model.add_reaction(reaction)

    # Define Timespan
    tspan = gillespy2.TimeSpan.linspace(t=100, num_points=101)

    # Set Model Timespan
    model.timespan(tspan)
    return model
 def create_event_test_model(parameter_values=None):
     model = gillespy2.Model(name='Event Test Model')
     model.add_species([gillespy2.Species(name='S', initial_value=0)])
     model.add_parameter(
         gillespy2.Parameter(name='event_tracker', expression=99))
     model.add_parameter(
         gillespy2.Parameter(name='event_tracker2', expression=0))
     model.add_reaction(
         gillespy2.Reaction(
             name='r1',
             products={'S': 1},
             rate=model.listOfParameters['event_tracker2']))
     eventTrig1 = gillespy2.EventTrigger(expression='t>=2')
     event1 = gillespy2.Event(name='event1', trigger=eventTrig1)
     event1.add_assignment(
         gillespy2.EventAssignment(variable='event_tracker',
                                   expression='t'))
     eventTrig2 = gillespy2.EventTrigger(
         expression='t >= event_tracker + 2')
     event2 = gillespy2.Event(name='event2', trigger=eventTrig2)
     event2.add_assignment(
         gillespy2.EventAssignment(variable='event_tracker2',
                                   expression='t'))
     model.add_event([event1, event2])
     return model
Exemple #3
0
def convert(filename, model_name=None, gillespy_model=None, report_silently_with_sbml_error=False):

    sbml_model, errors = __read_sbml_model(filename)
    
    if sbml_model is None:
        if report_silently_with_sbml_error:
            return None, errors
        errs = '\n\t'.join(errors)
        raise SBMLError(f"SBML model import failed.  Reason Given: \n\t{errs}")

    if len(errors) > 0 and not report_silently_with_sbml_error:
        from gillespy2 import log
        errs = '\n\t'.join(errors)
        log.warning(f"Error were detected in the SBML model.  Error: \n\t{errs}")

    if model_name is None:
        model_name = sbml_model.getName()
    if gillespy_model is None:
        gillespy_model = gillespy2.Model(name=model_name)
    gillespy_model.units = "concentration"

    __get_function_definitions(sbml_model, gillespy_model)
    __get_parameters(sbml_model, gillespy_model)
    __get_species(sbml_model, gillespy_model, errors)
    __get_compartments(sbml_model, gillespy_model)
    __get_reactions(sbml_model, gillespy_model, errors)
    __get_rules(sbml_model, gillespy_model, errors)
    __get_constraints(sbml_model, gillespy_model)
    __get_events(sbml_model, gillespy_model)
    __get_initial_assignments(sbml_model, gillespy_model)
    __resolve_evals(gillespy_model, init_state)


    return gillespy_model, errors
        def create_boundary_condition_test_model(parameter_values=None):
            model = gillespy2.Model(name="BoundaryConditionTestModel")
            s1 = gillespy2.Species(name="S1", boundary_condition=True, initial_value=0.001, mode='continuous')
            s2 = gillespy2.Species(name="S2", boundary_condition=False, initial_value=0.002, mode='continuous')
            s3 = gillespy2.Species(name="S3", boundary_condition=False, initial_value=0.001, mode='continuous')
            s4 = gillespy2.Species(name="S4", boundary_condition=True, initial_value=0.002, mode='continuous')
            model.add_species([s1, s2, s3, s4])

            k1 = gillespy2.Parameter(name="k1", expression="0.75")
            k2 = gillespy2.Parameter(name="k2", expression="0.25")
            model.add_parameter([k1, k2])

            reaction1 = gillespy2.Reaction(name="reaction1", propensity_function="vol*k1*S1*S2",
                                           reactants={s1: 1, s2: 1},
                                           products={s3: 1})
            reaction2 = gillespy2.Reaction(name="reaction2", propensity_function="vol*k2*S3",
                                           reactants={s3: 1},
                                           products={s1: 1, s2: 1})
            reaction3 = gillespy2.Reaction(name="reaction3", propensity_function="vol*k2*S3",
                                           reactants={s1: 1, s2: 2, s3: 1},
                                           products={s4: 1})
            model.add_reaction([reaction1, reaction2, reaction3])

            model.timespan(numpy.linspace(0, 20, 51))
            return model
Exemple #5
0
    def test_model_add__multiple_components__in_order(self):
        import gillespy2

        s1 = gillespy2.Species(name="s1", initial_value=29)
        k1 = gillespy2.Parameter(name="k1", expression=29)
        r1 = gillespy2.Reaction(name="r1", reactants={"s1": 1}, rate="k1")
        rr1 = gillespy2.RateRule(name="rr1", variable="k1", formula="29")
        ar1 = gillespy2.AssignmentRule(name="ar1", variable="s1", formula="29")
        ea = gillespy2.EventAssignment(name="ea",
                                       variable="k1",
                                       expression="29")
        et = gillespy2.EventTrigger(expression="t > 29")
        e1 = gillespy2.Event(name="e1", trigger=et, assignments=[ea])
        divide = gillespy2.FunctionDefinition(name="divide",
                                              function="x / y",
                                              args=["x", "y"])
        tspan = gillespy2.TimeSpan(range(100))

        model = gillespy2.Model(name="Test Model")
        model.add([s1, k1, r1, rr1, ar1, e1, divide, tspan])

        self.assertIn("ar1", model.listOfAssignmentRules)
        self.assertIn("e1", model.listOfEvents)
        self.assertIn("divide", model.listOfFunctionDefinitions)
        self.assertIn("k1", model.listOfParameters)
        self.assertIn("rr1", model.listOfRateRules)
        self.assertIn("r1", model.listOfReactions)
        self.assertIn("s1", model.listOfSpecies)
        self.assertEqual(tspan, model.tspan)
Exemple #6
0
def cbsa2gillespy(cbsa_model):
    import gillespy2 as glp
    
    gilles = glp.Model(name="Model")

    k = [glp.Parameter(name='k'+str(i), expression=cbsa_model.exp_k[i]) for i in range(1,cbsa_model.exp_n_reactions)]
    gilles.add_parameter(k)
    mols = [glp.Species(name='M'+str(i), initial_value=int(cbsa_model.exp_x0[i])) for i in range(1,cbsa_model.exp_n_molecules)]
    gilles.add_species(mols)
    
    reactions = []
    
    for i in range(1,cbsa_model.exp_n_reactions):
        reactants = list(np.where(cbsa_model.expS[:,i] < 0)[0])
        reactants_sto = list(cbsa_model.expS[:,i][reactants]*-1)
        modifiers = list(np.where(cbsa_model.expR[:,i] > 0)[0])
        modifiers_sto = list(cbsa_model.expR[:,i][modifiers])
        products = list(np.where(cbsa_model.expS[:,i] > 0)[0])
        products_sto = list(cbsa_model.expS[:,i][products])
        
        reactants += modifiers
        reactants_sto += modifiers_sto
        products += modifiers
        products_sto += modifiers_sto
        
        reactions.append(glp.Reaction(name="R"+str(i),
                                      rate=k[i-1],
                                      reactants={mols[reactants[j]-1]:reactants_sto[j] for j in range(len(reactants))},
                                      products={mols[products[j]-1]:products_sto[j] for j in range(len(products))}
                                     )
                        )
    
    gilles.add_reaction(reactions)
    
    return gilles
    def test_compile_w_spaces(self):
        import gillespy2
        self.solvers = [
            gillespy2.ODECSolver, gillespy2.SSACSolver,
            gillespy2.TauLeapingCSolver, gillespy2.TauHybridCSolver
        ]

        # create a model
        model = gillespy2.Model(name="Michaelis_Menten")

        # parameters
        rate1 = gillespy2.Parameter(name='rate1', expression=0.0017)
        rate2 = gillespy2.Parameter(name='rate2', expression=0.5)
        rate3 = gillespy2.Parameter(name='rate3', expression=0.1)
        model.add_parameter([rate1, rate2, rate3])

        # Species
        A = gillespy2.Species(name='A', initial_value=301)
        B = gillespy2.Species(name='B', initial_value=120)
        C = gillespy2.Species(name='C', initial_value=0)
        D = gillespy2.Species(name='D', initial_value=0)
        model.add_species([A, B, C, D])

        # reactions
        r1 = gillespy2.Reaction(name="r1",
                                reactants={
                                    A: 1,
                                    B: 1
                                },
                                products={C: 1},
                                rate=rate1)

        r2 = gillespy2.Reaction(name="r2",
                                reactants={C: 1},
                                products={
                                    A: 1,
                                    B: 1
                                },
                                rate=rate2)

        r3 = gillespy2.Reaction(name="r3",
                                reactants={C: 1},
                                products={
                                    B: 1,
                                    D: 1
                                },
                                rate=rate3)
        model.add_reaction([r1, r2, r3])
        model.timespan(gillespy2.TimeSpan.linspace(t=100, num_points=101))

        # run the model
        for solver in self.solvers:
            with self.subTest(solver=solver.name):
                if platform.system() == "Windows":
                    with self.assertRaises(gillespy2.SimulationError):
                        model.run(solver=solver)
                else:
                    result = model.run(solver=solver)
                    self.assertTrue(gillespy2.__file__ == os.path.join(
                        self.prefix_base_dir, 'A SPACE/gillespy2/__init__.py'))
Exemple #8
0
 def create_stoch_test_1(parameter_values=None):
     model = gillespy2.Model(name='StochTest1')
     A = gillespy2.Species(name='A', initial_value=10)
     B = gillespy2.Species(name='B', initial_value=0)
     model.add_species([A, B])
     k = gillespy2.Parameter(name='k', expression=10)
     model.add_parameter([k])
     r = gillespy2.Reaction(name='r',
                            reactants={A: 2},
                            products={B: 1},
                            rate=k)
     model.add_reaction([r])
     model.timespan(np.linspace(0, 100, 101))
     return model
Exemple #9
0
 def create_stoch_test_1(parameter_values=None):
     model = gillespy2.Model(name='StochTest1')
     A = gillespy2.Species(name='A', initial_value=10)
     B = gillespy2.Species(name='B', initial_value=0)
     model.add_species([A, B])
     k = gillespy2.Parameter(name='k', expression=10)
     model.add_parameter([k])
     r = gillespy2.Reaction(name='r',
                            reactants={A: 1},
                            products={B: 1},
                            propensity_function="k*A/vol"
                            )  # testing if 'vol' is a pre-set variable
     model.add_reaction([r])
     model.timespan(np.linspace(0, 100, 101))
     return model
 def create_truncated_state_model(parameter_values=None):
     model = gillespy2.Model(name="TruncatedStateModel")
     S1 = gillespy2.Species(name="S1", initial_value=0, mode="discrete")
     rate = gillespy2.Species(name="rate",
                              initial_value=0.9999,
                              mode="continuous")
     model.add_species([S1, rate])
     model.add_rate_rule(
         gillespy2.RateRule(variable="rate",
                            formula="-1/((t+0.9999)**2)"))
     model.add_reaction(
         # Because S1 is a "discrete" species, our reaction will be marked "stochastic."
         gillespy2.Reaction(products={S1: 1},
                            propensity_function="10.0*rate"))
     return model
        def create_rate_rule_test_model(parameter_values=None):
            model = gillespy2.Model(name="RateRuleTestModel")
            s1 = gillespy2.Species(name="S1", initial_value=0.015, mode='continuous')
            s2 = gillespy2.Species(name="S2", initial_value=0.0, mode='continuous')
            s3 = gillespy2.Species(name="S3", initial_value=1.0, mode='continuous')
            model.add_species([s1, s2, s3])

            k1 = gillespy2.Parameter(name="k1", expression="1.0")
            model.add_parameter([k1])

            rule1 = gillespy2.RateRule(name="rule1", variable="S1", formula="-k1*S1")
            rule2 = gillespy2.RateRule(name="rule2", variable="S2", formula="k1*S1")
            rule3 = gillespy2.RateRule(name="rule3", variable="S3", formula="0.015-(S1+S2)")
            model.add_rate_rule([rule1, rule2, rule3])

            model.timespan(numpy.linspace(0, 20, 51))
            return model
    def create_base_event_model(s1, s2, rate):
        model = gillespy2.Model(name="BasicEventModel")

        s1 = gillespy2.Species(name="S1", initial_value=s1, mode="continuous")
        s2 = gillespy2.Species(name="S2", initial_value=s2, mode="continuous")
        model.add_species([s1, s2])

        rate = gillespy2.Parameter(name="k1", expression=rate)
        model.add_parameter(rate)

        r1 = gillespy2.Reaction(
            name="r1",
            reactants={s1: 1},
            products={s2: 1},
            rate=rate,
        )
        model.add_reaction(r1)
        return model
Exemple #13
0
def convert(filename, model_name=None, gillespy_model=None):

    sbml_model, errors = __read_sbml_model(filename)
    if model_name is None:
        model_name = sbml_model.getName()
    if gillespy_model is None:
        gillespy_model = gillespy2.Model(name=model_name)
    gillespy_model.units = "concentration"

    __get_function_definitions(sbml_model, gillespy_model)
    __get_parameters(sbml_model, gillespy_model)
    __get_species(sbml_model, gillespy_model, errors)
    __get_compartments(sbml_model, gillespy_model)
    __get_reactions(sbml_model, gillespy_model, errors)
    __get_rules(sbml_model, gillespy_model, errors)
    __get_constraints(sbml_model, gillespy_model)
    __get_events(sbml_model, gillespy_model)
    __get_initial_assignments(sbml_model, gillespy_model)
    __resolve_evals(gillespy_model, init_state)

    return gillespy_model, errors
Exemple #14
0
def create_dimerization(parameter_values=None):
    # Initialize Model
    model = gillespy2.Model(name="Dimerization")

    # Define Variables (GillesPy2.Species)
    m = gillespy2.Species(name='monomer', initial_value=30)
    d = gillespy2.Species(name='dimer', initial_value=0)

    # Add Variables to Model
    model.add_species([m, d])

    # Define Parameters
    k_c = gillespy2.Parameter(name='k_c', expression=0.005)
    k_d = gillespy2.Parameter(name='k_d', expression=0.08)

    # Add Parameters to Model
    model.add_parameter([k_c, k_d])

    # Define Reactions
    r_creation = gillespy2.Reaction(name="r_creation",
                                    reactants={'monomer': 2},
                                    products={'dimer': 1},
                                    rate='k_c')
    r_dissociation = gillespy2.Reaction(name="r_dissociation",
                                        reactants={'dimer': 1},
                                        products={'monomer': 2},
                                        rate='k_d')

    # Add Reactions to Model
    model.add_reaction([r_creation, r_dissociation])

    # Define Timespan
    tspan = gillespy2.TimeSpan.linspace(t=100, num_points=101)

    # Set Model Timespan
    model.timespan(tspan)
    return model
Exemple #15
0
def create_vilar_oscillator(parameter_values=None):
    model = gillespy2.Model(name="VilarOscillator")

    # Set System Volume
    model.volume = 1

    # Define Variables (GillesPy2.Species)
    Da = gillespy2.Species(name="Da", initial_value=1, mode="discrete")
    Da_prime = gillespy2.Species(name="Da_prime",
                                 initial_value=0,
                                 mode="discrete")
    Ma = gillespy2.Species(name="Ma", initial_value=0, mode="discrete")
    Dr = gillespy2.Species(name="Dr", initial_value=1, mode="discrete")
    Dr_prime = gillespy2.Species(name="Dr_prime",
                                 initial_value=0,
                                 mode="discrete")
    Mr = gillespy2.Species(name="Mr", initial_value=0, mode="discrete")
    C = gillespy2.Species(name="C", initial_value=0, mode="discrete")
    A = gillespy2.Species(name="A", initial_value=0, mode="discrete")
    R = gillespy2.Species(name="R", initial_value=0, mode="discrete")

    # Add Vairables to Model
    model.add_species([Da, Da_prime, Ma, Dr, Dr_prime, Mr, C, A, R])

    # Define Parameters
    alphaA = gillespy2.Parameter(name="alphaA", expression=50)
    alphaA_prime = gillespy2.Parameter(name="alphaA_prime", expression=500)
    alphaR = gillespy2.Parameter(name="alphaR", expression=0.01)
    alphaR_prime = gillespy2.Parameter(name="alphaR_prime", expression=50)
    betaA = gillespy2.Parameter(name="betaA", expression=50)
    betaR = gillespy2.Parameter(name="betaR", expression=5)
    deltaMA = gillespy2.Parameter(name="deltaMA", expression=10)
    deltaMR = gillespy2.Parameter(name="deltaMR", expression=0.5)
    deltaA = gillespy2.Parameter(name="deltaA", expression=1)
    deltaR = gillespy2.Parameter(name="deltaR", expression=0.2)
    gammaA = gillespy2.Parameter(name="gammaA", expression=1)
    gammaR = gillespy2.Parameter(name="gammaR", expression=1)
    gammaC = gillespy2.Parameter(name="gammaC", expression=2)
    thetaA = gillespy2.Parameter(name="thetaA", expression=50)
    thetaR = gillespy2.Parameter(name="thetaR", expression=100)

    # Add Parameters to Model
    model.add_parameter([
        alphaA, alphaA_prime, alphaR, alphaR_prime, betaA, betaR, deltaMA,
        deltaMR, deltaA, deltaR, gammaA, gammaR, gammaC, thetaA, thetaR
    ])

    # Define Reactions
    r1 = gillespy2.Reaction(name="r1",
                            reactants={
                                'A': 1,
                                'R': 1
                            },
                            products={'C': 1},
                            rate="gammaC")
    r2 = gillespy2.Reaction(name="r2",
                            reactants={'A': 1},
                            products={},
                            rate="deltaA")
    r3 = gillespy2.Reaction(name="r3",
                            reactants={'C': 1},
                            products={'R': 1},
                            rate="deltaA")
    r4 = gillespy2.Reaction(name="r4",
                            reactants={'R': 1},
                            products={},
                            rate="deltaR")
    r5 = gillespy2.Reaction(name="r5",
                            reactants={
                                'A': 1,
                                'Da': 1
                            },
                            products={'Da_prime': 1},
                            rate="gammaA")
    r6 = gillespy2.Reaction(name="r6",
                            reactants={'Da_prime': 1},
                            products={
                                'A': 1,
                                'Da': 1
                            },
                            rate="thetaA")
    r7 = gillespy2.Reaction(name="r7",
                            reactants={'Da': 1},
                            products={
                                'Da': 1,
                                'Ma': 1
                            },
                            rate="alphaA")
    r8 = gillespy2.Reaction(name="r8",
                            reactants={'Da_prime': 1},
                            products={
                                'Da_prime': 1,
                                'Ma': 1
                            },
                            rate="alphaA_prime")
    r9 = gillespy2.Reaction(name="r9",
                            reactants={'Ma': 1},
                            products={},
                            rate="deltaMA")
    r10 = gillespy2.Reaction(name="r10",
                             reactants={'Ma': 1},
                             products={
                                 'A': 1,
                                 'Ma': 1
                             },
                             rate="betaA")
    r11 = gillespy2.Reaction(name="r11",
                             reactants={
                                 'A': 1,
                                 'Dr': 1
                             },
                             products={'Dr_prime': 1},
                             rate="gammaR")
    r12 = gillespy2.Reaction(name="r12",
                             reactants={'Dr_prime': 1},
                             products={
                                 'A': 1,
                                 'Dr': 1
                             },
                             rate="thetaR")
    r13 = gillespy2.Reaction(name="r13",
                             reactants={'Dr': 1},
                             products={
                                 'Dr': 1,
                                 'Mr': 1
                             },
                             rate="alphaR")
    r14 = gillespy2.Reaction(name="r14",
                             reactants={'Dr_prime': 1},
                             products={
                                 'Dr_prime': 1,
                                 'Mr': 1
                             },
                             rate="alphaR_prime")
    r15 = gillespy2.Reaction(name="r15",
                             reactants={'Mr': 1},
                             products={},
                             rate="deltaMR")
    r16 = gillespy2.Reaction(name="r16",
                             reactants={'Mr': 1},
                             products={
                                 'Mr': 1,
                                 'R': 1
                             },
                             rate="betaR")

    # Add Reactions to Model
    model.add_reaction([
        r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16
    ])

    # Define Timespan
    tspan = gillespy2.TimeSpan.linspace(t=200, num_points=201)

    # Set Model Timespan
    model.timespan(tspan)
    return model
Exemple #16
0
def create_tyson_2_state(parameter_values=None):
    """
    Here, as a test case, we run a simple two-state oscillator (Novak & Tyson
    2008) as an example of a stochastic reaction system.
    """
    system_volume = 300  #system volume
    model = gillespy2.Model(name="tyson-2-state", volume=system_volume)
    model.timespan(np.linspace(0, 100, 101))

    # =============================================
    # Define model species, initial values, parameters, and volume
    # =============================================

    # Parameter values  for this biochemical system are given in
    # concentration units. However, stochastic systems must use population
    # values. For example, a concentration unit of 0.5mol/(L*s)
    # is multiplied by a volume unit, to get a population/s rate
    # constant. Thus, for our non-mass action reactions, we include the
    # parameter "vol" in order to convert population units to concentration
    # units. Volume here = 300.

    P = gillespy2.Parameter(name='P', expression=2.0)
    kt = gillespy2.Parameter(name='kt', expression=20.0)
    kd = gillespy2.Parameter(name='kd', expression=1.0)
    a0 = gillespy2.Parameter(name='a0', expression=0.005)
    a1 = gillespy2.Parameter(name='a1', expression=0.05)
    a2 = gillespy2.Parameter(name='a2', expression=0.1)
    kdx = gillespy2.Parameter(name='kdx', expression=1.0)
    model.add_parameter([P, kt, kd, a0, a1, a2, kdx])

    # Species
    # Initial values of each species (concentration converted to pop.)
    X = gillespy2.Species(name='X',
                          initial_value=int(0.65609071 * system_volume))
    Y = gillespy2.Species(name='Y',
                          initial_value=int(0.85088331 * system_volume))
    model.add_species([X, Y])

    # =============================================
    # Define the reactions within the model
    # =============================================

    # creation of X:
    rxn1 = gillespy2.Reaction(
        name='X production',
        reactants={},
        products={X: 1},
        propensity_function='vol*1/(1+(Y*Y/((vol*vol))))')

    # degradadation of X:
    rxn2 = gillespy2.Reaction(name='X degradation',
                              reactants={X: 1},
                              products={},
                              rate=kdx)

    # creation of Y:
    rxn3 = gillespy2.Reaction(name='Y production',
                              reactants={X: 1},
                              products={
                                  X: 1,
                                  Y: 1
                              },
                              rate=kt)

    # degradation of Y:
    rxn4 = gillespy2.Reaction(name='Y degradation',
                              reactants={Y: 1},
                              products={},
                              rate=kd)

    # nonlinear Y term:
    rxn5 = gillespy2.Reaction(
        name='Y nonlin',
        reactants={Y: 1},
        products={},
        propensity_function='Y/(a0 + a1*(Y/vol)+a2*Y*Y/(vol*vol))')

    model.add_reaction([rxn1, rxn2, rxn3, rxn4, rxn5])
    return model
Exemple #17
0
 def create_test_model(parameter_values=None):
     model = gillespy2.Model(name="TestModel")
     model.add_species(gillespy2.Species(name="S", initial_value=0))
     model.timespan(np.linspace(0, 10, 11))
     return model
Exemple #18
0
def create_tyson_oscillator(parameter_values=None):
    # Initialize Model
    model = gillespy2.Model(name="tyson-2-state")

    # Set System Volume
    model.volume = 300

    # Define Variables (GillesPy2.Species)
    # Initial values of each species (concentration converted to pop.)
    X = gillespy2.Species(name='X',
                          initial_value=int(0.65609071 * model.volume))
    Y = gillespy2.Species(name='Y',
                          initial_value=int(0.85088331 * model.volume))

    # Add Variables to Model
    model.add_species([X, Y])

    # Define Parameters
    P = gillespy2.Parameter(name='P', expression=2.0)
    kt = gillespy2.Parameter(name='kt', expression=20.0)
    kd = gillespy2.Parameter(name='kd', expression=1.0)
    a0 = gillespy2.Parameter(name='a0', expression=0.005)
    a1 = gillespy2.Parameter(name='a1', expression=0.05)
    a2 = gillespy2.Parameter(name='a2', expression=0.1)
    kdx = gillespy2.Parameter(name='kdx', expression=1.0)

    # Add Parameters to Model
    model.add_parameter([P, kt, kd, a0, a1, a2, kdx])

    # Define Reactions
    # creation of X:
    rxn1 = gillespy2.Reaction(
        name='X production',
        reactants={},
        products={'X': 1},
        propensity_function='vol*1/(1+(Y*Y/((vol*vol))))')
    # degradadation of X:
    rxn2 = gillespy2.Reaction(name='X degradation',
                              reactants={'X': 1},
                              products={},
                              rate='kdx')
    # creation of Y:
    rxn3 = gillespy2.Reaction(name='Y production',
                              reactants={'X': 1},
                              products={
                                  'X': 1,
                                  'Y': 1
                              },
                              rate='kt')
    # degradation of Y:
    rxn4 = gillespy2.Reaction(name='Y degradation',
                              reactants={'Y': 1},
                              products={},
                              rate='kd')
    # nonlinear Y term:
    rxn5 = gillespy2.Reaction(
        name='Y nonlin',
        reactants={'Y': 1},
        products={},
        propensity_function='Y/(a0 + a1*(Y/vol)+a2*Y*Y/(vol*vol))')

    # Add Reactions to Model
    model.add_reaction([rxn1, rxn2, rxn3, rxn4, rxn5])

    # Define Timespan
    tspan = gillespy2.TimeSpan.linspace(t=20, num_points=21)

    # Set Model Timespan
    model.timespan(tspan)
    return model
Exemple #19
0
def convert(filename, model_name=None, gillespy_model=None):
    try:
        import libsbml
    except ImportError:
        raise ImportError('libsbml is required to convert SBML files for GillesPy.')

    document = libsbml.readSBML(filename)
    errors = []
    error_count = document.getNumErrors()
    if error_count > 0:
        for i in range(error_count):
            error = document.getError(i)
            converter_code = 0
            converter_code = -10

            errors.append(["SBML {0}, code {1}, line {2}: {3}".format(error.getSeverityAsString(), error.getErrorId(),
                                                                      error.getLine(), error.getMessage()),
                           converter_code])
    if min([code for error, code in errors] + [0]) < 0:
        return None, errors
    model = document.getModel()
    if model_name is None:
        model_name = model.getName()
    if gillespy_model is None:
        gillespy_model = gillespy2.Model(name=model_name)
    gillespy_model.units = "concentration"
    for i in range(model.getNumSpecies()):
        species = model.getSpecies(i)
        if species.getId() == 'EmptySet':
            errors.append([
                              "EmptySet species detected in model on line {0}. EmptySet is not an explicit species in "
                              "gillespy".format(
                                  species.getLine()), 0])
            continue
        name = species.getId()
        if species.isSetInitialAmount():
            value = int(species.getInitialAmount())
            mode = 'dynamic'
        elif species.isSetInitialConcentration():
            value = species.getInitialConcentration()
            mode = 'continuous'
        else:
            rule = model.getRule(species.getId())
            if rule:
                msg = ""
                if rule.isAssignment():
                    msg = "assignment "
                elif rule.isRate():
                    msg = "rate "
                elif rule.isAlgebraic():
                    msg = "algebraic "

                msg += "rule"

                errors.append([
                                  "Species '{0}' does not have any initial conditions. Associated {1} '{2}' found, "
                                  "but {1}s are not supported in gillespy. Assuming initial condition 0".format(
                                      species.getId(), msg, rule.getId()), 0])
            else:
                errors.append([
                                  "Species '{0}' does not have any initial conditions or rules. Assuming initial "
                                  "condition 0".format(
                                      species.getId()), 0])

            value = 0

        is_negative = value < 0.0
        gillespy_species = gillespy2.Species(name=name, initial_value=value, allow_negative_populations= is_negative, mode=mode)
        gillespy_model.add_species([gillespy_species])

    for i in range(model.getNumParameters()):
        parameter = model.getParameter(i)
        name = parameter.getId()
        value = parameter.getValue()

        gillespy_parameter = gillespy2.Parameter(name=name, expression=value)
        gillespy_model.add_parameter([gillespy_parameter])

    for i in range(model.getNumCompartments()):
        compartment = model.getCompartment(i)
        name = compartment.getId()
        value = compartment.getSize()

        gillespy_parameter = gillespy2.Parameter(name=name, expression=value)
        gillespy_model.add_parameter([gillespy_parameter])

    # local parameters
    for i in range(model.getNumReactions()):
        reaction = model.getReaction(i)
        kinetic_law = reaction.getKineticLaw()

        for j in range(kinetic_law.getNumParameters()):
            parameter = kinetic_law.getParameter(j)
            name = parameter.getId()
            value = parameter.getValue()
            gillespy_parameter = gillespy2.Parameter(name=name, expression=value)
            gillespy_model.add_parameter([gillespy_parameter])

    # reactions
    for i in range(model.getNumReactions()):
        reaction = model.getReaction(i)
        name = reaction.getId()

        reactants = {}
        products = {}

        for j in range(reaction.getNumReactants()):
            species = reaction.getReactant(j)

            if species.getSpecies() == "EmptySet":
                errors.append([
                                  "EmptySet species detected as reactant in reaction '{0}' on line {1}. EmptySet is "
                                  "not an explicit species in gillespy".format(
                                      reaction.getId(), species.getLine()), 0])
            else:
                reactants[species.getSpecies()] = species.getStoichiometry()

        # get products
        for j in range(reaction.getNumProducts()):
            species = reaction.getProduct(j)

            if species.getSpecies() == "EmptySet":
                errors.append([
                                  "EmptySet species detected as product in reaction '{0}' on line {1}. EmptySet is "
                                  "not an explicit species in gillespy".format(
                                      reaction.getId(), species.getLine()), 0])
            else:
                products[species.getSpecies()] = species.getStoichiometry()

        # propensity
        kinetic_law = reaction.getKineticLaw()
        propensity = kinetic_law.getFormula()

        gillespy_reaction = gillespy2.Reaction(name=name, reactants=reactants, products=products,
                                             propensity_function=propensity)

        gillespy_model.add_reaction([gillespy_reaction])

    for i in range(model.getNumRules()):
        rule = model.getRule(i)

        t = []

        if rule.isCompartmentVolume():
            t.append('compartment')
        if rule.isParameter():
            t.append('parameter')
        elif rule.isAssignment():
            t.append('assignment')
        elif rule.isRate():
            t.append('rate')
        elif rule.isAlgebraic():
            t.append('algebraic')

        if len(t) > 0:
            t[0] = t[0].capitalize()

            msg = ", ".join(t)
            msg += " rule"
        else:
            msg = "Rule"

        errors.append(["{0} '{1}' found on line '{2}' with equation '{3}'. gillespy does not support SBML Rules".format(
            msg, rule.getId(), rule.getLine(), libsbml.formulaToString(rule.getMath())), -5])

    for i in range(model.getNumCompartments()):
        compartment = model.getCompartment(i)

        errors.append([
                          "Compartment '{0}' found on line '{1}' with volume '{2}' and dimension '{3}'. gillespy "
                          "assumes a single well-mixed, reaction volume".format(
                              compartment.getId(), compartment.getLine(), compartment.getVolume(),
                              compartment.getSpatialDimensions()), -5])

    for i in range(model.getNumConstraints()):
        constraint = model.getConstraint(i)

        errors.append([
                          "Constraint '{0}' found on line '{1}' with equation '{2}'. gillespy does not support SBML "
                          "Constraints".format(
                              constraint.getId(), constraint.getLine(), libsbml.formulaToString(constraint.getMath())),
                          -5])

    for i in range(model.getNumEvents()):
        event = model.getEvent(i)

        errors.append([
                          "Event '{0}' found on line '{1}' with trigger equation '{2}'. gillespy does not support "
                          "SBML Events".format(
                              event.getId(), event.getLine(), libsbml.formulaToString(event.getTrigger().getMath())),
                          -5])

    for i in range(model.getNumFunctionDefinitions()):
        function = model.getFunctionDefinition(i)

        errors.append([
                          "Function '{0}' found on line '{1}' with equation '{2}'. gillespy does not support SBML "
                          "Function Definitions".format(
                              function.getId(), function.getLine(), libsbml.formulaToString(function.getMath())), -5])

    return gillespy_model, errors