PySCeS Module documentation

PyscesUtils

The PyscesUtils module holds a collection of methods of general use such as timers and array export fucntionality that can be accessed as pysces.write.

pysces.PyscesUtils.ConvertFileD2U(Filelist)[source]

Converts a [Filename] from rn to n inplace no effect if the line termination is correct

  • Filelist a file or list of files to convert

pysces.PyscesUtils.ConvertFileU2D(Filelist)[source]

Converts a [Filename] from n to rn inplace no effect if the line termination is correct:

  • Filelist a file or list of files to convert

pysces.PyscesUtils.CopyModels(*args, **kwargs)[source]
pysces.PyscesUtils.CopyTestModels(*args, **kwargs)[source]
class pysces.PyscesUtils.TimerBox[source]

A timer “container” class that can be used to hold user defined timers

normal_timer(name)[source]

Creates a normal timer method with <name> in the TimerBox instance. Normal timers print the elapsed time since creation when called.

  • name the timer name

reset_step(name)[source]

Reset the number of steps of timer <name> in the TimerBox to zero

  • name the step timer whose steps should be reset

step_timer(name, maxsteps)[source]

Creates a step timer method with <name> in the TimerBox instance. Step timers print the elapsed time as well as the next step out of maxsteps when called.

  • name the timer name

  • maxsteps the maximum number of steps associated with this timer

stop(name)[source]

Delete the timer <name> from the TimerBox instance

  • name the timer name to delete

pysces.PyscesUtils.VersionCheck(ver='0.1.5')[source]
class pysces.PyscesUtils.WriteOutput[source]

This code is adapted from:

CBMPy: CBTools module

Constraint Based Modelling in Python (http://cbmpy.sourceforge.net) Copyright (C) 2009-2017 Brett G. Olivier, VU University Amsterdam, Amsterdam, The Netherlands

exportArray2CSV(arr, fname)[source]

Export an array to fname.csv

  • arr the an array like object

  • fname the output filename

  • sep [default=’,’] the column separator

exportArray2TXT(arr, fname)[source]

Export an array to fname.txt

  • arr the an array like object

  • fname the output filename

  • sep [default=’,’] the column separator

exportLabelledArray(arr, names, fname, sep=',', sformat='%f')[source]

Write a 2D array type object to file

  • arr the an array like object

  • names the list of row names

  • fname the output filename

  • sep [default=’,’] the column separator

  • format [default=’%s’] the output number format

exportLabelledArray2CSV(arr, names, fname)[source]

Export an array with row names to fname.csv

  • arr the an array like object

  • names the list of row names

  • fname the output filename

exportLabelledArray2TXT(arr, names, fname)[source]

Export an array with row names to fname.txt

  • arr the an array like object

  • names the list of row names

  • fname the output filename

exportLabelledArrayWithHeader(arr, names, header, fname, sep=',', format='%f')[source]

Export an array with row names and header

  • arr the an array like object

  • names the list of row names

  • header the list of column names

  • fname the output filename

  • sep [default=’,’] the column separator

  • format [default=’%s’] the output number format

  • appendlist [default=False] if True append the array to fname otherwise create a new file

exportLabelledArrayWithHeader2CSV(arr, names, header, fname)[source]

Export an array with row names and header to fname.csv

  • arr the an array like object

  • names the list of row names

  • header the list of column names

  • fname the output filename

exportLabelledArrayWithHeader2TXT(arr, names, header, fname)[source]

Export an array with row names and header to fname.txt

  • arr the an array like object

  • names the list of row names

  • header the list of column names

  • fname the output filename

exportLabelledLinkedList(arr, fname, names=None, sep=',', format='%s', appendlist=False)[source]

Write a 2D linked list [[…],[…],[…],[…]] and optionally a list of row labels to file:

  • arr the linked list

  • fname the output filename

  • names the list of row names

  • sep [default=’,’] the column separator

  • format [default=’%s’] the output number format

  • appendlist [default=False] if True append the array to fname otherwise create a new file

pysces.PyscesUtils.str2bool(s)[source]

Tries to convert a string to a Python boolean

  • s True if ‘True’, ‘true’ or’1’ else False

PyscesPlot2

PyscesPlot2 is a new graphics susbsystem for PySCeS which will include a Unified Plotting Interface which can take advantage of different plotting backends via a common user interface.

class pysces.PyscesPlot2.FIFOBuffer(size)[source]

Simple fixed size FIFO buffer.

add(x)[source]
get()[source]
class pysces.PyscesPlot2.GnuPlotUPI(work_dir=None, gnuplot_dir=None)[source]

PySCeS/GnuPlot is reborn, leaner and meaner than ever before. This class enables plotting with GnuPlot via a subprocess link:

  • work_dir optional argument setting directory for dat file(s)

  • gnuplot_dir optional argument specifying the location of pgnuplot.exe (win32) or gnuplot

GnuPlot backend to the Unified Plotting Interface.

CommonStyleDefs = {'lines': 'w l', 'points': 'w p'}
DATF_FORMAT = '%.8e'
PAUSE_TIME = 0.1
Terminals = {'png': 'medium size 800,600', 'windows': '', 'x11': ''}
export(name, directory=None, type='png')[source]

Export the current plot as a <format> file.

  • filename the filename

  • directory optional (default = current working directory)

  • type the file format (default=’png’).

Currently only PNG is guaranteed to be available in all interfaces.

g_file_write_array(arr, dfmt=None)[source]

Write a normal (2D) dataset to temp file. Dumps the array to file using the format:

  • arr the array (r>0, c>1)

  • fmt default ‘%.8e’

g_file_write_array3D(arr, yaxis=1, dfmt=None)[source]

Write a GnuPlot format 3D dataset. The yaxis argument specifies the column that should be used to split the dataset into GnuPlot slices.

  • arr the array (r>1, c>2)

  • fmt default ‘%.8e’

  • yaxis default 1

g_pause()[source]

A small pause defined by self.PAUSE_TIME (multiplied by 2 when in multiplot).

g_write(cmd)[source]

Write a command to the GnuPlot interpreter

  • cmd the GnuPlot command

plot(data, x, y, title='', format='w l')[source]

Plot a single line data[y] vs data[x] where:

  • data the data array

  • x x column index

  • y y column index

  • title is the line key

  • format is the GnuPlot format string (default=’w l’)

Format can also be the CommonStyle ‘lines’ or ‘points’.

plotLines(data, x, y=[], titles=[], formats=['w l'])[source]

Plot a multiple lines data[y1, y2, ] vs data[x] where:

  • data the data array

  • x x column index

  • y is a list of line indexes, if empty all of y not including x is plotted

  • titles is a list of line keys if empty Line1, Line2, Line3 is used

  • formats is a list (per line) of GnuPlot format strings (default=’w l’).

If formats only contains a single item, this format is used for all lines and can also be the CommonStyle ‘lines’ or ‘points’.

replot()[source]

Replot the current GnuPlot plot

replotAndWait(seconds=0.5)[source]

Replot the current GnuPlot plot and wait default (seconds = 0.5) or until enter is pressed (seconds = -1)

save(name, directory=None, dfmt=None)[source]

Save the last plot as a GnuPlot file name.plt which references name.dat.

  • name the name of the GnuPlot plt and and datafile

  • directory (optional) the directory to use (defaults to working directory)

  • dfmt is ignored and uses the value of self.DATF_FORMAT

set(key, value='')[source]

Send set <key> or optionally set <key> <value> to GnuPlot.

setAxisLabel(axis, label='')[source]

Set the axis label:

  • axis = x, y, z, xy, xz, yz, zyx

  • label = string (default=’’)

Called with only the axis argument clears the axis label.

setDataFileNumberFormat(format='%.8e')[source]

Sets the format string for data written to file

  • format format string (default=’%.8e’)

setGraphTitle(title='PySCeS Plot')[source]

Set the graph title, unset if title argument is None

  • title (string, default=’PySCeS Plot’) the graph title

setGrid(value)[source]

Display or remove graph grid.

  • value (boolean) True (on) or False (off)

setKey(value=False)[source]

Enable or disable the current plot key, no arguments removes key.

  • value boolean (default = False)

setLogScale(axis)[source]

Set axis to logscale where:

  • axis = x, y, z, xy, xz, yz, zyx

setMultiplot()[source]

Begin a multiplot session

setNoLogScale(axis)[source]

Set axis to a linear scale where:

  • axis = x, y, z, xy, xz, yz, zyx

setOrigin(xpos=0, ypos=0)[source]

Set the origin (lower left corner) of the next plot. Uses GnuPlot screen coordinates. If no arguments are supplied reset origin to 0,0.

  • xpos of next plot (default = 0)

  • ypos of next plot (default = 0)

setRange(axis, min=None, max=None)[source]

Set axis range where:

  • axis = x, y, z, xy, xz, yz, zyx

  • min = range(s) lower bound (default=None) autoscale

  • max = range(s) upper bound (default=None) autoscale

If only the axis argument is provided, GnuPlot will autoscale the ranges to the data.

setSize(width=1.0, height=1.0)[source]

Set the size of the next plot relative to the GnuPlot canvas (e.g. screen) size which is defined to be 1. For example if width = height = 0.5 the plot is 1/4 the size of the viewable canvas. If no arguments are supplied reset size to 1,1.

  • width of next plot (default = 1.0)

  • height of next plot (default = 1.0)

setSizeAndOrigin(width=1, height=1, xpos=0, ypos=0)[source]

Set the size and origin of the next plot. If no arguments are supplied, reset the size to 1,1 and origin to 0.0

  • width of next plot (default = 1.0)

  • height of next plot (default = 1.0)

  • xpos of next plot (default = 0)

  • ypos of next plot (default = 0)

setTerminal(name, options='')[source]

Sets the terminal, gnuplot: set terminal name options

splot(data, x, y, z, titles='', format='w l')[source]

Plot a surface data[z] vs data[y] vs data[x] where:

  • data the data array

  • x x column index

  • y y column index

  • z z column index

  • titles is the surface key

  • format is the GnuPlot format string (default=’w l’)

Format can also be the CommonStyle ‘lines’ or ‘points’.

splotSurfaces(data, x, y, z=[], titles=[], formats=['w l'])[source]

Plot data[z1, z2, ] vs data[y] vs data[x] where:

  • data the data array

  • x x column index

  • y y column index

  • z list of z column indexes, if empty all of z not including x, y are plotted

  • titles is a list of surface keys, if empty Surf1, Surf2, Surf3 is used

  • formats is a list (per line) of GnuPlot format strings (default=’w l’).

If formats only contains a single item, this format is used for all surface and can also be the CommonStyle ‘lines’ or ‘points’.

unset(key, value='')[source]

Send unset <key> or optionally unset <key> <value> to GnuPlot.

unsetMultiplot()[source]

End a multiplot session.

class pysces.PyscesPlot2.MatplotlibUPI(work_dir=None, backend=None)[source]

Refactored Matplotlib backend to the Unified Plotting Interface

  • work_dir (optional) working directory

CommonStyleDefs = {'lines': '-', 'points': 'o'}
MAX_OPEN_WINDOWS = 10
closeAll()[source]

Close all open matplotlib figures.

export(name, directory=None, type='png')[source]

Export the current plot as a <format> file.

  • filename the filename

  • directory optional (default = current working directory)

  • type the file format (default=’png’).

Currently only PNG is guaranteed to be available in all interfaces.

hold(hold=False)[source]

Enable plot holding where each new graph is plotted on top of the previous one.

  • hold boolean (default = False)

isnotebook()[source]
plot(data, x, y, title='', format='-')[source]

Plot a single line data[y] vs data[x] where:

  • data the data array

  • x x column index

  • y y column index

  • title is the line key

  • format is the Matplotlib format string (default=’-‘)

Format can also be the CommonStyle ‘lines’ or ‘points’.

plotLines(data, x, y=[], titles=[], formats=['-'])[source]

Plot a multiple lines data[y1, y2, ] vs data[x] where:

  • data the data array

  • x x column index

  • y is a list of line indexes

  • titles is a list of line keys

  • formats is a list (per line) of Matplotlib format strings.

If formats only contains a single item, this format is used for all lines and can also be the CommonStyle ‘lines’ or ‘points’.

pyplot = None
save(name, directory=None, dfmt='%.8e')[source]

Save the plot data to

  • filename the filename

  • directory optional (default = current working directory)

  • dfmt the data format string (default=’%.8e’)

setAxisLabel(axis, label='')[source]

Set the axis label:

  • axis = x, y, z, xy, xz, yz, zyx

  • label = string (default=’’)

Called with only the axis argument clears the axis label.

setGraphTitle(title='PySCeS Plot')[source]

Set the graph title, unset if title=None

  • title (string, default=’PySCeS Plot’) the graph title

setGrid(value)[source]

Display or remove graph grid.

  • value (boolean) True (on) or False (off)

setKey(value=False)[source]

Enable or disable the current plot key, no arguments removes key.

  • value boolean (default = False)

setLineWidth(width=1)[source]

Sets the line width for current axis

  • width the line width

setLogScale(axis)[source]

Set axis to logscale where:

  • axis = x, y, z, xy, xz, yz, zyx

setNoLogScale(axis)[source]

Set axis to a linear scale where:

  • axis = x, y, z, xy, xz, yz, zyx

setRange(axis, min=None, max=None)[source]

Set axis range where

  • axis = x, y, z, xy, xz, yz, zyx

  • min = range(s) lower bound (default=None) autoscale

  • max = range(s) upper bound (default=None) autoscale

class pysces.PyscesPlot2.PlotBase[source]

Abstract class defining the Unified Plotting Interface methods. These methods should be overridden and the class extended by interface specific subclasses.

CommonStyleDefs = {'lines': '', 'points': ''}
axisInputStringToList(input)[source]

Extracts axis information from a string input, returns a boolean triple representing (x=True/False, y=True/False, z=True/False).

  • input the input string

export(name, directory=None, type='png')[source]

Export the current plot as a <format> file.

  • filename the filename

  • directory optional (default = current working directory)

  • type the file format (default=’png’).

Currently only PNG is guaranteed to be available in all interfaces.

plot(data, x, y, title='', format='')[source]

Plot a single line data[y] vs data[x] where:

  • data the data array

  • x x column index

  • y y column index

  • title is the line key

  • format is the XXX format string (default=’’)

Format can also be the CommonStyle ‘lines’ or ‘points’

plotLines(data, x, y=[], titles=[], formats=[''])[source]

Plot a multiple lines data[y1, y2, ] vs data[x] where:

  • data the data array

  • x x column index

  • y is a list of line indexes, if empty all of y not including x is plotted

  • titles is a list of line keys, if empty Line1,Line2,Line3 is used

  • formats is a list (per line) of XXX format strings.

If formats only contains a single item, this format is used for all lines and can also be the CommonStyle ‘lines’ or ‘points’.

save(name, directory=None, dfmt='%.8e')[source]

Save the plot data and (optionally) XXX format file

  • filename the filename

  • directory optional (default = current working directory)

  • dfmt the data format string (default=’%.8e’)

setAxisLabel(axis, label='')[source]

Set the axis label:

  • axis = x, y, z, xy, xz, yz, zyx

  • label = string (default=’’)

Called with only the axis argument clears the axis label.

setGraphTitle(title='PySCeS Plot')[source]

Set the graph title, unset if title=None

  • title (string, default=’PySCeS Plot’) the graph title

setGrid(value)[source]

Display or remove graph grid.

  • value (boolean) True (on) or False (off)

setKey(value=False)[source]

Enable or disable the current plot key, no arguments removes key.

  • value boolean (default = False)

setLogScale(axis)[source]

Set axis to logscale where:

  • axis = x, y, z, xy, xz, yz, zyx

setNoLogScale(axis)[source]

Set axis to a linear scale where:

  • axis = x, y, z, xy, xz, yz, zyx

setRange(axis, min=None, max=None)[source]

Set axis range where

  • axis = x, y, z, xy, xz, yz, zyx

  • min = range(s) lower bound (default=None) autoscale

  • max = range(s) upper bound (default=None) autoscale

splot(data, x, y, z, titles='', format='')[source]

Plot a surface data[z] vs data[y] vs data[x] where:

  • data the data array

  • x x column index

  • y y column index

  • z z column index

  • title is the surface key

  • format is the XXX format string (default=’’)

Format can also be the CommonStyle ‘lines’ or ‘points’.

splotSurfaces(data, x, y, z=[], titles=[], formats=[''])[source]

Plot data[z1, z2, ] vs data[y] vs data[x] where:

  • data the data array

  • x x column index

  • y y column index

  • z list of z column indexes, if empty all of z not including x, y are plotted

  • titles is a list of surface keys, if empty Surf1, Surf2, Surf3 is used

  • formats is a list (per line) of XXX format strings (default=’’).

If formats only contains a single item, this format is used for all surfaces and can also be the CommonStyle ‘lines’ or ‘points’.

wait(seconds=3)[source]

Wait seconds (default = 3) or until enter is pressed (seconds = -1)

class pysces.PyscesPlot2.PyscesUPI[source]

This is the frontend to the PySCeS Unified Plotting Interface (pysces.plt.*) that allows one to specify which backend should be used to plot when a UPI method is called. More than one interface can be active at the same time and so far the Matplotlib and GnuPlot backends are available for use.

This is an experiment which must be refactored into a more general way of doing things. Basically, I want an instance of the abstract plotting class which will plot to one, any or all currently available backends. If anybody has an idea how I can generate this class automatically please let me know ;-)

closeAll()[source]

Close all active Matplolib figures

export(name, directory=None, type='png')[source]

Export the current plot as a <format> file.

  • filename the filename

  • directory optional (default = current working directory)

  • type the file format (default=’png’).

Currently only PNG is guaranteed to be available in all interfaces.

g = None
m = None
p_activateInterface(interface)[source]

Activate an interface that has been set with p_setInterface() but deactivated with p_deactivateInterface

  • interface one of [‘matplotlib’,’gnuplot’]

p_deactivateInterface(interface)[source]

Deactivate the interface. This does not delete the interface and it is possible to reactivate the deactivated interface with p_activateInterface.

  • interface one of [‘matplotlib’,’gnuplot’]

p_setInterface(name, instance)[source]

Add an interface to the backend selector

  • name the interface name currently one of [‘matplotlib’,’gnuplot’]

  • instance an instance of a PlotBase derived (UPI) interface

plot(data, x, y, title='', format='')[source]

Plot a single line data[y] vs data[x] where:

  • data the data array

  • x x column index

  • y y column index

  • title is the line key

  • format is the backend format string (default=’’)

plotLines(data, x, y=[], titles=[], formats=[''])[source]

Plot a multiple lines data[y1, y2, ] vs data[x] where:

  • data the data array

  • x x column index

  • y is a list of line indexes, if empty all of y not including x is plotted

  • titles is a list of line keys, if empty Line1,Line2,Line3 is used

  • formats is a list (per line) of XXX format strings.

If formats only contains a single item, this format is used for all lines.

replot()[source]

Replot the current figure for all active interfaces

save(name, directory=None, dfmt='%.8e')[source]

Save the plot data and (optionally) XXX format file

  • filename the filename

  • directory optional (default = current working directory)

  • dfmt the data format string (default=’%.8e’)

setAxisLabel(axis, label='')[source]

Set the axis label:

  • axis = x, y, z, xy, xz, yz, zyx

  • label = string (default=None)

Called with only the axis argument clears the axis label.

setGraphTitle(title='PySCeS Plot')[source]

Set the graph title, unset if title=None

  • title (string, default=’PySCeS Plot’) the graph title

setGrid(value)[source]

Display or remove graph grid.

  • value (boolean) True (on) or False (off)

setKey(value=False)[source]

Enable or disable the current plot key, no arguments removes key.

  • value boolean (default = False)

setLogScale(axis)[source]

Set axis to logscale where:

  • axis = x, y, z, xy, xz, yz, zyx

setNoLogScale(axis)[source]

Set axis to a linear scale where:

  • axis = x, y, z, xy, xz, yz, zyx

setRange(axis, min=None, max=None)[source]

Set axis range where

  • axis = x, y, z, xy, xz, yz, zyx

  • min = range(s) lower bound (default=None) autoscale

  • max = range(s) upper bound (default=None) autoscale

splot(data, x, y, z, titles='', format='')[source]

Plot a surface data[z] vs data[y] vs data[x] where:

  • data the data array

  • x x column index

  • y y column index

  • z z column index

  • titles is a list of surface keys whose len matches data columns

  • format is the XXX format string (default=’’)

splotSurfaces(data, x, y, z=[], titles=[], formats=[''])[source]

Plot data[z1, z2, ] vs data[y] vs data[x] where:

  • data the data array

  • x x column index

  • y y column index

  • z list of z column indexes, if empty all of z not including x, y are plotted

  • titles is a list of surface keys, if empty Surf1, Surf2, Surf3 is used

  • formats is a list (per line) of XXX format strings (default=’’).

If formats only contains a single item, this format is used for all surfaces.

PyscesModel

This module contains the core PySCeS classes which create the model and associated data objects

class pysces.PyscesModel.BagOfStuff(matrix, row, col)[source]

A collection of attributes defined by row and column lists used by Response coefficients etc matrix is an array of values while row/col are lists of row colummn name strings

col = None
get(attr1, attr2)[source]

Returns a single attribute “attr1_attr2” or None

list()[source]

Return all attributes as a attr:val dictionary

listAllOrdered(order='descending', absolute=True)[source]

Return an ordered list of (attr, value) tuples

  • order [default=’descending’] the order to return as: ‘descending’ or ‘ascending’

  • absolute [default=True] use the absolute value

load()[source]
matrix = None
row = None
select(attr, search='a')[source]

Return a dictionary of <attr>_<name>, <name>_<attr> : val or {} if none If attr exists as an index for both left and right attr then: search=’a’ : both left and right attributes (default) search=’l’ : left attributes only search=’r’ : right attributes

class pysces.PyscesModel.Event(name, mod)[source]

Events have triggers and fire EventAssignments when required. Ported from Core2.

assignments = None
code_string = None
delay = 0.0
formula = None
mod = None
piecewises = None
reset()[source]
setAssignment(var, formula)[source]
setTrigger(formula, delay=0.0)[source]
state = False
state0 = False
symbols = None
trigger = None
xcode = None
class pysces.PyscesModel.EventAssignment(name, mod)[source]

Event assignments are actions that are triggered by an event. Ported from Core2 to build an event handling framework fro PySCeS

code_string = None
evaluateAssignment()[source]
formula = None
mod = None
piecewises = None
setFormula(formula)[source]
setVariable(var)[source]
symbols = None
variable = None
xcode = None
class pysces.PyscesModel.Function(name, mod)[source]

Function class ported from Core2 to enable the use of functions in PySCeS.

addFormula(formula)[source]
argsl = None
code_string = None
formula = None
functions = None
mod = None
piecewises = None
setArg(var, value=None)[source]
symbols = None
value = None
xcode = None
class pysces.PyscesModel.IntegrationDataObj[source]

This class is specifically designed to store the results of a time simulation It has methods for setting the Time, Labels, Species and Rate data and getting Time, Species and Rate (including time) arrays. However, of more use:

  • getOutput(*args) feed this method species/rate labels and it will return an array of [time, sp1, r1, ….]

  • getDataAtTime(time) the data generated at time point “time”.

  • getDataInTimeInterval(time, bounds=None) more intelligent version of the above returns an array of all data points where: time-bounds <= time <= time+bounds

HAS_RATES = False
HAS_RULES = False
HAS_SPECIES = False
HAS_TIME = False
HAS_XDATA = False
IS_VALID = True
TYPE_INFO = 'Deterministic'
getAllSimData(lbls=False)[source]

Return all available data as time+species+rates+rules if lbls=True returns (array,lables) else just array

getDataAtTime(time)[source]

Return all data generated at “time”

getDataInTimeInterval(time, bounds=None)[source]

getDataInTimeInterval(time, bounds=None) returns an array of all data points where: time-bounds <= time <= time+bounds where bound defaults to stepsize

getOutput(*args, **kwargs)[source]

Old alias for getSimData() getOutput(*args) feed this method species/rate labels and it will return an array of [time, sp1, r1, ….]

getRates(lbls=False)[source]

return time+rate array

getRules(lbls=False)[source]

Return time+rule array

getSimData(*args, **kwargs)[source]

getSimData(*args) feed this method species/rate labels and it will return an array of [time, sp1, r1, ….]

getSpecies(lbls=False)[source]

return time+species array

getTime(lbls=False)[source]

return the time vector

getXData(lbls=False)[source]

Return time+xdata array

rate_labels = None
rates = None
rules = None
rules_labels = None
setLabels(species=None, rates=None, rules=None)[source]

set the species, rate and rule label lists

setRates(rates, lbls=None)[source]

set the rate array

setRules(rules, lbls=None)[source]

Set the results of rate rules

setSpecies(species, lbls=None)[source]

Set the species array

setTime(time, lbl=None)[source]

Set the time vector

setXData(xdata, lbls=None)[source]

Sets extra simulation data

species = None
species_labels = None
time = None
time_label = 'Time'
xdata = None
xdata_labels = None
class pysces.PyscesModel.NewCoreBase[source]

Core2 base class, needed here as we use Core2 derived classes in PySCes

get(attr)[source]

Return an attribute whose name is str(attr)

getName()[source]
name = None
setName(name)[source]
class pysces.PyscesModel.NumberBase[source]

Derived Core2 number class.

getValue()[source]
setValue(v)[source]
value = None
value_initial = None
class pysces.PyscesModel.PieceWise(pwd, mod)[source]

Generic piecewise class adapted from Core2 that generates a compiled Python code block that allows evaluation of arbitrary length piecewise functions. Piecewise statements should be defined in assignment rules as piecewise(<Piece>, <Conditional>, <OtherValue>) where there can be an arbitrary number of <Piece>, <Conditional> pairs.

  • args a dictionary of piecewise information generated by the InfixParser as InfixParser.piecewises

code_string = None
formula = None
name = None
value = None
xcode = None
class pysces.PyscesModel.PysMod(File=None, dir=None, loader='file', fString=None, autoload=True)[source]

Create a model object and instantiate a PySCeS model so that it can be used for further analyses. PySCeS model descriptions can be loaded from files or strings (see the loader argument for details).

  • File the name of the PySCeS input file if not explicit a *.psc extension is assumed.

  • dir if specified, the path to the input file otherwise the default PyscesModel directory (defined in the pys_config.ini file) is assumed.

  • autoload autoload the model, pre 0.7.1 call mod.doLoad(). (default=True) new

  • loader the default behaviour is to load PSC file, however, if this argument is set to ‘string’ an input file can be supplied as the fString argument (default=’file’)

  • fString a string containing a PySCeS model file (use with loader=’string’) the File argument now sepcifies the new input file name.

CVODE(initial)[source]

PySCeS interface to the CVode integration algorithm. Given a set of initial conditions.

Arguments:

initial: vector containing initial species concentrations

CVODE_VPYTHON(s)[source]

Future VPython hook for CVODE

CVODE_continue(tvec)[source]

Experimental: continues a simulation over a new time vector, the CVODE memobj is reused and not reinitialised and model parameters can be changed between calls to this method. The mod.data_sim objects from the initial simulation and all calls to this method are stored in the list mod.CVODE_continuous_result.

  • tvec a numpy array of time points

CVODE_continuous_result = None
CleanNaNsFromArray(arr, replace_val=0.0)[source]

Scan a matrix for NaN’s and replace with zeros:

  • arr the array to be cleaned

EvalCC()[source]

Calculate the MCA control coefficients using the current steady-state solution.

mod.__settings__[“mca_ccj_upsymb”] = 1 attach the flux control coefficients to the model instance mod.__settings__[“mca_ccs_upsymb”] = 1 attach the concentration control coefficients to the model instance

Arguments: None

EvalEigen()[source]

Calculate the eigenvalues or vectors of the unscaled Jacobian matrix and thereby analyse the stability of a system

Arguments: None

EvalEpar(input=None, input2=None)[source]

Calculate reaction elasticities towards the parameters.

Both inputs (input1=species,input2=rates) should be valid (steady state for MCA) solutions and given in the correct order for them to be used. If either or both are missing the last state values are used automatically. Elasticities are scaled using input 1 and 2.

Arguments:

  • input [default=None]: species concentration vector

  • input2 [default=None]: reaction rate vector

Settings, set in mod.__settings__:

- elas_epar_upsymb   [default = 1] attach individual elasticity symbols to model instance
- elas_scaling_div0_fix [default=False] if NaN's are detected in the variable and parameter elasticity matrix replace with zero
EvalEvar(input=None, input2=None)[source]

Calculate reaction elasticities towards the variable species.

Both inputs (input1=species,input2=rates) should be valid (steady state for MCA) solutions and given in the correct order for them to be used. If either or both are missing the last state values are used automatically. Elasticities are scaled using input 1 and 2.

Arguments:

- input [default=None]:  species concentration vector
- input2 [default=None]: reaction rate vector

Settings, set in mod.__settings__:

- elas_evar_upsymb   [default = 1] attach individual elasticity symbols to model instance
- elas_zero_conc_fix [default=False] if zero concentrations are detected in a steady-state solution make it a very small number
- elas_zero_flux_fix [default=False] if zero fluxes are detected in a steady-state solution make it a very small number
- elas_scaling_div0_fix [default=False] if INf's are detected after scaling set to zero
EvalRC()[source]

Calculate the MCA response coefficients using the current steady-state solution.

Arguments: None

EvalRCT()[source]

Calculate the MCA response coefficients using the current steady-state solution.

Responses to changes in the sums of moiety conserved cycles are also calculated.

Arguments: None

FINTSLV(initial)[source]

Forward integration steady-state solver. Finds a steady state when the maximum change in species concentration falls within a specified tolerance. Returns the steady-state solution and a error flag. Algorithm controls are available as mod.fintslv_<control>

Arguments:

initial: vector of initial concentrations

Fix_S_fullinput(s_vec)[source]

Using the full concentration vector evaluate the dependent species

Arguments:

s_vec: a full length concentration vector

Fix_S_indinput(s_vec, amounts=True)[source]

whether to use self.__tvec_a__ (default) or self.__tvec_c__

Given a vector of independent species evaluate and return a full concentration vector.

Arguments:

s_vec: vector of independent species

Fix_Sim(metab, flux=0, par=0)[source]

Deprecated

FluxGenSim(s)[source]

Deprecated

Forcing_Function()[source]

User defined forcing function either defined in the PSC input file as !F or by overwriting this method. This method is evaluated prior to every rate equation evaluation.

Arguments: None

HYBRD(initial)[source]

PySCeS interface to the HYBRD solver. Returns a steady-state solution and error flag. Good general purpose solver. Algorithm controls are available as mod.hybrd_<control>

Arguments:

initial: vector of initial species concentrations

InitialiseCompartments()[source]
InitialiseConservationArrays()[source]

Initialise conservation related vectors/array was in InitialiseModel but has been moved out so is can be called by when the stoichiometry is reanalysed

InitialiseEvents()[source]
InitialiseFunctions()[source]
InitialiseInputFile()[source]

Parse the input file associated with the PySCeS model instance and assign the basic model attributes

Arguments: None

InitialiseModel()[source]

Initialise and set up dynamic model attributes and methods using the model defined in the associated PSC file

Arguments: None

InitialiseOldFunctions()[source]

Parse and initialise user defined functions specified by !T !U in the PSC input file

Arguments: None

InitialiseRuleChecks()[source]
InitialiseRules()[source]
LSODA(initial)[source]

PySCeS interface to the LSODA integration algorithm. Given a set of initial conditions LSODA returns an array of species concentrations and a status flag. LSODA controls are accessible as mod.lsoda_<control>

Arguments:

initial: vector containing initial species concentrations

LoadFromFile(File=None, dir=None)[source]

__init__(File=None,dir=None)

Initialise a PySCeS model object with PSC file that can be found in optional directory. If a a filename is not supplied the pysces.model_dir directory contents is displayed and the model name can be entered at the promp (<ctrl>+C exits the loading process).

Arguments:

File [default=None]: the name of the PySCeS input file dir [default=pysces.model_dir]: the optional directory where the PSC file can be found

LoadFromString(File=None, fString=None)[source]

Docstring required

ModelLoad(stoich_load=0)[source]

Load and instantiate a PySCeS model so that it can be used for further analyses. This function replaces the pre-0.7.1 doLoad() method.

  • stoich_load try to load a structural analysis saved with Stoichiometry_Save_Serial() (default=0)

NLEQ2(initial)[source]

PySCeS interface to the (optional) NLEQ2 algorithm. This is a powerful steady-state solver that can usually find a solution for when HYBRD() fails. Algorithm controls are available as: mod.nleq2_<control> Returns as steady-state solution and error flag.

Arguments:

initial: vector of initial species concentrations

PITCON(scanpar, scanpar3d=None)[source]

PySCeS interface to the PITCON continuation algorithm. Single parameter continuation has been implemented as a “scan” with the continuation being initialised in mod.pitcon_par_space. The second argument does not affect the continuation but can be used to insert a third axis parameter into the results. Returns an array containing the results. Algorithm controls are available as mod.pitcon_<control>

Arguments:

scanpar: the model parameter to scan (x5) scanpar3d [default=None]: additional output parameter for 3D plots

ParGenSim()[source]

Deprecated

ReloadInitFunc()[source]

Recompile and execute the user initialisations (!I) as defined in the PSC input file. and in mod.__InitFuncs__.

UPDATE 2015: can now be used to define InitialAssignments (no need for self.* prefix in input file)

Arguments: None

ReloadUserFunc()[source]

Recompile and execute the user function (!U) from the input file.

Arguments: None

ResetNumberFormat()[source]

Reset PySCeS default number format stored as mod.mode_number format to %2.4e

Arguments: None

ScaleKL(input, input2)[source]

Scale the K and L matrices with current steady state (if either input1 or 2 == None) or user input.

Arguments:

input: vector of species concentrations input2: vector of reaction rates

Scan1(range1=[], runUF=0)[source]

Perform a single dimension parameter scan using the steady-state solvers. The parameter to be scanned is defined (as a model attribute “P”) in mod.scan_in while the required output is entered into the list mod.scan_out. Results of a parameter scan can be easilly viewed with Scan1Plot().

mod.scan_in - a model attribute written as in the input file (eg. P, Vmax1 etc) mod.scan_out - a list of required output [‘A’,’T2’, ‘ecR1_s1’, ‘ccJR1_R1’, ‘rcJR1_s1’, …] mod.scan_res - the results of a parameter scan mod.scan - numpy record array with the scan results (scan_in and scan_out), call as mod.scan.Vmax, mod.scan.A_ss, mod.scan.J_R1, etc. mod.__settings__[“scan1_mca_mode”] - force the scan algorithm to evaluate the elasticities (1) and control coefficients (2) (this should also be auto-detected by the Scan1 method).

Arguments:

range1 [default=[]]: a predefined range over which to scan. runUF [default=0]: run (1) the user defined function mod.User_Function (!U) before evaluating the steady state.

Scan1Plot(plot=[], title=None, log=None, format='lines', filename=None)[source]

Plot the results of a parameter scan generated with Scan1()

  • plot if empty mod.scan_out is used, otherwise any subset of mod.scan_out (default=[])

  • filename the filename of the PNG file (default=None, no export)

  • title the plot title (default=None)

  • log if None a linear axis is assumed otherwise one of [‘x’,’xy’,’xyz’] (default=None)

  • format the backend dependent line format (default=’lines’) or the CommonStyle ‘lines’ or ‘points’.

Scan2D(p1, p2, output, log=False)[source]

Generate a 2 dimensional parameter scan using the steady-state solvers.

  • p1 is a list of [parameter1, start, end, points]

  • p2 is a list of [parameter2, start, end, points]

  • output steady-state variable/properties e.g. ‘J_R1’, ‘A_ss’, ‘ecR1_s1’

  • log scan using log ranges for both axes

Scan2DPlot(title=None, log=None, format='lines', filename=None)[source]

Plot the results of a 2D scan generated with Scan2D

  • filename the filename of the PNG file (default=None, no export)

  • title the plot title (default=None)

  • log if None a linear axis is assumed otherwise one of [‘x’,’xy’,’xyz’] (default=None)

  • format the backend dependent line format (default=’lines’) or the CommonStyle ‘lines’ or ‘points’.

SerialDecode(filename)[source]

Decode and return a serialised object saved with SerialEncode.

Arguments:

filename: the filename (.pscdat is assumed)

SerialEncode(data, filename)[source]

Serialise and save a Python object using a binary pickle to file. The serialised object is saved as <filename>.pscdat in the directory defined by mod.model_serial.

Arguments:

data: pickleable Python object filename: the ouput filename

SetLoud()[source]

Turn on as much solver reporting noise as possible: mod.__settings__[‘hybrd_mesg’] = 1 mod.__settings__[‘nleq2_mesg’] = 1 mod.__settings__[“lsoda_mesg”] = 1 mod.__settings__[‘mode_state_mesg’] = 1 mod.__settings__[‘scan1_mesg’] = 1 mod.__settings__[‘solver_switch_warning’] = True

Arguments: None

SetQuiet()[source]

Turn off as much solver reporting noise as possible: mod.__settings__[‘hybrd_mesg’] = 0 mod.__settings__[‘nleq2_mesg’] = 0 mod.__settings__[“lsoda_mesg”] = 0 mod.__settings__[‘mode_state_mesg’] = 0 mod.__settings__[‘scan1_mesg’] = 0 mod.__settings__[‘solver_switch_warning’] = False

Arguments: None

SetStateSymb(flux, metab)[source]

Sets the individual steady-state flux and concentration attributes as mod.J_<reaction> and mod.<species>_ss

Arguments:

flux: the steady-state flux array metab: the steady-state concentration array

SimPlot(plot='species', filename=None, title=None, log=None, format='lines')[source]

Plot the simulation results, uses the new UPI pysces.plt interface:

  • plot: output to plot (default=’species’)

  • ‘all’ rates and species

  • ‘species’ species

  • ‘rates’ reaction rates

  • [‘S1’, ‘R1’, ] a list of model attributes (species, rates)

  • filename if not None file is exported to filename (default=None)

  • title the plot title (default=None)

  • log use log axis for ‘x’, ‘y’, ‘xy’ (default=None)

  • format line format, backend dependant (default=’’)

Simulate(userinit=0)[source]

PySCeS integration driver routine that evolves the system over the time. Resulting array of species concentrations is stored in the mod.data_sim object Initial concentrations can be selected using mod.__settings__[‘mode_sim_init’] (default=0):

  • 0 initialise with intial concentrations

  • 1 initialise with a very small (close to zero) value

  • 2 initialise with results of previously calculated steady state

  • 3 initialise with final point of previous simulation

userinit values can be (default=0):

  • 0: initial species concentrations intitialised from (mod.S_init),

    time array calculated from sim_start/sim_end/sim_points

  • 1: intial species concentrations intitialised from (mod.S_init) existing

    “mod.sim_time” used directly

  • 2: initial species concentrations read from “mod.__inspec__”,

    “mod.sim_time” used directly

State()[source]

PySCeS non-linear solver driver routine. Solve for a steady state using HYBRD/NLEQ2/FINTSLV algorithms. Results are stored in mod.state_species and mod.state_flux. The results of a steady-state analysis can be viewed with the mod.showState() method.

The solver can be initialised in 3 ways using the mode_state_init switch. mod.mode_state_init = 0 initialize with species initial values mod.mode_state_init = 1 initialize with small values mod.mode_state_init = 2 initialize with the final value of a 10-logstep simulation numpy.logspace(0,5,18)

Arguments: None

Stoich_nmatrix_SetValue(species, reaction, value)[source]

Change a stoichiometric coefficient’s value in the N matrix. Only a coefficients magnitude may be set, in other words a a coefficient’s value must remain negative, positive or zero. After changing a coefficient it is necessary to Reanalyse the stoichiometry.

Arguments:

species: species name (s0) reaction: reaction name (R4) value: new coefficient value

Stoichiometry_Analyse(override=0, load=0)[source]

Perform a structural analyses. The default behaviour is to construct and analyse the model from the parsed model information. Overriding this behaviour analyses the stoichiometry based on the current stoichiometric matrix. If load is specified PySCeS tries to load a saved stoichiometry, otherwise the stoichiometric analysis is run. The results of the analysis are checked for floating point error and nullspace rank consistancy.

Arguments:

override [default=0]: override stoichiometric analysis intialisation from parsed data load [default=0]: load a presaved stoichiometry

Stoichiometry_Init(nmatrix, load=0)[source]

Initialize the model stoichiometry. Given a stoichiometric matrix N, this method will return an instantiated PyscesStoich instance and status flag. Alternatively, if load is enabled, PySCeS will attempt to load a previously saved stoichiometric analysis (saved with Stoichiometry_Save_Serial) and test it’s correctness. The status flag indicates 0 = reanalyse stoichiometry or 1 = complete structural analysis preloaded.

Arguments:

nmatrix: The input stoichiometric matrix, N load [default=0]: try to load a saved stoichiometry (1)

Stoichiometry_Load_Serial()[source]

Load a saved stoichiometry saved with mod.Stoichiometry_Save_Serial() and return a stoichiometry instance.

Arguments: None

Stoichiometry_ReAnalyse()[source]

Reanalyse the stoichiometry using the current N matrix ie override=1 (for use with mod.Stoich_matrix_SetValue)

Arguments: None

Stoichiometry_Save_Serial()[source]

Serialize and save a Stoichiometric instance to binary pickle Stoichiometry_Save_Serial()

Serilaise and save the current model stoichiometry to a file with name <model>_stoichiometry.pscdat in the mod.__settings__[‘serial_dir’] directory (default: mod.model_output/pscdat)

Arguments: None

TestSimState(endTime=10000, points=101, diff=1e-05)[source]

Deprecated

User_Function()[source]

Deprecated

Write_array(input, File=None, Row=None, Col=None, close_file=0, separator='  ')[source]

Write an array to File with optional row/col labels. A ‘,’ separator can be specified to create a CSV style file.

mod.__settings__[‘write_array_header’]: add <filename> as a header line (1 = yes, 0 = no) mod.__settings__[‘write_array_spacer’]: add a space after the header line (1 = yes, 0 = no) mod.__settings__[‘write_arr_lflush’]: set the flush rate for large file writes

Arguments:

input: the array to be written File [default=None]: an open, writable Python file object Row [default=None]: a list of row labels Col [default=None]: a list of column labels close_file [default=0]: close the file after write (1) or leave open (0) separator [default=’ ‘]: the column separator to use

Write_array_html(input, File=None, Row=None, Col=None, name=None, close_file=0)[source]

Write an array as an HTML table (no header/footer) or complete document. Tables are formatted with coloured columns if they exceed a specified size.

mod.__settings__[‘write_array_html_header’]: write the HTML document header mod.__settings__[‘write_array_html_footer’]: write the HTML document footer

Arguments:

input: the array to be written File [default=None]: an open, writable Python file object Row [default=None]: a list of row labels Col [default=None]: a list of column labels name [default=None]: an HTML table description line close_file [default=0]: close the file after write (1) or leave open (0)

Write_array_latex(input, File=None, Row=None, Col=None, close_file=0)[source]

Write an array to an open file as a ‘LaTeX’ {array}

Arguments:

input: the array to be written File [default=None]: an open, writable Python file object Row [default=None]: a list of row labels Col [default=None]: a list of column labels close_file [default=0]: close the file after write (1) or leave open (0)

clone()[source]

Returns a deep copy of this model object (experimental!)

doEigen()[source]

Calculate the eigenvalues, automatically performs a steady state and elasticity analysis.

Calls: State() EvalEvar() Evaleigen()

Arguments: None

doEigenMca()[source]

Calculate a full Control Analysis and eigenvalues, automatically performs a steady state, elasticity, control analysis.

Calls: State() EvalEvar() EvalCC() Evaleigen()

Arguments: None

doEigenShow()[source]

Calculate the eigenvalues, automatically performs a steady state and elasticity analysis and displays the results.

Calls: doEigen() showEigen()

Arguments: None

doElas()[source]

Calculate the model elasticities, this method automatically calculates a steady state.

Calls: State() EvalEvar() EvalEpar()

Arguments: None

doLoad(stoich_load=0)[source]

Load and instantiate a PySCeS model so that it can be used for further analyses. This function is being replaced by the ModelLoad() method.

  • stoich_load try to load a structural analysis saved with Stoichiometry_Save_Serial() (default=0)

doMca()[source]

Perform a complete Metabolic Control Analysis on the model, automatically calculates a steady state.

Calls: State() EvalEvar() EvalEpar() EvalCC()

Arguments: None

doMcaRC()[source]

doMca()

Perform a complete Metabolic Control Analysis on the model, automatically calculates a steady state.

Calls: State() EvalEvar() EvalEpar() EvalCC() EvalRC()

Arguments: None

doMcaRCT()[source]

Perform a complete Metabolic Control Analysis on the model, automatically calculates a steady state.

In additional, response coefficients to the sums of moiety-conserved cycles are calculated.

Calls: State() EvalEvar() EvalEpar() EvalCC() EvalRC() EvalRCT()

Arguments: None

doSim(end=10.0, points=20.0)[source]

Run a time simulation from t=0 to t=sim_end with sim_points.

Calls: Simulate()

Arguments:

end [default=10.0]: simulation end time points [default=20.0]: number of points in the simulation

doSimPerturb(pl, end)[source]

Deprecated: use events instead

doSimPlot(end=10.0, points=21, plot='species', fmt='lines', filename=None)[source]

Run a time simulation from t=0 to t=sim_end with sim_points and plot the results. The required output data and format can be set:

  • end the end time (default=10.0)

  • points the number of points in the simulation (default=20.0)

  • plot (default=’species’) select output data

  • ‘species’

  • ‘rates’

  • ‘all’ both species and rates

  • fmt plot format, UPI backend dependent (default=’’) or the CommonStyle ‘lines’ or ‘points’.

  • filename if not None (default) then the plot is exported as filename.png

Calls: - Simulate() - SimPlot()

doState()[source]

Calculate the steady-state solution of the system.

Calls: State()

Arguments: None

doStateShow()[source]

Calculate the steady-state solution of a system and show the results.

Calls: State() showState()

Arguments: None

exportSimAsSedML(output='files', return_sed=False, vc_given='PySCeS', vc_family='Software', vc_email='', vc_org='pysces.sourceforge.net')[source]

Exports the current simulation as SED-ML in various ways it creates and stores the SED-ML files in a folder generated from the model name.

  • output [default=’files’] the SED-ML export type can be one or more comma separated e.g. ‘files,combine’

  • files export the plain SBML and SEDML XML files

  • archive export as a SED-ML archive <file>.sedx containing the SBML and SEDML xml files

  • combine export as a COMBINE archive <file>.omex containing the SBML, SEDML, manifest (XML) and metadata (RDF) - vc_given [default=’PySCeS’] - vc_family [default=’Software’] - vc_email [default=’bgoli@users.sourceforge.net’] - vc_org [default=’<pysces.sourceforge.net>’]

random = <module 'pysces.PyscesRandom' from '../../pysces/PyscesRandom.py'>
reLoad(stoich_load=0)[source]

Re-load and instantiate a PySCeS model so that it can be used for further analyses. This is just a convenience call to the ModelLoad() method.

  • stoich_load try to load a structural analysis saved with Stoichiometry_Save_Serial() (default=0)

property scan
showCC(File=None)[source]

Print all control coefficients as ‘LaTex’ formatted strings to the screen or file.

Arguments:

File [default=None]: an open, writable Python file object

showConserved(File=None, screenwrite=1, fmt='%2.3f')[source]

Print the moiety conserved cycles present in the system.

Arguments:

File [default=None]: an open writable Python file object screenwrite [default=1]: write results to console (0 means no reponse) fmt [default=’%2.3f’]: the output number format string

showEigen(File=None)[source]

Print the eigenvalues and stability analysis of a system generated with EvalEigen() to the screen or file.

Arguments:

File [default=None]: an open, writable Python file object

showElas(File=None)[source]

Print all elasticities to screen or file as ‘LaTeX’ compatible strings. Calls showEvar() and showEpar()

Arguments:

File [default=None]: an open writable Python file object

showEpar(File=None)[source]

Write out all nonzero parameter elasticities as ‘LaTeX’ formatted strings, alternatively write to file.

Arguments:

File [default=None]: an open writable Python file object

showEvar(File=None)[source]

Write out all variable elasticities as ‘LaTeX’ formatted strings, alternatively write results to a file.

Arguments:

File [default=None]: an open writable Python file object

showFluxRelationships(File=None)[source]

showConserved(File=None)

Print the flux relationships present in the system.

Arguments:

File [default=None]: an open writable Python file object

showK(File=None, fmt='%2.3f')[source]

Print the Kernel matrix (K), including row and column labels to screen or File.

Arguments:

File [default=None]: an open, writable Python file object fmt [default=’%2.3f’]: output number format

showL(File=None, fmt='%2.3f')[source]

Print the Link matrix (L), including row and column labels to screen or File.

Arguments:

File [default=None]: an open, writable Python file object fmt [default=’%2.3f’]: output number format

showModel(filename=None, filepath=None, skipcheck=0)[source]

The PySCeS ‘save’ command, prints the entire model to screen or File in a PSC format. (Currently this only applies to basic model attributes, ! functions are not saved).

Arguments:

filename [default=None]: the output PSC file filepath [default=None]: the output directory skipcheck [default=0]: skip check to see if the file exists (1) auto-averwrite

showModifiers(File=None)[source]

Prints the current value of the model’s modifiers per reaction to screen or file.

Arguments:

File [default=None]: an open, writable Python file object

showN(File=None, fmt='%2.3f')[source]

Print the stoichiometric matrix (N), including row and column labels to screen or File.

Arguments:

File [default=None]: an open, writable Python file object fmt [default=’%2.3f’]: output number format

showNr(File=None, fmt='%2.3f')[source]

Print the reduced stoichiometric matrix (Nr), including row and column labels to screen or File.

Arguments:

File [default=None]: an open, writable Python file object fmt [default=’%2.3f’]: output number format

showODE(File=None, fmt='%2.3f')[source]

Print a representation of the full set of ODE’s generated by PySCeS to screen or file.

Arguments:

File [default=None]: an open, writable Python file object fmt [default=’%2.3f’]: output number format

showODEr(File=None, fmt='%2.3f')[source]

Print a representation of the reduced set of ODE’s generated by PySCeS to screen or file.

Arguments:

File [default=None]: an open, writable Python file object fmt [default=’%2.3f’]: output number format

showPar(File=None)[source]

Prints the current value of the model’s parameter values (mod.P) to screen or file.

Arguments:

File [default=None]: an open, writable Python file object

showRate(File=None)[source]

Prints the current rates of all the reactions using the current parameter values and species concentrations

  • File an open, writable Python file object (default=None)

showRateEq(File=None)[source]

Prints the reaction stoichiometry and rate equations to screen or File.

Arguments:

File [default=None]: an open, writable Python file object

showSpecies(File=None)[source]

Prints the current value of the model’s variable species (mod.X) to screen or file.

Arguments:

File [default=None]: an open, writable Python file object

showSpeciesFixed(File=None)[source]

Prints the current value of the model’s fixed species values (mod.X) to screen or file.

Arguments:

File [default=None]: an open, writable Python file object

showSpeciesI(File=None)[source]

Prints the current value of the model’s variable species initial values (mod.X_init) to screen or file.

Arguments:

File [default=None]: an open, writable Python file object

showState(File=None)[source]

Prints the result of the last steady-state analyses. Both steady-state flux’s and species concentrations are shown.

Arguments:

File [default=None]: an open, writable Python file object

property sim
class pysces.PyscesModel.ReactionObj(mod, name, kl, klrepl='self.')[source]

Defines a reaction with a KineticLaw kl8, *formula and name bound to a model instance, mod.

code_string = None
compartment = None
formula = None
mod = None
piecewises = None
rate = None
setKineticLaw(kl, klrepl='self.')[source]
symbols = None
xcode = None
class pysces.PyscesModel.ScanDataObj(par_label)[source]

New class used to store parameter scan data (uses StateDataObj)

ALL_VALID = True
HAS_FLUXES = False
HAS_MOD_DATA = False
HAS_RULES = False
HAS_SET_LABELS = False
HAS_SPECIES = False
HAS_XDATA = False
OPEN = True
addModData(mod, *args)[source]
addPoint(ipar, ssdata)[source]

takes a list/array of input parameter values and the associated ssdata object

closeScan()[source]
flux_labels = None
fluxes = None
getAllScanData(lbls=False)[source]
getFluxes(lbls=False)[source]
getModData(lbls=False)[source]
getRules(lbls=False)[source]
getScanData(*args, **kwargs)[source]

getScanData(*args) feed this method species/flux/rule/mod labels and it will return an array of [parameter(s), sp1, f1, ….]

getSpecies(lbls=False)[source]
getXData(lbls=False)[source]
invalid_states = None
mod_data = None
mod_data_labels = None
parameter_labels = None
parameters = None
rules = None
rules_labels = None
setLabels(ssdata)[source]
species = None
species_labels = None
xdata = None
xdata_labels = None
class pysces.PyscesModel.StateDataObj[source]

New class used to store steady-state data.

HAS_FLUXES = False
HAS_RULES = False
HAS_SPECIES = False
HAS_XDATA = False
IS_VALID = True
flux_labels = None
fluxes = None
getAllStateData(lbls=False)[source]

Return all available data as species+fluxes+rules if lbls=True returns (array,labels) else just array

getFluxes(lbls=False)[source]

return flux array

getRules(lbls=False)[source]

Return rule array

getSpecies(lbls=False)[source]

return species array

getStateData(*args, **kwargs)[source]

getSimData(*args) feed this method species/rate labels and it will return an array of [time, sp1, r1, ….]

getXData(lbls=False)[source]

Return xdata array

rules = None
rules_labels = None
setFluxes(fluxes, lbls=None)[source]

set the flux array

setRules(rules, lbls=None)[source]

Set the results of rate rules

setSpecies(species, lbls=None)[source]

Set the species array

setXData(xdata, lbls=None)[source]

Sets extra simulation data

species = None
species_labels = None
xdata = None
xdata_labels = None
class pysces.PyscesModel.WasteManagement[source]
pysces.PyscesModel.chkmdir()[source]

Import and grab pysces.model_dir

Arguments: None

pysces.PyscesModel.chkpsc(File)[source]

Chekc whether the filename “File” has a ‘.psc’ extension and adds one if not.

Arguments:

File: filename string

PyscesScan

PySCeS classes for continuations and multi-dimensional parameter scans

class pysces.PyscesScan.PITCONScanUtils(model)[source]

Static Bifurcation Scanning utilities using PITCON, call with loaded model object. Hopefully nobody else was trying to use the older class as it was horrible. This new one is is leaner, meaner and pretty cool ;-)

analyseData(analysis='elas')[source]

Performs “analysis” on the PITCON generated set of steady-state results where analysis is:

  • ‘elasv’ = variable elasticities

  • ‘elasp’ = parameter elasticities

  • ‘elas’ = all elasticities

  • ‘mca’ = control coefficients

  • ‘resp’ = response coefficients

  • ‘eigen’ = eigen values

  • ‘all’ = all of the above

Higher level analysis types automatically enable the lower level analysis needed e.g. selecting ‘mca’ implies ‘elasv’ etc. User output defined with mod.setUserOutput() is stored in the mod.res_user array.

getArrayListAsArray(array_list)[source]

Stack (concatenate) the list of arrays into a single array.

model = None
pitcon_range_high = None
pitcon_range_low = None
pitcon_res = None
pitcon_scan_density = None
pitcon_scan_parameter = None
pitcon_scan_parameter_3d = None
res_eigen = None
res_flux = None
res_idx = None
res_metab = None
res_user = None
runContinuation(parameter, low, high, density, par3d=None, logrange=True, runQuiet=True)[source]

Run the continuation using the following parameters:

Args:

  • parameter = str(the parameter to be scanned)

  • low = float(lower bound)

  • high = float(upper bound)

  • density = int(the number of initial points)

  • par3d = float(extra 3d parameter to insert into the output array) this parameter is not set ONLY used in output

  • logrange = boolean [default = True], if True generate the result using logspace(log10(low), log10(high), density) otherwise use a linear range

  • runQuiet = boolean [default = True], if True do not display intermediate results to screen, disable for debugging

After running the continuation the results are stored in numpy arrays

  • mod.res_idx = scan parameter values (and optionally par3d)

  • mod.res_metab = steady-state species concentrations

  • mod.res_flux = steady-state flux values

setUserOuput(*args)[source]

Set the user output required as n string arguments.

timer = None
user_output = None
class pysces.PyscesScan.Scanner(mod)[source]

Arbitrary dimension generic scanner. This class is initiated with a loaded PySCeS model and then allows the user to define scan parameters see self.addScanParameter() and user output see self.addUserOutput(). Steady-state results are always stored in self.SteadyStateResults while user output can be found in self.UserOutputResults - brett 2007.

Analyze()[source]

The analysis method, the mode is automatically set by the self.addUserOutput() method but can be reset by the user.

HAS_STATE_OUTPUT = True
HAS_USER_OUTPUT = False
MSG_PRINT_INTERVAL = 500
Run(ReRun=False)[source]

Run the parameter scan

RunAgain()[source]

While it is impossible to change the generator/range structure of a scanner (just build another one) you can ‘in principle’ change the User Output and run it again.

StoreData()[source]

Internal function which concatenates and stores the data generated by Analyze.

addScanParameter(name, start, end, points, log=False, follower=False)[source]

Add a parameter to scan (an axis if you like) input is:

  • str(name) = model parameter name

  • float(start) = lower bound of scan

  • float(end) = upper bound of scan

  • int(points) = number of points in scan range

  • bool(log) = Use a logarithmic (base10) range

  • bool(follower) = Scan parameters can be leaders i.e. an independent axis or a “follower” which moves synchronously with the previously defined parameter range.

The first ScanParameter cannot be a follower.

addUserOutput(*kw)[source]

Add output parameters to the scanner as a collection of one or more string arguments (‘O1’,’O2’,’O3’, ‘On’). These are evaluated at each iteration of the scanner and stored in the self.UserOutputResults array. The list of output is stored in self.UserOutputList.

genOn = True
getOutput()[source]

Will be the new output function.

getResultMatrix(stst=False, lbls=False)[source]

Returns an array of result data. I’m keepin this for backwards compatibility but it will be replaced by a getOutput() method when this scanner is updated to use the new data_scan object.

  • stst add steady-state data to output array

  • lbls return a tuple of (array, column_header_list)

If stst is True output has dimensions [scan_parameters]+[state_species+state_flux]+[Useroutput] otherwise [scan_parameters]+[Useroutput].

invalid_state_list = None
invalid_state_list_idx = None
makeRange(start, end, points, log)[source]

Should be pretty self evident it defines a range:

  • float(start)

  • float(end)

  • int(points)

  • bool(log)

nan_on_bad_state = True
quietRun = False
rangeGen(name, start, end, points, log)[source]

This is where things get more interesting. This function creates a cycling generator which loops over a parameter range.

  • parameter name

  • start value

  • end value

  • points

  • log scale

resetInputParameters()[source]

Just remembered what this does, I think it resets the input model parameters after a scan run.

setModValue(name, value)[source]

An easy one, assign value to name of the instantiated PySCeS model attribute

stepGen(offset)[source]

Another looping generator function. The idea here is to create a set of generators for the scan parameters. These generators then all fire together and determine whether the range generators should advance or not. Believe it or not this dynamically creates the matrix of parameter values to be evaluated.

testInputParameter(name)[source]

This tests whether a str(name) is an attribute of the model

PyscesInterfaces

Interfaces converting to and from PySCeS models - makes use of Brett’s Core2

class pysces.PyscesInterfaces.Core2interfaces[source]

Defines interfaces for translating PySCeS model objects into and from other formats.

convertSBML2PSC(sbmlfile, sbmldir=None, pscfile=None, pscdir=None)[source]

Convert an SBML file to a PySCeS MDL input file.

  • sbmlfile: the SBML file name

  • sbmldir: the directory of SBML files (if None current working directory is assumed)

  • pscfile: the output PSC file name (if None sbmlfile.psc is used)

  • pscdir: the PSC output directory (if None the pysces.model_dir is used)

core = None
core2psc = None
core2sbml = None
readMod2Core(mod, iValues=True)[source]

Convert a PySCeS model object to core2

  • iValues: if True then the models initial values are used (or the current values if False).

readSBMLToCore(filename, directory=None)[source]

Reads the SBML file specified with filename and converts it into a core2 object pysces.interface.core

  • filename: the SBML file

  • directory: (optional) the SBML file directory None means try the current working directory

sbml = None
sbml2core = None
sbml_level = 2
sbml_version = 1
writeCore2PSC(filename=None, directory=None, getstrbuf=False)[source]

Writes a Core2 object to a PSC file.

  • filename: writes <filename>.xml or <model_name>.xml if None

  • directory: (optional) an output directory

  • getstrbuf: if True a StringIO buffer is returned instead of writing to disk

writeCore2SBML(filename=None, directory=None, getdocument=False)[source]

Writes Core2 object to an SBML file.

  • filename: writes <filename>.xml or <model_name>.xml if None

  • directory: (optional) an output directory

  • getdocument: if True an SBML document object is returned instead of writing to disk or

writeMod2PSC(mod, filename=None, directory=None, iValues=True, getstrbuf=False)[source]

Writes a PySCeS model object to a PSC file.

  • filename: writes <filename>.psc or <model_name>.psc if None

  • directory: (optional) an output directory

  • iValues: if True then the models initial values are used (or the current values if False).

  • getstrbuf: if True a StringIO buffer is returned instead of writing to disk

writeMod2SBML(mod, filename=None, directory=None, iValues=True, getdocument=False, getstrbuf=False)[source]

Writes a PySCeS model object to an SBML file.

  • filename: writes <filename>.xml or <model_name>.xml if None

  • directory: (optional) an output directory

  • iValues: if True then the models initial values are used (or the current values if False).

  • getdocument: if True an SBML document object is returned instead of writing to disk or

  • getstrbuf: if True a StringIO buffer is returned instead of writing to disk

PyscesStoich

PySCeS stoichiometric analysis classes.

class pysces.PyscesStoich.MathArrayFunc[source]

PySCeS array functions - used by Stoich

LinAlgError = 'LinearAlgebraError'
MatrixFloatFix(mat, val=1e-15)[source]

Clean an array removing any floating point artifacts defined as being smaller than a specified value. Processes an array inplace

Arguments:

mat: the input 2D array val [default=1.e-15]: the threshold value (effective zero)

MatrixValueCompare(matrix)[source]

Finds the largest/smallest abs(value) > 0.0 in a matrix. Returns a tuple containing (smallest,largest) values

Arguments:

matrix: the input 2D array

SwapCol(res_a, r1, r2)[source]

Swap two columns using BLAS swap, arrays can be (or are upcast to) type double (d) or double complex (D). Returns the colswapped array

Arguments:

res_a: the input array r1: the first column to be swapped r2: the second column to be swapped

SwapCold(res_a, c1, c2)[source]

Swaps two double (d) columns in an array using BLAS DSWAP. Returns the colswapped array.

Arguments:

res_a: input array c1: column index 1 c2: column index 2

SwapColz(res_a, c1, c2)[source]

Swaps two double complex (D) columns in an array using BLAS ZSWAP. Returns the colswapped array.

Arguments:

res_a: input array c1: column index 1 c2: column index 2

SwapElem(res_a, r1, r2)[source]

Swaps two elements in a 1D vector

Arguments:

res_a: the input vector r1: index 1 r2: index 2

SwapRow(res_a, r1, r2)[source]

Swaps two rows using BLAS swap, arrays can be (or are upcast to) type double (d) or double complex (D). Returns the rowswapped array.

Arguments:

res_a: the input array r1: the first row index to be swapped r2: the second row index to be swapped

SwapRowd(res_a, c1, c2)[source]

Swaps two double (d) rows in an array using BLAS DSWAP. Returns the rowswapped array.

Arguments:

res_a: input array c1: row index 1 c2: row index 2

SwapRowz(res_a, c1, c2)[source]

Swaps two double complex (D) rows in an array using BLAS ZSWAP. Returns the rowswapped array.

Arguments:

res_a: input array c1: row index 1 c2: row index 2

array_kind = {'D': 1, 'F': 1, 'd': 0, 'f': 0, 'i': 0, 'l': 0}
array_precision = {'D': 1, 'F': 0, 'd': 1, 'f': 0, 'i': 1, 'l': 1}
array_type = [['f', 'd'], ['F', 'D']]
assertRank2(\*arrays)[source]

Check that we are using a 2D array

Arguments:

*arrays: input array(s)

castCopyAndTranspose(type, \*arrays)[source]

Cast numeric arrays to required type and transpose

Arguments:

type: the required type to cast to *arrays: the arrays to be processed

commonType(\*arrays)[source]

Numeric detect and set array precision (will be replaced with new scipy.core compatible code when ready)

Arguments:

*arrays: input arrays

class pysces.PyscesStoich.Stoich(input)[source]

PySCeS stoichiometric analysis class: initialized with a stoichiometric matrix N (input)

AnalyseK()[source]

Evaluate the stoichiometric matrix and calculate the nullspace using LU decomposition and backsubstitution . Generates the MCA K and Ko arrays and associated row and column vectors

Arguments: None

AnalyseL()[source]

Evaluate the stoichiometric matrix and calculate the left nullspace using LU factorization and backsubstitution. Generates the MCA L, Lo, Nr and Conservation matrix and associated row and column vectors

Arguments: None

BackSubstitution(res_a, row_vector, column_vector)[source]

Jordan reduction of a scaled upper triangular matrix. The returned array is now in the form [I R] and can be used for nullspace determination. Modified row and column tracking vetors are also returned.

Arguments:

res_a: unitary pivot upper triangular matrix row_vector: row tracking vector column_vector: column tracking vector

GetUpperMatrix(a)[source]

Core analysis algorithm; an input is preconditioned using PivotSort_initial and then cycles of PLUfactorize and PivotSort are run until the factorization is completed. During this process the matrix is reordered by column swaps which emulates a full pivoting LU factorization. Returns the pivot matrix P, upper factorization U as well as the row/col tracking vectors.

Arguments:

a: a stoichiometric matrix

GetUpperMatrixUsingQR(a)[source]

GetUpperMatrix(a)

Core analysis algorithm; an input is preconditioned using PivotSort_initial and then cycles of PLUfactorize and PivotSort are run until the factorization is completed. During this process the matrix is reordered by column swaps which emulates a full pivoting LU factorization. Returns the pivot matrix P, upper factorization U as well as the row/col tracking vectors.

Arguments:

a: a stoichiometric matrix

K_split_R(R_a, row_vector, column_vector)[source]

Using the R factorized form of the stoichiometric matrix we now form the K and Ko matrices. Returns the r_ipart,Komatrix,Krow,Kcolumn,Kmatrix,Korow,info

Arguments:

R_a: the Gauss-Jordan reduced stoichiometric matrix row_vector: row tracking vector column_vector: column tracking vector

L_split_R(Nfull, R_a, row_vector, column_vector)[source]

Takes the Gauss-Jordan factorized N^T and extract the L, Lo, conservation (I -Lo) and reduced stoichiometric matrices. Returns: lmatrix_col_vector, lomatrix, lomatrix_row, lomatrix_co, nrmatrix, Nred_vector_row, Nred_vector_col, info

Arguments:

Nfull: the original stoichiometric matrix N R_a: gauss-jordan factorized form of N^T row_vector: row tracking vector column_vector: column tracking vector

PLUfactorize(a_in)[source]

Performs an LU factorization using LAPACK D/ZGetrf. Now optimized for FLAPACK interface. Returns LU - combined factorization, IP - rowswap information and info - Getrf error control.

Arguments:

a_in: the matrix to be factorized

PivotSort(a, row_vector, column_vector)[source]

This is a sorting routine that accepts a matrix and row/colum vectors and then sorts them so that: there are no zero rows (by swapping with first non-zero row) The abs(largest) pivots are moved onto the diagonal to maintain numerical stability. Row and column swaps are recorded in the tracking vectors.

Arguments:

a: the input array row_vector: row tracking vector column_vector: column tracking vector

PivotSort_initial(a, row_vector, column_vector)[source]

This is a sorting routine that accepts a matrix and row/colum vectors and then sorts them so that: the abs(largest) pivots are moved onto the diagonal to maintain numerical stability i.e. the matrix diagonal is in descending max(abs(value)). Row and column swaps are recorded in the tracking vectors.

Arguments:

a: the input array row_vector: row tracking vector column_vector: column tracking vector

SVD_Rank_Check(matrix=None, factor=10000.0, resultback=0)[source]

Calculates the dimensions of L/L0/K/K) by way of SVD and compares them to the Guass-Jordan results. Please note that for LARGE ill conditioned matrices the SVD can become numerically unstable when used for nullspace determinations

Arguments:

matrix [default=None]: the stoichiometric matrix default is self.Nmatrix factor [default=1.0e4]: factor used to calculate the ‘zero pivot’ mask = mach_eps*factor resultback [default=0]: return the SVD results, U, S, vh

ScalePivots(a_one)[source]

Given an upper triangular matrix U, this method scales the diagonal (pivot values) to one.

Arguments:

a_one: an upper triangular matrix U

SplitLU(plu, row, col, t)[source]

PLU takes the combined LU factorization computed by PLUfactorize and extracts the upper matrix. Returns U.

Arguments:

plu: LU factorization row: row tracking vector col: column tracking vector t [default=None)]: typecode argument (currently not used)

USE_QR = False
info_moiety_conserve = False
class pysces.PyscesStoich.StructMatrix(array, ridx, cidx, row=None, col=None)[source]

This class is specifically designed to store structural matrix information give it an array and row/col index permutations it can generate its own row/col labels given the label src.

array = None
cidx = None
col = None
getByIdx(row, col)[source]
getByName(row, col)[source]
getColsByIdx(*args)[source]

Return the columns referenced by index (1,3,5)

getColsByName(*args)[source]

Return the columns referenced by label (‘s’,’x’,’d’)

getIndexes(axis='all')[source]

Return the matrix indexes ([rows],[cols]) where axis=’row’/’col’/’all’

getLabels(axis='all')[source]

Return the matrix labels ([rows],[cols]) where axis=’row’/’col’/’all’

getRowsByIdx(*args)[source]

Return the rows referenced by index (1,3,5)

getRowsByName(*args)[source]

Return the rows referenced by label (‘s’,’x’,’d’)

ridx = None
row = None
setByIdx(row, col, val)[source]
setByName(row, col, val)[source]
setCol(src)[source]

Assuming that the col index array is a permutation (full/subset) of a source label array by supplying that src to setCol maps the row labels to cidx and creates self.col (col label list)

setRow(src)[source]

Assuming that the row index array is a permutation (full/subset) of a source label array by supplying that source to setRow it maps the row labels to ridx and creates self.row (row label list)

shape = None