basico package
BasiCO is a simplified interface to COPASI.
This module provides convenience functions to quickly get a model loaded and simulated:
Example
>>> from basico import *
>>> load_biomodel(10)
>>> run_time_course().plot()
Submodules
basico.array_tools module
- basico.array_tools.compartment_names(**kwargs)
- basico.array_tools.plot_arrays_1d(df, species, **kwargs)
- basico.array_tools.remove_arrays(**kwargs)
Removes arrays from the model
- basico.array_tools.remove_template(**kwargs)
Removes the template model from the array model
basico.biomodels module
A submodule for accessing the BioModels API.
This submodule accesses the BioModels REST api as described on:
Examples
>>> # get info for a specific model
>>> info = get_model_info(12)
>>> print(info['name'], info['files']['main'][0]['name'])
>>> # get all files for one model
>>> files = get_files_for_model(12)
>>> print(files['main'][0]['name'])
>>> # get content of specific model
>>> sbml = get_content_for_model(12)
>>> print(sbml)
>>> # search for model
>>> models = search_for_model('repressilator')
>>> for model in models:
>>> print(model['id'], model['name'], model['format'])
- basico.biomodels.download_from(url)
Convenience method reading content from a URL.
This convenience method uses urlopen on either python 2.7 or 3.x
- Parameters
url (str) – the url to read from
- Returns
the contents of the URL as str
- Return type
str
- basico.biomodels.download_json(url)
Convenience method reading the content of the url as JSON.
- Parameters
url (str) – the url to read from
- Returns
a python object representing the json content loaded
- Return type
dict
- basico.biomodels.get_content_for_model(model_id, file_name=None)
Downloads the specified file from biomodels
- Parameters
model_id – the model id as int, or string
file_name – the filename to download (or None, to download the main file)
- Returns
the content of the specified file
- basico.biomodels.get_files_for_model(model_id)
Retrieves the json structure for all files for the given biomodel.
The structure is of form:
>>> get_files_for_model(10) { 'additional': [ {'description': 'Auto-generated Scilab file', 'fileSize': '3873', 'name': 'BIOMD0000000010.sci'}, ... ], 'main': [ {'fileSize': '31568', 'name': 'BIOMD0000000010_url.xml' } ] }
- Parameters
model_id – the model id (as int or string)
- Returns
json structure
- basico.biomodels.get_model_info(model_id)
Return the model info for the provided model_id.
- Parameters
model_id – either an integer, or a valid model id
- Returns
a python object describing the model
- basico.biomodels.search_for_model(query, offset=0, num_results=10, sort='id-asc')
Queries the biomodel database
Queries the database, for information about the query system see: <https://www.ebi.ac.uk/biomodels-static/jummp-biomodels-help/model_search.html>
Example
>>> search_for_model('glycolysis') [..., { 'format': 'SBML', 'id': 'BIOMD0000000206', 'lastModified': '2012-07-04T23:00:00Z', 'name': 'Wolf2000_Glycolytic_Oscillations', 'submissionDate': '2008-11-27T00:00:00Z', 'submitter': 'Harish Dharuri', 'url': 'https://www.ebi.ac.uk/biomodels/BIOMD0000000206' } ]
Note by default, it will include only manually curated models, to obtain Non-curated models you would use:
>>> search_for_model('Hodgkin AND curationstatus:"Non-curated"') [..., { 'format': 'SBML', 'id': 'MODEL1006230012', 'lastModified': '2012-02-02T00:00:00Z'', 'name': 'Stewart2009_ActionPotential_PurkinjeFibreCells', 'submissionDate': '2010-06-22T23:00:00Z', 'submitter': 'Camille Laibe', 'url': 'https://www.ebi.ac.uk/biomodels/MODEL1006230012' } ]
- Parameters
query – the query to use (it will be encoded with quote_plus before send out, so it is safe to use spaces)
offset – offset (defaults to 0)
num_results – number of results to obtain (defaults to 10)
sort – sort criteria to be used (defaults to id-asc)
- Returns
the search result as [{}]
basico.compartment_array_tools module
This module provides convenience functions for array of compartments.
COPASI can duplicate the current model in either a rectangular or linear manner, with diffusion reactions added in between the created model. This allows for a simplified spatial simulation.
This submodule adds functions, to create such an array, to delete the template model. Additionally some basic plotting functionality is available as well.
Example
>>> dm = load_example('brusselator')
>>> create_rectangular_array(10, 10, ['X', 'Y'], [0.16, 0.8], delete_template=True)
>>> set_species(['X{compartment[1,1]}',
... 'X{compartment[1,2]}',
... 'X{compartment[2,1]}',
... 'X{compartment[2,2]}'], initial_concentration=10)
>>> add_event('E0', 'Time > 10', [['X{compartment[1,1]}', '10'],
... ['X{compartment[1,2]}', '10'],
... ['X{compartment[2,1]}', '10'],
... ['X{compartment[2,2]}', '10']])
>>> data = run_time_course(start_time=0, duration=500)
>>> animate_rectangular_time_course_as_image(data, metabs=["X", "Y"], min_range=0, max_range=10)
- basico.compartment_array_tools.animate_rectangular_time_course(data, metab=None, prefix=None, shading='gouraud', min_range=nan, max_range=nan, filename=None, **kwargs)
Plots the simulation data on the loaded model assuming that this is in the format of an array of compartments as generated by COPASI. This will create a figure for each species at each of the specified time points.
- Parameters
data – timecourse simulation result
metab – optional parameter specifying the species to animate. If not given, one the first metab will be chosen
prefix – string of compartment prefix to indicate which compartment should be visualized. This is expected to not include the indices, so it would be ‘compartment’ rather than ‘compartment[0]’
shading – optional shading for the color mesh, defaults to ‘gouraud’ can also be ‘flat’
min_range – optional min range, defaults to NaN, meaning that it is to be the minimum value of the data
max_range – optional max range, defaults to NaN, meaning that it is to be the maximum value of the data
filename – optional filename to a file to which to save the animation to
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
the FuncAnimation constructed
- basico.compartment_array_tools.animate_rectangular_time_course_as_image(data, metabs=None, prefix=None, min_range=nan, max_range=nan, filename=None, **kwargs)
Plots the data as image.
- Parameters
data – data frame with results to plot
metabs –
prefix – string of compartment prefix to indicate which compartment should be visualized. This is expected to not include the indices, so it would be ‘compartment’ rather than ‘compartment[0]’
min_range – optional min range, defaults to NaN, meaning that it is to be the minimum value of the data
max_range – optional max range, defaults to NaN, meaning that it is to be the maximum value of the data
filename – optional filename to safe the image as
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
FuncAnimation result
- basico.compartment_array_tools.create_linear_array(num_steps, species=None, diffusion_coefficients=None, compartment_names=None, delete_template=False, **kwargs)
Utility function to create a linear duplicating the specified species, their reactions in the given compartments and created diffusion reactions between the newly created array
- Parameters
num_steps – the number of steps to create
species – array of species names, that should be diffusing between compartments
compartment_names – optional compartment names (will default to the compartment the species is in)
diffusion_coefficients – optional array of diffusion coefficients in the same order as the species (otherwise they will be set to 1)
delete_template – if True, the original template model in the specified compartment will be deleted.
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.compartment_array_tools.create_rectangular_array(num_steps_x, num_steps_y, species=None, diffusion_coefficients=None, compartment_names=None, delete_template=False, **kwargs)
Utility function to create a rectangular array duplicating the specified species, their reactions in the given compartments and created diffusion reactions between the newly created array
- Parameters
num_steps_x – the number of compartments to create along the x direction
num_steps_y – the number of compartments to create along the y direction
species – array of species names, that should be diffusing between compartments
compartment_names – optional compartment names (will default to the compartment the species is in)
diffusion_coefficients – optional array of diffusion coefficients in the same order as the species (otherwise they will be set to 1)
delete_template – if True, the original template model in the specified compartment will be deleted.
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.compartment_array_tools.delete_compartments(selection, **kwargs)
utility function for deleting a selection of compartments from the datamodel. This will also delete the species and reactions included.
- Parameters
selection – an array of tuples of indices at which the compartments should be deleted
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.compartment_array_tools.plot_linear_time_course(data, prefix=None, metab_names=None, shading='gouraud', min_range=nan, max_range=nan, **kwargs)
Plots the simulation data on the loaded model assuming that this is in the format of an array of compartments as generated by COPASI. This will create a figure for each species
- Parameters
data – timecourse simulation result
prefix – string of compartment prefix to indicate which compartment should be visualized. This is expected to not include the indices, so it would be ‘compartment’ rather than ‘compartment[0]’
metab_names – optional array of metabolite names that should be plotted (defaults to all)
shading – optional shading for the color mesh, defaults to ‘gouraud’ can also be ‘flat’
min_range – optional min range, defaults to NaN, meaning that it is to be the minimum value of the data
max_range – optional max range, defaults to NaN, meaning that it is to be the maximum value of the data
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
array with tuple of figures and their axis
- basico.compartment_array_tools.plot_rectangular_time_course(data, times=None, prefix=None, shading='gouraud', min_range=nan, max_range=nan, **kwargs)
Plots the simulation data on the loaded model assuming that this is in the format of an array of compartments as generated by COPASI. This will create a figure for each species at each of the specified time points.
- Parameters
data – timecourse simulation result
times – optional parameter specifying the times for which to plot the results. If not given, one figure will be created for each output time point in the data
prefix – string of compartment prefix to indicate which compartment should be visualized. This is expected to not include the indices, so it would be ‘compartment’ rather than ‘compartment[0]’
shading – optional shading for the color mesh, defaults to ‘gouraud’ can also be ‘flat’
min_range – optional min range, defaults to NaN, meaning that it is to be the minimum value of the data
max_range – optional max range, defaults to NaN, meaning that it is to be the maximum value of the data
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
array with tuple of figures and their axis
basico.jws_online module
Convenience module to access JWS models
This module provides convenience functions for accessing models from JWS Online <https://jjj.mib.ac.uk> using the netherlands endpoint.
Example
>>> # get all models with ATP
>>> atp_models = get_models_for_species('atp')
>>> # get all models with PFK
>>> pfk_models = get_models_for_reaction('pfk')
>>> # get all_models (this will take a while)
>>> all = get_all_models()
>>> # get manuscript information
>>> manuscript = get_manuscript('teusink')
>>> print(manuscript['title'], manuscript['abstract'], manuscript['url'])
>>> # get info for a specific model
>>> info = get_model_info('teusink')
>>> print(info['name'], info['status'])
>>> # get content of specific model
>>> sbml = get_sbml_model('teusink')
>>> print(sbml)
- basico.jws_online.download_from(url)
Convenience method reading content from a URL.
This convenience method uses urlopen on either python 2.7 or 3.x
- Parameters
url (str) – the url to read from
- Returns
the contents of the URL as str
- Return type
str
- basico.jws_online.download_json(url)
Convenience method reading the content of the url as JSON.
- Parameters
url (str) – the url to read from
- Returns
a python object representing the json content loaded
- Return type
dict
- basico.jws_online.get_all_models()
Returns the list of all models
>>> get_all_models() [..., { 'slug': 'zi1', 'name': 'zi1', 'cbm': False, 'status': 'CURATED', 'details': 'https://jjj.bio.vu.nl/rest/models/zi1/', 'manuscript': 'https://jjj.bio.vu.nl/rest/models/zi1/manuscript/', 'experiments': 'https://jjj.bio.vu.nl/rest/models/zi1/experiments/' } ]
- Returns
list of model ids
- basico.jws_online.get_manuscript(model_id)
Returns information about the model manuscript
>>> get_manuscript('wolf')
- Parameters
model_id – valid model slug
- Returns
manuscript structure (list of dictionary)
- basico.jws_online.get_mathematica_model(model_id)
Return the mathematica model for the slug
- Parameters
model_id – valid model slug
- Returns
the model as mathematica notebook
- basico.jws_online.get_model_info(model_id)
Returns information about the JWS model
>>> get_model_info('wolf') { 'slug': 'wolf', 'id': 'wolf', 'name': 'wolf', 'cbm': False, 'status': 'CURATED', 'species_set': ['at (ATP)', ... ], 'reaction_set': ['v_1 (glucose transporter)', ...], 'event_set': [], 'parameter_set': ['atot',...] }
- Parameters
model_id – a valid jws slug
- Returns
structure with information about the model [{}]
- basico.jws_online.get_models_for_reaction(reaction)
Searches for models containing a specific reaction
>>> get_models_for_reaction('pfk')
- Parameters
reaction – name of the reaction to search for
- Returns
(list of dictionary) of all models containing the reaction
- basico.jws_online.get_models_for_species(species)
Searches for models containing a specific chemical species
>>> get_models_for_species('atp')
- Parameters
species – the species name to search for
- Returns
(list of dictionary) of all models containing this species
- basico.jws_online.get_sbml_model(model_id)
Returns the SBML for the model.
- Parameters
model_id – valid model slug
- Returns
the model as sbml string
basico.model_info module
The model_info module contains basic functionality for interrogating the model.
Here all functionality for interrogating and manipulating the model is hosted. For each of the elements:
compartments
species
parameters
events
reactions
you will find functions to add, get, set, and remove them.
- class basico.model_info.T
Bases:
object
Constants for Task names
Convert between task names to enums
>>> T.from_enum(0) Steady-State
>>> T.to_enum('Steady-State') 0
- CROSS_SECTION = 'Cross Section'
- EFM = 'Elementary Flux Modes'
- LNA = 'Linear Noise Approximation'
- LYAPUNOV_EXPONENTS = 'Lyapunov Exponents'
- MCA = 'Metabolic Control Analysis'
- MOIETIES = 'Moieties'
- OPTIMIZATION = 'Optimization'
- PARAMETER_ESTIMATION = 'Parameter Estimation'
- SCAN = 'Scan'
- SENSITIVITIES = 'Sensitivities'
- STEADY_STATE = 'Steady-State'
- TIME_COURSE = 'Time-Course'
- TIME_COURSE_SENSITIVITIES = 'Time-Course Sensitivities'
- TIME_SCALE_SEPARATION = 'Time Scale Separation Analysis'
- classmethod all_task_names()
- classmethod from_enum(int_value)
- classmethod to_enum(value)
- basico.model_info.add_amount_expressions(**kwargs)
Utility function that adds model values for all metabolites to the model to compute the amount
The global parameters created will be named amount(metab_name), and so can be accessed at any time. Should the amount already exist, it will not be modified.
- Parameters
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.add_compartment(name, initial_size=1.0, **kwargs)
Adds a new compartment to the model.
- Parameters
name (str) – the name for the new compartment
initial_size (float) – the initial size for the compartment
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) all other parameters from
set_compartment()
.
- Returns
the compartment added
- basico.model_info.add_default_plot(name, **kwargs)
Adds a default plot to the list of plots
- Parameters
name (str) – name of the default plot
kwargs –
optional arguments
- new_name: to rename the plot specification
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
none or the name of the plot created
- Return type
str or None
- basico.model_info.add_equation(eqn, time_symbol='t', **kwargs)
This function allows to add arbitrary equations to the current model.
This function allows adding arbitrary ODE’s / assignments to the model. Nonexisting model entities will be created.
- Parameters
eqn (str) – the equation for example of form: d[X]/dt = k1 * exp({Time})
time_symbol (str) – optional symbol that will be used for time (defaults to t)
kwargs –
- Returns
- basico.model_info.add_event(name, trigger, assignments, **kwargs)
Adds a new event to the model.
- Parameters
name (str) – the name for the new event
trigger (str) – the trigger expression to be used. The expression can consist of all display names. for example Time > 10 would make the event trigger at time 10.
assignments ([(str,str)]) – All the assignments that should be made, when the event fires. This should be a list of tuples where the first element is the name of the element to change, and the second element the assignment expression.
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
the newly created event
- basico.model_info.add_event_assignment(name, assignment, exact=False, **kwargs)
Adds an event assignment to the named event
- Parameters
name (str) – the name (or substring of name) of an event
assignment ([(str,str)] or (str, str)) – tuple or list of tuples of event assignments of form (target, expression)
exact (bool) – boolean indicating whether the named expression has to be exact
- Returns
None
- basico.model_info.add_function(name, infix, type='general', mapping=None, **kwargs)
Adds a new function definition if none with that name already exists
- Parameters
name (str) – the name for the new function
infix (str) – the formula for the new function (e.g: V * S / ( K + S ))
type (str) – optional flag specifying whether the function is ‘reversible’, ‘irreversible’ or ‘general’
mapping (dict) –
optional dictionary mapping the elements of the infix to their usage. If not specified, the usage will default to parameter, other values possible would be substrate, product, modifier, volume or `time. One example for the infix for the infix above we would specify that S is substrate:
{ ‘S’: ‘substrate’ }
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- basico.model_info.add_parameter(name, initial_value=1.0, **kwargs)
Adds a new global parameter to the model.
- Parameters
name (str) – the name for the new global parameter
initial_value (float) – optional the initial value of the parameter (defaults to 1)
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) all other parameters from
set_parameters()
.
- Returns
the newly created parameter
- basico.model_info.add_plot(name, **kwargs)
Adds a new plot specification to the model.
- Parameters
name (str) – the name for the new plot specification
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) all other parameters from
set_plot_dict()
.
- Returns
the plot
- basico.model_info.add_reaction(name, scheme, **kwargs)
Adds a new reaction to the model
- Parameters
name (str) – the name for the new reaction
scheme (str) – the reaction scheme for the new reaction, if it includes Species that do not exist yet in the model they will be created. So for example a scheme of A -> B would create species A and B if they would not exist in the model, before creating the irreversible reaction.
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) all other parameters from
set_reaction()
.
- Returns
the newly created reaction
- basico.model_info.add_report(name, **kwargs)
Adds a new report specification to the model.
- Parameters
name (str) – the name for the new plot specification
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) all other parameters from
set_report_dict()
.
- Returns
the report definition
- basico.model_info.add_species(name, compartment_name='', initial_concentration=1.0, **kwargs)
Adds a new species to the model.
- Parameters
name (str) – the name for the new species
compartment_name (str) – optional the name of the compartment in which the species should be created, it will default to the first compartment. If no compartment is present, a unit compartment named compartment will be created.
initial_concentration (float) – optional the initial concentration of the species
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) all other parameters from
set_species()
.
- Returns
the newly created species
- basico.model_info.as_dict(df)
Convenience function returning the data frame as dictionary
- Parameters
df (pd.DataFrame) – the data frame
- Returns
the contents of the dataframe as [{}] if there are multiple ones, otherwise the dictionary if just one, or None
- Return type
List[Dict] or Dict or None
- basico.model_info.assign_report(name, task, filename='', append=True, confirm_overwrite=True, **kwargs)
Assigns the named report to the specified task
- Parameters
name (str) – the name of the report definition to assign
task (Union[int, str, COPASI.CCopasiTask]) – the task to assign the report to
filename (str) – the filename to write the result to or ‘’, if it is the empty, it resets the target of the task, and COPASI will not create that report
append (bool) – boolean indicating whether output should be appended (defaults to True)
confirm_overwrite (bool) – boolean indicating whether the copasi should ask before overwriting a file
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.get_cn(name_or_reference, initial=False, **kwargs)
Gets the cn of the named element or none
- Parameters
name_or_reference (str or COPASI.CDataObject) – display name of model element
initial (bool) – if True, an initial reference cn will be returned, rather than a transient one
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
the cn if found or None
- Return type
str or None
- basico.model_info.get_compartments(name=None, exact=False, **kwargs)
Returns all information about the compartments as pandas dataframe.
- Parameters
name (str) – optional filter expression for the compartment, if it is not included in the name, the compartment will not be added to the data set.
exact (bool) – boolean indicating, that the name has to be exact
kwargs –
optional arguments:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
a pandas dataframe with the information about the compartment
- Return type
pandas.DataFrame
- basico.model_info.get_default_plot_names(filter=None, **kwargs)
Returns a list of default plot names
- Parameters
filter – optional filter of substring to be in the name
kwargs –
- Returns
- basico.model_info.get_events(name=None, exact=False, **kwargs)
Returns all information about the events as pandas dataframe.
- Parameters
name (str) – optional filter expression for the event, if it is not included in the event name, the event will not be added to the data set.
exact (bool) – boolean indicating whether the name has to be exact
kwargs –
optional arguments:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
a pandas dataframe with the information about the event
- Return type
pandas.DataFrame
- basico.model_info.get_functions(name=None, **kwargs)
Returns all available functions as pandas dataframe.
- Parameters
name (str) – optional filter expression for the functions, if it is not included in the name, the function will not be added to the data set.
kwargs –
optional arguments:
reversible: to further filter for functions that are only reversible
- suitable_for: an optional reaction for which to filter the function list. Only functionssuitable for the reaction will be returned
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
a pandas dataframe with the information about the functions
- Return type
pandas.DataFrame
- basico.model_info.get_jacobian_matrix(apply_initial_values=False, **kwargs)
Returns the jacobian matrix of the model at the current state
- Parameters
apply_initial_values (bool) – if set to the the initial values will be applied, otherwise the jacobian from the current state will be returned
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
the stoichiometry matrix of the current model
- Return type
pd.DataFrame
- basico.model_info.get_miriam_annotation(**kwargs)
Returns the elements miriam annotations as dictionary of the form:
- {
‘created’: datetime, ‘creators’: [{
‘first_name’: ‘…’, ‘last_name’: ‘…’, ‘email’: ‘…’, ‘organization’: ‘…’
},…],
- ‘references’: [{
‘id’: ‘…’, ‘uri’: ‘identifiers.org uri’, ‘resource’: ‘human readable name of resource’, ‘description’, ‘…’
},…],
- ‘descriptions’: [{
‘id’: ‘…’, ‘qualifier’: ‘human readable qualifier string’, ‘uri’: ‘identifiers.org uri’, ‘resource’: ‘name of the resource referenced’
},…], ‘modifications’: [datetime,…]
}
- Parameters
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) - name: the display name of the element to set the notes on.otherwise the main model will be taken.
- element: any model element
- Returns
the elements annotation as dictionary as described
- Return type
{}
- basico.model_info.get_miriam_resources()
Retrieves the current MIRIAM resources from the configuration
- Returns
dataframe with the list of current miriam resources
- Return type
pandas.DataFrame
- basico.model_info.get_model_units(**kwargs)
Returns all model units as dictionary.
- Parameters
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
a dictionary containing the model units in the form: | { | ‘time_unit’: ‘’, | ‘quantity_unit’: ‘’, | ‘length_unit’: ‘’, | ‘area_unit’: ‘’, | ‘volume_unit’: ‘’, | }
- basico.model_info.get_notes(**kwargs)
Returns all notes on the element or model.
- Parameters
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) - name: the display name of the element to set the notes on.otherwise the main model will be taken.
- element: any model element
- Returns
the notes string (plain text, or xhtml)
- Return type
str
- basico.model_info.get_parameters(name=None, exact=False, **kwargs)
Returns all information about the global parameters as pandas dataframe.
- Parameters
name (str) – optional filter expression for the parameters, if it is not included in the name, the parameter will not be added to the data set.
exact (bool) – boolean indicating that the name has to be exact
kwargs –
optional arguments:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
a pandas dataframe with the information about the parameter
- Return type
pandas.DataFrame
- basico.model_info.get_plot_dict(plot_spec, **kwargs)
Returns the information for the specified plot
- Parameters
plot_spec (Union[str,int,COPASI.CPlotSpecification]) – the name, index or plot specification object
kwargs –
optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
dictionary of the form: | { | ‘name’: ‘Phase Plot’, | ‘active’: True, | ‘log_x’: False, | ‘log_y’: False, | ‘tasks’: ‘’, | ‘curves’: | [ | { | ‘name’: ‘[Y]|[X]’, # the name of the curve | ‘type’: ‘curve2d’,# type of the curve (one of curve2d, histoItem1d, bandedGraph | or spectogram) | ‘channels’: [‘[X]’, ‘[Y]’], # display names of all the items to be plotted | ‘color’: ‘auto’, # color as hex rgb value (i.e ‘#ff0000’ for red) or ‘auto’ | ‘line_type’: ‘lines’,# the line type (one of lines, points, symbols or | lines_and_symbols) | ‘line_subtype’: ‘solid’, # line subtype (one of solid, dotted, dashed, dot_dash or | dot_dot_dash) | ‘line_width’: 2.0, # line width | ‘symbol’: ‘small_cross’, # the symbol to be used (one of small_cross, large_cross | or circle ) | ‘activity’: ‘during’ # when the data should be collected (one of ‘before’, ‘during’, ‘after’) | from task | } | ] | }
- basico.model_info.get_plots(name=None, **kwargs)
Returns all information about the plot definitions as pandas dataframe.
- Parameters
name (str) – optional filter expression for the plots, if it is not included in the plot name, the plot will not be added to the data set.
kwargs –
optional arguments:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
a pandas dataframe with the information about the plot see also
get_plot_dict()
- Return type
pandas.DataFrame
- basico.model_info.get_reaction_mapping(reaction, **kwargs)
Returns the reaction mapping of the given reaction
- Parameters
reaction (str or COPASI.CReaction) – name of a reaction, or the reaction object
kwargs –
optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
the dictionary with the reaction mapping
- Return type
{}
- basico.model_info.get_reaction_parameters(name=None, **kwargs)
Returns all local parameters as pandas dataframe.
This also includes global parameters that are mapped to local ones.
- Parameters
name (str) – optional filter expression, if it is not included in the name, the function will not be added to the data set.
kwargs –
optional arguments:
- reaction_name: to further filter for local parameters of only certain reactions(that contain the substring)
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
a pandas dataframe with the information about local parameters
- Return type
pandas.DataFrame
- basico.model_info.get_reactions(name=None, exact=False, **kwargs)
Returns all reactions as pandas dataframe.
- Parameters
name (str) – optional filter expression, if it is not included in the name, the reaction will not be added to the data set.
exact (bool) – boolean indicating, that the name has to be exact
kwargs –
optional arguments:
- reaction_name: to further filter for local parameters of only certain reactions(that contain the substring)
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
a pandas dataframe with the information about local parameters
- Return type
pandas.DataFrame
- basico.model_info.get_reduced_jacobian_matrix(apply_initial_values=False, **kwargs)
Returns the jacobian matrix of the reduced model at the current state
- Parameters
apply_initial_values (bool) – if set to the the initial values will be applied, otherwise the jacobian from the current state will be returned
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
the stoichiometry matrix of the reduced current model
- Return type
pd.DataFrame
- basico.model_info.get_reduced_stoichiometry_matrix(**kwargs)
Returns the reduced stoichiometry matrix of the model
- Returns
the stoichiometry matrix of the current model
- Return type
pd.DataFrame
- basico.model_info.get_report_dict(report, **kwargs)
Returns all information about the plot as dictionary
- Parameters
report (COPASI.CReportDefinition or int or str) – report definition, index or name
kwargs –
optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
a dictionary with all information about the plot
- Return type
dict
- basico.model_info.get_reports(name=None, ignore_automatic=False, task=None, **kwargs)
Returns the reports as dataframe
- Parameters
name – optional filter by name
ignore_automatic – if true, only manually created reports are returned
task – optional task name, to the get the report for
kwargs –
optional arguments:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
a data frame with all the report information
- Return type
pd.DataFrame
- basico.model_info.get_scheduled_tasks(**kwargs)
Returns the list of scheduled tasks
- Parameters
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
list of tasks that are scheduled
- Return type
[str]
- basico.model_info.get_species(name=None, exact=False, **kwargs)
Returns all information about the species as pandas dataframe.
Example:
Assume you have the brusselator example loaded load_example(‘brusselator’)
>>> get_species()
returns you a dataframe of all species with the species name as index.
>>> get_species('X')
returns you only those species, that include X in the name.
- Parameters
name (str) – optional filter expression for the species, if it is not included in the species name, the species will not be added to the data set.
exact (bool) – if true, the name has to match precisely the name of the species
kwargs –
optional arguments to further filter down the species. recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) compartment: to filter down only species in specific compartments
type: to filter for species of specific simulation type
- Returns
a pandas dataframe with the information about the species
- Return type
pandas.DataFrame
- basico.model_info.get_stoichiometry_matrix(**kwargs)
Returns the stoichiometry matrix of the model
- Returns
the stoichiometry matrix of the current model
- Return type
pd.DataFrame
- basico.model_info.get_task_settings(task, basic_only=True, **kwargs)
Returns the settings of the given task
- Parameters
task (COPASI.CCopasiTask or str) – the task to read the settings of
basic_only (bool) – boolean flag, indicating that only the basic parameters should be returned
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
dict of task settings
- Return type
{}
- basico.model_info.get_time_unit(**kwargs)
Returns the time unit of the model
- basico.model_info.get_value(name_or_reference, initial=False, **kwargs)
Gets the value of the named element or nones
- Parameters
name_or_reference (str or COPASI.CDataObject) – display name of model element
initial (bool or None) – if True, an initial value will be returned, rather than a transient one. If set to None, the default reference will be returned and not coerced.
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
the value if found or None
- Return type
float or None
- basico.model_info.have_miriam_resources()
Utility function returning whether MIRIAM resources are avaialble
- Returns
boolean indicating whether there are MIRIAM resources available or not
- Return type
bool
- basico.model_info.remove_amount_expressions(**kwargs)
Utility function that removes model values created using add_amount_expressions.
The global parameters created will be named amount(metab_name), and so can be accessed at any time.
- Parameters
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.remove_compartment(name, **kwargs)
Deletes the named compartment (and everything included)
- Parameters
name (str) – the name of a compartment in the model
kwargs –
optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.remove_event(name, **kwargs)
Deletes the named event
- Parameters
name (str) – the name of an event in the model
kwargs –
optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.remove_function(name, **kwargs)
Removes the function with the given name
- Parameters
name (str) – the name of the function to be removed
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
- basico.model_info.remove_parameter(name, **kwargs)
Deletes the named global parameter
- Parameters
name (str) – the name of a parameter in the model
kwargs –
optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.remove_plot(name, **kwargs)
Deletes the named plot
- Parameters
name (str) – the name of an plot in the model
kwargs –
optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.remove_reaction(name, **kwargs)
Deletes the named reaction
- Parameters
name (str) – the name of a reaction in the model
kwargs –
optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.remove_report(name, **kwargs)
Deletes the named report
- Parameters
name (str) – the name of a report in the model
kwargs –
optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.remove_report_from_task(task, **kwargs)
Clears the report filename from the specified task
- Parameters
task (Union[int, str, COPASI.CCopasiTask]) – the task to assign the report to
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.remove_species(name, **kwargs)
Deletes the named species
- Parameters
name (str) – the name of a species in the model
kwargs –
optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.remove_user_defined_functions()
Removes all user defined functions along with all elements that still use them
- basico.model_info.set_compartment(name=None, exact=False, **kwargs)
Sets properties of the named compartment
- Parameters
name (str) – the name of the compartment (or a substring of the name)
exact (bool) – boolean indicating whether the name has to be exact
kwargs –
optional arguments
- new_name: the new name for the compartment
- initial_value or initial_size: to set the initial size of the compartment
- value or size: to set the transient size of the compartment
- initial_expression: the initial expression for the compartment
- status or type: the type of the compartment one of fixed, assignment or ode
- expression: the expression for the compartment (only valid when type is ode or assignment)
- dimensionality: sets the dimensionality of the compartment (int value 1..3)
- notes: sets notes for the compartment (either plain text, or valid xhtml)
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.set_element_name(element, new_name, **kwargs)
Sets the name of the element
- Parameters
element (COPASI.CDataObject or str) – the element whose name to change
new_name (str) – the new name for the element
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- basico.model_info.set_event(name, exact=False, trigger=None, assignments=None, **kwargs)
Sets properties of the named event
- Parameters
name (str) – the name of the event (or a substring of the name)
exact (bool) – boolean indicating, that the name has to be exact
trigger (str or None) – the trigger expression to be used. The expression can consist of all display names. for example Time > 10 would make the event trigger at time 10.
assignments ([(str,str)] or None) – All the assignments that should be made, when the event fires. This should be a list of tuples where the first element is the name of the element to change, and the second element the assignment expression.
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
- basico.model_info.set_miriam_annotation(created=None, creators=None, references=None, descriptions=None, modifications=None, replace=True, **kwargs)
Sets the MIRIAM annotations for the provided element or model
- Parameters
created (datetime.datetime or None) – the date/time to set as the objects creation time or None, if not to be set
creators (list or None) –
None, if not to be modified, otherwise list of creators of the form:{‘first_name’: ‘…’,’last_name’: ‘…’,’email’: ‘…’,’organization’: ‘…’}references (list or None) –
None if not to be modified, otherwise list of references of the form:{‘resource’: ‘human readable name of resource’,’id’: ‘…’,’uri’: ‘identifiers.org uri’,’description’, ‘…’}only the uri needs to be provided, or alternatively id + resource.descriptions (list or None) –
None if not to be modified, otherwise list of descriptions of the form:{‘resource’: ‘human readable name of resource’,’id’: ‘…’,’qualifier’: ‘…’,’uri’: ‘identifiers.org uri’,}only the uri needs to be provided, or alternatively id + resource.modifications (list or None) –
None if not to be modified, otherwise list of datetime objects representingmodification datesreplace – Boolean indicating whether existing entries should be removed.
- Returns
None
- basico.model_info.set_model_name(new_name, **kwargs)
Renames the model to the provided new name
- Parameters
new_name (str) – the new name of the model
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.set_model_unit(**kwargs)
Sets the model units.
- Parameters
kwargs –
optional parameters
- time_unit: time unit expression
- substance_unit or quantity_unit: substance unit expression
- length_unit: length unit expression
- area_unit: area unit expression
- volume_unit: volume unit expression
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- basico.model_info.set_notes(notes, **kwargs)
Sets notes on the provided element
- Parameters
notes (str) – the notes to be set, can be either plain text, or valid xhtml
kwargs –
optional parameters, recognized are:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) - name: the display name of the element to set the notes on.otherwise the main model will be taken.
- element: any model element
- Returns
None
- basico.model_info.set_parameters(name=None, exact=False, **kwargs)
Sets properties of the named parameter(s).
- Parameters
name (str) – the name of the parameter (or a substring of the name)
exact (bool) – boolean indicating whether the name has to be exact or not
kwargs –
optional arguments
- new_name: the new name for the parameter
- unit: the unit expression to be set
- initial_value: to set the initial value for the parameter
- value: set the transient value for the parameter
- initial_expression: the initial expression
- status or type: the type of the parameter one of fixed, assignment or ode
- expression: the expression for the parameter (only valid when type is ode or assignment)
- notes: sets notes for the parameter (either plain text, or valid xhtml)
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.set_plot_curves(plot_spec, curves, **kwargs)
Sets all curves of the named plot specification (all curves will be replaced)
- Parameters
plot_spec (Union[str,int,COPASI.CPlotSpecification]) – the name, index or plot specification object
curves ([{}]) –
list of dictionaries of curve items to be added. For example[{‘name’: ‘[Y]|[X]’, # the name of the curve’type’: ‘curve2d’, # type of the curve (one of curve2d, histoItem1d, bandedGraphor spectogram)’channels’: [‘[X]’, ‘[Y]’], # display names of all the items to be plotted’color’: ‘auto’, # color as hex rgb value (i.e ‘#ff0000’ for red) or ‘auto’’line_type’: ‘lines’, # the line type (one of lines, points, symbols orlines_and_symbols)’line_subtype’: ‘solid’, # line subtype (one of solid, dotted, dashed, dot_dash ordot_dot_dash)’line_width’: 2.0, # line width’symbol’: ‘small_cross’, # the symbol to be used (one of small_cross, large_cross or circle)’activity’: ‘during’ # when the data should be collected (one of ‘before’, ‘during’, ‘after’)}]Additionally, histograms may have the bin size in a increment element. Spectograms can havelog_z, color_map (one of ‘Default’, ‘Yellow-Red’, ‘Grayscale’ or ‘Blue-White-Red’),’bilinear’ (should the plot interpolate between values), ‘contours’ (at which values to draw contours)’max_z’ (max z value).kwargs –
optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.set_plot_dict(plot_spec, active=True, log_x=False, log_y=False, tasks='', **kwargs)
Sets properties of the named plot specification.
- Parameters
plot_spec (Union[str,int,COPASI.CPlotSpecification]) – the name, index or plot specification object
active (bool) – boolean indicating whether plot should be active (defaults to true)
log_x (bool) – boolean indicating that the x axis should be logarithmic
log_y (bool) – boolean indicating that the y axis should be logarithmic
tasks (str) –
task type (or colon separated list of task types) for which the plotshould be brought upkwargs –
optional arguments
- new_name: to rename the plot specification
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) curves: dictionary in the format as described in
set_plot_curves()
.
- Returns
None
- basico.model_info.set_reaction(name=None, exact=False, **kwargs)
Sets attributes of the named reaction.
- Parameters
name (str) – the name of the reaction (or a substring of the name)
exact (bool) – boolean indicating whether the name has to be exact
kwargs –
optional arguments
- new_name: new name of the reaction
- scheme: the reaction scheme, new species will be created automatically
- function: the function from the function database to set
- mapping: an optional dictionary that maps model elements to the functionparameters. (can be any volume, species, modelvalue or in case oflocal parameters a value)
- notes: sets notes for the reaction (either plain text, or valid xhtml)
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.set_reaction_mapping(reaction, mapping, **kwargs)
Sets the reaction mapping of the parameters as specified in the mapping dictionary
- Parameters
reaction (str or COPASI.CReaction) – the name of the reaction (or reaction object)
mapping ({}) –
- dictionary that maps model elements to the function
parameters. (can be any volume, species, modelvalue or in case of
local parameters a value)
kwargs –
optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
boolean indicating whether the reaction was changed
- Return type
bool
- basico.model_info.set_reaction_parameters(name=None, **kwargs)
Sets local parameter values.
- Parameters
name (str) – the name of the parameter (or a substring of the name)
kwargs –
optional arguments
- reaction_name: if specified only parameters of the named reaction will be changed
- value: the new value of the parameter to set. (only one of value / mapped_to should be defined)
- mapped_to: the name of a global parameter to map the local parameter to
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.set_report_dict(spec, precision=None, separator=None, table=None, print_headers=True, header=None, body=None, footer=None, task=None, comment=None, **kwargs)
Sets properties of the named report definition.
- Parameters
spec (Union[str,int,COPASI.CReportDefinition]) – the name, index or report definition object
precision (Optional[int]) – number of digits to print (defaults to 6)
separator (Optional[str]) – the separator to use between elements (defaults to )
table ([str]) – a list of CNs or display names of elements to collect in a table. If table is specified the header, body, footer argument will be ignored
print_headers (bool) – optional arguments, indicating whether table headers will be printed (only applies when the table argument is given
header ([str]) – a list of CNs or display names of elements to collect in the header column
body ([str]) – a list of CNs or display names of elements to collect in the body rows
footer ([str]) – a list of CNs or display names of elements to collect in the footer column
task (Optional[str]) –
task name for which the report should be usedcomment (Optional[str]) – a documentation string for the report (can bei either string, or xhtml string)
kwargs –
optional arguments
- new_name: to rename the report
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.set_scheduled_tasks(task_name, **kwargs)
Sets the scheduled tasks
Only the tasks with the listed names will be set to be scheduled.
- Parameters
task_name (str or [str]) – name or list of names of tasks set to be scheduled
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.set_species(name=None, exact=False, **kwargs)
Sets properties of the named species
- Parameters
name (str) – the name of the species (or a substring of the name)
exact (bool) – boolean indicating, that the name has to be exact
kwargs –
optional arguments
- new_name: the new name for the species
- initial_concentration: to set the initial concentration for the species
- initial_particle_number: to set the initial particle number for the species
- initial_expression: the initial expression for the species
- concentration: the new transient concentration for the species
- particle_number: the new transient particle number for the species
- status or type: the type of the species one of fixed, assignment or ode
- expression: the expression for the species (only valid when type is ode or assignment)
- notes: sets notes for the species (either plain text, or valid xhtml)
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.set_task_settings(task, settings, **kwargs)
Applies the task settings present in the settings object
- Parameters
task (COPASI.CCopasiTask or str) – the task to set
settings (dict) – dictionary in the same format as the ones obtained from
get_task_settings()
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_info.set_time_unit(unit, **kwargs)
Sets the time unit of the model.
- Parameters
unit (str) – the time unit expression
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- basico.model_info.set_value(name_or_reference, new_value, initial=False, **kwargs)
Gets the value of the named element or nones
- Parameters
name_or_reference (str or COPASI.CDataObject) – display name of model element
initial (bool or None) – if True, an initial value will be set, rather than a transient one. If set to None, the default reference will be returned and not coerced.
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
the value if found or None
- Return type
float or None
- basico.model_info.update_miriam_resources()
This method downloads the latest miriam resources from the COPASI website and stores the configuration
basico.model_io module
This module hosts all method for loading/saving new models.
All methods for loading / saving a new model are within this module. As well as
the functionality to get/set the currently loaded model. Whenever a function needs
the currently loaded model, and no model was provided in the kwargs, the
get_current_model()
function retrieves the model loaded last. There are also convenience
methods to load models directly from BioModels or from url.
- basico.model_io.create_datamodel()
creates a new data model
- Returns
new data model
- Return type
COPASI.CDataModel
- basico.model_io.get_current_model()
Returns the current model.
This function returns the current model. That is the model loaded / created last. If no model exists a new one will be created first.
- Returns
the current model
- Return type
COPASI.CDataModel
- basico.model_io.get_examples(selector='')
Returns the filenames of examples bundled with this version.
A number of example models are included with the distribution. This method returns the filenames to those examples. Filtered by the argument.
- Parameters
selector (str) – a filter expression to be used, only files matching *{selector}.[cps|xml] will be returned
- Returns
the list of examples matching
- Return type
[str]
- basico.model_io.get_model_from_dict_or_default(d, key='model')
Convenience function returning the data model from the dictionary
- Parameters
d – the dictionary optionally containing the data model
key – the key that the model is under (defaults to ‘model’)
- Returns
the data model if found, or the one from
get_current_model()
- Return type
COPASI.CDataModel
- basico.model_io.get_num_loaded_models()
- Returns
the number of loaded models
- basico.model_io.load_biomodel(model_id)
Loads a model from the BioModels Database.
- Parameters
model_id (Union[int,str]) – either an integer of the biomodels id, or a valid biomodels id
- Returns
- Return type
COPASI.CDataModel
- basico.model_io.load_example(selector)
Loads the example matching the selector.
- Parameters
selector (str) – the filter expression to use for the examples see
get_examples()
- Returns
the loaded model, or None, if none matched
- Return type
COPASI.CDataModel or None
- basico.model_io.load_model(location)
Loads the model and sets it as current
- Parameters
location (str) – either a filename, url or raw string of a COPASI / SBML model
- Returns
the loaded model
- Return type
COPASI.CDataModel
- basico.model_io.load_model_from_string(content)
Loads either COPASI model / SBML model from the raw string given.
- Parameters
content (str or bytes) – the copasi / sbml model serialized as string
- Returns
the loaded model
- Return type
COPASI.CDataModel
- basico.model_io.load_model_from_url(url)
Loads either COPASI model / SBML model from the url.
- Parameters
url (str) – url to a copasi / sbml model
- Returns
the loaded model
- Return type
COPASI.CDataModel
- basico.model_io.new_model(**kwargs)
Creates a new model and sets it as current.
- Parameters
kwargs – optional arguments
name (str): the name for the new model
quantity_unit (str): the unit to use for species
time_unit (str): the time unit to use
volume_unit (str): the unit to use for 3D compartments
area_unit (str): the unit to use for 2D compartments
length_unit (str): the unit to use for 1D compartments
- notes: sets notes for the model (either plain text, or valid xhtml)
- Returns
the new model
- Return type
COPASI.CDataModel
- basico.model_io.open_copasi(filename='', **kwargs)
Saves the model as COPASI file and opens it in COPASI.
The file will be written to a temporary file, and then it will be executed, so that the application registered to open it will start.
- Parameters
filename (str) – the file name to write to, if not given a temp file will be created that will be deleted at the end of the python session.
kwargs – optional arguments:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.model_io.overview(model=None)
Returns a basic representation of the model.
- Parameters
model (COPASI.CDataModel or None) – the model to get the overview for
- Returns
a string, consisting of name, # compartments, # species, # parameters, # reaction
- Return type
str
- basico.model_io.print_model(model=None)
Prints the model overview.
See also
overview()
- Parameters
model (COPASI.CDataModel) – the model
- Returns
None
- basico.model_io.remove_datamodel(model)
Removes the model from the internal list of loaded models.
The model is removed from the list of models, and current model, before it is freed
- Parameters
model – the model to be removed
:type model:COPASI.CDataModel :return: None
- basico.model_io.save_model(filename, **kwargs)
Saves the model to the given filename.
- Parameters
filename (str) – the file to be written
kwargs – optional arguments:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) type (str): copasi to write COPASI files, sbml to write SBML files (defaults to copasi)
overwrite (bool): whether the file should be overwritten if present (defaults to True)
level (int): SBML level to export
version (int): SBML version to export
export_copasi_miriam (bool): whether to export copasi miriam annotations
export_incomplete (bool): whether to export incomplete SBML model
- Returns
None
- basico.model_io.save_model_and_data(filename, **kwargs)
Saves the model to the give filename, along with all experimental data files.
- Parameters
filename – the filename of the COPASI file to write
filename – str
kwargs – optional arguments:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) - delete_data_on_exit (bool): a flag indicating whether the files should be deleted at the end of thepython session (defaults to False)
- Returns
None
- basico.model_io.save_model_to_string(**kwargs)
Saves the current model to string
- Parameters
kwargs – optional arguments:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
the copasi model as string
- Return type
str
- basico.model_io.set_current_model(model)
Sets the current model.
The current model, is the one that all functions will use if not is provided explicitly.
- Parameters
model (COPASI.CDataModel) – the model to be set as current
- Returns
the model
- Return type
COPASI.CDataModel
basico.task_parameterestimation module
Submodule with utility methods for carrying out and plotting of parameter estimations.
The main function provided by this submodule is run_parameter_estimation()
. Without any parameters, the
previously set up parameter estimation as stored in the file will be carried out. And the parameters found will
be returned.
It is also possible to set up parameter estimation problems from scratch. To make it as simple as possible, pandas data frames are used, the mapping from the columns to the model element will be done implicitly by naming the columns like the corresponding model elements.
Example
>>> from basico import *
>>> m = model_io.load_example("LM-test1")
>>> print(get_fit_parameters())
>>> print(get_parameters_solution())
>>> run_parameter_estimation(method='Levenberg - Marquardt')
>>> print(get_parameters_solution())
- class basico.task_parameterestimation.PE
Bases:
object
Constants for Parameter estimation method names
Convert between method names to enums
>>> T.from_enum(0) 'Current Solution Statistics'
>>> T.to_enum('Current Solution Statistics') 17
- CURRENT_SOLUTION = 'Current Solution Statistics'
- DIFFERENTIAL_EVOLUTION = 'Differential Evolution'
- EVOLUTIONARY_PROGRAMMING = 'Evolutionary Programming'
- EVOLUTIONARY_STRATEGY_SRES = 'Evolution Strategy (SRES)'
- GENETIC_ALGORITHM = 'Genetic Algorithm'
- GENETIC_ALGORITHM_SR = 'Genetic Algorithm SR'
- HOOKE_JEEVES = 'Hooke & Jeeves'
- LEVENBERG_MARQUARDT = 'Levenberg - Marquardt'
- NELDER_MEAD = 'Nelder - Mead'
- NL2SOL = 'NL2SOL'
- PARTICLE_SWARM = 'Particle Swarm'
- PRAXIS = 'Praxis'
- RANDOM_SEARCH = 'Random Search'
- SCATTER_SEARCH = 'Scatter Search'
- SIMULATED_ANNEALING = 'Simulated Annealing'
- STEEPEST_DESCENT = 'Steepest Descent'
- TRUNCATED_NEWTON = 'Truncated Newton'
- classmethod all_method_names()
- classmethod from_enum(int_value)
- classmethod to_enum(value)
- basico.task_parameterestimation.add_experiment(name, data, **kwargs)
Adds a new experiment to the model.
This method adds a new experiment file to the parameter estimation task. The provided data frame will be written into the current directory as experiment_name.txt unless a filename has been provided.
The mapping between the columns and the model elements should be done by having the columns of the data frame be model element names in question. So for example [A] to note that the transient concentrations of a species A is to be mapped as dependent variable. or [A]_0 to note that the initial concentration of a species A is to be mapped as independent variable.
- Parameters
name (str) – the name of the experiment
data (pandas.DataFrame) – the data frame with the experimental data
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) - file_name (str): the file name to save the experimental data to (otherwise it will be name.txt)
- Returns
the filename of the generated data file
- Return type
str
- basico.task_parameterestimation.add_experiment_from_dict(exp_dict, **kwargs)
Adds an experiment from dictionary
- Parameters
exp_dict –
- Returns
- basico.task_parameterestimation.get_data_from_experiment(experiment, **kwargs)
Returns the data of the given experiment as dataframe
- Parameters
experiment – the experiment
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) - rename_headers (bool): if true (default) the columns of the headers will be renamedwith the names of the element it is mapped to. Also all ignored columns will be removed from thedataset
- Returns
dataframe with experimental data
- Return type
pandas.DataFrame
- basico.task_parameterestimation.get_experiment(experiment, **kwargs)
Returns the specified experiment.
- Parameters
experiment (int or str or COPASI.CExperiment) – experiment name or index
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
the experiment or an error if none existent
- basico.task_parameterestimation.get_experiment_data_from_model(model=None)
Returns all experimental data from the model
- Parameters
model (COPASI.CDataModel or None) – the model to get the data from
- Returns
list of dataframes with experimental data (with columns renamed and unmapped columns dropped)
- Return type
[pandas.DataFrame]
- basico.task_parameterestimation.get_experiment_dict(experiment, **kwargs)
Returns all information about the experiment as dictionary
- Parameters
experiment – copasi experiment, experiment name or index
kwargs – optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
all information about the experiment as dictionary
- basico.task_parameterestimation.get_experiment_filenames(model=None)
Returns filenames of all experiments
- Parameters
model (COPASI.CDataModel or None) – the model to get the data from
- Returns
list of filenames of experimental data
- Return type
[str]
- basico.task_parameterestimation.get_experiment_mapping(experiment, **kwargs)
Retrieves a data frame of the experiment mapping.
The resulting data frame will have the columns: * column (int): index of the column in the file * type (str): ‘time’, ‘dependent’, ‘indepenent’ or ‘ignored’ * ‘mapping’ (str): the name of the element it is mapped to * ‘cn’ (str): internal identifier
- Parameters
experiment – the experiment to get the mapping from
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
data frame with the mapping as described
- Return type
pandas.DataFrame
- basico.task_parameterestimation.get_experiment_names(**kwargs)
Returns the list of experiment names
- Parameters
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
list of experiment names defined
- Return type
[str]
- basico.task_parameterestimation.get_fit_item_template(include_local=False, include_global=False, default_lb=0.001, default_ub=1000, model=None)
Returns a template list of items to be used for the parameter estimation
- Parameters
include_local (bool) – boolean, indicating whether to include local parameters
include_global (bool) – boolean indicating whether to include global parameters
default_lb (float) – default lower bound to be used
default_ub (float) – default upper bound to be used
model (COPASI.CDataModel or None) – the model or None
- Returns
List of dictionaries, with the local / global parameters in the format needed by:
set_fit_parameters()
.- Return type
[{}]
- basico.task_parameterestimation.get_fit_parameters(model=None)
Returns a data frame with all fit parameters
The resulting dataframe will have the following columns:
name: the name of the fit parameter
lower: the lower bound of the parameter
upper: the upper bound of the parameter
start: the start value
- affected: a list of all experiments (names) the fit parameter should apply to. If empty the parameter shouldbe varied for all experiments.
cn: internal identifier
- Parameters
model (COPASI.CDataModel or None) – the model to get the fit parameters from
- Returns
data frame with the fit parameters
- Return type
pandas.DataFrame
- basico.task_parameterestimation.get_fit_statistic(include_parameters=False, include_experiments=False, include_fitted=False, **kwargs)
Return information about the last fit.
- Parameters
include_parameters (bool) – whether to include information about the parameters in a result entry with key parameters
include_experiments (bool) – whether to include information about the experiments in a result entry with key experiments
include_fitted (bool) – whether to include information about the fitted values in a result entry with key fitted
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
dictionary with the fit statistic
- Return type
{}
- basico.task_parameterestimation.get_parameters_solution(model=None)
Returns the solution found for the fit parameters as data frame
The resulting data frame will have the columns:
name: the name of the parameter
lower: the parameters lower bound
upper: the parameters upper bound
sol: the solution found in the last run (or NaN, if not run yet, or no solution found)
affected: the experiments this parameter applies to (or an empty list if it applies to all)
- Parameters
model (COPASI.CDataModel or None) – the model to use, or None
- Returns
data frame as described
- Return type
pandas.DataFrame
- basico.task_parameterestimation.get_simulation_results(values_only=False, update_parameters=True, **kwargs)
Runs the current solution statistics and returns result of simulation and experimental data
- Parameters
values_only (bool) – if true, only time points at the measurements will be returned
update_parameters (bool) – if set true, the model will be updated with the parameters found from the solution. (defaults to True)
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) - solution: a solution data frame to use, if not specified a current solution statistic will be computed
- Returns
tuple of lists of experiment data, and a list of simulation data
- Return type
([pandas.DataFrame],[pandas.DataFrame])
- basico.task_parameterestimation.load_experiments_from_dict(experiments, **kwargs)
Loads all experiments from the specified experiment description
All existing experiments will be replaced with the ones from the specified file.
- Parameters
experiments – list of experiment dictionaries
kwargs – optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
- basico.task_parameterestimation.load_experiments_from_yaml(experiment_description, **kwargs)
Loads all experiments from the specified experiment description
All existing experiments will be replaced with the ones from the specified file.
- Parameters
experiment_description – filename or yamlstring
kwargs – optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
- basico.task_parameterestimation.num_experiment_files(**kwargs)
Return the number of experiment files defined.
- Parameters
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
number of experiment files
- Return type
int
- basico.task_parameterestimation.num_validations_files(**kwargs)
Returns the number of cross validation experiment files
- Parameters
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
number of cross validation experiment files
- Return type
int
- basico.task_parameterestimation.plot_per_dependent_variable(**kwargs)
This function creates a figure for each dependent variable, with traces for all experiments.
- Parameters
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
array of tuples (fig, ax) for each figure created
- basico.task_parameterestimation.plot_per_experiment(**kwargs)
This function creates one figure per experiment defined, with plots of all dependent variables and their fit in it.
- Parameters
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
array of tuples (fig, ax) for the figures created
- basico.task_parameterestimation.prune_simulation_results(simulation_results)
Removes all columns & time points from the simulation set, that are not available in the measurement set
- Parameters
simulation_results – the simulation result as obtained by get_simulation_results
- Returns
- basico.task_parameterestimation.remove_experiments(**kwargs)
Removes all experiments from the model
- Parameters
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.task_parameterestimation.remove_fit_parameters(**kwargs)
Removes all fit items
- Parameters
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.task_parameterestimation.run_parameter_estimation(**kwargs)
Runs the parameter estimation task as specified:
The following are valid methods to be used for the parameter estimation task.
Current Solution:
Current Solution Statistics,
Global Methods:
Random Search,
Simulated Annealing,
Differential Evolution,
Scatter Search,
Genetic Algorithm,
Evolutionary Programming,
Genetic Algorithm SR,
Evolution Strategy (SRES),
Particle Swarm,
Local Methods:
Levenberg - Marquardt,
Hooke & Jeeves,
Nelder - Mead,
Steepest Descent,
NL2SOL,
Praxis,
Truncated Newton,
- Parameters
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) - method (str): one of the strings from above
- randomize_start_values (bool): if true, parameters will be randomized before starting otherwise theparameters starting value will be taken.
- calculate_statistics (bool): if true, the statistics will be calculated at the end of the task
- create_parametersets (bool): if true, parameter sets will be created for all experiments
use_initial_values (bool): whether to use initial values
scheduled (bool): sets whether the task is scheduled or not
update_model (bool): sets whether the model should be updated, or reset to initial conditions.
- settings (dict): a dictionary with settings to use, in the same format as the ones obtained from
write_report (bool): overrides the writing of a report file of filename is specified. (defaults to True)
- Returns
the solution for the fit parameters see
get_parameters_solution()
.- Return type
pandas.DataFrame
- basico.task_parameterestimation.save_experiments_to_dict(**kwargs)
Returns a list of dictionaries with the parameter estimation experiments
- Parameters
kwargs – optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
the parameter estimation experimetns as list of dictionary
- Return type
[{}]
- basico.task_parameterestimation.save_experiments_to_yaml(filename=None, **kwargs)
Saves the experiment to yaml
- Parameters
filename – optional filename to write to
kwargs – optional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
the yaml string
- basico.task_parameterestimation.set_fit_parameters(fit_parameters, model=None)
Replaces all existing fit items with the ones provided
- Parameters
fit_parameters (pandas.DataFrame or [{}]) –
the fit parameters as pandas data frame of list of dictionaries with keys:
’name’ str: the display name of the model element to map the column to.
’lower’: the lower bound of the parameter
’upper’: the upper bound of the parameter
’start’ (float, optional): the start value
’affected’ (list[str], optional): a list of affected experiment names.
’cn’ (str, optional): internal identifier
model (COPASI.CDataModel or None) – the model or None
- Returns
None
basico.task_steadystate module
This module is concerned with brining the model to steady state.
The run_steadystate()
method brings the currently loaded model to steady state
supporting a number of parameters you could set. Once done, additional calls to functions
like get_species()
or get_reactions()
will contain the steady state values.
Example
>>> run_steadystate()
>>> get_species()
- basico.task_steadystate.run_steadystate(**kwargs)
Brings the model to steady state.
The function will use the
get_current_model()
unless one is provided.- Parameters
kwargs –
optional arguments:
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) use_initial_values (bool): whether to use initial values
scheduled (bool): sets whether the task is scheduled or not
update_model (bool): sets whether the model should be updated, or reset to initial conditions.
- criterion (str): specifies the acceptance criterion to be used for a steady state can be one of:* Distance and Rate: both the Distance and the Rate criterion have to be fulfilled to accept* Distance: the distance criterion* Rate: the rate of change has to be sufficiently small
- settings (dict): a dictionary with settings to use, in the same format as the ones obtained from
- Returns
integer status information whether the steady state was reached:
0: not found
1: steady state found
2: equillibrium steady state found
3: steady state with negative concentrations found
- Return type
int
basico.task_timecourse module
This module encapsulates methods for running time course simulations.
main method provided is the run_time_course()
method, that will
simulate the given model (or the current get_current_model()
).
Examples
To run a time course for the duration of 10 time units use
>>> run_time_course(10)
To run a time course for the duration of 10 time units, in 50 simulation steps use
>>> run_time_course(10, 50)
To run a time course from 0, for the duration of 10 time units, in 50 simulation steps use:
>>> run_time_course(0, 10, 50)
all parameters can also be given as key value pairs.
- basico.task_timecourse.create_data_handler(output_selection, during=None, after=None, before=None, model=None)
Creates an output handler for the given selection
- Parameters
output_selection ([str]) – list of display names or cns, of elements to capture
during ([str]) – optional list of elements from the output selection, that should be collected during the run of the task
after ([str]) – optional list of elements from the output selection, that should be collected after the run of the task
before ([str]) – optional list of elements from the output selection, that should be collected before the run of the task
model – the model in which to resolve the display names
- Returns
tuple of the data handler from which to retrieve output later, and their columns
- Return type
(COPASI.CDataHandler, [])
- basico.task_timecourse.get_data_from_data_handler(dh, columns)
- basico.task_timecourse.run_time_course(*args, **kwargs)
Simulates the current or given model, returning a data frame with the results
- Parameters
args –
positional arguments
1 argument: the duration to simulate the model
2 arguments: the duration and number of steps to take
3 arguments: start time, duration, number of steps
kwargs –
additional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) use_initial_values (bool): whether to use initial values
scheduled (bool): sets whether the task is scheduled or not
update_model (bool): sets whether the model should be updated, or reset to initial conditions.
- method (str): sets the simulation method to use (otherwise the previously set method will be used)support methods:* deterministic / lsoda: the LSODA implementation* stochastic: the Gibson & Bruck Gillespie implementation* directMethod: Gillespie Direct Method* others: hybridode45, hybridlsoda, adaptivesa, tauleap, radau5, sde
duration (float): the duration in time units for how long to simulate
automatic (bool): whether to use automatic determined steps (True), or the specified interval / number of steps
output_event (bool): if true, output will be collected at the time a discrete event occurs.
- values ([float]): if given, output will only returned at the output points specifiedfor example use values=[0, 1, 4] to return output only for those three times
- start_time (float): the output start time. If the model is not at that start time, a simulationwill be performed in one step, to reach it before starting to collect output.
- step_number or intervals (int): the number of output steps. (will only be used if automaticor stepsize is not used.
- stepsize (float): the output step size (will only be used if automatic is False).
- seed (int): set the seed that will be used if use_seed is true, using this stochastic trajectories canbe repeated
- ’use_seed’ (bool): if true, the specified seed will be used.
- a_tol (float): the absolute tolerance to be used
- r_tol (float): the relative tolerance to be used
- max_steps (int): the maximum number of internal steps the integrator is allowed to use.
- use_concentrations (bool): whether to return just the concentrations (default)
- use_numbers (bool): return all elements collected
- Returns
data frame with simulation results
- Return type
pandas.DataFrame
- basico.task_timecourse.run_time_course_with_output(output_selection, *args, **kwargs)
Simulates the current model, returning only the data specified in the output_selection array
- Parameters
output_selection – selection of elements to return, for example [‘Time’, ‘[ATP]’, ‘ATP.Rate’] to return the time column, ATP concentration and the rate of change of ATP. The strings can be either the Display names as can be found in COPASI, or the CN’s of the elements.
args –
positional arguments
1 argument: the duration to simulate the model
2 arguments: the duration and number of steps to take
3 arguments: start time, duration, number of steps
kwargs –
additional arguments
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) use_initial_values (bool): whether to use initial values
scheduled (bool): sets whether the task is scheduled or not
update_model (bool): sets whether the model should be updated, or reset to initial conditions.
- method (str): sets the simulation method to use (otherwise the previously set method will be used)support methods:* deterministic / lsoda: the LSODA implementation* stochastic: the Gibson & Bruck Gillespie implementation* directMethod: Gillespie Direct Method* others: hybridode45, hybridlsoda, adaptivesa, tauleap, radau5, sde
duration (float): the duration in time units for how long to simulate
automatic (bool): whether to use automatic determined steps (True), or the specified interval / number of steps
output_event (bool): if true, output will be collected at the time a discrete event occurs.
- values ([float]): if given, output will only returned at the output points specifiedfor example use values=[0, 1, 4] to return output only for those three times
- start_time (float): the output start time. If the model is not at that start time, a simulationwill be performed in one step, to reach it before starting to collect output.
- step_number or intervals (int): the number of output steps. (will only be used if automaticor stepsize is not used.
- stepsize (float): the output step size (will only be used if automatic is False).
- seed (int): set the seed that will be used if use_seed is true, using this stochastic trajectories canbe repeated
- ’use_seed’ (bool): if true, the specified seed will be used.
- a_tol (float): the absolute tolerance to be used
- r_tol (float): the relative tolerance to be used
- max_steps (int): the maximum number of internal steps the integrator is allowed to use.
basico.task_scan module
Utility functions for dealing with scan tasks
While usually it is easier to encode scan functionality directly in python code, the utility methods here make it easy to set up scan tasks as supported by COPASI directly. That way they can be carried out from the command line version of COPASI, or from the graphical user interface.
- basico.task_scan.add_scan_item(**kwargs)
Adds the scan item to the model
- Parameters
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken) - type (str): the type for the scan item can be one of scan,repeat or random. If not specified scan will be used.
- cn (str): the cn of the element to use in the scan item (use whenno suitable display names for the item you are interested in exist)if you specify cn, don’t use the item optional paramter
- item (str): the display name of the item you want to use, for example[Signal]_0 for the initial concentration of species Signal, or(r1).k for the local parameter k of reaction r1.
- values(str or [float]): if you want to scan over specific values,rather than a range, specify them here e.g.: [0.1, 0.5, 1, 2]. Usingthis parameter also sets use_values to True
- use_values (bool): indicates that the values specified should be usedrather than the min / max range
- num_steps (int): the number of steps in the range of [min, max] or thenumber of repeats.
- min (float): minimum value for the range or first distribution parameter
- max (float): maximum value for the range, or the 2nd distributon parameter
- log (bool): boolean indicating that the range should be used logarithmically.
- distribution (str): one of uniform, normal, poisson or gamma
- Returns
- basico.task_scan.get_scan_items(**kwargs)
Retrieves the scan items specified on the scan task:
>>> get_scan_items() [ { 'type': 'scan', 'num_steps': 10, 'log': False, 'min': 0.5, 'max': 2.0, 'item': '(R1).k1', } ]
- Parameters
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
array of dictionary with the scan items specified
- Return type
[{}]
- basico.task_scan.get_scan_items_frame(**kwargs)
Returns all the scan items as pandas DataFrame
- Parameters
kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
data frame of scan items
- basico.task_scan.get_scan_settings(**kwargs)
Returns the scan settings as dictionary
>>> get_scan_settings() { 'update_model': False, 'scheduled': False, 'subtask': 'Steady-State', 'output_during_subtask': False, 'continue_from_current_state': False, 'continue_on_error': False, 'scan_items': [ ... ] }
- Parameters
kwargs – optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
dictionary of scan settings
- Return type
{}
- basico.task_scan.run_scan(**kwargs)
Runs the scan task
- Parameters
kwargs –
optional parameters
- settings: optional dictionary with the scan settings
- scan_items: a list of scan items see
set_scan_items()
- output ([(str)]): optional list of cns or display names, of elementsto collect in the scan.
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None if output is not specified, otherwise the collected output as dataframe.
- Return type
None or pd.DataFrame
- basico.task_scan.set_scan_items(scan_items, **kwargs)
Replaces the scan items in the task, with the scan items passed in
If you just wanted to change a specific entry, you could would retrieve the current set of scan items, make the change and then set them again:
>>> scan_items = get_scan_items()
the list of scan items is returned as array of dictionary items, and can be freely modified (say change the number of steps of the first item to a new value), or add new entries, remove some
>>> scan_items[0]['num_steps'] = 20
Finally a call to scan items, will replace the ones in the model with the ones from the array.
>>> set_scan_items(scan_items)
- Parameters
scan_items ([{}]) – list of dictionaries as returned by
get_scan_items()
.kwargs –
optional parameters
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
None
- basico.task_scan.set_scan_settings(**kwargs)
Changes the scan settings
- Parameters
kwargs –
optional parameters
settings: dictionary with the scan settings
subtask: sub task name
output_during_subtask: boolean, indicating whether ouput should be collected during the subtask execution
- continue_from_current_state: boolean indicating, whether the subtask should be reset to initial values (False)
or not (True)
continue_on_error: boolean indicating, whether executions should continue, in case one subtask execution failed (True) or not.
scan_items: a list of scan items see
set_scan_items()
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
basico.task_optimization module
Submodule with utility methods for setting up and carrying out optimization tasks.
The main function provided by this submodule is run_optimization()
. Without any parameters, the
previously set up parameter estimation as stored in the file will be carried out. And the parameters found will
be returned.
Example
Create an optimization problem
>>> from bascio import *
>>> new_model(name='Square')
>>> add_parameter('x', initial_value=0)
>>> add_parameter('y', initial_value=0)
>>> add_parameter('f', type='assignment',
... expression='(1+{Values[x].InitialValue})^2+(1 + {Values[y].InitialValue})^2')
Setup the optimization
>>> set_opt_settings({
... 'expression': 'Values[f].InitialValue',
... 'subtask': T.TIME_COURSE,
... 'method': {'name': PE.LEVENBERG_MARQUARDT}
... })
Specifiy which paramters to vary:
>>> set_opt_parameters(get_opt_item_template(include_global=True))
Run the optimization
>>> run_optimization()
Get statistic, to see how good the fit was:
>>> get_opt_statistic()
- basico.task_optimization.get_opt_item_template(include_local=False, include_global=False, default_lb=0.001, default_ub=1000, model=None)
Returns a template dictionary with optimization items
- Parameters
include_local (bool) – boolean, indicating whether to include local parameters
include_global (bool) – boolean indicating whether to include global parameters
default_lb (float) – default lower bound to be used
default_ub (float) – default upper bound to be used
model (COPASI.CDataModel or None) – the model or None
- Returns
List of dictionaries, with the local / global parameters in the format needed by:
set_opt_parameters()
.- Return type
[{}]
- basico.task_optimization.get_opt_parameters(model=None)
Returns a data frame with all parameters to be varied during optimization
The resulting dataframe will have the following columns:
name: the name of the fit parameter
lower: the lower bound of the parameter
upper: the upper bound of the parameter
start: the start value
cn: internal identifier
- Parameters
model (COPASI.CDataModel or None) – the model to get the optitems from
- Returns
data frame with the fit parameters
- Return type
pandas.DataFrame
- basico.task_optimization.get_opt_settings(model=None, basic_only=True)
Returns a dictionary with the optimization setup
The result int dictionary includes the objective function, and the subtask.
- Parameters
model – the model or None for the current one
basic_only (bool) – boolean flag indicating whether only basic settings should be returned
- Returns
dictionary with settings
- basico.task_optimization.get_opt_solution(model=None)
Returns the solution found for the optimization parameters as data frame
The resulting data frame will have the columns:
name: the name of the parameter
lower: the parameters lower bound
upper: the parameters upper bound
sol: the solution found in the last run (or NaN, if not run yet, or no solution found)
- Parameters
model (COPASI.CDataModel or None) – the model to use, or None
- Returns
data frame as described
- Return type
pandas.DataFrame
- basico.task_optimization.get_opt_statistic(**kwargs)
Return information about the last optimization run.
- Parameters
kwargs –
- model: to specify the data model to be used (if not specifiedthe one from
get_current_model()
will be taken)
- Returns
dictionary with the statistic
- Return type
{}
- basico.task_optimization.run_optimization(expression=None, output=None, settings=None, **kwargs)
Runs the optimization
- Parameters
expression – optional objective function to be used
settings – optional settings dictionary
output – optional list of output to collect
kwargs – optional arguments
- Returns
pandas data frame of the specified output, or the resulting solution for the parameters
- basico.task_optimization.set_objective_function(expression, maximize=None, minimize=None, model=None)
Sets the objective function to be used
- Parameters
expression – the expression to be used as objective function, it can contain any display names of model elements. So for example to minimize an initial value of a global parameter x the expression would look like Values[x].InitialValue.
maximize – optional boolean indicating whether the expression should be maximized
minimize – optional boolean indicating whether the expression should be minimized
model – the model to be used or None
- Returns
None
- basico.task_optimization.set_opt_parameters(opt_parameters, model=None)
Replaces all existing opt items with the ones provided
- Parameters
opt_parameters (pandas.DataFrame or [{}]) –
the optimization parameters as pandas data frame of list of dictionaries with keys:
’name’ str: the display name of the model element to map the column to.
’lower’: the lower bound of the parameter
’upper’: the upper bound of the parameter
’start’ (float, optional): the start value
’cn’ (str, optional): internal identifier
model (COPASI.CDataModel or None) – the model or None
- Returns
None
- basico.task_optimization.set_opt_settings(settings, model=None)
Changes the optimization setup
- Parameters
settings – a dictionary as returned by
get_opt_parameters()
model – the model to be used, nor None
- Returns