Example #1
0
def test_masteq():
    mdl = smod.Model()

    A = smod.Spec('A', mdl)

    volsys = smod.Volsys('vsys', mdl)

    # Production
    R1 = smod.Reac('R1', volsys, lhs=[], rhs=[A], kcst=KCST_f)
    R2 = smod.Reac('R2', volsys, lhs=[A], rhs=[], kcst=KCST_b)

    geom = sgeom.Geom()

    comp1 = sgeom.Comp('comp1', geom, VOL)
    comp1.addVolsys('vsys')

    rng = srng.create('mt19937', 1000)
    rng.initialize(int(time.time() % 4294967295))

    sim = ssolv.Wmdirect(mdl, geom, rng)
    sim.reset()

    tpnts = numpy.arange(0.0, INT, DT)
    ntpnts = tpnts.shape[0]

    res = numpy.zeros([ntpnts])

    sim.restore('./validation_cp/cp/masteq')

    for t in range(0, ntpnts):
        sim.run(tpnts[t])
        res[t] = sim.getCompCount('comp1', 'A')

    def fact(x):
        return (1 if x == 0 else x * fact(x - 1))

    # Do cumulative count, but not comparing them all.
    # Don't get over 50 (I hope)
    steps_n_res = numpy.zeros(50)
    for r in res:
        steps_n_res[int(r)] += 1
    for s in range(50):
        steps_n_res[s] = steps_n_res[s] / ntpnts

    passed = True
    max_err = 0.0

    k1 = KCST_b
    k2 = KCST_f * (6.022e23 * 1.0e-15)

    # Compare 5 to 15
    for m in range(5, 16):
        analy = (1.0 / fact(m)) * math.pow((k2 / k1), m) * math.exp(-(k2 / k1))
        assert (tol_funcs.tolerable(steps_n_res[m], analy, tolerance))
Example #2
0
def test_forev():
    mdl = smod.Model()

    A = smod.Spec('A', mdl)
    B = smod.Spec('B', mdl)

    volsys = smod.Volsys('vsys', mdl)

    R1 = smod.Reac('R1', volsys, lhs=[A], rhs=[B], kcst=KCST_f)
    R2 = smod.Reac('R2', volsys, lhs=[B], rhs=[A], kcst=KCST_b)

    geom = sgeom.Geom()

    comp1 = sgeom.Comp('comp1', geom, VOL)
    comp1.addVolsys('vsys')

    rng = srng.create('mt19937', 512)
    rng.initialize(int(time.time() % 4294967295))

    sim = ssolv.Wmdirect(mdl, geom, rng)
    sim.reset()

    tpnts = numpy.arange(0.0, INT, DT)
    ntpnts = tpnts.shape[0]

    res_m = numpy.zeros([NITER, ntpnts, 2])

    for i in range(0, NITER):
        sim.restore('./validation_cp/cp/first_order_rev')
        for t in range(0, ntpnts):
            sim.run(tpnts[t])
            res_m[i, t, 0] = sim.getCompConc('comp1', 'A') * 1e6
            res_m[i, t, 1] = sim.getCompConc('comp1', 'B') * 1e6

    mean_res = numpy.mean(res_m, 0)

    Aeq = COUNT * (KCST_b /
                   KCST_f) / (1 +
                              (KCST_b / KCST_f)) / (VOL * 6.0221415e26) * 1e6
    Beq = (COUNT / (VOL * 6.0221415e26)) * 1e6 - Aeq

    max_err = 0.0
    passed = True
    for i in range(ntpnts):
        if i < 7: continue
        assert (tol_funcs.tolerable(mean_res[i, 0], Aeq, tolerance))
        assert (tol_funcs.tolerable(mean_res[i, 1], Beq, tolerance))
Example #3
0
def cbsa2steps(cbsa_model):
    
    import steps.geom as swm
    import steps.model as smodel
    import steps.rng as srng
    import steps.solver as ssolver
    
    mdl = smodel.Model()
    vsys = smodel.Volsys('vsys', mdl)    
    mols = [smodel.Spec('M'+str(i), mdl) for i in range(1,cbsa_model.exp_n_molecules)]    
    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
        
        reactants_objs = [[mols[reactants[j]-1] for k in range(reactants_sto[j])] for j in range(len(reactants))]
        reactants_objs = [item for sublist in reactants_objs for item in sublist]
        
        products_objs = [[mols[products[j]-1] for k in range(products_sto[j])] for j in range(len(products))]
        products_objs = [item for sublist in products_objs for item in sublist]
        
        reactions.append(smodel.Reac("R"+str(i), vsys, lhs=reactants_objs, rhs=products_objs, kcst=cbsa_model.exp_k[i]))
    
    wmgeom = swm.Geom()

    comp = swm.Comp('comp', wmgeom)
    comp.addVolsys('vsys')
    comp.setVol(1.6667e-21)

    r = srng.create('mt19937', 256)
    r.initialize(int(timer()))
    sim = ssolver.Wmdirect(mdl, wmgeom, r)
    sim.reset()

    for i in range(1,cbsa_model.exp_n_molecules):
        sim.setCompConc('comp', 'M'+str(i), cbsa_model.exp_x0[i]*1e-6)
    
    return sim
Example #4
0
def get_solver(solver_type, mdl, geom):
    r = srng.create('r123', 1000)
    if solver_type == "Wmrk4":
        solver = ssolv.Wmrk4(mdl, geom)
        solver.setDT(1e-5)
        return solver
    elif solver_type == "Wmdirect":
        solver = ssolv.Wmdirect(mdl, geom, r)
        return solver
    if solver_type == "Wmrssa":
        solver = ssolv.Wmrssa(mdl, geom, r)
        return solver
    elif solver_type == "Tetexact":
        solver = ssolv.Tetexact(mdl, geom, r)
        return solver
    else:
        assert (False)
Example #5
0
def test_foirev():
    mdl = smod.Model()

    A = smod.Spec('A', mdl)
    volsys = smod.Volsys('vsys', mdl)
    R1 = smod.Reac('R1', volsys, lhs=[A], rhs=[], kcst=KCST)

    geom = sgeom.Geom()
    comp1 = sgeom.Comp('comp1', geom, VOL)
    comp1.addVolsys('vsys')

    rng = srng.create('mt19937', 1000)
    rng.initialize(int(time.time() % 4294967295))

    sim = ssolv.Wmdirect(mdl, geom, rng)
    sim.reset()

    tpnts = np.arange(0.0, INT, DT)
    ntpnts = tpnts.shape[0]

    res_m = np.zeros([NITER, ntpnts, 1])
    res_std1 = np.zeros([ntpnts, 1])
    res_std2 = np.zeros([ntpnts, 1])

    for i in range(0, NITER):
        sim.restore('./validation_cp/cp/first_order_irev')
        for t in range(0, ntpnts):
            sim.run(tpnts[t])
            res_m[i, t, 0] = sim.getCompCount('comp1', 'A')

    mean_res = np.mean(res_m, 0)
    std_res = np.std(res_m, 0)

    m_tol = 0
    s_tol = 0

    passed = True
    for i in range(ntpnts):
        if i == 0: continue
        analy = N * np.exp(-KCST * tpnts[i])
        std = np.power((N * (np.exp(-KCST * tpnts[i])) *
                        (1 - (np.exp(-KCST * tpnts[i])))), 0.5)
        if not tol_funcs.tolerable(analy, mean_res[i], tolerance):
            passed = False
        assert (tol_funcs.tolerable(std, std_res[i], tolerance))
Example #6
0
def run_sim():
    # Set up and run the simulations once, before the tests
    # analyze the results.

    ##################### First order irreversible #########################

    global KCST_foi, N_foi, tolerance_foi

    KCST_foi = 5  # The reaction constant
    N_foi = 50  # Can set count or conc

    NITER_foi = 100000  # The number of iterations

    # Tolerance for the comparison:
    # In test runs, with good code, < 1%  will fail with a 1.5% tolerance
    tolerance_foi = 2.0 / 100

    ####################### First order reversible #########################

    global KCST_f_for, KCST_b_for, COUNT_for, tolerance_for

    KCST_f_for = 10.0  # The reaction constant
    KCST_b_for = 2.0

    COUNT_for = 100000  # Can set count or conc

    NITER_for = 10  # The number of iterations

    # In test runs, with good code, <0.1% will fail with a tolerance of 1%
    tolerance_for = 1.0 / 100

    ####################### Second order irreversible A2 ###################

    global KCST_soA2, CONCA_soA2, tolerance_soA2

    KCST_soA2 = 10.0e6  # The reaction constant

    CONCA_soA2 = 10.0e-6

    NITER_soA2 = 1000  # The number of iterations

    # In test runs, with good code, <0.1% will fail with a tolerance of 2%
    tolerance_soA2 = 1.0 / 100

    ####################### Second order irreversible AA ###################

    global KCST_soAA, CONCA_soAA, CONCB_soAA, tolerance_soAA

    KCST_soAA = 50.0e6  # The reaction constant

    CONCA_soAA = 20.0e-6
    CONCB_soAA = CONCA_soAA

    NITER_soAA = 1000  # The number of iterations

    # In test runs, with good code, <0.1% will fail with a tolerance of 1%
    tolerance_soAA = 1.0 / 100

    ####################### Second order irreversible AB ###################

    global KCST_soAB, CONCA_soAB, CONCB_soAB, tolerance_soAB

    KCST_soAB = 5.0e6  # The reaction constant

    CONCA_soAB = 1.0e-6
    n_soAB = 2
    CONCB_soAB = CONCA_soAB / n_soAB

    NITER_soAB = 1000  # The number of iterations

    # In test runs, with good code, <0.1% will fail with a tolerance of 1%
    tolerance_soAB = 1.0 / 100

    ####################### Third order irreversible A3 ###################

    global KCST_toA3, CONCA_toA3, tolerance_toA3

    KCST_toA3 = 1.0e12  # The reaction constant

    CONCA_toA3 = 100.0e-6

    NITER_toA3 = 1000  # The number of iterations

    # In test runs, with good code, <0.1% will fail with a tolerance of 1%
    tolerance_toA3 = 1.0 / 100

    ####################### Third order irreversible A2B ###################

    global KCST_toA2B, CONCA_toA2B, CONCB_toA2B, tolerance_toA2B

    KCST_toA2B = 0.1e12  # The reaction constant

    CONCA_toA2B = 30.0e-6
    CONCB_toA2B = 20.0e-6

    NITER_toA2B = 1000  # The number of iterations

    # In test runs, with good code, <0.1% will fail with a tolerance of 1%
    tolerance_toA2B = 1.0 / 100

    ####################### Second order irreversible 2D ###################

    global COUNTA_so2d, COUNTB_so2d, CCST_so2d, tolerance_so2d

    COUNTA_so2d = 100.0
    n_so2d = 2.0
    COUNTB_so2d = COUNTA_so2d / n_so2d

    KCST_so2d = 10.0e10  # The reaction constant

    AREA_so2d = 10.0e-12

    CCST_so2d = KCST_so2d / (6.02214179e23 * AREA_so2d)

    NITER_so2d = 1000  # The number of iterations

    # In tests fewer than 0.1% fail with tolerance of 2%
    tolerance_so2d = 2.0 / 100

    ############################ Common parameters ########################

    global VOL

    DT = 0.1  # Sampling time-step
    INT = 1.1  # Sim endtime
    VOL = 9.0e-18

    NITER_max = 100000

    ########################################################################

    mdl = smod.Model()
    volsys = smod.Volsys('vsys', mdl)
    surfsys = smod.Surfsys('ssys', mdl)

    # First order irreversible
    A_foi = smod.Spec('A_foi', mdl)
    R1_foi = smod.Reac('R1_foi', volsys, lhs=[A_foi], rhs=[], kcst=KCST_foi)

    # First order reversible
    A_for = smod.Spec('A_for', mdl)
    B_for = smod.Spec('B_for', mdl)
    R1_for = smod.Reac('R1_for',
                       volsys,
                       lhs=[A_for],
                       rhs=[B_for],
                       kcst=KCST_f_for)
    R2_for = smod.Reac('R2_for',
                       volsys,
                       lhs=[B_for],
                       rhs=[A_for],
                       kcst=KCST_b_for)

    # Second order irreversible A2
    A_soA2 = smod.Spec('A_soA2', mdl)
    C_soA2 = smod.Spec('C_soA2', mdl)
    R1_soA2 = smod.Reac('R1_soA2',
                        volsys,
                        lhs=[A_soA2, A_soA2],
                        rhs=[C_soA2],
                        kcst=KCST_soA2)

    # Second order irreversible AA
    A_soAA = smod.Spec('A_soAA', mdl)
    B_soAA = smod.Spec('B_soAA', mdl)
    C_soAA = smod.Spec('C_soAA', mdl)
    R1_soAA = smod.Reac('R1_soAA',
                        volsys,
                        lhs=[A_soAA, B_soAA],
                        rhs=[C_soAA],
                        kcst=KCST_soAA)

    # Second order irreversible AB
    A_soAB = smod.Spec('A_soAB', mdl)
    B_soAB = smod.Spec('B_soAB', mdl)
    C_soAB = smod.Spec('C_soAB', mdl)
    R1_soAB = smod.Reac('R1_soAB',
                        volsys,
                        lhs=[A_soAB, B_soAB],
                        rhs=[C_soAB],
                        kcst=KCST_soAB)

    # Third order irreversible A3
    A_toA3 = smod.Spec('A_toA3', mdl)
    C_toA3 = smod.Spec('C_toA3', mdl)
    R1_toA3 = smod.Reac('R1_toA3',
                        volsys,
                        lhs=[A_toA3, A_toA3, A_toA3],
                        rhs=[C_toA3],
                        kcst=KCST_toA3)

    # Third order irreversible A2B
    A_toA2B = smod.Spec('A_toA2B', mdl)
    B_toA2B = smod.Spec('B_toA2B', mdl)
    C_toA2B = smod.Spec('C_toA2B', mdl)
    R1_toA3 = smod.Reac('R1_toA2B',
                        volsys,
                        lhs=[A_toA2B, A_toA2B, B_toA2B],
                        rhs=[C_toA2B],
                        kcst=KCST_toA2B)

    # Second order irreversible 2D
    A_so2d = smod.Spec('A_so2d', mdl)
    B_so2d = smod.Spec('B_so2d', mdl)
    C_so2d = smod.Spec('C_so2d', mdl)
    SR1_so2d = smod.SReac('SR1_so2d',
                          surfsys,
                          slhs=[A_so2d, B_so2d],
                          srhs=[C_so2d],
                          kcst=KCST_so2d)

    geom = sgeom.Geom()
    comp1 = sgeom.Comp('comp1', geom, VOL)
    comp1.addVolsys('vsys')
    patch1 = sgeom.Patch('patch1', geom, comp1, area=AREA_so2d)
    patch1.addSurfsys('ssys')

    rng = srng.create('r123', 512)
    rng.initialize(1000)

    sim = ssolv.Wmdirect(mdl, geom, rng)
    sim.reset()

    global tpnts, ntpnts
    tpnts = numpy.arange(0.0, INT, DT)
    ntpnts = tpnts.shape[0]

    res_m_foi = numpy.zeros([NITER_foi, ntpnts, 1])
    res_std1_foi = numpy.zeros([ntpnts, 1])
    res_std2_foi = numpy.zeros([ntpnts, 1])

    res_m_for = numpy.zeros([NITER_for, ntpnts, 2])

    res_m_soA2 = numpy.zeros([NITER_soA2, ntpnts, 2])

    res_m_soAA = numpy.zeros([NITER_soAA, ntpnts, 3])

    res_m_soAB = numpy.zeros([NITER_soAB, ntpnts, 3])

    res_m_toA3 = numpy.zeros([NITER_toA3, ntpnts, 2])

    res_m_toA2B = numpy.zeros([NITER_toA2B, ntpnts, 3])

    res_m_so2d = numpy.zeros([NITER_so2d, ntpnts, 3])

    for i in range(0, NITER_max):
        sim.reset()

        if i < NITER_foi:
            sim.setCompCount('comp1', 'A_foi', N_foi)

        if i < NITER_for:
            sim.setCompCount('comp1', 'A_for', COUNT_for)
            sim.setCompCount('comp1', 'B_for', 0.0)

        if i < NITER_soA2:
            sim.setCompConc('comp1', 'A_soA2', CONCA_soA2)

        if i < NITER_soAA:
            sim.setCompConc('comp1', 'A_soAA', CONCA_soAA)
            sim.setCompConc('comp1', 'B_soAA', CONCB_soAA)

        if i < NITER_soAB:
            sim.setCompConc('comp1', 'A_soAB', CONCA_soAB)
            sim.setCompConc('comp1', 'B_soAB', CONCB_soAB)

        if i < NITER_toA3:
            sim.setCompConc('comp1', 'A_toA3', CONCA_toA3)

        if i < NITER_toA2B:
            sim.setCompConc('comp1', 'A_toA2B', CONCA_toA2B)
            sim.setCompConc('comp1', 'B_toA2B', CONCB_toA2B)

        if i < NITER_so2d:
            sim.setPatchCount('patch1', 'A_so2d', COUNTA_so2d)
            sim.setPatchCount('patch1', 'B_so2d', COUNTB_so2d)

        for t in range(0, ntpnts):
            sim.run(tpnts[t])

            if i < NITER_foi:
                res_m_foi[i, t, 0] = sim.getCompCount('comp1', 'A_foi')

            if i < NITER_for:
                res_m_for[i, t, 0] = sim.getCompConc('comp1', 'A_for') * 1e6
                res_m_for[i, t, 1] = sim.getCompConc('comp1', 'B_for') * 1e6

            if i < NITER_soA2:
                res_m_soA2[i, t, 0] = sim.getCompConc('comp1', 'A_soA2')

            if i < NITER_soAA:
                res_m_soAA[i, t, 0] = sim.getCompConc('comp1', 'A_soAA')
                res_m_soAA[i, t, 1] = sim.getCompConc('comp1', 'B_soAA')

            if i < NITER_soAB:
                res_m_soAB[i, t, 0] = sim.getCompConc('comp1', 'A_soAB')
                res_m_soAB[i, t, 1] = sim.getCompConc('comp1', 'B_soAB')

            if i < NITER_toA3:
                res_m_toA3[i, t, 0] = sim.getCompConc('comp1', 'A_toA3')

            if i < NITER_toA2B:
                res_m_toA2B[i, t, 0] = sim.getCompConc('comp1', 'A_toA2B')
                res_m_toA2B[i, t, 1] = sim.getCompConc('comp1', 'B_toA2B')
                res_m_toA2B[i, t, 2] = sim.getCompConc('comp1', 'C_toA2B')

            if i < NITER_so2d:
                res_m_so2d[i, t, 0] = sim.getPatchCount('patch1', 'A_so2d')
                res_m_so2d[i, t, 1] = sim.getPatchCount('patch1', 'B_so2d')

    global mean_res_foi, std_res_foi
    mean_res_foi = numpy.mean(res_m_foi, 0)
    std_res_foi = numpy.std(res_m_foi, 0)

    global mean_res_for
    mean_res_for = numpy.mean(res_m_for, 0)

    global mean_res_soA2
    mean_res_soA2 = numpy.mean(res_m_soA2, 0)

    global mean_res_soAA
    mean_res_soAA = numpy.mean(res_m_soAA, 0)

    global mean_res_soAB
    mean_res_soAB = numpy.mean(res_m_soAB, 0)

    global mean_res_toA3
    mean_res_toA3 = numpy.mean(res_m_toA3, 0)

    global mean_res_toA2B
    mean_res_toA2B = numpy.mean(res_m_toA2B, 0)

    global mean_res_so2d
    mean_res_so2d = numpy.mean(res_m_so2d, 0)

    global ran_sim
    ran_sim = True
    def testSetCompVolWmdirect(self):
        self.sim = ssolver.Wmdirect(self.mdl, self.geom, self.rng)
        self.sim.reset()

        self._testSetCompVol()
Example #8
0
def test_masteq():
    "Reaction - Production and degradation (Wmdirect)"

    ########################################################################

    KCST_f = 100 / (6.022e23 * 1.0e-15)  # The reaction constant, production
    KCST_b = 10  # The reaction constant, degradation
    VOL = 1.0e-18

    DT = 0.1  # Sampling time-step
    INT = 200000.1  # Sim endtime

    # Tolerance for the comparison:
    # In tests with good code <1% fail with tolerance of 1.5%
    tolerance = 1.5 / 100

    ########################################################################

    mdl = smod.Model()

    A = smod.Spec('A', mdl)

    volsys = smod.Volsys('vsys', mdl)

    # Production
    R1 = smod.Reac('R1', volsys, lhs=[], rhs=[A], kcst=KCST_f)
    R2 = smod.Reac('R2', volsys, lhs=[A], rhs=[], kcst=KCST_b)

    geom = sgeom.Geom()

    comp1 = sgeom.Comp('comp1', geom, VOL)
    comp1.addVolsys('vsys')

    rng = srng.create('r123', 1000)
    rng.initialize(1000)

    sim = ssolv.Wmdirect(mdl, geom, rng)
    sim.reset()

    tpnts = numpy.arange(0.0, INT, DT)
    ntpnts = tpnts.shape[0]

    res = numpy.zeros([ntpnts])

    sim.reset()
    sim.setCompCount('comp1', 'A', 0)

    for t in range(0, ntpnts):
        sim.run(tpnts[t])
        res[t] = sim.getCompCount('comp1', 'A')

    def fact(x):
        return (1 if x == 0 else x * fact(x - 1))

    # Do cumulative count, but not comparing them all.
    # Don't get over 50 (I hope)
    steps_n_res = numpy.zeros(50)
    for r in res:
        steps_n_res[int(r)] += 1
    for s in range(50):
        steps_n_res[s] = steps_n_res[s] / ntpnts

    passed = True
    max_err = 0.0

    k1 = KCST_b
    k2 = KCST_f * (6.022e23 * 1.0e-15)

    # Compare 5 to 15
    for m in range(5, 16):
        analy = (1.0 / fact(m)) * math.pow((k2 / k1), m) * math.exp(-(k2 / k1))
        assert tol_funcs.tolerable(steps_n_res[m], analy, tolerance)
Example #9
0
tolerance = 2.0 / 100

########################################################################

mdl = smod.Model()

A = smod.Spec('A', mdl)
volsys = smod.Volsys('vsys', mdl)
R1 = smod.Reac('R1', volsys, lhs=[A], rhs=[], kcst=KCST)

geom = sgeom.Geom()
comp1 = sgeom.Comp('comp1', geom, VOL)
comp1.addVolsys('vsys')

rng = srng.create('mt19937', 1000)
rng.initialize(int(time.time() % 4294967295))

sim = ssolv.Wmdirect(mdl, geom, rng)
sim.reset()

tpnts = numpy.arange(0.0, INT, DT)
ntpnts = tpnts.shape[0]

res_m = numpy.zeros([NITER, ntpnts, 1])
res_std1 = numpy.zeros([ntpnts, 1])
res_std2 = numpy.zeros([ntpnts, 1])

sim.reset()
sim.setCompCount('comp1', 'A', N)
sim.checkpoint('./validation_cp/cp/first_order_irev')
import steps.rng as srng
#import package with alias srng.

r = srng.create('mt19937', 256)
#we actually generate a random number generator we want.
#using the function steps.rng.create()
#STEPS currently only implements one pseudo RNG algorithm, 'mt19937'

r.initialize(23412)
#initialize the random number generator with a seed value

import steps.solver as ssolver
#to create the actual solver object, first of all we import the
#package in which all solvers have been implemented

sim = ssolver.Wmdirect(mdl, wmgeom, r)

sim.reset()
#reset the function on the solver project

#we can start manipulating the "state" of simulation

sim.setCompConc('comp', 'molX1bar', 100)
sim.setCompConc('comp', 'molY1', 20)
#this means we're setting the concentration of molX1bar to 31.4
#micro m and molY1 to 22.3 micro m in our compartment comp.
#we are setting these concentration value at simulation time t=0.

import numpy
#we use Numpy to generate some auxilialy numerical arrays that will
#be used during simulation
Example #11
0
def runSBMLmod(sbmlFile,
               time_end,
               time_dt,
               iter_n=1,
               solver='Wmdirect',
               specs_plot={},
               vol_units=1.0e-3,
               vol_def=False):
    iSbml = ssbml.Interface(sbmlFile,
                            volunits_def=vol_units,
                            volume_def=vol_def)
    mdl = iSbml.getModel()
    mesh = iSbml.getGeom()
    comp_specs = {}
    if not specs_plot: got_sp = False
    else: got_sp = True
    for comp in mesh.getAllComps():
        comp_specs[comp.getID()] = []
        volsys_strings = comp.getVolsys()
        for vsys_str in volsys_strings:
            vsys = mdl.getVolsys(vsys_str)
            specs = vsys.getAllSpecs()
            for spec in specs:
                comp_specs[comp.getID()].append(spec.getID())
                if (got_sp == False): specs_plot.update({spec.getID(): ''})
    comp_specs_n = 0
    for comp in comp_specs:
        comp_specs[comp].sort()
        comp_specs_n += len(comp_specs[comp])
    time_pnts = numpy.arange(0.0, time_end, time_dt)
    points_n = int(round(time_end / time_dt))
    if (len(time_pnts) == (points_n + 1)):
        time_pnts = numpy.delete(time_pnts, len(time_pnts) - 1)
    res = numpy.zeros([iter_n, points_n, comp_specs_n])
    r = srng.create('mt19937', 256)
    r.initialize(7233)
    if (solver == 'Wmdirect'):
        sim = ssolver.Wmdirect(mdl, mesh, r)
    elif (solver == 'Wmrk4'):
        sim = ssolver.Wmrk4(mdl, mesh, r)
        sim.setDT(0.0001)
    else:
        raise NameError(
            "Unsupported solver. SBML importer accepts well-mixed solvers 'Wmrk4' and 'Wmdirect'"
        )
    for it in range(0, iter_n):
        sim.reset()
        iSbml.reset()
        iSbml.setupSim(sim)
        for tp in range(0, points_n):
            sim.run(time_pnts[tp])
            i = 0
            for comp in comp_specs:
                for spec in comp_specs[comp]:
                    res[it, tp, i] = sim.getCompConc(comp, spec)
                    i += 1
            iSbml.updateSim(sim, time_dt)
    mean_res = numpy.mean(res, 0)
    i = 0
    for comp in comp_specs:
        for spec in comp_specs[comp]:
            if (spec in specs_plot):
                if (specs_plot[spec]):
                    plot(time_pnts,
                         mean_res[:, i],
                         label=spec + ", " + comp,
                         color=specs_plot[spec])
                else:
                    plot(time_pnts, mean_res[:, i], label=spec + ", " + comp)
            i += 1
    legend(loc='best', numpoints=1)
    xlabel('Time (s)')
    ylabel('Conc (M)')
    show()
Example #12
0
 def testWmdirect(self):
     solver = solv.Wmdirect(self.model, self.geom, self.rng)
     self._runTest(solver)
Example #13
0
def run(model_string,
        initial_condition_string,
        stop_time,
        event_string='',
        seed=23412,
        solver='wmdirect',
        dt=1,
        rk4dt=1e-5,
        realisations=1,
        file=False):
    """ 
       Run a Matlab Simbiology model in STEPS
       using the Wmdriect or Wmrk4 solver.

       This is the entry point called by Matlab via the main code.

       Input parameters:
       - STEPS model as a string,
       - initial condition part of the STEPS model as a string,
       - stop time
       - pseudo random number generator seed,
       - solver: wmdirect or wmrk4,
       - dt: time increment betwen sampling points
       - realisations: number of times the simulation is to be run
       - file: flag to indicate if the generated model should be 
               written to file. The file name carries a timestamp.
    """
    if (not solver.upper() == 'WMDIRECT' and not solver.upper() == 'WMRK4'):
        logger.error('run unknown solver string: ' + solver)
        raise Exception('run unknown solver string: ' + solver)

    if (file):
        if (not os.path.exists(steps_path + '/.logs')):
            os.makedirs(steps_path + '/.logs')

        outfile = open(
            steps_path + '/.logs/matlab_steps_model_' +
            str(datetime.datetime.now()), 'w')
        outfile.write(model_string)
        outfile.write(initial_condition_string)
        outfile.close()

    exec(model_string.encode('ascii').decode('unicode-escape'), globals())

    # setup the solver, only two solvers are supported,
    # so a simple if construct is sufficient.
    global sim
    if (solver.upper() == 'WMDIRECT'):
        r = srng.create('mt19937', 256)
        r.initialize(seed)
        sim = ssolver.Wmdirect(model, geometry, r)
    elif (solver.upper() == 'WMRK4'):
        sim = ssolver.Wmrk4(model, geometry)
        sim.setRk4DT(rk4dt)
    else:
        logger.error('run unknown solver string: ' + solver)
        raise Exception('run unknown solver string: ' + solver)

    # steup the return data structures
    nSpecies = len(model.getAllSpecs())
    list_of_species = model.getAllSpecs()
    specie_names = []
    for s in list_of_species:
        specie_names.append(s.getID())
    tvector = numpy.arange(0, stop_time, dt)

    # get a list of the compartment names
    compartment_names = []
    compartments = geometry.getAllComps()
    for comp in compartments:
        compartment_names.append(str(comp.getID()))

    res = numpy.zeros(
        [realisations, len(compartments),
         len(tvector), nSpecies])

    # parse the events and
    # store them in a dictionary
    event_string = json.loads(event_string.replace('][', ', '))
    logger.debug('run got events: ' + str(event_string))

    # iterate the names of the reaction rates
    rate_names = event_string[1]

    # iterate the events
    event_string = event_string[0]

    # number of events, each event is a dict with trigger and event entry
    nevents = len(event_string)

    event_dict = {}
    # iterate all the dictionaries
    for i in range(nevents):
        # extract the trigger and event
        event_dict.update(event_string[i])

    event_times = {}
    nevents = len(event_dict)

    if (nevents % 2 != 0):
        logger.error(
            'run internal error, number of triggers and events do not match: '
            + str(event_dict))
        raise RuntimeError(
            'run internal error, number of triggers and events do not match: '
            + str(event_dict))

    for i in range(nevents // 2):
        trigger = event_dict['trigger_' + str(i)]

        if (trigger.find('>=') >= 0):
            tmp = trigger.split('>=')
        elif (trigger.find('>') >= 0):
            tmp = trigger.split('>')
        else:
            logger.error('run invalid event trigger: ' + e)
            raise RuntimeError('run invalid event trigger: ' + e)

        #if(event_times.has_key(float(tmp[1]))):
        if (float(tmp[1]) in event_times):
            event_times[float(tmp[1])].append(event_dict['event_' + str(i)])
        else:
            event_times[float(tmp[1])] = [event_dict['event_' + str(i)]]

    # build the event queue - sort the events
    event_queue = sorted(event_times.keys())

    if (not event_queue):
        # run without event queue
        for i in range(realisations):  # this is an index
            sim.reset()
            exec(
                initial_condition_string.encode('ascii').decode(
                    'unicode-escape'), globals())

            for t in range(len(tvector)):  # this is an index
                for c in range(len(compartment_names)):  # this is an index
                    for s in range(len(specie_names)):
                        res[i, c, t,
                            s] = sim.getCompCount(compartment_names[c],
                                                  specie_names[s])
                sim.run(tvector[t])
    else:
        # run with event queue
        logger.debug('run event times: ' + str(event_times))
        logger.debug('run event queue ' + str(event_queue))
        logger.debug('run event dict: ' + str(event_dict))
        for i in range(realisations):
            # copy the event queue for this realisation
            # FIXME: replace copying the queue with a counter
            eq = list(event_queue)
            t_event = float(eq.pop(0))

            # initial conditions
            sim.reset()
            exec(
                initial_condition_string.encode('ascii').decode(
                    'unicode-escape'), globals())

            for t in range(len(tvector)):
                if tvector[t] >= float(t_event):
                    logger.debug('run time of next event: ' +
                                 str((float(t_event))))
                    sim.run(float(t_event))

                    # handle all events event queued for this t_event
                    for e in event_times[t_event]:
                        tmp = handleEvent(e, sim, model, spec_names,
                                          comp_names, rate_names, reac_to_comp,
                                          sreac_to_patch, kcst_si_factor)
                        exec(tmp)

                    # get next event
                    if eq:
                        t_event = eq.pop(0)
                    else:
                        t_event = float('inf')
                # end if

                sim.run(tvector[t])

                # get molecule counts
                for c in range(len(compartment_names)):  # this is an index
                    #sim.run(tvector[t])
                    for s in range(len(specie_names)):
                        res[i, c, t,
                            s] = sim.getCompCount(compartment_names[c],
                                                  specie_names[s])

    # return the data json encoded
    data = {
        'species': specie_names,
        'compartments': compartment_names,
        'data': res.tolist()
    }
    sys.stdout.write(json.dumps(data))
    sys.stdout.flush()
    sys.exit(0)
Example #14
0
print 'Inner compartment to memb is', memb.getIComp().getID()
print 'Outer compartment to memb is', memb.getOComp().getID()

#RNG setup
import steps.rng as srng
import pylab
import numpy

r = srng.create('mt19937', 1000)
r.initialize(7233)

#solver setup
import steps.solver as ssolover
if deterministic: sim = ssolover.Wmrk4(mdl, wmgeom, r)
else: sim = ssolover.Wmdirect(mdl, wmgeom, r)

tpnt = numpy.arange(0.0, 20.01, 0.01)
res = numpy.zeros([NITER, 2001, 4])
res_std = numpy.zeros([2001, 4])
res_std1 = numpy.zeros([2001, 4])
res_std2 = numpy.zeros([2001, 4])

prob = []

ca = 0.1e-6
ip = 2e-6

for i in range(0, NITER):
    sim.reset()
    if deterministic: sim.setRk4DT(0.000001)
Example #15
0
def test_soirevAA():
    KCST = 50.0e6  # The reaction constant

    CONCA = 20.0e-6
    CONCB = CONCA

    VOL = 9.0e-18

    NITER = 1000  # The number of iterations
    DT = 0.1  # Sampling time-step
    INT = 1.1  # Sim endtime

    # In test runs, with good code, <0.1% will fail with a tolerance of 1%
    tolerance = 1.0 / 100

    ########################################################################

    mdl = smod.Model()

    A = smod.Spec('A', mdl)
    B = smod.Spec('B', mdl)
    C = smod.Spec('C', mdl)

    volsys = smod.Volsys('vsys', mdl)

    R1 = smod.Reac('R1', volsys, lhs=[A, B], rhs=[C], kcst=KCST)

    geom = sgeom.Geom()

    comp1 = sgeom.Comp('comp1', geom, VOL)
    comp1.addVolsys('vsys')

    rng = srng.create('mt19937', 512)
    rng.initialize(int(time.time() % 4294967295))

    sim = ssolv.Wmdirect(mdl, geom, rng)
    sim.reset()

    tpnts = numpy.arange(0.0, INT, DT)
    ntpnts = tpnts.shape[0]

    res_m = numpy.zeros([NITER, ntpnts, 3])

    for i in range(0, NITER):
        sim.restore('./validation_cp/cp/second_order_irev_AA')
        for t in range(0, ntpnts):
            sim.run(tpnts[t])
            res_m[i, t, 0] = sim.getCompConc('comp1', 'A')
            res_m[i, t, 1] = sim.getCompConc('comp1', 'B')

    mean_res = numpy.mean(res_m, 0)

    invA = numpy.zeros(ntpnts)
    invB = numpy.zeros(ntpnts)
    lineA = numpy.zeros(ntpnts)
    lineB = numpy.zeros(ntpnts)

    max_err = 0.0
    passed = True
    for i in range(ntpnts):
        invA[i] = (1.0 / mean_res[i][0])
        invB[i] = (1.0 / mean_res[i][1])
        lineA[i] = (1.0 / CONCA + ((tpnts[i] * KCST)))
        lineB[i] = (1.0 / CONCB + ((tpnts[i] * KCST)))

        assert (tol_funcs.tolerable(invA[i], lineA[i], tolerance))
        assert (tol_funcs.tolerable(invB[i], lineB[i], tolerance))
Example #16
0
import steps.rng as srng
import steps.solver as ssolver
import numpy

####

#Concentrations for Ca in cytosol
ca_concs = numpy.array([0.001e-6, 0.003e-6, 0.01e-6, 0.02e-6, 0.05e-6, 0.07e-6, 0.10e-6, 0.15e-6, 0.20e-6, 0.25e-6, \
                        0.28e-6, 0.30e-6, 0.33e-6, 0.35e-6, 0.36e-6, 0.38e-6, 0.43e-6, 0.50e-6, 1.00e-6, 1.50e-6, 2.00e-6,\
                        2.50e-6, 5.00e-6, 10.00e-6]) # mol/l

# Solver settings
r = srng.create('mt19937', 1000)
r.initialize(2605)
sim = ssolver.Wmdirect(model.mdl, model.cell, r)

# Number of iterations (defines how many times the model is simulated)
NITER = 1  #5000

tpnt = numpy.arange(0.0, 50.01, 0.01)

# array for simulation results
res = numpy.zeros([ca_concs.size, 2])

print 'Simulating the IP3R model of Dawson et al. 2003.'

for i in xrange(ca_concs.size):

    print 'Round', i + 1, '/', ca_concs.size
    temp_res = numpy.zeros([NITER, tpnt.size])
Example #17
0
print "Membrane created."

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # SIMULATION  # # # # # # # # # # # # # # # # # # # # # #

r = srng.create_mt19937(512)
r.initialize(int(time.time()%1000))

# Random-number generator 
r_dummy = srng.create_mt19937(512)
r_dummy.initialize(int(time.time()%1000))

print "Creating tetexact solver..."
sim_stoch = ssolver.Tetexact(mdl_stoch, mesh_stoch, r, True)

print "Creating WM solver"
sim_WM = ssolver.Wmdirect(mdl_WM, wmgeom, r_dummy)

print "Resetting simulation objects.."
sim_stoch.reset()
sim_WM.reset()


print "Injecting molecules.."

sim_stoch.setTemp(TEMPERATURE+273.15)

for i in range(len(Length)):
    for j in range(int(Nannulis[i])):
        sim_WM.setCompConc('shells'+str(i)+str(j), 'Ca', Ca_iconc)
        sim_WM.setCompConc('shells'+str(i)+str(j), 'Mg', Mg_conc)
Example #18
0
def solver(mdl, geom, tissue, sim_opt):
    """ run the simulation using sim_options and model and geometry (above) """
    treated_tissue = copy.deepcopy(tissue)
    reactants = ['NP', 'NPi', 'NPR', 'R']
    NT = int(sim_opt['general'].NT)
    t_final = int(sim_opt['general'].t_final)
    N_VC, unique_p = 0, []
    for cell in treated_tissue:
        if cell.type == 'VC':
            N_VC += 1
        [unique_p.append(p) for p in cell.prtcl_names if p not in unique_p]

    r = srng.create('mt19937', 512)
    seed = randint(1, 10000)
    r.initialize(seed)
    sim = ssolver.Wmdirect(mdl, geom, r)
    tpnt = np.linspace(0.0, t_final, NT)
    resi = np.zeros([NT, len(treated_tissue) * len(unique_p), len(reactants)])
    for n, cell in enumerate(treated_tissue):
        for p in cell.prtcl_names:
            tag = str(n) + p
            prtcl = getattr(cell, p)
            if hasattr(cell, 'NR'):
                sim.setCompCount("cell_{}".format(tag), 'R', float(cell.NR))
            if 'NP0' in prtcl:
                if prtcl['T'] == 1:
                    sim.setCompCount("cell_{}".format(tag), 'N{}'.format(p),
                                     prtcl['NP0'])
                else:
                    sim.setCompCount("cell_{}".format(tag), 'N{}'.format(p),
                                     prtcl['NP0'])
                    sim.setCompClamped("cell_{}".format(tag), 'N{}'.format(p),
                                       True)

    printProgressBar(0, NT, prefix='Progress:', suffix='Complete', length=40)
    for t in range(NT):
        sim.run(tpnt[t])
        printProgressBar(t,
                         NT,
                         prefix='Progress:',
                         suffix='Complete',
                         length=40)
        n = 0
        for nc, cell in enumerate(treated_tissue):
            for p_idx, p in enumerate(cell.prtcl_names):
                tag = str(nc) + p
                prtcl = getattr(cell, p)
                if hasattr(cell, 'NR'):
                    resi[t, n, 0] = sim.getCompCount("cell_{}".format(tag),
                                                     'N{}'.format(p))
                    resi[t, n, 1] = sim.getCompCount("cell_{}".format(tag),
                                                     'R')
                    resi[t, n, 2] = sim.getCompCount("cell_{}".format(tag),
                                                     'NPR')
                    resi[t, n, 3] = sim.getCompCount("cell_{}".format(tag),
                                                     'N{}i'.format(p))
                else:
                    resi[t, n, 0] = sim.getCompCount("cell_{}".format(tag),
                                                     'N{}'.format(p))
                if 'T' in prtcl:
                    if (tpnt[t] > prtcl['T']) or (prtcl['T'] == 1):
                        sim.setCompClamped("cell_{}".format(tag),
                                           'N{}'.format(p), False)
                if ('NP_max' in prtcl) and (resi[t, n, 3] > prtcl['NP_max']):
                    cell.type = 'dead'
                n += 1
    return treated_tissue, resi
def test_soirev2d():
    VOL = 1.0e-18

    COUNTA = 100.0
    n=2.0
    COUNTB = COUNTA/n 


    KCST = 10.0e10			# The reaction constant

    AREA = 10.0e-12

    CCST = KCST/(6.02214179e23*AREA)


    NITER = 1000			# The number of iterations
    DT = 0.05			# Sampling time-step
    INT = 1.05			# Sim endtime

    # In tests fewer than 0.1% fail with tolerance of 2%
    tolerance = 2.0/100

    ########################################################################

    mdl  = smod.Model()

    A = smod.Spec('A', mdl)
    B = smod.Spec('B', mdl)
    C = smod.Spec('C', mdl)

    surfsys = smod.Surfsys('ssys',mdl)

    SR1 = smod.SReac('SR1', surfsys, slhs = [A, B], srhs = [C], kcst = KCST)

    geom = sgeom.Geom()

    comp1 = sgeom.Comp('comp1', geom, VOL)
    patch1 = sgeom.Patch('patch1', geom, comp1, area = AREA)
    patch1.addSurfsys('ssys')

    import random
    rng = srng.create('mt19937', 1000)
    rng.initialize(int(random.random()*4294967295))


    sim = ssolv.Wmdirect(mdl, geom, rng)
    sim.reset()

    tpnts = numpy.arange(0.0, INT, DT)
    ntpnts = tpnts.shape[0]

    res_m = numpy.zeros([NITER, ntpnts, 3])

    for i in range (0, NITER):
        sim.restore('./validation_cp/cp/second_order_irev_2D')
        for t in range(0, ntpnts):
            sim.run(tpnts[t])
            res_m[i, t, 0] = sim.getPatchCount('patch1', 'A')
            res_m[i, t, 1] = sim.getPatchCount('patch1', 'B')       

    mean_res = numpy.mean(res_m, 0)

    lnBA = numpy.zeros(ntpnts)
    lineAB = numpy.zeros(ntpnts)

    C = COUNTA-COUNTB
    passed  =True
    max_err = 0.0

    for i in range(ntpnts):
        A = mean_res[i][0]
        B = mean_res[i][1]
        lnBA[i] = math.log(B/A)
        lineAB[i] = math.log(COUNTB/COUNTA) -C*CCST*tpnts[i]
        assert(tol_funcs.tolerable(lnBA[i], lineAB[i], tolerance))