Skip to content

Commit

Permalink
Multiple bug fixes (#11)
Browse files Browse the repository at this point in the history
* setting up setuptools to install subsbml package (not yet working)

* core working branch

* tutorial.py working - share, combine, connect. Initial amount volume mode does not work

* volume mode problems fixed for shareSpecies. Need to carry forward changes to others. Also not working for species not in list of shared resources. Also setting size using system size in volume mode amounts

* tutorial.py and iptg_transport.py both are working now. share, combine, and connect all working. Need to fix the volume mode and make it consistent all over.

* iptg graph temp

* setup working. imports fixed. consistent and correct importing of modules.

* simulatemultiplevariable method modified, compartment option added. IPTG_transport graph generate for multiple inputs

* combine/share etc. all working and updated for normal combine, not working yet in the new framework for combinations inside a System

* changed back to l3v2, because fast attribute is mandatory with l3v1, and it has been removed from the code. tutorial.py is working but combineSubsystem is not. minor fixes needed

* problem with combinesubsystems

* shareSubsystem working with volume mode

* subsystem.py modified

* combine working. share, connect, combine, all 3 working in all of the modes. Volume mode also works perfectly, virtual mode works too. combine does not depend on share now. All valid SBML models generated in SBML l3v2.

* removing trash files

* all of the core features in subsbml are working, generating and converting to latest SBML level and version (l3v2). IPTG transport example working with this commit

* jupyter notebooks edited, all 3 working now

* removed useless files and removed model reduction example since fast attribute was used which is obsolete in SBML L3v2

* added createBasicSubsystem to create one Subsystem with a SBMLDocument, SBML Model inside, and make all the basic settings using a standard set of preassigned values. An important bug fix in createSimpleReaction in SimpleModel class, to allow for reactions which create or degrade a particular species into nothing (when product/reactant missing).

* modified SimpleReaction.py to fix bug for creating simple reaction with numbers in species names/ids

* modified SimpleReaction.py to fix bug for creating simple reaction with numbers in species names/ids (#3)

* modified iptg transport circuit. Improved membrane model. simulateVariableInputs method modified and multiple bugs fixed. Accepts lists for compartments, plotting options in a single plot or a matrix using subplots (not yet working).

* added varying alhl and varying gfp dna plots to guide experiment on their concentrations. fixed minor bug in simulate variable inputs for compartment species in else loop set to species id, replaced now with blank string, so optional keywords arguments should work. also added **kwargs to this function argument

* iptg transport working with modifications to variable input simulations

* bug in create unit definition in simple model fixed

* added gitignore to remove temp files to go to github repo, bug fixes in SimpleModel class

* Simple model (#5)

* modified SimpleReaction.py to fix bug for creating simple reaction with numbers in species names/ids

* bug in create unit definition in simple model fixed

* added gitignore to remove temp files to go to github repo, bug fixes in SimpleModel class

* Transport - setMembrane etc. fixed.  (#4)

* modified SimpleReaction.py to fix bug for creating simple reaction with numbers in species names/ids

* modified iptg transport circuit. Improved membrane model. simulateVariableInputs method modified and multiple bugs fixed. Accepts lists for compartments, plotting options in a single plot or a matrix using subplots (not yet working).

* added varying alhl and varying gfp dna plots to guide experiment on their concentrations. fixed minor bug in simulate variable inputs for compartment species in else loop set to species id, replaced now with blank string, so optional keywords arguments should work. also added **kwargs to this function argument

* iptg transport working with modifications to variable input simulations

* all examples and tutorials running with the latest code. Need to create unit tests so that further code developments have backward compatibility. IPTG transport example renamed to main_IPTG_transport for better visibility.

* added debug option to system.getModel and kwargs options to some functions. Downgraded SBML output to L3V1

* minor bug fixed

* commiting changes from examples

Co-authored-by: ayush-pandey <[email protected]>
  • Loading branch information
ayush9pandey and ayush-pandey authored Jan 30, 2020
1 parent 79bc6c1 commit 894f229
Show file tree
Hide file tree
Showing 4 changed files with 121 additions and 66 deletions.
19 changes: 14 additions & 5 deletions examples/IPTG transport/main_IPTG_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,21 @@
# cell_sub.simulateVariableInputs('DNA pOR1OR2--utr1--alHL',[0, 5, 10, 100, 15, 30], ['IPTG'], timepoints, mode = 'reset', compartmentInput= 'cell_internal',compartmentSpecies = 'cell_internal')
# cell_sub.simulateVariableInputs('DNA pOR1OR2--utr1--alHL',[0, 5, 10, 100, 15, 30], ['IPTG'], timepoints, mode = 'reset', compartmentInput= 'cell_internal',compartmentSpecies = 'cell_external')
# cell_sub.simulateVariableInputs('DNA pOR1OR2--utr1--alHL',[6, 10, 15, 20], ['protein deGFP*'], timepoints, plotShow = 'single')

# cell_sub.simulateVariableInputs('DNA pOR1OR2--utr1--alHL',[0,5, 10, 20, 100], ['protein deGFP*'],
# timepoints, mode = 'reset', compartmentInput = 'cell_internal', compartmentSpecies= 'cell_internal',
# plotShow = 'single', xlabel = 'time', ylabel = 'concentration',title = 'deGFP with varying DNA-alHL (without resource limits)',
# lineWidth = 2, sizeOfXLabels = 12, sizeOfYLabels = 12, legendFontSize= 8)
# cell_sub.simulateVariableInputs(ListOfInputs = ['DNA plac--utr1--deGFP', 'DNA pOR1OR2--utr1--alHL'], ListOfListOfAmounts = [[5,5],[5,15],[5,25],[15,5],[15,15],[15,20],[20,5],[20,15],[20,25]], ListOfSpeciesToPlot = ['protein deGFP*'], timepoints = timepoints, mode = 'reset', compartmentInput = ['cell_internal','cell_internal'],compartmentSpecies= 'cell_internal', plotShow = 'matrix', xlabel = 'time', ylabel = 'concentration', lineWidth = 2, sizeOfXLabels = 12, sizeOfYLabels = 12, legendFontSize= 6)
# cell_sub.simulateVariableInputs(ListOfInputs = ['DNA plac--utr1--deGFP', 'DNA pOR1OR2--utr1--alHL'], ListOfListOfAmounts = [[5,5],[5,10],[20,5],[20,10]], ListOfSpeciesToPlot = ['protein deGFP*'], timepoints = timepoints, mode = 'reset', plotShow = 'matrix', legendFontSize = 6)
# timepoints, mode = 'reset', compartmentInput = 'cell_internal', compartmentSpecies= 'cell_internal',
# plotShow = 'single', xlabel = 'time', ylabel = 'concentration',title = 'deGFP with varying DNA-alHL',
# lineWidth = 2, sizeOfXLabels = 12, sizeOfYLabels = 12, legendFontSize= 8)

# cell_sub.simulateVariableInputs(ListOfInputs = ['DNA plac--utr1--deGFP', 'DNA pOR1OR2--utr1--alHL'],
# ListOfListOfAmounts = [[5,5],[5,15],[5,25],[15,5],[15,15],[15,20],[20,5],[20,15],[20,25]],
# ListOfSpeciesToPlot = ['protein deGFP*'], timepoints = timepoints, mode = 'reset',
# compartmentInput = ['cell_internal','cell_internal'],compartmentSpecies= 'cell_internal',
# plotShow = 'matrix', xlabel = 'time', ylabel = 'concentration', lineWidth = 2, sizeOfXLabels = 12, sizeOfYLabels = 12, legendFontSize= 6)

# cell_sub.simulateVariableInputs(ListOfInputs = ['DNA plac--utr1--deGFP', 'DNA pOR1OR2--utr1--alHL'],
# ListOfListOfAmounts = [[5,5],[5,10],[20,5],[20,10]], ListOfSpeciesToPlot = ['protein deGFP*'],
# timepoints = timepoints, mode = 'reset', plotShow = 'matrix', legendFontSize = 6)

# More simulation options and optimizations in simulations

Expand Down
101 changes: 72 additions & 29 deletions subsbml/Subsystem.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Import packaged available with Python
import time
import copy
import warnings
import numpy as np
import matplotlib as mpl
Expand Down Expand Up @@ -133,7 +134,7 @@ def convertSubsystemLevelAndVersion(self, newLevel, newVersion):
check(document.setLevelAndVersion(newLevel,newVersion), 'converting SBMLDocument to new level and version')
# To check errors, uncomment:
# if document.getNumErrors():
# print(' The SBML document has errors {0}'.format(document.printErrors()))
# print(' The SBML document has errors : {0}'.format(document.printErrors()))
# raise ValueError('Invalid SBMLDocument error.')
# else:
# return self.getSBMLDocument()
Expand Down Expand Up @@ -350,6 +351,8 @@ def setCompartments(self, newCompartments):
document = self.getSBMLDocument()
check(document,'retreiving document from subsystem in setSubsystemCompartments')
compartments = document.getModel().getListOfCompartments()
if not len(compartments):
return
check(compartments,'retreiving list of compartments in setSubsystemCompartments')
if type(newCompartments) is not list:
if type(newCompartments) is str:
Expand Down Expand Up @@ -405,7 +408,7 @@ def createNewModel(self, modelId, timeUnits, extentUnits, substanceUnits):
'set model substance units')
return model

def mergeSubsystemModels(self, ListOfSubsystems):
def mergeSubsystemModels(self, ListOfSubsystems, **kwargs):
'''
The ListOfSubsystems are merged together. All components are
merged together except the Species.
Expand All @@ -416,56 +419,96 @@ def mergeSubsystemModels(self, ListOfSubsystems):
# functions, units, compartments, species, parameters,
# initial assignments, rules, constraints, reactions, and events
document = self.getSBMLDocument()
debug = kwargs.get('debug')
check(document,'retreiving document in mergeSubsystem')
model_base = ListOfSubsystems[0].getSBMLDocument().getModel()
check(model_base,'retreiving model in mergeSubsystems')
model = self.createNewModel('merged_model',model_base.getTimeUnits(), model_base.getExtentUnits(), model_base.getSubstanceUnits())
check(document.setModel(model),'setting model for document in mergeSubsystem')
if debug:
check(model.setAreaUnits(model_base.getAreaUnits()), 'set area units to merged ss')
check(model.setExtentUnits(model_base.getExtentUnits()), 'set extent units to merged ss')
check(model.setLengthUnits(model_base.getLengthUnits()), 'set length units to merged ss')
check(model.setSubstanceUnits(model_base.getSubstanceUnits()), 'set substance units to merged ss')
check(model.setTimeUnits(model_base.getTimeUnits()), 'set time units to merged ss')
check(model.setVolumeUnits(model_base.getVolumeUnits()), 'set volume units to merged ss')
check(document.setModel(model),'set model for document in mergeSubsystem')
else:
model.setAreaUnits(model_base.getAreaUnits())
model.setExtentUnits(model_base.getExtentUnits())
model.setLengthUnits(model_base.getLengthUnits())
model.setSubstanceUnits(model_base.getSubstanceUnits())
model.setTimeUnits(model_base.getTimeUnits())
model.setVolumeUnits(model_base.getVolumeUnits())
document.setModel(model)

for subsystem in ListOfSubsystems:
if type(subsystem) is not Subsystem:
raise ValueError('All items of the ListOfSubsystems argument should be of Subsystem class')
mod = subsystem.getSBMLDocument().getModel()
check(mod,'retreiving model in mergeSubsystem')
if debug:
check(mod,'retreive Subsystem model in mergeSubsystem')
# Obsolete in SBML Level 3
# if mod.getNumCompartmentTypes() != 0:
# for each_compartmentType in mod.getListOfCompartmentType():
# model.addCompartmentType(each_compartmentType)
if mod.getNumConstraints() != 0:
for each_constraint in mod.getListOfConstraints():
model.addConstraint(each_constraint)
if debug:
check(model.addConstraint(each_constraint), 'add constraint to merged model')
else:
model.addConstraint(each_constraint)

if mod.getNumInitialAssignments() != 0:
for each_initialAssignment in mod.getListOfInitialAssignments():
model.addInitialAssignment(each_initialAssignment)
if debug:
check(model.addInitialAssignment(each_initialAssignment), 'add initial assignment to merged model')
else:
model.addInitialAssignment(each_initialAssignment)
if mod.getNumFunctionDefinitions() != 0:
for each_functionDefinition in mod.getListOfFunctionDefinitions():
model.addFunctionDefinition(each_functionDefinition)
if debug:
check(model.addFunctionDefinition(each_functionDefinition), 'add function definition to merged model')
else:
model.addFunctionDefinition(each_functionDefinition)
if mod.getNumRules() != 0:
for each_rule in mod.getListOfRules():
model.addRule(each_rule)
if debug:
check(model.addRule(each_rule), 'add rule to merged model')
else:
model.addRule(each_rule)
if mod.getNumEvents() != 0:
for each_event in mod.getListOfEvents():
model.addEvent(each_event)
if debug:
check(model.addEvent(each_event), 'add event to merged model')
else:
model.addEvent(each_event)
if mod.getNumCompartments() != 0:
for each_compartment in mod.getListOfCompartments():
model.addCompartment(each_compartment)
if debug:
check(model.addCompartment(each_compartment), 'add compartment from SS into merged ss')
else:
model.addCompartment(each_compartment)
if mod.getNumParameters() != 0:
for each_parameter in mod.getListOfParameters():
model.addParameter(each_parameter)
if debug:
check(model.addParameter(each_parameter), 'add parameter to merged model')
else:
model.addParameter(each_parameter)
if mod.getNumUnitDefinitions() != 0:
for each_unit in mod.getListOfUnitDefinitions():
model.addUnitDefinition(each_unit)
if debug:
check(model.addUnitDefinition(each_unit), 'add unit definition to merged model')
else:
model.addUnitDefinition(each_unit)
if mod.getNumReactions() != 0:
for each_reaction in mod.getListOfReactions():
model.addReaction(each_reaction)
model.setAreaUnits(mod.getAreaUnits())
model.setExtentUnits(mod.getExtentUnits())
model.setLengthUnits(mod.getLengthUnits())
model.setSubstanceUnits(mod.getSubstanceUnits())
model.setTimeUnits(mod.getTimeUnits())
model.setVolumeUnits(mod.getVolumeUnits())
if debug:
check(model.addReaction(each_reaction), 'add reaction to merged model')
else:
model.addReaction(each_reaction)
return self.getSBMLDocument()

def shareSubsystems(self, ListOfSubsystems, ListOfSharedResources, mode = 'virtual'):
def shareSubsystems(self, ListOfSubsystems, ListOfSharedResources, mode = 'virtual', **kwargs):
'''
Merges the ListOfSubsystems together along with all the Species.
The Species in ListOfSharedResources are combined together
Expand Down Expand Up @@ -522,11 +565,11 @@ def shareSubsystems(self, ListOfSubsystems, ListOfSharedResources, mode = 'virtu
check(model.setId('shared_model_of_' + mod_id),'setting new model id for shared model')
return self.getSBMLDocument()

def shareSubsystem(self, ListOfSharedResources, mode = 'virtual'):
def shareSubsystem(self, ListOfSharedResources, mode = 'virtual', **kwargs):
self.shareSpecies([], ListOfSharedResources, mode)
return self.getSBMLDocument()

def combineSubsystems(self, ListOfSubsystems, mode = 'virtual', combineNames = True):
def combineSubsystems(self, ListOfSubsystems, mode = 'virtual', combineNames = True, **kwargs):
'''
Combines the ListOfSubsystems.
Species with the same name together are combined, if combineNames is True.
Expand Down Expand Up @@ -569,7 +612,7 @@ def combineSubsystems(self, ListOfSubsystems, mode = 'virtual', combineNames = T
total_size = 0
for subsystem in ListOfSubsystems:
total_size += subsystem.getSBMLDocument().getModel().getCompartment(0).getSize()
model = self.mergeSubsystemModels(ListOfSubsystems).getModel()
model = self.mergeSubsystemModels(ListOfSubsystems, **kwargs).getModel()
check(model,'retreiving model in combineSubsystems')
mod_id = ''

Expand Down Expand Up @@ -845,7 +888,7 @@ def shareSpecies(self, ListOfSubsystems, ListOfResources, mode):
if not system_set:
total_size = 0
for species in comp_dict[species_comp]:
check(model.addSpecies(species),'adding species in shareSpecies else case')
check(model.addSpecies(species),'add species in shareSpecies else case')
mod = species.getModel()
ssys_size = mod.getElementBySId(species.getCompartment()).getSize()
if not system_set:
Expand All @@ -854,17 +897,17 @@ def shareSpecies(self, ListOfSubsystems, ListOfResources, mode):
cumulative_amount += (species.getInitialAmount()) * ssys_size
spe_id = species.getId()
oldid = spe_id
check(oldid, 'retreiving oldid in combineSpecies else case')
check(oldid, 'retreive oldid in combineSpecies else case')
newid = trans.getValidIdForName(uni_sp.getId()) + '_shared'
self.renameSId(oldid, newid)
if count >= 1:
check(model.removeSpecies(newid),'removing duplicate species')
warnings.warn('Removing duplicate species {0} in the same compartment'.format(newid))
check(model.removeSpecies(newid),'remove duplicate species in shareSpecies' + newid)
warnings.warn('Remove duplicate species {0} in the same compartment'.format(newid))
else:
id_added_species = newid
count += 1
if mode == 'volume':
check(model.getSpecies(id_added_species).setInitialAmount(cumulative_amount/total_size),'setting initial amount to cumulative in volume mode in combineSpecies else case')
check(model.getSpecies(id_added_species).setInitialAmount(cumulative_amount/total_size),'set initial amount to cumulative in volume mode in combineSpecies else case')
return self.getSBMLDocument()


Expand Down Expand Up @@ -1046,7 +1089,7 @@ def combineSpecies(self, ListOfSubsystems, ListOfResources, mode):
newid = trans.getValidIdForName(uni_sp.getId()) + '_combined'
self.renameSId(oldid, newid)
if count >= 1:
check(model.removeSpecies(newid),'removing duplicate species')
check(model.removeSpecies(newid),'remove duplicate species - ' + newid)
warnings.warn('Removing duplicate species {0} in the same compartment'.format(newid))
else:
id_added_species = newid
Expand Down
23 changes: 13 additions & 10 deletions subsbml/System.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
# The latest level and version of SBML
# These are used to convert the models given as input to the latest SBML version
latestLevel = 3
latestVersion = 2
latestVersion = 1

class System(object):
'''
Expand Down Expand Up @@ -224,7 +224,7 @@ def createSubsystem(self, filename, subsystemName = ''):
model = sbmlDoc.getModel()
check(model,'retreiving model in createSubsystem')
if model == None:
raise SyntaxError('Model object not created')
raise SyntaxError('No Model found while creating Subsystem')
subsystem = Subsystem(sbmlDoc)
subsystem.setSystem(self)
if subsystem.getSBMLDocument().getLevel() != latestLevel or subsystem.getSBMLDocument().getVersion() != latestVersion:
Expand All @@ -235,14 +235,17 @@ def createSubsystem(self, filename, subsystemName = ''):
warnings.warn('No compartments in the Subsystem model, the System compartment will be used. Compartment Size will be set to zero for this Subsystem.')
elif model.getNumCompartments() > 1:
warnings.warn('More than 1 compartments in the Subsystem model. Check resulting models for consistency.')

if not model.getCompartment(0).isSetSize():
warnings.warn('Compartment Size is not set. Setting to one.')
model.getCompartment(0).setSize(1)
if model.getNumCompartments():
if not model.getCompartment(0).isSetSize():
warnings.warn('Compartment Size is not set. Setting to one.')
model.getCompartment(0).setSize(1)


subsystem.setCompartments([name])
self.ListOfInternalSubsystems.append(subsystem)
self.Size += model.getCompartment(0).getSize()
if len(model.getListOfCompartments()):
subsystem.setCompartments([name])
self.Size += model.getCompartment(0).getSize()
# libsbml.writeSBML(subsystem.getSBMLDocument(), 'test_create_ss'+subsystem.getSBMLDocument().getModel().getId()+'.xml')
return subsystem

def createNewSubsystem(self, level = latestLevel, version = latestVersion):
Expand Down Expand Up @@ -351,7 +354,7 @@ def setMembrane(self, subsystem):
raise ValueError('The two compartments of the membrane subsystem must each have a name attribute, with names "internal" and "external"')
return self.ListOfMembraneSubsystems

def getModel(self, mode='virtual'):
def getModel(self, mode='virtual', **kwargs):
'''
Returns the System model (SBMLDocument object) by combining the models of
1. All subsystems internal to the System (in a compartment called '<system_name>_internal')
Expand All @@ -362,7 +365,7 @@ def getModel(self, mode='virtual'):
internal_subsystems = self.ListOfInternalSubsystems
external_subsystems = self.ListOfExternalSubsystems
membranes = self.ListOfMembraneSubsystems
system_sbml.combineSubsystems([internal_subsystems, external_subsystems, membranes], mode)
system_sbml.combineSubsystems([internal_subsystems, external_subsystems, membranes], mode, **kwargs)
return system_sbml.getSBMLDocument(), system_sbml


Expand Down
Loading

0 comments on commit 894f229

Please sign in to comment.