예제 #1
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)
예제 #2
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()
예제 #3
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)
예제 #4
0
memb.setArea(0.21544368e-12)

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()
예제 #5
0
print "Sim Time: %e" % sim.getTime()
print "Sim Steps: %e" % sim.getNSteps()

# or step, without checkpointing
print "Run 1 SSA step"
sim.step()
print "Sim Time: %e" % sim.getTime()
print "Sim Steps: %e" % sim.getNSteps()

###################################
# Restore from checkpoint file
###################################
print "Restore from file"
sim.restore("manual.checkpoint")
print "Sim Time: %e" % sim.getTime()
print "Sim Steps: %e" % sim.getNSteps()

###################################
# RK4 solver
###################################
print "Well Mixed RK4"
rk4sim = ssolver.Wmrk4(mdl, wmgeom, r)

rk4sim.reset()
rk4sim.setDT(1e-4)
rk4sim.setCompConc('comp', 'molA', 31.4e-6)
rk4sim.setCompConc('comp', 'molB', 22.3e-6)

# Notice: No checkpointing for RK4 yet
rk4sim.run(1e-3)
print "Sim Time: %e" % rk4sim.getTime()
예제 #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 = 1        # The number of iterations

    # Tolerance for the comparison. 
    tolerance_foi = 1e-3/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 = 1            # The number of iterations

    # Tolerance for the comparison. The only test where tolerance must
    # be relatively high    
    tolerance_for = 0.5/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 = 1         # The number of iterations

    tolerance_soA2 = 1.0e-3/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 = 1         # The number of iterations
    
    tolerance_soAA = 1.0e-3/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 = 1         # The number of iterations

    tolerance_soAB = 1.0e-3/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 = 1         # The number of iterations
    
    tolerance_toA3 = 1.0e-3/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 = 1         # The number of iterations
    
    tolerance_toA2B = 1.0e-3/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 = 1         # The number of iterations

    tolerance_so2d = 1.0e-3/100

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

    global VOL

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

    NITER_max = 1

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

    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.Wmrk4(mdl, geom, rng)
    sim.setDT(0.00001)


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


    res_m_foi = numpy.zeros([NITER_foi, 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):

        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
    mean_res_foi = numpy.mean(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