def loadModel(self, request): self.fileUploadForm = DocumentForm(request.POST, request.FILES) if self.fileUploadForm.is_valid(): new_sbml_model = SbmlModel(project=self.project, sbml_file=request.FILES['docfile']) new_sbml_model.save() try: doc = SbmlDocument() doc.readSbmlFromFile( os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file))) new_sbml_model.name = doc.model.getName() new_sbml_model.save() except MissingSubmodelException: new_sbml_model.delete() self.addError( "This model is importing some models which were not found in the project folder. Please import them first" ) # Is triggered where name is None ?? except ModelException: name = os.path.splitext(str(new_sbml_model.sbml_file))[0] new_sbml_model.name = name new_sbml_model.save()
def __loadModelVariables(self): if self.model_id is not None: t_model = SbmlModel.objects.get(project=self.project_id, id=self.model_id) self.model_filename = os.path.join(settings.MEDIA_ROOT, str(t_model.sbml_file)) t_doc = SbmlDocument() t_doc.readSbmlFromFile(self.model_filename) self.model = t_doc.model self.model_name = self.model.getName() self.model_list_of_submodels = self.model.listOfSubmodels.values() self.model_list_of_submodels_names = [] self.model_list_of_submodels_types = [] for submodel in self.model.listOfSubmodels.values(): if submodel.getModelRef( ) in self.model.parentDoc.listOfModelDefinitions.sbmlIds(): self.model_list_of_submodels_names.append( self.model.parentDoc.listOfModelDefinitions. getBySbmlId(submodel.getModelRef()).getNameOrSbmlId()) self.model_list_of_submodels_types.append(0) if submodel.getModelRef( ) in self.model.parentDoc.listOfExternalModelDefinitions.sbmlIds( ): self.model_list_of_submodels_names.append( self.model.parentDoc.listOfExternalModelDefinitions. getBySbmlId(submodel.getModelRef()).getNameOrSbmlId()) self.model_list_of_submodels_types.append(1)
def readModel(self, request): self.optimizationModel = SbmlDocument() self.optimizationModel.readSbmlFromFile(os.path.join(self.optimPath, "model.sbml")) if self.optimizationModel.getModelInstance().getNameOrSbmlId() is not None: self.modelName = self.optimizationModel.getModelInstance().getNameOrSbmlId() else: self.modelName = self.optimizationModel.model.getNameOrSbmlId()
def loadOptimizations(self, request): if self.list_of_models is not None and len(self.list_of_models) > 0: t_model = SbmlModel.objects.get(project=self.project, id=self.model_id) optimizations = Optimization.objects.filter(project=self.project, model=t_model) self.listOfOptimizations = [] for optimization in optimizations: # t_session_id = optimization.session_id t_optim_id = optimization.optimization_id optim_path = join( settings.MEDIA_ROOT, str(self.project.folder), "optimizations/optimization_%s/" % str(t_optim_id)) # os.path.abspath(os.path.join(settings.BASE_DIR,"../../../tmp/optimization_%s/" % t_optim_id)) optimization_status = None if not exists(optim_path): optimization_status = "Not found" elif isfile(optim_path + "/logs/score/score"): optimization_status = "Finished" elif isfile(optim_path + "/err_optim"): if getsize(optim_path + "/err_optim") > 0: optimization_status = "Interrupted" else: optimization_status = "Ongoing" else: optimization_status = "Ongoing" t_time_of_launch = self.hms_string( int(time()) - (int(t_optim_id) / 1000)) + " ago" t_model_name = "" if isfile(optim_path + "/model.sbml"): try: t_document = SbmlDocument() t_document.readSbmlFromFile( str(optim_path + "/model.sbml")) t_model_name = t_document.model.getName() except ModelException as e: t_model_name = "Unknown" self.listOfOptimizations.append( (optimization, optimization_status, t_time_of_launch, t_model_name))
def loadSimulation(self, request): self.fileUploadForm = DocumentForm(request.POST, request.FILES) if self.fileUploadForm.is_valid(): sedml_archive = SEDMLSimulation( project=self.project, sedml_file=request.FILES['docfile']) sedml_archive.name = basename(str( request.FILES['docfile'])).split('.')[0] sedml_archive.save() # Now everything is in the same folder sedml_doc = SedmlDocument() sedml_doc.readSedmlFromFile( join(settings.MEDIA_ROOT, str(sedml_archive.sedml_file))) sedml_doc.listOfModels.removePaths() sbml_files = sedml_doc.listOfModels.makeLocalSources() for sbml_file in sbml_files: if len( SbmlModel.objects.filter( project=self.project, sbml_file=join( join(str(self.project.folder), "models"), basename(sbml_file)))) == 0: t_file = File(open(sbml_file, 'r')) sbml_model = SbmlModel(project=self.project, sbml_file=t_file) sbml_model.save() try: doc = SbmlDocument() doc.readSbmlFromFile( join(settings.MEDIA_ROOT, str(sbml_model.sbml_file))) sbml_model.name = doc.model.getName() sbml_model.save() except ModelException: name = os.path.splitext(str(sbml_model.sbml_file))[0] sbml_model.name = name sbml_model.save() sedml_doc.writeSedmlToFile( join(settings.MEDIA_ROOT, str(sedml_archive.sedml_file))) self.loadListOfSimulations()
def getModelSBMLSubmodels(self, request): """ Returning the submodels of a model available within the project """ if self.isUserLoggedIn( request ) and self.project is not None and self.model_id is not None: t_filename = os.path.join(settings.MEDIA_ROOT, str(self.model_filename)) doc = SbmlDocument() doc.readSbmlFromFile(t_filename) if doc.useCompPackage: return ( doc.listOfModelDefinitions.getListOfModelDefinitions() + doc.listOfExternalModelDefinitions. getListOfModelDefinitions())
def newModel(self, request): model_name = str(request.POST['model_name']) model_filename = os.path.join(settings.MEDIA_ROOT, new_model_filename()) open(model_filename, "a") new_model = SbmlModel(project=self.project, name=model_name, sbml_file=File(open(model_filename, "r"))) os.remove(model_filename) new_model.save() doc = SbmlDocument() doc.model.newModel(model_name) doc.writeSbmlToFile( os.path.join(settings.MEDIA_ROOT, str(new_model.sbml_file)))
def getModelSubmodels(self, request, model_id): """ Returning the submodels of a model available within the project """ if self.isUserLoggedIn(request) and self.project is not None: t_models = [ pm for pm in self.getProjectModels(request) if pm.id != self.model_id ] t_filename = os.path.join(settings.MEDIA_ROOT, str(t_models[model_id].sbml_file)) doc = SbmlDocument() doc.readSbmlFromFile(t_filename) if doc.useCompPackage: return [doc.model.getSbmlId() ] + doc.listOfModelDefinitions.sbmlIds( ) + doc.listOfExternalModelDefinitions.sbmlIds() else: return [doc.model.getSbmlId()]
def getListOfObjects(self, request): if str(request.POST['model_id']) != "": # print "model id = %d" % int(request.POST['model_id']) # print [pm.name for pm in self.getProjectModels(request)] # print [pm.id for pm in self.getProjectModels(request)] # print self.model_name # print self.model_id list_of_project_models = [pm for pm in self.getProjectModels(request) if pm.id != self.model_id] print "list of models : %s" % [pm.name for pm in list_of_project_models] # print "selected model : %s" % str(list_of_project_models[int(request.POST['model_id'])].name) t_model = list_of_project_models[int(request.POST['model_id'])] t_filename = join(settings.MEDIA_ROOT, str(t_model.sbml_file)) doc = SbmlDocument() doc.readSbmlFromFile(t_filename) self.listOfObjects = [] for t_object in doc.model.listOfSbmlObjects.values(): if isinstance(t_object, Variable) and not t_object.isStoichiometry(): self.listOfObjects.append(t_object.getNameOrSbmlId() + (" (%s)" % type(t_object).__name__)) # print self.listOfObjects return self.listOfObjects
def duplicateModel(self, request): model = SbmlModel.objects.get(id=request.POST['id']) t_file = File( open(os.path.join(settings.MEDIA_ROOT, str(model.sbml_file)))) new_sbml_model = SbmlModel(project=self.project, name=("%s (copy)" % str(model.name)), sbml_file=t_file) new_sbml_model.save() t_filename = os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file)) doc = SbmlDocument() doc.readSbmlFromFile(t_filename) doc.model.setName(str(new_sbml_model.name)) doc.writeSbmlToFile(t_filename)
class OptimizationResultView(TemplateView, HasWorkingProject): template_name = 'fit/result.html' def __init__(self, **kwargs): TemplateView.__init__(self, **kwargs) HasWorkingProject.__init__(self) self.optimizationId = None self.parameters = None self.inputParameters = None self.outputParameters = None self.modelName = None self.submodelNames = None self.modifiedSubmodelNames = None self.optimizationStatus = None self.showGraph = None self.optimPath = None self.experiments = None self.experimentsData = None self.scoreTime = [] self.scoreValues = [] self.scoreRawValues = [] self.scoreMinEv = [] self.scoreMaxEv = [] self.optimizationModel = None def get_context_data(self, **kwargs): kwargs = HasWorkingProject.get_context_data(self, **kwargs) kwargs['optimization_id'] = self.optimizationId kwargs['parameters'] = self.parameters kwargs['model_name'] = self.modelName kwargs['submodel_names'] = self.submodelNames kwargs['modified_submodel_names'] = self.modifiedSubmodelNames kwargs['show_graph'] = self.showGraph kwargs['optimization_status'] = self.optimizationStatus kwargs['score_time'] = self.scoreTime kwargs['score_values'] = self.scoreValues kwargs['score_rawvalues'] = self.scoreRawValues kwargs['score_minev'] = self.scoreMinEv kwargs['score_maxev'] = self.scoreMaxEv kwargs['colors'] = Settings.default_colors kwargs['experiments'] = self.experimentsData return kwargs def get(self, request, *args, **kwargs): self.load(request, *args, **kwargs) return TemplateView.get(self, request, *args, **kwargs) def post(self, request, *args, **kwargs): self.load(request, *args, **kwargs) if "action" in request.POST: if HasWorkingProject.isChooseProject(self, request): return redirect('list_of_optimizations') if request.POST['action'] == "save_model": self.saveFittedModel(request) elif request.POST['action'] == "stop_optim": self.stopOptimization() elif request.POST['action'] == "restart_optim": self.restartOptimization() return TemplateView.get(self, request, *args, **kwargs) def load(self, request, *args, **kwargs): HasWorkingProject.load(self, request, *args, **kwargs) if self.isProjectLoaded(): self.loadOptimization(request, *args) def stopOptimization(self): stopOptimization(self.optimPath) self.optimizationStatus = Optimization.objects.get(optimization_id=self.optimizationId).status def restartOptimization(self): t = Thread( group=None, target=restartOptimization, args=(self.optimPath,) ) t.setDaemon(True) t.start() sleep(2) self.optimizationStatus = Optimization.objects.get(optimization_id=self.optimizationId).status def saveFittedModel(self, request): t_document = SbmlDocument() t_document.readSbmlFromFile(str(self.optimPath + "/model.sbml")) model = t_document.model if request.POST.get('model_name') is not None: self.modelName = str(request.POST['model_name']) elif model.getName() is not None: self.modelName = model.getName() else: self.modelName = self.model_name if not SbmlModel.objects.filter(name=self.modelName): document = SbmlDocument() document.readSbmlFromFile(os.path.join(settings.MEDIA_ROOT, os.path.join(self.optimPath, "model.sbml"))) if not document.useCompPackage: file = File(open(os.path.join(settings.MEDIA_ROOT, os.path.join(self.optimPath, "model.sbml")))) new_sbml_model = SbmlModel(project=self.project, name=self.modelName, sbml_file=file) new_sbml_model.save() new_document = SbmlDocument() new_document.readSbmlFromFile(os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file))) new_document.model.setName(self.modelName) for i_param, (xpath, value) in enumerate(self.outputParameters): param = new_document.getByXPath(xpath) param.setValue(value) new_document.writeSbmlToFile(os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file))) else: modifieds = [] for i_param, (xpath, value) in enumerate(self.outputParameters): param = document.getModelInstance().getDefinitionVariableByXPath(xpath) modifieds.append(param[0].getModel().parentDoc) modifieds = list(set(modifieds)) submodel_names = [] i_submodel = 0 while request.POST.get("submodel_%d_name" % i_submodel) is not None: submodel_names.append(request.POST["submodel_%d_name" % i_submodel]) i_submodel += 1 modified_files = {} for i_modified, modified in enumerate(modifieds): file = File(open(os.path.join(settings.MEDIA_ROOT, os.path.join(self.optimPath, modified.documentFilename)), 'rb')) new_sbml_model = SbmlModel(project=self.project, name=submodel_names[i_modified], sbml_file=file) new_sbml_model.save() new_document = SbmlDocument() new_document.readSbmlFromFile(os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file))) new_document.model.setName(str(submodel_names[i_modified])) new_document.writeSbmlToFile(os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file))) modified_files.update({modified.documentFilename: os.path.basename(str(new_sbml_model.sbml_file))}) print(modified_files) print(subdoc.documentFilename for subdoc in document.documentDependencies) renaming = {} for subdoc in document.documentDependencies: if subdoc.documentFilename in modified_files: renaming.update({subdoc.documentFilename: modified_files[subdoc.documentFilename]}) else: renaming.update({subdoc.documentFilename: subdoc.documentFilename}) print(renaming) file = File(open(os.path.join(settings.MEDIA_ROOT, os.path.join(self.optimPath, "model.sbml")), 'rb')) new_sbml_model = SbmlModel(project=self.project, name=self.modelName, sbml_file=file) new_sbml_model.save() new_document = SbmlDocument() new_document.readSbmlFromFile(os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file))) new_document.renameExternalDocumentDependencies(renaming) new_document.model.setName(self.modelName) new_document.writeSbmlToFile(os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file))) def loadOptimization(self, request, *args): self.optimizationId = str(args[0]) self.optimPath = os.path.join(self.getProjectFolder(), "optimizations/optimization_%s/" % self.optimizationId) self.optimizationStatus = Optimization.objects.get(optimization_id=self.optimizationId).status self.showGraph = None self.parameters = [] self.loadOptimizationResults(request) self.loadOptimizationScore(request) self.readModel(request) self.loadParameters(request) self.loadSubmodels(request) request.session['optim_dir'] = self.optimPath request.session['logdir'] = os.path.join(self.optimPath, "logs") def loadOptimizationResults(self, request): nb_experiments = 0 nb_conditions = 0 self.max_conditions = 0 self.max_vars = 0 vars_structure = [] data_structure = [] while (os.path.isfile(os.path.join(self.optimPath, "logs/exp_%d_cond_%d_var_%d" % ( nb_experiments, 0, 0)))): nb_conditions = 0 t_cond_vars_structure = [] t_cond_data_structure = [] while (os.path.isfile(os.path.join(self.optimPath, "logs/exp_%d_cond_%d_var_0" % (nb_experiments, nb_conditions)))): nb_vars = 0 t_var_data_structure = [] while(os.path.isfile(os.path.join(self.optimPath, "logs/exp_%d_cond_%d_var_%d" % (nb_experiments, nb_conditions, nb_vars)))): t_var_data_structure.append((self.readModelSimulation(nb_experiments,nb_conditions, nb_vars), self.readObservation(nb_experiments, nb_conditions, nb_vars))) nb_vars += 1 #print t_var_data_structure t_cond_vars_structure.append(nb_vars) t_cond_data_structure.append(t_var_data_structure) nb_conditions += 1 self.max_vars = max(self.max_vars, nb_vars) self.max_conditions = max(self.max_conditions, nb_conditions) vars_structure.append(t_cond_vars_structure) data_structure.append(t_cond_data_structure) nb_experiments += 1 #print data_structure self.experiments = vars_structure self.experimentsData = data_structure def readObservation(self, experiment, condition, var): f_optim = open( os.path.join(self.optimPath, "logs/exp_%d_cond_%d_var_%d" % (experiment, condition, var)), "r") res = [] for line in f_optim: data = re.split("\t", line.strip()) res.append((float(data[0]), float(data[1]), float(data[2]))) f_optim.close() return res def readModelSimulation(self, experiment, condition, var, proc=0): if os.path.isfile(os.path.join(self.optimPath, "logs/res/model_exp_%d_cond_%d_var_%d_proc_%d" % (experiment, condition, var, proc))): f_optim = open( os.path.join(self.optimPath, "logs/res/model_exp_%d_cond_%d_var_%d_proc_%d" % (experiment, condition, var, proc)), "r") elif os.path.isfile(os.path.join(self.optimPath, "logs/best_res/model_exp_%d_cond_%d_var_%d_proc_%d" % (experiment, condition, var, proc))): f_optim = open( os.path.join(self.optimPath, "logs/best_res/model_exp_%d_cond_%d_var_%d_proc_%d" % (experiment, condition, var, proc)), "r") else: return res = [] for line in f_optim: data = re.split("\t", line.strip()) res.append((float(data[0]), float(data[1]))) f_optim.close() return res def loadOptimizationScore(self, request): if os.path.isfile(os.path.join(self.optimPath, "plsa.log")): # Reading file f_optim = open(os.path.join(self.optimPath, "plsa.log"), "r") for line in f_optim: data = re.split("\t", line.strip()) self.scoreTime.append(float(data[0])) self.scoreValues.append(float(data[5])) self.scoreRawValues.append(float(data[3])) self.scoreMinEv.append(max(0.0, float(data[5])-float(data[6]))) self.scoreMaxEv.append(float(data[5])+float(data[6])) def loadParameters(self, request): self.inputParameters = [] self.outputParameters = [] if os.path.isfile(os.path.join(self.optimPath, "logs/params/input")): f_input = open(os.path.join(self.optimPath, "logs/params/input")) for line in f_input: res = re.split(" ", line.strip()) xpath = res[0] value = res[2] self.inputParameters.append((xpath, value)) if os.path.isfile(os.path.join(self.optimPath, "logs/params/output")): f_input = open(os.path.join(self.optimPath, "logs/params/output")) for line in f_input: res = re.split(" ", line.strip()) xpath = res[0] value = res[2] self.outputParameters.append((xpath, value)) elif os.path.isfile(os.path.join(self.optimPath, "logs/best_res/parameters_0")): f_input = open(os.path.join(self.optimPath, "logs/best_res/parameters_0")) for line in f_input: res = re.split(" ", line.strip()) xpath = res[0] value = res[2] self.outputParameters.append((xpath, value)) if len(self.inputParameters) > 0 and len(self.outputParameters) == len(self.inputParameters): self.parameters = [] for i, (xpath, value) in enumerate(self.inputParameters): parameter = self.optimizationModel.getByXPath(xpath, instance=self.optimizationModel.useCompPackage) self.parameters.append((parameter.getNameOrSbmlId(), value, self.outputParameters[i][1])) def loadSubmodels(self, request): if self.optimizationModel.useCompPackage: self.optimizationModel.loadExternalDocumentDependencies() self.modifiedSubmodelNames = {} for subdoc in self.optimizationModel.documentDependencies: self.modifiedSubmodelNames[subdoc.model.getNameOrSbmlId()] = False for i_param, (xpath, value) in enumerate(self.outputParameters): param = self.optimizationModel.getModelInstance().getDefinitionVariableByXPath(xpath) self.modifiedSubmodelNames[param[0].getModel().getName()] = True self.submodelNames = [] for subdoc in self.optimizationModel.documentDependencies: if self.modifiedSubmodelNames[subdoc.model.getNameOrSbmlId()]: if subdoc.model.getNameOrSbmlId() is None: self.submodelNames.append("") else: self.submodelNames.append(subdoc.model.getNameOrSbmlId()) def readModel(self, request): self.optimizationModel = SbmlDocument() self.optimizationModel.readSbmlFromFile(os.path.join(self.optimPath, "model.sbml")) if self.optimizationModel.getModelInstance().getNameOrSbmlId() is not None: self.modelName = self.optimizationModel.getModelInstance().getNameOrSbmlId() else: self.modelName = self.optimizationModel.model.getNameOrSbmlId()
def saveFittedModel(self, request): t_document = SbmlDocument() t_document.readSbmlFromFile(str(self.optimPath + "/model.sbml")) model = t_document.model if request.POST.get('model_name') is not None: self.modelName = str(request.POST['model_name']) elif model.getName() is not None: self.modelName = model.getName() else: self.modelName = self.model_name if not SbmlModel.objects.filter(name=self.modelName): document = SbmlDocument() document.readSbmlFromFile(os.path.join(settings.MEDIA_ROOT, os.path.join(self.optimPath, "model.sbml"))) if not document.useCompPackage: file = File(open(os.path.join(settings.MEDIA_ROOT, os.path.join(self.optimPath, "model.sbml")))) new_sbml_model = SbmlModel(project=self.project, name=self.modelName, sbml_file=file) new_sbml_model.save() new_document = SbmlDocument() new_document.readSbmlFromFile(os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file))) new_document.model.setName(self.modelName) for i_param, (xpath, value) in enumerate(self.outputParameters): param = new_document.getByXPath(xpath) param.setValue(value) new_document.writeSbmlToFile(os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file))) else: modifieds = [] for i_param, (xpath, value) in enumerate(self.outputParameters): param = document.getModelInstance().getDefinitionVariableByXPath(xpath) modifieds.append(param[0].getModel().parentDoc) modifieds = list(set(modifieds)) submodel_names = [] i_submodel = 0 while request.POST.get("submodel_%d_name" % i_submodel) is not None: submodel_names.append(request.POST["submodel_%d_name" % i_submodel]) i_submodel += 1 modified_files = {} for i_modified, modified in enumerate(modifieds): file = File(open(os.path.join(settings.MEDIA_ROOT, os.path.join(self.optimPath, modified.documentFilename)), 'rb')) new_sbml_model = SbmlModel(project=self.project, name=submodel_names[i_modified], sbml_file=file) new_sbml_model.save() new_document = SbmlDocument() new_document.readSbmlFromFile(os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file))) new_document.model.setName(str(submodel_names[i_modified])) new_document.writeSbmlToFile(os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file))) modified_files.update({modified.documentFilename: os.path.basename(str(new_sbml_model.sbml_file))}) print(modified_files) print(subdoc.documentFilename for subdoc in document.documentDependencies) renaming = {} for subdoc in document.documentDependencies: if subdoc.documentFilename in modified_files: renaming.update({subdoc.documentFilename: modified_files[subdoc.documentFilename]}) else: renaming.update({subdoc.documentFilename: subdoc.documentFilename}) print(renaming) file = File(open(os.path.join(settings.MEDIA_ROOT, os.path.join(self.optimPath, "model.sbml")), 'rb')) new_sbml_model = SbmlModel(project=self.project, name=self.modelName, sbml_file=file) new_sbml_model.save() new_document = SbmlDocument() new_document.readSbmlFromFile(os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file))) new_document.renameExternalDocumentDependencies(renaming) new_document.model.setName(self.modelName) new_document.writeSbmlToFile(os.path.join(settings.MEDIA_ROOT, str(new_sbml_model.sbml_file)))
def loadFolder(self, request): self.fileUploadForm = DocumentForm(request.POST, request.FILES) if self.fileUploadForm.is_valid(): new_folder = Project(user=request.user) new_folder.save() mkdir(join(settings.MEDIA_ROOT, str(new_folder.folder))) new_archive = CombineArchiveModel(project=new_folder, archive_file=request.FILES['docfile']) new_archive.save() new_combine_archive = CombineArchive() filename = join(settings.MEDIA_ROOT, str(new_archive.archive_file)) t_name = basename(str(new_archive.archive_file)) new_folder.name = t_name.split('.')[0] new_folder.save() try: new_combine_archive.readArchive(filename) for sbml_file in new_combine_archive.getAllSbmls(): t_file = File(open(sbml_file, 'r')) sbml_model = SbmlModel(project=new_folder, sbml_file=t_file) sbml_model.save() try: doc = SbmlDocument() doc.readSbmlFromFile(join(settings.MEDIA_ROOT, str(sbml_model.sbml_file))) sbml_model.name = doc.model.getName() sbml_model.save() except ModelException: name = splitext(str(sbml_model.sbml_file))[0] sbml_model.name = name sbml_model.save() for sedml_filename in new_combine_archive.getAllSedmls(): sedml_archive = SEDMLSimulation(project=new_folder, sedml_file=File(open(sedml_filename, 'r'))) sedml_archive.name = basename(sedml_filename).split('.')[0] sedml_archive.save() # Now everything is in the same folder sedml_doc = SedmlDocument() sedml_doc.readSedmlFromFile(join(settings.MEDIA_ROOT, str(sedml_archive.sedml_file))) sedml_doc.listOfModels.removePaths() sbml_files = sedml_doc.listOfModels.makeLocalSources() for sbml_file in sbml_files: if len(SbmlModel.objects.filter(project=new_folder, sbml_file=join(join(str(new_folder.folder), "models"), basename(sbml_file)))) == 0: t_file = File(open(sbml_file, 'r')) sbml_model = SbmlModel(project=new_folder, sbml_file=t_file) sbml_model.save() try: doc = SbmlDocument() doc.readSbmlFromFile(join(settings.MEDIA_ROOT, str(sbml_model.sbml_file))) sbml_model.name = doc.model.getName() sbml_model.save() except ModelException: name = splitext(str(sbml_model.sbml_file))[0] sbml_model.name = name sbml_model.save() sedml_doc.writeSedmlToFile(join(settings.MEDIA_ROOT, str(sedml_archive.sedml_file))) except CombineException as e: print e.message
def testSpecies(self): settings.MEDIA_ROOT = "/tmp/" user = User.objects.filter(username='******')[0] self.assertEqual(len(Project.objects.filter(user=user)), 1) project = Project.objects.filter(user=user)[0] self.assertEqual(len(SbmlModel.objects.filter(project=project)), 0) c = Client() self.assertTrue(c.login(username='******', password='******')) response_choose_project = c.get('/project/%s/' % project.folder) self.assertRedirects(response_choose_project, '/models/', status_code=302, target_status_code=200) files_folder = join(dirname(__file__), "files") model_filename = join(files_folder, "modelqlzB7i.xml") response_load_model = c.post('/models/', { 'action': 'load_model', 'docfile': open(model_filename, 'r') }) self.assertEqual(response_load_model.status_code, 200) self.assertEqual(len(SbmlModel.objects.filter(project=project)), 1) model = SbmlModel.objects.filter(project=project)[0] sbml_doc = SbmlDocument() sbml_doc.readSbmlFromFile(join(settings.MEDIA_ROOT, str(model.sbml_file))) sbml_model = sbml_doc.getModelInstance() species = sbml_model.listOfSpecies.getBySbmlId('ras_gtp') response_get_species = c.post('/json/get_species/', { 'sbml_id': 'ras_gtp' }) self.assertEqual(response_get_species.status_code, 200) json_response = loads(response_get_species.content) self.assertEqual(json_response[u'id'], sbml_model.listOfSpecies.values().index(species)) self.assertEqual(json_response[u'sbml_id'], species.getSbmlId()) self.assertEqual(json_response[u'name'], species.getName()) self.assertEqual(json_response[u'compartment_name'], species.getCompartment().getName()) self.assertEqual(json_response[u'compartment_id'], sbml_model.listOfCompartments.values().index(species.getCompartment())) self.assertEqual(json_response[u'value'], species.getValue()) self.assertEqual(json_response[u'isConcentration'], 1 if not species.hasOnlySubstanceUnits else 0) self.assertEqual(json_response[u'constant'], 1 if species.constant else 0) self.assertEqual(json_response[u'boundaryCondition'], 1 if species.boundaryCondition else 0) response_choose_project = c.post('/models/', { 'action': 'choose_project', 'project_id': 0 }) self.assertEqual(response_choose_project.status_code, 200) self.assertEqual(response_choose_project.context['project_name'], "Project") response_choose_model = c.post('/edit/species/', { 'action': 'choose_model', 'model_id': 0 }) self.assertEqual(response_choose_model.status_code, 200) self.assertEqual(response_choose_model.context['model_name'], "SOS-Ras-MAPK with n17") response_save_species = c.post('/edit/species/', { 'action': 'save', 'species_id': 2, 'species_name': "New name", 'species_sbml_id': "new_name", 'species_value': 75, 'species_value_type': 0, 'species_compartment': 0, 'species_unit': 2, 'species_constant': "on", 'species_boundary': "on", 'species_sboterm': "", }) self.assertEqual(response_save_species.status_code, 200) sbml_doc = SbmlDocument() sbml_doc.readSbmlFromFile(join(settings.MEDIA_ROOT, str(model.sbml_file))) sbml_model = sbml_doc.getModelInstance() species = sbml_model.listOfSpecies.getBySbmlId('new_name') self.assertTrue(species is not None) self.assertEqual(species.getName(), "New name") self.assertEqual(species.getValue(), 75) self.assertEqual(species.hasOnlySubstanceUnits, True) self.assertEqual(species.constant, True) self.assertEqual(species.boundaryCondition, True) response_delete_species = c.post('/edit/species/', { 'action': 'delete', 'species_id': sbml_model.listOfSpecies.values().index(species) }) self.assertEqual(response_delete_species.status_code, 200) self.assertEqual(response_delete_species.context['getErrors'], ['Species is used in reactions']) response_save_new_species = c.post('/edit/species/', { 'action': 'save', 'species_id': "", 'species_name': "New species", 'species_sbml_id': "new_species", 'species_value': 2500, 'species_value_type': 0, 'species_compartment': 0, 'species_unit': 2, 'species_constant': "off", 'species_boundary': "off", 'species_sboterm': "", }) self.assertEqual(response_save_new_species.status_code, 200) sbml_doc = SbmlDocument() sbml_doc.readSbmlFromFile(join(settings.MEDIA_ROOT, str(model.sbml_file))) sbml_model = sbml_doc.getModelInstance() species = sbml_model.listOfSpecies.getBySbmlId('new_species') self.assertTrue(species != None) self.assertEqual(species.getName(), "New species") self.assertEqual(species.getValue(), 2500) self.assertEqual(species.isConcentration(), False) self.assertEqual(species.getCompartment().getName(), "cell") self.assertEqual(species.constant, False) self.assertEqual(species.boundaryCondition, False) response_delete_species = c.post('/edit/species/', { 'action': 'delete', 'species_id': sbml_model.listOfSpecies.values().index(species) }) self.assertEqual(response_delete_species.status_code, 200) sbml_doc = SbmlDocument() sbml_doc.readSbmlFromFile(join(settings.MEDIA_ROOT, str(model.sbml_file))) sbml_model = sbml_doc.getModelInstance() species = sbml_model.listOfSpecies.getBySbmlId('new_species') self.assertEqual(species, None)
def testCompaartment(self): settings.MEDIA_ROOT = "/tmp/" user = User.objects.filter(username='******')[0] self.assertEqual(len(Project.objects.filter(user=user)), 1) project = Project.objects.filter(user=user)[0] self.assertEqual(len(SbmlModel.objects.filter(project=project)), 0) c = Client() self.assertTrue(c.login(username='******', password='******')) response_choose_project = c.get('/project/%s/' % project.folder) self.assertRedirects(response_choose_project, '/models/', status_code=302, target_status_code=200) files_folder = join(dirname(__file__), "files") model_filename = join(files_folder, "modelqlzB7i.xml") response_load_model = c.post('/models/', { 'action': 'load_model', 'docfile': open(model_filename, 'r') }) self.assertEqual(response_load_model.status_code, 200) self.assertEqual(len(SbmlModel.objects.filter(project=project)), 1) model = SbmlModel.objects.filter(project=project)[0] sbml_doc = SbmlDocument() sbml_doc.readSbmlFromFile( join(settings.MEDIA_ROOT, str(model.sbml_file))) sbml_model = sbml_doc.getModelInstance() compartment = sbml_model.listOfCompartments.getBySbmlId('cell') response_get_compartment = c.post('/json/get_compartment/', { 'sbml_id': 'cell', }) self.assertEqual(response_get_compartment.status_code, 200) json_response = loads(response_get_compartment.content) self.assertEqual( json_response[u'id'], sbml_model.listOfCompartments.values().index(compartment)) self.assertEqual(json_response[u'sbml_id'], compartment.getSbmlId()) self.assertEqual(json_response[u'name'], compartment.getName()) self.assertEqual(json_response[u'value'], compartment.getValue()) self.assertEqual(json_response[u'constant'], 1 if compartment.constant else 0) response_choose_project = c.post('/models/', { 'action': 'choose_project', 'project_id': 0 }) self.assertEqual(response_choose_project.status_code, 200) self.assertEqual(response_choose_project.context['project_name'], "Project") response_choose_model = c.post('/edit/parameters/', { 'action': 'choose_model', 'model_id': 0 }) self.assertEqual(response_choose_model.status_code, 200) self.assertEqual(response_choose_model.context['model_name'], "SOS-Ras-MAPK with n17") response_save_compartment = c.post( '/edit/compartments/', { 'action': 'save', 'compartment_id': sbml_model.listOfCompartments.values().index(compartment), 'compartment_name': "New name", 'compartment_sbml_id': "new_name", 'compartment_size': 75, 'compartment_unit': 2, 'compartment_constant': "on", 'compartment_sboterm': "", }) self.assertEqual(response_save_compartment.status_code, 200) self.assertEqual(response_save_compartment.context['getErrors'], []) sbml_doc = SbmlDocument() sbml_doc.readSbmlFromFile( join(settings.MEDIA_ROOT, str(model.sbml_file))) sbml_model = sbml_doc.getModelInstance() compartment = sbml_model.listOfCompartments.getBySbmlId('new_name') self.assertTrue(compartment is not None) self.assertEqual(compartment.getName(), "New name") self.assertEqual(compartment.getValue(), 75) self.assertEqual(compartment.constant, True) self.assertEqual(compartment.getUnits(), sbml_model.listOfUnitDefinitions[2]) response_delete_compartment = c.post( '/edit/compartments/', { 'action': 'delete', 'compartment_id': sbml_model.listOfCompartments.values().index(compartment) }) self.assertEqual(response_delete_compartment.status_code, 200) self.assertEqual(response_delete_compartment.context['getErrors'], ['Compartment contains 25 species']) response_save_new_compartment = c.post( '/edit/compartments/', { 'action': 'save', 'compartment_id': "", 'compartment_name': "New compartment", 'compartment_sbml_id': "new_compartment", 'compartment_size': 75, 'compartment_unit': "", 'compartment_constant': "on", 'compartment_sboterm': "", }) self.assertEqual(response_save_new_compartment.status_code, 200) sbml_doc = SbmlDocument() sbml_doc.readSbmlFromFile( join(settings.MEDIA_ROOT, str(model.sbml_file))) sbml_model = sbml_doc.getModelInstance() compartment = sbml_model.listOfCompartments.getBySbmlId( 'new_compartment') self.assertTrue(compartment != None) self.assertEqual(compartment.getName(), "New compartment") self.assertEqual(compartment.getValue(), 75) self.assertEqual(compartment.getUnits(), None) self.assertEqual(compartment.constant, True) response_delete_compartment = c.post( '/edit/compartments/', { 'action': 'delete', 'compartment_id': sbml_model.listOfCompartments.values().index(compartment) }) self.assertEqual(response_delete_compartment.status_code, 200) self.assertEqual(response_delete_compartment.context['getErrors'], [])
def testReactions(self): settings.MEDIA_ROOT = "/tmp/" user = User.objects.filter(username='******')[0] self.assertEqual(len(Project.objects.filter(user=user)), 1) project = Project.objects.filter(user=user)[0] self.assertEqual(len(SbmlModel.objects.filter(project=project)), 0) c = Client() self.assertTrue(c.login(username='******', password='******')) response_choose_project = c.get('/project/%s/' % project.folder) self.assertRedirects(response_choose_project, '/models/', status_code=302, target_status_code=200) files_folder = join(dirname(__file__), "files") model_filename = join(files_folder, "modelqlzB7i.xml") response_load_model = c.post('/models/', { 'action': 'load_model', 'docfile': open(model_filename, 'r') }) self.assertEqual(response_load_model.status_code, 200) self.assertEqual(len(SbmlModel.objects.filter(project=project)), 1) model = SbmlModel.objects.filter(project=project)[0] sbml_doc = SbmlDocument() sbml_doc.readSbmlFromFile( join(settings.MEDIA_ROOT, str(model.sbml_file))) sbml_model = sbml_doc.getModelInstance() reaction = sbml_model.listOfReactions.getBySbmlId('reaction_2') response_choose_project = c.post('/models/', { 'action': 'choose_project', 'project_id': 0 }) self.assertEqual(response_choose_project.status_code, 200) self.assertEqual(response_choose_project.context['project_name'], "Project") response_choose_model = c.post('/edit/reactions/', { 'action': 'choose_model', 'model_id': 0 }) self.assertEqual(response_choose_model.status_code, 200) self.assertEqual(response_choose_model.context['model_name'], "SOS-Ras-MAPK with n17") self.assertEqual([ t_reaction.getReactionDescription() for t_reaction in response_choose_model.context['list_of_reactions'] ], [ t_reaction.getReactionDescription() for t_reaction in sbml_model.listOfReactions.values() ]) response_get_reaction = c.post('/json/get_reaction/', {'sbml_id': 'reaction_2'}) self.assertEqual(response_get_reaction.status_code, 200) json_response = loads(response_get_reaction.content) self.assertEqual(json_response[u'id'], sbml_model.listOfReactions.values().index(reaction)) self.assertEqual(json_response[u'sbml_id'], reaction.getSbmlId()) self.assertEqual(json_response[u'name'], reaction.getName()) self.assertEqual(json_response[u'kinetic_law'], reaction.kineticLaw.getPrettyPrintMathFormula()) self.assertEqual(json_response[u'reaction_type'], reaction.getReactionType()) self.assertEqual(json_response[u'reaction_type_name'], KineticLaw.reactionTypes[reaction.getReactionType()]) self.assertEqual(json_response[u'reversible'], reaction.reversible) self.assertEqual(json_response[u'list_of_reactants'], [[ sbml_model.listOfSpecies.index(reactant.getSpecies()), reactant.stoichiometry.getPrettyPrintMathFormula() ] for reactant in reaction.listOfReactants.values()]) self.assertEqual(json_response[u'list_of_modifiers'], [[ sbml_model.listOfSpecies.index(modifier.getSpecies()), modifier.stoichiometry.getPrettyPrintMathFormula() ] for modifier in reaction.listOfModifiers.values()]) self.assertEqual(json_response[u'list_of_products'], [[ sbml_model.listOfSpecies.index(product.getSpecies()), product.stoichiometry.getPrettyPrintMathFormula() ] for product in reaction.listOfProducts.values()])