def _translate(model, mesh, initial_dist, param_values=None, dif0=None, y0=None):
    
    
    urdme_model = pyurdme.URDMEModel(model.name)
    urdme_model.add_species(_translate_species(model, initial_dist, dif0, y0)[0])
    urdme_model.mesh = mesh
    urdme_model.add_parameter(_translate_parameters(model, param_values))
    urdme_model.add_reaction(_translate_reactions(model))
    initial_d_info = _translate_species(model, initial_dist, dif0, y0)[1]
    for id in initial_d_info:
        getattr(urdme_model, id[0][0])({urdme_model.get_species(id[1].keys()[0]):id[1].values()[0]}, id[0][1])
       
    return urdme_model
Esempio n. 2
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
Esempio n. 3
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()
Esempio n. 4
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"