Example #1
0
    def setUp(self):
        self.model = smodel.Model()

        self.vsys1 = smodel.Volsys('vsys1', self.model)
        self.ssys1 = smodel.Surfsys('ssys1', self.model)

        if __name__ == "__main__":
            self.mesh = meshio.loadMesh('meshes/cyl_len10_diam1')[0]
        else:
            self.mesh = meshio.loadMesh(
                'getROIArea_bugfix_test/meshes/cyl_len10_diam1')[0]

        ntets = self.mesh.countTets()
        comp1Tets, comp2Tets = [], []
        comp1Tris, comp2Tris = set(), set()
        for i in range(ntets):
            if self.mesh.getTetBarycenter(i)[0] > 0:
                comp1Tets.append(i)
                comp1Tris |= set(self.mesh.getTetTriNeighb(i))
            else:
                comp2Tets.append(i)
                comp2Tris |= set(self.mesh.getTetTriNeighb(i))
        patch1Tris = list(comp1Tris & comp2Tris)

        self.comp1 = sgeom.TmComp('comp1', self.mesh, comp1Tets)
        self.comp2 = sgeom.TmComp('comp2', self.mesh, comp2Tets)
        self.comp1.addVolsys('vsys1')
        self.comp2.addVolsys('vsys1')

        self.patch1 = sgeom.TmPatch('patch1', self.mesh, patch1Tris,
                                    self.comp1, self.comp2)
        self.patch1.addSurfsys('ssys1')

        self.ROI1 = self.mesh.addROI('ROI1', sgeom.ELEM_TRI, patch1Tris)
    def setUp(self):
        self.model = smodel.Model()
        A = smodel.Spec("A", self.model)
        B = smodel.Spec("B", self.model)
        C = smodel.Spec("C", self.model)
        D = smodel.Spec("D", self.model)
        E = smodel.Spec("E", self.model)

        self.vsys1 = smodel.Volsys('vsys1', self.model)
        self.vsys2 = smodel.Volsys('vsys2', self.model)
        self.ssys1 = smodel.Surfsys('ssys1', self.model)

        self.reac1 = smodel.Reac('reac1', self.vsys1, lhs = [A], rhs = [A],  kcst = 1e5)
        self.reac2 = smodel.Reac('reac2', self.vsys2, lhs = [E], rhs = [E],  kcst = 1e4)

        self.sreac = smodel.SReac('sreac', self.ssys1, slhs = [B], srhs = [B],  kcst = 1e3)
    
        if __name__ == "__main__":
            self.mesh = meshio.loadMesh('meshes/cyl_len10_diam1')[0]
        else:
            self.mesh = meshio.loadMesh('getROIArea_bugfix_test/meshes/cyl_len10_diam1')[0]

        ntets = self.mesh.countTets()
        comp1Tets, comp2Tets = [], []
        comp1Tris, comp2Tris = set(), set()
        for i in range(ntets):
            if self.mesh.getTetBarycenter(i)[0] > 0:
                comp1Tets.append(i)
                comp1Tris |= set(self.mesh.getTetTriNeighb(i))
            else:
                comp2Tets.append(i)
                comp2Tris |= set(self.mesh.getTetTriNeighb(i))
        patch1Tris = list(comp1Tris & comp2Tris)

        self.comp1 = sgeom.TmComp('comp1', self.mesh, comp1Tets)
        self.comp2 = sgeom.TmComp('comp2', self.mesh, comp2Tets)
        self.comp1.addVolsys('vsys1')
        self.comp2.addVolsys('vsys2')

        self.patch1 = sgeom.TmPatch('patch1', self.mesh, patch1Tris, self.comp1, self.comp2)
        self.patch1.addSurfsys('ssys1')

        self.ROI1 = self.mesh.addROI('ROI1', sgeom.ELEM_TET, comp1Tets)
        self.ROI2 = self.mesh.addROI('ROI2', sgeom.ELEM_TET, comp2Tets)
        self.ROI3 = self.mesh.addROI('ROI3', sgeom.ELEM_TRI, patch1Tris)
    
        self.rng = srng.create('r123', 512)
        self.rng.initialize(1000)
        tet_hosts = gd.linearPartition(self.mesh, [steps.mpi.nhosts, 1, 1])
        tri_hosts = gd.partitionTris(self.mesh, tet_hosts, patch1Tris)
        self.solver = solv.TetOpSplit(self.model, self.mesh, self.rng, solv.EF_NONE, tet_hosts, tri_hosts)
Example #3
0
def gen_geom():
    mesh = meshio.loadMesh('./validation_rd/meshes/' + MESHFILE)[0]

    a = mesh.getBoundMax()[2] - mesh.getBoundMin()[2]
    area = mesh.getMeshVolume() / a

    ntets = mesh.countTets()
    comp = stetmesh.TmComp('cyto', mesh, range(ntets))
    comp.addVolsys('cytosolv')

    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]))
        min = mesh.getBoundMin()
        r = baryc[2] - min[2]
        # Convert to microns
        tetrads[i] = r * 1.0e6

    return mesh, area, a
Example #4
0
def gen_geom():
    mesh = meshio.loadMesh('validation_rd_mpi/meshes/' + MESHFILE)[0]

    ntets = mesh.countTets()

    comp = stetmesh.TmComp('cyto', mesh, range(ntets))
    comp.addVolsys('cytosolv')

    # 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 centre of the tets to the Z lower face
    for i in range(SAMPLE):
        baryc = mesh.getTetBarycenter(int(tetidxs[i]))
        min = mesh.getBoundMin()
        r = baryc[2] - min[2]
        # Convert to microns
        tetrads[i] = r * 1.0e6

    return mesh
Example #5
0
def build_geometry(mesh_path, file_format="xml", scale=1.):

    scale = float(scale)

    if file_format == "xml":
        mesh = meshio.loadMesh(mesh_path)[0]
    elif file_format == "msh":
        mesh = meshio.importGmsh(mesh_path + ".msh", scale)[0]
    elif file_format == "inp":
        mesh = meshio.importAbaqus(mesh_path + ".inp", scale)[0]
    else:
        raise TypeError("File format " + str(file_format) +
                        " not available: choose among xml, msh, inp")

    cyto = sgeom.TmComp('cyto', mesh, range(mesh.ntets))

    (zmin_tris, zmin_vset, zmax_tris, zmax_vset) = zminmax_tris(mesh)
    memb_tris = list(mesh.getSurfTris())
    for tri in zmin_tris:
        memb_tris.remove(tri)
    for tri in zmax_tris:
        memb_tris.remove(tri)
    memb = sgeom.TmPatch('memb', mesh, memb_tris, cyto)
    membrane = sgeom.Memb('membrane', mesh, [memb])

    mesh.addROI('v_zmin', sgeom.ELEM_VERTEX, zmin_vset)
    mesh.addROI('v_zmin_sample', sgeom.ELEM_VERTEX,
                radial_extrema(mesh, zmin_vset))
    mesh.addROI('v_zmax_sample', sgeom.ELEM_VERTEX,
                radial_extrema(mesh, zmax_vset))
    return mesh
Example #6
0
def main():
    print("Import mesh to STEPS")
    tetmesh = meshio.importAbaqus("meshes/tets.inp", 1e-6)[0]

    print("Create spatial index")
    spatial_index = pRs.gen_tet_spatial_index(tetmesh, 1e-6)

    print("Add ROIs according to boundaries and signatures")
    boundary_files = ["meshes/ER.stl", "meshes/PSD.stl"]
    roi_labels = {"ER": "-*",   # inside ER.stl, doesn't matter for PSD.stl
                  "PSD": "+-"}  # not inside ER.stl, inside PSD.stl

    pRs.add_tet_ROIs(tetmesh, 1e-6, spatial_index, boundary_files, roi_labels)

    print("Save to STEPS xml file")
    meshio.saveMesh("meshes/labeled_mesh", tetmesh)

    print("Load the xml file")
    loaded_mesh = meshio.loadMesh("meshes/labeled_mesh")[0]

    print("Visualize the ROIs")
    ER_tets = loaded_mesh.getROIData("ER")
    PSD_tets = loaded_mesh.getROIData("PSD")
    Cyto_tets = set(range(loaded_mesh.ntets)) - set(ER_tets)

    print(
        "PSD tets / Cyto tets / ER tets / All tets: %i / %i / %i / %i"
        % (len(PSD_tets), len(Cyto_tets), len(ER_tets), loaded_mesh.ntets)
    )

    tet_groups = {}
    for tet in Cyto_tets:
        if tet in PSD_tets:
            tet_groups[tet] = "PSD"
        else:
            tet_groups[tet] = "Cyto"
    for tet in ER_tets:
        tet_groups[tet] = "ER"

    color_map = dict(
        PSD=[0.0, 0.0, 1.0, 0.1],  # blue, alpha 0.1
        Cyto=[1.0, 1.0, 1.0, 0.1], # grey, alpha 0.1
        ER=[1.0, 0.0, 0.0, 0.1],  # red, alpha 0.1
    )

    app = pg.mkQApp()
    w = steps.visual.TetPartitionDisplay(
        loaded_mesh, tet_groups, color_map=color_map
    )
    app.exec_()
def gen_geom():

    mesh = smeshio.loadMesh('validation_rd/meshes/' + MESHFILE)[0]

    ntets = mesh.countTets()
    comp = stetmesh.TmComp('cyto', mesh, range(ntets))

    alltris = mesh.getSurfTris()

    patch_tris = []
    for t in alltris:
        baryc = mesh.getTriBarycenter(t)
        rad = np.sqrt(np.power(baryc[0], 2) + np.power(baryc[1], 2))
        # By checking the cubit mesh the outer tris fall in the following bound
        if rad > 0.000009955 and rad < 0.00001001: patch_tris.append(t)

    patch = stetmesh.TmPatch('patch', mesh, patch_tris, icomp=comp)
    patch.addSurfsys('ssys')

    area = 0
    for t in patch_tris:
        area += mesh.getTriArea(t)

    inject_tris = []
    for p in patch_tris:
        # X should be maximum (10) for the inject region
        if mesh.getTriBarycenter(p)[0] > 9.999e-6:
            inject_tris.append(p)

    patch_tris_n = len(patch_tris)

    # Now find the distances along the edge for all tris
    tridists = np.zeros(patch_tris_n)
    triareas = np.zeros(patch_tris_n)

    for i in range(patch_tris_n):
        baryc = mesh.getTriBarycenter(patch_tris[i])
        rad = np.sqrt(np.power(baryc[0], 2) + np.power(baryc[1], 2))

        theta = np.arctan2(baryc[1], baryc[0])

        tridists[i] = (theta * rad * 1e6)
        triareas[i] = mesh.getTriArea(patch_tris[i])

    # Triangles will be separated into those to the 'high' side (positive y) with positive L
    # and those on the low side (negative y) with negative L

    return mesh, patch_tris, patch_tris_n, inject_tris, tridists, triareas
Example #8
0
def gen_geom():
    mesh = smeshio.loadMesh('meshes/coin_10r_1h_13861')[0]

    ntets = mesh.countTets()
    comp = stetmesh.TmComp('cyto', mesh, range(ntets))

    alltris = mesh.getSurfTris()

    # Sort patch triangles as those of positive z
    patch_tris = []
    for t in alltris:
        vert0, vert1, vert2 = mesh.getTri(t)
        if (mesh.getVertex(vert0)[2] > 0.0 \
            and mesh.getVertex(vert1)[2] > 0.0 \
            and mesh.getVertex(vert2)[2] > 0.0):
            patch_tris.append(t)

    # Create the patch
    patch = stetmesh.TmPatch('patch', mesh, patch_tris, icomp=comp)
    patch.addSurfsys('ssys')

    patch_tris_n = len(patch_tris)
    trirads = pylab.zeros(patch_tris_n)
    triareas = pylab.zeros(patch_tris_n)

    # Find the central tri
    ctetidx = mesh.findTetByPoint([0.0, 0.0, 0.5e-6])
    ctet_trineighbs = mesh.getTetTriNeighb(ctetidx)
    ctri_idx = -1
    for t in ctet_trineighbs:
        if t in patch_tris:
            ctri_idx = t

    # Now find the distance of the centre of each tri to the central tri
    cbaryc = mesh.getTriBarycenter(ctri_idx)
    for i in range(patch_tris_n):
        baryc = mesh.getTriBarycenter(patch_tris[i])
        r2 = math.pow((baryc[0]-cbaryc[0]),2) + \
                math.pow((baryc[1]-cbaryc[1]),2) + \
                    math.pow((baryc[2]-cbaryc[2]),2)
        r = math.sqrt(r2)
        # Convert to microns
        trirads[i] = r * 1.0e6
        triareas[i] = mesh.getTriArea(patch_tris[i]) * 1.0e12

    return mesh, patch_tris, patch_tris_n, ctri_idx, trirads, triareas
Example #9
0
def gen_geom():
    mesh = meshio.loadMesh('meshes/cyl_len10_diam1')[0]
    ntets = mesh.countTets()
    
    tets_compA = []
    tets_compB = []
    tris_compA = set()
    tris_compB = set()
    z_max = mesh.getBoundMax()[2]
    z_min = mesh.getBoundMin()[2]
    z_mid = z_min+(z_max-z_min)/2.0
    
    for t in range(ntets):
        # Fetch the z coordinate of the barycenter
        barycz = mesh.getTetBarycenter(t)[2]
        # Fetch the triangle indices of the tetrahedron, a tuple of length 4:
        tris = mesh.getTetTriNeighb(t)
        if barycz < z_mid: 
            tets_compA.append(t)
            tris_compA.add(tris[0])
            tris_compA.add(tris[1])
            tris_compA.add(tris[2])
            tris_compA.add(tris[3])
        else: 
            tets_compB.append(t)
            tris_compB.add(tris[0])
            tris_compB.add(tris[1])
            tris_compB.add(tris[2])
            tris_compB.add(tris[3])
    
    # Create the mesh compartments
    compA = sgeom.TmComp('compA', mesh, tets_compA)
    compB = sgeom.TmComp('compB', mesh, tets_compB)
    compA.addVolsys('vsysA')
    compB.addVolsys('vsysB')
    
    # Make the diff boundary tris with the intersection and convert to list
    tris_DB = tris_compA.intersection(tris_compB)
    tris_DB = list(tris_DB)
    
    # Create the diffusion boundary between compA and compB
    diffb = sgeom.DiffBoundary('diffb', mesh, tris_DB)
    
    return mesh, tets_compA, tets_compB
def gen_geom():
    mesh = meshio.loadMesh('meshes/cyl_len10_diam1')[0]
    ntets = mesh.countTets()

    tets_compA = []
    tets_compB = []
    tris_compA = set()
    tris_compB = set()
    z_max = mesh.getBoundMax()[2]
    z_min = mesh.getBoundMin()[2]
    z_mid = z_min + (z_max - z_min) / 2.0

    for t in range(ntets):
        # Fetch the z coordinate of the barycenter
        barycz = mesh.getTetBarycenter(t)[2]
        # Fetch the triangle indices of the tetrahedron, a tuple of length 4:
        tris = mesh.getTetTriNeighb(t)
        if barycz < z_mid:
            tets_compA.append(t)
            tris_compA.add(tris[0])
            tris_compA.add(tris[1])
            tris_compA.add(tris[2])
            tris_compA.add(tris[3])
        else:
            tets_compB.append(t)
            tris_compB.add(tris[0])
            tris_compB.add(tris[1])
            tris_compB.add(tris[2])
            tris_compB.add(tris[3])

    # Create the mesh compartments
    compA = sgeom.TmComp('compA', mesh, tets_compA)
    compB = sgeom.TmComp('compB', mesh, tets_compB)
    compA.addVolsys('vsysA')
    compB.addVolsys('vsysB')

    # Make the diff boundary tris with the intersection and convert to list
    tris_DB = tris_compA.intersection(tris_compB)
    tris_DB = list(tris_DB)

    # Create the diffusion boundary between compA and compB
    diffb = sgeom.DiffBoundary('diffb', mesh, tris_DB)

    return mesh, tets_compA, tets_compB
Example #11
0
def gen_geom():
    mesh = smeshio.loadMesh('validation_rd/meshes/' + MESHFILE)[0]

    ctetidx = mesh.findTetByPoint([0.0, 0.0, 0.5e-6])

    ntets = mesh.countTets()
    comp = stetmesh.TmComp('cyto', mesh, range(ntets))

    alltris = mesh.getSurfTris()

    patch_tris = []
    for t in alltris:
        vert0, vert1, vert2 = mesh.getTri(t)
        if (mesh.getVertex(vert0)[2] > 0.0 and mesh.getVertex(vert1)[2] > 0.0
                and mesh.getVertex(vert2)[2] > 0.0):
            patch_tris.append(t)

    patch_tris_n = len(patch_tris)

    patch = stetmesh.TmPatch('patch', mesh, patch_tris, icomp=comp)
    patch.addSurfsys('ssys')

    trirads = numpy.zeros(patch_tris_n)
    triareas = numpy.zeros(patch_tris_n)

    # TRy to find the central tri
    ctet_trineighbs = mesh.getTetTriNeighb(ctetidx)
    ctri_idx = -1
    for t in ctet_trineighbs:
        if t in patch_tris:
            ctri_idx = t

    # Now find the distance of the center of the tets to the center of the center tet (at 0,0,0)
    cbaryc = mesh.getTriBarycenter(ctri_idx)
    for i in range(patch_tris_n):
        baryc = mesh.getTriBarycenter(patch_tris[i])
        r2 = math.pow((baryc[0] - cbaryc[0]), 2) + math.pow(
            (baryc[1] - cbaryc[1]), 2) + math.pow((baryc[2] - cbaryc[2]), 2)
        r = math.sqrt(r2)
        # Conver to microns
        trirads[i] = r * 1.0e6
        triareas[i] = mesh.getTriArea(patch_tris[i])

    return mesh, patch_tris, patch_tris_n, ctri_idx, trirads, triareas
Example #12
0
def build_geometry(mesh_path):
    mesh = meshio.loadMesh(mesh_path)[0]

    cyto = sgeom.TmComp('cyto', mesh, range(mesh.ntets))

    (zmin_tris,zmin_vset,zmax_tris,zmax_vset) = zminmax_tris(mesh)
    memb_tris = list(mesh.getSurfTris())
    for tri in zmin_tris: memb_tris.remove(tri)
    for tri in zmax_tris: memb_tris.remove(tri)
    memb = sgeom.TmPatch('memb', mesh, memb_tris, cyto)
    membrane = sgeom.Memb('membrane', mesh, [memb] )

    #mesh.addROI('v_zmin',sgeom.ELEM_VERTEX,ROIset(zmin_vset))
    #mesh.addROI('v_zmin_sample',sgeom.ELEM_VERTEX,ROIset(radial_extrema(mesh,zmin_vset)))
    #mesh.addROI('v_zmax_sample',sgeom.ELEM_VERTEX,ROIset(radial_extrema(mesh,zmax_vset)))
    mesh.addROI('v_zmin',sgeom.ELEM_VERTEX,zmin_vset)
    mesh.addROI('v_zmin_sample',sgeom.ELEM_VERTEX,radial_extrema(mesh,zmin_vset))
    mesh.addROI('v_zmax_sample',sgeom.ELEM_VERTEX,radial_extrema(mesh,zmax_vset))
    return mesh
Example #13
0
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

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

def gen_model():
    
    mdl = smodel.Model()
    X = smodel.Spec('X', mdl)
    ssys = smodel.Surfsys('ssys', mdl)
    diff_X = smodel.Diff('diffX', ssys, X,  DCST)
    
    return mdl

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

mesh = smeshio.loadMesh('meshes/coin_10r_1h_13861')[0]

ntets = mesh.countTets()
comp = stetmesh.TmComp('cyto', mesh, range(ntets))


alltris = mesh.getSurfTris()

# Sort patch triangles as those of positive z: A +ve x, B -ve x
patchA_tris = []
patchB_tris = []
patchA_bars = set()
patchB_bars = set()

for t in alltris:
    vert0, vert1, vert2 = mesh.getTri(t)
Example #15
0
    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)
Example #16
0
def test_kis_ode():
    "Reaction-diffusion - Degradation-diffusion (TetODE)"

    NITER = 1  # The number of iterations
    DT = 0.01  # Sampling time-step
    INT = 0.11  # Sim endtime

    DCSTA = 400 * 1e-12
    DCSTB = DCSTA
    RCST = 100000.0e6

    NA0 = 10000  # Initial number of A molecules
    NB0 = NA0  # Initial number of B molecules

    SAMPLE = 5000

    # create the array of tet indices to be found at random
    tetidxs = np.zeros(SAMPLE, dtype='int')
    # further create the array of tet barycentre distance to centre
    tetrads = np.zeros(SAMPLE)

    #Small expected error
    tolerance = 1.5 / 100

    ########################################################################
    rng = srng.create('r123', 512)
    rng.initialize(1000)  # 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_STEPS')[0]
    ntets = mesh.countTets()

    VOLA = mesh.getMeshVolume() / 2.0
    VOLB = VOLA

    comp1 = sgeom.TmComp('comp1', mesh, range(ntets))
    comp1.addVolsys('vsys')

    # Now fill the array holding the tet indices to sample at random
    assert (SAMPLE <= ntets)

    numfilled = 0
    while (numfilled < SAMPLE):
        if (ntets != SAMPLE):
            max = mesh.getBoundMax()
            min = mesh.getBoundMin()

            rnx = rng.getUnfII()
            rny = rng.getUnfII()
            rnz = rng.getUnfII()

            xpnt = min[0] + (max[0] - min[0]) * rnx
            ypnt = min[1] + (max[1] - min[1]) * rny
            zpnt = min[2] + (max[2] - min[2]) * rnz

            idx = mesh.findTetByPoint([xpnt, ypnt, zpnt])

            if (idx == -1): continue
            if (idx not in tetidxs):
                tetidxs[numfilled] = idx
                numfilled += 1
        else:
            tetidxs[numfilled] = numfilled
            numfilled += 1
    tetidxs.sort()

    # Now find the distance of the centre 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 * 1e6

    Atets = []
    Btets = []

    for t in range(ntets):
        baryx = mesh.getTetBarycenter(t)[0]
        if (baryx < 0.0):
            Atets.append(t)
            continue
        if (baryx >= 0.0):
            Btets.append(t)
            continue
        assert (False)

    sim = ssolv.TetODE(mdl, mesh, rng)
    sim.setTolerances(1.0e-3, 1.0e-3)

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

    resA = np.zeros((NITER, ntpnts, SAMPLE))
    resB = np.zeros((NITER, ntpnts, SAMPLE))

    for i in range(0, NITER):
        sim.setCompCount('comp1', 'A', 2 * NA0)
        sim.setCompCount('comp1', 'B', 2 * NB0)

        for t in Btets:
            sim.setTetCount(t, 'A', 0)
        for t in Atets:
            sim.setTetCount(t, 'B', 0)

        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 = np.mean(resA, axis=0)
    itermeansB = np.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)) * np.exp(
                (-(DCSTA / (20.0e-6)) * np.power(
                    (2 * n + 1), 2) * np.power(np.pi, 2) * t) / (4 * L)) *
                      np.sin(((2 * n + 1) * np.pi * x) / (2 * L)))
        concA *= ((4 * NA0 / np.pi) / (VOLA * 6.022e26)) * 1.0e6

        return concA

    tpnt_compare = [5, 10]

    for tidx in tpnt_compare:
        NBINS = 50
        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 = 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_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 = np.zeros(NBINS)
        bin_concsB = np.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]
                assert tol_funcs.tolerable(det_conc, steps_conc, tolerance)

            if (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)
Example #17
0
def gen_geom():
    
    print "Loading mesh..."
    mesh = smeshio.loadMesh('meshes/sphere_rad10_11Ktets')[0]
    print "Mesh Loaded"
    
    # Find the total number of tetrahedrons in the mesh	
    ntets = mesh.countTets()
    # Create a compartment containing all tetrahedron
    comp = stetmesh.TmComp('cyto', mesh, range(ntets))
    comp.addVolsys('cytosolv')
    
    print "Finding tetrahedron samples..."
    # Fetch the central tetrahedron index and store:
    ctetidx = mesh.findTetByPoint([0.0, 0.0, 0.0])
    tetidxs[0] = ctetidx

    # Find the central tetrahedron's four neighbours:
    neighbidcs = mesh.getTetTetNeighb(ctetidx)
    tetidxs[1], tetidxs[2], tetidxs[3], tetidxs[4] = neighbidcs
    
    # Keep track how many tet indices we have stored so far
    stored = 5
    
    # Find the maximum and minimum coordinates of the mesh
    max = mesh.getBoundMax()
    min = mesh.getBoundMin()
    
    # Run a loop until we have stored all tet indices we require
    while (stored < SAMPLE):

        # Fetch 3 random numbers between 0 and 1
        rnx = random.random()
        rny = random.random()
        rnz = random.random()  
              
        # Find the coordinates in the mesh that these numbers relate to
        xcrd = min[0] + (max[0]-min[0])*rnx
        ycrd = min[1] + (max[1]-min[1])*rny
        zcrd = min[2] + (max[2]-min[2])*rnz
        
        # Find the tetrahedron that encompasses this point.
        tidx = mesh.findTetByPoint([xcrd, ycrd, zcrd])
        
        # -1 was returned if point is outside the mesh:
        if (tidx == -1): continue
        if (tidx not in tetidxs):
            tetidxs[stored] = tidx
            stored += 1
    
    # Find the barycenter of the central tetrahedron
    cbaryc = mesh.getTetBarycenter(ctetidx)
    
    for i in range(SAMPLE):
        # Fetch the barycenter of the tetrahedron:
        baryc = mesh.getTetBarycenter(tetidxs[i])

        # Find the radial distance of this tetrahedron to mesh center:
        r = math.sqrt(math.pow((baryc[0]-cbaryc[0]),2) + \
                math.pow((baryc[1]-cbaryc[1]),2) + \
                    math.pow((baryc[2]-cbaryc[2]),2))

        # Store the radial distance (in microns):
        tetrads[i] = r*1.0e6
        
    print "Tetrahedron samples found"
    
    return mesh
Example #18
0
OC2_SK = smodel.OhmicCurr('OC2_SK',
                          ssys_stoch,
                          chanstate=SK_O2,
                          erev=SK_rev,
                          g=SK_G)

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

########### MESH & COMPARTMENTALIZATION #################

##########Import Mesh

# For stochastic sim:
mesh_stoch = meshio.loadMesh('./meshes/' + meshfile_ab)[0]

# For determinstic sim:
mesh_det = meshio.loadMesh('./meshes/' + meshfile_ab)[0]

outer_tets = range(mesh_stoch.ntets)
inner_tets = gettets.getcyl(mesh_stoch, 1e-6, -200e-6, 200e-6)[0]

for i in inner_tets:
    outer_tets.remove(i)

print outer_tets.__len__(), " tets in outer compartment"
print inner_tets.__len__(), " tets in inner compartment"

# Record voltage from the central tetrahedron
cent_tet = mesh_stoch.findTetByPoint([0.0, 0.0, 0.0])
Example #19
0
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))
Example #20
0
volsys = smodel.Volsys('vsys', mdl)

# Fetch reference to Calcium and IP3 Spec objects
Ca = mdl.getSpec('Ca')
IP3 = mdl.getSpec('IP3')

# Create diffusion rules
Ca_diff = smodel.Diff('Ca_diff', volsys, Ca, DCST_Ca)
IP3_diff = smodel.Diff('IP3_diff', volsys, IP3, DCST_IP3)

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Import mesh
import steps.utilities.meshio as meshio

mesh = meshio.loadMesh("ip3r_mesh")[0]

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

# Create random number generator
r = srng.create('mt19937', 512)
r.initialize(456)

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

# Create reaction-diffusion solver object
sim = ssolver.Tetexact(mdl, mesh, r)

# Setup initial condition
sim.setCompCount('cyt', 'Ca', 1)
sim.setCompConc('cyt', 'IP3', 2.5e-6)
Example #21
0
def test_kisilevich():
    "Reaction-diffusion - Degradation-diffusion (Parallel TetOpSplit)"

    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 barycentre distance to centre
    tetrads = numpy.zeros(SAMPLE)

    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_mpi/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 centre 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('r123', 512)
    rng.initialize(1000)

    tet_hosts = gd.binTetsByAxis(mesh, steps.mpi.nhosts)
    sim = solvmod.TetOpSplit(mdl, mesh, rng, False, tet_hosts)

    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.reset()

        sim.setDiffBoundaryDiffusionActive('diffb', 'A', True)
        sim.setDiffBoundaryDiffusionActive('diffb', 'B', True)

        sim.setCompCount('compa', 'A', NA0)
        sim.setCompCount('compb', 'B', NB0)

        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]
                assert tol_funcs.tolerable(det_conc, steps_conc, tolerance)

            if (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)
Example #22
0
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]
Example #23
0
def test_rallpack3():
    print("Rallpack 3 with TetODE")
    #meshfile ='axon_cube_L1000um_D866m_600tets'
    meshfile = 'axon_cube_L1000um_D866m_1135tets'
    #meshfile = 'axon_cube_L1000um_D866nm_1978tets'

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

    # Potassium conductance, Siemens/m^2
    K_G = 360
    # Sodium conductance, Siemens/m^2
    Na_G = 1200
    # Leak conductance, Siemens/m^2
    L_G = 0.25

    # Potassium reversal potential, V
    K_rev = -77e-3
    # Sodium reversal potential, V
    Na_rev = 50e-3
    # Leak reveral potential, V
    leak_rev = -65.0e-3

    # Potassium channel density
    K_ro = 18.0e12
    # Sodium channel density
    Na_ro = 60.0e12

    # Total leak conductance for ideal cylinder:
    surfarea_cyl = 1.0 * np.pi * 1000 * 1e-12
    L_G_tot = L_G * surfarea_cyl

    # A table of potassium density factors at -65mV, found in getpops. n0, n1, n2, n3, n4
    K_FACS = [0.216750577045, 0.40366011853, 0.281904943772, \
                0.0874997924409, 0.0101845682113 ]

    # A table of sodium density factors. m0h1, m1h1, m2h1, m3h1, m0h0, m1h0, m2h0, m3h0
    NA_FACS = [0.343079175644, 0.0575250437508, 0.00321512825945, 5.98988373918e-05, \
                0.506380603793, 0.0849062503811, 0.00474548939393, 8.84099403236e-05]

    # Ohm.m
    Ra = 1.0

    # # # # # # # # # # # # # # # # SIMULATION CONTROLS # # # # # # # # # # # # # #

    # The simulation dt (seconds); for TetODE this is equivalent to EField dt
    SIM_DT = 5.0e-6

    # Sim end time (seconds)
    SIM_END = 0.1

    # The number of sim 'time points'; * SIM_DT = sim end time
    SIM_NTPNTS = int(SIM_END / SIM_DT) + 1

    # The current injection in amps
    Iinj = 0.1e-9

    # # # # # # # # # # # # # DATA COLLECTION # # # # # # # # # # # # # # # # # #

    # record potential at the two extremes along (z) axis
    POT_POS = np.array([0.0, 1.0e-03])

    POT_N = len(POT_POS)

    # Length of the mesh, in m
    LENGTH = 1000.0e-6

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

    mdl = smodel.Model()
    ssys = smodel.Surfsys('ssys', mdl)

    # K channel
    K = smodel.Chan('K', mdl)
    K_n0 = smodel.ChanState('K_n0', mdl, K)
    K_n1 = smodel.ChanState('K_n1', mdl, K)
    K_n2 = smodel.ChanState('K_n2', mdl, K)
    K_n3 = smodel.ChanState('K_n3', mdl, K)
    K_n4 = smodel.ChanState('K_n4', mdl, K)

    # Na channel
    Na = smodel.Chan('Na', mdl)
    Na_m0h1 = smodel.ChanState('Na_m0h1', mdl, Na)
    Na_m1h1 = smodel.ChanState('Na_m1h1', mdl, Na)
    Na_m2h1 = smodel.ChanState('Na_m2h1', mdl, Na)
    Na_m3h1 = smodel.ChanState('Na_m3h1', mdl, Na)
    Na_m0h0 = smodel.ChanState('Na_m0h0', mdl, Na)
    Na_m1h0 = smodel.ChanState('Na_m1h0', mdl, Na)
    Na_m2h0 = smodel.ChanState('Na_m2h0', mdl, Na)
    Na_m3h0 = smodel.ChanState('Na_m3h0', mdl, Na)

    # Leak
    L = smodel.Chan('L', mdl)
    Leak = smodel.ChanState('Leak', mdl, L)

    # Gating kinetics
    _a_m = lambda mV: ((((0.1 * (25 - (mV + 65.)) / (np.exp(
        (25 - (mV + 65.)) / 10.) - 1)))))
    _b_m = lambda mV: ((((4. * np.exp(-((mV + 65.) / 18.))))))
    _a_h = lambda mV: ((((0.07 * np.exp((-(mV + 65.) / 20.))))))
    _b_h = lambda mV: ((((1. / (np.exp((30 - (mV + 65.)) / 10.) + 1)))))
    _a_n = lambda mV: ((((0.01 * (10 - (mV + 65.)) / (np.exp(
        (10 - (mV + 65.)) / 10.) - 1)))))
    _b_n = lambda mV: ((((0.125 * np.exp(-(mV + 65.) / 80.)))))

    Kn0n1 = smodel.VDepSReac('Kn0n1',
                             ssys,
                             slhs=[K_n0],
                             srhs=[K_n1],
                             k=lambda V: 1.0e3 * 4. * _a_n(V * 1.0e3))
    Kn1n2 = smodel.VDepSReac('Kn1n2',
                             ssys,
                             slhs=[K_n1],
                             srhs=[K_n2],
                             k=lambda V: 1.0e3 * 3. * _a_n(V * 1.0e3))
    Kn2n3 = smodel.VDepSReac('Kn2n3',
                             ssys,
                             slhs=[K_n2],
                             srhs=[K_n3],
                             k=lambda V: 1.0e3 * 2. * _a_n(V * 1.0e3))
    Kn3n4 = smodel.VDepSReac('Kn3n4',
                             ssys,
                             slhs=[K_n3],
                             srhs=[K_n4],
                             k=lambda V: 1.0e3 * 1. * _a_n(V * 1.0e3))

    Kn4n3 = smodel.VDepSReac('Kn4n3',
                             ssys,
                             slhs=[K_n4],
                             srhs=[K_n3],
                             k=lambda V: 1.0e3 * 4. * _b_n(V * 1.0e3))
    Kn3n2 = smodel.VDepSReac('Kn3n2',
                             ssys,
                             slhs=[K_n3],
                             srhs=[K_n2],
                             k=lambda V: 1.0e3 * 3. * _b_n(V * 1.0e3))
    Kn2n1 = smodel.VDepSReac('Kn2n1',
                             ssys,
                             slhs=[K_n2],
                             srhs=[K_n1],
                             k=lambda V: 1.0e3 * 2. * _b_n(V * 1.0e3))
    Kn1n0 = smodel.VDepSReac('Kn1n0',
                             ssys,
                             slhs=[K_n1],
                             srhs=[K_n0],
                             k=lambda V: 1.0e3 * 1. * _b_n(V * 1.0e3))

    Na_m0h1_m1h1 = smodel.VDepSReac('Na_m0h1_m1h1',
                                    ssys,
                                    slhs=[Na_m0h1],
                                    srhs=[Na_m1h1],
                                    k=lambda V: 1.0e3 * 3. * _a_m(V * 1.0e3))
    Na_m1h1_m2h1 = smodel.VDepSReac('Na_m1h1_m2h1',
                                    ssys,
                                    slhs=[Na_m1h1],
                                    srhs=[Na_m2h1],
                                    k=lambda V: 1.0e3 * 2. * _a_m(V * 1.0e3))
    Na_m2h1_m3h1 = smodel.VDepSReac('Na_m2h1_m3h1',
                                    ssys,
                                    slhs=[Na_m2h1],
                                    srhs=[Na_m3h1],
                                    k=lambda V: 1.0e3 * 1. * _a_m(V * 1.0e3))

    Na_m3h1_m2h1 = smodel.VDepSReac('Na_m3h1_m2h1',
                                    ssys,
                                    slhs=[Na_m3h1],
                                    srhs=[Na_m2h1],
                                    k=lambda V: 1.0e3 * 3. * _b_m(V * 1.0e3))
    Na_m2h1_m1h1 = smodel.VDepSReac('Na_m2h1_m1h1',
                                    ssys,
                                    slhs=[Na_m2h1],
                                    srhs=[Na_m1h1],
                                    k=lambda V: 1.0e3 * 2. * _b_m(V * 1.0e3))
    Na_m1h1_m0h1 = smodel.VDepSReac('Na_m1h1_m0h1',
                                    ssys,
                                    slhs=[Na_m1h1],
                                    srhs=[Na_m0h1],
                                    k=lambda V: 1.0e3 * 1. * _b_m(V * 1.0e3))

    Na_m0h0_m1h0 = smodel.VDepSReac('Na_m0h0_m1h0',
                                    ssys,
                                    slhs=[Na_m0h0],
                                    srhs=[Na_m1h0],
                                    k=lambda V: 1.0e3 * 3. * _a_m(V * 1.0e3))
    Na_m1h0_m2h0 = smodel.VDepSReac('Na_m1h0_m2h0',
                                    ssys,
                                    slhs=[Na_m1h0],
                                    srhs=[Na_m2h0],
                                    k=lambda V: 1.0e3 * 2. * _a_m(V * 1.0e3))
    Na_m2h0_m3h0 = smodel.VDepSReac('Na_m2h0_m3h0',
                                    ssys,
                                    slhs=[Na_m2h0],
                                    srhs=[Na_m3h0],
                                    k=lambda V: 1.0e3 * 1. * _a_m(V * 1.0e3))

    Na_m3h0_m2h0 = smodel.VDepSReac('Na_m3h0_m2h0',
                                    ssys,
                                    slhs=[Na_m3h0],
                                    srhs=[Na_m2h0],
                                    k=lambda V: 1.0e3 * 3. * _b_m(V * 1.0e3))
    Na_m2h0_m1h0 = smodel.VDepSReac('Na_m2h0_m1h0',
                                    ssys,
                                    slhs=[Na_m2h0],
                                    srhs=[Na_m1h0],
                                    k=lambda V: 1.0e3 * 2. * _b_m(V * 1.0e3))
    Na_m1h0_m0h0 = smodel.VDepSReac('Na_m1h0_m0h0',
                                    ssys,
                                    slhs=[Na_m1h0],
                                    srhs=[Na_m0h0],
                                    k=lambda V: 1.0e3 * 1. * _b_m(V * 1.0e3))

    Na_m0h1_m0h0 = smodel.VDepSReac('Na_m0h1_m0h0',
                                    ssys,
                                    slhs=[Na_m0h1],
                                    srhs=[Na_m0h0],
                                    k=lambda V: 1.0e3 * _a_h(V * 1.0e3))
    Na_m1h1_m1h0 = smodel.VDepSReac('Na_m1h1_m1h0',
                                    ssys,
                                    slhs=[Na_m1h1],
                                    srhs=[Na_m1h0],
                                    k=lambda V: 1.0e3 * _a_h(V * 1.0e3))
    Na_m2h1_m2h0 = smodel.VDepSReac('Na_m2h1_m2h0',
                                    ssys,
                                    slhs=[Na_m2h1],
                                    srhs=[Na_m2h0],
                                    k=lambda V: 1.0e3 * _a_h(V * 1.0e3))
    Na_m3h1_m3h0 = smodel.VDepSReac('Na_m3h1_m3h0',
                                    ssys,
                                    slhs=[Na_m3h1],
                                    srhs=[Na_m3h0],
                                    k=lambda V: 1.0e3 * _a_h(V * 1.0e3))

    Na_m0h0_m0h1 = smodel.VDepSReac('Na_m0h0_m0h1',
                                    ssys,
                                    slhs=[Na_m0h0],
                                    srhs=[Na_m0h1],
                                    k=lambda V: 1.0e3 * _b_h(V * 1.0e3))
    Na_m1h0_m1h1 = smodel.VDepSReac('Na_m1h0_m1h1',
                                    ssys,
                                    slhs=[Na_m1h0],
                                    srhs=[Na_m1h1],
                                    k=lambda V: 1.0e3 * _b_h(V * 1.0e3))
    Na_m2h0_m2h1 = smodel.VDepSReac('Na_m2h0_m2h1',
                                    ssys,
                                    slhs=[Na_m2h0],
                                    srhs=[Na_m2h1],
                                    k=lambda V: 1.0e3 * _b_h(V * 1.0e3))
    Na_m3h0_m3h1 = smodel.VDepSReac('Na_m3h0_m3h1',
                                    ssys,
                                    slhs=[Na_m3h0],
                                    srhs=[Na_m3h1],
                                    k=lambda V: 1.0e3 * _b_h(V * 1.0e3))

    OC_K = smodel.OhmicCurr('OC_K',
                            ssys,
                            chanstate=K_n4,
                            erev=K_rev,
                            g=K_G / K_ro)
    OC_Na = smodel.OhmicCurr('OC_Na',
                             ssys,
                             chanstate=Na_m3h0,
                             erev=Na_rev,
                             g=Na_G / Na_ro)

    # Mesh geometry
    mesh = meshio.loadMesh('validation_efield/meshes/' + meshfile)[0]

    cyto = sgeom.TmComp('cyto', mesh, range(mesh.ntets))

    # The tetrahedrons from which to record potential
    POT_TET = np.zeros(POT_N, dtype='uint')

    i = 0
    for p in POT_POS:
        # Assuming axiz aligned with z-axis
        POT_TET[i] = mesh.findTetByPoint([0.0, 0.0, POT_POS[i]])
        i = i + 1

    # 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(mesh.ntets):
        tettemp = mesh.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__())

    # Find the tets on the z=0 and z=1000um boundaries, and the triangles
    minztets = []
    minztris = []
    maxztris = []
    minzverts = set([])

    boundminz = mesh.getBoundMin()[2] + LENGTH / mesh.ntets
    boundmaxz = mesh.getBoundMax()[2] - LENGTH / mesh.ntets

    for i in range(boundtets.__len__()):
        # get the boundary triangle
        for btriidx in bt_srftriidx[i]:
            zminboundtri = True
            tribidx = mesh.getTetTriNeighb(boundtets[i])[btriidx]
            tritemp = mesh.getTri(tribidx)
            trizs = [0.0, 0.0, 0.0]
            trizs[0] = mesh.getVertex(tritemp[0])[2]
            trizs[1] = mesh.getVertex(tritemp[1])[2]
            trizs[2] = mesh.getVertex(tritemp[2])[2]
            for j in range(3):
                if (trizs[j] > boundminz): zminboundtri = False
            if (zminboundtri):
                minztets.append(boundtets[i])
                minztris.append(tribidx)
                minzverts.add(tritemp[0])
                minzverts.add(tritemp[1])
                minzverts.add(tritemp[2])
                continue

            zmaxboundtri = True
            for j in range(3):
                if (trizs[j] < boundmaxz): zmaxboundtri = False
            if (zmaxboundtri):
                maxztris.append(tribidx)

    n_minztris = len(minztris)
    assert (n_minztris > 0)
    minzverts = list(minzverts)
    n_minzverts = len(minzverts)
    assert (n_minzverts > 0)

    memb_tris = list(mesh.getSurfTris())

    # Doing this now, so will inject into first little z section
    for t in minztris:
        memb_tris.remove(t)
    for t in maxztris:
        memb_tris.remove(t)

    # Create the membrane with the tris removed at faces
    memb = sgeom.TmPatch('memb', mesh, memb_tris, cyto)
    memb.addSurfsys('ssys')

    membrane = sgeom.Memb('membrane',
                          mesh, [memb],
                          opt_method=2,
                          search_percent=100.0)

    # Set the single-channel conductance:
    g_leak_sc = L_G_tot / len(memb_tris)
    OC_L = smodel.OhmicCurr('OC_L',
                            ssys,
                            chanstate=Leak,
                            erev=leak_rev,
                            g=g_leak_sc)

    # Create the solver objects
    sim = ssolver.TetODE(mdl, mesh, calcMembPot=True)
    sim.setTolerances(1.0e-6, 1e-6)

    surfarea_mesh = sim.getPatchArea('memb')
    surfarea_cyl = 1.0 * np.pi * 1000 * 1e-12
    corr_fac_area = surfarea_mesh / surfarea_cyl

    vol_cyl = np.pi * 0.5 * 0.5 * 1000 * 1e-18
    vol_mesh = sim.getCompVol('cyto')
    corr_fac_vol = vol_mesh / vol_cyl

    RES_POT = np.zeros((SIM_NTPNTS, POT_N))

    for t in memb_tris:
        sim.setTriCount(t, 'Leak', 1)

    sim.setPatchCount('memb', 'Na_m0h1', (Na_ro * surfarea_cyl * NA_FACS[0]))
    sim.setPatchCount('memb', 'Na_m1h1', (Na_ro * surfarea_cyl * NA_FACS[1]))
    sim.setPatchCount('memb', 'Na_m2h1', (Na_ro * surfarea_cyl * NA_FACS[2]))
    sim.setPatchCount('memb', 'Na_m3h1', (Na_ro * surfarea_cyl * NA_FACS[3]))
    sim.setPatchCount('memb', 'Na_m0h0', (Na_ro * surfarea_cyl * NA_FACS[4]))
    sim.setPatchCount('memb', 'Na_m1h0', (Na_ro * surfarea_cyl * NA_FACS[5]))
    sim.setPatchCount('memb', 'Na_m2h0', (Na_ro * surfarea_cyl * NA_FACS[6]))
    sim.setPatchCount('memb', 'Na_m3h0', (Na_ro * surfarea_cyl * NA_FACS[7]))
    sim.setPatchCount('memb', 'K_n0', (K_ro * surfarea_cyl * K_FACS[0]))
    sim.setPatchCount('memb', 'K_n1', (K_ro * surfarea_cyl * K_FACS[1]))
    sim.setPatchCount('memb', 'K_n2', (K_ro * surfarea_cyl * K_FACS[2]))
    sim.setPatchCount('memb', 'K_n3', (K_ro * surfarea_cyl * K_FACS[3]))
    sim.setPatchCount('memb', 'K_n4', (K_ro * surfarea_cyl * K_FACS[4]))

    sim.setMembPotential('membrane', -65e-3)
    sim.setMembVolRes('membrane', Ra * corr_fac_vol)
    sim.setMembCapac('membrane', 0.01 / corr_fac_area)

    for v in minzverts:
        sim.setVertIClamp(v, Iinj / n_minzverts)

    for l in range(SIM_NTPNTS):

        sim.run(SIM_DT * l)

        for p in range(POT_N):
            RES_POT[l, p] = sim.getTetV(int(POT_TET[p])) * 1.0e3

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

    # Benchmark
    # At 0um- the end of the mesh
    ifile_benchmark_x0 = open(
        'validation_efield/data/rallpack3_benchmark/rallpack3_0_0.001dt_1000seg',
        'r')

    # At 1000um- the end of the mesh
    ifile_benchmark_x1000 = open(
        'validation_efield/data/rallpack3_benchmark/rallpack3_1000_0.001dt_1000seg',
        'r')

    tpnt_benchmark = []
    v_benchmark_x0 = []
    v_benchmark_x1000 = []

    lines_benchmark_x0 = ifile_benchmark_x0.readlines()[2:]

    # Read in mv and ms
    for line_benchmark_x0 in lines_benchmark_x0:
        nums = line_benchmark_x0.split()
        tpnt_benchmark.append(float(nums[0]))
        v_benchmark_x0.append(float(nums[1]))

    lines_benchmark_x1000 = ifile_benchmark_x1000.readlines()[2:]

    for line_benchmark_x1000 in lines_benchmark_x1000:
        nums = line_benchmark_x1000.split()
        v_benchmark_x1000.append(float(nums[1]))

    # Get rid of the last point which seems to be missing from STEPS
    v_benchmark_x0 = v_benchmark_x0[:-1]
    tpnt_benchmark = tpnt_benchmark[:-1]
    v_benchmark_x1000 = v_benchmark_x1000[:-1]

    rms0 = stats(v_benchmark_x0, RES_POT[:, 0])
    assert (rms0 < 0.15)
    rms1000 = stats(v_benchmark_x1000, RES_POT[:, 1])
    assert (rms1000 < 1.1)
Example #24
0
def test_masteq_diff():
    "Reaction-diffusion - Production and second order degradation (Parallel TetOpSplit)"

    ### NOW   A+B-> B,  0->A (see Erban and Chapman, 2009)

    ########################################################################
    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_mpi/meshes/' + filename)[0]

    comp1 = sgeom.TmComp('comp1', geom, range(geom.ntets))
    comp1.addVolsys('vsys')

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

    tet_hosts = gd.binTetsByAxis(geom, steps.mpi.nhosts)
    sim = solvmod.TetOpSplit(mdl, geom, rng, False, tet_hosts)

    sim.reset()

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

    res = numpy.zeros([ntpnts])
    res_std1 = numpy.zeros([ntpnts])
    res_std2 = numpy.zeros([ntpnts])

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

    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 = 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

    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)) * math.pow(
            (k2 * v * v) / (B0 * k1), m) * math.exp(-((k2 * v * v) /
                                                      (k1 * B0)))
        assert tol_funcs.tolerable(steps_n_res[m], analy, tolerance)
Example #25
0
SIM_NTPNTS = int(SIM_END / SIM_DT) + 1

# # # # # # # # # # # # # DATA COLLECTION # # # # # # # # # # # # # # # # # #

# Length of the mesh, in m
LENGTH = 1000.0e-6

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

mdl = smodel.Model()
ssys = smodel.Surfsys('ssys', mdl)

L = smodel.Chan('L', mdl)
Leak = smodel.ChanState('Leak', mdl, L)

mesh = meshio.loadMesh('meshes/' + meshfile)[0]

cyto = sgeom.TmComp('cyto', mesh, range(mesh.ntets))

# 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(mesh.ntets):
    tettemp = mesh.getTetTetNeighb(i)
    if (tettemp[0] == -1 or tettemp[1] == -1 or tettemp[2] == -1
            or tettemp[3] == -1):
        boundtets.append(i)
        templist = []
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])
def gen_geom():
    mesh = smeshio.loadMesh('testMeshSphere')[0]

    # Total no. of Tetrahedron in the mesh
    ntets = mesh.countTets()

    tets_comp1 = []
    tets_comp2 = []

    tris_comp1 = set()
    tris_comp2 = set()

    # Crestion of a compartment object
    comp = stetmesh.TmComp('cyto',mesh, range(ntets))
    comp.addVolsys('cytosolv')

    # Central tetrahedron index
    ctetidx = mesh.findTetByPoint([0, 0, 0])
    tetidxs[0] = ctetidx

    # Central tetrahedron's four neighbours
    neighbidcs = mesh.getTetTetNeighb(ctetidx)
    tetidxs[1], tetidxs[2], tetidxs[3], tetidxs[4] = neighbidcs

    stored = 5

    max = mesh.getBoundMax()
    min = mesh.getBoundMin()

    while(stored<SAMPLE):
        rnx = random.random()
        rny = random.random()
        rnz = random.random()

        xcrd = min[0] + (max[0] - min[0]) * rnx
        ycrd = min[1] + (max[1] - min[1]) * rny
        zcrd = min[2] + (max[2] - min[2]) * rnz

        tidx = mesh.findTetByPoint([xcrd, ycrd, zcrd])

        if tidx == -1:
            continue

        if tidx not in tetidxs:
            tetidxs[stored] = tidx
            stored += 1

        cbaryc = mesh.getTetBarycenter(ctetidx)

        for i in range(SAMPLE):
            baryc  = mesh.getTetBarycenter(tetidxs[i])
            r = math.sqrt(math.pow((baryc[0]-cbaryc[0]),2)+math.pow((baryc[1]-cbaryc[1]),2)+math.pow((baryc[2]-cbaryc[2]),2))

            tetrads[i] = r*1.0e6

    R = tetrads.getBoundMax()
    print tetrads.getBoundMax()

    for j in range(ntets):
        baryc = mesh.getTetBarycenter(j)
        tris = mesh.getTetTriNeighb(j)

        r = math.sqrt(math.pow((baryc[0] - cbaryc[0]), 2) + math.pow((baryc[1] - cbaryc[1]), 2) + math.pow((baryc[2] - cbaryc[2]), 2))

        if r > 0.01*R:
            tets_comp1.append(j)
            tris_comp1.add(tris[0])
            tris_comp1.add(tris[1])
            tris_comp1.add(tris[2])
            tris_comp1.add(tris[3])

        else:
            tets_comp2.append(j)
            tris_comp2.add(tris[0])
            tris_comp2.add(tris[1])
            tris_comp2.add(tris[2])
            tris_comp2.add(tris[3])

    comp1 = stetmesh.TmComp('comp1', mesh, tets_comp1)
    comp2 = stetmesh.TmComp('comp2', mesh, tets_comp2)

    comp1.addVolsys('vsys1')
    comp2.addVolsys('vsys2')

    tris_DB = tris_comp1.intersection(tris_comp2)
    tris_DB = list(tris_DB)
    diffb = stetmesh.DiffBoundary('diffb', mesh, tris_DB)

    return mesh
def gen_geom():

    #n = 5
    #print n

    mesh = meshio.loadMesh('testMeshCylinder1')[0]

    ntets = mesh.countTets()

    tets_compA = []
    tets_compB = []
    tris_compA = set()
    tris_compB = set()

    z_max = mesh.getBoundMax()[2]
    z_min = mesh.getBoundMin()[2]
    x_max = mesh.getBoundMax()[0]
    x_min = mesh.getBoundMin()[0]
    y_max = mesh.getBoundMax()[1]
    y_min = mesh.getBoundMin()[1]

    print z_max
    print z_min
    print x_max
    print x_min
    print y_max
    print y_min

    z_mid = z_min + (z_max - z_min) / 2.0

    for t in range(ntets):

        barycz = mesh.getTetBarycenter(t)[2]

        tris = mesh.getTetTriNeighb(t)

        if (barycz < z_mid):
            tets_compA.append(t)
            tris_compA.add(tris[0])
            tris_compA.add(tris[1])
            tris_compA.add(tris[2])
            tris_compA.add(tris[3])
        else:
            tets_compB.append(t)
            tris_compB.add(tris[0])
            tris_compB.add(tris[1])
            tris_compB.add(tris[2])
            tris_compB.add(tris[3])

    compA = sgeom.TmComp('compA', mesh, tets_compA)
    compB = sgeom.TmComp('compB', mesh, tets_compB)

    compA.addVolsys('vsysA')
    compB.addVolsys('vsysB')

    tris_DB = tris_compA.intersection(tris_compB)
    tris_DB = list(tris_DB)

    diffusion_boundary = sgeom.DiffBoundary('diffusion_boundary', mesh, tris_DB)

    return mesh, tets_compA, tets_compB
def coarse_gen(cd,bdim,bmin,file_name):
	# INPUT: voxel cube side length (fl), box dimensions (fl), box minimum values (fl), name of file to create for mesh output (str)
	# This function generates a coarse mesh given info from NEURON sections.
	# Returns this mesh as a STEPS tuple, of which entry 0 is a steps.geom.Tetmesh object,
	# also saves STEPS format files for the Tetmesh to current directory under given file name (xml & ASCII file formats).

	## CALCULATE BOX INFO ##
	box_w = bdim[0]
	box_l = bdim[1]
	box_h = bdim[2]

	min_x = bmin[0]
	min_y = bmin[1]
	min_z = bmin[2]

	cl = cd

	if not (box_w % cl == box_l % cl == box_h % cl == 0):
		print 'ERRROR: voxel cube side length not a common factor of all box dimensions'
		sys.exit()
	
	wpoints = 1+(box_w)/cl
	lpoints = 1+(box_l)/cl 
	hpoints = 1+(box_h)/cl

	print "cube side length: ", cl
	print "box w,l,h: ", box_w,box_l,box_h
	print "w,l,h # points: ", wpoints,lpoints,hpoints

	cpoints = []
	hfacets = []
	vfacets = []

	## GENERATE POINTS AND FACETS ##
	for hp in range(int(hpoints)):
		for lp in range(int(lpoints)):
			for wp in range(int(wpoints)):
				cpoints.append((min_x+wp*cl,min_y+lp*cl,min_z+hp*cl))
				pindex = (hp*lpoints*wpoints)+(lp*wpoints)+wp
				# horizontal facets
				if (wp < int(wpoints)-1 and lp < int(lpoints)-1):
					hfacets.append([int(pindex), int(pindex+1), int(pindex+1+wpoints), int(pindex+wpoints)])
				# vertical facets
				if (hp > 0):
					if (wp > 0):
						vfacets.append([int(pindex),int(pindex-1),int(pindex-1-lpoints*wpoints),int(pindex-lpoints*wpoints)])
					if (lp > 0):
						vfacets.append([int(pindex),int(pindex-wpoints),int(pindex-wpoints-lpoints*wpoints),int(pindex-lpoints*wpoints)])
	all_facets = hfacets+vfacets

	## PASS MESH TO STEPS ##
	mesh_info = MeshInfo()
	mesh_info.set_points(cpoints)
	mesh_info.set_facets(all_facets)
	m = build(mesh_info)

	# write mesh proxies
	nodeproxy = smeshio.ElementProxy('node',3)
	for i, p in enumerate(m.points):
	    nodeproxy.insert(i,p)

	tetproxy = smeshio.ElementProxy('tet',4)
	newtet = [0,0,0,0]
	for i, t in enumerate(m.elements):
	    newtet[0] = nodeproxy.getSTEPSID(int(t[0]))
	    newtet[1] = nodeproxy.getSTEPSID(int(t[1]))
	    newtet[2] = nodeproxy.getSTEPSID(int(t[2]))
	    newtet[3] = nodeproxy.getSTEPSID(int(t[3]))
	    tetproxy.insert(i, newtet)
	 
	# build mesh from proxies and save in STEPS format (xml & ASCII)
	nodedata = nodeproxy.getAllData()
	tetdata = tetproxy.getAllData()
	newmesh = steps.geom.Tetmesh(nodedata, tetdata)
	smeshio.saveMesh(file_name,newmesh)

	# Load mesh into STEPS
	steps_mesh = smeshio.loadMesh(file_name)
	print "STEPS loaded Tetmesh successfully."
	print "# Vertices: ", steps_mesh[0].countVertices()
	print "# Tets: ", steps_mesh[0].countTets()
	print "# Faces/Tris: ", steps_mesh[0].countTris()
	return steps_mesh
Example #30
0
def gen_geom():

    print "Loading mesh..."
    mesh = smeshio.loadMesh('meshes/sphere_rad10_11Ktets')[0]
    print "Mesh Loaded"

    # Find the total number of tetrahedrons in the mesh
    ntets = mesh.countTets()
    # Create a compartment containing all tetrahedron
    comp = stetmesh.TmComp('cyto', mesh, range(ntets))
    comp.addVolsys('cytosolv')

    print "Finding tetrahedron samples..."
    # Fetch the central tetrahedron index and store:
    ctetidx = mesh.findTetByPoint([0.0, 0.0, 0.0])
    tetidxs[0] = ctetidx

    # Find the central tetrahedron's four neighbours:
    neighbidcs = mesh.getTetTetNeighb(ctetidx)
    tetidxs[1], tetidxs[2], tetidxs[3], tetidxs[4] = neighbidcs

    # Keep track how many tet indices we have stored so far
    stored = 5

    # Find the maximum and minimum coordinates of the mesh
    max = mesh.getBoundMax()
    min = mesh.getBoundMin()

    # Run a loop until we have stored all tet indices we require
    while (stored < SAMPLE):

        # Fetch 3 random numbers between 0 and 1
        rnx = random.random()
        rny = random.random()
        rnz = random.random()

        # Find the coordinates in the mesh that these numbers relate to
        xcrd = min[0] + (max[0] - min[0]) * rnx
        ycrd = min[1] + (max[1] - min[1]) * rny
        zcrd = min[2] + (max[2] - min[2]) * rnz

        # Find the tetrahedron that encompasses this point.
        tidx = mesh.findTetByPoint([xcrd, ycrd, zcrd])

        # -1 was returned if point is outside the mesh:
        if (tidx == -1): continue
        if (tidx not in tetidxs):
            tetidxs[stored] = tidx
            stored += 1

    # Find the barycenter of the central tetrahedron
    cbaryc = mesh.getTetBarycenter(ctetidx)

    for i in range(SAMPLE):
        # Fetch the barycenter of the tetrahedron:
        baryc = mesh.getTetBarycenter(int(tetidxs[i]))

        # Find the radial distance of this tetrahedron to mesh center:
        r = math.sqrt(math.pow((baryc[0]-cbaryc[0]),2) + \
                      math.pow((baryc[1]-cbaryc[1]),2) + \
                      math.pow((baryc[2]-cbaryc[2]),2))

        # Store the radial distance (in microns):
        tetrads[i] = r * 1.0e6

    print "Tetrahedron samples found"

    return mesh
Example #31
0
OC_Na = smodel.OhmicCurr('OC_Na', ssys, chanstate=Na_m3h1, g=Na_G, erev=Na_rev)

# Leak channel
L = smodel.Chan('L', mdl)
Leak = smodel.ChanState('Leak', mdl, L)

OC_L = smodel.OhmicCurr('OC_L', ssys, chanstate=Leak, g=L_G, erev=leak_rev)

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

########### MESH & COMPARTMENTALIZATION #################

##########Import Mesh

mesh = meshio.loadMesh('./meshes/' + meshfile_ab)[0]

outer_tets = range(mesh.ntets)

###USE OF gettets
#getcyl(tetmesh, rad,  zmin, zmax, binnum=120, x = 0.0, y = 0.0):
inner_tets = gettets.getcyl(mesh, 1e-6, -200e-6, 200e-6)[0]

for i in inner_tets:
    outer_tets.remove(i)
assert (outer_tets.__len__() + inner_tets.__len__() == mesh.ntets)

print outer_tets.__len__(), " tets in outer compartment"
print inner_tets.__len__(), " tets in inner compartment"

# Record voltage from the central tetrahedron