Example #1
0
    def __init__(self, model_name="cylinder_demo3d"):
        pyurdme.URDMEModel.__init__(self, model_name)

        # System constants
        D_const = 0.1

        # Define Species
        A = pyurdme.Species(name="A", diffusion_constant=D_const)
        B = pyurdme.Species(name="B", diffusion_constant=D_const)
        self.add_species([A, B])

        # Define Geometry
        pt1 = dolfin.Point(MAX_X_DIM, 0, 0)
        pt2 = dolfin.Point(MIN_X_DIM, 0, 0)
        cylinder = mshr.Cylinder(pt1, pt2, 1.0, 1.0)
        self.mesh = pyurdme.URDMEMesh(mesh=mshr.generate_mesh(cylinder, 32))

        # Define Subdomains
        self.add_subdomain(Edge1(), 2)
        self.add_subdomain(Edge2(), 3)

        data = self.get_solver_datastructure()
        vol = data['vol']
        sd = data['sd']
        left = numpy.sum(vol[sd == 2])
        right = numpy.sum(vol[sd == 3])

        k_react = pyurdme.Parameter(name="k_react", expression=1.0)

        k_creat1 = pyurdme.Parameter(name="k_creat1", expression=100 / right)
        k_creat2 = pyurdme.Parameter(name="k_creat2", expression=100 / left)

        self.add_parameter([k_react, k_creat1, k_creat2])

        # Define Reactions
        R1 = pyurdme.Reaction(name="R1",
                              reactants=None,
                              products={A: 1},
                              rate=k_creat1,
                              restrict_to=2)
        R2 = pyurdme.Reaction(name="R2",
                              reactants=None,
                              products={B: 1},
                              rate=k_creat2,
                              restrict_to=3)
        R3 = pyurdme.Reaction(name="R3",
                              reactants={
                                  A: 1,
                                  B: 1
                              },
                              products=None,
                              rate=k_react)
        self.add_reaction([R1, R2, R3])

        # Define simulation timespan
        self.timespan(range(200))
Example #2
0
 def __init__(self):
     pyurdme.URDMEModel.__init__(self,"test1D")
     X = pyurdme.Species(name="X",  diffusion_constant=0.001)
     self.add_species([X])
     self.mesh = pyurdme.URDMEMesh.generate_unit_interval_mesh(nx=100, periodic=True)
     self.set_initial_condition_place_near({X:1000}, 0.1)
     self.timespan(range(10))
def _translate_species(model, initial_dist, dif0=None, y0=None):
    # Error check
    
   
    if y0 and len(y0) != len(model.species):
        raise Exception("len(dif0) and len(y0) must equal len(model.species)")            
    species_list = len(model.species) * [None]
    for i,sp in enumerate(model.species):
        val = 0.
        if dif0:
            val=dif0[i]
        else:
            for id in model.diffusivities:
                if str(id[0]) == str(sp):
                    val=id[1]
        species_list[i] = pyurdme.Species(name="__s%d" % i, diffusion_constant=val)

    distribution_list = len(initial_dist.keys()) * [None]
    for i,sp in enumerate(model.species):
        if str(sp) in initial_dist.keys():
            val = 0.
            if y0:
                val=y0[i]
            else:
                for ic in model.initial_conditions:
                    if str(ic[0]) == str(sp):
                        val=np.round(ic[1].value)
            distribution_list[i] = [initial_dist[str(sp)],{'__s%d'%i:val}]
        else: pass

    return species_list, distribution_list
Example #4
0
    def __init__(self):
        pyurdme.URDMEModel.__init__(self, name="simple_diffusion2")

        A = pyurdme.Species(name="A", diffusion_constant=0.1, dimension=2)
        B = pyurdme.Species(name="B", diffusion_constant=0.1, dimension=1)

        self.add_species([A, B])

        # Import a circle mesh
        self.mesh = pyurdme.URDMEMesh.read_dolfin_mesh("circle.xml")

        # A mesh function for the cells
        cell_function = dolfin.CellFunction("size_t", self.mesh)
        cell_function.set_all(1)

        # Create a mesh function over then edges of the mesh
        facet_function = dolfin.FacetFunction("size_t", self.mesh)
        facet_function.set_all(0)

        # Mark the boundary points
        membrane = Membrane()
        membrane.mark(facet_function, 2)

        membrane_patch = MembranePatch()
        membrane_patch.mark(facet_function, 3)

        self.add_subdomain(cell_function)
        self.add_subdomain(facet_function)

        k1 = pyurdme.Parameter(name="k1", expression=100.0)
        self.add_parameter([k1])

        R1 = pyurdme.Reaction(name="R1",
                              reactants={A: 1},
                              products={B: 1},
                              massaction=True,
                              rate=k1,
                              restrict_to=3)
        self.add_reaction([R1])

        # Restrict species B to the membrane subdomain
        self.restrict(species=B, subdomains=[2, 3])
        self.timespan(numpy.linspace(0, 1, 50))

        # Place the A molecules in the voxel nearest to the center of the square
        self.set_initial_condition_place_near({A: 10000}, point=[0, 0])
Example #5
0
 def __init__(self, diffusion_constant=0.01):
     pyurdme.URDMEModel.__init__(self,name="simple_diffusion")
     A = pyurdme.Species(name="A",diffusion_constant=diffusion_constant,dimension=2)
     self.add_species([A])
     # A unit square
     self.mesh = pyurdme.URDMEMesh.generate_unit_square_mesh(10,10)
     # Place the A molecules in the voxel nearest the center of the square
     #self.set_initial_condition_place_near({A:10000},point=[0.5,0.5])
     self.set_initial_condition_scatter({A:10000})
     self.timespan(numpy.linspace(0,5,200))
Example #6
0
    def construct_pyurdme_model(self, data):
        '''
        '''
        json_model_refs = ModelManager.getModel(
            self, int(data["id"])
        )  # data["id"] is the model id of the selected model I think

        stochkit_model_obj = StochKitModelWrapper.get_by_id(int(
            data["id"])).createStochKitModel()
        #print 'json_model_refs["spatial"]["mesh_wrapper_id"]:', json_model_refs["spatial"]["mesh_wrapper_id"]
        try:
            meshWrapperDb = mesheditor.MeshWrapper.get_by_id(
                json_model_refs["spatial"]["mesh_wrapper_id"])
        except Exception as e:
            raise Exception(
                "No Mesh file set. Choose one in the Mesh tab of the Model Editor"
            )

        try:
            meshFileObj = fileserver.FileManager.getFile(
                self, meshWrapperDb.meshFileId)
            mesh_filename = meshFileObj["storePath"]
        except IOError as e:
            #blowup here, need a mesh
            #self.response.write(json.dumps({"status" : False,
            #                                "msg" : "No Mesh file given"}))
            #return
            raise Exception("Mesh file inaccessible. Try another mesh")
            #TODO: if we get advanced options, we don't need a mesh

        reaction_subdomain_assigments = json_model_refs["spatial"][
            "reactions_subdomain_assignments"]  #e.g. {'R1':[1,2,3]}
        species_subdomain_assigments = json_model_refs["spatial"][
            "species_subdomain_assignments"]  #e.g. {'S1':[1,2,3]}
        species_diffusion_coefficients = json_model_refs["spatial"][
            "species_diffusion_coefficients"]  #e.g. {'S1':0.5}
        initial_conditions = json_model_refs["spatial"][
            "initial_conditions"]  #e.g.  { ic0 : { type : "place", species : "S0",  x : 5.0, y : 10.0, z : 1.0, count : 5000 }, ic1 : { type : "scatter",species : "S0", subdomain : 1, count : 100 }, ic2 : { type : "distribute",species : "S0", subdomain : 2, count : 100 } }

        for species in stochkit_model_obj.listOfSpecies:
            if species not in species_diffusion_coefficients:
                raise Exception(
                    "Species '{0}' does not have a diffusion coefficient set. Please do that in the Species tab of the Model Editor"
                    .format(species))

        simulation_end_time = data['time']
        simulation_time_increment = data['increment']
        simulation_algorithm = data[
            'algorithm']  # Don't trust this! I haven't implemented the algorithm selection for this yet
        simulation_exec_type = data[
            'execType']  # This should contain 'spatial' -- Not that you really need it, only spatial requests will be routed here
        simulation_realizations = data['realizations']
        simulation_seed = data[
            'seed']  # If this is set to -1, it means choose a seed at random! (Whatever that means)

        #### Construct the PyURDME object from the Stockkit model and mesh and other inputs
        try:
            # model
            pymodel = pyurdme.URDMEModel(name=stochkit_model_obj.name)
            # mesh
            pymodel.mesh = pyurdme.URDMEMesh.read_dolfin_mesh(
                str(mesh_filename))
            # timespan
            pymodel.timespan(
                numpy.arange(0,
                             simulation_end_time + simulation_time_increment,
                             simulation_time_increment))
            # subdomains
            if len(meshWrapperDb.subdomains) > 0:
                pymodel.set_subdomain_vector(
                    numpy.array(meshWrapperDb.subdomains))

            # species
            for s in stochkit_model_obj.listOfSpecies:
                pymodel.add_species(
                    pyurdme.Species(name=s,
                                    diffusion_constant=float(
                                        species_diffusion_coefficients[s])))
            # species subdomain restriction
            for s, sd_list in species_subdomain_assigments.iteritems():
                spec = pymodel.listOfSpecies[s]
                pymodel.restrict(spec, sd_list)
            # parameters
            for p_name, p in stochkit_model_obj.listOfParameters.iteritems():
                pymodel.add_parameter(
                    pyurdme.Parameter(name=p_name, expression=p.expression))
            # reactions
            for r_name, r in stochkit_model_obj.listOfReactions.iteritems():
                if r.massaction:
                    pymodel.add_reaction(
                        pyurdme.Reaction(name=r_name,
                                         reactants=r.reactants,
                                         products=r.products,
                                         rate=r.marate,
                                         massaction=True))
                else:
                    pymodel.add_reaction(
                        pyurdme.Reaction(
                            name=r_name,
                            reactants=r.reactants,
                            products=r.products,
                            propensity_function=r.propensity_function))
            # reaction subdomain restrictions
            for r in reaction_subdomain_assigments:
                pymodel.listOfReactions[
                    r].restrict_to = reaction_subdomain_assigments[r]
            # Initial Conditions
            # initial_conditions = json_model_refs["spatial"]["initial_conditions"] #e.g.  { ic0 : { type : "place", species : "S0",  x : 5.0, y : 10.0, z : 1.0, count : 5000 }, ic1 : { type : "scatter",species : "S0", subdomain : 1, count : 100 }, ic2 : { type : "distribute",species : "S0", subdomain : 2, count : 100 } }
            for ic in initial_conditions:
                spec = pymodel.listOfSpecies[ic['species']]
                if ic['type'] == "place":
                    pymodel.set_initial_condition_place_near(
                        {spec: int(ic['count'])},
                        point=[float(ic['x']),
                               float(ic['y']),
                               float(ic['z'])])
                elif ic['type'] == "scatter":
                    pymodel.set_initial_condition_scatter(
                        {spec: int(ic['count'])},
                        subdomains=[int(ic['subdomain'])])
                elif ic['type'] == "distribute":
                    pymodel.set_initial_condition_distribute_uniformly(
                        {spec: int(ic['count'])},
                        subdomains=[int(ic['subdomain'])])
                else:
                    #self.response.write(json.dumps({"status" : False,
                    #                                "msg" : "Unknown initial condition type {0}".format(ic['type'])}))
                    #return
                    raise Exception(
                        "Unknown initial condition type {0}".format(
                            ic['type']))
        except Exception as e:
            raise Exception("Error while assembling the model: {0}".format(e))

        return pymodel
Example #7
0
        def __init__(self, **kwargs):
            modelType = self.json_data["modelType"]
            species = self.json_data["species"]
            parameters = self.json_data["parameters"]
            reactions = self.json_data["reactions"]
            maxTime = self.json_data["maxTime"]
            if maxTime is None:
                maxTime = 100
            increment = self.json_data["increment"]
            if increment is None:
                increment = 1
            reaction_subdomain_assignments = self.json_data[
                "reaction_subdomain_assignments"]  # e.g. {'R1':[1,2,3]}
            species_subdomain_assignments = self.json_data[
                "species_subdomain_assignments"]  # e.g. {'S1':[1,2,3]}
            species_diffusion_coefficients = self.json_data[
                "species_diffusion_coefficients"]  # e.g. {'S1':0.5}
            initial_conditions = self.json_data[
                "initial_conditions"]  # e.g.  { ic0 : { type : "place", species : "S0",  x : 5.0, y : 10.0, z : 1.0, count : 5000 }, ic1 : { type : "scatter",species : "S0", subdomain : 1, count : 100 }, ic2 : { type : "distribute",species : "S0", subdomain : 2, count : 100 } }

            pyurdme.URDMEModel.__init__(self, name=self.json_data["name"])
            mesh_file = tempfile.NamedTemporaryFile(suffix='.xml')
            mesh_file.write(self.json_data["mesh"])
            mesh_file.seek(0)
            self.mesh = pyurdme.URDMEMesh.read_dolfin_mesh(str(mesh_file.name))
            self.set_subdomain_vector(numpy.array(
                self.json_data["subdomains"]))

            parameterByName = dict()

            for parameter in parameters:
                if parameter['name'] in kwargs:
                    parameterByName[parameter['name']] = pyurdme.Parameter(
                        name=parameter['name'],
                        expression=kwargs[parameter['name']])
                else:
                    parameterByName[parameter['name']] = pyurdme.Parameter(
                        name=parameter['name'], expression=parameter['value'])

                self.add_parameter(parameterByName[parameter['name']])

            speciesByName = dict()

            for specie in species:
                speciesByName[specie['name']] = pyurdme.Species(
                    name=specie['name'],
                    diffusion_constant=float(
                        species_diffusion_coefficients[specie['name']]))
                self.add_species(speciesByName[specie['name']])
            for s, sd_list in species_subdomain_assignments.iteritems():
                spec = self.listOfSpecies[s]
                self.restrict(spec, sd_list)

            for reaction in reactions:
                inReactants = dict()
                for reactant in reaction['reactants']:
                    if reactant['specie'] not in inReactants:
                        inReactants[reactant['specie']] = 0

                    inReactants[
                        reactant['specie']] += reactant['stoichiometry']

                inProducts = dict()
                for product in reaction['products']:
                    if product['specie'] not in inProducts:
                        inProducts[product['specie']] = 0

                    inProducts[product['specie']] += product['stoichiometry']

                reactants = dict([(speciesByName[reactant[0]], reactant[1])
                                  for reactant in inReactants.items()])

                products = dict([(speciesByName[product[0]], product[1])
                                 for product in inProducts.items()])

                if (reaction['type'] == 'custom'):
                    self.add_reaction(
                        pyurdme.Reaction(
                            name=reaction['name'],
                            reactants=reactants,
                            products=products,
                            propensity_function=reaction['equation']))
                else:
                    self.add_reaction(
                        pyurdme.Reaction(
                            name=reaction['name'],
                            reactants=reactants,
                            products=products,
                            rate=parameterByName[reaction['rate']]))
            for r in reaction_subdomain_assignments:
                self.listOfReactions[
                    r].restrict_to = reaction_subdomain_assignments[r]

            for ic in initial_conditions:
                spec = self.listOfSpecies[ic['species']]
                if ic['type'] == "place":
                    self.set_initial_condition_place_near(
                        {spec: int(ic['count'])},
                        point=[float(ic['x']),
                               float(ic['y']),
                               float(ic['z'])])
                elif ic['type'] == "scatter":
                    self.set_initial_condition_scatter(
                        {spec: int(ic['count'])},
                        subdomains=[int(ic['subdomain'])])
                elif ic['type'] == "distribute":
                    self.set_initial_condition_distribute_uniformly(
                        {spec: int(ic['count'])},
                        subdomains=[int(ic['subdomain'])])
                else:
                    raise Exception(
                        "Unknown initial condition type {0}".format(
                            ic['type']))

            self.timespan(
                numpy.concatenate(
                    (numpy.arange(maxTime / increment) * increment, [maxTime
                                                                     ])))
Example #8
0
    def __init__(self, model_name="Hes1"):

        #Base constructure
        pyurdme.URDMEModel.__init__(self, model_name)

        #Species
        Pf = pyurdme.Species(name="Pf", diffusion_constant=0., dimension=3)
        Po = pyurdme.Species(name="Po", diffusion_constant=0., dimension=3)
        mRNA = pyurdme.Species(name="mRNA",
                               diffusion_constant=6.e-1,
                               dimension=3)
        protein = pyurdme.Species(name="protein",
                                  diffusion_constant=6.e-1,
                                  dimension=3)

        self.add_species([Pf, Po, mRNA, protein])

        #Mesh
        basedir = os.path.dirname(os.path.abspath(__file__))
        self.mesh = pyurdme.URDMEMesh.read_mesh(basedir + "/mesh/cell.msh")

        #Domains markers
        nucleus = [2]
        cytoplasm = [1]
        promoter_site = [3]

        #Domains
        self.add_subdomain(Nucleus(), nucleus[0])
        self.get_subdomain_vector()
        self.sd[self.mesh.closest_vertex([0, 0, 0])] = promoter_site[0]

        #Parameters
        k1 = pyurdme.Parameter(name="k1", expression=1.e9)
        k2 = pyurdme.Parameter(name="k2", expression=0.1)
        alpha_m = pyurdme.Parameter(name="alpha_m", expression=3.)
        alpha_m_gamma = pyurdme.Parameter(name="alpha_m_gamma",
                                          expression=3. / 30.)
        alpha_p = pyurdme.Parameter(name="alpha_p", expression=1.)
        mu_m = pyurdme.Parameter(name="mu_m", expression=0.015)
        mu_p = pyurdme.Parameter(name="mu_p", expression=0.043)

        self.add_parameter(
            [k1, k2, alpha_m, alpha_m_gamma, alpha_p, mu_m, mu_p])

        #Reactions
        R1 = pyurdme.Reaction(name="R1",
                              reactants={
                                  Pf: 1,
                                  protein: 1
                              },
                              products={Po: 1},
                              massaction=True,
                              rate=k1,
                              restrict_to=promoter_site)
        R2 = pyurdme.Reaction(name="R2",
                              reactants={Po: 1},
                              products={
                                  Pf: 1,
                                  protein: 1
                              },
                              massaction=True,
                              rate=k2,
                              restrict_to=promoter_site)
        R3 = pyurdme.Reaction(name="R3",
                              reactants={Pf: 1},
                              products={
                                  Pf: 1,
                                  mRNA: 1
                              },
                              massaction=True,
                              rate=alpha_m,
                              restrict_to=promoter_site)
        R4 = pyurdme.Reaction(name="R4",
                              reactants={Po: 1},
                              products={
                                  Po: 1,
                                  mRNA: 1
                              },
                              massaction=True,
                              rate=alpha_m_gamma,
                              restrict_to=promoter_site)
        R5 = pyurdme.Reaction(name="R5",
                              reactants={mRNA: 1},
                              products={
                                  mRNA: 1,
                                  protein: 1
                              },
                              massaction=True,
                              rate=alpha_p,
                              restrict_to=cytoplasm)
        R6 = pyurdme.Reaction(name="R6",
                              reactants={mRNA: 1},
                              products={},
                              massaction=True,
                              rate=mu_m)
        R7 = pyurdme.Reaction(name="R7",
                              reactants={protein: 1},
                              products={},
                              massaction=True,
                              rate=mu_p)

        self.add_reaction([R1, R2, R3, R4, R5, R6, R7])

        #Restrict to promoter_site
        self.restrict(Po, promoter_site)
        self.restrict(Pf, promoter_site)

        #Distribute molecules over the mesh
        self.set_initial_condition_scatter({Pf: 1}, promoter_site)
        self.set_initial_condition_scatter({protein: 60}, cytoplasm)
        self.set_initial_condition_scatter({mRNA: 10}, nucleus)

        self.timespan(range(1200))
Example #9
0
    def __init__(self, model_name="G_protein_cycle_1D"):
        pyurdme.URDMEModel.__init__(self, model_name)

        # Species
        # R RL G Ga Gbg Gd
        R = pyurdme.Species(name="R", diffusion_constant=0.01)
        RL = pyurdme.Species(name="RL", diffusion_constant=0.01)
        G = pyurdme.Species(name="G", diffusion_constant=0.01)
        Ga = pyurdme.Species(name="Ga", diffusion_constant=0.01)
        Gbg = pyurdme.Species(name="Gbg", diffusion_constant=0.01)
        Gd = pyurdme.Species(name="Gd", diffusion_constant=0.01)

        self.add_species([R, RL, G, Ga, Gbg, Gd])

        L = 4 * 3.14159
        NUM_VOXEL = 200
        MOLAR = 6.02e-01 * ((L / NUM_VOXEL)**3)
        self.mesh = pyurdme.URDMEMesh.generate_interval_mesh(nx=NUM_VOXEL,
                                                             a=-2 * 3.14159,
                                                             b=2 * 3.14159,
                                                             periodic=True)

        SA = pyurdme.Parameter(name="SA", expression=201.056)
        V = pyurdme.Parameter(name="V", expression=33.5)
        k_RL = pyurdme.Parameter(name="k_RL", expression=2e-03 / MOLAR)
        k_RLm = pyurdme.Parameter(name="k_RLm", expression=1e-02)
        k_Rs = pyurdme.Parameter(name="k_Rs", expression="4.0/SA")
        k_Rd0 = pyurdme.Parameter(name="k_Rd0", expression=4e-04)
        k_Rd1 = pyurdme.Parameter(name="k_Rd1", expression=4e-04)
        k_G1 = pyurdme.Parameter(name="k_G1", expression="1.0*SA")
        k_Ga = pyurdme.Parameter(name="k_Ga", expression="1e-06*SA")
        k_Gd = pyurdme.Parameter(name="k_Gd", expression=0.1)
        self.add_parameter(
            [SA, V, k_RL, k_RLm, k_Rs, k_Rd0, k_Rd1, k_G1, k_Ga, k_Gd])

        # Add Data Function to model the mating pheromone gradient.
        self.add_data_function(
            PheromoneGradient(a=-2 * 3.14159, b=2 * 3.14159, MOLAR=MOLAR))

        # Reactions
        R0 = pyurdme.Reaction(name="R0",
                              reactants={},
                              products={R: 1},
                              massaction=True,
                              rate=k_Rs)
        R1 = pyurdme.Reaction(name="R1",
                              reactants={R: 1},
                              products={},
                              massaction=True,
                              rate=k_Rd0)
        R2 = pyurdme.Reaction(
            name="R2",
            reactants={R: 1},
            products={RL: 1},
            propensity_function="k_RL*R*PheromoneGradient/vol")
        R3 = pyurdme.Reaction(name="R3",
                              reactants={RL: 1},
                              products={R: 1},
                              massaction=True,
                              rate=k_RLm)
        R4 = pyurdme.Reaction(name="R4",
                              reactants={RL: 1},
                              products={},
                              massaction=True,
                              rate=k_RLm)
        R5 = pyurdme.Reaction(name="R5",
                              reactants={G: 1},
                              products={
                                  Ga: 1,
                                  Gbg: 1
                              },
                              propensity_function="k_Ga*RL*G/vol")
        R6 = pyurdme.Reaction(name="R6",
                              reactants={Ga: 1},
                              products={Gd: 1},
                              massaction=True,
                              rate=k_Ga)
        R7 = pyurdme.Reaction(name="R7",
                              reactants={
                                  Gd: 1,
                                  Gbg: 1
                              },
                              products={G: 1},
                              massaction=True,
                              rate=k_G1)
        self.add_reaction([R0, R1, R2, R3, R4, R5, R6, R7])

        # Distribute molecules randomly over the mesh according to their initial values
        self.set_initial_condition_scatter({R: 10000})
        self.set_initial_condition_scatter({G: 10000})

        self.timespan(range(201))
Example #10
0
    def __init__(self, model_name="mincde"):
        pyurdme.URDMEModel.__init__(self, model_name)

        # Species
        MinD_m = pyurdme.Species(name="MinD_m",
                                 diffusion_constant=1e-14,
                                 dimension=2)
        MinD_c_atp = pyurdme.Species(name="MinD_c_atp",
                                     diffusion_constant=2.5e-12,
                                     dimension=3)
        MinD_c_adp = pyurdme.Species(name="MinD_c_adp",
                                     diffusion_constant=2.5e-12,
                                     dimension=3)
        MinD_e = pyurdme.Species(name="MinD_e",
                                 diffusion_constant=2.5e-12,
                                 dimension=3)
        MinDE = pyurdme.Species(name="MinDE",
                                diffusion_constant=1e-14,
                                dimension=2)

        self.add_species([MinD_m, MinD_c_atp, MinD_c_adp, MinD_e, MinDE])

        # Make sure that we have the correct path to the mesh file even if we are not executing from the basedir.
        basedir = os.path.dirname(os.path.abspath(__file__))
        self.mesh = pyurdme.URDMEMesh.read_dolfin_mesh(basedir +
                                                       "/mesh/coli.xml")

        interior = dolfin.CellFunction("size_t", self.mesh)
        interior.set_all(1)
        boundary = dolfin.FacetFunction("size_t", self.mesh)
        boundary.set_all(0)

        # Mark the boundary points
        membrane = Membrane()
        membrane.mark(boundary, 2)

        self.add_subdomain(interior)
        self.add_subdomain(boundary)

        # Average mesh size to feed into the propensity functions
        h = self.mesh.get_mesh_size()
        self.add_data_function(MeshSize(self.mesh))

        # Parameters
        NA = pyurdme.Parameter(name="NA", expression=6.022e23)
        sigma_d = pyurdme.Parameter(name="sigma_d", expression=2.5e-8)
        sigma_dD = pyurdme.Parameter(name="sigma_dD", expression=0.0016e-18)
        sigma_e = pyurdme.Parameter(name="sigma_e", expression=0.093e-18)
        sigma_de = pyurdme.Parameter(name="sigma_de", expression=0.7)
        sigma_dt = pyurdme.Parameter(name="sigma_dt", expression=1.0)

        self.add_parameter(
            [NA, sigma_d, sigma_dD, sigma_e, sigma_de, sigma_dt])

        # List of Physical domain markers that match those in the  Gmsh .geo file.
        interior = [1]
        boundary = [2]

        # Reactions
        R1 = pyurdme.Reaction(
            name="R1",
            reactants={MinD_c_atp: 1},
            products={MinD_m: 1},
            propensity_function="MinD_c_atp*sigma_d/MeshSize",
            restrict_to=boundary)
        R2 = pyurdme.Reaction(name="R2",
                              reactants={
                                  MinD_c_atp: 1,
                                  MinD_m: 1
                              },
                              products={MinD_m: 2},
                              massaction=True,
                              rate=sigma_dD)
        R3 = pyurdme.Reaction(name="R3",
                              reactants={
                                  MinD_m: 1,
                                  MinD_e: 1
                              },
                              products={MinDE: 1},
                              massaction=True,
                              rate=sigma_e)
        R4 = pyurdme.Reaction(name="R4",
                              reactants={MinDE: 1},
                              products={
                                  MinD_c_adp: 1,
                                  MinD_e: 1
                              },
                              massaction=True,
                              rate=sigma_de)
        R5 = pyurdme.Reaction(name="R5",
                              reactants={MinD_c_adp: 1},
                              products={MinD_c_atp: 1},
                              massaction=True,
                              rate=sigma_dt)
        R6 = pyurdme.Reaction(name="R6",
                              reactants={
                                  MinDE: 1,
                                  MinD_c_atp: 1
                              },
                              products={
                                  MinD_m: 1,
                                  MinDE: 1
                              },
                              massaction=True,
                              rate=sigma_dD)

        self.add_reaction([R1, R2, R3, R4, R5, R6])

        # Restrict to boundary
        self.restrict(MinD_m, boundary)
        self.restrict(MinDE, boundary)

        # Distribute molecules over the mesh according to their initial values
        self.set_initial_condition_scatter({MinD_c_adp: 4500})
        self.set_initial_condition_scatter({MinD_e: 1575})

        self.timespan(range(500))
Example #11
0
    def updateMesh(handler, jsonMesh, rename=False):
        if "undeletable" not in jsonMesh:
            jsonMesh["undeletable"] = False

        # This basically says to prefer the userId in the input
        if 'user_id' in jsonMesh:
            userId = jsonMesh['user_id']
        else:
            userId = handler.user.user_id()

        if "id" in jsonMesh:
            meshDb = MeshWrapper.get_by_id(jsonMesh["id"])
            name = jsonMesh["name"]
        else:
            # Make sure name isn't taken, or build one that isn't taken
            if "name" in jsonMesh:
                name = jsonMesh["name"]
                usedNames = set([
                    x.name for x in db.Query(MeshWrapper).filter(
                        'user_id =', userId).run()
                ])
                if name in usedNames:
                    if rename:
                        i = 1
                        name = '{0}_{1}'.format(jsonMesh["name"], i)

                        while name in usedNames:
                            i = i + 1
                            name = '{0}_{1}'.format(jsonMesh["name"], i)
                    else:
                        raise Exception("Name is required on new meshes")

            meshDb = MeshWrapper()

        meshDb.user_id = userId
        meshDb.name = name
        meshDb.description = jsonMesh["description"]
        meshDb.meshFileId = jsonMesh["meshFileId"]
        meshDb.subdomains = jsonMesh["subdomains"]
        meshDb.uniqueSubdomains = jsonMesh["uniqueSubdomains"]
        meshDb.undeletable = jsonMesh["undeletable"]

        pymodel = pyurdme.URDMEModel(name='test')
        meshFileObj = fileserver.FileManager.getFile(handler,
                                                     meshDb.meshFileId)
        pymodel.mesh = pyurdme.URDMEMesh.read_dolfin_mesh(
            str(meshFileObj["storePath"]))
        coordinates = pymodel.mesh.coordinates()
        minx = numpy.min(coordinates[:, 0])
        maxx = numpy.max(coordinates[:, 0])
        miny = numpy.min(coordinates[:, 1])
        maxy = numpy.max(coordinates[:, 1])
        minz = numpy.min(coordinates[:, 2])
        maxz = numpy.max(coordinates[:, 2])
        pymodel.add_species(pyurdme.Species('T', 1))

        if len(meshDb.subdomains) == 0:
            meshDb.subdomains = [1] * len(coordinates)
            meshDb.uniqueSubdomains = [1]

        pymodel.set_subdomain_vector(numpy.array(meshDb.subdomains))
        sd = pymodel.get_subdomain_vector()
        vol_accumulator = numpy.zeros(numpy.unique(sd).shape)
        for ndx, v in enumerate(pymodel.get_solver_datastructure()['vol']):
            vol_accumulator[sd[ndx] - 1] += v

        volumes = {}

        for s, v in enumerate(vol_accumulator):
            volumes[s + 1] = v

        meshDb.volumes = volumes
        meshDb.boundingBox = [[minx, maxx], [miny, maxy], [minz, maxz]]

        return meshDb.put().id()
Example #12
0
def setupMeshes(handler):
    try:
        base = os.path.dirname(
            os.path.realpath(__file__)) + '/../static/spatial/'

        files = [
            'coli_with_membrane_mesh.xml', 'cylinder_mesh.xml',
            'unit_cube_with_membrane_mesh.xml',
            'unit_sphere_with_membrane_mesh.xml'
        ]

        descriptions = {
            'coli_with_membrane_mesh.xml':
            'Simplified E-coli model mesh',
            'cylinder_mesh.xml':
            'Cylindrical domain',
            'unit_cube_with_membrane_mesh.xml':
            'Cubic domain of edge length 1.0',
            'unit_sphere_with_membrane_mesh.xml':
            'Spherical domain with radius 1.0'
        }

        namesToFilenames = {
            'E-coli with membrane': 'coli_with_membrane_mesh.xml',
            'Cylinder': 'cylinder_mesh.xml',
            'Unit cube': 'unit_cube_with_membrane_mesh.xml',
            'Unit sphere': 'unit_sphere_with_membrane_mesh.xml'
        }

        converted = set()
        for wrapper in db.GqlQuery(
                "SELECT * FROM MeshWrapper WHERE user_id = :1",
                handler.user.user_id()).run():
            converted.add(wrapper.name)

        for name in set(namesToFilenames.keys()) - converted:
            fileName = namesToFilenames[name]

            meshDb = MeshWrapper()

            # To get the subdomains, there is a .txt file stored along with every .xml
            baseName, ext = os.path.splitext(fileName)
            subdomainsFile = open(os.path.join(base, baseName + '.txt'), 'r')

            subdomains = []

            for line in subdomainsFile.read().split():
                v, s = line.strip().split(',')

                v = int(v)
                s = int(float(s))

                subdomains.append((v, s))

            subdomainsFile.close()

            subdomains = [y for x, y in sorted(subdomains, key=lambda x: x[0])]
            uniqueSubdomains = list(set(subdomains))

            meshFile = open(os.path.join(base, fileName), 'r')
            meshFileId = fileserver.FileManager.createFile(
                handler, "meshFiles", fileName, meshFile.read(), 777)
            meshFile.close()

            meshDb.user_id = handler.user.user_id()
            meshDb.name = name
            meshDb.description = descriptions[fileName]
            meshDb.meshFileId = int(meshFileId)
            meshDb.subdomains = subdomains
            meshDb.uniqueSubdomains = uniqueSubdomains
            meshDb.undeletable = True

            pymodel = pyurdme.URDMEModel(name='test')
            pymodel.mesh = pyurdme.URDMEMesh.read_dolfin_mesh(
                str(os.path.join(base, fileName)))
            coordinates = pymodel.mesh.coordinates()
            minx = numpy.min(coordinates[:, 0])
            maxx = numpy.max(coordinates[:, 0])
            miny = numpy.min(coordinates[:, 1])
            maxy = numpy.max(coordinates[:, 1])
            minz = numpy.min(coordinates[:, 2])
            maxz = numpy.max(coordinates[:, 2])
            pymodel.add_species(pyurdme.Species('T', 1))
            pymodel.set_subdomain_vector(numpy.array(subdomains))
            sd = pymodel.get_subdomain_vector()
            vol_accumulator = numpy.zeros(numpy.unique(sd).shape)
            for ndx, v in enumerate(pymodel.get_solver_datastructure()['vol']):
                vol_accumulator[sd[ndx] - 1] += v

            volumes = {}

            for s, v in enumerate(vol_accumulator):
                volumes[s + 1] = v

            meshDb.volumes = volumes
            meshDb.boundingBox = [[minx, maxx], [miny, maxy], [minz, maxz]]

            meshDb.put()
    except:
        traceback.print_exc()
        print "ERROR: Failed to import example public models"
Example #13
0
    def __init__(self, model_name="polarisome_1D"):
        pyurdme.URDMEModel.__init__(self, model_name)

        default_D = 0.0053
        fast_D = 1000 * default_D
        # Species
        Bni1c = pyurdme.Species(name="Bni1c", diffusion_constant=fast_D)
        Bni1m = pyurdme.Species(name="Bni1m", diffusion_constant=default_D)
        Spa2c = pyurdme.Species(name="Spa2c", diffusion_constant=fast_D)
        Spa2m = pyurdme.Species(name="Spa2m", diffusion_constant=default_D)
        Actinc = pyurdme.Species(name="Actinc", diffusion_constant=fast_D)
        Actinm = pyurdme.Species(name="Actinm", diffusion_constant=default_D)
        self.add_species([Bni1c, Bni1m, Spa2c, Spa2m, Actinc, Actinm])

        NUM_VOXEL = 160
        self.mesh = pyurdme.URDMEMesh.generate_interval_mesh(nx=NUM_VOXEL,
                                                             a=-4 * numpy.pi,
                                                             b=4 * numpy.pi,
                                                             periodic=True)

        Bon = pyurdme.Parameter(name="Bon", expression=1.6e-6)
        Boff = pyurdme.Parameter(name="Boff", expression=0.25)
        Bfb = pyurdme.Parameter(name="Bfb", expression=1.9e-5)
        Aon = pyurdme.Parameter(name="Aon", expression=7.7e-5)
        Aoff = pyurdme.Parameter(name="Aoff", expression=0.018)
        Km = pyurdme.Parameter(name="Km", expression=3500)
        Son = pyurdme.Parameter(name="Son", expression=0.16)
        Soff = pyurdme.Parameter(name="Soff", expression=0.35)
        self.add_parameter([Bon, Boff, Bfb, Aon, Aoff, Km, Son, Soff])

        # Add Data Function to model the mating pheromone gradient.
        self.add_data_function(Cdc42())

        # Reactions
        R0 = pyurdme.Reaction(name="R0",
                              reactants={Bni1c: 1},
                              products={Bni1m: 1},
                              propensity_function="Bon*Bni1c*NUM_VOXELS*Cdc42")
        R1 = pyurdme.Reaction(name="R1",
                              reactants={Bni1m: 1},
                              products={Bni1c: 1},
                              massaction=True,
                              rate=Boff)
        R2 = pyurdme.Reaction(
            name="R2",
            reactants={Actinc: 1},
            products={Actinm: 1},
            propensity_function="Aon*Bni1m*Actinc*NUM_VOXELS")
        R3 = pyurdme.Reaction(name="R3",
                              reactants={Actinm: 1},
                              products={Actinc: 1},
                              propensity_function="Aoff*Km/(Km+Spa2m)*Actinm")
        R4 = pyurdme.Reaction(
            name="R4",
            reactants={Spa2c: 1},
            products={Spa2m: 1},
            propensity_function="Son*Spa2c*NUM_VOXELS*Actinm")
        R5 = pyurdme.Reaction(name="R5",
                              reactants={Spa2m: 1},
                              products={Spa2c: 1},
                              massaction=True,
                              rate=Soff)
        R6 = pyurdme.Reaction(name="R6",
                              reactants={Bni1c: 1},
                              products={Bni1m: 1},
                              propensity_function="Bfb*Bni1c*NUM_VOXELS*Spa2m")
        self.add_reaction([R0, R1, R2, R3, R4, R5, R6])

        # Distribute molecules randomly over the mesh according to their initial values
        self.set_initial_condition_scatter({Bni1c: 1000})
        self.set_initial_condition_scatter({Spa2c: 5000})
        self.set_initial_condition_scatter({Actinc: 40})

        #self.timespan(range(0,3601,30))
        self.timespan(range(0, 201, 10))
Example #14
0
    def __init__(self, name="coral_reef", D_c=1.0, D_m=1.0, version=1):
        pyurdme.URDMEModel.__init__(self, name)

        # Species
        Coral = pyurdme.Species(name="Coral",diffusion_constant=0.0)
        Coral_m = pyurdme.Species(name="Coral_m",diffusion_constant=D_c)
        MA = pyurdme.Species(name="MA", diffusion_constant=0.0)
        MA_m = pyurdme.Species(name="MA_m", diffusion_constant=D_m)
        Turf = pyurdme.Species(name="Turf", diffusion_constant=0.0)
        self.add_species([Coral, MA, Coral_m, MA_m, Turf])

        # Parameters
        phi_c = pyurdme.Parameter(name="phi_c", expression=0.0011) #1/year
        phi_m = pyurdme.Parameter(name="phi_m", expression=0.001) #1/year
        g_tc = pyurdme.Parameter(name="g_tc", expression=0.1) #1/year
        g_tm = pyurdme.Parameter(name="g_tm", expression=0.2) #1/year
        Gamma = pyurdme.Parameter(name="Gamma", expression=0.05)
        dc = pyurdme.Parameter(name="dc", expression=0.05) #1/year
        dm = pyurdme.Parameter(name="dm", expression=1.0) #1/year
        #dm = pyurdme.Parameter(name="dm", expression=0.2) #1/year
        phi_g = pyurdme.Parameter(name="psi_g", expression=0.0)
        # Death rate of mobile propgules.  Combine with diffusion to determine spread.
        mu_c = pyurdme.Parameter(name="mu_c", expression=1.0) #1/year
        mu_m = pyurdme.Parameter(name="mu_m", expression=1.0) #1/year
        # mobile propogules destroyed by estabilished 
        alpha_c = pyurdme.Parameter(name="alpha_c", expression=0.1) #1/year
        alpha_m = pyurdme.Parameter(name="alpha_m", expression=0.5) #1/year
        # Production of mobile propogules
        R_c = pyurdme.Parameter(name="R_c", expression=1.0) #1/year
        R_m = pyurdme.Parameter(name="R_m", expression=1.0) #1/year

        self.add_parameter([phi_c, phi_m, g_tc, g_tm, Gamma, dc, dm, phi_g, mu_c, mu_m, alpha_c, alpha_m, R_c, R_m])
                

        # Reactions:
        # C -> T : dc
        self.add_reaction(pyurdme.Reaction(name="R3", reactants={Coral:1}, products={Turf:1}, rate=dc))
        # MA -> T : dm
        self.add_reaction(pyurdme.Reaction(name="R4", reactants={MA:1}, products={Turf:1}, rate=dm))
        # T + C_m -> C : phi_c
        self.add_reaction(pyurdme.Reaction(name="R5", reactants={Turf:1, Coral_m:1}, products={Coral:1}, rate=phi_c))
        # T + MA_m -> MA : phi_m
        self.add_reaction(pyurdme.Reaction(name="R6", reactants={Turf:1, MA_m:1}, products={MA:1}, rate=phi_m))
        # C + T -> 2C : g_tc * exp(-1.0 * psi_g * MA / 100)
        self.add_reaction(pyurdme.Reaction(name="R7", reactants={Turf:1, Coral:1}, products={Coral:2}, propensity_function="g_tc*Turf*Coral*exp(-1.0 * psi_g * MA / Space_per_voxel)/vol"))
        # MA + T -> 2MA : g_tm
        self.add_reaction(pyurdme.Reaction(name="R8", reactants={Turf:1, MA:1}, products={MA:2}, rate=g_tm))
        # C + MA -> 2MA : Gamma * g_tm
        self.add_reaction(pyurdme.Reaction(name="R9", reactants={Coral:1, MA:1}, products={MA:2}, propensity_function="g_tm*Gamma*Coral*MA/vol"))
        # C -> C + C_m : R_c
        self.add_reaction(pyurdme.Reaction(name="R10", reactants={Coral:1}, products={Coral:1, Coral_m:1}, rate=R_c))
        # MA -> MA + MA_m : R_m
        self.add_reaction(pyurdme.Reaction(name="R11", reactants={MA:1}, products={MA:1, MA_m:1}, rate=R_m))
        # C_m -> 0 : mu_c
        self.add_reaction(pyurdme.Reaction(name="R12", reactants={Coral_m:1}, products={}, rate=mu_c))
        # MA_m -> 0 : mu_m
        self.add_reaction(pyurdme.Reaction(name="R13", reactants={MA_m:1},  products={}, rate=mu_m))
        # MA + C_m -> MA : alpha_c
        self.add_reaction(pyurdme.Reaction(name="R14", reactants={MA:1, Coral_m:1},  products={MA:1}, rate=alpha_c))
        # C + MA_m -> C : alpha_m
        self.add_reaction(pyurdme.Reaction(name="R15", reactants={Coral:1, MA_m:1},  products={Coral:1}, rate=alpha_m))
 
        

        # A unit square
        # each grid point is 10cm x 10cm, domain is 5m x 5m
        self.mesh = pyurdme.URDMEMesh.generate_square_mesh(L=5, nx=50, ny=50, periodic=True)

        Space_per_voxel = 10
        self.add_parameter(pyurdme.Parameter(name="Space_per_voxel", expression=Space_per_voxel)) #1/year
        
                          
        if True:
            # Start with two colonys
            self.set_initial_condition_distribute_uniformly({Turf:Space_per_voxel})
            self.set_initial_condition_place_near({Coral:Space_per_voxel}, point=[1,1])
            self.set_initial_condition_place_near({Turf:0}, point=[1,1])
            self.set_initial_condition_place_near({MA:Space_per_voxel}, point=[4,4])
            self.set_initial_condition_place_near({Turf:0}, point=[4,4])
        else:
            # Every voxel is the same
            self.set_initial_condition_distribute_uniformly({Turf:0})
            self.set_initial_condition_distribute_uniformly({Coral:Space_per_voxel-1})
            self.set_initial_condition_distribute_uniformly({MA:1})


        for vndx in range(self.u0.shape[1]):
            tot = 0
            for sndx, sname in enumerate(self.listOfSpecies):
                tot += self.u0[sndx][vndx]
            if tot > 100:
                for sndx, sname in enumerate(self.listOfSpecies):
                    print "u0[{0}][{1}] = {2}".format(sname, vndx, self.u0[sndx][vndx])

        #self.timespan(numpy.linspace(0,500,501)) #500 years
        #self.timespan(numpy.linspace(0,5,72)) #5 years, by months
        self.timespan(numpy.linspace(0,11,66)) #10 years, by 2 months
Example #15
0
    def __init__(self, model_name="hes1"):
        pyurdme.URDMEModel.__init__(self, model_name)

        #Species
        Pf = pyurdme.Species(name="Pf", diffusion_constant=0., dimension=3)
        Po = pyurdme.Species(name="Po", diffusion_constant=0., dimension=3)
        mRNA = pyurdme.Species(name="mRNA",
                               diffusion_constant=6.e-1,
                               dimension=3)
        protein = pyurdme.Species(name="protein",
                                  diffusion_constant=6.e-1,
                                  dimension=3)

        self.add_species([Pf, Po, mRNA, protein])

        #Domains
        basedir = os.path.dirname(os.path.abspath(__file__))
        self.mesh = pyurdme.URDMEMesh.read_mesh(basedir + "/mesh/cell.msh")

        volumes = dolfin.MeshFunction(
            "size_t", self.mesh, basedir + "/mesh/cell_physical_region.xml")
        self.add_subdomain(volumes)

        h = self.mesh.get_mesh_size()
        self.add_data_function(MeshSize(self.mesh))

        #Parameters
        k1 = pyurdme.Parameter(name="k1", expression=1.e9)
        k2 = pyurdme.Parameter(name="k2", expression=0.1)
        alpha_m = pyurdme.Parameter(name="alpha_m", expression=3.)
        alpha_m_gamma = pyurdme.Parameter(name="alpha_m_gamma",
                                          expression=3. / 30.)
        alpha_p = pyurdme.Parameter(name="alpha_p", expression=1.)
        mu_m = pyurdme.Parameter(name="mu_m", expression=0.015)
        mu_p = pyurdme.Parameter(name="mu_p", expression=0.043)

        self.add_parameter(
            [k1, k2, alpha_m, alpha_m_gamma, alpha_p, mu_m, mu_p])

        #Domains markers
        nucleus = [1]
        cytoplasm = [2]
        promoter_site = [1]

        #Reactions
        R1 = pyurdme.Reaction(name="R1",
                              reactants={
                                  Pf: 1,
                                  protein: 1
                              },
                              products={Po: 1},
                              massaction=True,
                              rate=k1,
                              restrict_to=promoter_site)
        R2 = pyurdme.Reaction(name="R2",
                              reactants={Po: 1},
                              products={
                                  Pf: 1,
                                  protein: 1
                              },
                              massaction=True,
                              rate=k2,
                              restrict_to=promoter_site)
        R3 = pyurdme.Reaction(name="R3",
                              reactants={Pf: 1},
                              products={
                                  Pf: 1,
                                  mRNA: 1
                              },
                              massaction=True,
                              rate=alpha_m,
                              restrict_to=promoter_site)
        R4 = pyurdme.Reaction(name="R4",
                              reactants={Po: 1},
                              products={
                                  Po: 1,
                                  mRNA: 1
                              },
                              massaction=True,
                              rate=alpha_m_gamma,
                              restrict_to=promoter_site)
        R5 = pyurdme.Reaction(name="R5",
                              reactants={mRNA: 1},
                              products={
                                  mRNA: 1,
                                  protein: 1
                              },
                              massaction=True,
                              rate=alpha_p,
                              restrict_to=cytoplasm)
        R6 = pyurdme.Reaction(name="R6",
                              reactants={mRNA: 1},
                              products={},
                              massaction=True,
                              rate=mu_m)
        R7 = pyurdme.Reaction(name="R7",
                              reactants={protein: 1},
                              products={},
                              massaction=True,
                              rate=mu_p)

        self.add_reaction([R1, R2, R3, R4, R5, R6, R7])

        #Restrict to promoter_site
        self.restrict(Po, promoter_site)
        self.restrict(Pf, promoter_site)

        #Distribute molecules over the mesh
        self.set_initial_condition_place_near({Pf: 1}, [0, 0, 0])
        self.set_initial_condition_scatter({protein: 60}, cytoplasm)
        self.set_initial_condition_scatter({mRNA: 10}, nucleus)

        self.timespan(range(1200))