def test_Date_copyConstructor(self): date = libsbml.Date(2005, 12, 30, 12, 15, 45, 1, 2, 0) self.assert_(date.getMonth() == 12) self.assert_(date.getSecond() == 45) date2 = libsbml.Date(date) self.assert_(date2.getMonth() == 12) self.assert_(date2.getSecond() == 45) date2 = None date = None pass
def test_Date_assignmentOperator(self): date = libsbml.Date(2005, 12, 30, 12, 15, 45, 1, 2, 0) self.assert_(date.getMonth() == 12) self.assert_(date.getSecond() == 45) date2 = libsbml.Date() date2 = date self.assert_(date2.getMonth() == 12) self.assert_(date2.getSecond() == 45) date2 = None date = None pass
def test_Date_getDateAsString(self): dd = "2005-02-02T14:56:11Z" date = libsbml.Date(dd) self.assert_(date != None) self.assert_(date.getYear() == 2005) self.assert_(date.getMonth() == 2) self.assert_(date.getDay() == 2) self.assert_(date.getHour() == 14) self.assert_(date.getMinute() == 56) self.assert_(date.getSecond() == 11) self.assert_(date.getSignOffset() == 0) self.assert_(date.getHoursOffset() == 0) self.assert_(date.getMinutesOffset() == 0) date.setYear(2012) date.setMonth(3) date.setDay(28) date.setHour(23) date.setMinute(4) date.setSecond(32) date.setSignOffset(1) date.setHoursOffset(2) date.setMinutesOffset(32) self.assert_(("2012-03-28T23:04:32+02:32" == date.getDateAsString())) _dummyList = [date] _dummyList[:] = [] del _dummyList pass
def test_Date_setDateAsString(self): date = libsbml.Date(2007, 10, 23, 14, 15, 16, 1, 3, 0) self.assert_(date != None) i = date.setDateAsString("20081-12-30T12:15:45+02:00") self.assert_(i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE) self.assert_(("2007-10-23T14:15:16+03:00" == date.getDateAsString())) i = date.setDateAsString("200-12-30T12:15:45+02:00") self.assert_(i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE) self.assert_(("2007-10-23T14:15:16+03:00" == date.getDateAsString())) i = date.setDateAsString("") self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS) self.assert_(("2000-01-01T00:00:00Z" == date.getDateAsString())) i = date.setDateAsString("2008-12-30T12:15:45+02:00") self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS) self.assert_(date.getYear() == 2008) self.assert_(date.getMonth() == 12) self.assert_(date.getDay() == 30) self.assert_(date.getHour() == 12) self.assert_(date.getMinute() == 15) self.assert_(date.getSecond() == 45) self.assert_(date.getSignOffset() == 1) self.assert_(date.getHoursOffset() == 2) self.assert_(date.getMinutesOffset() == 0) _dummyList = [date] _dummyList[:] = [] del _dummyList pass
def test_Date_setters(self): date = libsbml.Date(2005, 12, 30, 12, 15, 45, 1, 2, 0) self.assert_(date != None) date.setYear(2012) date.setMonth(3) date.setDay(28) date.setHour(23) date.setMinute(4) date.setSecond(32) date.setSignOffset(1) date.setHoursOffset(2) date.setMinutesOffset(32) self.assert_(date.getYear() == 2012) self.assert_(date.getMonth() == 3) self.assert_(date.getDay() == 28) self.assert_(date.getHour() == 23) self.assert_(date.getMinute() == 4) self.assert_(date.getSecond() == 32) self.assert_(date.getSignOffset() == 1) self.assert_(date.getHoursOffset() == 2) self.assert_(date.getMinutesOffset() == 32) self.assert_(("2012-03-28T23:04:32+02:32" == date.getDateAsString())) _dummyList = [date] _dummyList[:] = [] del _dummyList pass
def test_L3_Species_ModelHistory(self): (self.S).setMetaId("_3") history = libsbml.ModelHistory() i = (self.S).setModelHistory(history) self.assert_(i == libsbml.LIBSBML_INVALID_OBJECT) self.assertEqual(False, (self.S).isSetModelHistory()) mc = libsbml.ModelCreator() date = libsbml.Date(2005, 12, 30, 12, 15, 45, 1, 2, 0) mc.setFamilyName("Keating") mc.setGivenName("Sarah") mc.setEmail("*****@*****.**") mc.setOrganisation("UH") history.addCreator(mc) history.setCreatedDate(date) history.setModifiedDate(date) i = (self.S).setModelHistory(history) self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS) self.assertEqual(True, (self.S).isSetModelHistory()) i = (self.S).unsetModelHistory() self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS) self.assertEqual(False, (self.S).isSetModelHistory()) self.assert_((self.S).getModelHistory() == None) _dummyList = [history] _dummyList[:] = [] del _dummyList pass
def test_RDFAnnotation2_modelWithHistoryWithCharacterReference(self): h = libsbml.ModelHistory() c = libsbml.ModelCreator() c.setFamilyName("Dräger") c.setGivenName("Andreas") h.addCreator(c) d = libsbml.Date(2005, 2, 2, 14, 56, 11) h.setCreatedDate(d) h.addModifiedDate(d) self.m2.unsetModelHistory() self.m2.setModelHistory(h) ann = libsbml.RDFAnnotationParser.parseModelHistory(self.m2) expected = wrapString( "<annotation>\n" + " <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:vCard=\"http://www.w3.org/2001/vcard-rdf/3.0#\" xmlns:bqbiol=\"http://biomodels.net/biology-qualifiers/\" xmlns:bqmodel=\"http://biomodels.net/model-qualifiers/\">\n" + " <rdf:Description rdf:about=\"#_000001\">\n" + " <dc:creator rdf:parseType=\"Resource\">\n" + " <rdf:Bag>\n" + " <rdf:li rdf:parseType=\"Resource\">\n" + " <vCard:N rdf:parseType=\"Resource\">\n" + " <vCard:Family>Dräger</vCard:Family>\n" + " <vCard:Given>Andreas</vCard:Given>\n" + " </vCard:N>\n" + " </rdf:li>\n" + " </rdf:Bag>\n" + " </dc:creator>\n" + " <dcterms:created rdf:parseType=\"Resource\">\n" + " <dcterms:W3CDTF>2005-02-02T14:56:11Z</dcterms:W3CDTF>\n" + " </dcterms:created>\n" + " <dcterms:modified rdf:parseType=\"Resource\">\n" + " <dcterms:W3CDTF>2005-02-02T14:56:11Z</dcterms:W3CDTF>\n" + " </dcterms:modified>\n" + " </rdf:Description>\n" + " </rdf:RDF>\n" + "</annotation>") self.assertEqual(True, self.equals(expected, ann.toXMLString())) pass
def test_Model_setgetModelHistory(self): self.M.setMetaId("_001") history = libsbml.ModelHistory() mc = libsbml.ModelCreator() date = libsbml.Date(2005, 12, 30, 12, 15, 45, 1, 2, 0) mc.setFamilyName("Keating") mc.setGivenName("Sarah") mc.setEmail("*****@*****.**") mc.setOrganisation("UH") history.addCreator(mc) history.setCreatedDate(date) history.setModifiedDate(date) self.assert_(self.M.isSetModelHistory() == False) self.M.setModelHistory(history) self.assert_(self.M.isSetModelHistory() == True) newMC = history.getCreator(0) self.assert_(newMC != None) self.assert_(("Keating" == newMC.getFamilyName())) self.assert_(("Sarah" == newMC.getGivenName())) self.assert_(("*****@*****.**" == newMC.getEmail())) self.assert_(("UH" == newMC.getOrganisation())) self.M.unsetModelHistory() self.assert_(self.M.isSetModelHistory() == False) _dummyList = [history] _dummyList[:] = [] del _dummyList _dummyList = [mc] _dummyList[:] = [] del _dummyList pass
def date_now(): """ Get current time stamp for history. :return: current libsbml Date """ time = datetime.datetime.now() timestr = time.strftime('%Y-%m-%dT%H:%M:%S') return libsbml.Date(timestr)
def test_Date_clone(self): date = libsbml.Date(2005, 12, 30, 12, 15, 45, 1, 2, 0) self.assert_(date.getMonth() == 12) self.assert_(date.getSecond() == 45) date2 = date.clone() self.assert_(date2.getMonth() == 12) self.assert_(date2.getSecond() == 45) date2 = None date = None pass
def test_ModelHistory_addModifiedDate(self): history = libsbml.ModelHistory() self.assert_(history != None) self.assert_(history.isSetModifiedDate() == False) self.assert_(history.getNumModifiedDates() == 0) date = libsbml.Date(2005, 12, 30, 12, 15, 45, 1, 2, 0) history.addModifiedDate(date) _dummyList = [date] _dummyList[:] = [] del _dummyList self.assert_(history.getNumModifiedDates() == 1) self.assert_(history.isSetModifiedDate() == True) newdate = history.getListModifiedDates().get(0) self.assert_(newdate.getYear() == 2005) self.assert_(newdate.getMonth() == 12) self.assert_(newdate.getDay() == 30) self.assert_(newdate.getHour() == 12) self.assert_(newdate.getMinute() == 15) self.assert_(newdate.getSecond() == 45) self.assert_(newdate.getSignOffset() == 1) self.assert_(newdate.getHoursOffset() == 2) self.assert_(newdate.getMinutesOffset() == 0) date1 = libsbml.Date(2008, 11, 2, 16, 42, 40, 1, 2, 0) history.addModifiedDate(date1) _dummyList = [date1] _dummyList[:] = [] del _dummyList self.assert_(history.getNumModifiedDates() == 2) self.assert_(history.isSetModifiedDate() == True) newdate1 = history.getModifiedDate(1) self.assert_(newdate1.getYear() == 2008) self.assert_(newdate1.getMonth() == 11) self.assert_(newdate1.getDay() == 2) self.assert_(newdate1.getHour() == 16) self.assert_(newdate1.getMinute() == 42) self.assert_(newdate1.getSecond() == 40) self.assert_(newdate1.getSignOffset() == 1) self.assert_(newdate1.getHoursOffset() == 2) self.assert_(newdate1.getMinutesOffset() == 0) _dummyList = [history] _dummyList[:] = [] del _dummyList pass
def test_ModelHistory_setModifiedDate2(self): mh = libsbml.ModelHistory() self.assert_( mh != None ) date = libsbml.Date(200,13,76,56,89,90,0,0,0) i = mh.setModifiedDate(date) self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT ) self.assert_( mh.isSetModifiedDate() == False ) _dummyList = [ date ]; _dummyList[:] = []; del _dummyList _dummyList = [ mh ]; _dummyList[:] = []; del _dummyList pass
def test_ModelHistory_setCreatedDate2(self): mh = libsbml.ModelHistory() self.assert_( mh != None ) date = libsbml.Date("Jan 12") i = mh.setCreatedDate(date) self.assert_( i == libsbml.LIBSBML_INVALID_OBJECT ) self.assert_( mh.isSetCreatedDate() == False ) _dummyList = [ date ]; _dummyList[:] = []; del _dummyList _dummyList = [ mh ]; _dummyList[:] = []; del _dummyList pass
def change_modified_date(sbml): """ Change SBML modified date to now. """ history = sbml.getModel().getModelHistory() if history: history.setModifiedDate(libsbml.Date(w3c_time())) # remove all but final modified date while history.getListModifiedDates().getSize() > 1: history.getListModifiedDates().remove(0)
def test_Date_setHoursOffset(self): date = libsbml.Date(2005, 12, 30, 12, 15, 45, 1, 2, 0) self.assert_(date != None) i = date.setHoursOffset(434) self.assert_(i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE) self.assert_(date.getHoursOffset() == 0) i = date.setHoursOffset(11) self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS) self.assert_(date.getHoursOffset() == 11) self.assert_(("2005-12-30T12:15:45+11:00" == date.getDateAsString())) _dummyList = [date] _dummyList[:] = [] del _dummyList pass
def test_Validation_ModelHistory3(self): mh = libsbml.ModelHistory() self.assert_(mh != None) self.assertEqual(False, (mh.hasRequiredAttributes())) date = libsbml.Date(2007, 12, 30, 12, 15, 45, 1, 2, 0) mh.setCreatedDate(date) self.assertEqual(False, (mh.hasRequiredAttributes())) mh.setModifiedDate(date) self.assertEqual(False, (mh.hasRequiredAttributes())) mc = libsbml.ModelCreator() mc.setFamilyName("Keating") mh.addCreator(mc) self.assertEqual(False, (mh.hasRequiredAttributes())) mh = None pass
def test_ModelHistory_setModifiedDate1(self): mh = libsbml.ModelHistory() self.assert_( mh != None ) date = libsbml.Date("2005-12-30T12:15:32+02:00") i = mh.setModifiedDate(date) self.assert_( i == libsbml.LIBSBML_OPERATION_SUCCESS ) self.assert_( mh.isSetModifiedDate() == True ) self.assert_( date != mh.getModifiedDate() ) dateChar = mh.getModifiedDate().getDateAsString() self.assert_(( "2005-12-30T12:15:32+02:00" == dateChar )) i = mh.setModifiedDate(None) self.assert_( i == libsbml.LIBSBML_OPERATION_FAILED ) self.assert_( mh.isSetModifiedDate() == True ) _dummyList = [ date ]; _dummyList[:] = []; del _dummyList _dummyList = [ mh ]; _dummyList[:] = []; del _dummyList pass
def test_Date_create(self): date = libsbml.Date(2005, 12, 30, 12, 15, 45, 1, 2, 0) self.assert_(date != None) self.assert_(date.getYear() == 2005) self.assert_(date.getMonth() == 12) self.assert_(date.getDay() == 30) self.assert_(date.getHour() == 12) self.assert_(date.getMinute() == 15) self.assert_(date.getSecond() == 45) self.assert_(date.getSignOffset() == 1) self.assert_(date.getHoursOffset() == 2) self.assert_(date.getMinutesOffset() == 0) _dummyList = [date] _dummyList[:] = [] del _dummyList pass
def test_Date_setDay(self): date = libsbml.Date(2005, 2, 12, 12, 15, 45, 1, 2, 0) self.assert_(date != None) i = date.setDay(29) self.assert_(i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE) self.assert_(date.getDay() == 1) i = date.setDay(31) self.assert_(i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE) self.assert_(date.getDay() == 1) i = date.setDay(15) self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS) self.assert_(date.getDay() == 15) self.assert_(("2005-02-15T12:15:45+02:00" == date.getDateAsString())) _dummyList = [date] _dummyList[:] = [] del _dummyList pass
def test_Date_setMinute(self): date = libsbml.Date(2005, 12, 30, 12, 15, 45, 1, 2, 0) self.assert_(date != None) i = date.setMinute(434) self.assert_(i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE) self.assert_(date.getMinute() == 0) i = date.setMinute(12121) self.assert_(i == libsbml.LIBSBML_INVALID_ATTRIBUTE_VALUE) self.assert_(date.getMinute() == 0) i = date.setMinute(32) self.assert_(i == libsbml.LIBSBML_OPERATION_SUCCESS) self.assert_(date.getMinute() == 32) self.assert_(("2005-12-30T12:32:45+02:00" == date.getDateAsString())) _dummyList = [date] _dummyList[:] = [] del _dummyList pass
def test_Date_createFromString(self): dd = "2012-12-02T14:56:11Z" date = libsbml.Date(dd) self.assert_(date != None) self.assert_(("2012-12-02T14:56:11Z" == date.getDateAsString())) self.assert_(date.getYear() == 2012) self.assert_(date.getMonth() == 12) self.assert_(date.getDay() == 2) self.assert_(date.getHour() == 14) self.assert_(date.getMinute() == 56) self.assert_(date.getSecond() == 11) self.assert_(date.getSignOffset() == 0) self.assert_(date.getHoursOffset() == 0) self.assert_(date.getMinutesOffset() == 0) _dummyList = [date] _dummyList[:] = [] del _dummyList pass
def test_RDFAnnotation2_modelWithHistoryAndCVTerms(self): h = libsbml.ModelHistory() c = libsbml.ModelCreator() c.setFamilyName("Keating") c.setGivenName("Sarah") h.addCreator(c) d = libsbml.Date(2008, 11, 17, 18, 37, 0, 0, 0, 0) h.setCreatedDate(d) h.setModifiedDate(d) self.m2.unsetModelHistory() self.m2.setModelHistory(h) cv = libsbml.CVTerm() cv.setQualifierType(libsbml.BIOLOGICAL_QUALIFIER) cv.setBiologicalQualifierType(libsbml.BQB_IS_VERSION_OF) cv.addResource("http://www.geneontology.org/#GO:0005892") self.m2.addCVTerm(cv) ann = libsbml.RDFAnnotationParser.parseModelHistory(self.m2) expected = wrapString( "<annotation>\n" + " <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:vCard=\"http://www.w3.org/2001/vcard-rdf/3.0#\" xmlns:bqbiol=\"http://biomodels.net/biology-qualifiers/\" xmlns:bqmodel=\"http://biomodels.net/model-qualifiers/\">\n" + " <rdf:Description rdf:about=\"#_000001\">\n" + " <dc:creator rdf:parseType=\"Resource\">\n" + " <rdf:Bag>\n" + " <rdf:li rdf:parseType=\"Resource\">\n" + " <vCard:N rdf:parseType=\"Resource\">\n" + " <vCard:Family>Keating</vCard:Family>\n" + " <vCard:Given>Sarah</vCard:Given>\n" + " </vCard:N>\n" + " </rdf:li>\n" + " </rdf:Bag>\n" + " </dc:creator>\n" + " <dcterms:created rdf:parseType=\"Resource\">\n" + " <dcterms:W3CDTF>2008-11-17T18:37:00Z</dcterms:W3CDTF>\n" + " </dcterms:created>\n" + " <dcterms:modified rdf:parseType=\"Resource\">\n" + " <dcterms:W3CDTF>2008-11-17T18:37:00Z</dcterms:W3CDTF>\n" + " </dcterms:modified>\n" + " <bqbiol:isVersionOf>\n" + " <rdf:Bag>\n" + " <rdf:li rdf:resource=\"http://www.geneontology.org/#GO:0005892\"/>\n" + " </rdf:Bag>\n" + " </bqbiol:isVersionOf>\n" + " </rdf:Description>\n" + " </rdf:RDF>\n" + "</annotation>") if (ann != None): self.assertEqual(True, self.equals(expected, ann.toXMLString())) pass pass pass
def _create_history(creators: Union[List[Any], Dict[Any, Any]], set_timestamps: bool = False) -> libsbml.ModelHistory: """Create the model history. Sets the create and modified date to the current time. Creators are a list or dictionary with values as :param creators: :param set_timestamps: :return: """ h = libsbml.ModelHistory() items: List[Any] if isinstance(creators, dict): items = list(creators.values()) else: items = creators # add all creators for creator in items: c = libsbml.ModelCreator() if creator.familyName: c.setFamilyName(creator.familyName) if creator.givenName: c.setGivenName(creator.givenName) if creator.email: c.setEmail(creator.email) if creator.organization: c.setOrganization(creator.organization) check(h.addCreator(c), "add creator") # create time is now if set_timestamps: datetime = date_now() else: datetime = libsbml.Date("1900-01-01T00:00:00") check(h.setCreatedDate(datetime), "set creation date") check(h.setModifiedDate(datetime), "set modified date") return h
def test_ModelHistory_copyConstructor(self): mh = libsbml.ModelHistory() mc = libsbml.ModelCreator() mc.setFamilyName("Keating") mc.setGivenName("Sarah") mc.setEmail("*****@*****.**") mh.addCreator(mc) mc = None date = libsbml.Date(2005, 12, 30, 12, 15, 45, 1, 2, 0) mh.setCreatedDate(date) date = None self.assert_(mh.getCreatedDate().getMonth() == 12) self.assert_(mh.getCreatedDate().getSecond() == 45) self.assert_(mh.getCreator(0).getFamilyName() == "Keating") mh2 = libsbml.ModelHistory(mh) self.assert_(mh2.getCreatedDate().getMonth() == 12) self.assert_(mh2.getCreatedDate().getSecond() == 45) self.assert_(mh2.getCreator(0).getFamilyName() == "Keating") mh2 = None mh = None pass
def test_ModelHistory_setModifiedDate(self): history = libsbml.ModelHistory() self.assert_(history != None) self.assert_(history.isSetModifiedDate() == False) date = libsbml.Date(2005, 12, 30, 12, 15, 45, 1, 2, 0) history.setModifiedDate(date) _dummyList = [date] _dummyList[:] = [] del _dummyList self.assert_(history.isSetModifiedDate() == True) newdate = history.getModifiedDate() self.assert_(newdate.getYear() == 2005) self.assert_(newdate.getMonth() == 12) self.assert_(newdate.getDay() == 30) self.assert_(newdate.getHour() == 12) self.assert_(newdate.getMinute() == 15) self.assert_(newdate.getSecond() == 45) self.assert_(newdate.getSignOffset() == 1) self.assert_(newdate.getHoursOffset() == 2) self.assert_(newdate.getMinutesOffset() == 0) _dummyList = [history] _dummyList[:] = [] del _dummyList pass
def test_Validation_Date4(self): date = libsbml.Date(2007, 12, 30, 12, 15, 45, 1, 2, 0) self.assert_(date != None) self.assertEqual(True, date.representsValidDate()) date = None pass
def test_Validation_Date3(self): date = libsbml.Date("Jan 12") self.assert_(date != None) self.assertEqual(False, (date.representsValidDate())) date = None pass
def write_sbml_ec_model( ec_model: Model, filename: str, f_replace=F_REPLACE, units=True, group_untyped_proteins: bool = True, ): """Write cobra model to filename. Enzyme constraint changes: proteins are written as metabolites with initialAmount. The created model is SBML level 3 version 1 (L1V3) with fbc package v2 (fbc-v2). If the given filename ends with the suffix ".gz" (for example, "myfile.xml.gz"), libSBML assumes the caller wants the file to be written compressed in gzip format. Similarly, if the given filename ends with ".zip" or ".bz2", libSBML assumes the caller wants the file to be compressed in zip or bzip2 format (respectively). Files whose names lack these suffixes will be written uncompressed. Special considerations for the zip format: If the given filename ends with ".zip", the file placed in the zip archive will have the suffix ".xml" or ".sbml". For example, the file in the zip archive will be named "test.xml" if the given filename is "test.xml.zip" or "test.zip". Similarly, the filename in the archive will be "test.sbml" if the given filename is "test.sbml.zip". Warnings -------- If :meth:`geckopy.Model.constrain_pool()` was called on the model, the protein pool (exchange and metabolite) will be ignored and NOT written to the SBML file. A `UserWarning` appears in this case. Parameters ---------- cobra_model : geckopy.Model Model instance which is written to SBML filename : string path to which the model is written f_replace: dict of replacement functions for id replacement group_untyped_proteins: bool if True (default) the proteins whose id is not compliant with Uniprot and which are not part of the :code:`Protein` group will be added to it. This is an inplace operation! """ cobra_model = ec_model protein_pool_metabolite = None protein_pool_exchange = None if hasattr(ec_model, "protein_pool_exchange"): warnings.warn( "Protein pool will not be serialized to the SBML document.") protein_pool_metabolite = ec_model.common_protein_pool protein_pool_exchange = ec_model.protein_pool_exchange if f_replace is None: f_replace = {} if group_untyped_proteins: prot_to_add = [ prot.id for prot in cobra_model.proteins if not PROT_PATTERN.match(prot.id) ] group_proteins(ec_model, prot_to_add) sbml_ns = libsbml.SBMLNamespaces(3, 1) # SBML L3V1 sbml_ns.addPackageNamespace("fbc", 2) # fbc-v2 doc: libsbml.SBMLDocument = libsbml.SBMLDocument(sbml_ns) doc.setPackageRequired("fbc", False) doc.setSBOTerm(SBO_FBA_FRAMEWORK) model: libsbml.Model = doc.createModel() model_fbc: libsbml.FbcModelPlugin = model.getPlugin("fbc") model_fbc.setStrict(True) if cobra_model.id is not None: model.setId(cobra_model.id) model.setMetaId("meta_" + cobra_model.id) else: model.setMetaId("meta_model") if cobra_model.name is not None: model.setName(cobra_model.name) # for parsing annotation corresponding to the model _sbase_annotations(model, cobra_model.annotation) # for parsing notes corresponding to the model _sbase_notes_dict(model, cobra_model.notes) # Meta information (ModelHistory) related to SBMLDocument if hasattr(cobra_model, "_sbml"): meta = cobra_model._sbml if "annotation" in meta: _sbase_annotations(doc, meta["annotation"]) if "notes" in meta: _sbase_notes_dict(doc, meta["notes"]) history: libsbml.ModelHistory = libsbml.ModelHistory() if "created" in meta and meta["created"]: history.setCreatedDate(meta["created"]) else: time = datetime.datetime.now() timestr = time.strftime("%Y-%m-%dT%H:%M:%S") date = libsbml.Date(timestr) _check(history.setCreatedDate(date), "set creation date") _check(history.setModifiedDate(date), "set modified date") if "creators" in meta: for cobra_creator in meta["creators"]: # noqa: E501 creator: libsbml.ModelCreator = libsbml.ModelCreator() if cobra_creator.get("familyName", None): creator.setFamilyName(cobra_creator["familyName"]) if cobra_creator.get("givenName", None): creator.setGivenName(cobra_creator["givenName"]) if cobra_creator.get("organisation", None): creator.setOrganisation(cobra_creator["organisation"]) if cobra_creator.get("email", None): creator.setEmail(cobra_creator["email"]) _check(history.addCreator(creator), "adding creator to ModelHistory.") # TODO: Will be implemented as part of # https://github.com/opencobra/cobrapy/issues/810 # _check(model.setModelHistory(history), 'set model history') # Units if units: flux_udef = model.createUnitDefinition() # type:libsbml.UnitDefinition flux_udef.setId(UNITS_FLUX[0]) for u in UNITS_FLUX[1]: unit = flux_udef.createUnit() # type: libsbml.Unit unit.setKind(u.kind) unit.setExponent(u.exponent) unit.setScale(u.scale) unit.setMultiplier(u.multiplier) # minimum and maximum value from model if len(cobra_model.reactions) > 0: min_value = min(cobra_model.reactions.list_attr("lower_bound")) max_value = max(cobra_model.reactions.list_attr("upper_bound")) else: min_value = config.lower_bound max_value = config.upper_bound _create_parameter(model, pid=LOWER_BOUND_ID, value=min_value, sbo=SBO_DEFAULT_FLUX_BOUND) _create_parameter(model, pid=UPPER_BOUND_ID, value=max_value, sbo=SBO_DEFAULT_FLUX_BOUND) _create_parameter(model, pid=ZERO_BOUND_ID, value=0, sbo=SBO_DEFAULT_FLUX_BOUND) _create_parameter(model, pid=BOUND_MINUS_INF, value=-float("Inf"), sbo=SBO_DEFAULT_FLUX_BOUND) _create_parameter(model, pid=BOUND_PLUS_INF, value=float("Inf"), sbo=SBO_DEFAULT_FLUX_BOUND) # Compartments for cid, name in cobra_model.compartments.items(): compartment: libsbml.Compartment = model.createCompartment() compartment.setId(cid) compartment.setName(name) compartment.setConstant(True) # Species for metabolite in cobra_model.metabolites: if metabolite == protein_pool_metabolite: continue specie: libsbml.Species = model.createSpecies() specie.setId(f_replace[F_SPECIE_REV](metabolite.id) if f_replace and F_SPECIE_REV in f_replace else metabolite.id) specie.setConstant(False) specie.setBoundaryCondition(False) specie.setHasOnlySubstanceUnits(False) specie.setName(metabolite.name) specie.setCompartment(metabolite.compartment) s_fbc: libsbml.FbcSpeciesPlugin = specie.getPlugin("fbc") if metabolite.charge is not None: s_fbc.setCharge(int(metabolite.charge)) if metabolite.formula is not None: s_fbc.setChemicalFormula(metabolite.formula) _sbase_annotations(specie, metabolite.annotation) _sbase_notes_dict(specie, metabolite.notes) for metabolite in ec_model.proteins: specie: libsbml.Species = model.createSpecies() specie.setId(f_replace[F_SPECIE_REV](metabolite.id) if f_replace and F_SPECIE_REV in f_replace else metabolite.id) specie.setConstant(False) specie.setBoundaryCondition(False) specie.setHasOnlySubstanceUnits(False) specie.setName(metabolite.name) specie.setCompartment(metabolite.compartment) if isinstance(metabolite.concentration, numbers.Number) and not isnan(metabolite.concentration): specie.setInitialAmount(metabolite.concentration) s_fbc: libsbml.FbcSpeciesPlugin = specie.getPlugin("fbc") if metabolite.charge is not None: s_fbc.setCharge(int(metabolite.charge)) if metabolite.formula is not None: s_fbc.setChemicalFormula(metabolite.formula) _sbase_annotations(specie, metabolite.annotation) # Genes for cobra_gene in cobra_model.genes: gp: libsbml.GeneProduct = model_fbc.createGeneProduct() gid = cobra_gene.id if f_replace and F_GENE_REV in f_replace: gid = f_replace[F_GENE_REV](gid) gp.setId(gid) gname = cobra_gene.name if gname is None or len(gname) == 0: gname = gid gp.setName(gname) gp.setLabel(gid) _sbase_annotations(gp, cobra_gene.annotation) _sbase_notes_dict(gp, cobra_gene.notes) # Objective objective: libsbml.Objective = model_fbc.createObjective() objective.setId("obj") objective.setType(SHORT_LONG_DIRECTION[cobra_model.objective.direction]) model_fbc.setActiveObjectiveId("obj") # Reactions reaction_coefficients = linear_reaction_coefficients(cobra_model) for cobra_reaction in cobra_model.reactions: if cobra_reaction == protein_pool_exchange: continue rid = cobra_reaction.id if f_replace and F_REACTION_REV in f_replace: rid = f_replace[F_REACTION_REV](rid) reaction: libsbml.Reaction = model.createReaction() reaction.setId(rid) reaction.setName(cobra_reaction.name) reaction.setFast(False) reaction.setReversible((cobra_reaction.lower_bound < 0)) _sbase_annotations(reaction, cobra_reaction.annotation) _sbase_notes_dict(reaction, cobra_reaction.notes) # stoichiometry for metabolite, stoichiometry in cobra_reaction._metabolites.items(): sid = metabolite.id if f_replace and F_SPECIE_REV in f_replace: sid = f_replace[F_SPECIE_REV](sid) if stoichiometry < 0: sref = (reaction.createReactant() ) # noqa: E501 type: libsbml.SpeciesReference sref.setSpecies(sid) sref.setStoichiometry(-stoichiometry) sref.setConstant(True) else: sref = (reaction.createProduct() ) # noqa: E501 type: libsbml.SpeciesReference sref.setSpecies(sid) sref.setStoichiometry(stoichiometry) sref.setConstant(True) # bounds r_fbc: libsbml.FbcReactionPlugin = reaction.getPlugin("fbc") r_fbc.setLowerFluxBound( _create_bound( model, cobra_reaction, "lower_bound", f_replace=f_replace, units=units, flux_udef=flux_udef, )) r_fbc.setUpperFluxBound( _create_bound( model, cobra_reaction, "upper_bound", f_replace=f_replace, units=units, flux_udef=flux_udef, )) # GPR gpr = cobra_reaction.gene_reaction_rule if gpr is not None and len(gpr) > 0: # replace ids in string if f_replace and F_GENE_REV in f_replace: gpr = gpr.replace("(", "( ") gpr = gpr.replace(")", " )") tokens = gpr.split() for k in range(len(tokens)): if tokens[k] not in ["and", "or", "(", ")"]: tokens[k] = f_replace[F_GENE_REV](tokens[k]) gpr_new = " ".join(tokens) else: gpr_new = gpr gpa: libsbml.GeneProductAssociation = ( r_fbc.createGeneProductAssociation()) # noqa: E501 # uses ids to identify GeneProducts (True), # does not create GeneProducts (False) _check(gpa.setAssociation(gpr_new, True, False), "set gpr: " + gpr_new) # objective coefficients if reaction_coefficients.get(cobra_reaction, 0) != 0: flux_obj: libsbml.FluxObjective = (objective.createFluxObjective() ) # noqa: E501 flux_obj.setReaction(rid) flux_obj.setCoefficient(cobra_reaction.objective_coefficient) # write groups if len(cobra_model.groups) > 0: doc.enablePackage( "http://www.sbml.org/sbml/level3/version1/groups/version1", "groups", True) doc.setPackageRequired("groups", False) model_group: libsbml.GroupsModelPlugin = model.getPlugin( "groups") # noqa: E501 for cobra_group in cobra_model.groups: group: libsbml.Group = model_group.createGroup() if f_replace and F_GROUP_REV in f_replace: gid = f_replace[F_GROUP_REV](cobra_group.id) else: gid = cobra_group.id group.setId(gid) group.setName(cobra_group.name) group.setKind(cobra_group.kind) _sbase_notes_dict(group, cobra_group.notes) _sbase_annotations(group, cobra_group.annotation) for cobra_member in cobra_group.members: member: libsbml.Member = group.createMember() mid = cobra_member.id m_type = str(type(cobra_member)) # id replacements if "Reaction" in m_type: if f_replace and F_REACTION_REV in f_replace: mid = f_replace[F_REACTION_REV](mid) if "Metabolite" in m_type or "Protein" in m_type: if f_replace and F_SPECIE_REV in f_replace: mid = f_replace[F_SPECIE_REV](mid) if "Gene" in m_type: if f_replace and F_GENE_REV in f_replace: mid = f_replace[F_GENE_REV](mid) member.setIdRef(mid) if cobra_member.name and len(cobra_member.name) > 0: member.setName(cobra_member.name) if isinstance(filename, str): # write to path libsbml.writeSBMLToFile(doc, filename) elif hasattr(filename, "write"): # write to file handle sbml_str = libsbml.writeSBMLToString(doc) filename.write(sbml_str)