Skip to content
Commits on Source (2)
......@@ -3,615 +3,9 @@ Bug-Debian: https://bugs.debian.org/936261
Author: Andreas Tille <tille@debian.org>
Last-Update: Tue, 10 Sep 2019 20:29:13 +0200
--- a/Cain.py
+++ b/Cain.py
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#!/usr/bin/python3
"""The script that launches Cain."""
@@ -32,15 +32,15 @@ def main():
errors.append('Consult the documentation available at http://cain.sourceforge.net/.')
hasTk = True
try:
- import Tkinter
+ import tkinter
except:
hasTk = False
if hasTk:
- import tkMessageBox
- root = Tkinter.Tk()
+ import tkinter.messagebox
+ root = tkinter.Tk()
#Tkinter.Label(root, text='\n'.join(errors)).pack()
#root.title('Error')
- tkMessageBox.showwarning('Error', '\n'.join(errors))
+ tkinter.messagebox.showwarning('Error', '\n'.join(errors))
root.mainloop()
else:
print('\n'.join(errors))
@@ -49,7 +49,7 @@ def main():
# Launch the application.
from gui.Application import Application
if len(sys.argv) > 2:
- print "Warning: Unmatched command line arguments."
+ print("Warning: Unmatched command line arguments.")
app = Application()
if len(sys.argv) == 2:
#app.readInitialFile(sys.argv[1])
--- a/fio/ContentHandler.py
+++ b/fio/ContentHandler.py
@@ -48,7 +48,7 @@ class ContentHandler(xml.sax.ContentHand
#
# The top level element.
if name == 'cain':
- if 'version' in attributes.keys():
+ if 'version' in list(attributes.keys()):
self.version = float(attributes['version'])
else:
self.version = 1.10
@@ -63,9 +63,9 @@ class ContentHandler(xml.sax.ContentHand
elif name == 'model':
# Start a new model.
self.model = Model()
- if 'id' in attributes.keys():
+ if 'id' in list(attributes.keys()):
self.model.id = attributes['id']
- if 'name' in attributes.keys():
+ if 'name' in list(attributes.keys()):
self.model.name = attributes['name']
elif name == 'listOfParameters':
# Start the dictionary of parameters.
@@ -88,7 +88,7 @@ class ContentHandler(xml.sax.ContentHand
self.model.triggerEvents = []
elif name == 'parameter':
# Append a parameter.
- if not 'id' in attributes.keys():
+ if not 'id' in list(attributes.keys()):
self.errors += 'Missing id attribute in parameter.\n'
return
x = Value('', '')
@@ -99,7 +99,7 @@ class ContentHandler(xml.sax.ContentHand
self.model.parameters[attributes['id']] = x
elif name == 'compartment':
# Append a compartment.
- if not 'id' in attributes.keys():
+ if not 'id' in list(attributes.keys()):
self.errors += 'Missing id attribute in compartment.\n'
return
if not attributes['id']:
@@ -110,7 +110,7 @@ class ContentHandler(xml.sax.ContentHand
self.model.compartments[attributes['id']] = compartment
elif name == 'species':
# Append a species.
- if not 'id' in attributes.keys():
+ if not 'id' in list(attributes.keys()):
self.errors += 'Missing id attribute in species.\n'
return
x = Species(None, None, None)
@@ -158,11 +158,11 @@ class ContentHandler(xml.sax.ContentHand
if not self.model.reactions:
self.errors += 'Badly placed speciesReference tag.\n'
return
- if not 'species' in attributes.keys():
+ if not 'species' in list(attributes.keys()):
self.errors +=\
'Missing species attribute in speciesReference.\n'
return
- if 'stoichiometry' in attributes.keys():
+ if 'stoichiometry' in list(attributes.keys()):
stoichiometry = int(attributes['stoichiometry'])
else:
stoichiometry = 1
@@ -181,7 +181,7 @@ class ContentHandler(xml.sax.ContentHand
if not self.model.reactions:
self.errors += 'Badly placed modifierSpeciesReference tag.\n'
return
- if not 'species' in attributes.keys():
+ if not 'species' in list(attributes.keys()):
self.errors +=\
'Missing species attribute in modifierSpeciesReference.\n'
return
@@ -210,11 +210,11 @@ class ContentHandler(xml.sax.ContentHand
pass
# CONTINUE: trajectoryFrames is deprecated.
elif name in ('timeSeriesFrames', 'trajectoryFrames'):
- if not 'model' in attributes.keys():
+ if not 'model' in list(attributes.keys()):
self.errors +=\
'Missing model attribute in timeSeriesFrames.\n'
return
- if not 'method' in attributes.keys():
+ if not 'method' in list(attributes.keys()):
self.errors += 'Missing method attribute in timeSeriesFrames.\n'
return
key = (attributes['model'], attributes['method'])
@@ -228,25 +228,25 @@ class ContentHandler(xml.sax.ContentHand
self.currentOutput = self.output[key]
# CONTINUE: trajectoryAllReactions is deprecated.
elif name in ('timeSeriesAllReactions', 'trajectoryAllReactions'):
- if not 'model' in attributes.keys():
+ if not 'model' in list(attributes.keys()):
self.errors +=\
'Missing model attribute in timeSeriesAllReactions.\n'
return
- if not 'method' in attributes.keys():
+ if not 'method' in list(attributes.keys()):
self.errors += 'Missing method attribute in timeSeriesAllReactions.\n'
return
key = (attributes['model'], attributes['method'])
if self.version >= 1:
- if not 'initialTime' in attributes.keys():
+ if not 'initialTime' in list(attributes.keys()):
self.errors +=\
'Missing initialTime attribute in timeSeriesAllReactions.\n'
return
- if not 'finalTime' in attributes.keys():
+ if not 'finalTime' in list(attributes.keys()):
self.errors +=\
'Missing finalTime attribute in timeSeriesAllReactions.\n'
return
else:
- if not 'endTime' in attributes.keys():
+ if not 'endTime' in list(attributes.keys()):
self.errors +=\
'Missing endTime attribute in timeSeriesAllReactions.\n'
return
@@ -264,26 +264,26 @@ class ContentHandler(xml.sax.ContentHand
model = self.models[attributes['model']]
if self.version >= 1:
self.output[key] =\
- TimeSeriesAllReactions(range(len(model.speciesIdentifiers)),
- range(len(model.reactions)),
+ TimeSeriesAllReactions(list(range(len(model.speciesIdentifiers))),
+ list(range(len(model.reactions))),
float(attributes['initialTime']),
float(attributes['finalTime']))
else:
# CONTINUE: Deprecated.
self.output[key] =\
- TimeSeriesAllReactions(range(len(model.speciesIdentifiers)),
- range(len(model.reactions)),
+ TimeSeriesAllReactions(list(range(len(model.speciesIdentifiers))),
+ list(range(len(model.reactions))),
0.,
float(attributes['endTime']))
self.currentOutput = self.output[key]
elif name == 'histogramFrames':
for key in ('model', 'method', 'numberOfTrajectories'):
- if not key in attributes.keys():
+ if not key in list(attributes.keys()):
self.errors +=\
'Missing ' + key + ' attribute in histogramFrames.\n'
return
# CONTINUE: Make multiplicity mandatory.
- if 'multiplicity' in attributes.keys():
+ if 'multiplicity' in list(attributes.keys()):
multiplicity = int(attributes['multiplicity'])
else:
multiplicity = 2
@@ -306,12 +306,12 @@ class ContentHandler(xml.sax.ContentHand
float(attributes['numberOfTrajectories'])
elif name == 'histogramAverage':
for key in ('model', 'method', 'numberOfTrajectories'):
- if not key in attributes.keys():
+ if not key in list(attributes.keys()):
self.errors +=\
'Missing ' + key + ' attribute in histogramAverage.\n'
return
# CONTINUE: Make multiplicity mandatory.
- if 'multiplicity' in attributes.keys():
+ if 'multiplicity' in list(attributes.keys()):
multiplicity = int(attributes['multiplicity'])
else:
multiplicity = 2
@@ -334,7 +334,7 @@ class ContentHandler(xml.sax.ContentHand
float(attributes['numberOfTrajectories'])
elif name == 'statisticsFrames':
for key in ('model', 'method'):
- if not key in attributes.keys():
+ if not key in list(attributes.keys()):
self.errors +=\
'Missing ' + key + ' attribute in statisticsFrames.\n'
return
@@ -354,7 +354,7 @@ class ContentHandler(xml.sax.ContentHand
self.currentOutput = self.output[key]
elif name == 'statisticsAverage':
for key in ('model', 'method'):
- if not key in attributes.keys():
+ if not key in list(attributes.keys()):
self.errors +=\
'Missing ' + key + ' attribute in statisticsAverage.\n'
return
@@ -416,13 +416,13 @@ class ContentHandler(xml.sax.ContentHand
# CONTINUE: Add 'cardinality', 'mean', 'summedSecondCenteredMoment',
# and 'sumOfWeights' to the required attributes.
for key in ('lowerBound', 'width', 'species'):
- if not key in attributes.keys():
+ if not key in list(attributes.keys()):
self.errors +=\
'Missing ' + key + ' attribute in histogram.\n'
return
species = int(attributes['species'])
if self.currentOutput.__class__.__name__ == 'HistogramFrames':
- if not 'frame' in attributes.keys():
+ if not 'frame' in list(attributes.keys()):
self.errors +=\
'Missing frame attribute in histogram.\n'
return
@@ -472,7 +472,7 @@ class ContentHandler(xml.sax.ContentHand
# Elements for the random number generator state.
#
elif name == 'random':
- if 'seed' in attributes.keys():
+ if 'seed' in list(attributes.keys()):
self.seed = int(attributes['seed'])
elif name == 'stateMT19937':
self.listOfMt19937States.append([])
@@ -501,62 +501,62 @@ class ContentHandler(xml.sax.ContentHand
self.errors += 'No species were defined.\n'
elif name == 'frameTimes':
self.currentOutput.setFrameTimes\
- (map(float, self.content.split()))
+ (list(map(float, self.content.split())))
self.content = ''
elif name == 'recordedSpecies':
self.currentOutput.setRecordedSpecies\
- (map(int, self.content.split()))
+ (list(map(int, self.content.split())))
self.content = ''
elif name == 'recordedReactions':
self.currentOutput.recordedReactions =\
- map(int, self.content.split())
+ list(map(int, self.content.split()))
self.content = ''
elif name == 'histogram':
self.currentHistogram = None
self.currentHistogramIndex = None
# CONTINUE: These are deprecated.
elif name == 'firstHistogram':
- self.currentHistogram.set(0, map(float, self.content.split()))
+ self.currentHistogram.set(0, list(map(float, self.content.split())))
self.content = ''
elif name == 'secondHistogram':
- self.currentHistogram.set(1, map(float, self.content.split()))
+ self.currentHistogram.set(1, list(map(float, self.content.split())))
self.content = ''
elif name == 'histogramElement':
self.currentHistogram.set(self.currentHistogramIndex,
- map(float, self.content.split()))
+ list(map(float, self.content.split())))
self.currentHistogramIndex += 1
self.content = ''
elif name == 'populations':
# Add the populations to the current set of trajectories.
self.currentOutput.appendPopulations\
- (map(float, self.content.split()))
+ (list(map(float, self.content.split())))
self.content = ''
elif name == 'reactionCounts':
# Add the reaction counts the current set of trajectories.
self.currentOutput.appendReactionCounts\
- (map(float, self.content.split()))
+ (list(map(float, self.content.split())))
self.content = ''
elif name == 'initialPopulations':
# Add the initial populations to the current set of trajectories.
self.currentOutput.appendInitialPopulations\
- (map(float, self.content.split()))
+ (list(map(float, self.content.split())))
self.content = ''
elif name == 'indices':
# Add the reaction indices to the current set of trajectories.
- self.currentOutput.appendIndices(map(int, self.content.split()))
+ self.currentOutput.appendIndices(list(map(int, self.content.split())))
self.content = ''
elif name == 'times':
# Add the reaction times to the current set of trajectories.
self.currentOutput.appendTimes\
- (map(float, self.content.split()))
+ (list(map(float, self.content.split())))
self.content = ''
elif name == 'statistics':
self.currentOutput.setStatistics\
- (map(float, self.content.split()))
+ (list(map(float, self.content.split())))
self.content = ''
elif name == 'stateMT19937':
# Add the elements to the state.
- self.listOfMt19937States[-1].extend(map(int, self.content.split()))
+ self.listOfMt19937States[-1].extend(list(map(int, self.content.split())))
self.content = ''
# 624 for the array, 1 for the position.
if len(self.listOfMt19937States[-1]) != 625:
--- a/fio/ContentHandlerSbml.py
+++ b/fio/ContentHandlerSbml.py
@@ -93,17 +93,17 @@ class ContentHandlerSbml(xml.sax.Content
return
elif name == 'parameter':
# Append a parameter.
- if 'id' in attributes.keys():
+ if 'id' in list(attributes.keys()):
id = attributes['id']
else:
- if 'name' in attributes.keys():
+ if 'name' in list(attributes.keys()):
id = attributes['name']
self.errors += 'Missing id attribute in reaction parameter. Using name for id.\n'
else:
self.errors += 'Missing id attribute in reaction parameter.\n'
return
# Ignore the name attribute.
- if 'value' in attributes.keys():
+ if 'value' in list(attributes.keys()):
expression = attributes['value']
else:
expression = ''
@@ -160,7 +160,7 @@ class ContentHandlerSbml(xml.sax.Content
# The top level element.
#
if name == 'sbml':
- if 'level' in attributes.keys() and attributes['level'] == 1:
+ if 'level' in list(attributes.keys()) and attributes['level'] == 1:
self.errors += 'Error: SBML level 1 is not supported. Use level 2 or higher.\n'
return
#
@@ -170,15 +170,15 @@ class ContentHandlerSbml(xml.sax.Content
# Start a new model.
self.model = Model()
# If an ID was specified, use it.
- if 'id' in attributes.keys():
+ if 'id' in list(attributes.keys()):
self.model.id = attributes['id']
# Otherwise try the name.
- elif 'name' in attributes.keys():
+ elif 'name' in list(attributes.keys()):
self.model.id = attributes['name']
# If there is no ID or name, just use 'model'.
else:
self.model.id = 'model'
- if 'name' in attributes.keys():
+ if 'name' in list(attributes.keys()):
self.model.name = attributes['name']
elif name == 'listOfParameters':
return
@@ -194,27 +194,27 @@ class ContentHandlerSbml(xml.sax.Content
self.model.reactions = []
elif name == 'parameter':
# Append a parameter.
- if 'id' in attributes.keys():
+ if 'id' in list(attributes.keys()):
id = attributes['id']
else:
- if 'name' in attributes.keys():
+ if 'name' in list(attributes.keys()):
id = attributes['name']
self.errors += 'Missing id attribute in parameter. Using name for id.\n'
else:
self.errors += 'Missing id attribute in parameter.\n'
return
- if 'name' in attributes.keys():
+ if 'name' in list(attributes.keys()):
parameterName = attributes['name']
else:
parameterName = ''
- if 'value' in attributes.keys():
+ if 'value' in list(attributes.keys()):
expression = attributes['value']
else:
expression = ''
self.model.parameters[id] = Value(parameterName, expression)
elif name == 'compartment':
# Append a compartment.
- if not 'id' in attributes.keys():
+ if not 'id' in list(attributes.keys()):
self.errors += 'Missing id attribute in compartment.\n'
return
if not attributes['id']:
@@ -222,9 +222,9 @@ class ContentHandlerSbml(xml.sax.Content
return
# No default name. Default size of 1.
compartment = Value('', '1')
- if 'name' in attributes.keys():
+ if 'name' in list(attributes.keys()):
compartment.name = attributes['name']
- if 'size' in attributes.keys():
+ if 'size' in list(attributes.keys()):
compartment.expression = attributes['size']
else:
# Cain uses compartment sizes like parameter values. Thus
@@ -234,24 +234,24 @@ class ContentHandlerSbml(xml.sax.Content
self.model.compartments[attributes['id']] = compartment
elif name == 'species':
# Append a species.
- if 'id' in attributes.keys():
+ if 'id' in list(attributes.keys()):
id = attributes['id']
else:
- if 'name' in attributes.keys():
+ if 'name' in list(attributes.keys()):
id = attributes['name']
self.errors += 'Missing id attribute in species. Using name for id.\n'
else:
self.errors += 'Missing id attribute in species.\n'
return
- if not 'compartment' in attributes.keys():
+ if not 'compartment' in list(attributes.keys()):
self.errors += 'Missing compartment attribute in species' +\
id + '.\n'
return
- if 'name' in attributes.keys():
+ if 'name' in list(attributes.keys()):
speciesName = attributes['name']
else:
speciesName = ''
- if 'initialAmount' in attributes.keys():
+ if 'initialAmount' in list(attributes.keys()):
initialAmount = attributes['initialAmount']
else:
initialAmount = ''
@@ -260,16 +260,16 @@ class ContentHandlerSbml(xml.sax.Content
self.model.speciesIdentifiers.append(id)
elif name == 'reaction':
# Append a reaction.
- if 'id' in attributes.keys():
+ if 'id' in list(attributes.keys()):
id = attributes['id']
else:
- if 'name' in attributes.keys():
+ if 'name' in list(attributes.keys()):
id = attributes['name']
self.errors += 'Missing id attribute in reaction. Using name for id.\n'
else:
self.errors += 'Missing id attribute in reaction.\n'
return
- if 'name' in attributes.keys():
+ if 'name' in list(attributes.keys()):
reactionName = attributes['name']
else:
reactionName = ''
@@ -277,7 +277,7 @@ class ContentHandlerSbml(xml.sax.Content
r = Reaction(id, reactionName, [], [], False, '0')
# Note if the reaction is reversible. The reversible field is true
# by default.
- if not 'reversible' in attributes.keys() or\
+ if not 'reversible' in list(attributes.keys()) or\
attributes['reversible'] == 'true':
r.reversible = True
self.model.reactions.append(r)
@@ -298,11 +298,11 @@ class ContentHandlerSbml(xml.sax.Content
if not self.model.reactions:
self.errors += 'Badly placed speciesReference tag.\n'
return
- if not 'species' in attributes.keys():
+ if not 'species' in list(attributes.keys()):
self.errors +=\
'Missing species attribute in speciesReference.\n'
return
- if 'stoichiometry' in attributes.keys():
+ if 'stoichiometry' in list(attributes.keys()):
stoichiometry = int(attributes['stoichiometry'])
else:
stoichiometry = 1
@@ -321,7 +321,7 @@ class ContentHandlerSbml(xml.sax.Content
if not self.model.reactions:
self.errors += 'Badly placed modifierSpeciesReference tag.\n'
return
- if not 'species' in attributes.keys():
+ if not 'species' in list(attributes.keys()):
self.errors +=\
'Missing species attribute in modifierSpeciesReference.\n'
return
@@ -423,11 +423,11 @@ if __name__ == '__main__':
handler = ContentHandlerSbml()
parse(open(name, 'r'), handler)
if handler.warnings:
- print('\nWarning for ' + name)
- print(handler.warnings)
+ print(('\nWarning for ' + name))
+ print((handler.warnings))
if handler.errors:
- print('\nError for ' + name)
- print(handler.errors)
+ print(('\nError for ' + name))
+ print((handler.errors))
assert not handler.errors
for name in sys.argv[1:]:
--- a/fio/ReactionTextParser.py
+++ b/fio/ReactionTextParser.py
@@ -161,38 +161,38 @@ def main():
assert not parser.parse('1', 's1 + 2 s2', 's3', '1', '2.5', 'reaction 1',
['s1', 's2', 's3'], [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('r1', '1 + 2 s2', 's3', '1', '2.5', 'reaction 1',
['s1', 's2', 's3'], [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('r1', 's1 - 2 s2', 's3', '1', '2.5', 'reaction 1',
['s1', 's2', 's3'], [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('r1', 's1 + 2 s2', '3', '1', '2.5', 'reaction 1',
['s1', 's2', 's3'], [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('r1', 's1 + 2 s2', 's3 + s4', '1', 'reaction 1',
'2.5', ['s1', 's2', 's3'], [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('r1', 's1 + 2 s2', 's3', '1', '', 'reaction 1',
['s1', 's2', 's3'], [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
# Does not check for negative numbers.
assert parser.parse('r1', 's1 + 2 s2', 's3', '1', '-2.5', 'reaction 1',
@@ -201,8 +201,8 @@ def main():
assert not parser.parse('r1', 's1 + 2 s2', 's3', '1', '2.5', 'reaction 1',
['s1', 's2', 's3'], ['r1'])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert parser.parseTable(
[['r1', 's1 + 2 s2', 's3', '1', '2.5', 'reaction 1']],
@@ -219,16 +219,16 @@ def main():
[['1', 's1 + 2 s2', 's3', '1', '2.5', 'reaction 1']],
['s1', 's2', 's3'], [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parseTable(
[['r1', 's1 + 2 s2', 's3', '1', '2.5', 'reaction 1'],
['r1', 's1 + s2', 's3', '1', '2.5', 'reaction 2']],
['s1', 's2', 's3'], [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
if __name__ == '__main__':
main()
--- a/fio/SbmlReader.py
+++ b/fio/SbmlReader.py
@@ -1,3 +1,4 @@
+#!/usr/bin/python3
"""SBML reader.
This code is currently not used. I cannot get libsbml and wxPython to work
together. Thus I wrote my own SBML parser in ContentHandlerSbml."""
@@ -17,15 +18,15 @@ def readSbmlFile(fileName):
@@ -17,15 +17,15 @@ def readSbmlFile(fileName):
# Create an empty model.
model = Model()
# Read the SBML file.
......@@ -630,248 +24,103 @@ Last-Update: Tue, 10 Sep 2019 20:29:13 +0200
#sbmlModel = document.getModel()
sbmlModel = libsbml.SBMLReader().readSBML(fileName).getModel()
# Model identifier.
@@ -77,8 +78,8 @@ def readSbmlFile(fileName):
@@ -39,7 +39,7 @@ def readSbmlFile(fileName):
model.species[sbmlSpecies.getId()] = \
Species(sbmlSpecies.getName(), str(sbmlSpecies.getInitialAmount()))
# Add to the list of species identifiers.
- model.speciesIdentifiers.append(sbmlSpecies.getId())
+ model.speciesIdentifiers.append(sbmlSpecies.getId())
# For each reaction.
for n in range(sbmlModel.getNumReactions()):
sbmlReaction = sbmlModel.getReaction(n)
@@ -77,8 +77,8 @@ def readSbmlFile(fileName):
if __name__ == '__main__':
if (len(sys.argv) != 2):
- print 'Usage:'
- print 'python SbmlReader.py file.xml'
+ print('Usage:')
+ print('python3 SbmlReader.py file.xml')
+ print('python SbmlReader.py file.xml')
raise 'Bad command line arguments.'
- print sys.argv[1]
+ print(sys.argv[1])
model = readSbmlFile(sys.argv[1])
--- a/fio/SpeciesTextParser.py
+++ b/fio/SpeciesTextParser.py
@@ -101,23 +101,23 @@ def main():
assert not parser.parse('a', '', '', 'c1', [])
assert not parser.parse('a', '1', '', 'c1', ['a'])
- print parser.parseTable([['s1', '100', 'species 1', 'c1']], [])
+ print(parser.parseTable([['s1', '100', 'species 1', 'c1']], []))
assert not parser.errorMessage
- print parser.parseTable([['s1', '100', 'species 1', 'c1'],
- ['s2', '200', 'species 2', 'c1']], [])
+ print(parser.parseTable([['s1', '100', 'species 1', 'c1'],
+ ['s2', '200', 'species 2', 'c1']], []))
assert not parser.errorMessage
- print parser.parseTable([['1', '100', 'species 1', 'c1']], [])
+ print(parser.parseTable([['1', '100', 'species 1', 'c1']], []))
assert parser.errorMessage
- print parser.errorMessage
+ print(parser.errorMessage)
- print parser.parseTable([['s1', '100', 'species 1', 'c1'],
- ['s1', '200', 'species 2', 'c1']], [])
+ print(parser.parseTable([['s1', '100', 'species 1', 'c1'],
+ ['s1', '200', 'species 2', 'c1']], []))
assert parser.errorMessage
- print parser.errorMessage
+ print(parser.errorMessage)
- print parser.parseTable([['s1', '100', 'species 1', 'c1']], [])
+ print(parser.parseTable([['s1', '100', 'species 1', 'c1']], []))
assert not parser.errorMessage
if __name__ == '__main__':
--- a/fio/TimeEventTextParser.py
+++ b/fio/TimeEventTextParser.py
@@ -88,35 +88,35 @@ def main():
assert not parser.parse('1', '1', 's1=2', 'name', [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('e1', '1', 's1=2', 'name', ['e1'])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('e1', 'a', 's1=2', 'name', [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('e1', '[a]', 's1=2', 'name', [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('e1', '1', '', 'name', [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
identifiers = []
assert parser.parseTable([['e1', '1', 's1=2', 'name']], identifiers)
assert not parser.parseTable([['e1', '1', 's1=2', 'name']], identifiers)
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
if __name__ == '__main__':
main()
--- a/fio/TriggerEventTextParser.py
+++ b/fio/TriggerEventTextParser.py
@@ -89,28 +89,28 @@ def main():
assert not parser.parse('1', 't>1', 's1=2', '0', '', 'name', [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('e1', '', 's1=2', '0', '', 'name', [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('e1', 't>1', '', '0', '', 'name', [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('e1', 't>1', 's1=2', 'a', '', 'name', [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
assert not parser.parse('e1', 't>1', 's1=2', '-1', '', 'name', [])
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
identifiers = []
assert parser.parseTable([['e1', 't>1', 's1=2', '0', '', 'name']],
@@ -118,8 +118,8 @@ def main():
assert not parser.parseTable([['e1', 't>1', 's1=2', '0', '', 'name']],
identifiers)
assert parser.errorMessage
- print parser.errorMessage
- print ''
+ print(parser.errorMessage)
+ print('')
if __name__ == '__main__':
main()
--- a/fio/ValueTextParser.py
+++ b/fio/ValueTextParser.py
@@ -77,21 +77,21 @@ def main():
assert not parser.parse('a', '', '', [])
assert not parser.parse('a', 'expression', '', ['a'])
- print parser.parseTable([['a', 'expression', '']], [])
+ print(parser.parseTable([['a', 'expression', '']], []))
assert not parser.errorMessage
- print parser.parseTable([['', 'expression', '']], [])
+ print(parser.parseTable([['', 'expression', '']], []))
assert parser.errorMessage
- print parser.errorMessage
+ print(parser.errorMessage)
- print parser.parseTable([['a', '', '']], [])
+ print(parser.parseTable([['a', '', '']], []))
assert parser.errorMessage
- print parser.errorMessage
+ print(parser.errorMessage)
- print parser.parseTable([['a', 'expression', ''], ['a', 'expression', '']],
- [])
+ print(parser.parseTable([['a', 'expression', ''], ['a', 'expression', '']],
+ []))
assert parser.errorMessage
- print parser.errorMessage
+ print(parser.errorMessage)
if __name__ == '__main__':
main()
--- a/fio/XmlWriter.py
+++ b/fio/XmlWriter.py
@@ -19,7 +19,7 @@ class XmlWriter:
Why use standard solutions when you can roll your own?"""
- def __init__(self, out=sys.stdout, encoding="utf-8", indent=u" "):
+ def __init__(self, out=sys.stdout, encoding="utf-8", indent=" "):
self.out = out
self.encoding = encoding
self.indent = indent
@@ -35,7 +35,7 @@ class XmlWriter:
def beginDocument(self):
assert self.openElements == []
- self.out.write(u'<?xml version="1.0" encoding="%s"?>\n' %
+ self.out.write('<?xml version="1.0" encoding="%s"?>\n' %
self.encoding)
def endDocument(self):
@@ -43,7 +43,7 @@ class XmlWriter:
def beginElement(self, tag, attributes={}):
self._write('<' + tag)
- for (name, value) in attributes.items():
+ for (name, value) in list(attributes.items()):
self.out.write(' %s="%s"' % (name, escape(value)))
self.out.write('>\n')
self.openElements.append(tag)
@@ -64,7 +64,7 @@ class XmlWriter:
def writeEmptyElement(self, tag, attributes={}):
self._write('<' + tag)
- for (name, value) in attributes.items():
+ for (name, value) in list(attributes.items()):
self.out.write(' %s="%s"' % (name, escape(value)))
self.out.write('/>\n')
--- a/fio/readModelText.py
+++ b/fio/readModelText.py
@@ -48,7 +48,7 @@ def readModelText(input):
for n in range(numberOfSpecies):
model.species[sid[n]] = Species('', '', initialAmounts[n])
# Read the packed reactions into a list of integers.
- data = map(int, input.readline().rstrip().split())
+ data = list(map(int, input.readline().rstrip().split()))
# The propensity factors.
propensityFactors = input.readline().rstrip().split()
# Add the reactions.
@@ -82,7 +82,7 @@ def readModelText(input):
True, propensityFactors[i]))
# Return the model.
return model
- except Exception, error:
+ except Exception as error:
print(error)
return None
--- a/gui/Application.py
+++ b/gui/Application.py
@@ -8,7 +8,6 @@ import os.path
import wx
from MainFrame import MainFrame
from resourcePath import resourcePath
-from os.path import expanduser, join
class Application(wx.App):
"""The application class for Cain."""
--- a/gui/DuplicateDialog.py
+++ b/gui/DuplicateDialog.py
@@ -48,11 +48,11 @@ def main():
@@ -2,17 +2,18 @@
import wx
+
class DuplicateDialog(wx.Dialog):
"""The duplicate dialog."""
-
+
def __init__(self, parent=None):
- """."""
- wx.Dialog.__init__(self, parent, -1, 'Duplicate the model.')
+ """."""
+ wx.Dialog.__init__(self, parent, -1, 'Duplicate the model.')
# Multiplicity.
- multiplicitySizer = wx.BoxSizer(wx.HORIZONTAL)
+ multiplicitySizer = wx.BoxSizer(wx.HORIZONTAL)
self.multiplicity = wx.SpinCtrl(self, -1, value='2', min=2, max=1000000,
- initial=2)
+ initial=2)
multiplicitySizer.Add(self.multiplicity, 0, wx.ALL, 5)
label = wx.StaticText(self, -1, 'Multiplicity.')
multiplicitySizer.Add(label, 0, wx.ALL, 5)
@@ -21,21 +22,21 @@ class DuplicateDialog(wx.Dialog):
self.scale = wx.CheckBox(self, -1, 'Randomly scale propensities.')
# Buttons.
- okButton = wx.Button(self, wx.ID_OK, 'OK')
+ okButton = wx.Button(self, wx.ID_OK, 'OK')
okButton.SetDefault()
- cancelButton = wx.Button(self, wx.ID_CANCEL, 'Cancel')
- buttons = wx.BoxSizer(wx.HORIZONTAL)
+ cancelButton = wx.Button(self, wx.ID_CANCEL, 'Cancel')
+ buttons = wx.BoxSizer(wx.HORIZONTAL)
buttons.Add(okButton, 0, wx.ALIGN_RIGHT, 5)
buttons.Add(cancelButton, 0, wx.ALIGN_RIGHT, 5)
- sizer = wx.BoxSizer(wx.VERTICAL)
- sizer.Add(multiplicitySizer, 0, wx.EXPAND | wx.ALL, border=5)
- sizer.Add(self.scale, 0, wx.EXPAND | wx.ALL, border=5)
- sizer.Add(buttons, 0, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM, 5)
-
- self.SetSizer(sizer)
- self.Layout()
- self.Fit()
+ sizer = wx.BoxSizer(wx.VERTICAL)
+ sizer.Add(multiplicitySizer, 0, wx.EXPAND | wx.ALL, border=5)
+ sizer.Add(self.scale, 0, wx.EXPAND | wx.ALL, border=5)
+ sizer.Add(buttons, 0, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM, 5)
+
+ self.SetSizer(sizer)
+ self.Layout()
+ self.Fit()
def getMultiplicity(self):
return self.multiplicity.GetValue()
@@ -43,18 +44,20 @@ class DuplicateDialog(wx.Dialog):
def useScaling(self):
return self.scale.GetValue()
+
def main():
app = wx.PySimpleApp()
frame = DuplicateDialog()
result = frame.ShowModal()
if result == wx.ID_OK:
......@@ -887,451 +136,299 @@ Last-Update: Tue, 10 Sep 2019 20:29:13 +0200
frame.Destroy()
app.MainLoop()
--- a/gui/Export.py
+++ b/gui/Export.py
@@ -65,8 +65,8 @@ def main():
r = ['r1', 'r2', 'r3', 'r4']
t = TimeSeriesFrames()
t.setFrameTimes([0, 1, 2])
- t.recordedSpecies = range(len(s))
- t.recordedReactions = range(len(r))
+ t.recordedSpecies = list(range(len(s)))
+ t.recordedReactions = list(range(len(r)))
t.appendPopulations([1]*len(s) + [2]*len(s) + [3]*len(s))
t.appendReactionCounts([0]*len(r) + [2]*len(r) + [4]*len(r))
t.appendPopulations([2]*len(s) + [3]*len(s) + [5]*len(s))
@@ -87,8 +87,8 @@ def main():
r = ['r1', 'r2', 'r3', 'r4']
t = TimeSeriesFrames()
t.setFrameTimes([0, 1, 2])
- t.recordedSpecies = range(len(s))
- t.recordedReactions = range(len(r))
+ t.recordedSpecies = list(range(len(s)))
+ t.recordedReactions = list(range(len(r)))
t.appendPopulations([1]*len(s) + [2]*len(s) + [3]*len(s))
t.appendReactionCounts([0]*len(r) + [2]*len(r) + [4]*len(r))
t.appendPopulations([2]*len(s) + [3]*len(s) + [5]*len(s))
--- a/gui/ExportHistogramGrid.py
+++ b/gui/ExportHistogramGrid.py
@@ -1,6 +1,7 @@
"""Grid of the species to export."""
import os, os.path
+from functools import reduce
# If we are running the test code.
if os.path.split(os.getcwd())[1] == 'gui':
import sys
@@ -97,8 +98,7 @@ class ExportHistogramGrid(wx.grid.Grid):
def getCheckedItems(self):
"""Return the list of checked item indices."""
- return filter(lambda row: self.GetCellValue(row, 0),
- range(self.GetNumberRows()))
+ return [row for row in range(self.GetNumberRows()) if self.GetCellValue(row, 0)]
def areAnyItemsSelected(self):
return self.GetNumberRows() != 0 and\
--- a/gui/ExportTimeSeries.py
+++ b/gui/ExportTimeSeries.py
@@ -612,8 +612,8 @@ def main():
r = ['r1', 'r2', 'r3', 'r4']
t = TimeSeriesFrames()
t.setFrameTimes([0, 1, 2])
- t.recordedSpecies = range(len(s))
- t.recordedReactions = range(len(r))
+ t.recordedSpecies = list(range(len(s)))
+ t.recordedReactions = list(range(len(r)))
t.appendPopulations([1]*len(s) + [2]*len(s) + [3]*len(s))
t.appendReactionCounts([0]*len(r) + [2]*len(r) + [4]*len(r))
t.appendPopulations([2]*len(s) + [3]*len(s) + [5]*len(s))
@@ -634,8 +634,8 @@ def main():
r = ['r1', 'r2', 'r3', 'r4']
t = TimeSeriesFrames()
t.setFrameTimes([0, 1, 2])
- t.recordedSpecies = range(len(s))
- t.recordedReactions = range(len(r))
+ t.recordedSpecies = list(range(len(s)))
+ t.recordedReactions = list(range(len(r)))
t.appendPopulations([1]*len(s) + [2]*len(s) + [3]*len(s))
t.appendReactionCounts([0]*len(r) + [2]*len(r) + [4]*len(r))
t.appendPopulations([2]*len(s) + [3]*len(s) + [5]*len(s))
--- a/gui/ExportTimeSeriesGrid.py
+++ b/gui/ExportTimeSeriesGrid.py
@@ -1,6 +1,7 @@
"""Grid of the items (species or reactions) to export."""
import os, os.path
+from functools import reduce
# If we are running the test code.
if os.path.split(os.getcwd())[1] == 'gui':
import sys
@@ -109,8 +110,7 @@ class ExportTimeSeriesGrid(wx.grid.Grid)
def getCheckedItems(self):
"""Return the list of checked item indices."""
- return filter(lambda row: self.GetCellValue(row, 0),
- range(self.GetNumberRows()))
+ return [row for row in range(self.GetNumberRows()) if self.GetCellValue(row, 0)]
def areAnyItemsSelected(self):
return self.GetNumberRows() != 0 and\
+
if __name__ == '__main__':
main()
--- a/gui/GridRowEditor.py
+++ b/gui/GridRowEditor.py
@@ -381,7 +381,7 @@ class GridRowEditor(wx.Panel, StateModif
wx.MessageBox('The identifiers are not distinct.',
'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
return
- keys = tableRows.keys()
+ keys = list(tableRows.keys())
keys.sort()
if not isAscending:
keys.reverse()
@@ -464,8 +464,8 @@ if __name__ == '__main__':
self.editor)
def firstColumnModified(self, event):
- print('First column modified.',
- self.editor.getNonEmptyCellsInFirstColumn())
+ print(('First column modified.',
+ self.editor.getNonEmptyCellsInFirstColumn()))
app = wx.PySimpleApp()
frame = GridRowEditorFrame()
--- a/gui/Launcher.py
+++ b/gui/Launcher.py
@@ -24,7 +24,7 @@ def cpuCount():
# http://codeliberates.blogspot.com/2008/05/detecting-cpuscores-in-python.html
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
- if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
+ if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
# Linux & Unix:
count = os.sysconf("SC_NPROCESSORS_ONLN")
if isinstance(count, int) and count > 0:
@@ -32,7 +32,7 @@ def cpuCount():
else: # OS X:
return int(os.popen2("sysctl -n hw.ncpu")[1].read())
# Windows:
- if os.environ.has_key("NUMBER_OF_PROCESSORS"):
+ if "NUMBER_OF_PROCESSORS" in os.environ:
count = int(os.environ["NUMBER_OF_PROCESSORS"]);
if count > 0:
return count
@@ -362,28 +362,28 @@ class LauncherFrame(wx.Frame):
self.importTrajectories)
def launch(self):
- print 'launch'
+ print('launch')
def compile(self):
- print 'compile'
+ print('compile')
def stop(self):
- print 'stop'
+ print('stop')
def kill(self):
- print 'kill'
+ print('kill')
def saveExecutable(self):
- print 'saveExecutable'
+ print('saveExecutable')
def exportJobs(self):
- print 'exportJobs'
+ print('exportJobs')
def importTrajectories(self):
- print 'importTrajectories'
+ print('importTrajectories')
def exportMathematica(self):
- print 'exportMathematica'
+ print('exportMathematica')
def getSelectedModelId(self):
return '1'
--- a/gui/MainFrame.py
+++ b/gui/MainFrame.py
@@ -17,7 +17,7 @@ import threading
import webbrowser
import platform
import tempfile
-import urllib2
+import urllib.request, urllib.error, urllib.parse
from About import About
from IdentifierListEditor import IdentifierListEditor
@@ -200,7 +200,7 @@ class MainFrame(wx.Frame):
def checkVersion(self):
try:
url = 'http://cain.sourceforge.net/version.txt'
- currentVersion = urllib2.urlopen(url, timeout=2).read()
+ currentVersion = urllib.request.urlopen(url, timeout=2).read()
c = currentVersion.split('.')
t = self.state.version.split('.')
if int(t[0]) < int(c[0]) or \
@@ -1026,7 +1026,7 @@ class MainFrame(wx.Frame):
self.state.importStatistics(filename, self.modelId,
self.methodId, recordedSpecies)
self.updateSimulations()
- except Exception, exception:
+ except Exception as exception:
truncatedErrorBox("Problem in importing %s.\n" % filename +
str(exception))
self.deleteOutput(self.modelId, self.methodId)
@@ -1059,7 +1059,7 @@ class MainFrame(wx.Frame):
self.state.importSuiteOfTrajectories(dialog.GetPaths(),
self.modelId,
self.methodId)
- except Exception, exception:
+ except Exception as exception:
truncatedErrorBox("Problem in importing trajectories.\n" +
str(exception))
self.updateSimulations()
@@ -1088,7 +1088,7 @@ class MainFrame(wx.Frame):
if re.search('<sbml', open(filename, 'r').read()):
self.importSbml(filename, useMessageBox)
return
- except Exception, exception:
+ except Exception as exception:
if useMessageBox:
truncatedErrorBox('Problem in determining the file type for ' +
filename + '.\n' + str(exception))
@@ -1119,7 +1119,7 @@ class MainFrame(wx.Frame):
self.filename = filename
self.SetTitle(self.title + ' -- ' + self.filename)
self.isModified = False
- except Exception, exception:
+ except Exception as exception:
if useMessageBox:
truncatedErrorBox("Problem in reading %s.\n" % filename +
errors + '\n' + str(exception))
@@ -1146,7 +1146,7 @@ class MainFrame(wx.Frame):
# Select the model.
self.modelsList.selectLast()
self.isModified = True
- except Exception, exception:
+ except Exception as exception:
if useMessageBox:
truncatedErrorBox("Problem in importing %s.\n" % filename +
errors + '\n' + str(exception))
@@ -1170,7 +1170,7 @@ class MainFrame(wx.Frame):
# Select the model.
self.modelsList.selectLast()
self.isModified = True
- except Exception, exception:
+ except Exception as exception:
if useMessageBox:
truncatedErrorBox("Problem in importing text model %s.\n"
% filename + '\n' + str(exception))
--- a/gui/ModelEditor.py
+++ b/gui/ModelEditor.py
@@ -184,8 +184,8 @@ if __name__ == '__main__':
self.speciesOrReactionsModified, self.panel)
def speciesOrReactionsModified(self, event):
- print('Species or reactions modified.',
- self.panel.getSpeciesAndReactionIdentifiers())
+ print(('Species or reactions modified.',
+ self.panel.getSpeciesAndReactionIdentifiers()))
app = wx.PySimpleApp()
frame = TestFrame()
--- a/gui/PValueMean.py
+++ b/gui/PValueMean.py
@@ -190,7 +190,7 @@ class Selection(wx.Panel):
if s == 0:
species = [self.species.GetString(n) for n in
range(1, self.species.GetCount())]
- speciesIndices = range(self.species.GetCount() - 1)
+ speciesIndices = list(range(self.species.GetCount() - 1))
else:
species = [self.species.GetString(s)]
speciesIndices = [s-1]
@@ -208,7 +208,7 @@ class Selection(wx.Panel):
if f == 0:
frames = [self.frame.GetString(n) for n in
range(1,self.frame.GetCount())]
- frameIndices = range(self.frame.GetCount() - 1)
+ frameIndices = list(range(self.frame.GetCount() - 1))
else:
frames = [self.frame.GetString(f)]
frameIndices = [f-1]
--- a/gui/Plot.py
+++ b/gui/Plot.py
@@ -73,8 +73,8 @@ def main():
r = ['r1', 'r2', 'r3', 'r4']
t = TimeSeriesFrames()
t.setFrameTimes([0, 1, 2])
- t.recordedSpecies = range(len(s))
- t.recordedReactions = range(len(r))
+ t.recordedSpecies = list(range(len(s)))
+ t.recordedReactions = list(range(len(r)))
t.appendPopulations([1]*len(s) + [2]*len(s) + [3]*len(s))
t.appendReactionCounts([0]*len(r) + [2]*len(r) + [4]*len(r))
t.appendPopulations([2]*len(s) + [3]*len(s) + [5]*len(s))
@@ -95,8 +95,8 @@ def main():
r = ['r1', 'r2', 'r3', 'r4']
t = TimeSeriesFrames()
t.setFrameTimes([0, 1, 2])
- t.recordedSpecies = range(len(s))
- t.recordedReactions = range(len(r))
+ t.recordedSpecies = list(range(len(s)))
+ t.recordedReactions = list(range(len(r)))
t.appendPopulations([1]*len(s) + [2]*len(s) + [3]*len(s))
t.appendReactionCounts([0]*len(r) + [2]*len(r) + [4]*len(r))
t.appendPopulations([2]*len(s) + [3]*len(s) + [5]*len(s))
--- a/gui/PlotHistogramGrid.py
+++ b/gui/PlotHistogramGrid.py
@@ -1,6 +1,7 @@
"""Grid of the items (species or frames) to plot."""
import os, os.path
+from functools import reduce
# If we are running the test code.
if os.path.split(os.getcwd())[1] == 'gui':
@@ -1,6 +1,11 @@
"""Grid editor that can be used to edit species or reactions."""
-import os, os.path
+from StateModified import StateModified
+from wx.lib.buttons import GenBitmapToggleButton
+import wx.grid
+import wx
+import os
+import os.path
import sys
@@ -183,8 +184,8 @@ class PlotHistogramGrid(wx.grid.Grid):
value = self.upperBound
self.SetCellValue(row, col, str(value))
except:
- print('Could not convert "' + self.GetCellValue(row, col) +
- '" to an integer.')
+ print(('Could not convert "' + self.GetCellValue(row, col) +
+ '" to an integer.'))
else:
for row in range(self.GetNumberRows()):
try:
@@ -193,8 +194,8 @@ class PlotHistogramGrid(wx.grid.Grid):
value = self.lowerBound
self.SetCellValue(row, col, str(value))
except:
- print('Could not convert "' + self.GetCellValue(row, col) +
- '" to an integer.')
+ print(('Could not convert "' + self.GetCellValue(row, col) +
+ '" to an integer.'))
def incrementAlpha(self, col, isLeft):
if isLeft:
@@ -205,8 +206,8 @@ class PlotHistogramGrid(wx.grid.Grid):
value = 1.
self.SetCellValue(row, col, str(value))
except:
- print('Could not convert "' + self.GetCellValue(row, col) +
- '" to a float.')
+ print(('Could not convert "' + self.GetCellValue(row, col) +
+ '" to a float.'))
else:
for row in range(self.GetNumberRows()):
try:
@@ -215,8 +216,8 @@ class PlotHistogramGrid(wx.grid.Grid):
value = 0.
self.SetCellValue(row, col, str(value))
except:
- print('Could not convert "' + self.GetCellValue(row, col) +
- '" to a float.')
+ print(('Could not convert "' + self.GetCellValue(row, col) +
+ '" to a float.'))
def legendLabels(self, col, isLeft):
if isLeft:
@@ -261,8 +262,7 @@ class PlotHistogramGrid(wx.grid.Grid):
def getCheckedItems(self):
"""Return the list of checked item indices."""
- return filter(lambda row: self.GetCellValue(row, 0),
- range(self.GetNumberRows()))
+ return [row for row in range(self.GetNumberRows()) if self.GetCellValue(row, 0)]
def getLineStyles(self, row):
"""Get the line styles. If no legend label is specified, use a single
--- a/gui/PlotTimeSeries.py
+++ b/gui/PlotTimeSeries.py
@@ -434,8 +434,8 @@ def main():
r = ['r1', 'r2', 'r3', 'r4']
t = TimeSeriesFrames()
t.setFrameTimes([0, 1, 2])
- t.recordedSpecies = range(len(s))
- t.recordedReactions = range(len(r))
+ t.recordedSpecies = list(range(len(s)))
+ t.recordedReactions = list(range(len(r)))
t.appendPopulations([1]*len(s) + [2]*len(s) + [3]*len(s))
t.appendReactionCounts([0]*len(r) + [2]*len(r) + [4]*len(r))
t.appendPopulations([2]*len(s) + [3]*len(s) + [5]*len(s))
@@ -456,8 +456,8 @@ def main():
r = ['r1', 'r2', 'r3', 'r4']
t = TimeSeriesFrames()
t.setFrameTimes([0, 1, 2])
- t.recordedSpecies = range(len(s))
- t.recordedReactions = range(len(r))
+ t.recordedSpecies = list(range(len(s)))
+ t.recordedReactions = list(range(len(r)))
t.appendPopulations([1]*len(s) + [2]*len(s) + [3]*len(s))
t.appendReactionCounts([0]*len(r) + [2]*len(r) + [4]*len(r))
t.appendPopulations([2]*len(s) + [3]*len(s) + [5]*len(s))
--- a/gui/PlotTimeSeriesGrid.py
+++ b/gui/PlotTimeSeriesGrid.py
@@ -1,6 +1,7 @@
"""Grid of the items (species or reactions) to plot."""
import os, os.path
+from functools import reduce
# If we are running the test code.
if os.path.split(os.getcwd())[1] == 'gui':
import sys
@@ -213,8 +214,8 @@ class PlotTimeSeriesGrid(wx.grid.Grid):
value = self.upperBound
self.SetCellValue(row, col, str(value))
except:
- print('Could not convert "' + self.GetCellValue(row, col) +
- '" to an integer.')
+ print(('Could not convert "' + self.GetCellValue(row, col) +
+ '" to an integer.'))
else:
@@ -9,22 +14,21 @@ if os.path.split(os.getcwd())[1] == 'gui
else:
from resourcePath import resourcePath
-import wx
-import wx.grid
-from wx.lib.buttons import GenBitmapToggleButton
-from StateModified import StateModified
class FirstColumnModifiedEvent(wx.PyCommandEvent):
"""Event that is processed when the first column of a GridRowEditor is
modified."""
+
def __init__(self, evtType, id):
wx.PyCommandEvent.__init__(self, evtType, id)
+
# Generate an event type.
EVT_FIRST_COLUMN_MODIFIED_TYPE = wx.NewEventType()
# Create a binder object.
EVT_FIRST_COLUMN_MODIFIED = wx.PyEventBinder(EVT_FIRST_COLUMN_MODIFIED_TYPE, 1)
+
class GridRowEditorButtons(wx.Panel):
def __init__(self, parent=None):
wx.Panel.__init__(self, parent)
@@ -58,7 +62,8 @@ class GridRowEditorButtons(wx.Panel):
'gui/icons/16x16/upDisabled.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
self.moveUp.SetBitmapDisabled(bmp)
- self.moveUp.SetToolTip(wx.ToolTip('Left click to move row up. Right click to move row to top.'))
+ self.moveUp.SetToolTip(wx.ToolTip(
+ 'Left click to move row up. Right click to move row to top.'))
bmp = wx.Image(os.path.join(resourcePath, 'gui/icons/16x16/down.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
@@ -68,7 +73,8 @@ class GridRowEditorButtons(wx.Panel):
'gui/icons/16x16/downDisabled.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
self.moveDown.SetBitmapDisabled(bmp)
- self.moveDown.SetToolTip(wx.ToolTip('Left click to move row down. Right click to move row to bottom.'))
+ self.moveDown.SetToolTip(wx.ToolTip(
+ 'Left click to move row down. Right click to move row to bottom.'))
bmp = wx.Image(os.path.join(resourcePath, 'gui/icons/16x16/sort.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
@@ -78,7 +84,8 @@ class GridRowEditorButtons(wx.Panel):
'gui/icons/16x16/sortDisabled.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
self.sort.SetBitmapDisabled(bmp)
- self.sort.SetToolTip(wx.ToolTip('Left click to sort in ascending order. Right click for descending order.'))
+ self.sort.SetToolTip(wx.ToolTip(
+ 'Left click to sort in ascending order. Right click for descending order.'))
bmp = wx.Image(os.path.join(resourcePath, 'gui/icons/16x16/scale.png'),
wx.BITMAP_TYPE_PNG).ConvertToBitmap()
@@ -145,6 +152,7 @@ class GridRowEditorButtons(wx.Panel):
self.moveDown.Disable()
self.sort.Enable(self.isEditable)
+
class GridRowEditorGrid(wx.grid.Grid):
def __init__(self, parent, columnLabels, columnSizes, boolean, details):
wx.grid.Grid.__init__(self, parent)
@@ -173,9 +181,9 @@ class GridRowEditorGrid(wx.grid.Grid):
def getTableData(self):
# Save any values being edited in the grid.
- if self.IsCellEditControlShown():
- self.SaveEditControlValue()
- self.HideCellEditControl()
+ if self.IsCellEditControlShown():
+ self.SaveEditControlValue()
+ self.HideCellEditControl()
data = []
for row in range(self.GetNumberRows()):
try:
@@ -223,8 +224,8 @@ class PlotTimeSeriesGrid(wx.grid.Grid):
value = self.lowerBound
self.SetCellValue(row, col, str(value))
except:
- print('Could not convert "' + self.GetCellValue(row, col) +
- '" to an integer.')
+ print(('Could not convert "' + self.GetCellValue(row, col) +
+ '" to an integer.'))
def markerStyle(self, col, isLeft):
if isLeft:
@@ -310,8 +311,7 @@ class PlotTimeSeriesGrid(wx.grid.Grid):
def getCheckedItems(self):
"""Return the list of checked item indices."""
- return filter(lambda row: self.GetCellValue(row, 0),
- range(self.GetNumberRows()))
+ return [row for row in range(self.GetNumberRows()) if self.GetCellValue(row, 0)]
def useMarkers(self, row):
"""Return True if the specified item should be plotted with markers."""
--- a/gui/Preferences.py
+++ b/gui/Preferences.py
@@ -63,9 +63,9 @@ def main():
preferences.openDialog()
app.MainLoop()
for category in preferences.data:
- print category
+ print(category)
for field in preferences.data[category]:
- print ' ', preferences.data[category][field]
+ print(' ', preferences.data[category][field])
rowData = []
@@ -228,6 +236,7 @@ class GridRowEditorGrid(wx.grid.Grid):
self.SetColSize(i, 0)
self.ForceRefresh()
+
class GridRowEditor(wx.Panel, StateModified):
def __init__(self, parent, title, columnLabels, columnSizes=[], boolean=[],
details=[], toolTip=None):
@@ -268,7 +277,7 @@ class GridRowEditor(wx.Panel, StateModif
sizer = wx.BoxSizer(wx.VERTICAL)
if title:
sizer.Add(self.title, 0, wx.ALL, 0)
- sizer.Add(wx.StaticLine(self), 0, wx.EXPAND|wx.ALL, 1)
+ sizer.Add(wx.StaticLine(self), 0, wx.EXPAND | wx.ALL, 1)
sizer.Add(self.buttons, 0)
sizer.Add(self.grid, 1, wx.EXPAND)
self.SetSizer(sizer)
@@ -277,7 +286,7 @@ class GridRowEditor(wx.Panel, StateModif
def enable(self):
self.buttons.isEditable = True
self.update()
- #self.buttons.enable()
+ # self.buttons.enable()
self.grid.EnableEditing(True)
def disable(self):
@@ -296,14 +305,14 @@ class GridRowEditor(wx.Panel, StateModif
if not self.buttons.expand.GetValue():
self.grid.hideDetails()
self.Layout()
-
+
def onExpand(self, event):
if self.buttons.expand.GetValue():
self.grid.showDetails()
else:
self.grid.hideDetails()
self.Layout()
-
+
def onInsert(self, event):
selected = self.grid.GetSelectedRows()
if selected:
@@ -378,8 +387,8 @@ class GridRowEditor(wx.Panel, StateModif
tableRows[self.grid.GetCellValue(row, 0)] =\
[self.grid.GetCellValue(row, col) for col in range(numCols)]
if len(tableRows) != numRows:
- wx.MessageBox('The identifiers are not distinct.',
- 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
+ wx.MessageBox('The identifiers are not distinct.',
+ 'Error!', style=wx.OK | wx.ICON_EXCLAMATION)
return
keys = tableRows.keys()
keys.sort()
@@ -404,8 +413,8 @@ class GridRowEditor(wx.Panel, StateModif
row = event.GetRow()
# If a row was selected.
if row != -1:
- self.buttons.setRowSelectedState\
- (row != 0, row != self.grid.GetNumberRows() - 1)
+ self.buttons.setRowSelectedState(
+ row != 0, row != self.grid.GetNumberRows() - 1)
# If the whole grid was selected.
elif event.GetCol() == -1:
self.buttons.setRowSelectedState(False, False)
@@ -420,8 +429,8 @@ class GridRowEditor(wx.Panel, StateModif
self.buttons.setCellSelectedState()
elif len(selected) == 1:
row = selected[0]
- self.buttons.setRowSelectedState\
- (row != 0, row != self.grid.GetNumberRows() - 1)
+ self.buttons.setRowSelectedState(
+ row != 0, row != self.grid.GetNumberRows() - 1)
else:
self.buttons.setMultiRowSelectedState()
@@ -448,12 +457,13 @@ class GridRowEditor(wx.Panel, StateModif
self.GetId())
# Process the event.
self.GetEventHandler().ProcessEvent(event)
-
+
+
if __name__ == '__main__':
main()
class GridRowEditorFrame(wx.Frame):
def __init__(self, parent=None):
wx.Frame.__init__(self, parent, title='Reaction Editor',
- size=(600,300))
+ size=(600, 300))
self.editor = GridRowEditor(self, 'Reactions',
['ID', 'Name', 'Reactants', 'Products',
'MA', 'Propensity'],
--- a/gui/MethodHelp.py
+++ b/gui/MethodHelp.py
@@ -16,12 +16,12 @@ class MethodHelp(wx.Frame):
"""The help window."""
def __init__(self, time, category, method, option, parent=None):
- """Render the HTML help file."""
- wx.Frame.__init__(self, parent, -1, 'Method information',
+ """Render the HTML help file."""
+ wx.Frame.__init__(self, parent, -1, 'Method information',
size=(600,400))
- self.html = HtmlWindow(self)
- if "gtk2" in wx.PlatformInfo:
- self.html.SetStandardFonts()
+ self.html = HtmlWindow(self)
+ if "gtk2" in wx.PlatformInfo:
+ self.html.SetStandardFonts()
source =\
[''.join(['<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><html><body>',
'<p><tt>', timeDependence[time], '</tt> - ',
@@ -38,7 +38,7 @@ class MethodHelp(wx.Frame):
if re.search(key, source[0]):
source.append('<li>' + bibliography[key])
source.append('</ul></p></body></html>')
- self.html.SetPage(''.join(source))
+ self.html.SetPage(''.join(source))
def main():
app = wx.PySimpleApp()
--- a/gui/PreferencesDialog.py
+++ b/gui/PreferencesDialog.py
@@ -83,19 +83,19 @@ def main():
@@ -2,17 +2,18 @@
import wx
+
class PreferencesDialog(wx.Dialog):
"""The preferences dialog."""
-
+
def __init__(self, preferences, parent=None):
- """."""
- wx.Dialog.__init__(self, parent, -1, 'Cain Preferences.')
+ """."""
+ wx.Dialog.__init__(self, parent, -1, 'Cain Preferences.')
# Store a reference so we can reset the data.
self.preferences = preferences
- panels = wx.BoxSizer(wx.VERTICAL)
+ panels = wx.BoxSizer(wx.VERTICAL)
# The text and choice controls.
self.controls = {}
# For each category.
@@ -23,7 +24,7 @@ class PreferencesDialog(wx.Dialog):
category = subject[0]
header = wx.StaticText(self, -1, category)
panel.Add(header, 0, wx.ALL, 5)
- panel.Add(wx.StaticLine(self), 0, wx.EXPAND|wx.ALL, 5)
+ panel.Add(wx.StaticLine(self), 0, wx.EXPAND | wx.ALL, 5)
# The fields.
entries = wx.FlexGridSizer(len(subject) - 1, 2, hgap=10)
for (field, value, width) in subject[1:]:
@@ -45,23 +46,23 @@ class PreferencesDialog(wx.Dialog):
self.controls[category] = controlList
# Buttons.
- okButton = wx.Button(self, wx.ID_OK, 'OK')
+ okButton = wx.Button(self, wx.ID_OK, 'OK')
okButton.SetDefault()
- cancelButton = wx.Button(self, wx.ID_CANCEL, 'Cancel')
+ cancelButton = wx.Button(self, wx.ID_CANCEL, 'Cancel')
restoreButton = wx.Button(self, -1, 'Restore Defaults')
self.Bind(wx.EVT_BUTTON, self.onRestoreDefaults, restoreButton)
- buttons = wx.BoxSizer(wx.HORIZONTAL)
+ buttons = wx.BoxSizer(wx.HORIZONTAL)
buttons.Add(okButton, 0, wx.ALIGN_RIGHT, 5)
buttons.Add(cancelButton, 0, wx.ALIGN_RIGHT, 5)
buttons.Add(restoreButton, 0, wx.ALIGN_RIGHT, 5)
- sizer = wx.BoxSizer(wx.VERTICAL)
- sizer.Add(panels, 0, wx.EXPAND | wx.ALL, border=5)
- sizer.Add(buttons, 0, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM, 5)
-
- self.SetSizer(sizer)
- self.Layout()
- self.Fit()
+ sizer = wx.BoxSizer(wx.VERTICAL)
+ sizer.Add(panels, 0, wx.EXPAND | wx.ALL, border=5)
+ sizer.Add(buttons, 0, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM, 5)
+
+ self.SetSizer(sizer)
+ self.Layout()
+ self.Fit()
def onRestoreDefaults(self, event):
self.reset()
@@ -76,6 +77,7 @@ class PreferencesDialog(wx.Dialog):
def reset(self):
self.preferences.reset()
+
def main():
from Preferences import Preferences
app = wx.PySimpleApp()
@@ -83,21 +85,22 @@ def main():
frame = PreferencesDialog(preferences)
result = frame.ShowModal()
if result == wx.ID_OK:
......@@ -1358,9 +455,86 @@ Last-Update: Tue, 10 Sep 2019 20:29:13 +0200
frame.Destroy()
app.MainLoop()
+
if __name__ == '__main__':
main()
--- a/gui/SpeciesFrameDialog.py
+++ b/gui/SpeciesFrameDialog.py
@@ -65,11 +65,11 @@ def main():
@@ -2,46 +2,47 @@
import wx
+
class SpeciesFrameDialog(wx.Dialog):
"""Select a species and a frame with a dialog."""
-
+
def __init__(self, parent, model, output):
- """Construct."""
- wx.Dialog.__init__(self, parent, -1, 'Select a histogram.')
+ """Construct."""
+ wx.Dialog.__init__(self, parent, -1, 'Select a histogram.')
# Species.
- selectionSizer = wx.BoxSizer(wx.HORIZONTAL)
+ selectionSizer = wx.BoxSizer(wx.HORIZONTAL)
label = wx.StaticText(self, -1, 'Species:')
selectionSizer.Add(label, 0, wx.ALL, 5)
- self.species = wx.Choice(self,
+ self.species = wx.Choice(self,
choices=[model.speciesIdentifiers[_i]
for _i in output.recordedSpecies])
- self.species.SetSelection(0)
+ self.species.SetSelection(0)
selectionSizer.Add(self.species, 0, wx.ALL, 5)
# Frame.
label = wx.StaticText(self, -1, 'Frame:')
selectionSizer.Add(label, 0, wx.ALL, 5)
- self.frame = wx.Choice(self, choices=[str(_t) for _t in
+ self.frame = wx.Choice(self, choices=[str(_t) for _t in
output.frameTimes])
- self.frame.SetSelection(0)
+ self.frame.SetSelection(0)
selectionSizer.Add(self.frame, 0, wx.ALL, 5)
# Buttons.
- okButton = wx.Button(self, wx.ID_OK, 'OK')
+ okButton = wx.Button(self, wx.ID_OK, 'OK')
okButton.SetDefault()
- cancelButton = wx.Button(self, wx.ID_CANCEL, 'Cancel')
- buttons = wx.BoxSizer(wx.HORIZONTAL)
+ cancelButton = wx.Button(self, wx.ID_CANCEL, 'Cancel')
+ buttons = wx.BoxSizer(wx.HORIZONTAL)
buttons.Add(okButton, 0, wx.ALIGN_RIGHT, 5)
buttons.Add(cancelButton, 0, wx.ALIGN_RIGHT, 5)
- sizer = wx.BoxSizer(wx.VERTICAL)
- sizer.Add(selectionSizer, 0, wx.EXPAND | wx.ALL, border=5)
- sizer.Add(buttons, 0, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM, 5)
-
- self.SetSizer(sizer)
- self.Layout()
- self.Fit()
+ sizer = wx.BoxSizer(wx.VERTICAL)
+ sizer.Add(selectionSizer, 0, wx.EXPAND | wx.ALL, border=5)
+ sizer.Add(buttons, 0, wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM, 5)
+
+ self.SetSizer(sizer)
+ self.Layout()
+ self.Fit()
def getSpecies(self):
return self.species.GetCurrentSelection()
@@ -49,6 +50,7 @@ class SpeciesFrameDialog(wx.Dialog):
def getFrame(self):
return self.frame.GetCurrentSelection()
+
def main():
import sys
sys.path.insert(1, '..')
@@ -65,16 +67,14 @@ def main():
frame = SpeciesFrameDialog(None, model, hf)
result = frame.ShowModal()
if result == wx.ID_OK:
......@@ -1376,571 +550,119 @@ Last-Update: Tue, 10 Sep 2019 20:29:13 +0200
frame.Destroy()
app.MainLoop()
--- a/gui/TableHistogram.py
+++ b/gui/TableHistogram.py
@@ -41,7 +41,7 @@ class TableHistogramFrame(wx.Frame):
def main():
import math
- from StringIO import StringIO
+ from io import StringIO
import sys
sys.path.insert(1, '..')
--- a/gui/TableHistogramAverage.py
+++ b/gui/TableHistogramAverage.py
@@ -42,7 +42,7 @@ class TableErrorFrame(wx.Frame):
def main():
import math
- from StringIO import StringIO
+ from io import StringIO
import sys
sys.path.insert(1, '..')
--- a/gui/TableHistogramAverageStatistics.py
+++ b/gui/TableHistogramAverageStatistics.py
@@ -8,7 +8,7 @@ def flatten(theList):
"""Flatten the list."""
result = []
for x in theList:
- if hasattr(x, '__iter__') and not isinstance(x, basestring):
+ if hasattr(x, '__iter__') and not isinstance(x, str):
result.extend(flatten(x))
else:
result.append(x)
@@ -26,7 +26,7 @@ class Grid(TableBase):
# A row for each recorded species. The first column is the mean, the
# second is the standard deviation.
self.resize(len(output.recordedSpecies), 2)
- self.setColumnLabels([u'\u03bc', u'\u03c3'])
+ self.setColumnLabels(['\u03bc', '\u03c3'])
# For each recorded species.
for row in range(len(output.recordedSpecies)):
# Species identifier.
@@ -60,7 +60,7 @@ class TableHistogramAverageStatistics(wx
#
if __name__ == '__main__':
- from StringIO import StringIO
+ from io import StringIO
import sys
sys.path.insert(1, '..')
--- a/gui/TableHistogramFrames.py
+++ b/gui/TableHistogramFrames.py
@@ -47,7 +47,7 @@ class TableErrorFrame(wx.Frame):
def main():
import math
- from StringIO import StringIO
+ from io import StringIO
import sys
sys.path.insert(1, '..')
--- a/gui/TableHistogramFramesStatistics.py
+++ b/gui/TableHistogramFramesStatistics.py
@@ -8,7 +8,7 @@ def flatten(theList):
"""Flatten the list."""
result = []
for x in theList:
- if hasattr(x, '__iter__') and not isinstance(x, basestring):
+ if hasattr(x, '__iter__') and not isinstance(x, str):
result.extend(flatten(x))
else:
result.append(x)
@@ -24,8 +24,8 @@ class Grid(TableBase):
# A column for the mean and standard deviation of each recorded species.
self.resize(numberOfRows, 2 * len(output.recordedSpecies))
self.setColumnLabels(flatten([
- (u'\u03bc(' + model.speciesIdentifiers[_i] + ')',
- u'\u03c3(' + model.speciesIdentifiers[_i] + ')')
+ ('\u03bc(' + model.speciesIdentifiers[_i] + ')',
+ '\u03c3(' + model.speciesIdentifiers[_i] + ')')
for _i in output.recordedSpecies]))
# For each frame.
for i in range(len(output.frameTimes)):
@@ -62,7 +62,7 @@ class TableHistogramFramesStatistics(wx.
#
if __name__ == '__main__':
- from StringIO import StringIO
+ from io import StringIO
import sys
sys.path.insert(1, '..')
--- a/gui/TableStatisticsAverage.py
+++ b/gui/TableStatisticsAverage.py
@@ -16,7 +16,7 @@ class Grid(TableBase):
# A row for each recorded species. The first column is the mean, the
# second is the standard deviation.
self.resize(len(output.recordedSpecies), 2)
- self.setColumnLabels([u'\u03bc', u'\u03c3'])
+ self.setColumnLabels(['\u03bc', '\u03c3'])
# For each recorded species.
for row in range(len(output.recordedSpecies)):
# Species identifier.
@@ -46,7 +46,7 @@ class TableStatisticsAverage(wx.Frame):
#
+
if __name__ == '__main__':
- from StringIO import StringIO
+ from io import StringIO
import sys
sys.path.insert(1, '..')
--- a/gui/TableStatisticsFrames.py
+++ b/gui/TableStatisticsFrames.py
@@ -8,7 +8,7 @@ def flatten(theList):
"""Flatten the list."""
result = []
for x in theList:
- if hasattr(x, '__iter__') and not isinstance(x, basestring):
+ if hasattr(x, '__iter__') and not isinstance(x, str):
result.extend(flatten(x))
else:
result.append(x)
@@ -24,8 +24,8 @@ class Grid(TableBase):
# A column for the mean and standard deviation of each recorded species.
self.resize(numberOfRows, 2 * len(output.recordedSpecies))
self.setColumnLabels(flatten([
- (u'\u03bc(' + model.speciesIdentifiers[_i] + ')',
- u'\u03c3(' + model.speciesIdentifiers[_i] + ')')
+ ('\u03bc(' + model.speciesIdentifiers[_i] + ')',
+ '\u03c3(' + model.speciesIdentifiers[_i] + ')')
for _i in output.recordedSpecies]))
# For each frame.
for i in range(len(output.frameTimes)):
@@ -58,7 +58,7 @@ class TableStatisticsFrames(wx.Frame):
#
main()
-
-
-
--- a/state/TrajectoryCalculator.py
+++ b/state/TrajectoryCalculator.py
@@ -135,16 +135,16 @@ def main():
t.appendInitialPopulations([13, 17])
times, populations, reactionCounts =\
x.makeFramesAtReactionEvents(t, 0, True, True)
- print 'times'
- print times
- print 'populations'
- print populations
- print 'reactionCounts'
- print reactionCounts
- print 'Final reaction counts.'
- print x.computeFinalReactionCounts(t, 0)
- print 'Final populations.'
- print x.computeFinalPopulations(t, 0)
+ print('times')
+ print(times)
+ print('populations')
+ print(populations)
+ print('reactionCounts')
+ print(reactionCounts)
+ print('Final reaction counts.')
+ print(x.computeFinalReactionCounts(t, 0))
+ print('Final populations.')
+ print(x.computeFinalPopulations(t, 0))
if __name__ == '__main__':
- from StringIO import StringIO
+ from io import StringIO
import sys
sys.path.insert(1, '..')
--- a/gui/TrajectoriesList.py
+++ b/gui/TrajectoriesList.py
@@ -209,11 +209,11 @@ class TrajectoriesList(wx.Panel, StateMo
self.updateState()
def tearDown(self):
- for child in self.children.values():
+ for child in list(self.children.values()):
child.Destroy()
def updateChildren(self):
- for x in self.children.values():
+ for x in list(self.children.values()):
x.refresh()
def clear(self):
@@ -646,37 +646,37 @@ class State:
self.identifiers = []
def delete(self, model, method):
- print 'delete', model, method
+ print('delete', model, method)
def plotPopulationStatistics(self, model, method):
- print 'plotPopulationStatistics', model, method
+ print('plotPopulationStatistics', model, method)
def plotReactionStatistics(self, model, method):
- print 'plotReactionStatistics', model, method
+ print('plotReactionStatistics', model, method)
def plotPopulations(self, model, method):
- print 'plotPopulations', model, method
+ print('plotPopulations', model, method)
def plotReactions(self, model, method):
- print 'plotReactions', model, method
+ print('plotReactions', model, method)
def displayStatisticsLast(self, model, method):
- print 'display statistics last', model, method
+ print('display statistics last', model, method)
def displayStatisticsAll(self, model, method):
- print 'display statistics all', model, method
+ print('display statistics all', model, method)
def displayLast(self, model, method):
- print 'display last', model, method
+ print('display last', model, method)
main()
--- a/state/State.py
+++ b/state/State.py
@@ -109,7 +109,7 @@ class RecordingThreadPythonTimeSeriesFra
break
# Record the Mersenne twister state.
self.state.listOfMt19937States[0] = list(random.getstate()[1])
- except Exception, error:
+ except Exception as error:
wx.MessageBox(str(error), 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
self.state.numberOfTrajectories = 0
self.state.threads = []
@@ -180,7 +180,7 @@ class RecordingThreadTimeSeriesFrames(Re
self.state.readTimeSeriesFrames(self.output, self.index)
# Increment the progress gauge.
self.main.incrementProgressGauge(numberOfTrajectories)
- except Exception, error:
+ except Exception as error:
self.handleException(error)
def displayAll(self, model, method):
- print 'display all', model, method
+ print('display all', model, method)
class RecordingThreadTrajectoryAll(RecordingThread):
@@ -211,7 +211,7 @@ class RecordingThreadTrajectoryAll(Recor
self.state.readTimeSeriesAllReactions(self.output, self.index)
# Increment the progress gauge.
self.main.incrementProgressGauge(numberOfTrajectories)
- except Exception, error:
+ except Exception as error:
self.handleException(error)
def csv(self, model, method):
- print 'csv', model, method
+ print('csv', model, method)
class RecordingThreadHistogramFrames(RecordingThread):
@@ -241,7 +241,7 @@ class RecordingThreadHistogramFrames(Rec
self.output.readline()
# Record the histograms from the generated trajectories.
self.state.readHistogramFrames(self.output, self.index)
- except Exception, error:
+ except Exception as error:
self.handleException(error)
def gnuplot(self, model, method):
- print 'gnuplot', model, method
+ print('gnuplot', model, method)
class RecordingThreadHistogramAverage(RecordingThread):
@@ -271,7 +271,7 @@ class RecordingThreadHistogramAverage(Re
self.output.readline()
# Record the histograms from the generated trajectories.
self.state.readHistogramAverage(self.output, self.index)
- except Exception, error:
+ except Exception as error:
self.handleException(error)
class TrajectoriesListFrame(wx.Frame):
def __init__(self, parent=None):
@@ -689,13 +689,13 @@ class TrajectoriesListFrame(wx.Frame):
editor.insertItem('m3', 'p3', '300')
class State:
--- a/state/Species.py
+++ b/state/Species.py
@@ -93,22 +93,22 @@ def main():
x.writeXml(writer, 's1')
def exportCsv(self, modelId, methodId):
- print 'exportCsv', modelId, methodId
+ print('exportCsv', modelId, methodId)
x = Species('C1', 'species 1', '')
- print evaluateInitialAmounts({'s1':x}, {})
+ print(evaluateInitialAmounts({'s1':x}, {}))
def exportGnuplot(self, modelId, methodId):
- print 'exportGnuplot', modelId, methodId
+ print('exportGnuplot', modelId, methodId)
x = Species('C1', 'species 2', '1')
x.writeXml(writer, 's2')
def deleteOutput(self, modelId, methodId):
- print 'deleteOutput', modelId, methodId
+ print('deleteOutput', modelId, methodId)
x = Species('C1', 'species 2', '-1')
# I don't check the initial amount expression with hasErrors().
- print evaluateInitialAmounts({'s2':x}, {})
+ print(evaluateInitialAmounts({'s2':x}, {}))
x = Species('C1', 'species 2', 'p1')
- print evaluateInitialAmounts({'s1':x}, {})
+ print(evaluateInitialAmounts({'s1':x}, {}))
def main():
--- a/gui/statistics.py
+++ b/gui/statistics.py
@@ -32,9 +32,9 @@ def main():
print('Data:')
print(data)
print('Mean:')
- print(mean(data))
+ print((mean(data)))
print('Mean and standard deviation:')
- print(meanStdDev(data))
+ print((meanStdDev(data)))
x = Species('C1', 'species 2', 'p2')
p = Value('', '5.0')
p.value = 5.0
- print evaluateInitialAmounts({'s1':x}, {'p1':p})
+ print(evaluateInitialAmounts({'s1':x}, {'p1':p}))
if __name__ == '__main__':
main()
--- a/simulation/Direct.py
+++ b/simulation/Direct.py
@@ -13,7 +13,7 @@ class Direct(Solver):
Solver.__init__(self, model, maxSteps)
self.sumOfPropensities = 0.
self.propensities = numpy.zeros(len(model.reactions))
- self.reactionIdentifiers = self.model.reactions.keys()
+ self.reactionIdentifiers = list(self.model.reactions.keys())
def initialize(self):
# Initialize the state.
@@ -32,7 +32,7 @@ class Direct(Solver):
# The time at the end of the next step or frame.
tau = min(min(reactionTime, self.eventQueue[0][0]), endTime)
# Check the trigger events.
- for e in self.model.triggerEvents.values():
+ for e in list(self.model.triggerEvents.values()):
if e.evaluate(tau):
t = self.model.time + e.delay
if e.useValuesFromTriggerTime:
--- a/simulation/FirstReaction.py
+++ b/simulation/FirstReaction.py
@@ -28,7 +28,7 @@ class FirstReaction(Solver):
# The time at the end of the next step or frame.
tau = min(min(reactionTime, self.eventQueue[0][0]), endTime)
# Check the trigger events.
- for e in self.model.triggerEvents.values():
+ for e in list(self.model.triggerEvents.values()):
if e.evaluate(tau):
t = self.model.time + e.delay
if e.useValuesFromTriggerTime:
--- a/simulation/Solver.py
+++ b/simulation/Solver.py
@@ -16,7 +16,7 @@ class Solver:
self.model.initialize()
# Add the time events to the event queue.
self.eventQueue = []
- for e in self.model.timeEvents.values():
+ for e in list(self.model.timeEvents.values()):
for t in e.times:
self.eventQueue.append((t, e))
# Add a null event at time = infinity, so we don't need to check if
--- a/simulation/TimeSeriesUniform.py
+++ b/simulation/TimeSeriesUniform.py
@@ -93,7 +93,7 @@ if __name__ == '__main__':
m.species['s1'] = Species(0)
m.reactions['r1'] = Reaction(m, [], [SpeciesReference('s1', 1)], '1')
solver = FirstReaction(m, 1000)
- simulation = TimeSeriesUniform(solver, ['s1'], ['r1'], range(11))
+ simulation = TimeSeriesUniform(solver, ['s1'], ['r1'], list(range(11)))
simulation.generateTrajectory()
print(simulation.populations)
print(simulation.reactionCounts)
--- a/src/solvers/env.py
+++ b/src/solvers/env.py
@@ -28,8 +28,8 @@ if serial['CXX'] == 'g++':
elif mode == 'debug':
serial.AppendUnique(CCFLAGS=['-g', '-DDEBUG_stlib'])
else:
- print('Error: Expected "debug" or "release" for the mode argument, '\
- 'found: "' + mode + '".')
+ print(('Error: Expected "debug" or "release" for the mode argument, '\
+ 'found: "' + mode + '".'))
Exit(1)
# Warnings. I don't use the pedantic flag because it will break code that
# uses long long.
--- a/state/Identifier.py
+++ b/state/Identifier.py
@@ -3,7 +3,7 @@
import re
import math
-builtinKeys = globals()['__builtins__'].keys()
+builtinKeys = list(globals()['__builtins__'].keys())
builtinExceptions = []
for s in builtinKeys:
if s[0].isupper():
@@ -12,7 +12,7 @@ builtinFunctions = []
for s in builtinKeys:
if s[0].islower():
builtinFunctions.append(s)
-mathFunctions = math.__dict__.keys()
+mathFunctions = list(math.__dict__.keys())
def hasFormatError(id, name='Object'):
"""Check if it is a valid Python identifier."""
--- a/state/Method.py
+++ b/state/Method.py
@@ -142,7 +142,7 @@ class Method:
# The attribute "dictionary" may not work as it should. In particular
# the test "x in attributes" may not work. Thus we need to directly
# use attributes.keys().
- keys = attributes.keys()
+ keys = list(attributes.keys())
if not 'id' in keys:
errors += 'Missing id attribute in method.\n'
# Fatal error.
--- a/state/Model.py
+++ b/state/Model.py
@@ -81,7 +81,7 @@ class Model:
return 'There are no reactions or events.'
# Check the species.
- compartmentIdentifiers = self.compartments.keys()
+ compartmentIdentifiers = list(self.compartments.keys())
for id in self.speciesIdentifiers:
error = self.species[id].hasErrors(compartmentIdentifiers)
if error:
@@ -126,7 +126,7 @@ class Model:
if error:
return 'Error in parameter ' + id + '.\n' + error
# Check that the parameter identifiers are unique.
- parameterIdentifiers = self.parameters.keys()
+ parameterIdentifiers = list(self.parameters.keys())
if len(set(parameterIdentifiers)) != len(parameterIdentifiers):
return 'The parameter identifiers are not unique.'
@@ -231,7 +231,7 @@ class Model:
self.parameters[id] = v
prefix = '__p_'
- decorator = KineticLawDecorator(prefix, self.parameters.keys(),
+ decorator = KineticLawDecorator(prefix, list(self.parameters.keys()),
'x', self.speciesIdentifiers)
result = ''
for i in range(len(self.reactions)):
@@ -246,7 +246,7 @@ class Model:
result += ' using namespace std;\n'
expression = self.reactions[i].propensity
# Parameters.
- for id in getParameters(expression, self.parameters.keys()):
+ for id in getParameters(expression, list(self.parameters.keys())):
result += ' const Number ' + prefix + id + ' = ' +\
repr(self.parameters[id].value) + ';\n'
f = decorator(expression)
@@ -288,14 +288,14 @@ class Model:
self.parameters[id] = v
prefix = '__p_'
- decorator = KineticLawDecorator(prefix, self.parameters.keys(),
+ decorator = KineticLawDecorator(prefix, list(self.parameters.keys()),
'x', self.speciesIdentifiers)
lines = ['inline',
'void',
'computePropensities(std::vector<double>* propensities, const std::vector<double>& x, const double t) {',
' using namespace std;']
# The parameters.
- for id in self.parameters.keys():
+ for id in list(self.parameters.keys()):
lines.append(' const double ' + prefix + id + ' = ' +\
repr(self.parameters[id].value) + ';')
# The propensities.
@@ -323,7 +323,7 @@ class Model:
def convertCustomToMassAction(self):
"""Try to convert the custom rate laws to mass action ones."""
- parameters = self.compartments.keys() + self.parameters.keys()
+ parameters = list(self.compartments.keys()) + list(self.parameters.keys())
for reaction in self.reactions:
reaction.convertCustomToMassAction(self.speciesIdentifiers,
parameters)
@@ -418,7 +418,7 @@ class Model:
if self.doUseUnnamedCompartment():
# Get a unique name.
unnamedCompartment = getUniqueName('Unnamed',
- self.compartments.keys())
+ list(self.compartments.keys()))
# Write the unnamed compartment.
c = Value('', '1')
c.value = 1.
@@ -834,8 +834,8 @@ def writeModelMathematica(model, method,
writer = MathematicaWriter(out)
else:
writer = MathematicaWriter()
- recordedSpecies = range(len(model.species))
- recordedReactions = range(len(model.reactions))
+ recordedSpecies = list(range(len(model.species)))
+ recordedReactions = list(range(len(model.reactions)))
model.writeMathematica(writer, method, recordedSpecies, recordedReactions)
def main():
@@ -843,7 +843,7 @@ def main():
from Method import Method
from SpeciesReference import SpeciesReference
- print('-'*79)
+ print(('-'*79))
print('Time Homogeneous')
model = Model()
model.id = 'model'
@@ -861,22 +861,22 @@ def main():
[SpeciesReference('s1', 2)], True, '2.5 * e'))
writeModelXml(model)
print('')
- print(model.writeSpeciesTable())
+ print((model.writeSpeciesTable()))
print('')
- print(model.writeReactionsTable())
+ print((model.writeReactionsTable()))
# The model must be evaluated for writing SBML or the C++ code.
model.evaluate()
writeModelSbml(model, open('model.xml', 'w'))
method = Method()
writeModelMathematica(model, method, open('model.nb', 'w'))
print('')
- print(model.makePropensitiesNumberOfReactions())
- print(model.makePropensitiesConstructor())
- print(model.makePropensitiesMemberFunctions(True))
+ print((model.makePropensitiesNumberOfReactions()))
+ print((model.makePropensitiesConstructor()))
+ print((model.makePropensitiesMemberFunctions(True)))
print('')
model.writeCmdl(sys.stdout)
- print('-'*79)
+ print(('-'*79))
print('Not mass-action.')
model = Model()
model.id = 'model'
@@ -894,22 +894,22 @@ def main():
[SpeciesReference('s1', 2)], False, '2.5 * e'))
writeModelXml(model)
print('')
- print(model.writeSpeciesTable())
+ print((model.writeSpeciesTable()))
print('')
- print(model.writeReactionsTable())
+ print((model.writeReactionsTable()))
# The model must be evaluated for writing SBML or the C++ code.
model.evaluate()
writeModelSbml(model, open('model.xml', 'w'))
method = Method()
writeModelMathematica(model, method, open('modelNma.nb', 'w'))
print('')
- print(model.makePropensitiesNumberOfReactions())
- print(model.makePropensitiesConstructor())
- print(model.makePropensitiesMemberFunctions(True))
+ print((model.makePropensitiesNumberOfReactions()))
+ print((model.makePropensitiesConstructor()))
+ print((model.makePropensitiesMemberFunctions(True)))
print('')
model.writeCmdl(sys.stdout)
- print('-'*79)
+ print(('-'*79))
print('Time Inhomogeneous')
model = Model()
model.id = 'model'
@@ -926,14 +926,14 @@ def main():
[SpeciesReference('s1', 2)], False, '1+exp(-t)'))
writeModelXml(model)
print('')
- print(model.writeSpeciesTable())
+ print((model.writeSpeciesTable()))
print('')
- print(model.writeReactionsTable())
+ print((model.writeReactionsTable()))
# The model must be evaluated for writing SBML or the C++ code.
model.evaluateInhomogeneous()
writeModelSbml(model, open('model.xml', 'w'))
print('')
- print(model.makeInhomogeneousPropensities(True))
+ print((model.makeInhomogeneousPropensities(True)))
print('')
if __name__ == '__main__':
--- a/state/ParameterEvaluation.py
+++ b/state/ParameterEvaluation.py
@@ -43,7 +43,7 @@ def checkIdentifiers(identifiers):
Parameters:
- identifiers is a list of the identifiers."""
# Check that each is a valid SBML identifier.
- reserved = math.__dict__.keys()
+ reserved = list(math.__dict__.keys())
for id in identifiers:
matchObject = re.match('([a-zA-z]|_)[a-zA-Z0-9_]*', id)
if not (matchObject and matchObject.group(0) == id):
@@ -157,7 +157,7 @@ def evaluateValues(parameters):
prefix = '__p_'
# Make a list of identifiers and mangled expressions.
remaining = [(id, mangle(parameters[id].expression, prefix,
- parameters.keys())) for id in parameters]
+ list(parameters.keys()))) for id in parameters]
passes = 0
while remaining:
passes += 1
@@ -201,7 +201,7 @@ def evaluateParametersOld(__parameters):
for id in __names.parameters:
__names.parameters[id].value = None
# Evaluate the expressions.
- __names.remaining = __names.parameters.keys()
+ __names.remaining = list(__names.parameters.keys())
__names.passes = 0
while __names.remaining:
__names.passes += 1
@@ -240,7 +240,7 @@ def evaluateInitialAmounts(species, para
for id in parameters:
assert parameters[id].value is not None
exec(prefix + id + " = parameters['" + id + "'].value")
- parameterIdentifiers = parameters.keys()
+ parameterIdentifiers = list(parameters.keys())
# Evaluate the initial amounts for the species.
for id in species:
# Start with a null value.
@@ -272,7 +272,7 @@ def evaluatePropensityFactors(reactions,
for id in parameters:
assert parameters[id].value is not None
exec(prefix + id + " = parameters['" + id + "'].value")
- parameterIdentifiers = parameters.keys()
+ parameterIdentifiers = list(parameters.keys())
# Evaluate the propensity factors for the mass action kinetic laws.
for r in reactions:
# Start with a null value.
@@ -292,9 +292,9 @@ def evaluatePropensityFactors(reactions,
def makeValuesDictionary(model):
values = {}
- for k, v in model.parameters.iteritems():
+ for k, v in model.parameters.items():
values[k] = v
- for k, v in model.compartments.iteritems():
+ for k, v in model.compartments.items():
values[k] = v
return values
@@ -319,52 +319,52 @@ def main():
from Value import Value
......@@ -2016,551 +738,85 @@ Last-Update: Tue, 10 Sep 2019 20:29:13 +0200
if __name__ == '__main__':
--- a/state/PoissonSampler.py
+++ b/state/PoissonSampler.py
@@ -386,7 +386,7 @@ if __name__ == '__main__':
tests = 20
h = Histogram(size, 1)
- parameters = range(1,21)
+ parameters = list(range(1,21))
for k in parameters:
count = 0
for i in range(tests):
@@ -394,7 +394,7 @@ if __name__ == '__main__':
h.setCurrent(0)
while (histogramDistance(h, pmf) > 0.1):
count += generateErlang(k, h, mean)
- print(k, count / float(tests))
+ print((k, count / float(tests)))
sys.exit(0)
@@ -403,7 +403,7 @@ if __name__ == '__main__':
h.clear()
while (histogramDistance(h, pmf) > 0.1):
count += generateErlang3(h, mean)
- print(count / float(tests))
+ print((count / float(tests)))
count = 0
@@ -411,21 +411,21 @@ if __name__ == '__main__':
h.clear()
while (histogramDistance(h, pmf) > 0.1):
count += generateErlang2(h, mean)
- print(count / float(tests))
+ print((count / float(tests)))
count = 0
for i in range(tests):
h.clear()
while (histogramDistance(h, pmf) > 0.1):
count += generateExponential(h, mean)
- print(count / float(tests))
+ print((count / float(tests)))
count = 0
for i in range(tests):
h.clear()
while (histogramDistance(h, pmf) > 0.1):
count += generateSingle(h, mean)
- print(count / float(tests))
+ print((count / float(tests)))
#print(histogramDistance(h, pmf))
#p = h.getProbabilities()
@@ -442,14 +442,14 @@ if __name__ == '__main__':
h.clear()
while (histogramDistance(h, pmf) > 0.1):
count += generateFillVariable(h, mean, splits)
- print(count / float(tests), splits)
+ print((count / float(tests), splits))
sys.exit(0)
count = 0
differences = [1,2,4,8]
factors = [2,4]
- initials = range(1,2)
+ initials = list(range(1,2))
for difference in differences:
for factor in factors:
for initial in initials:
@@ -458,7 +458,7 @@ if __name__ == '__main__':
h.clear()
while (histogramDistance(h, pmf) > 0.1):
count += generateFillTimes(h, mean, difference, times)
- print(count / float(tests), difference, factor, initial)
+ print((count / float(tests), difference, factor, initial))
count = 0
@@ -469,7 +469,7 @@ if __name__ == '__main__':
h.clear()
while (histogramDistance(h, pmf) > 0.1):
count += generateFill(h, mean, difference)
- print(count / float(tests), difference)
+ print((count / float(tests), difference))
count = 0
@@ -481,13 +481,13 @@ if __name__ == '__main__':
h.clear()
while (histogramDistance(h, pmf) > 0.1):
count += generate(h, mean, times)
- print(count / float(tests), times)
+ print((count / float(tests), times))
#factors = range(2,5)
#initials = range(1,5)
- factors = range(2,5)
- initials = range(1,2)
+ factors = list(range(2,5))
+ initials = list(range(1,2))
for factor in factors:
for initial in initials:
times = splittingTimes(mean, factor, initial)
@@ -496,7 +496,7 @@ if __name__ == '__main__':
h.clear()
while (histogramDistance(h, pmf) > 0.1):
count += generate(h, mean, times)
- print(factor, initial, count / float(tests), times)
+ print((factor, initial, count / float(tests), times))
factors = [1.5, 1.6, 1.7, 1.8, 1.9]
@@ -508,5 +508,5 @@ if __name__ == '__main__':
h.clear()
while (histogramDistance(h, pmf) > 0.1):
count += generate(h, mean, times)
- print(factor, count / float(tests), times)
+ print((factor, count / float(tests), times))
--- a/state/Reaction.py
+++ b/state/Reaction.py
@@ -323,7 +323,7 @@ class Reaction:
# The attribute "dictionary" may not work as it should. In particular
# the test "x in attributes" may not work. Thus we need to directly
# use attributes.keys().
- keys = attributes.keys()
+ keys = list(attributes.keys())
if not 'id' in keys:
return 'Missing id attribute in reaction.\n'
self.id = attributes['id']
--- a/state/Species.py
+++ b/state/Species.py
@@ -63,17 +63,17 @@ class Species:
# The attribute "dictionary" may not work as it should. In particular
# the test "x in attributes" may not work. Thus we need to directly
# use attributes.keys().
- keys = attributes.keys()
+ keys = list(attributes.keys())
# If the compartment is not specified, use the unnamed compartment.
- if 'compartment' in attributes.keys():
+ if 'compartment' in list(attributes.keys()):
self.compartment = attributes['compartment']
else:
self.compartment = ''
- if 'name' in attributes.keys():
+ if 'name' in list(attributes.keys()):
self.name = attributes['name']
else:
self.name = ''
- if 'initialAmount' in attributes.keys():
+ if 'initialAmount' in list(attributes.keys()):
self.initialAmount = attributes['initialAmount']
else:
self.initialAmount = ''
@@ -93,22 +93,22 @@ def main():
x.writeXml(writer, 's1')
--- a/gui/TrajectoriesList.py
+++ b/gui/TrajectoriesList.py
@@ -209,11 +209,11 @@ class TrajectoriesList(wx.Panel, StateMo
self.updateState()
x = Species('C1', 'species 1', '')
- print evaluateInitialAmounts({'s1':x}, {})
+ print(evaluateInitialAmounts({'s1':x}, {}))
def tearDown(self):
- for child in self.children.values():
+ for child in list(self.children.values()):
child.Destroy()
x = Species('C1', 'species 2', '1')
x.writeXml(writer, 's2')
def updateChildren(self):
- for x in self.children.values():
+ for x in list(self.children.values()):
x.refresh()
x = Species('C1', 'species 2', '-1')
# I don't check the initial amount expression with hasErrors().
- print evaluateInitialAmounts({'s2':x}, {})
+ print(evaluateInitialAmounts({'s2':x}, {}))
def clear(self):
@@ -646,37 +646,37 @@ class State:
self.identifiers = []
x = Species('C1', 'species 2', 'p1')
- print evaluateInitialAmounts({'s1':x}, {})
+ print(evaluateInitialAmounts({'s1':x}, {}))
def delete(self, model, method):
- print 'delete', model, method
+ print('delete', model, method)
x = Species('C1', 'species 2', 'p2')
p = Value('', '5.0')
p.value = 5.0
- print evaluateInitialAmounts({'s1':x}, {'p1':p})
+ print(evaluateInitialAmounts({'s1':x}, {'p1':p}))
def plotPopulationStatistics(self, model, method):
- print 'plotPopulationStatistics', model, method
+ print('plotPopulationStatistics', model, method)
if __name__ == '__main__':
main()
--- a/state/State.py
+++ b/state/State.py
@@ -109,7 +109,7 @@ class RecordingThreadPythonTimeSeriesFra
break
# Record the Mersenne twister state.
self.state.listOfMt19937States[0] = list(random.getstate()[1])
- except Exception, error:
+ except Exception as error:
wx.MessageBox(str(error), 'Error!', style=wx.OK|wx.ICON_EXCLAMATION)
self.state.numberOfTrajectories = 0
self.state.threads = []
@@ -180,7 +180,7 @@ class RecordingThreadTimeSeriesFrames(Re
self.state.readTimeSeriesFrames(self.output, self.index)
# Increment the progress gauge.
self.main.incrementProgressGauge(numberOfTrajectories)
- except Exception, error:
+ except Exception as error:
self.handleException(error)
def plotReactionStatistics(self, model, method):
- print 'plotReactionStatistics', model, method
+ print('plotReactionStatistics', model, method)
class RecordingThreadTrajectoryAll(RecordingThread):
@@ -211,7 +211,7 @@ class RecordingThreadTrajectoryAll(Recor
self.state.readTimeSeriesAllReactions(self.output, self.index)
# Increment the progress gauge.
self.main.incrementProgressGauge(numberOfTrajectories)
- except Exception, error:
+ except Exception as error:
self.handleException(error)
def plotPopulations(self, model, method):
- print 'plotPopulations', model, method
+ print('plotPopulations', model, method)
class RecordingThreadHistogramFrames(RecordingThread):
@@ -241,7 +241,7 @@ class RecordingThreadHistogramFrames(Rec
self.output.readline()
# Record the histograms from the generated trajectories.
self.state.readHistogramFrames(self.output, self.index)
- except Exception, error:
+ except Exception as error:
self.handleException(error)
def plotReactions(self, model, method):
- print 'plotReactions', model, method
+ print('plotReactions', model, method)
class RecordingThreadHistogramAverage(RecordingThread):
@@ -271,7 +271,7 @@ class RecordingThreadHistogramAverage(Re
self.output.readline()
# Record the histograms from the generated trajectories.
self.state.readHistogramAverage(self.output, self.index)
- except Exception, error:
+ except Exception as error:
self.handleException(error)
def displayStatisticsLast(self, model, method):
- print 'display statistics last', model, method
+ print('display statistics last', model, method)
class State:
@@ -338,7 +338,7 @@ class State:
"""Insert a new model. Return the new model identifier."""
# Make an empty model with a unique identifier.
model = Model()
- model.id = getNewIntegerString(self.models.keys())
+ model.id = getNewIntegerString(list(self.models.keys()))
# Add the model to the dictionary.
self.models[model.id] = model
# Return the new model's key.
@@ -350,7 +350,7 @@ class State:
assert id in self.models
# Make an empty model with a unique identifier.
model = copy.deepcopy(self.models[id])
- model.id = getUniqueName(id, self.models.keys())
+ model.id = getUniqueName(id, list(self.models.keys()))
# Add the model to the dictionary.
self.models[model.id] = model
# Return the new model's key.
@@ -362,7 +362,7 @@ class State:
assert id in self.models
# Make a duplicated model with a unique identifier.
model = duplicateModel(self.models[id], multiplicity, useScaling)
- model.id = getUniqueName(id, self.models.keys())
+ model.id = getUniqueName(id, list(self.models.keys()))
# Add the model to the dictionary.
self.models[model.id] = model
# Return the new model's key.
@@ -372,7 +372,7 @@ class State:
"""Insert new simulation method. Return the new identifier."""
# Make an empty model with a unique identifier.
m = Method()
- m.id = getNewIntegerString(self.methods.keys())
+ m.id = getNewIntegerString(list(self.methods.keys()))
# Add the method to the dictionary.
self.methods[m.id] = m
# Return the new key.
@@ -383,7 +383,7 @@ class State:
assert id in self.methods
# Make an empty method with a unique identifier.
m = copy.deepcopy(self.methods[id])
- m.id = getUniqueName(id, self.methods.keys())
+ m.id = getUniqueName(id, list(self.methods.keys()))
# Add to the dictionary.
self.methods[m.id] = m
# Return the new key.
@@ -395,13 +395,13 @@ class State:
self.models[new].id = new
del self.models[old]
# Change in the simulation output.
- for (modelId, methodId) in self.output.keys():
+ for (modelId, methodId) in list(self.output.keys()):
if modelId == old:
self.output[(new, methodId)] =\
self.output[(old, methodId)]
del self.output[(old, methodId)]
# Change in the set of solvers.
- for (modelId, methodId) in self.solvers.keys():
+ for (modelId, methodId) in list(self.solvers.keys()):
if modelId == old:
self.solvers[(new, methodId)] =\
self.solvers[(old, methodId)]
@@ -413,26 +413,26 @@ class State:
self.methods[new].id = new
del self.methods[old]
# Change in the simulation output.
- for (modelId, methodId) in self.output.keys():
+ for (modelId, methodId) in list(self.output.keys()):
if methodId == old:
self.output[(modelId, new)] =\
self.output[(modelId, old)]
del self.output[(modelId, old)]
# Change in the set of solvers.
- for (modelId, methodId) in self.solvers.keys():
+ for (modelId, methodId) in list(self.solvers.keys()):
if methodId == old:
self.solvers[(modelId, new)] =\
self.solvers[(modelId, old)]
del self.solvers[(modelId, old)]
def doesModelHaveDependentOutput(self, id):
- for (modelId, methodId) in self.output.keys():
+ for (modelId, methodId) in list(self.output.keys()):
if id == modelId:
return True
return False
def doesMethodHaveDependentOutput(self, id):
- for (modelId, methodId) in self.output.keys():
+ for (modelId, methodId) in list(self.output.keys()):
if id == methodId:
return True
return False
@@ -823,7 +823,7 @@ class State:
sourceName = simulationMethods.names[method.timeDependence]\
[method.category][method.method][method.options]
assert not (modelId, methodId) in self.solvers
- executableName = getUniqueName(sourceName, self.solvers.values())
+ executableName = getUniqueName(sourceName, list(self.solvers.values()))
if sys.platform in ('win32', 'win64'):
suffix = '.exe'
else:
@@ -1139,7 +1139,7 @@ class State:
n = len(output.recordedSpecies)
output.statistics = []
for f in output.frameTimes:
- data = map(float, inputFile.readline().rstrip().split())
+ data = list(map(float, inputFile.readline().rstrip().split()))
if len(data) != 2 * n:
raise Exception('Expected a list of %s numbers in the row '\
'for time frame %s.' % (2 * n, f))
@@ -1156,7 +1156,7 @@ class State:
"""
# Mean and standard deviation for each recorded species.
n = len(output.recordedSpecies)
- data = map(float, inputFile.readline().rstrip().split())
+ data = list(map(float, inputFile.readline().rstrip().split()))
if len(data) != 2 * n:
raise Exception('Expected a list of %s numbers.' % 2 * n)
output.statistics = [(data[2*i], data[2*i+1]) for i in range(n)]
@@ -1195,10 +1195,10 @@ class State:
errorMessage = inputFile.readline().rstrip()
if errorMessage == '':
# List of populations.
- populations = map(float, inputFile.readline().rstrip().split())
+ populations = list(map(float, inputFile.readline().rstrip().split()))
# List of reaction counts.
- reactionCounts = map(float,
- inputFile.readline().rstrip().split())
+ reactionCounts = list(map(float,
+ inputFile.readline().rstrip().split()))
# Acquire the lock so that we can modify self.currentOutput.
self.lock.acquire()
try:
@@ -1214,7 +1214,7 @@ class State:
finally:
self.lock.release()
# List of final MT 19937 state.
- state = map(int, inputFile.readline().rstrip().split())
+ state = list(map(int, inputFile.readline().rstrip().split()))
# If this is a stochastic method.
if state:
assert len(state) == 625
@@ -1253,11 +1253,11 @@ class State:
errorMessage = inputFile.readline().rstrip()
if errorMessage == '':
# List of initial populations.
- initial = map(float, inputFile.readline().rstrip().split())
+ initial = list(map(float, inputFile.readline().rstrip().split()))
# List of reaction indices.
- indices = map(int, inputFile.readline().rstrip().split())
+ indices = list(map(int, inputFile.readline().rstrip().split()))
# List of reaction times.
- times = map(float, inputFile.readline().rstrip().split())
+ times = list(map(float, inputFile.readline().rstrip().split()))
# Acquire the lock so that we can modify self.currentOutput.
self.lock.acquire()
try:
@@ -1274,7 +1274,7 @@ class State:
finally:
self.lock.release()
# List of final MT 19937 state.
- state = map(int, inputFile.readline().rstrip().split())
+ state = list(map(int, inputFile.readline().rstrip().split()))
# If this is a stochastic method.
if state:
assert len(state) == 625
@@ -1339,7 +1339,7 @@ class State:
finally:
self.lock.release()
# List of final MT 19937 state.
- state = map(int, inputFile.readline().rstrip().split())
+ state = list(map(int, inputFile.readline().rstrip().split()))
assert len(state) == 625
# Record the RNG state.
self.listOfMt19937States[processIndex] = state
@@ -1397,7 +1397,7 @@ class State:
finally:
self.lock.release()
# List of final MT 19937 state.
- state = map(int, inputFile.readline().rstrip().split())
+ state = list(map(int, inputFile.readline().rstrip().split()))
assert len(state) == 625
# Record the RNG state.
self.listOfMt19937States[processIndex] = state
@@ -1477,12 +1477,12 @@ class State:
# number of species to record
n = int(inputFile.readline())
# list of species to record
- recordedSpecies = map(int, inputFile.readline().split())
+ recordedSpecies = list(map(int, inputFile.readline().split()))
assert n == len(recordedSpecies)
# number of reactions to record
n = int(inputFile.readline())
# list of reactions to record
- recordedReactions = map(int, inputFile.readline().split())
+ recordedReactions = list(map(int, inputFile.readline().split()))
assert n == len(recordedReactions)
return recordedSpecies, recordedReactions
@@ -1534,7 +1534,7 @@ class State:
# Check that the identifier is distinct.
if model.id in self.models:
# If not, change it.
- model.id = getNewIntegerString(self.models.keys())
+ model.id = getNewIntegerString(list(self.models.keys()))
# Add the reverse reactions, if any.
model.addReverseReactions()
# Try converting custom propensity function to mass action equivalents.
@@ -1561,7 +1561,7 @@ class State:
# If reading the model was successful.
if model:
# Get a distinct identifier.
- model.id = getNewIntegerString(self.models.keys())
+ model.id = getNewIntegerString(list(self.models.keys()))
# Add the model to the dictionary.
self.models[model.id] = model
# Return the new model's key.
@@ -1575,12 +1575,12 @@ class State:
writer.beginElement('cain', {'version':self.version})
if self.models:
writer.beginElement('listOfModels')
- for model in self.models.values():
+ for model in list(self.models.values()):
model.writeXml(writer)
writer.endElement()
if self.methods:
writer.beginElement('listOfMethods')
- for p in self.methods.values():
+ for p in list(self.methods.values()):
p.writeXml(writer)
writer.endElement()
if self.output:
--- a/state/TimeEvent.py
+++ b/state/TimeEvent.py
@@ -46,7 +46,7 @@ class TimeEvent:
# The attribute "dictionary" may not work as it should. In particular
# the test "x in attributes" may not work. Thus we need to directly
# use attributes.keys().
- keys = attributes.keys()
+ keys = list(attributes.keys())
for x in ['id', 'times', 'assignments']:
if not x in keys:
return 'Missing ' + x + ' attribute in time event.\n'
--- a/state/TrajectoryCalculator.py
+++ b/state/TrajectoryCalculator.py
@@ -135,16 +135,16 @@ def main():
t.appendInitialPopulations([13, 17])
times, populations, reactionCounts =\
x.makeFramesAtReactionEvents(t, 0, True, True)
- print 'times'
- print times
- print 'populations'
- print populations
- print 'reactionCounts'
- print reactionCounts
- print 'Final reaction counts.'
- print x.computeFinalReactionCounts(t, 0)
- print 'Final populations.'
- print x.computeFinalPopulations(t, 0)
+ print('times')
+ print(times)
+ print('populations')
+ print(populations)
+ print('reactionCounts')
+ print(reactionCounts)
+ print('Final reaction counts.')
+ print(x.computeFinalReactionCounts(t, 0))
+ print('Final populations.')
+ print(x.computeFinalPopulations(t, 0))
def displayStatisticsAll(self, model, method):
- print 'display statistics all', model, method
+ print('display statistics all', model, method)
if __name__ == '__main__':
main()
--- a/state/TriggerEvent.py
+++ b/state/TriggerEvent.py
@@ -54,7 +54,7 @@ class TriggerEvent:
# The attribute "dictionary" may not work as it should. In particular
# the test "x in attributes" may not work. Thus we need to directly
# use attributes.keys().
- keys = attributes.keys()
+ keys = list(attributes.keys())
for x in ['id', 'trigger', 'assignments']:
if not x in keys:
return 'Missing ' + x + ' attribute in trigger event.\n'
--- a/state/Value.py
+++ b/state/Value.py
@@ -45,7 +45,7 @@ class Value:
# The attribute "dictionary" may not work as it should. In particular
# the test "x in attributes" may not work. Thus we need to directly
# use attributes.keys().
- keys = attributes.keys()
+ keys = list(attributes.keys())
if not 'expression' in keys:
return 'Missing expression attribute in parameter or compartment.\n'
self.expression = attributes['expression']
--- a/gui/Application.py
+++ b/gui/Application.py
@@ -1,4 +1,4 @@
-#! /usr/bin/env python
+#!/usr/bin/python3
def displayLast(self, model, method):
- print 'display last', model, method
+ print('display last', model, method)
"""The script that launches Cain."""
def displayAll(self, model, method):
- print 'display all', model, method
+ print('display all', model, method)
--- a/fio/SbmlLevel1To2.py
+++ b/fio/SbmlLevel1To2.py
@@ -1,10 +1,11 @@
+#!/usr/bin/python3
"""SbmlLevel1To2.py."""
def csv(self, model, method):
- print 'csv', model, method
+ print('csv', model, method)
import sys, re
def gnuplot(self, model, method):
- print 'gnuplot', model, method
+ print('gnuplot', model, method)
if len(sys.argv) != 3:
print("""Usage:
-python SbmlLevel1To2.py input.xml output.xml
+python3 SbmlLevel1To2.py input.xml output.xml
Bad command line arguments. Exiting...""")
sys.exit()
class TrajectoriesListFrame(wx.Frame):
def __init__(self, parent=None):
@@ -689,13 +689,13 @@ class TrajectoriesListFrame(wx.Frame):
editor.insertItem('m3', 'p3', '300')
def exportCsv(self, modelId, methodId):
- print 'exportCsv', modelId, methodId
+ print('exportCsv', modelId, methodId)
def exportGnuplot(self, modelId, methodId):
- print 'exportGnuplot', modelId, methodId
+ print('exportGnuplot', modelId, methodId)
def deleteOutput(self, modelId, methodId):
- print 'deleteOutput', modelId, methodId
+ print('deleteOutput', modelId, methodId)
def main():