Пример #1
0
    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()
Пример #2
0
    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()
Пример #4
0
    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))
Пример #5
0
    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()
Пример #6
0
    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())
Пример #7
0
    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)))
Пример #8
0
    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)
Пример #9
0
    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()]
Пример #10
0
	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 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)))
Пример #12
0
	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
Пример #13
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)
Пример #14
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'], [])
Пример #15
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()])