def setUp(self): self.model = smodel.Model() A = smodel.Spec('A', self.model) surfsys = smodel.Surfsys('ssys', self.model) D_a = smodel.Diff('D_a', surfsys, A) self.DCST = 0.2e-9 D_a.setDcst(self.DCST) self.mesh = meshio.importAbaqus2("directional_dcst_test/mesh_tet.inp", "directional_dcst_test/mesh_tri.inp", 1e-6, "directional_dcst_test/mesh_conf")[0] boundary_tris = self.mesh.getROIData("boundary") v1_tets = self.mesh.getROIData("v1_tets") comp1 = sgeom.TmComp("comp1", self.mesh, v1_tets) patch1 = sgeom.TmPatch("patch", self.mesh, boundary_tris, comp1) patch1.addSurfsys("ssys") self.neigh_tris = self.mesh.getROIData("neigh_tri") self.focus_tri = self.mesh.getROIData("focus_tri")[0] self.rng = srng.create('r123', 512) self.rng.initialize(1000) self.solver = solv.Tetexact(self.model, self.mesh, self.rng)
def setUp(self): self.model = smodel.Model() A = smodel.Spec('A', self.model) volsys = smodel.Volsys('vsys', self.model) D_a = smodel.Diff('D_a', volsys, A) self.DCST = 0.2e-9 D_a.setDcst(self.DCST) self.mesh = meshio.importAbaqus2("directional_dcst_test/mesh_tet.inp", "directional_dcst_test/mesh_tri.inp", 1e-6, "directional_dcst_test/mesh_conf")[0] boundary_tris = self.mesh.getROIData("boundary") v1_tets = self.mesh.getROIData("v1_tets") v2_tets = self.mesh.getROIData("v2_tets") comp1 = sgeom.TmComp("comp1", self.mesh, v1_tets) comp2 = sgeom.TmComp("comp2", self.mesh, v2_tets) comp1.addVolsys("vsys") comp2.addVolsys("vsys") db = sgeom.DiffBoundary("boundary", self.mesh, boundary_tris) self.rng = srng.create('r123', 512) self.rng.initialize(1000) self.solver = solv.Tetexact(self.model, self.mesh, self.rng)
def setUp(self): self.model = smodel.Model() A = smodel.Spec('A', self.model) volsys = smodel.Volsys('vsys', self.model) D_a = smodel.Diff('D_a', volsys, A) self.DCST = 0.2e-9 D_a.setDcst(self.DCST) self.mesh = meshio.importAbaqus2("directional_dcst_test/mesh_tet.inp", "directional_dcst_test/mesh_tri.inp", 1e-6, "directional_dcst_test/mesh_conf")[0] comp = sgeom.TmComp("comp", self.mesh, range(self.mesh.ntets)) comp.addVolsys("vsys") self.rng = srng.create('r123', 512) self.rng.initialize(1000) self.solver = solv.Tetexact(self.model, self.mesh, self.rng) boundary_tris = self.mesh.getROIData("boundary") boundary_tets1 = self.mesh.getROIData("boundary_tets_1") boundary_tets2 = self.mesh.getROIData("boundary_tets_2") self.pairing = {} for tri in boundary_tris: neigh_tets = self.mesh.getTriTetNeighb(tri) if neigh_tets[0] in boundary_tets1: self.pairing[tri] = (neigh_tets[0], neigh_tets[1]) else: self.pairing[tri] = (neigh_tets[1], neigh_tets[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)
def init_sim(model, mesh, seed, param): # previous setup # rng = srng.create('r123', 512) # rng.initialize(seed) # sim = ssolver.Tetexact(model, mesh, rng, True) # Create the solver objects if param['SSA_solver'] == 'TetODE': sim = ssolver.TetODE(model, mesh, calcMembPot=sim_parameters['EF_solver']) sim.setTolerances(1.0e-6, 1e-6) elif param['SSA_solver'] == 'Tetexact': rng = srng.create('mt19937', 512) rng.initialize(seed) sim = ssolver.Tetexact(model, mesh, rng, calcMembPot=sim_parameters['EF_solver']) sim.reset() sim.setEfieldDT(param['EF_dt']) else: raise ValueError('SSA solver ' + param['SSA_solver'] + 'not available') print('Running Rallpack1 test with ' + param['SSA_solver']) # Correction factor for deviation between mesh and model cylinder: area_cylinder = np.pi * param['diameter'] * param['length'] area_mesh_factor = sim.getPatchArea('memb') / area_cylinder # Set initial conditions memb = sgeom.castToTmPatch(mesh.getPatch('memb')) for t in memb.tris: sim.setTriCount(t, 'Leak', 1) sim.setMembPotential('membrane', param['E_M']) sim.setMembVolRes('membrane', param['R_A']) sim.setMembCapac('membrane', param['C_M'] / area_mesh_factor) v_zmin = mesh.getROIData('v_zmin') I = param['Iinj'] / len(v_zmin) for v in v_zmin: sim.setVertIClamp(v, I) return sim
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # STEPS - STochastic Engine for Pathway Simulation # Copyright (C) 2007-2011 Okinawa Institute of Science and Technology, Japan. # Copyright (C) 2003-2006 University of Antwerp, Belgium. # # See the file AUTHORS for details. # # This file is part of STEPS. # # STEPS is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # STEPS is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # import steps.model as smod import steps.geom as sgeom import steps.rng as srng import steps.solver as ssolv import math import time import steps.utilities.meshio as smeshio
print "Creating membrane.." membrane = sgeom.Memb('membrane', mesh_stoch, [memb_stoch]) print "Membrane created." # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # SIMULATION # # # # # # # # # # # # # # # # # # # # # # r = srng.create_mt19937(512) r.initialize(7) r_dummy = srng.create_mt19937(512) r_dummy.initialize(7) print "Creating Tet exact solver" #Creating two solvers sim_stoch = ssolver.Tetexact(mdl_stoch, mesh_stoch, r, True) print "Creating Tet ODE solver" sim_det = ssolver.TetODE(mdl_det, mesh_det, r_dummy) sim_det.setTolerances(1.0e-3, 1.0e-3) print "Resetting simulation objects.." sim_stoch.reset() print "Injecting molecules.." sim_stoch.setTemp(TEMPERATURE + 273.15) sim_stoch.setCompConc('cyto_stoch', 'Ca_stoch', Ca_iconc)
def test_masteqdiff(): SCALE = 1.0 KCST_f = 100e6 * SCALE # The reaction constant, degradation KCST_b = (20.0e-10 * SCALE) # The reaction constant, production DCST_A = 20e-12 DCST_B = 20e-12 B0 = 1 # The number of B moleucles DT = 0.1 # Sampling time-step INT = 50000.1 # Sim endtime filename = 'cube_1_1_1_73tets.inp' # A tolerance of 7.5% will fail <1% of the time tolerance = 7.5 / 100 ######################################################################## mdl = smod.Model() A = smod.Spec('A', mdl) B = smod.Spec('B', mdl) volsys = smod.Volsys('vsys', mdl) diffA = smod.Diff('diffA', volsys, A) diffA.setDcst(DCST_A) diffB = smod.Diff('diffB', volsys, B) diffB.setDcst(DCST_B) # Production R1 = smod.Reac('R1', volsys, lhs=[A, B], rhs=[B], kcst=KCST_f) R2 = smod.Reac('R2', volsys, lhs=[], rhs=[A], kcst=KCST_b) geom = meshio.loadMesh('./validation_rd/meshes/' + filename)[0] comp1 = sgeom.TmComp('comp1', geom, range(geom.ntets)) comp1.addVolsys('vsys') rng = srng.create('mt19937', 512) rng.initialize(int(time.time() % 4294967295)) sim = ssolv.Tetexact(mdl, geom, rng) sim.reset() tpnts = np.arange(0.0, INT, DT) ntpnts = tpnts.shape[0] res = np.zeros([ntpnts]) res_std1 = np.zeros([ntpnts]) res_std2 = np.zeros([ntpnts]) sim.restore('./validation_cp/cp/masteq_diff') b_time = time.time() 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 = np.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_f / 6.022e23 k2 = KCST_b * 6.022e23 v = comp1.getVol() * 1.0e3 # litres for m in range(5, 11): analy = (1.0 / fact(m)) * np.power( (k2 * v * v) / (B0 * k1), m) * np.exp(-((k2 * v * v) / (k1 * B0))) assert (tol_funcs.tolerable(steps_n_res[m], analy, tolerance))
# tetrahedrons in v2 and adjancent to the boundary boundary_tets2 = mesh.getROIData("boundary_tets_2") # pairing their indices pairing = {} for tri in boundary_tris: neigh_tets = mesh.getTriTetNeighb(tri) if neigh_tets[0] in boundary_tets1: pairing[tri] = (neigh_tets[0], neigh_tets[1]) else: pairing[tri] = (neigh_tets[1], neigh_tets[0]) rng = srng.create('mt19937', 512) rng.initialize(int(time.time()%4294967295)) solver = solv.Tetexact(model, mesh, rng) print "Set dcst from v1 to v2 to 0..." for tri in pairing.keys(): solver.setTetDiffD(pairing[tri][0], "D_a", 0, pairing[tri][1]) # use this to get directional dcst #print solver.getTetDiffD(pairing[tri][0], "D_a", pairing[tri][1]) solver.setTetCount(pairing[tri][0], "A", 10) print "V1 Count: ", solver.getROICount("v1_tets", "A") print "V2 Count: ", solver.getROICount("v2_tets", "A") solver.run(1) print "V1 Count: ", solver.getROICount("v1_tets", "A") print "V2 Count: ", solver.getROICount("v2_tets", "A") print "Set dcst from v1 to v2 to 1/10 of DCST..." solver.reset()
def test_unbdiff2D(): "Surface Diffusion - Unbounded, point source (Tetexact), serial" m = gen_model() g, patch_tris, patch_tris_n, ctri_idx, trirads, triareas = gen_geom() sim = solvmod.Tetexact(m, g, rng) tpnts = numpy.arange(0.0, INT, DT) ntpnts = tpnts.shape[0] #Create the big old data structure: iterations x time points x concentrations res_count = numpy.zeros((NITER, ntpnts, patch_tris_n)) res_conc = numpy.zeros((NITER, ntpnts, patch_tris_n)) for j in range(NITER): sim.reset() sim.setTriCount(ctri_idx, 'X', NINJECT) for i in range(ntpnts): sim.run(tpnts[i]) for k in range(patch_tris_n): res_count[j, i, k] = sim.getTriCount(patch_tris[k], 'X') res_conc[j, i, k] = sim.getTriCount( patch_tris[k], 'X') / sim.getTriArea(patch_tris[k]) itermeans_count = numpy.mean(res_count, axis=0) itermeans_conc = numpy.mean(res_conc, axis=0) tpnt_compare = [12, 16, 20] passed = True max_err = 0.0 for t in tpnt_compare: bin_n = 20 r_max = 0.0 for i in trirads: if (i > r_max): r_max = i r_min = 0.0 r_seg = (r_max - r_min) / bin_n bin_mins = numpy.zeros(bin_n + 1) r_tris_binned = numpy.zeros(bin_n) bin_areas = numpy.zeros(bin_n) r = r_min for b in range(bin_n + 1): bin_mins[b] = r if (b != bin_n): r_tris_binned[b] = r + r_seg / 2.0 r += r_seg bin_counts = [None] * bin_n for i in range(bin_n): bin_counts[i] = [] for i in range((itermeans_count[t].size)): i_r = trirads[i] for b in range(bin_n): if (i_r >= bin_mins[b] and i_r < bin_mins[b + 1]): bin_counts[b].append(itermeans_count[t][i]) bin_areas[b] += sim.getTriArea(int(patch_tris[i])) break bin_concs = numpy.zeros(bin_n) for c in range(bin_n): for d in range(bin_counts[c].__len__()): bin_concs[c] += bin_counts[c][d] bin_concs[c] /= (bin_areas[c] * 1.0e12) for i in range(bin_n): if (r_tris_binned[i] > 2.0 and r_tris_binned[i] < 5.0): rad = r_tris_binned[i] * 1.0e-6 det_conc = 1.0e-12 * ( NINJECT / (4 * math.pi * DCST * tpnts[t])) * (math.exp( (-1.0 * (rad * rad)) / (4 * DCST * tpnts[t]))) steps_conc = bin_concs[i] assert tol_funcs.tolerable(det_conc, steps_conc, tolerance)
numfilled +=1 # Now find the distance of the center of the tets to the Z lower face for i in range(SAMPLE): baryc = mesh.getTetBarycenter(int(tetidxs[i])) r = baryc[0] tetrads[i] = r*1.0e6 Atets = acomptets Btets = bcomptets rng = srng.create('mt19937', 16384) rng.initialize(int(time.time()%4294967295)) sim = ssolv.Tetexact(mdl, mesh, rng) sim.reset() tpnts = numpy.arange(0.0, INT, DT) ntpnts = tpnts.shape[0] resA = numpy.zeros((NITER, ntpnts, SAMPLE)) resB = numpy.zeros((NITER, ntpnts, SAMPLE)) sim.reset() sim.setDiffBoundaryDiffusionActive('diffb', 'A', True) sim.setDiffBoundaryDiffusionActive('diffb', 'B', True) sim.setCompCount('compa', 'A', NA0)
def test_efield_vc(): mesh = make_tri_prism(3, 10, 1.0) interior = sgeom.TmComp('interior', mesh, range(mesh.ntets)) model = smodel.Model() # need at minimum one species sA = smodel.Spec('A', model) patch = sgeom.TmPatch('patch', mesh, mesh.getSurfTris(), interior) memb = sgeom.Memb('membrane', mesh, [patch], opt_method=1) rng = srng.create('r123', 512) sim = ssolver.Tetexact(model, mesh, rng, True) EF_dt = 1e-6 # 1 microsecond sim.reset() sim.setEfieldDT(EF_dt) # initialise potential of mesh vertices to 0V sim.setMembPotential('membrane', 0) # membrane capacitance sim.setMembCapac('membrane', 0) # volume resistivity sim.setMembVolRes('membrane', 1) # 1 ohm·m # clamp top and bottom of prism vtop = set( (vi for tri in mesh.getROIData('top') for vi in mesh.getTri(tri))) vbottom = set( (vi for tri in mesh.getROIData('bottom') for vi in mesh.getTri(tri))) for v in vtop: sim.setVertV(v, 10.0) sim.setVertVClamped(v, True) for v in vbottom: sim.setVertV(v, 0.0) sim.setVertVClamped(v, True) # get means across all horizontal slices slices = dict((int(mo.group(1)), mesh.getROIData(s)) for s in mesh.getAllROINames() for mo in [re.search('slice(\d+)', s)] if mo) slice_keys = list(slices.keys()) slice_keys.sort() N = 10 result = np.zeros((N, 1 + len(slice_keys))) for k in range(N): result[k, 0] = k sim.advance(EF_dt) j = 1 for s in slice_keys: nv = 0 sumv = 0.0 for vi in slices[s]: nv += 1 sumv += sim.getVertV(vi) result[k, j] = sumv / nv j += 1 for i in np.arange(1.0, 12.0): for j in result[1:, int(i)]: assert (abs(j - (i - 1)) < 1e-10)
tetmesh = meshio.importAbaqus('2_20_0.7.inp', 1e-6, None, "2_20_0.7_conf")[0] ######################################################################## # Create Random number generator import steps.rng as srng import time rng = srng.create('mt19937', 512) rng.initialize(int(time.time() % 4294967295)) # The max unsigned long ######################################################################## # Initialize simulation import steps.solver as ssolver sim = ssolver.Tetexact(mdl, tetmesh, rng) sim.setROICount("injection", "X", 2000) ######################################################################## # Visualization import pyqtgraph as pg import steps.visual as visual app = pg.mkQApp() # Create simulation displays display1 = visual.SimDisplay("Show Spine Species") display2 = visual.SimDisplay("Hide Spine Species")
diffB = smod.Diff('diffB', volsys, B) diffB.setDcst(DCST_B) # Production R1 = smod.Reac('R1', volsys, lhs = [A, B], rhs = [B], kcst = KCST_f) R2 = smod.Reac('R2', volsys, lhs = [], rhs = [A], kcst = KCST_b) geom = meshio.loadMesh('./validation_rd/meshes/'+filename)[0] comp1 = sgeom.TmComp('comp1', geom, range(geom.ntets)) comp1.addVolsys('vsys') rng = srng.create('mt19937', 512) rng.initialize(int(time.time()%4294967295)) sim = ssolv.Tetexact(mdl, geom, rng) sim.reset() tpnts = np.arange(0.0, INT, DT) ntpnts = tpnts.shape[0] res = np.zeros([ntpnts]) res_std1 = np.zeros([ntpnts]) res_std2 = np.zeros([ntpnts]) sim.reset() sim.setCompCount('comp1', 'A', 0) sim.setCompCount('comp1', 'B', B0) sim.checkpoint('./validation_cp/cp/masteq_diff')
def test_kis(): NITER = 50 # The number of iterations DT = 0.1 # Sampling time-step INT = 0.3 # Sim endtime DCSTA = 400 * 1e-12 DCSTB = DCSTA RCST = 100000.0e6 #NA0 = 100000 # 1000000 # Initial number of A molecules NA0 = 1000 NB0 = NA0 # Initial number of B molecules SAMPLE = 1686 # <1% fail with a tolerance of 7.5% tolerance = 7.5 / 100 # create the array of tet indices to be found at random tetidxs = numpy.zeros(SAMPLE, dtype='int') # further create the array of tet barycenter distance to center tetrads = numpy.zeros(SAMPLE) ######################################################################## rng = srng.create('mt19937', 512) rng.initialize(int(time.time() % 4294967295)) # The max unsigned long 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, B], rhs=[]) R1.setKcst(RCST) D_a = smod.Diff('D_a', volsys, A) D_a.setDcst(DCSTA) D_b = smod.Diff('D_b', volsys, B) D_b.setDcst(DCSTB) mesh = meshio.loadMesh('./validation_rd/meshes/brick_40_4_4_1686tets')[0] VOLA = mesh.getMeshVolume() / 2.0 VOLB = VOLA ntets = mesh.countTets() acomptets = [] bcomptets = [] max = mesh.getBoundMax() min = mesh.getBoundMax() midz = 0.0 compatris = set() compbtris = set() for t in range(ntets): barycz = mesh.getTetBarycenter(t)[0] tris = mesh.getTetTriNeighb(t) if barycz < midz: acomptets.append(t) compatris.add(tris[0]) compatris.add(tris[1]) compatris.add(tris[2]) compatris.add(tris[3]) else: bcomptets.append(t) compbtris.add(tris[0]) compbtris.add(tris[1]) compbtris.add(tris[2]) compbtris.add(tris[3]) dbset = compatris.intersection(compbtris) dbtris = list(dbset) compa = sgeom.TmComp('compa', mesh, acomptets) compb = sgeom.TmComp('compb', mesh, bcomptets) compa.addVolsys('vsys') compb.addVolsys('vsys') diffb = sgeom.DiffBoundary('diffb', mesh, dbtris) # Now fill the array holding the tet indices to sample at random assert (SAMPLE <= ntets) numfilled = 0 while (numfilled < SAMPLE): tetidxs[numfilled] = numfilled numfilled += 1 # Now find the distance of the center of the tets to the Z lower face for i in range(SAMPLE): baryc = mesh.getTetBarycenter(int(tetidxs[i])) r = baryc[0] tetrads[i] = r * 1.0e6 Atets = acomptets Btets = bcomptets rng = srng.create('mt19937', 16384) rng.initialize(int(time.time() % 4294967295)) sim = ssolv.Tetexact(mdl, mesh, rng) sim.reset() tpnts = numpy.arange(0.0, INT, DT) ntpnts = tpnts.shape[0] resA = numpy.zeros((NITER, ntpnts, SAMPLE)) resB = numpy.zeros((NITER, ntpnts, SAMPLE)) for i in range(0, NITER): sim.restore('./validation_cp/cp/kisilevich') for t in range(0, ntpnts): sim.run(tpnts[t]) for k in range(SAMPLE): resA[i, t, k] = sim.getTetCount(int(tetidxs[k]), 'A') resB[i, t, k] = sim.getTetCount(int(tetidxs[k]), 'B') itermeansA = numpy.mean(resA, axis=0) itermeansB = numpy.mean(resB, axis=0) def getdetc(t, x): N = 1000 # The number to represent infinity in the exponential calculation L = 20e-6 concA = 0.0 for n in range(N): concA += ((1.0 / (2 * n + 1)) * math.exp( (-(DCSTA / (20.0e-6)) * math.pow( (2 * n + 1), 2) * math.pow(math.pi, 2) * t) / (4 * L)) * math.sin(((2 * n + 1) * math.pi * x) / (2 * L))) concA *= ((4 * NA0 / math.pi) / (VOLA * 6.022e26)) * 1.0e6 return concA tpnt_compare = [1, 2] passed = True max_err = 0.0 for tidx in tpnt_compare: NBINS = 10 radmax = 0.0 radmin = 10.0 for r in tetrads: if (r > radmax): radmax = r if (r < radmin): radmin = r rsec = (radmax - radmin) / NBINS binmins = numpy.zeros(NBINS + 1) tetradsbinned = numpy.zeros(NBINS) r = radmin bin_vols = numpy.zeros(NBINS) for b in range(NBINS + 1): binmins[b] = r if (b != NBINS): tetradsbinned[b] = r + rsec / 2.0 r += rsec bin_countsA = [None] * NBINS bin_countsB = [None] * NBINS for i in range(NBINS): bin_countsA[i] = [] bin_countsB[i] = [] filled = 0 for i in range(itermeansA[tidx].size): irad = tetrads[i] for b in range(NBINS): if (irad >= binmins[b] and irad < binmins[b + 1]): bin_countsA[b].append(itermeansA[tidx][i]) bin_vols[b] += sim.getTetVol(int(tetidxs[i])) filled += 1.0 break filled = 0 for i in range(itermeansB[tidx].size): irad = tetrads[i] for b in range(NBINS): if (irad >= binmins[b] and irad < binmins[b + 1]): bin_countsB[b].append(itermeansB[tidx][i]) filled += 1.0 break bin_concsA = numpy.zeros(NBINS) bin_concsB = numpy.zeros(NBINS) for c in range(NBINS): for d in range(bin_countsA[c].__len__()): bin_concsA[c] += bin_countsA[c][d] for d in range(bin_countsB[c].__len__()): bin_concsB[c] += bin_countsB[c][d] bin_concsA[c] /= (bin_vols[c]) bin_concsA[c] *= (1.0e-3 / 6.022e23) * 1.0e6 bin_concsB[c] /= (bin_vols[c]) bin_concsB[c] *= (1.0e-3 / 6.022e23) * 1.0e6 for i in range(NBINS): rad = abs(tetradsbinned[i]) * 1.0e-6 if (tetradsbinned[i] < -5): # compare A det_conc = getdetc(tpnts[tidx], rad) steps_conc = bin_concsA[i] if not tol_funcs.tolerable(det_conc, steps_conc, tolerance): passed = False if (abs(2 * (det_conc - steps_conc) / (det_conc + steps_conc)) > max_err): max_err = abs(2 * (det_conc - steps_conc) / (det_conc + steps_conc)) #print("Error:",abs(2*(det_conc-steps_conc)/(det_conc+steps_conc))*100.0, "%") #print("") elif (tetradsbinned[i] > 5): # compare B det_conc = getdetc(tpnts[tidx], rad) steps_conc = bin_concsB[i] assert (tol_funcs.tolerable(det_conc, steps_conc, tolerance))
plt.legend() CA_FLUX_ONSET = 0.020 CA_FLUX_OFFSET = 0.021 CA_FLUSH = 0.030 NITER = 100 # The number of iterations to run DT = 0.0003 # The data collection time increment (s) T = 0.04 # The simulation endtime (s) OC_CaP.setP(CaP_P) # Set single channel permeability rng = srng.create('mt19937', 512) rng.initialize(2903) sim = solvmod.Tetexact(model, mesh, rng, True) pbarlen = 50 # initialize a progressbar: tpnts = numpy.arange(0.0, T, DT) ntpnts = tpnts.shape[0] res = np.zeros((NITER, len(specs) + 2, ntpnts)) for i in range(NITER): tt = time.time() sim = ResetSim(sim, model, mesh, rng) printProgressBar(0, NITER, prefix='Progress:', suffix='Complete', length=pbarlen) for j in range(ntpnts): if tpnts[j] > CA_FLUX_ONSET and tpnts[j] < CA_FLUX_OFFSET:
def test_unbdiff(): "Diffusion - Unbounded (Tetexact)" m = gen_model() g = gen_geom() # Fetch the index of the centre tet ctetidx = g.findTetByPoint([0.0, 0.0, 0.0]) # And fetch the total number of tets to make the data structures ntets = g.countTets() sim = solvmod.Tetexact(m, g, rng) tpnts = np.arange(0.0, INT, DT) ntpnts = tpnts.shape[0] # Create the big old data structure: iterations x time points x concentrations res = np.zeros((NITER, ntpnts, SAMPLE)) for j in range(NITER): sim.reset() sim.setTetCount(ctetidx, 'X', NINJECT) for i in range(ntpnts): sim.run(tpnts[i]) for k in range(SAMPLE): res[j, i, k] = sim.getTetCount(int(tetidxs[k]), 'X') itermeans = np.mean(res, axis=0) tpnt_compare = [10, 15, 20] passed = True max_err = 0.0 for t in tpnt_compare: bin_n = 20 r_max = tetrads.max() r_min = 0.0 r_seg = (r_max - r_min) / bin_n bin_mins = np.zeros(bin_n + 1) r_tets_binned = np.zeros(bin_n) bin_vols = np.zeros(bin_n) r = r_min for b in range(bin_n + 1): bin_mins[b] = r if (b != bin_n): r_tets_binned[b] = r + r_seg / 2.0 r += r_seg bin_counts = [None] * bin_n for i in range(bin_n): bin_counts[i] = [] for i in range((itermeans[t].size)): i_r = tetrads[i] for b in range(bin_n): if (i_r >= bin_mins[b] and i_r < bin_mins[b + 1]): bin_counts[b].append(itermeans[t][i]) bin_vols[b] += sim.getTetVol(int(tetidxs[i])) break bin_concs = np.zeros(bin_n) for c in range(bin_n): for d in range(bin_counts[c].__len__()): bin_concs[c] += bin_counts[c][d] bin_concs[c] /= (bin_vols[c] * 1.0e18) for i in range(bin_n): if (r_tets_binned[i] > 2.0 and r_tets_binned[i] < 6.0): rad = r_tets_binned[i] * 1.0e-6 det_conc = 1e-18 * ((NINJECT / (np.power( (4 * np.pi * DCST * tpnts[t]), 1.5))) * (np.exp( (-1.0 * (rad * rad)) / (4 * DCST * tpnts[t])))) steps_conc = bin_concs[i] assert tol_funcs.tolerable(det_conc, steps_conc, tolerance)
def setUp(self): self.DCST = 0.08e-12 self.model = smodel.Model() A = smodel.Spec('A', self.model) X = smodel.Spec('X', self.model) self.ssys1 = smodel.Surfsys('ssys1', self.model) self.ssys2 = smodel.Surfsys('ssys2', self.model) self.sreac = smodel.SReac('sreac', self.ssys1, slhs = [A], srhs = [A], kcst = 1e5) self.diff1 = smodel.Diff('diffX1', self.ssys1, X, self.DCST) self.diff2 = smodel.Diff('diffX2', self.ssys2, X, self.DCST) if __name__ == "__main__": self.mesh = meshio.loadMesh('meshes/coin_10r_1h_13861')[0] else: self.mesh = meshio.loadMesh('sdiff_bugfix_test/meshes/coin_10r_1h_13861')[0] ntets = self.mesh.countTets() self.comp = sgeom.TmComp('cyto', self.mesh, range(ntets)) alltris = self.mesh.getSurfTris() patchA_tris = [] patchB_tris = [] patchA_bars = set() patchB_bars = set() for t in alltris: vert0, vert1, vert2 = self.mesh.getTri(t) if (self.mesh.getVertex(vert0)[2] > 0.0 \ and self.mesh.getVertex(vert1)[2] > 0.0 \ and self.mesh.getVertex(vert2)[2] > 0.0): if self.mesh.getTriBarycenter(t)[0] > 0.0: patchA_tris.append(t) bar = self.mesh.getTriBars(t) patchA_bars.add(bar[0]) patchA_bars.add(bar[1]) patchA_bars.add(bar[2]) else: patchB_tris.append(t) bar = self.mesh.getTriBars(t) patchB_bars.add(bar[0]) patchB_bars.add(bar[1]) patchB_bars.add(bar[2]) self.patchA = sgeom.TmPatch('patchA', self.mesh, patchA_tris, icomp = self.comp) self.patchA.addSurfsys('ssys1') self.patchB = sgeom.TmPatch('patchB', self.mesh, patchB_tris, icomp = self.comp) self.patchB.addSurfsys('ssys2') # Find the set of bars that connect the two patches as the intersecting bars barsDB = patchA_bars.intersection(patchB_bars) barsDB=list(barsDB) # Create the surface diffusion boundary self.diffb = sgeom.SDiffBoundary('sdiffb', self.mesh, barsDB, [self.patchA, self.patchB]) ctetidx = self.mesh.findTetByPoint([0.0, 0.0, 0.5e-6]) ctet_trineighbs = self.mesh.getTetTriNeighb(ctetidx) self.ctri_idx=-1 for t in ctet_trineighbs: if t in patchA_tris+patchB_tris: self.ctri_idx = t self.rng = srng.create('r123', 512) self.rng.initialize(1000) self.solver = solv.Tetexact(self.model, self.mesh, self.rng)
# Create the diffusion boundary between compA and compB diffb = sgeom.DiffBoundary('diffb', mesh, tris_DB) return mesh, tets_compA, tets_compB ######################################################################## mdl = gen_model() mesh, tets_compA, tets_compB = gen_geom() rng = srng.create_mt19937(256) rng.initialize(432) sim = solvmod.Tetexact(mdl, mesh, rng) sim.reset() tpnts = numpy.arange(0.0, 0.101, 0.001) ntpnts = tpnts.shape[0] # And fetch the total number of tets to make the data structures ntets = mesh.countTets() # Create the data structures: time points x tetrahedrons resX = numpy.zeros((ntpnts, ntets)) resY = numpy.zeros((ntpnts, ntets)) tetx = mesh.findTetByPoint([0, 0, -4.99e-6]) tety = mesh.findTetByPoint([0, 0, 4.99e-6])
min = mesh.getBoundMin() r = baryc[2] - min[2] # Convert to microns tetrads[i] = r*1.0e6 return mesh ######################################################################## m = gen_model() g = gen_geom() # And fetch the total number of tets to make the data structures ntets = g.countTets() sim = solvmod.Tetexact(m, g, rng) tpnts = np.arange(0.0, INT, DT) ntpnts = tpnts.shape[0] #Create the big old data structure: iterations x time points x concentrations res = np.zeros((NITER, ntpnts, SAMPLE)) # Find the tets connected to the bottom face # First find all the tets with ONE face on a boundary boundtets = [] # store the 0to3 index of the surface triangle for each of these boundary tets bt_srftriidx = []
def setUp(self): mdl = smodel.Model() S1 = smodel.Spec('S1', mdl) vsys = smodel.Volsys('vsys', mdl) ssys = smodel.Surfsys('ssys', mdl) smodel.Reac('R01', vsys, lhs=[S1], rhs=[S1], kcst=1) smodel.SReac('SR01', ssys, slhs=[S1], srhs=[S1], kcst=1) vrange = [-200.0e-3, 50e-3, 1e-3] vrate = lambda v: 2.0 Chan1 = smodel.Chan('Chan1', mdl) chanop = smodel.ChanState('chanop', mdl, Chan1) chancl = smodel.ChanState('chancl', mdl, Chan1) smodel.VDepSReac('VDSR01', ssys, slhs=[chancl], srhs=[chanop], k=vrate, vrange=vrange) smodel.VDepSReac('VDSR02', ssys, srhs=[chancl], slhs=[chanop], k=vrate, vrange=vrange) Chan1_Ohm_I = smodel.OhmicCurr('Chan1_Ohm_I', ssys, chanstate=chanop, g=20e-12, erev=-77e-3) if __name__ == "__main__": self.mesh = meshio.importAbaqus('meshes/test.inp', 1e-7)[0] else: self.mesh = meshio.importAbaqus( 'missing_solver_methods_test/meshes/test.inp', 1e-7)[0] comp1 = sgeom.TmComp('comp1', self.mesh, range(self.mesh.countTets())) comp1.addVolsys('vsys') patch1 = sgeom.TmPatch('patch1', self.mesh, self.mesh.getSurfTris(), comp1) patch1.addSurfsys('ssys') self.c1ROIInds = range(10) self.p1ROIInds = range(5) self.mesh.addROI('comp1ROI', sgeom.ELEM_TET, self.c1ROIInds) self.mesh.addROI('patch1ROI', sgeom.ELEM_TRI, self.p1ROIInds) membrane = sgeom.Memb('membrane', self.mesh, [patch1], opt_method=1) rng = srng.create('mt19937', 512) rng.initialize(1234) self.sim = ssolver.Tetexact(mdl, self.mesh, rng, True) self.sim.setEfieldDT(1e-4) self.sim.reset()
def test_bdiff(): m = gen_model() g, area, a = gen_geom() # And fetch the total number of tets to make the data structures ntets = g.countTets() sim = solvmod.Tetexact(m, g, rng) tpnts = numpy.arange(0.0, INT, DT) ntpnts = tpnts.shape[0] # Create the big old data structure: iterations x time points x concentrations res = numpy.zeros((NITER, ntpnts, SAMPLE)) # Find the tets connected to the bottom face # First find all the tets with ONE face on a boundary boundtets = [] #store the 0to3 index of the surface triangle for each of these boundary tets bt_srftriidx = [] for i in range(ntets): tettemp = g.getTetTetNeighb(i) templist = [t for t in range(4) if tettemp[t] == UNKNOWN_TET] if templist: boundtets.append(i) bt_srftriidx.append(templist) assert len(boundtets) == len(bt_srftriidx) minztets = [] boundminz = g.getBoundMin()[2] + 0.01e-06 num2s = 0 for i in range(boundtets.__len__()): # get the boundary triangle if (bt_srftriidx[i].__len__() == 2): num2s += 1 for btriidx in bt_srftriidx[i]: zminboundtri = True tribidx = g.getTetTriNeighb(boundtets[i])[btriidx] tritemp = g.getTri(tribidx) trizs = [0.0, 0.0, 0.0] trizs[0] = g.getVertex(tritemp[0])[2] trizs[1] = g.getVertex(tritemp[1])[2] trizs[2] = g.getVertex(tritemp[2])[2] for j in range(3): if (trizs[j] > boundminz): zminboundtri = False if (zminboundtri): minztets.append(boundtets[i]) nztets = minztets.__len__() volztets = 0.0 for z in minztets: volztets += g.getTetVol(z) conc = NITER * 6.022e23 * 1.0e-3 / volztets new_dir = './validation_cp/cp/' if not os.path.exists(new_dir): print("ok, then I create it !!!!!!!!") os.makedirs(new_dir) for j in range(NITER): sim.restore('./validation_cp/cp/boundiff') for i in range(ntpnts): sim.run(tpnts[i]) for k in range(SAMPLE): res[j, i, k] = sim.getTetCount(int(tetidxs[k]), 'X') #print('%d / %d' % (j + 1, NITER)) itermeans = numpy.mean(res, axis=0) ######################################################################## D = DCST pi = math.pi nmax = 1000 N = NINJECT N = int((1.0 * NINJECT) / nztets) * nztets def getprob(x, t): if (x > a): print('x out of bounds') return p = 0.0 for n in range(nmax): if (n == 0): A = math.sqrt(1.0 / a) else: A = math.sqrt(2.0 / a) p += math.exp(-D * math.pow( (n * pi / a), 2) * t) * A * math.cos(n * pi * x / a) * A * a return p * N / a tpnt_compare = [6, 8, 10] passed = True max_err = 0.0 for t in tpnt_compare: NBINS = 5 radmax = 0.0 radmin = 11.0 for r in tetrads: if (r > radmax): radmax = r if (r < radmin): radmin = r rsec = (radmax - radmin) / NBINS binmins = numpy.zeros(NBINS + 1) tetradsbinned = numpy.zeros(NBINS) r = radmin bin_vols = numpy.zeros(NBINS) for b in range(NBINS + 1): binmins[b] = r if (b != NBINS): tetradsbinned[b] = r + rsec / 2.0 r += rsec bin_counts = [None] * NBINS for i in range(NBINS): bin_counts[i] = [] filled = 0 for i in range(itermeans[t].size): irad = tetrads[i] for b in range(NBINS): if (irad >= binmins[b] and irad < binmins[b + 1]): bin_counts[b].append(itermeans[t][i]) bin_vols[b] += sim.getTetVol(int(tetidxs[i])) filled += 1.0 break bin_concs = numpy.zeros(NBINS) for c in range(NBINS): for d in range(bin_counts[c].__len__()): bin_concs[c] += bin_counts[c][d] bin_concs[c] /= (bin_vols[c]) bin_concs[c] *= (1.0e-3 / 6.022e23) * 1.0e6 for i in range(NBINS): if (tetradsbinned[i] > 2 and tetradsbinned[i] < 8): rad = tetradsbinned[i] * 1.0e-6 det_conc = (getprob(rad, tpnts[t]) / area) * (1.0 / 6.022e20) steps_conc = bin_concs[i] assert (tol_funcs.tolerable(det_conc, steps_conc, tolerance))
def testTetexact(self): solver = solv.Tetexact(self.model, self.mesh, self.rng) self._runTest(solver)
def test_csd_clamped(): "Diffusion - Clamped (Tetexact)" m = gen_model() g = gen_geom() # And fetch the total number of tets to make the data structures ntets = g.countTets() sim = solvmod.Tetexact(m, g, rng) tpnts = np.arange(0.0, INT, DT) ntpnts = tpnts.shape[0] #Create the big old data structure: iterations x time points x concentrations res = np.zeros((NITER, ntpnts, SAMPLE)) # Find the tets connected to the bottom face # First find all the tets with ONE face on a boundary boundtets = [] # store the 0to3 index of the surface triangle for each of these boundary tets bt_srftriidx = [] for i in range(ntets): tettemp = g.getTetTetNeighb(i) if (tettemp[0] ==-1 or tettemp[1] == -1 or tettemp[2] == -1 or tettemp[3] == -1): boundtets.append(i) templist = [] if (tettemp[0] == -1): templist.append(0) if (tettemp[1] == -1): templist.append(1) if (tettemp[2] == -1): templist.append(2) if (tettemp[3] == -1): templist.append(3) bt_srftriidx.append(templist) assert (boundtets.__len__() == bt_srftriidx.__len__()) minztets = [] boundminz = g.getBoundMin()[2] + 0.01e-06 num2s=0 for i in range(boundtets.__len__()): # get the boundary triangle if (bt_srftriidx[i].__len__() == 2): num2s+=1 for btriidx in bt_srftriidx[i]: zminboundtri = True tribidx = g.getTetTriNeighb(boundtets[i])[btriidx] tritemp = g.getTri(tribidx) trizs = [0.0, 0.0, 0.0] trizs[0] = g.getVertex(tritemp[0])[2] trizs[1] = g.getVertex(tritemp[1])[2] trizs[2] = g.getVertex(tritemp[2])[2] for j in range(3): if (trizs[j]>boundminz): zminboundtri = False if (zminboundtri): minztets.append(boundtets[i]) nztets = minztets.__len__() volztets = 0.0 for z in minztets: volztets += g.getTetVol(z) for j in range(NITER): sim.reset() totset = 0 for k in minztets: sim.setTetConc(k, 'X', CONC) sim.setTetClamped(k, 'X', True) totset+=sim.getTetCount(k, 'X') for i in range(ntpnts): sim.run(tpnts[i]) for k in range(SAMPLE): res[j, i, k] = sim.getTetCount(int(tetidxs[k]), 'X') #print('{0} / {0}'.format(j + 1, NITER)) itermeans = np.mean(res, axis = 0) ######################################################################## tpnt_compare = [3, 4] passed = True max_err = 0.0 for t in tpnt_compare: NBINS=10 radmax = 0.0 radmin = 11.0 for r in tetrads: if (r > radmax): radmax = r if (r < radmin) : radmin = r rsec = (radmax-radmin)/NBINS binmins = np.zeros(NBINS+1) tetradsbinned = np.zeros(NBINS) r = radmin bin_vols = np.zeros(NBINS) for b in range(NBINS+1): binmins[b] = r if (b!=NBINS): tetradsbinned[b] = r +rsec/2.0 r+=rsec bin_counts = [None]*NBINS for i in range(NBINS): bin_counts[i] = [] filled = 0 for i in range(itermeans[t].size): irad = tetrads[i] for b in range(NBINS): if(irad>=binmins[b] and irad<binmins[b+1]): bin_counts[b].append(itermeans[t][i]) bin_vols[b]+=sim.getTetVol(int(tetidxs[i])) filled+=1.0 break bin_concs = np.zeros(NBINS) for c in range(NBINS): for d in range(bin_counts[c].__len__()): bin_concs[c] += bin_counts[c][d] bin_concs[c]/=(bin_vols[c]) bin_concs[c]*=(1.0e-3/6.022e23)*1.0e6 for i in range(NBINS): if (tetradsbinned[i] > 1 and tetradsbinned[i] < 4): rad = tetradsbinned[i]*1.0e-6 det_conc = (getConc(CONC*6.022e26, DCST, rad, tpnts[t])/6.022e26)*1.0e6 steps_conc = bin_concs[i] assert tol_funcs.tolerable(det_conc, steps_conc, tolerance)
ca_curr_data = data_presets.readData(CA_P_CURR_DATA_FILE) ca_influx_profile = data_presets.genCaInfluxProfile( ca_curr_data, roi_areas, roi_vols, PRESET_DATA_START_TIME, PRESET_DATA_START_TIME + SIM_TIME, INFLUX_UPDATE_INTERVAL) # load preset background calcium concerntrations ca_conc_preset_file = open(CA_CONC_PRESET, 'r') ca_conc_preset = cPickle.load(ca_conc_preset_file) ca_conc_preset_file.close() ########################### SIMULATION INITIALIZATION ########################### r = srng.create_mt19937(512) r.initialize(int(time.time())) sim = ssolver.Tetexact(mdl, mesh, r) sim.setCompConc('cyto', 'Mg', Mg_conc) surfarea = sim.getPatchArea('memb') pumpnbs = 6.022141e12 * surfarea sim.setPatchCount('memb', 'Pump', round(pumpnbs)) sim.setPatchCount('memb', 'CaPump', 0) sim.setCompConc('cyto', 'iCBsf', iCBsf_conc) sim.setCompConc('cyto', 'iCBCaf', iCBCaf_conc) sim.setCompConc('cyto', 'iCBsCa', iCBsCa_conc) sim.setCompConc('cyto', 'iCBCaCa', iCBCaCa_conc) sim.setCompConc('cyto', 'CBsf', CBsf_conc)
import steps.rng as srng import time rngs = [] for d in [0, 2, 4, 8]: rng = srng.create('mt19937', 512) rng.initialize(int(time.time())) rngs.append(rng) ######################################################################## # Initialize simulation import steps.solver as ssolver sims = [] for d in range(4): sim = ssolver.Tetexact(mdl, meshes[d], rngs[d]) sim.setROICount("injection", "X", 2000) sims.append(sim) ######################################################################## # Visualization import pyqtgraph as pg import steps.visual as visual app = pg.mkQApp() # Create plot displays display_names = ["Density %i" % (d) for d in [0,2,4,8]] plots = visual.PlotDisplay("Molecule Distribution", size = (400, 800)) displays = []
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 = 3.0 / 100 ####################### Second order irreversible AA ################### global KCST_soAA, CONCA_soAA, CONCB_soAA, tolerance_soAA KCST_soAA = 5.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 = 2.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 = 10.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 = 3.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 NITER_so2d = 1000 # The number of iterations # In tests fewer than 0.1% fail with tolerance of 2% tolerance_so2d = 1.0 / 100 ############################ Common parameters ######################## global VOL DT = 0.1 # Sampling time-step INT = 1.1 # Sim endtime 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) A_foi_diff = smod.Diff('A_foi_diff', volsys, A_foi, 0.01e-12) 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) A_for_diff = smod.Diff('A_for_diff', volsys, A_for, 0.01e-12) B_for_diff = smod.Diff('B_for_diff', volsys, B_for, 0.01e-12) 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) A_soA2_diff = smod.Diff('A_soA2_diff', volsys, A_soA2, 1e-12) 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) A_soAA_diff = smod.Diff('A_soAA_diff', volsys, A_soAA, 0.2e-12) B_soAA_diff = smod.Diff('B_soAA_diff', volsys, B_soAA, 0.2e-12) 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) A_soAB_diff = smod.Diff('A_soAB_diff', volsys, A_soAB, 0.1e-12) B_soAB_diff = smod.Diff('B_soAB_diff', volsys, B_soAB, 0.1e-12) 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) A_soA3_diff = smod.Diff('A_soA3_diff', volsys, A_toA3, 0.2e-12) 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) A_soA2B_diff = smod.Diff('A_soA2B_diff', volsys, A_toA2B, 0.1e-12) B_soA2B_diff = smod.Diff('B_soA2B_diff', volsys, B_toA2B, 0.1e-12) 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) A_so2d_diff = smod.Diff('A_so2d_diff', surfsys, A_so2d, 1.0e-12) B_so2d_diff = smod.Diff('B_so2d_diff', surfsys, B_so2d, 1.0e-12) SR1_so2d = smod.SReac('SR1_so2d', surfsys, slhs=[A_so2d, B_so2d], srhs=[C_so2d], kcst=KCST_so2d) mesh = smeshio.importAbaqus('validation_rd/meshes/sphere_rad1_37tets.inp', 1e-6)[0] VOL = mesh.getMeshVolume() comp1 = sgeom.TmComp('comp1', mesh, range(mesh.ntets)) comp1.addVolsys('vsys') patch1 = sgeom.TmPatch('patch1', mesh, mesh.getSurfTris(), comp1) patch1.addSurfsys('ssys') CCST_so2d = KCST_so2d / (6.02214179e23 * patch1.getArea()) rng = srng.create('r123', 512) rng.initialize(1000) sim = ssolv.Tetexact(mdl, mesh, 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 test_ubdiff(): rng = srng.create('mt19937', 1024) rng.initialize(int(time.time()%4294967295)) # The max unsigned long # Number of iterations; plotting dt; sim endtime: NITER = 10 DT = 0.01 INT = 0.21 # Number of molecules injected in centre; diff constant; number of tets sampled: NINJECT = 100000 DCST = 0.02e-9 # With good code <1% fail with a tolerance of 5% tolerance = 5.0/100 ######################################################################## SAMPLE = 32552 # all tets MESHFILE = 'sphere_rad10_33Ktets_adaptive' # create the array of tet indices to be found at random tetidxs = np.zeros(SAMPLE, dtype = 'int') for i in range(SAMPLE): tetidxs[i] = i # further create the array of tet barycentre distance to centre tetrads = np.zeros(SAMPLE) tetvols = np.zeros(SAMPLE) ######################################################################## def gen_model(): mdl = smodel.Model() X = smodel.Spec('X', mdl) cytosolv = smodel.Volsys('cytosolv', mdl) dif_X = smodel.Diff('diffX', cytosolv, X) dif_X.setDcst(DCST) return mdl ######################################################################## def gen_geom(): mesh = smeshio.loadMesh('./validation_rd/meshes/'+MESHFILE)[0] ctetidx = mesh.findTetByPoint([0.0, 0.0, 0.0]) ntets = mesh.countTets() comp = stetmesh.TmComp('cyto', mesh, range(ntets)) comp.addVolsys('cytosolv') # Now find the distance of the centre of the tets to the centre of the centre tet (at 0,0,0) cbaryc = mesh.getTetBarycenter(ctetidx) for i in range(SAMPLE): baryc = mesh.getTetBarycenter(int(tetidxs[i])) r2 = np.power((baryc[0]-cbaryc[0]),2) + np.power((baryc[1]-cbaryc[1]),2) + np.power((baryc[2]-cbaryc[2]),2) r = np.sqrt(r2) # Conver to microns tetrads[i] = r*1.0e6 tetvols[i] = mesh.getTetVol(int(tetidxs[i])) return mesh ######################################################################## m = gen_model() g = gen_geom() # Fetch the index of the centre tet ctetidx = g.findTetByPoint([0.0, 0.0, 0.0]) # And fetch the total number of tets to make the data structures ntets = g.countTets() sim = solvmod.Tetexact(m, g, rng) tpnts = np.arange(0.0, INT, DT) ntpnts = tpnts.shape[0] #Create the big old data structure: iterations x time points x concentrations res = np.zeros((NITER, ntpnts, SAMPLE)) for j in range(NITER): sim.restore('./validation_cp/cp/unbdiff') for i in range(ntpnts): sim.run(tpnts[i]) for k in range(SAMPLE): res[j, i, k] = sim.getTetCount(int(tetidxs[k]), 'X') #print('{0} / {1}'.format(j + 1, NITER)) itermeans = np.mean(res, axis = 0) tpnt_compare = [10, 15, 20] passed = True max_err = 0.0 for t in tpnt_compare: bin_n = 20 r_max = tetrads.max() r_min = 0.0 r_seg = (r_max-r_min)/bin_n bin_mins = np.zeros(bin_n+1) r_tets_binned = np.zeros(bin_n) bin_vols = np.zeros(bin_n) r = r_min for b in range(bin_n + 1): bin_mins[b] = r if (b!=bin_n): r_tets_binned[b] = r +r_seg/2.0 r+=r_seg bin_counts = [None]*bin_n for i in range(bin_n): bin_counts[i] = [] for i in range((itermeans[t].size)): i_r = tetrads[i] for b in range(bin_n): if(i_r>=bin_mins[b] and i_r<bin_mins[b+1]): bin_counts[b].append(itermeans[t][i]) bin_vols[b]+=sim.getTetVol(int(tetidxs[i])) break bin_concs = np.zeros(bin_n) for c in range(bin_n): for d in range(bin_counts[c].__len__()): bin_concs[c] += bin_counts[c][d] bin_concs[c]/=(bin_vols[c]*1.0e18) for i in range(bin_n): if (r_tets_binned[i] > 2.0 and r_tets_binned[i] < 6.0): rad = r_tets_binned[i]*1.0e-6 det_conc = 1e-18*((NINJECT/(np.power((4*np.pi*DCST*tpnts[t]),1.5)))*(np.exp((-1.0*(rad*rad))/(4*DCST*tpnts[t])))) steps_conc = bin_concs[i] assert(tol_funcs.tolerable(det_conc, steps_conc, tolerance))
tetrads[i] = r * 1.0e6 print "Tetrahedron samples found" return mesh ######################################################################## model = gen_model() tmgeom = gen_geom() rng = srng.create('mt19937', 512) rng.initialize(2903) sim = solvmod.Tetexact(model, tmgeom, rng) tpnts = numpy.arange(0.0, INT, DT) # Find how many "time points" we have ntpnts = tpnts.shape[0] # Create the data structure: iterations x time points x tet samples res = numpy.zeros((NITER, ntpnts, SAMPLE)) # Fetch the index of the tetrahedron at the centre of the mesh ctetidx = tmgeom.findTetByPoint([0.0, 0.0, 0.0]) # Run NITER number of iterations: for i in range(NITER): sim.reset() print "Running iteration", i
ntets = mesh.countTets() comp = stetmesh.TmComp('comp', mesh, range(ntets)) comp.addVolsys('vsys') return mesh ######################################################################## m = gen_model() g = gen_geom() ######################################################################## rng = srng.create('mt19937', 512) rng.initialize(int(time.time() % 4294967295)) # The max unsigned long sim = ssa_solver.Tetexact(m, g, rng) ######################################################################## # recording sim_result_dir = RESULT_DIR + "/ssa_%e_%s" % (MOLECULE_RATIO, MESHFILE) try: os.mkdir(RESULT_DIR) except: pass try: os.mkdir(sim_result_dir) except: pass summary_file = open(sim_result_dir + "/result.csv", 'w', 0) summary_file.write("Simulation Time,")