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)))
Пример #3
0
    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'], [])
Пример #4
0
	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)
Пример #5
0
    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()])