Commit d0e5d2c7 authored by Peter Schubert's avatar Peter Schubert
Browse files

Initial commit

parents
This diff is collapsed.
include LICENSE
Convert between SBML coded files and Pandas DataFrames
======================================================
Example:
import sbmlxdf
model = sbmlxdf.Model()
model.import_sbml('orig_model.xml')
model.validate_sbml('orig_model.xml')
model.to_excel('model.xlsx')
#model.to_csv('model')
# modify, update model using MS Excel
upd_model=sbmlxdf.Model()
upd_model.from_excel('model.xlsx')
upd_model.export_sbml('upd_model.xml')
#upd_dict = upd_model.to_df()
Peter Schubert, October 2020
from .model import Model
__version__ = '0.1'
__author__ = 'Peter Schubert'
"""Implementation of Compartment components.
Peter Schubert, HHU Duesseldorf, October 2020
"""
import pandas as pd
import libsbml
from .sbase import SBase
# Explore_SBML_import_export_2020-10-05.ipynb
class ListOfCompartments(SBase):
def __init__(self):
self.compartments = []
super().__init__()
def import_sbml(self, sbml_model):
sbml_lc = sbml_model.getListOfCompartments()
for sbml_c in sbml_lc:
c = Compartment()
c.import_sbml(sbml_c)
self.compartments.append(c)
super().import_sbml(sbml_lc)
def export_sbml(self, sbml_model):
for c in self.compartments:
c.export_sbml(sbml_model)
super().export_sbml(sbml_model.getListOfCompartments())
def to_df(self):
return pd.DataFrame([c.to_df() for c in self.compartments])
def from_df(self, lc_df):
for idx, c_s in lc_df.iterrows():
c = Compartment()
c.from_df(c_s.dropna().to_dict())
self.compartments.append(c)
class Compartment(SBase):
def __init__(self):
super().__init__()
def import_sbml(self, sbml_c):
if sbml_c.isSetSpatialDimensions():
self.spatial_dim = sbml_c.getSpatialDimensionsAsDouble()
if sbml_c.isSetSize():
self.size = sbml_c.getSize()
if sbml_c.isSetUnits():
self.units = sbml_c.getUnits()
self.constant = sbml_c.getConstant()
super().import_sbml(sbml_c)
def export_sbml(self, sbml_model):
sbml_c = sbml_model.createCompartment()
if hasattr(self, 'spatial_dim'):
sbml_c.setSpatialDimensions(self.spatial_dim)
if hasattr(self, 'size'):
sbml_c.setSize(self.size)
if hasattr(self, 'units'):
sbml_c.setUnits(self.units)
sbml_c.setConstant(self.constant)
super().export_sbml(sbml_c)
def to_df(self):
c_dict = super().to_df()
if hasattr(self, 'spatial_dim'):
c_dict['spatialDimension'] = self.spatial_dim
if hasattr(self, 'size'):
c_dict['size'] = self.size
if hasattr(self, 'units'):
c_dict['units'] = self.units
c_dict['constant'] = self.constant
return c_dict
def from_df(self, c_dict):
if 'spatialDimension' in c_dict:
self.spatial_dim = float(c_dict['spatialDimension'])
if 'size' in c_dict:
self.size = float(c_dict['size'])
if 'units' in c_dict:
self.units = c_dict['units']
self.constant = (c_dict['constant']==str(True))
super().from_df(c_dict)
"""Implementation of Constraints components.
Peter Schubert, HHU Duesseldorf, October 2020
"""
import pandas as pd
import libsbml
from .sbase import SBase
# Explore_SBML_import_export_2020-10-05.ipynb
class ListOfConstraints(SBase):
def __init__(self):
self.constraints = []
super().__init__()
def import_sbml(self, sbml_model):
sbml_lc = sbml_model.getListOfConstraints()
for sbml_c in sbml_lc:
c = Constraint()
c.import_sbml(sbml_c)
self.constraints.append(c)
super().import_sbml(sbml_lc)
def export_sbml(self, sbml_model):
for c in self.constraints:
c.export_sbml(sbml_model)
super().export_sbml(sbml_model.getListOfConstraints())
def to_df(self):
return pd.DataFrame([c.to_df() for c in self.constraints])
def from_df(self, lco_df):
for idx, co_s in lco_df.iterrows():
co = Constraint()
co.from_df(co_s.dropna().to_dict())
self.constraints.append(co)
class Constraint(SBase):
def __init__(self):
super().__init__()
def import_sbml(self, sbml_c):
self.math = libsbml.formulaToL3String(sbml_c.getMath())
if sbml_c.isSetMessage():
self.message = sbml_c.getMessageString()
super().import_sbml(sbml_c)
def export_sbml(self, sbml_model):
sbml_c = sbml_model.createConstraint()
sbml_c.setMath(libsbml.parseL3Formula(self.math))
if hasattr(self, 'message'):
sbml_c.setMessage(self.message)
super().export_sbml(sbml_c)
def to_df(self):
c_dict = super().to_df()
c_dict['math'] = self.math
if hasattr(self, 'message'):
xmsg = libsbml.XMLNode.convertStringToXMLNode(self.message)
if isinstance(xmsg, libsbml.XMLNode) and xmsg.getNumChildren():
c_dict['message'] = ''
xp = xmsg.getChild(0)
for child in range(xp.getNumChildren()):
c_dict['message'] += xp.getChild(child).toXMLString().strip()
return c_dict
def from_df(self, co_dict):
self.math = co_dict.get('math', '')
if 'message' in co_dict:
msg = ('<message>'
' <p xmlns="http://www.w3.org/1999/xhtml">'
' </p>'
'</message> ')
xmsg = libsbml.XMLNode.convertStringToXMLNode(msg)
xp = xmsg.getChild('p')
xcontent = libsbml.XMLNode.convertStringToXMLNode(
' ' + co_dict['message'] + ' ')
if not xcontent.isEOF():
xp.addChild(xcontent)
else:
for i in range(xcontent.getNumChildren()):
xp.addChild(xcontent.getChild(i))
self.message = xmsg.toXMLString()
super().from_df(co_dict)
"""Implementation of Events components.
Peter Schubert, HHU Duesseldorf, October 2020
"""
import pandas as pd
import libsbml
from .sbase import SBase
from .misc import extract_vps
# Explore_SBML_import_export_2020-10-05.ipynb
class ListOfEvents(SBase):
def __init__(self):
self.events = []
super().__init__()
def import_sbml(self, sbml_model):
sbml_le = sbml_model.getListOfEvents()
for sbml_e in sbml_le:
e = Event()
e.import_sbml(sbml_e)
self.events.append(e)
super().import_sbml(sbml_le)
def export_sbml(self, sbml_model):
for e in self.events:
e.export_sbml(sbml_model)
super().export_sbml(sbml_model.getListOfEvents())
def to_df(self):
return pd.DataFrame([e.to_df() for e in self.events])
def from_df(self, le_df):
for idx, e_s in le_df.iterrows():
e = Event()
e.from_df(e_s.dropna().to_dict())
self.events.append(e)
class Event(SBase):
def __init__(self):
self.event_assignments = {}
super().__init__()
def import_sbml(self, sbml_e):
self.from_trigger_time = sbml_e.getUseValuesFromTriggerTime()
self.trigger = Trigger()
self.trigger.import_sbml(sbml_e)
if sbml_e.isSetPriority():
self.priority = Priority()
self.priority.import_sbml(sbml_e)
if sbml_e.isSetDelay():
self.delay = Delay()
self.delay.import_sbml(sbml_e)
for sbml_ea in sbml_e.getListOfEventAssignments():
ea = EventAssignment()
ea.import_sbml(sbml_ea)
self.event_assignments[ea.variable] = ea
super().import_sbml(sbml_e)
def export_sbml(self, sbml_model):
sbml_e = sbml_model.createEvent()
sbml_e.setUseValuesFromTriggerTime(self.from_trigger_time)
self.trigger.export_sbml(sbml_e)
if hasattr(self, 'priority'):
self.priority.export_sbml(sbml_e)
if hasattr(self, 'delay'):
self.delay.export_sbml(sbml_e)
for ea in self.event_assignments.values():
ea.export_sbml(sbml_e)
super().export_sbml(sbml_e)
def to_df(self):
e_dict = super().to_df()
e_dict['valFromTriggerTime'] = self.from_trigger_time
for key, val in self.trigger.to_df().items():
e_dict[key] = val
if hasattr(self, 'priority'):
for key, val in self.priority.to_df().items():
e_dict[key] = val
if hasattr(self, 'delay'):
for key, val in self.delay.to_df().items():
e_dict[key] = val
if len(self.event_assignments):
e_dict['eventAssign'] = '; '.join([
ea.to_df()
for ea in self.event_assignments.values()
])
return e_dict
def from_df(self, e_dict):
self.from_trigger_time = (e_dict['valFromTriggerTime']==str(True))
self.trigger = Trigger()
self.trigger.from_df(e_dict)
if Priority.is_in_df(e_dict):
self.priority = Priority()
self.priority.from_df(e_dict)
if Delay.is_in_df(e_dict):
self.delay = Delay()
self.delay.from_df(e_dict)
if 'eventAssign' in e_dict:
for ea_str in e_dict['eventAssign'].split(';'):
ea = EventAssignment()
ea.from_df(ea_str)
self.event_assignments[ea.variable] = ea
super().from_df(e_dict)
class Trigger(SBase):
def __init__(self):
super().__init__()
def import_sbml(self, sbml_e):
sbml_t = sbml_e.getTrigger()
self.init_val = sbml_t.getInitialValue()
self.persistent = sbml_t.getPersistent()
self.math = libsbml.formulaToL3String(sbml_t.getMath())
super().import_sbml(sbml_t)
def export_sbml(self, sbml_e):
sbml_t = sbml_e.createTrigger()
sbml_t.setInitialValue(self.init_val)
sbml_t.setPersistent(self.persistent)
sbml_t.setMath(libsbml.parseL3Formula(self.math))
super().export_sbml(sbml_t)
def to_df(self):
tr_dict = {}
tr_dict['triggerInitVal'] = self.init_val
tr_dict['triggerPersistent'] = self.persistent
tr_dict['triggerMath'] = self.math
if hasattr(self, 'sboterm'):
tr_dict['triggerSboTerm'] = self.sboterm
return tr_dict
def from_df(self, e_dict):
self.init_val = (e_dict['triggerInitVal']==str(True))
self.persistent = (e_dict['triggerPersistent']==str(True))
self.math = e_dict['triggerMath']
if 'triggerSboTerm' in e_dict:
self.sboterm = e_dict['triggerSboTerm']
class Priority(SBase):
def __init__(self):
super().__init__()
def import_sbml(self, sbml_e):
sbml_p = sbml_e.getPriority()
self.math = libsbml.formulaToL3String(sbml_p.getMath())
super().import_sbml(sbml_p)
def export_sbml(self, sbml_e):
sbml_p = sbml_e.createPriority()
sbml_p.setMath(libsbml.parseL3Formula(self.math))
super().export_sbml(sbml_p)
def to_df(self):
pr_dict = {}
pr_dict['priorityMath'] = self.math
if hasattr(self, 'sboterm'):
pr_dict['prioritySboTerm'] = self.sboterm
return pr_dict
def is_in_df(e_dict):
return 'priorityMath' in e_dict
def from_df(self, e_dict):
self.math = e_dict['priorityMath']
if 'prioritySboTerm' in e_dict:
self.sboterm = e_dict['prioritySboTerm']
class Delay(SBase):
def __init__(self):
super().__init__()
def import_sbml(self, sbml_e):
sbml_d = sbml_e.getDelay()
self.math = libsbml.formulaToL3String(sbml_d.getMath())
super().import_sbml(sbml_d)
def export_sbml(self, sbml_e):
sbml_d = sbml_e.createDelay()
sbml_d.setMath(libsbml.parseL3Formula(self.math))
super().export_sbml(sbml_d)
def to_df(self):
de_dict = {}
de_dict['delayMath'] = self.math
if hasattr(self, 'sboterm'):
de_dict['delaySboTerm'] = self.sboterm
return de_dict
def is_in_df(e_dict):
return 'delayMath' in e_dict
def from_df(self, de_dict):
self.math = de_dict['delayMath']
if 'delaySboTerm' in de_dict:
self.sboterm = de_dict['delaySboTerm']
class EventAssignment(SBase):
def __init__(self):
super().__init__()
def import_sbml(self, sbml_ea):
self.variable = sbml_ea.getVariable()
self.math = libsbml.formulaToL3String(sbml_ea.getMath())
super().import_sbml(sbml_ea)
def export_sbml(self, sbml_e):
sbml_ea = sbml_e.createEventAssignment()
sbml_ea.setVariable(self.variable)
sbml_ea.setMath(libsbml.parseL3Formula(self.math))
super().export_sbml(sbml_ea)
def to_df(self):
attr = ['variable=' + self.variable,
'math=' + self.math]
if hasattr(self, 'sboterm'):
attr.append('sboterm=' + self.sboterm)
return ', '.join(attr)
def from_df(self, ea_str):
ea_dict = extract_vps(ea_str)
if 'variable' in ea_dict:
self.variable = ea_dict['variable']
if 'math' in ea_dict:
self.math = ea_dict['math']
if 'sboterm' in ea_dict:
self.sboterm = ea_dict['sboterm']
"""Implementation of fbc ext. package components.
Peter Schubert, HHU Duesseldorf, October 2020
"""
import pandas as pd
import libsbml
from .sbase import SBase
from .misc import extract_vps
# Explore_SBML_import_export_2020-10-05.ipynb
class FbcListOfObjectives(SBase):
def __init__(self):
self.objectives = []
super().__init__()
def import_sbml(self, sbml_model):
fbc_mplugin = sbml_model.getPlugin('fbc')
sbml_lo = fbc_mplugin.getListOfObjectives()
self.active = sbml_lo.getActiveObjective()
for sbml_o in sbml_lo:
o = FbcObjective()
o.import_sbml(sbml_o)
self.objectives.append(o)
super().import_sbml(sbml_lo)
def export_sbml(self, sbml_model):
fbc_mplugin = sbml_model.getPlugin('fbc')
for o in self.objectives:
o.export_sbml(fbc_mplugin)
sbml_lo = fbc_mplugin.getListOfObjectives()
sbml_lo.setActiveObjective(self.active)
super().export_sbml(sbml_lo)
def to_df(self):
df_obj = pd.DataFrame([o.to_df() for o in self.objectives])
df_obj.insert(1, 'active', df_obj['id'] == str(self.active))
return df_obj
def from_df(self, lo_df):
active = lo_df['id'][lo_df['active']=='True'].values
if len(active):
self.active = active[0]
for idx, o_s in lo_df.iterrows():
o = FbcObjective()
o.from_df(o_s.dropna().to_dict())
self.objectives.append(o)
class FbcObjective(SBase):
# note: list_of_flux_objectives object not implemented
def __init__(self):
self.flux_objectives = []
super().__init__()
def import_sbml(self, sbml_o):
self.type = sbml_o.getType()
sbml_lfo = sbml_o.getListOfFluxObjectives()
for sbml_fo in sbml_lfo:
fo = FbcFluxObjective()
fo.import_sbml(sbml_fo)
self.flux_objectives.append(fo)
super().import_sbml(sbml_o)
def export_sbml(self, fbc_mplugin):
sbml_o = fbc_mplugin.createObjective()
sbml_o.setType(self.type)
for fo in self.flux_objectives:
fo.export_sbml(sbml_o)
super().export_sbml(sbml_o)
def to_df(self):
o_dict = {}
o_dict['type'] = self.type
o_dict['fluxObjectives'] = '; '.join([fo.to_df()
for fo in self.flux_objectives])
if hasattr(self, 'sboterm'):
o_dict['sboterm'] = self.sboterm
return o_dict
def from_df(self, o_dict):
self.type = o_dict['type']
for fo_str in o_dict['fluxObjectives'].split(';'):
fo = FbcFluxObjective()
fo.from_df(fo_str.strip())
self.flux_objectives.append(fo)
super().from_df(o_dict)
class FbcFluxObjective(SBase):
def __init__(self):
super().__init__()
def import_sbml(self, sbml_fo):
self.reaction = sbml_fo.getReaction()
self.coefficient = sbml_fo.getCoefficient()
super().import_sbml(sbml_fo)
def export_sbml(self, sbml_o):
sbml_fo = sbml_o.createFluxObjective()
sbml_fo.setReaction(self.reaction)
sbml_fo.setCoefficient(self.coefficient)
super().export_sbml(sbml_fo)
def to_df(self):
attr = []
if hasattr(self, 'id'):
attr.append('id=' + self.id)
if hasattr(self, 'name'):
attr.append('name=' + self.name)
attr.append('reac=' + self.reaction)
attr.append('coef=' + str(self.coefficient))
if hasattr(self, 'sboterm'):
attr.append('sboterm=' + self.sboterm)
return ', '.join(attr)
def from_df(self, fo_str):
fo_dict = extract_vps(fo_str)
if 'id' in fo_dict:
self.id = fo_dict['id']
if 'name' in fo_dict:
self.name = fo_dict['name']
if 'reac' in fo_dict:
self.reaction = fo_dict['reac']
if 'coef' in fo_dict:
self.coefficient = float(fo_dict['coef'])
if 'sboterm' in fo_dict:
self.sboterm = fo_dict['sboterm']
class FbcListOfGeneProducts(SBase):
def __init__(self):
self.gene_products = []
super().__init__()
def import_sbml(self, sbml_model):
fbc_mplugin = sbml_model.getPlugin('fbc')
sbml_lgp = fbc_mplugin.getListOfGeneProducts()
for sbml_gp in sbml_lgp:
gp = FbcGeneProduct()
gp.import_sbml(sbml_gp)
self.gene_products.append(gp)
super().import_sbml(sbml_lgp)
def export_sbml(self, sbml_model):
fbc_mplugin = sbml_model.getPlugin('fbc')
for gp in self.gene_products:
gp.